branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep># Shape ์ค๊ณ ๊ด๋ จ
## Shape
๊ธฐ์กด์ ๋ Dot์ ๊ฐ์ง๋ Circle/Line/Segment ๋ฅผ ๋ Vector2 ๋ง์ ๊ฐ์ง๊ฒ ๋ฐ๊พธ๊ณ ๊ธฐ์กด์ ๋ํ์ฒ๋ผ ์ฌ์ฉํ๋ ค๋ฉด ๋ ์ ์ ์์กดํ๋ Rule์ ์ฌ์ฉํ๊ฒ๋ ์ค์ ํ๊ฒ๋ ํ๋ ค๊ณ ํจ.
<file_sep>๏ปฟusing System.Linq;
using System.Collections.Generic;
using Grid.Framework;
using Grid.Framework.Components;
using Grid.Framework.GUIs;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using ContextMenuStrip = System.Windows.Forms.ContextMenuStrip;
namespace GCS
{
public class ConstructComponent : Renderable
{
public Vector2 Location { get; set; }
public Point Size { get; set; } = new Point(10000, 10000);
public Rectangle Bound => new Rectangle(Location.ToPoint(), Scene.CurrentScene.ScreenBounds);
private DrawState _drawState = DrawState.NONE;
private DotNaming _dotNamer = new DotNaming();
private bool _wasDrawing = false;
private bool _readyForDrag = false;
private bool _isDragging = false;
private Dot _ellipseLastPoint;
private Dot _lastPoint;
private List<Shape> _shapes;
private Vector2 _pos;
private Vector2 _rightPos;
private List<Shape> _rightNearShapes;
private List<Shape> _nearShapes;
private List<Shape> _selectedShapes;
private ContextMenuStrip _menuStrip;
private List<ConstructRecode> _recodes;
private bool _isAnyGuiUseMouse => _menuStrip.Focused || (Scene.CurrentScene as Main).GetFocused();
private bool _isLeftMouseDown => Scene.CurrentScene.IsLeftMouseDown && _isAnyGuiUseMouse;
private bool _isLeftMouseUp => Scene.CurrentScene.IsLeftMouseUp && _isAnyGuiUseMouse;
private bool _isLeftMouseClicking => Scene.CurrentScene.IsLeftMouseClicking && _isAnyGuiUseMouse;
private Dot samplepoint = Dot.FromCoord(0, 0);
private Vector2 _lastpos;
public ConstructComponent()
{
_shapes = new List<Shape>();
_nearShapes = new List<Shape>();
_selectedShapes = new List<Shape>();
_recodes = new List<ConstructRecode>();
_lastPoint = Dot.FromCoord(0, 0);
OnCamera = false;
InitMenuStrip();
}
private void InitMenuStrip()
{
_menuStrip = new ContextMenuStrip();
_menuStrip.Items.Add("์ ๊ฑฐ");
_menuStrip.Items.Add("์ฌ๊ธฐ๋ก ๋ณํฉ");
_menuStrip.Items.Add("์คํ ์ทจ์");
_menuStrip.Items[0].Click += (s, e) => DeleteSelected();
_menuStrip.Items[1].Click += (s, e) => UpdateAttach();
_menuStrip.Items[2].Click += (s, e) => Undo();
}
public void Clear()
{
_shapes.Clear();
_selectedShapes.Clear();
}
public void DeleteSelected()
{
if (_selectedShapes.Count == 0) return;
Delete(_selectedShapes);
_selectedShapes.Clear();
}
private void Delete(IEnumerable<Shape> target)
{
List<Shape> sh = new List<Shape>();
foreach (var s in target)
{
foreach (var ss in s.Delete())
if (_shapes.Contains(ss))
{
sh.Add(ss);
_shapes.Remove(ss);
}
}
_recodes.Add(new ConstructRecode(RecodeType.DELETE, sh));
}
public void Undo()
{
if (_recodes.Count == 0) return;
ConstructRecode r = _recodes.Last();
switch (r.type)
{
case RecodeType.CREATE:
foreach (var s in r.targetshapes)
{
_shapes.Remove(s);
}
break;
case RecodeType.DELETE:
foreach (var s in r.targetshapes)
AddShape(s);
break;
case RecodeType.MOVE:
foreach (Shape s in r.targetshapes)
{
s.Move(r.moveRecode);
}
break;
}
_recodes.RemoveAt(_recodes.Count - 1);
}
public void ChangeState(DrawState state)
=> _drawState = state;
private void UpdateLists(SpriteBatch sb)
{
foreach (var s in _shapes)
{
s.Draw(sb);
}
}
private void AddShape(Shape shape)
{
if (_shapes.Contains(shape)) return;
if (shape is Dot && string.IsNullOrEmpty(shape.Name))
shape.Name = _dotNamer.GetCurrent();
shape.InitializeProperties();
_shapes.Add(shape);
_recodes.Add(new ConstructRecode(RecodeType.CREATE, new List<Shape>() { shape }));
}
private void Select(Shape shape)
{
shape.Selected = true;
shape.UnSelect = false;
_selectedShapes.Add(shape);
}
private void SelectAll()
{
foreach (var s in _shapes)
Select(s);
}
private void Unselect(Shape shape)
{
shape.UnSelect = true;
shape.Selected = false;
_selectedShapes.Remove(shape);
}
private void UnselectAll()
{
_selectedShapes.ForEach(s => { s.UnSelect = true; s.Selected = false; });
_selectedShapes.Clear();
}
public override void Update()
{
base.Update();
//_pos = Camera.Current.GetRay(Mouse.GetState().Position.ToVector2());
_pos = Mouse.GetState().Position.ToVector2() + Location;
foreach (var s in _shapes) s.Update(_pos);
//์ ํ, ๊ฐ๊น์ด์๋ ์ ์ ํ
_nearShapes = _shapes.Where(s => s.Focused).ToList();
UpdateRightClick();
UpdateAdding();
UpdateSelect();
UpdateDrag();
UpdateShortcuts();
}
private void UpdateAdding()
{
if (_isAnyGuiUseMouse) return;
if (Mouse.GetState().LeftButton == ButtonState.Pressed)
{
if (_drawState != DrawState.NONE)
{
if (!_wasDrawing)
{
_lastPoint = GetDot(_pos);
_wasDrawing = true;
}
else if (_drawState == DrawState.DOT || _drawState == DrawState.ELLIPSE)
_lastPoint.MoveTo(_pos);
}
}
if (_wasDrawing && Mouse.GetState().LeftButton == ButtonState.Released)
{
if (_drawState == DrawState.DOT)
{
AddShape(_lastPoint);
}
else if (_drawState == DrawState.ELLIPSE)
{
_ellipseLastPoint = _lastPoint;
_drawState = DrawState.ELLIPSE_POINT;
_wasDrawing = false;
return;
}
else
{
var p = GetDot(_pos);
AddShape(p);
AddShape(_lastPoint);
Shape sp = null;
if (_drawState == DrawState.CIRCLE)
{
sp = Circle.FromTwoDots(_lastPoint, p);
AddShape(sp);
}
else if (_drawState == DrawState.SEGMENT)
{
sp = Segment.FromTwoDots(_lastPoint, p);
AddShape(sp);
}
else if (_drawState == DrawState.LINE)
{
sp = Line.FromTwoDots(_lastPoint, p);
AddShape(sp);
}
else if (_drawState == DrawState.VECTOR)
{
sp = Vector.FromTwoDots(_lastPoint, p);
AddShape(sp);
}
else if (_drawState == DrawState.ELLIPSE_POINT)
{
AddShape(_ellipseLastPoint);
sp = Ellipse.FromThreeDots(_ellipseLastPoint, _lastPoint, p);
AddShape(sp);
}
}
_wasDrawing = false;
_drawState = DrawState.NONE;
}
}
private void UpdateAttach()
{
if (_drawState == DrawState.NONE)
{
if (_selectedShapes.Count == 1)
{
if (_selectedShapes[0] is Dot)
{
if (_rightNearShapes?.Count > 0)
{
if (_selectedShapes[0].Parents.Count == 0)
{
var parent = GetDot(_rightPos, _rightNearShapes);
AddShape(parent);
(_selectedShapes[0] as Dot).AttachTo(parent);
}
}
}
}
}
}
private void UpdateSelect()
{
if (_isAnyGuiUseMouse) return;
if (_drawState == DrawState.NONE)
{
if (_nearShapes.Count > 0)
{
Shape nearest = _nearShapes[0];
float dist = int.MaxValue;
foreach (var s in _nearShapes)
{
if (s is Dot)
{
// ๋ค ๋๋ฌ๋ค ๊ทธ์ง ๊นฝ๊นฝ์ด๋ค์!! ์ ์ด ์ฐ์ ์์ ์ต๊ณ ๋ค!
nearest = s;
break;
}
if (dist > s.Distance)
{
nearest = s;
dist = s.Distance;
}
}
if (Scene.CurrentScene.IsLeftMouseDown)
{
if (!nearest.Selected)
{
_selectedShapes.ForEach(s => s.UnSelect = true);
_selectedShapes.Add(nearest);
nearest.Selected = true;
nearest.UnSelect = false;
}
else
nearest.UnSelect = true;
}
if (Scene.CurrentScene.IsLeftMouseUp)
{
if (nearest.Selected && nearest.UnSelect)
{
_selectedShapes.Remove(nearest);
nearest.Selected = false;
}
}
}
else
{
if (Scene.CurrentScene.IsLeftMouseUp)
{
//UnselectAll();
}
}
}
}
private void UpdateDrag()
{
if (_drawState == DrawState.NONE)
{
if (_selectedShapes.Count == 0) return;
if (Scene.CurrentScene.IsLeftMouseDown && _selectedShapes.Any(s => s.IsEnoughClose(_pos)))
{
_readyForDrag = true;
}
if (_readyForDrag && Scene.CurrentScene.IsMouseMoved)
{
_readyForDrag = false;
ConstructRecode r = new ConstructRecode(RecodeType.MOVE, _selectedShapes);
_recodes.Add(r);
_lastpos = samplepoint.Coord;
if (Scene.CurrentScene.IsLeftMouseClicking)
_isDragging = true;
}
if (_isDragging || Scene.CurrentScene.IsLeftMouseClicking && Scene.CurrentScene.IsMouseMoved)
{
var diff = Scene.CurrentScene.MousePosition - Scene.CurrentScene.LastMousePosition;
if (_isDragging || _selectedShapes.Any(s => s.IsEnoughClose(_pos)))
{
if (!_isDragging) _isDragging = true;
_selectedShapes.ForEach(s => { s.UnSelect = false; s.Move(diff.ToVector2()); });
samplepoint.Move(diff.ToVector2());
}
if (Scene.CurrentScene.IsLeftMouseUp)
{
_isDragging = false;
_recodes.Last().WriteMoveRecode(samplepoint.Coord - _lastpos);
return;
}
}
}
}
private void UpdateRightClick()
{
// ์ฐ์ ํ
์คํธ ์ ๋๋ก ์๋ ๋์ถฉ ๋๋๋ก ์ง๋ดค์
if (_drawState == DrawState.NONE)
{
if (Scene.CurrentScene.IsRightMouseUp)
{
//UnselectAll();
//Select(_nearShapes[0]);
_rightPos = _pos;
_rightNearShapes = _nearShapes.ToList();
_menuStrip.Show(System.Windows.Forms.Control.FromHandle(Scene.CurrentScene.Window.Handle),
Scene.CurrentScene.MousePosition.X, Scene.CurrentScene.MousePosition.Y);
}
}
/*
if (_shapeMenuStrip.IsSelected)
{
if (_shapeMenuStrip.SelectedItem.Text == "Delete")
DeleteSelected();
else if (_shapeMenuStrip.SelectedItem.Text == "Merge")
UpdateAttach();
}
*/
}
private void UpdateShortcuts()
{
var state = Keyboard.GetState();
if (state.IsKeyDown(Keys.Delete))
{
DeleteSelected();
}
if (state.IsKeyDown(Keys.LeftControl) && state.IsKeyDown(Keys.A))
{
SelectAll();
}
}
private Dot GetDot(Vector2 coord)
=> GetDot(coord, _nearShapes);
/// <summary>
/// ๊ฐ๊น์ด ์ ์ด ์๋ค๋ฉด ๊ทธ ์ ์, ์๋ค๋ฉด ์ ์ ์
/// </summary>
private Dot GetDot(Vector2 coord, List<Shape> nears)
{
Dot nearestDot = null;
Shape nearest = null;
float distDot = int.MaxValue;
float dist = int.MaxValue;
foreach (var s in nears)
{
if (s is Dot)
{
if (s.IsEnoughClose(coord))
{
nearestDot = s as Dot;
distDot = s.Distance;
}
}
else
{
if (s.Distance <= dist)
{
nearest = s;
dist = s.Distance;
}
}
}
if (nearestDot == null) // ๊ฐ์ฅ ๊ฐ๊น์ด๊ฒ ์ ์ด ์๋๋ผ๋ฉด
{
if (nears.Count == 0)
return Dot.FromCoord(coord);
if (nears.Count == 1)
{
return OneShapeRuleDot(nearest, coord);
}
else if (nears.Count == 2)
{
Vector2[] intersects = Geometry.GetIntersect(nears[0], nears[1]);
if (intersects.Length != 0)
{
Vector2 dot = intersects[0];
if (intersects.Length == 2)
{
dot = Vector2.Distance(coord, intersects[0]) < Vector2.Distance(intersects[1], coord)
? intersects[0] : intersects[1];
}
return Dot.FromIntersection(nears[0], nears[1], dot);
}
else return OneShapeRuleDot(nearest, coord);
}
else return OneShapeRuleDot(nearest, coord);
}
else if (nearestDot is Dot) return nearestDot as Dot;
else return Dot.FromCoord(coord);
}
private Dot OneShapeRuleDot(Shape nearest, Vector2 coord)
{
return Dot.FromOneShape(nearest, coord);
}
public override void Draw(SpriteBatch sb)
{
//_pos = Camera.Current.GetRay(Mouse.GetState().Position.ToVector2());
sb.BeginAA();
_pos = Mouse.GetState().Position.ToVector2() + Location;
if (_wasDrawing || _drawState == DrawState.ELLIPSE_POINT)
{
if (_drawState == DrawState.CIRCLE)
{
float radius = (_pos - _lastPoint.Coord).Length();
GUI.DrawCircle(sb, _lastPoint.Coord - Location, radius, 2, Color.DarkGray, 100);
}
else if (_drawState == DrawState.ELLIPSE)
{
_lastPoint.Draw(sb);
}
else if (_drawState == DrawState.ELLIPSE_POINT)
{
_ellipseLastPoint.Draw(sb);
Ellipse.FromThreeDots(_ellipseLastPoint, _lastPoint, Dot.FromCoord(_pos)).Draw(sb);
}
else if (_drawState == DrawState.SEGMENT)
{
GUI.DrawLine(sb, _lastPoint.Coord - Location, _pos - Location, 2, Color.DarkGray);
}
else if (_drawState == DrawState.VECTOR)
{
Vector.FromTwoDots(_lastPoint, Dot.FromCoord(_pos)).Draw(sb);
}
else if (_drawState == DrawState.LINE)
{
Line.FromTwoPoints(_lastPoint.Coord, _pos).Draw(sb);
}
else if (_drawState == DrawState.DOT)
{
_lastPoint.Draw(sb);
}
}
UpdateLists(sb);
sb.End();
}
public void SelectConstruct(ConstructType type)
{
switch (type)
{
case ConstructType.ParallelLine:
if (_selectedShapes.Count == 2)
{
if (_selectedShapes[0] is LineLike && _selectedShapes[1] is Dot
|| _selectedShapes[0] is Dot && _selectedShapes[1] is LineLike)
{
var line = _selectedShapes[0] as LineLike ?? _selectedShapes[1] as LineLike;
var dot = _selectedShapes[0] as Dot ?? _selectedShapes[1] as Dot;
_shapes.Add(Line.ParallelLine(line, dot));
}
}
break;
case ConstructType.PerpendicularLine:
if (_selectedShapes.Count == 2)
{
if (_selectedShapes[0] is LineLike && _selectedShapes[1] is Dot
|| _selectedShapes[0] is Dot && _selectedShapes[1] is LineLike)
{
var line = _selectedShapes[0] as LineLike ?? _selectedShapes[1] as LineLike;
var dot = _selectedShapes[0] as Dot ?? _selectedShapes[1] as Dot;
_shapes.Add(Line.PerpendicularLine(line, dot));
}
}
break;
case ConstructType.Tangent:
if (_selectedShapes.Count == 2)
{
if (_selectedShapes[0] is Circle && _selectedShapes[1] is Dot
|| _selectedShapes[0] is Dot && _selectedShapes[1] is Circle)
{
var cir = _selectedShapes[0] as Circle ?? _selectedShapes[1] as Circle;
var dot = _selectedShapes[0] as Dot ?? _selectedShapes[1] as Dot;
_shapes.Add(Line.TangentLine(cir, dot));
}
else if (_selectedShapes[0] is Ellipse && _selectedShapes[1] is Dot
|| _selectedShapes[0] is Dot && _selectedShapes[1] is Ellipse)
{
var elp = _selectedShapes[0] as Ellipse ?? _selectedShapes[1] as Ellipse;
var dot = _selectedShapes[0] as Dot ?? _selectedShapes[1] as Dot;
_shapes.Add(Line.TangentLine(elp, dot));
}
}
break;
case ConstructType.Reflection:// ์ฒซ ์ ํ์ด ๋์นญ์ถ, ๋๋ฒ์งธ ์ ํ์ด ๋์นญ์ํฌ ๋ํ
if (_selectedShapes.Count == 2 )
{
if (_selectedShapes[0] is LineLike)
{
var axis = _selectedShapes[0] as LineLike;
if (_selectedShapes[1] is Ellipse) _shapes.Add(Ellipse.FromReflection(axis, _selectedShapes[1] as Ellipse));
else if (_selectedShapes[1] is Circle) _shapes.Add(Circle.FromReflection(axis, _selectedShapes[1] as Circle));
else if (_selectedShapes[1] is Line) _shapes.Add(Line.FromReflection(axis, _selectedShapes[1] as Line));
else if (_selectedShapes[1] is Vector) _shapes.Add(Vector.FromReflection(axis, _selectedShapes[1] as Vector));
else if (_selectedShapes[1] is Segment) _shapes.Add(Segment.FromReflection(axis, _selectedShapes[1] as Segment));
else _shapes.Add(Dot.FromReflection(axis, _selectedShapes[1] as Dot));
}
}
break;
case ConstructType.Ellipse:
{
if (_selectedShapes.Count == 3)
{
var f1 = _selectedShapes[0] as Dot;
var f2 = _selectedShapes[1] as Dot;
var pin = _selectedShapes[2] as Dot;
if (f1 == null) return;
if (f2 == null) return;
if (pin == null) return;
AddShape(Ellipse.FromThreeDots(f1, f2, pin));
}
break;
}
}
}
}
}
<file_sep>๏ปฟusing System;
using System.Linq;
using Grid.Framework;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;
namespace GCS
{
public abstract partial class Shape
{
private static readonly float _nearDistance = 5;
public abstract class BasisDots : IEnumerable<Vector2>
{
protected Shape _shape;
private int _count;
public BasisDots(Shape shape, int count)
{
this._shape = shape;
this._count = count;
}
public abstract Vector2 this[int i] { get; set; }
public IEnumerator<Vector2> GetEnumerator()
{
return new DotEnumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> GetEnumerator();
public class DotEnumerator : IEnumerator<Vector2>
{
BasisDots _dots;
int _cur;
public DotEnumerator(BasisDots dots)
{
_dots = dots;
_cur = -1;
}
public bool MoveNext()
{
return ++_cur < _dots._count;
}
public void Reset()
{
_cur = -1;
}
object System.Collections.IEnumerator.Current
=> this.Current;
public Vector2 Current
=> _dots[_cur];
public void Dispose() { }
}
}
public BasisDots DotList;
internal List<Shape> Parents { get; private set; }
internal List<Shape> Childs { get; private set; }
internal ShapeRule _rule = null;
private bool _disabled = false;
public bool Disabled
{
get => _disabled || Parents.Any(p => p.Disabled);
set => _disabled = value;
}
protected ConstructComponent _comp;
protected Vector2 _drawDelta => -_comp.Location;
public bool IsShowingName { get; set; } = true;
public string Name { get; set; }
public float Border { get; set; } = 2f;
public Color Color { get; set; } = Color.Black;
public Color FocusedColor { get; set; } = Color.Orange;
public Color SelectedColor { get; set; } = Color.Cyan;
public Color TextColor { get; set; } = Color.Black;
public bool Focused { get; set; } = false;
public bool Selected { get; set; } = false;
/// <summary>
/// ๋ง์ฐ์ค๋ฅผ ๋ผ๋ฉด Selected๊ฐ false๊ฐ ๋์ด์ผ ํ๋๊ฐ?
/// </summary>
internal bool UnSelect { get; set; } = false;
/// <summary>
/// ์ปค์์์ ๊ฑฐ๋ฆฌ
/// </summary>
public float Distance { get; set; } = -1;
public virtual void Draw(SpriteBatch sb)
{
Color = Color.Black;
if (Focused) Color = FocusedColor;
if (Selected) Color = SelectedColor;
}
public abstract void Move(Vector2 add);
public abstract void MoveTo(Vector2 at);
public Shape()
{
Parents = new List<Shape>();
Childs = new List<Shape>();
if (_comp == null)
_comp = GameObject.Find("construct").GetComponent<ConstructComponent>();
}
public void InitializeProperties()
{
Selected = false;
Focused = false;
UnSelect = false;
Disabled = false;
}
public virtual bool IsEnoughClose(Vector2 coord)
=> Geometry.GetNearestDistance(this, coord) <= _nearDistance;
public virtual void Update(Vector2 cursor)
{
Distance = Geometry.GetNearestDistance(this, cursor);
if (IsEnoughClose(cursor))
Focused = true;
else if (Focused)
Focused = false;
}
public IEnumerable<Shape> Delete()
{
yield return this;
foreach (var child in Childs)
foreach (var c in child.Delete())
yield return c;
}
}
public partial class Circle : Shape
{
public static int Sides = 100;
public class CircleDots : BasisDots
{
public CircleDots(Circle circle) : base(circle, 2) { }
public override Vector2 this[int i]
{
get
{
switch (i)
{
case 0: return (_shape as Circle).Center;
case 1: return (_shape as Circle).Another;
default: throw new IndexOutOfRangeException();
}
}
set
{
switch (i)
{
case 0: (_shape as Circle).Center = value; break;
case 1: (_shape as Circle).Another = value; break;
default: throw new IndexOutOfRangeException();
}
}
}
}
public Vector2 Center { get; protected set; }
public Vector2 Another { get; protected set; }
public float Radius
{
get => Vector2.Distance(Center, Another);
set => throw new NotSupportedException();
}
protected Circle() : base()
{
DotList = new CircleDots(this);
}
public override void Draw(SpriteBatch sb)
{
if (Disabled) return;
base.Draw(sb);
GUI.DrawCircle(sb, Center + _drawDelta, Radius, Border, Color, Sides);
}
public override void Move(Vector2 add)
{
Center += add;
Another += add;
_rule?.OnMoved();
}
public override void MoveTo(Vector2 at)
{
var diff = at - Center;
Move(diff);
}
public static Circle FromTwoDots(Dot center, Dot another)
{
Circle circle = new Circle();
new CircleOnTwoDotsRule(circle, center, another);
return circle;
}
public static Circle FromReflection(LineLike axis, Circle original)
{
Circle cir = new Circle();
new ReflectedShapeRule(axis, original, cir);
return cir;
}
}
public partial class Ellipse : Shape
{
public static int Sides = 100;
public class EllipseDots : BasisDots
{
public EllipseDots(Ellipse ellipse) : base(ellipse, 3) { }
public override Vector2 this[int i]
{
get
{
switch (i)
{
case 0: return (_shape as Ellipse).Focus1;
case 1: return (_shape as Ellipse).Focus2;
case 2: return (_shape as Ellipse).PinPoint;
default: throw new IndexOutOfRangeException();
}
}
set
{
switch (i)
{
case 0: (_shape as Ellipse).Focus1 = value; break;
case 1: (_shape as Ellipse).Focus2 = value; break;
case 2: (_shape as Ellipse).PinPoint = value; break;
default: throw new IndexOutOfRangeException();
}
}
}
}
public Vector2 Focus1 { get; protected set; }
public Vector2 Focus2 { get; protected set; }
public Vector2 PinPoint { get; protected set; }
public Vector2 Center => (Focus1 + Focus2) / 2;
public float Sublength => Vector2.Distance(Focus1, Focus2) / 2;//c
public float Semimajor => (Vector2.Distance(Focus1, PinPoint) + Vector2.Distance(Focus2, PinPoint)) / 2;//a
public float Semiminor => (float)Math.Sqrt(Semimajor * Semimajor - Sublength * Sublength);//b
protected Ellipse() : base()
{
DotList = new EllipseDots(this);
}
public override void Draw(SpriteBatch sb)
{
if (Disabled) return;
base.Draw(sb);
GUI.DrawEllipse(sb, Focus1 + _drawDelta, Focus2 + _drawDelta, PinPoint + _drawDelta, Border, Color, Sides);
}
public override void Move(Vector2 add)
{
Focus1 += add;
Focus2 += add;
PinPoint += add;
_rule?.OnMoved();
}
public override void MoveTo(Vector2 at)
{
var diff = at - PinPoint;
Move(diff);
}
public static Ellipse FromThreeDots(Dot f1, Dot f2, Dot pin)
{
Ellipse ellipse = new Ellipse();
new EllipseOnThreeDotsRule(ellipse, f1, f2, pin);
return ellipse;
}
public static Ellipse FromReflection(LineLike axis, Ellipse original)
{
Ellipse elp = new Ellipse();
new ReflectedShapeRule(axis, original, elp);
return elp;
}
}
public abstract partial class LineLike : Shape
{
public class LineDots : BasisDots
{
public LineDots(LineLike line) : base(line, 2) { }
public override Vector2 this[int i]
{
get
{
switch (i)
{
case 0: return (_shape as LineLike).Point1;
case 1: return (_shape as LineLike).Point2;
default: throw new IndexOutOfRangeException();
}
}
set
{
switch (i)
{
case 0: (_shape as LineLike).Point1 = value; break;
case 1: (_shape as LineLike).Point2 = value; break;
default: throw new IndexOutOfRangeException();
}
}
}
}
public Vector2 Point1 { get; protected set; }
public Vector2 Point2 { get; protected set; }
public float Grad => (Point2.Y - Point1.Y) / (Point2.X - Point1.X);
public float Yint => Point1.Y - Grad * Point1.X;
protected LineLike(Vector2? p1 = null, Vector2? p2 = null)
{
DotList = new LineDots(this);
Point1 = p1 ?? new Vector2();
Point2 = p2 ?? new Vector2();
Move(Vector2.Zero);
}
public override void Move(Vector2 add)
{
Point1 += add;
Point2 += add;
//Grad = (Point2.Y - Point1.Y) / (Point2.X - Point1.X);
//Yint = Point1.Y - Grad * Point1.X;
_rule?.OnMoved();
}
public override void MoveTo(Vector2 at)
{
var diff = at - Point1;
Move(diff);
}
}
public partial class Line : LineLike
{
protected Line(Vector2? p1 = null, Vector2? p2 = null) : base(p1, p2) { }
public override void Draw(SpriteBatch sb)
{
if (Disabled) return;
base.Draw(sb);
GUI.DrawLine(sb, new Vector2(0, Yint) + _drawDelta, new Vector2(_comp.Size.X, _comp.Size.X * Grad + Yint) + _drawDelta, Border, Color);
}
public static Line FromTwoDots(Dot d1, Dot d2)
{
Line line = new Line();
var rule = new LineLikeOnTwoDotsRule(line, d1, d2);
return line;
}
internal static Line FromTwoPoints(Vector2 p1, Vector2 p2)
=> new Line(p1, p2);
public static Line ParallelLine(LineLike original, Dot on)
{
Line line = new Line();
new ParallelLineRule(line, original, on);
return line;
}
public static Line PerpendicularLine(LineLike original, Dot on)
{
Line line = new Line();
new PerpendicularLineRule(line, original, on);
return line;
}
public static Line TangentLine(Circle original, Dot on)
{
Line line = new Line();
new TangentLineRule(line, original, on);
return line;
}
public static Line TangentLine(Ellipse original, Dot on)
{
Line line = new Line();
new TangentLineRule(line, original, on);
return line;
}
public static Line FromReflection(LineLike axis, Line original )
{
Line lin = new Line();
new ReflectedShapeRule(axis, original, lin);
return lin;
}
}
public class Segment : LineLike
{
protected Segment(Vector2? p1 = null, Vector2? p2 = null) : base(p1, p2) { }
public override void Draw(SpriteBatch sb)
{
if (Disabled) return;
base.Draw(sb);
GUI.DrawLine(sb, Point1 + _drawDelta, Point2 + _drawDelta, Border, Color);
}
public static Segment FromTwoDots(Dot d1, Dot d2)
{
var seg = new Segment();
var rule = new LineLikeOnTwoDotsRule(seg, d1, d2);
return seg;
}
public static Segment FromReflection(LineLike axis, Segment original)
{
Segment lin = new Segment();
new ReflectedShapeRule(axis, original, lin);
return lin;
}
}
public class Vector : Segment
{
readonly static float arrowAngle = (float)Math.PI/6;
readonly static float arrowlength = 20;
protected Vector(Vector2? p1 = null, Vector2? p2 = null) : base(p1, p2) { }
public override void Draw(SpriteBatch sb)
{
if (Disabled) return;
base.Draw(sb);
Vector2 del = Point2 - Point1;
Vector2 delta1, delta2;
float angle = (float)Math.Atan(del.Y/del.X);
Vector2 Initvector = new Vector2(Point1.X + Vector2.Distance(Point1, Point2), Point1.Y);
delta1 = new Vector2((float)(Initvector.X - arrowlength*Math.Cos(arrowAngle)) , (float)(Initvector.Y + arrowlength*Math.Sin(arrowAngle)));
delta2 = new Vector2((float)(Initvector.X - arrowlength * Math.Cos(arrowAngle)), (float)(Initvector.Y - arrowlength * Math.Sin(arrowAngle)));
if(del.X >0)
{
GUI.DrawLine(sb, Point2 + _drawDelta, Point1 + Geometry.Rotate(delta1 - Point1, angle) + _drawDelta, Border, Color);
GUI.DrawLine(sb, Point2 + _drawDelta, Point1 + Geometry.Rotate(delta2 - Point1, angle) + _drawDelta, Border, Color);
}
else
{
GUI.DrawLine(sb, Point2 + _drawDelta, Point1 - Geometry.Rotate(delta1 - Point1, angle) + _drawDelta, Border, Color);
GUI.DrawLine(sb, Point2 + _drawDelta, Point1 - Geometry.Rotate(delta2 - Point1, angle) + _drawDelta, Border, Color);
}
}
public new static Vector FromTwoDots(Dot d1, Dot d2)
{
var vec = new Vector();
var rule = new LineLikeOnTwoDotsRule(vec, d1, d2);
return vec;
}
public static Vector FromReflection(LineLike axis, Vector original)
{
Vector lin = new Vector();
new ReflectedShapeRule(axis, original, lin);
return lin;
}
}
public partial class Dot : Shape
{
private static readonly float _nearDotDistance = 10;
public class DotDots : BasisDots
{
public DotDots(Dot dot) : base(dot, 1) { }
public override Vector2 this[int i]
{
get
{
switch (i)
{
case 0: return (_shape as Dot).Coord;
default: throw new IndexOutOfRangeException();
}
}
set
{
switch (i)
{
case 0: (_shape as Dot).Coord = value; break;
default: throw new IndexOutOfRangeException();
}
}
}
}
private Vector2 _coord;
public Vector2 Coord { get => _coord; set => _coord = value; }
protected Dot(Vector2 coord) : base()
{
DotList = new DotDots(this);
_coord = coord;
Color = Color.OrangeRed;
}
public override bool Equals(object obj)
{
var o = obj as Dot;
return o == null ? false : Coord.Equals(o.Coord);
}
public override int GetHashCode()
=> Coord.GetHashCode();
public override bool IsEnoughClose(Vector2 coord)
=> Geometry.GetNearestDistance(this, coord) <= _nearDotDistance;
public override void Draw(SpriteBatch sb)
{
if (Disabled) return;
base.Draw(sb);
if (_rule != null && _rule is DotOnDotRule)
if (Parents[0].Selected)
Color = SelectedColor;
GUI.DrawCircle(sb, Coord + _drawDelta, 4f, Border, Color, 20);
// GUI.DrawPoint(sb, Coord, Border, Color);\
if (IsShowingName && Name != null)
{
var size = Resources.Font.MeasureString(Name).ToPoint();
GUI.DrawString(sb,
Resources.Font,
Name,
Alignment.Left | Alignment.Bottom,
new Rectangle((Coord - _comp.Location).ToPoint() - size, size),
TextColor,
0f);
}
}
public override void MoveTo(Vector2 at)
{
var diff = at - Coord;
Move(diff);
}
public override void Move(Vector2 delta)
{
Coord += delta;
_rule?.OnMoved();
}
public static Dot FromCoord(Vector2 coord)
{
var dot = new Dot(coord);
new EmptyDotRule(dot);
return dot;
}
public static Dot FromCoord(float x, float y)
=> FromCoord(new Vector2(x, y));
public static Dot FromOneShape(Shape shape, Vector2 coord)
{
var dot = new Dot(coord);
new DotOnShapeRule(dot, shape);
return dot;
}
public static Dot FromIntersection(Shape p1, Shape p2, Vector2 coord)
{
var dot = new Dot(coord);
new DotOnIntersectionRule(dot, p1, p2);
return dot;
}
public static Dot FromReflection(LineLike axis, Dot original )
{
Dot d = new Dot(Vector2.Zero);
new ReflectedShapeRule(axis, original, d);
return d;
}
public void AttachTo(Dot parent)
{
new DotOnDotRule(this, parent);
}
}
}
<file_sep># GCS
Geometric Construction Simulator, ์๋ ์๋ฎฌ๋ ์ด์
ํ๋ก๊ทธ๋จ

# ์ฌ์ฉ ๋ฐฉ๋ฒ
## ๊ธฐ๋ณธ ์กฐ์
๊ทธ๋ฆด ๋ํ์ ๋ฒํผ์ ํด๋ฆญํ๊ณ (์ , ์ , ์), ๋๋๊ทธ ์ ๋๋์ผ๋ก ๊ทธ๋ฆฐ๋ค. ๋๋๊ทธํ์ฌ ๋ํ์ ์์ง์ด๊ณ , ํด๋ฆญํ์ฌ ์ ํ๋ ๋ํ์ ๋ค์ ํด๋ฆญํ์ฌ ์ ํ ํด์ ํ๋ค. Clear ๋ฒํผ์ ๋ชจ๋ ๋ํ์ ์ง์ฐ๊ณ , Delete ๋ฒํผ์ ์ ํ๋์ด์๋ ๋ํ๋ค์ ์ง์ด๋ค. Undo ๋ฒํผ์ ์์
์ ์ทจ์ํ๋ค.
## ๋ํ ๊ทธ๋ฆฌ๊ธฐ
### ์
์ ์ ๋ชจ๋ ๋ํ์ ๊ทธ๋ฆฌ๋๋ฐ ๊ธฐ๋ณธ์ด ๋๊ณ , ์ ์ฐ๊ธฐ๋ ์จ ์ฐ์ฃผ์ ๊ธฐ์ด์ ๋ด์ ์ฐ์ด์ผ ์ด์๊ฒ ์ ์ฐํ๋ค. ์ ์ ์ฃผํฉ์์ผ๋ก ํ์๋๋ ๊ฐ๊น์ด ํฌ์ปค์ค๋ ๋ํ ์์ ์ฐ์ด์ง๊ณ , ํฌ์ปค์ค๋๋ ๋ํ์ด ์๋ค๋ฉด ์ ํํ ๋ง์ฐ์ค์ ์์น์ ์ฐ์ด์ง๋ค. ํฌ์ปค์ค๋ ๋ํ์ด ์ฌ๋ฌ๊ฐ์ด๋ฉด ๋ํ์ ๊ต์ ์ ์ฐํ๊ฒ ๋๋ค.
### ์
์ค์ฌ์ ์ด ๋ ์์น์ ๋ง์ฐ์ค ๋ค์ด ํ ๋๋จธ์ง ํ ์ ์ด ๋ ์์น์์ ๋ง์ฐ์ค ์
### ํ์
์ฒซ๋ฒ์งธ ์ด์ ์ ์ฒซ ํด๋ฆญ์ผ๋ก ๊ฒฐ์ . ๋๋ฒ์งธ ์ด์ ์ ๋๋ฒ์งธ ๋ง์ฐ์ค ๋ค์ด, ํํฌ์ธํธ๋ ๋๋ฒ์งธ ๋ง์ฐ์ค ์
### ์ ๋ถ
ํ ์ ์์ ๋ง์ฐ์ค ๋ค์ด ํ ๋๋จธ์ง ํ ์ ์ด ๋ ์์น์์ ๋ง์ฐ์ค ์
### ์ง์
[์ ๋ถ](#์ ๋ถ)๊ณผ ๊ฐ์
### ๋ฒกํฐ
[์ ๋ถ](#์ ๋ถ)๊ณผ ๊ฐ์. ๋จ ๋ง์ฐ์ค๋ฅผ ๋ค์ดํ ์ ์ด ์์ ,๋ง์ฐ์ค๋ฅผ ์
ํ ์ ์ด ์ข
์ ์ด ๋จ
## ์ด๋ ๊ท์น
์ ๋ถ์ด๋ ์ง์ ์์ ์ฐํ ์ ์ ์ ์ด ์์ง์ด๋ฉด ์ ์ ์ด๋ฃจ๋ ๋ ์ ๊ณผ์ ๋น์จ์ ๋ง์ถฐ ์์ง์ธ๋ค. ์ ์์ ์ฐํ ์ ์ ๊ฐ๋๊ฐ ๊ณ ์ ๋์ด ์์ง์ธ๋ค. ๊ต์ ์์ ์ฐํ ์ ์ ์์น๋ ๊ต์ ์ ๋ฐ๋ผ๊ฐ๊ฒ ๋๋ค. ๋ค๋ฅธ ๋ํ ์์ ์๋ ์ ์ ํ ์ ์ผ๋ก ๊ฐ์ง๋ ๋ํ์ด ์๋ค๋ฉด, ๋ค๋ฅธ ๋ํ์ด ์์ง์ฌ ๊ทธ ์ ์ด ์์ง์ธ๋ค๋ฉด ์๊ธฐ ์์ ๋ ์์ง์ด๊ฒ ๋๋ค.
# ToDo
- [x] Undo ๊ตฌํ
- [ ] WinForm ์ผ๋ก ํฌํ
- [ ] ๋ณต์ฌ/๋ถ์ฌ๋ฃ๊ธฐ
- [x] ์ ๋ณํฉ
- [ ] ์ ๋ถ๋ฆฌ
- [ ] ํ์ผ๋ก ์ ์ฅ
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
namespace GCS
{
class ConstructRecode
{
public List<Shape> targetshapes;
public Vector2 moveRecode;
public RecodeType type;
public ConstructRecode(RecodeType Type, List<Shape> Target)
{
this.targetshapes = Target;
this.type = Type;
}
public void WriteMoveRecode(Vector2 diff)
{
this.moveRecode = -diff;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
namespace GCS
{
public static class Geometry
{
//์ฃผ์ ) Ellipse ์ ๋ํด์๋ ํญ์ GetIntersect ๋ก ํธ์ถ
public static Vector2[] GetIntersect(Shape shape1, Shape shape2)
{
if (shape2 is Ellipse) return GetIntersect(shape2, shape1);
if (shape1 is Segment)
{
if (shape2 is Segment)
return getIntersect(shape1 as Segment, shape2 as Segment);
else if (shape2 is Line)
return getIntersect(shape2 as Line, shape1 as Segment);
else if (shape2 is Circle)
return getIntersect(shape1 as Segment, shape2 as Circle);
}
else if (shape1 is Line)
{
if (shape2 is Segment)
return getIntersect(shape1 as Line, shape2 as Segment);
else if (shape2 is Line)
return getIntersect(shape1 as Line, shape2 as Line);
else if (shape2 is Circle)
return getIntersect(shape1 as Line, shape2 as Circle);
}
else if (shape1 is Circle)
{
if (shape2 is Segment)
return getIntersect(shape2 as Segment, shape1 as Circle);
else if (shape2 is Line)
return getIntersect(shape2 as Line, shape1 as Circle);
else if (shape2 is Circle)
return getIntersect(shape1 as Circle, shape2 as Circle);
}
else if (shape1 is Ellipse)
{
Vector2[] result=new Vector2[] { };
Ellipse elp = shape1 as Ellipse;
Vector2 diff = elp.Focus1 - elp.Focus2;
float angle = (float)Math.Atan2(diff.Y, diff.X);
Vector2 cent = Rotate(elp.Center, -angle);
Ellipse ellipse = Ellipse.FromThreeDots(Dot.FromCoord(Rotate(elp.Focus1, -angle) - cent),
Dot.FromCoord(Rotate(elp.Focus2, -angle) - Rotate(elp.Center, -angle)), Dot.FromCoord(Rotate(elp.PinPoint, -angle) - cent));
if(shape2 is Segment)
{
Segment seg = shape2 as Segment;
Segment segment = Segment.FromTwoDots(Dot.FromCoord(Rotate(seg.Point1, -angle) - cent),
Dot.FromCoord(Rotate(seg.Point2, -angle) - Rotate(elp.Center, -angle)));
result = getIntersect(ellipse, segment);
}
else if(shape2 is Line)
{
Line lin = shape2 as Line;
Line line = Line.FromTwoDots(Dot.FromCoord(Rotate(lin.Point1, -angle) - cent),
Dot.FromCoord(Rotate(lin.Point2, -angle) - cent));
result = getIntersect(ellipse, line);
}
else if(shape2 is Circle)
{
Circle cir = shape2 as Circle;
Circle circle = Circle.FromTwoDots(Dot.FromCoord(Rotate(cir.Center, -angle) - cent),
Dot.FromCoord(Rotate(cir.Another, -angle) - cent));
result = getIntersect(ellipse, circle);
}
else if(shape2 is Ellipse)
{
Ellipse elps = shape2 as Ellipse;
Ellipse ellipse2 = Ellipse.FromThreeDots(Dot.FromCoord(Rotate(elps.Focus1, -angle) - cent),
Dot.FromCoord(Rotate(elps.Focus2, -angle) - cent),
Dot.FromCoord(Rotate(elps.PinPoint, -angle) - cent));
result = getIntersect(ellipse, ellipse2);
}
for(int i =0; i< result.Length; i++)
{
result[i] = Rotate(result[i] + cent, angle);
}
return result;
}
if (shape1 is Dot || shape2 is Dot) return new Vector2[] { };
throw new ArgumentException("๋จ;;");
}
private static Vector2[] getIntersect(Segment line1, Segment line2)
{
if (line1.Grad == line2.Grad && line1.Yint == line2.Yint) { throw new NotFiniteNumberException("์ผ์น"); }
else if (line1.Grad == line2.Grad) { return new Vector2[] { }; }
float intersectx = (line2.Yint - line1.Yint) / (line1.Grad - line2.Grad);
Vector2 intersect = new Vector2(intersectx, intersectx * line1.Grad + line1.Yint);
if (Vector2.Distance(intersect, line1.Point1) < Vector2.Distance(line1.Point1, line1.Point2) &&
Vector2.Distance(intersect, line1.Point2) < Vector2.Distance(line1.Point1, line1.Point2) &&
Vector2.Distance(intersect, line2.Point1) < Vector2.Distance(line2.Point1, line2.Point2) &&
Vector2.Distance(intersect, line2.Point2) < Vector2.Distance(line2.Point1, line2.Point2))
{
return new Vector2[] { intersect };
}
else return new Vector2[] { };
}
private static Vector2[] getIntersect(Line line1, Segment line2)
{
if (line1.Grad == line2.Grad && line1.Yint == line2.Yint) { throw new NotFiniteNumberException("์ผ์น"); }
else if (line1.Grad == line2.Grad) { return new Vector2[] { }; }
float intersectx = (line2.Yint - line1.Yint) / (line1.Grad - line2.Grad);
Vector2 intersect = new Vector2(intersectx, intersectx * line1.Grad + line1.Yint);
if (Vector2.Distance(intersect, line2.Point1) < Vector2.Distance(line2.Point1, line2.Point2) &&
Vector2.Distance(intersect, line2.Point2) < Vector2.Distance(line2.Point1, line2.Point2))
{
return new Vector2[] { intersect };
}
else return new Vector2[] { };
}
private static Vector2[] getIntersect(Line line1, Line line2)
{
if (line1.Grad == line2.Grad && line1.Yint == line2.Yint) { throw new NotFiniteNumberException("์ผ์น"); }
else if (line1.Grad == line2.Grad) { return new Vector2[] { }; }
float intersectx = (line2.Yint - line1.Yint) / (line1.Grad - line2.Grad);
return new Vector2[] { new Vector2(intersectx, intersectx * line1.Grad + line1.Yint) };
}
private static Vector2[] getIntersect(Line line, Circle circle)
{
Vector2 d = line.Point2 - line.Point1;
float dr = d.Length();
float D = (line.Point1.X - circle.Center.X) * (line.Point2.Y - circle.Center.Y)
- (line.Point2.X - circle.Center.X) * (line.Point1.Y - circle.Center.Y);
float discriminant = circle.Radius * circle.Radius * dr * dr - D * D;
if (discriminant < 0)
return new Vector2[] { };
else if (discriminant == 0)
return new[] { new Vector2(D * d.Y / (dr * dr) + circle.Center.X, -D * d.X / (dr * dr) + circle.Center.Y) };
else
{
float x = D * d.Y / (dr * dr) + circle.Center.X;
float y = -D * d.X / (dr * dr) + circle.Center.Y;
float sgnDy = d.Y < 0 ? -1 : 1;
float xd = sgnDy * d.X * (float)Math.Sqrt(discriminant) / (dr * dr);
float yd = Math.Abs(d.Y) * (float)Math.Sqrt(discriminant) / (dr * dr);
return new[]
{
new Vector2(x + xd, y + yd),
new Vector2(x - xd, y - yd)
};
}
}
private static Vector2[] getIntersect(Segment line, Circle circle)
{
Line lin = Line.FromTwoDots(Dot.FromCoord(line.Point1), Dot.FromCoord(line.Point2));
Vector2[] intersects = getIntersect(lin, circle);
float len = Vector2.Distance(line.Point1, line.Point2);
if (intersects.Length == 0) return new Vector2[] { };
else if (intersects.Length == 1)
{
if (Vector2.Distance(intersects[0], line.Point1) < len && Vector2.Distance(intersects[0], line.Point2) < len)
return intersects;
else return new Vector2[] { };
}
else
{
if (Vector2.Distance(intersects[0], line.Point1) < len && Vector2.Distance(intersects[0], line.Point2) < len)
{
if (Vector2.Distance(intersects[1], line.Point1) < len && Vector2.Distance(intersects[1], line.Point2) < len)
return intersects;
else return new Vector2[] { intersects[0] };
}
else if (Vector2.Distance(intersects[1], line.Point1) < len && Vector2.Distance(intersects[1], line.Point2) < len)
return new Vector2[] { intersects[1] };
else return new Vector2[] { };
}
}
private static Vector2[] getIntersect(Circle circle1, Circle circle2)
{
float distance = (float)Math.Sqrt(Math.Pow(circle2.Center.X - circle1.Center.X, 2) + Math.Pow(circle2.Center.Y - circle1.Center.Y, 2));
if (distance == 0) return new Vector2[] { };
else if (distance > circle1.Radius + circle2.Radius) //๋ ์์ด ๋ฐ์ ์์ผ๋ฉด์ ๋ง๋์ง ์์.
{
return new Vector2[] { };
}
else if ((float)Math.Abs(circle1.Radius - circle2.Radius) > distance) // ๋ ์ ์ค ํ๋๊ฐ ์๋ก๋ฅผ ํฌํจ.
{
return new Vector2[] { };
}
else
{
float d = (circle1.Center - circle2.Center).Length();
float r1 = circle1.Radius;
float r2 = circle2.Radius;
float x = (d * d + r1 * r1 - r2 * r2) / (2 * d);
Vector2 p1 = circle1.Center + (circle2.Center - circle1.Center) * x / d;
Vector2 v1 = circle1.Center - circle2.Center;
v1 = new Vector2(-v1.Y, v1.X);
Vector2 p2 = p1 + v1;
return getIntersect(Line.FromTwoPoints(p1, p2), circle1);
}
}
//ํ์ ์ด์ ์ x์ขํ๊ฐ ์๋ก ๊ฐ์๋ ์์ธ๋ฅผ ๋ฐ์ํด ์ค์ผ ํจ. ๊ทผ๋ฐ ๊ท์ฐจ๋ ^^
private static Vector2[] getIntersect(Ellipse ellipse1, Line line1)
{
float a = ellipse1.Semimajor;
float b = ellipse1.Semiminor;
float c = line1.Grad;
float d = line1.Yint;
float [] xvec = MathMatics.solve2Eq(a * a * c * c + b * b, 2 * a * a * c * d, a * a * (d * d - b * b));
if (xvec.Length == 0) return new Vector2[] { };
if (xvec[0] == xvec[1]) return new[] { new Vector2(xvec[0], c * xvec[0] + d) };
else return new[]
{
new Vector2(xvec[0] , c * xvec[0] + d ),
new Vector2(xvec[1] , c * xvec[1] + d)
};
}
private static Vector2[] getIntersect(Ellipse ellipse1, Segment segment1)
{
Line lin = Line.FromTwoDots(Dot.FromCoord(segment1.Point1), Dot.FromCoord(segment1.Point2));
Vector2[] intersects = getIntersect(ellipse1, lin);
float len = Vector2.Distance(segment1.Point1, segment1.Point2);
if (intersects.Length == 0) return new Vector2[] { };
else if (intersects.Length == 1)
{
if (Vector2.Distance(intersects[0], segment1.Point1) < len && Vector2.Distance(intersects[0], segment1.Point2) < len)
return intersects;
else return new Vector2[] { };
}
else
{
if (Vector2.Distance(intersects[0], segment1.Point1) < len && Vector2.Distance(intersects[0], segment1.Point2) < len)
{
if (Vector2.Distance(intersects[1], segment1.Point1) < len && Vector2.Distance(intersects[1], segment1.Point2) < len)
return intersects;
else return new Vector2[] { intersects[0] };
}
else if (Vector2.Distance(intersects[1], segment1.Point1) < len && Vector2.Distance(intersects[1], segment1.Point2) < len)
return new Vector2[] { intersects[1] };
else return new Vector2[] { };
}
}
private static Vector2[] getIntersect(Ellipse ellipse1, Circle circle1)
{
throw new WorkWoorimException("์ผ๋จ ์ฌ๊ธด ๋๋์");
}
private static Vector2[] getIntersect(Ellipse ellipse1, Ellipse ellipse2)
{
throw new WorkWoorimException("์ฌ๊ธด ๋ X๊ฐ๊ณ ");
}
public static Vector2 GetNearest(Shape shape, Vector2 point)
{
if (shape is Segment) return getNearest(shape as Segment, point);
if (shape is Line) return getNearest(shape as Line, point);
if (shape is Circle) return getNearest(shape as Circle, point);
if (shape is Ellipse) return getNearest(shape as Ellipse, point);
if (shape is Dot) return (shape as Dot).Coord;
throw new ArgumentException("๋จ์ฐ;");
}
private static Vector2 getNearest(Line line, Vector2 point)
{
Vector2 temppoint = point - new Vector2(0, line.Yint);
Line templine = Line.FromTwoPoints(line.Point1 - new Vector2(0, line.Yint), line.Point2 - new Vector2(0, line.Yint));
Line orthogonal = Line.FromTwoPoints(temppoint, new Vector2(temppoint.X + templine.Grad * 10, temppoint.Y - 10));
Vector2 result = getIntersect(templine, orthogonal)[0] + new Vector2(0, line.Yint);
return result;
}
private static Vector2 getNearest(Segment line, Vector2 point)
{
Vector2 temppoint = point - new Vector2(0, line.Yint);
Line templine = Line.FromTwoPoints(line.Point1 - new Vector2(0, line.Yint), line.Point2 - new Vector2(0, line.Yint));
Line orthogonal = Line.FromTwoPoints(temppoint, new Vector2(temppoint.X + templine.Grad * 10, temppoint.Y - 10));
Vector2 result = getIntersect(templine, orthogonal)[0] + new Vector2(0, line.Yint);
return Vector2.Clamp(result, Vector2.Min(line.Point1, line.Point2), Vector2.Max(line.Point1, line.Point2));
}
private static Vector2 getNearest(Circle circle, Vector2 point)
{
if (circle.Center == point) { return circle.Center; }
Vector2[] res = getIntersect(Line.FromTwoPoints(circle.Center, point), circle);
return Vector2.Distance(res[0], point) < Vector2.Distance(res[1], point) ? res[0] : res[1];
}
private static Vector2 getNearest(Ellipse ellipse, Vector2 point)
{
Line lin1 = Line.FromTwoDots(Dot.FromCoord(ellipse.Focus1), Dot.FromCoord(point));
Line lin2 = Line.FromTwoDots(Dot.FromCoord(ellipse.Focus2), Dot.FromCoord(point));
Vector2[] intersects1 = GetIntersect(ellipse, lin1);
Vector2[] intersects2 = GetIntersect(ellipse, lin2);
Vector2 intersect1 = Vector2.Distance(intersects1[0], point) < Vector2.Distance(intersects1[1], point) ? intersects1[0] : intersects1[1];
Vector2 intersect2 = Vector2.Distance(intersects2[0], point) < Vector2.Distance(intersects2[1], point) ? intersects2[0] : intersects2[1];
Line seg1 = Line.FromTwoDots(Dot.FromCoord(ellipse.Focus1), Dot.FromCoord(intersect2));
Line seg2 = Line.FromTwoDots(Dot.FromCoord(ellipse.Focus2), Dot.FromCoord(intersect1));
try
{
Vector2 intersect3 = getIntersect(seg1, seg2)[0];
Vector2[] intersects3 = GetIntersect(ellipse, Line.FromTwoDots(Dot.FromCoord(intersect3), Dot.FromCoord(point)));
Vector2 near = Vector2.Distance(intersects3[0], point) < Vector2.Distance(intersects3[1], point) ? intersects3[0] : intersects3[1];
return near;
}
catch (NotFiniteNumberException inf) {
Vector2[] intsc = GetIntersect(ellipse, seg1);
return Vector2.Distance(intsc[0], point) < Vector2.Distance(intsc[1], point) ? intsc[0] : intsc[1];
}
throw new WorkWoorimException("์๋ฐํ ์ฆ๋ช
์์ด ์ด ์๊ณ ๋ฆฌ์ฆ์ด์ง๋ง ๋ด๊ฐ ์ฆ๋ช
ํ๋ฉด ๋๋๊น ใฑใ
.");
}
public static float GetNearestDistance(Shape shape, Vector2 point)
{
if (shape is Line)
{
Line line = (Line)shape;
return (float)(Math.Abs(line.Grad * point.X - point.Y + line.Yint) / Math.Sqrt(line.Grad * line.Grad + 1));
}
else if (shape is Segment)
{
Segment line = (Segment)shape;
return Vector2.Distance(point, getNearest(line, point));
}
else if (shape is Circle) return Math.Abs(Vector2.Distance((shape as Circle).Center, point) - ((shape as Circle).Radius));
else if (shape is Ellipse) return Vector2.Distance(getNearest(shape as Ellipse , point), point);
else if (shape is Dot) return Vector2.Distance(point, (shape as Dot).Coord);
throw new ArgumentException("๋จ์ฐ;;;");
}
public static Vector2 Rotate(Vector2 vec, float angle)
{
return new Vector2((float)(vec.X * Math.Cos(angle) - vec.Y * Math.Sin(angle)), (float)(vec.X * Math.Sin(angle) + vec.Y * Math.Cos(angle)));
}
public static Vector2 Reflect(Vector2 vec, LineLike axis)
{
Line lin = Line.FromTwoPoints(axis.Point1 - new Vector2(0, axis.Yint), axis.Point2 - new Vector2(0, axis.Yint));
Vector2 d = vec - new Vector2(0, axis.Yint);
float angle = (float)Math.Atan(lin.Grad);
Vector2 ReflectedDot = new Vector2((float)(d.X * Math.Cos(2 * angle) + d.Y * Math.Sin(2 * angle)),
(float)(d.X * Math.Sin(2 * angle) - d.Y * Math.Cos(2 * angle)));
return ReflectedDot + new Vector2(0, axis.Yint);
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Grid.Framework;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace GCS
{
using Keys = Microsoft.Xna.Framework.Input.Keys;
public class MoveConstructComponent : Component
{
public ConstructComponent Comp;
private VScrollBar _vscroll;
private HScrollBar _hscroll;
public VScrollBar Vscroll
{
get => _vscroll;
set
{
if (_vscroll != null)
_vscroll.Scroll -= scroll_Scroll;
_vscroll = value;
_vscroll.Scroll += scroll_Scroll;
value.Minimum = 0;
value.Maximum = (Comp.Size.Y - Comp.Bound.Height) / 5;
}
}
public HScrollBar Hscroll
{
get => _hscroll;
set
{
if (_hscroll != null)
_hscroll.Scroll -= scroll_Scroll;
_hscroll = value;
_hscroll.Scroll += scroll_Scroll;
value.Minimum = 0;
value.Maximum = (Comp.Size.X - Comp.Bound.Width) / 5;
}
}
public MoveConstructComponent()
{
}
public override void Start()
{
base.Start();
_vscroll.Value = _vscroll.Maximum / 2;
_hscroll.Value = _hscroll.Maximum / 2;
scroll_Scroll(null, null);
}
private void scroll_Scroll(object sender, ScrollEventArgs e)
{
Comp.Location = new Vector2(_hscroll.Value * 5, _vscroll.Value * 5);
}
public void Scroll(int x, int y)
{
_hscroll.Value = MathHelper.Clamp(_hscroll.Value + x, _hscroll.Minimum, _hscroll.Maximum);
_vscroll.Value = MathHelper.Clamp(_vscroll.Value + y, _vscroll.Minimum, _vscroll.Maximum);
scroll_Scroll(null, null);
}
public override void Update()
{
base.Update();
var state = Keyboard.GetState();
if (state.IsKeyDown(Keys.Down))
Scroll(0, 5);
if (state.IsKeyDown(Keys.Up))
Scroll(0, -5);
if (state.IsKeyDown(Keys.Left))
Scroll(-5, 0);
if (state.IsKeyDown(Keys.Right))
Scroll(5, 0);
}
}
}
<file_sep>๏ปฟusing System.Linq;
using System.Collections.Generic;
using Grid.Framework;
using Grid.Framework.Components;
using Grid.Framework.GUIs;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using ContextMenuStrip = System.Windows.Forms.ContextMenuStrip;
namespace GCS
{
class GeometrytestComponent : Renderable
{
public override void Draw(SpriteBatch sb)
{
Ellipse elp = Ellipse.FromThreeDots(Dot.FromCoord(0, 0), Dot.FromCoord(300, 300), Dot.FromCoord(400, 250));
//Line lin = Line.FromTwoPoints(new Vector2(100,120), new Vector2(500,670));
Vector2 p = new Vector2(400,100);
Dot d = Dot.FromCoord(Geometry.GetNearest(elp, p));
Line lin1 = Line.FromTwoPoints(elp.Focus1, p);
Line lin2 = Line.FromTwoPoints(elp.Focus2, p);
Dot d2 = Dot.FromCoord(Geometry.GetIntersect(lin1, elp)[1]);
elp.Draw(sb);
Dot.FromCoord(elp.Focus1).Draw(sb);
Dot.FromCoord(elp.Focus2).Draw(sb);
Dot.FromCoord(p).Draw(sb);
lin1.Draw(sb);
lin2.Draw(sb);
d.Draw(sb);
d2.Draw(sb);
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GCS
{
public enum DrawState
{
NONE,
CIRCLE,
ELLIPSE,
ELLIPSE_POINT,
SEGMENT,
LINE,
VECTOR,
DOT
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
namespace GCS
{
public static class MathMatics
{
private const float Upperbound = 1000;
public static float [] solve2Eq(float a, float b, float c)
{
float d = b * b - 4 * a * c;
if (d < 0) return new float[] { };
else if (d == 0) return new float[] { -b / (2 * a), -b / (2 * a) };
else return new float[] { (-b + (float)Math.Sqrt(d)) / (2 * a), (-b - (float)Math.Sqrt(d)) / (2 * a) };
}
// ๊ทผ์ด - Upperbound, Upperbound ์์ ์๋ค๊ณ ๊ฐ์ , ์ถฉ๋ถํ ํฐ Upperbound ๋ฅผ ์ฃผ๋ฉด ๋จ
public static float[] solveNEq(float[] polynorm, int accuracy = 3)
{
List<float> answer = new List<float>();
List<float> coef = polynorm.ToList();
if (coef.Count == 0) return new float[] { };
else
{
while (coef.First() == 0) coef.Remove(0);
}
if (coef.Count == 0) return new float[] { };
else if (coef.Count == 1) return new float[] { };
else if (coef.Count == 2) return new float[] { -coef[0] / coef[1] };
else if (coef.Count == 3) return solve2Eq(coef[0], coef[1], coef[2]);
else
{
var diff = new float[coef.Count - 1];
for (int i = 0; i < coef.Count - 1; i++)
{
diff[i] = (coef.Count - 1 - i) * coef[i]; // ๊ทน๊ฐ์ ๊ตฌํ ํ
}
List<float> extreme_vals = solveNEq(diff, accuracy).ToList();
extreme_vals.Sort();
extreme_vals.Insert(0, -Upperbound);
extreme_vals.Add(Upperbound);
for (int j = 0; j < extreme_vals.Count - 1; j++)//๊ทน๊ฐ์ ๊ธฐ์ค์ผ๋ก ๊ตฌ๊ฐ์ ๋๋ ์ ์ด์ง ํ์ ์ค์
{
if (applyPolynormialFunc(coef, extreme_vals[j]) < Math.Pow(10, -accuracy)) answer.Add(extreme_vals[j]);
else if (applyPolynormialFunc(coef, extreme_vals[j + 1]) < Math.Pow(10, -accuracy)) answer.Add(extreme_vals[j + 1]);
//์ค๊ทผ์ ๋จผ์ ์ฐพ๊ณ (์ค๊ทผ์ ๊ทน๊ฐ์์ ์์)
else if (applyPolynormialFunc(coef, extreme_vals[j]) * applyPolynormialFunc(coef, extreme_vals[j + 1]) < 0)
{
float[] interval = new float[] { extreme_vals[j], extreme_vals[j + 1] };
while (Math.Abs(applyPolynormialFunc(coef, interval[0])) > Math.Pow(10, -accuracy))
{
if (applyPolynormialFunc(coef, interval[0]) * applyPolynormialFunc(coef, (interval[0] + interval[1]) / 2) < 0)
interval[1] = (interval[1] + interval[0]) / 2;
else
interval[0] = (interval[1] + interval[0]) / 2;
}
answer.Add(interval[0]);
}
}
answer.ForEach(x => Math.Round(x, accuracy));
return answer.ToArray();
}
}
private static float applyPolynormialFunc(List<float> polynorm, float x)
{
float sum = 0;
for (int i = 0; i < polynorm.Count; i++)
sum += (float)Math.Pow(x, polynorm.Count - 1 - i) * polynorm[i];
return sum;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
namespace GCS
{
public abstract class ShapeRule
{
public Shape Shape { get; }
protected bool IsHandling = false;
public ShapeRule(Shape shape)
{
Shape = shape;
shape._rule = this;
}
protected abstract void Fix();
public abstract void OnMoved();
public abstract void OnParentMoved();
public virtual void Detach()
{
foreach(var p in Shape.Parents)
{
p.Childs.Remove(Shape);
}
Shape.Parents.Clear();
Shape._rule = null;
}
public void MoveChilds()
{
foreach (var c in Shape.Childs)
c._rule.OnParentMoved();
}
}
public class ReflectedShapeRule : ShapeRule
{
public ReflectedShapeRule(LineLike axis, Shape original, Shape shape) : base(shape)
{
shape.Parents.Add(axis);
shape.Parents.Add(original);
axis.Childs.Add(shape);
original.Childs.Add(shape);
Fix();
}
public override void OnMoved()
{
if (IsHandling) return;
IsHandling = true;
FixParent();
MoveChilds();
IsHandling = false;
}
public override void OnParentMoved()
{
if (IsHandling) return;
Fix();
MoveChilds();
}
protected void FixParent()
{
var axis = Shape.Parents[0] as LineLike;
var original = Shape.Parents[1];
int i = 0;
foreach (var dot in Shape.DotList)
{
original.DotList[i] = Geometry.Reflect(dot, axis);
i++;
}
}
protected override void Fix()
{
var axis = Shape.Parents[0] as LineLike;
var original = Shape.Parents[1];
int i = 0;
foreach (var dot in original.DotList)
{
Shape.DotList[i] = Geometry.Reflect(dot, axis);
i++;
}
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GCS
{
public enum RecodeType
{
CREATE,
DELETE,
MOVE
}
}
<file_sep>๏ปฟusing System;
using Microsoft.Xna.Framework;
namespace GCS
{
public partial class LineLike
{
public class LineLikeOnTwoDotsRule : ShapeRule
{
public LineLikeOnTwoDotsRule(LineLike line, Dot d1, Dot d2) : base(line)
{
d1.Childs.Add(line);
d2.Childs.Add(line);
line.Parents.Add(d1);
line.Parents.Add(d2);
Fix();
}
public override void OnMoved()
{
if (IsHandling) return;
IsHandling = true;
var line = Shape as LineLike;
Shape.Parents[0].MoveTo(line.Point1);
Shape.Parents[1].MoveTo(line.Point2);
Fix(); // ๋ถ๋ชจ ์ ์ด ๋ํ์ ์์กดํ์ฌ ์์ง์์ด ๊ท์ ๋๋ค๋ฉด ๋ค์ ์ฎ๊ฒจ์ค์ผ ํจ
MoveChilds();
IsHandling = false;
}
public override void OnParentMoved()
{
if (IsHandling) return;
Fix();
MoveChilds();
}
protected override void Fix()
{
var line = Shape as LineLike;
line.Point1 = (line.Parents[0] as Dot).Coord;
line.Point2 = (line.Parents[1] as Dot).Coord;
}
}
}
public partial class Line
{
public class ParallelLineRule : ShapeRule
{
private Vector2 _last = new Vector2();
public ParallelLineRule(Line line, LineLike original, Dot on) : base(line)
{
original.Childs.Add(line);
on.Childs.Add(line);
line.Parents.Add(original);
line.Parents.Add(on);
Fix();
}
public override void OnMoved()
{
if (IsHandling) return;
IsHandling = true;
var line = Shape as Line;
var delta = line.Point1 - _last;
var dot = line.Parents[1] as Dot;
dot.Move(delta);
Fix();
MoveChilds();
IsHandling = false;
}
public override void OnParentMoved()
{
if (IsHandling) return;
Fix();
MoveChilds();
}
protected override void Fix()
{
var line = Shape as Line;
var parent = (line.Parents[0] as LineLike);
var dot = (line.Parents[1] as Dot).Coord;
var gap = new Vector2(dot.X - (parent.Point1.X + parent.Point2.X) / 2,
dot.Y - (parent.Point1.Y + parent.Point2.Y) / 2);
line.Point1 = parent.Point1 + gap;
line.Point2 = parent.Point2 + gap;
_last = line.Point1;
}
}
public class PerpendicularLineRule : ShapeRule
{
private Vector2 _last = new Vector2();
public PerpendicularLineRule(Line line, LineLike original, Dot on) : base(line)
{
original.Childs.Add(line);
on.Childs.Add(line);
line.Parents.Add(original);
line.Parents.Add(on);
Fix();
}
public override void OnMoved()
{
if (IsHandling) return;
IsHandling = true;
var line = Shape as Line;
var delta = line.Point1 - _last;
var dot = line.Parents[1] as Dot;
dot.Move(delta);
Fix();
MoveChilds();
IsHandling = false;
}
public override void OnParentMoved()
{
if (IsHandling) return;
Fix();
MoveChilds();
}
protected override void Fix()
{
var line = Shape as Line;
var parent = (line.Parents[0] as LineLike);
var dot = (line.Parents[1] as Dot).Coord;
var gap = new Vector2(dot.X - (parent.Point1.X + parent.Point2.X) / 2,
dot.Y - (parent.Point1.Y + parent.Point2.Y) / 2);
var p1 = Geometry.Rotate(parent.Point1 + gap - dot, MathHelper.ToRadians(90)) + dot;
var p2 = Geometry.Rotate(parent.Point2 + gap - dot, MathHelper.ToRadians(90)) + dot;
line.Point1 = p1;
line.Point2 = p2;
_last = line.Point1;
}
}
public class TangentLineRule : ShapeRule
{
private Vector2 _last = new Vector2();
public TangentLineRule(Line line, Circle original, Dot on) : base(line)
{
original.Childs.Add(line);
on.Childs.Add(line);
line.Parents.Add(original);
line.Parents.Add(on);
Fix();
}
public TangentLineRule(Line line, Ellipse original, Dot on) : base(line)
{
original.Childs.Add(line);
on.Childs.Add(line);
line.Parents.Add(original);
line.Parents.Add(on);
Fix();
}
public override void OnMoved()
{
if (IsHandling) return;
IsHandling = true;
var line = Shape as Line;
var delta = line.Point1 - _last;
var dot = line.Parents[1] as Dot;
dot.Move(delta);
MoveChilds();
Fix();
IsHandling = false;
}
public override void OnParentMoved()
{
if (IsHandling) return;
Fix();
MoveChilds();
}
protected override void Fix()
{
var line = Shape as Line;
var dot = (line.Parents[1] as Dot).Coord;
if(line.Parents[0] is Ellipse)
{
var parent = (line.Parents[0] as Ellipse);
Vector2 diff = parent.Focus1 - parent.Focus2;
float angle = (float)Math.Atan2(diff.Y, diff.X);
var tempcenter = Geometry.Rotate(parent.Center, -angle);
var tempdot = Geometry.Rotate(dot, -angle);
float tempgrad = (parent.Semiminor * parent.Semiminor * (tempcenter.X - tempdot.X))/
(parent.Semimajor * parent.Semimajor * (tempdot.Y - tempcenter.Y ) );
float grad = (float)((tempgrad + Math.Tan(angle)) / (1 - tempgrad * Math.Tan(angle)));
//tangent ๋ง์
์ ๋ฆฌ
line.Point1 = dot;
line.Point2 = dot + new Vector2(1, grad);
}
else
{
var parent = (line.Parents[0] as Circle);
float grad = (parent.Center.X - dot.X) / (dot.Y - parent.Center.Y);
//float Weight = (float)Math.Sqrt(parent.Radius/(grad*grad+1));
line.Point1 = dot;
line.Point2 = dot + new Vector2(1, grad); // or (Weight, Weight * grad)
//Weight ๋ Point1 ๊ณผ Point2 ์ฌ์ด์ ๊ฑฐ๋ฆฌ๋ฅผ Radius ๋ก ๋ฝ์์ค ๋ ์ฐ๋ฉด ๋จ.
}
_last = line.Point1;
}
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GCS
{
public enum ConstructType
{
None,
ParallelLine,
PerpendicularLine,
Tangent,
Reflection,
Ellipse
}
}
<file_sep>๏ปฟusing Microsoft.Xna.Framework.Graphics;
namespace GCS
{
public static class SpriteBatchAntiAliasing
{
public static void BeginAA(this SpriteBatch sb)
{
var state = new RasterizerState { MultiSampleAntiAlias = true };
sb.Begin(rasterizerState: state);
}
}
}
<file_sep>๏ปฟusing System;
using Microsoft.Xna.Framework;
namespace GCS
{
public partial class Dot
{
public class EmptyDotRule : ShapeRule
{
public EmptyDotRule(Dot dot) : base(dot) { }
public override void OnMoved()
{
if (IsHandling) return;
IsHandling = true;
MoveChilds();
IsHandling = false;
}
public override void OnParentMoved()
{
throw new NotSupportedException("๋ถ๋ชจ๋ ์๋๊ฒ..");
}
protected override void Fix()
{
// Do nothing. Just like you.
}
}
public class DotOnShapeRule : ShapeRule
{
/// <summary>
/// ์ ์ด๋ฉด ๋น์จ, ์์ด๋ฉด ๊ฐ
/// </summary>
private float _ratio;
public DotOnShapeRule(Dot dot, Shape parent) : base(dot)
{
dot.Parents.Add(parent);
parent.Childs.Add(dot);
RecalcRatio();
Fix();
}
public override void OnMoved()
{
if (IsHandling) return;
IsHandling = true;
RecalcRatio();
Fix();
MoveChilds();
IsHandling = false;
}
public override void OnParentMoved()
{
if (IsHandling) return;
Fix();
MoveChilds();
}
protected void RecalcRatio()
{
var dot = Shape as Dot;
var parent = Shape.Parents[0];
//ํ์์ด๋ผ๊ณ ๋ค๋ฅผ ๊ฑด ์์. ๋ค๋ง ๋กํ
์ด์
์ ์ ๊ฒฝ์จ์ฃผ๋ฉด ๋ ๋ฟ
if (parent is Circle )
{
var circle = parent as Circle;
_ratio = (float)Math.Atan2(circle.Center.Y - dot.Coord.Y,
-dot.Coord.X + circle.Center.X) + (float)Math.PI;
//tan(theta + pi) = tan(theta);
}
else if (parent is Ellipse)
{
Ellipse ellipse = parent as Ellipse;
Vector2 diff = ellipse.Focus1 - ellipse.Focus2;
float angle = (float)Math.Atan2(diff.Y, diff.X);
Ellipse elp = Ellipse.FromThreeDots(Dot.FromCoord(Geometry.Rotate(ellipse.Focus1, -angle)),
Dot.FromCoord(Geometry.Rotate(ellipse.Focus2, -angle)),
Dot.FromCoord(Geometry.Rotate(ellipse.PinPoint, -angle)));
Vector2 dotc = Geometry.Rotate(dot.Coord, -angle);
_ratio = (float)Math.Atan2(dotc.Y - elp.Center.Y, -dotc.X + elp.Center.X) + (float)Math.PI;
}
else if (parent is LineLike)
{
var line = parent as LineLike;
_ratio = (dot.Coord.X - line.Point1.X) / (line.Point2.X - line.Point1.X);
}
}
protected override void Fix()
{
var dot = Shape as Dot;
var parent = Shape.Parents[0];
if (parent is Circle)
{
var circle = parent as Circle;
dot.Coord = new Vector2(circle.Center.X + (float)Math.Cos(_ratio) * circle.Radius,
circle.Center.Y + (float)Math.Sin(_ratio) * circle.Radius);
}
else if(parent is Ellipse)
{
var ellipse = parent as Ellipse;
Vector2 diff = ellipse.Focus1 - ellipse.Focus2;
float angle = (float)Math.Atan2(diff.Y, diff.X);
Ellipse elp = Ellipse.FromThreeDots(Dot.FromCoord(Geometry.Rotate(ellipse.Focus1, -angle)),
Dot.FromCoord(Geometry.Rotate(ellipse.Focus2, -angle)),
Dot.FromCoord(Geometry.Rotate(ellipse.PinPoint, -angle)));
float grad = (float)Math.Tan(_ratio);
Line lin = Line.FromTwoPoints(elp.Center, elp.Center + new Vector2(1, grad));
Vector2 [] stdpoints = Geometry.GetIntersect(elp, lin);
float dist = Vector2.Distance(stdpoints[0] , elp.Center);
dot.Coord = Geometry.Rotate(new Vector2(elp.Center.X + (float)Math.Cos(-_ratio ) * dist,
elp.Center.Y + (float)Math.Sin(-_ratio ) * dist), angle);//์ด์ผ ์์ ํ ์ง 1๋ ๋ชจ๋ฅด๊ฒ ๋ค
if (true) { };
}
else if (parent is LineLike)
{
var line = parent as LineLike;
var p1 = line.Point1;
var p2 = line.Point2;
dot.Coord = new Vector2(p2.X * _ratio + p1.X * (1 - _ratio),
p2.Y * _ratio + p1.Y * (1 - _ratio));
}
dot.Coord = Geometry.GetNearest(parent, dot.Coord);
}
}
public class DotOnIntersectionRule : ShapeRule
{
/// <summary>
/// ๊ต์ ์ด ๋๊ฐ์ผ ๊ฒฝ์ฐ์ ๋ํด ๋ฐฉํฅ ๊ฒฐ์
/// </summary>
private int _orientation;
private int _firstDirection;
public DotOnIntersectionRule(Dot dot, Shape p1, Shape p2) : base(dot)
{
dot.Parents.Add(p1);
dot.Parents.Add(p2);
p1.Childs.Add(dot);
p2.Childs.Add(dot);
Fix();
}
public override void OnMoved()
{
/*
if (IsHandling) return;
IsHandling = true;
Fix();
foreach (var c in Shape.Childs)
c._rule.OnParentMoved();
IsHandling = false;
*/
Fix();
}
public override void OnParentMoved()
{
if (IsHandling) return;
Fix();
MoveChilds();
//foreach (var c in Shape.Childs)
// c._rule.OnParentMoved();
}
protected override void Fix()
{
var dot = Shape as Dot;
var p1 = Shape.Parents[0];
var p2 = Shape.Parents[1];
var vs = Geometry.GetIntersect(p1, p2);
if(_orientation == 0)
{
if (p1 is Circle && p2 is Circle)
{
var c1 = p1 as Circle;
var c2 = p2 as Circle;
if (_firstDirection == 0) _firstDirection = c2.Center.X < c1.Center.X ? -1 : 1;
_orientation = CheckOrient(dot.Coord, Line.FromTwoPoints(c1.Center, c2.Center));
}
else if (p1 is Circle || p2 is Circle)
{
var c = p1 is Circle ? p1 as Circle : p2 as Circle;
var s = p1 is Circle ? p2 : p1;
if (_firstDirection == 0)
{
_firstDirection = (s as LineLike).Point1.Y < (s as LineLike).Point2.Y ? -1 : 1;
_orientation = CheckOrient(dot.Coord, Line.FromTwoPoints(c.Center, Geometry.GetNearest(s, c.Center)));
}
}
}
if (vs.Length == 0)
{
dot.Disabled = true;
return;
}
else
dot.Disabled = false;
if (vs.Length == 1)
{
dot.Coord = vs[0];
return;
}
else
{
Vector2 result = Vector2.Zero;
int orient = -1;
var c = p1 is Circle ? p1 as Circle : p2 as Circle;
var s = p1 is Circle ? p2 : p1;
int i1 = (_firstDirection + 1) / 2;
int i2 = Math.Abs(i1 - 1);
if (s is LineLike)
{
var l = s as LineLike;
orient = CheckOrient(vs[0], Line.FromTwoPoints(c.Center, Geometry.GetNearest(s, c.Center)));
if (l.Point1.Y < l.Point2.Y)
result = orient == _orientation ? vs[i1] : vs[i2];
else result = orient == _orientation ? vs[i2] : vs[i1];
}
else if (s is Circle)
{
orient = CheckOrient(vs[0], Line.FromTwoPoints(c.Center, (s as Circle).Center));
if((p2 as Circle).Center.X < (p1 as Circle).Center.X)
result = orient == _orientation ? vs[i1] : vs[i2];
else result = orient == _orientation ? vs[i2] : vs[i1];
}
dot.Coord = result;
return;
}
}
private static int CheckOrient(Vector2 d, Line l)
{
if (l.Grad * d.X + l.Yint > d.Y) return -1;
else return 1;
}
}
public class DotOnDotRule : ShapeRule
{
public DotOnDotRule(Dot dot, Dot parent) : base(dot)
{
dot.Parents.Add(parent);
parent.Childs.Add(dot);
Fix();
MoveChilds();
}
public override void OnMoved()
{
if (IsHandling) return;
IsHandling = true;
var dot = Shape.Parents[0] as Dot;
dot.MoveTo((Shape as Dot).Coord);
Fix();
MoveChilds();
IsHandling = false;
}
public override void OnParentMoved()
{
if (IsHandling) return;
Fix();
MoveChilds();
}
protected override void Fix()
{
(Shape as Dot).Coord = (Shape.Parents[0] as Dot).Coord;
}
}
}
}
<file_sep>๏ปฟusing System;
using Microsoft.Xna.Framework;
namespace GCS
{
public partial class Circle
{
public class CircleOnTwoDotsRule : ShapeRule
{
public CircleOnTwoDotsRule(Circle circle, Dot center, Dot another) : base(circle)
{
circle.Parents.Add(center);
circle.Parents.Add(another);
center.Childs.Add(circle);
another.Childs.Add(circle);
Fix();
}
public override void OnMoved()
{
if (IsHandling) return;
IsHandling = true;
var circle = Shape as Circle;
Shape.Parents[0].MoveTo(circle.Center);
Shape.Parents[1].MoveTo(circle.Another);
Fix();
MoveChilds();
IsHandling = false;
}
public override void OnParentMoved()
{
if (IsHandling) return;
Fix();
MoveChilds();
}
protected override void Fix()
{
var circle = Shape as Circle;
circle.Center = (circle.Parents[0] as Dot).Coord;
circle.Another = (circle.Parents[1] as Dot).Coord;
}
}
}
}
<file_sep>๏ปฟusing System;
using Microsoft.Xna.Framework;
namespace GCS
{
public partial class Ellipse
{
public class EllipseOnThreeDotsRule : ShapeRule
{
public EllipseOnThreeDotsRule(Ellipse ellipse, Dot f1, Dot f2, Dot pin) : base(ellipse)
{
ellipse.Parents.Add(f1);
ellipse.Parents.Add(f2);
ellipse.Parents.Add(pin);
f1.Childs.Add(ellipse);
f2.Childs.Add(ellipse);
pin.Childs.Add(ellipse);
Fix();
}
public override void OnMoved()
{
if (IsHandling) return;
IsHandling = true;
var ellipse = Shape as Ellipse;
ellipse.Parents[0].MoveTo(ellipse.Focus1);
ellipse.Parents[1].MoveTo(ellipse.Focus2);
ellipse.Parents[2].MoveTo(ellipse.PinPoint);
Fix();
MoveChilds();
IsHandling = false;
}
public override void OnParentMoved()
{
if (IsHandling) return;
Fix();
MoveChilds();
}
protected override void Fix()
{
var ellipse = Shape as Ellipse;
ellipse.Focus1 = (ellipse.Parents[0] as Dot).Coord;
ellipse.Focus2 = (ellipse.Parents[1] as Dot).Coord;
ellipse.PinPoint = (ellipse.Parents[2] as Dot).Coord;
}
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GCS
{
public class DotNaming
{
private int _current = 0;
private int _labelnum = 0;
public string GetCurrent()
{
try
{
if (_current < 26) // 'A' ~ 'Z'
{
return I2S(_current + 'A');
}
else
{
return string.Concat(I2S( _current % 26 + 'A'), Convert.ToString(_labelnum + 1));
if (_current % 26 == 0) _labelnum++;
}
}
finally
{
_current++;
}
}
private static string I2S(int i)
=> ((char)i).ToString();
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Grid.Framework;
using Grid.Framework.GUIs;
using Button = Grid.Framework.GUIs.Button;
using MenuStrip = System.Windows.Forms.MenuStrip;
using Color = Microsoft.Xna.Framework.Color;
namespace GCS
{
public class Main : Scene
{
private ConstructComponent _construct;
private MenuStrip shapeStrip;
private MenuStrip menu;
public bool GetFocused()
{
foreach (ToolStripMenuItem item in shapeStrip.Items)
if (item.IsOnDropDown ) return true;
foreach (ToolStripMenuItem item in menu.Items)
if (item.IsOnDropDown) return true;
return false;
}
protected override void Initialize()
{
base.Initialize();
// ์๋์ฐ ๋ฆฌ์ฌ์ด์ฆ๋ ๋ชจ๋
ธ๊ฒ์์์ฒด์ ๋ฒ๊ทธ๊ฐ ์๋ค๊ณ ํจ
/*
Window.ClientSizeChanged += (s, e) =>
{
_windowResized = !_windowResized;
if (_windowResized)
{
_graphics.PreferredBackBufferWidth = Window.ClientBounds.Width;
_graphics.PreferredBackBufferHeight = Window.ClientBounds.Height;
_graphics.ApplyChanges();
}
};
Window.AllowUserResizing = true;
*/
}
protected override void InitSize()
{
base.InitSize();
_graphics.PreferredBackBufferWidth = 1280;
_graphics.PreferredBackBufferHeight = 720;
}
protected override void LoadContent()
{
base.LoadContent();
//BackColor = new Color(133, 182, 203);
BackColor = new Color(221, 255, 221);
BackColor = Color.White;
Debugger.Color = Color.Black;
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
_graphics.PreferMultiSampling = true;
GameObject con = new GameObject("construct");
Instantiate(con);
_construct = con.AddComponent<ConstructComponent>();
_construct.Enabled = true;
Resources.LoadAll();
InitGUI();
MainCamera.AddComponent<Grid.Framework.Components.Movable2DCamera>();
/*
GameObject test = new GameObject("test");
test.AddComponent<GeometrytestComponent>();
test.Enabled = true;
Instantiate(test);*/
}
private void InitGUI()
{
shapeStrip = new MenuStrip()
{
BackColor = System.Drawing.Color.White,
Dock = DockStyle.Left
};
AddStripItem(shapeStrip, Icon.circle).Click += (b, d) => _construct.ChangeState(DrawState.CIRCLE);
AddStripItem(shapeStrip, Icon.ellipse).Click += (b, d) => _construct.ChangeState(DrawState.ELLIPSE);
AddStripItem(shapeStrip, Icon.segment).Click += (b, d) => _construct.ChangeState(DrawState.SEGMENT);
AddStripItem(shapeStrip, Icon.line).Click += (b, d) => _construct.ChangeState(DrawState.LINE);
AddStripItem(shapeStrip, Icon.vector).Click += (b, d) => _construct.ChangeState(DrawState.VECTOR);
AddStripItem(shapeStrip, Icon.dot).Click += (b, d) => _construct.ChangeState(DrawState.DOT);
VScrollBar vscroll = new VScrollBar();
vscroll.Dock = DockStyle.Right;
HScrollBar hscroll = new HScrollBar();
hscroll.Dock = DockStyle.Bottom;
var construct = GameObject.Find("construct");
var move = construct.AddComponent<MoveConstructComponent>();
move.Comp = construct.GetComponent<ConstructComponent>();
move.Hscroll = hscroll;
move.Vscroll = vscroll;
menu = new MenuStrip()
{
BackColor = System.Drawing.Color.White
};
var con = new ToolStripMenuItem("์๋(&C)");
con.DropDownItems.Add("ํํ์ (&E)");
con.DropDownItems.Add("์์ (&P)");
con.DropDownItems.Add("์ ์ (&T)");
con.DropDownItems.Add("๋์นญ์ด๋(&R)");
con.DropDownItems.Add("ํ์(&L)");
con.DropDownItems[0].Click += (s, e) => _construct.SelectConstruct(ConstructType.ParallelLine);
con.DropDownItems[1].Click += (s, e) => _construct.SelectConstruct(ConstructType.PerpendicularLine);
con.DropDownItems[2].Click += (s, e) => _construct.SelectConstruct(ConstructType.Tangent);
con.DropDownItems[3].Click += (s, e) => _construct.SelectConstruct(ConstructType.Reflection);
con.DropDownItems[4].Click += (s, e) => _construct.SelectConstruct(ConstructType.Ellipse);
menu.Items.Add(con);
var control = Control.FromHandle(Window.Handle);
control.Controls.Add(shapeStrip);
control.Controls.Add(menu);
control.Controls.Add(vscroll);
control.Controls.Add(hscroll);
}
private ToolStripMenuItem AddStripItem(MenuStrip strip, Image img)
{
var imageSize = new Size(60, 60);
var item = new ToolStripMenuItem(new Bitmap(img, imageSize));
item.ImageAlign = ContentAlignment.MiddleCenter;
item.ImageScaling = ToolStripItemImageScaling.None;
item.AutoSize = true;
strip.Items.Add(item);
return item;
}
}
}
/* ํ
์คํธ ์ปดํฌ๋ํธ๋ฅผ ์์ฑํ ๋๋
75 ์ค false
80 ~ 85 ์ค ์ฃผ์ํด์ */<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GCS
{
public class ShapeManager
{
private List<Shape> _shapes;
public ShapeManager()
{
_shapes = new List<Shape>();
}
public void DeleteShape(Shape shape)
{
if (!_shapes.Contains(shape))
return;
_shapes.Remove(shape);
}
public void DeleteShapes(IEnumerable<Shape> shapes)
{
foreach (var s in shapes)
_shapes.Remove(s);
}
}
}
| 4fbed7793216b31b33c018e445352a0cc8e1d903 | [
"Markdown",
"C#"
] | 21 | Markdown | bigblueberry/GCS | 706e72e9ef7221f8a392d5e1853e8a13fd98c0eb | 810ec4ed36b724e15e59fd0687824f6aaa0d106a |
refs/heads/master | <file_sep>//===============ROTATE WORDS================//
var html = '';
var words = [
{Title: ' Web Designer.'},
{Title: ' Innovator.'},
{Title: ' Ski Coach.'},
{Title: ' Longboarder.'},
{Title: ' Technologist.'},
{Title: ' Baltimorean.'},
{Title: ' Do-It-Yourselfer.'},
{Title: ' Problem-Solver.'}
];
function rotateWord(word) {
var ret = '';
ret += '<span id="animateWord" class="rotating-word">' + word.Title + '</span>';
return ret;
}
for (var i = 0; i < words.length; i++) {
html += rotateWord(words[i]);
}
$('#rotateWord').html(html);
$(document).ready(function() {
$('#rotateWord span:nth-child(1)').addClass('active-word');
$('#rotateWord span:nth-child(1)').removeClass('rotating-word');
});
setInterval(function() {
var active = $('.active-word');
var lastChild = $('.active-word').is('#animateWord:last-child');
if (lastChild) {
active.removeClass('active-word');
active.addClass('rotating-word');
$('#animateWord:first-child').addClass('active-word');
$('#animateWord:first-child').removeClass('rotating-word');
return true;
} else {
active.removeClass('active-word');
active.addClass('rotating-word');
active.next().removeClass('rotating-word');
active.next().addClass('active-word');
return true;
}
}, 3500);
//============Easy Scroll=============//
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 112
}, 1000);
return false;
}
}
});
//===========Modal Section============//
$('#tastyr').on('click', function() {
$('#tastyr-modal').openModal();
});
<file_sep>module.exports = function(grunt) {
require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks);
// require('load-grunt-tasks')(grunt); // npm install --save-dev load-grunt-tasks
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
notify_hooks: {
options: {
enabled: true,
max_jshint_notifications: 5,
title: "Off-Piste Designs" // Change this to your project
}
},
//- Concat JS into single files
concat: {
css : {
src: [
'src/assets/css/main.css',
'src/assets/css/vitality-blue.css'
],
dest : 'test/css/main-concat.css',
},
},
// // Prefix the CSS
// autoprefixer: {
// options: {
// browsers: ["last 2 versions", "> 5%", "ie 8", "ie 7"]
// },
// your_target: {
// options: {
// flatten: true
// },
// src: [
// 'test/css/main-concat.css'
// ],
// dest: [
// 'css/main.css',
// ]
// },
// },
// Minify CSS
// cssmin: {
// minify: {
// expand: true,
// cwd: 'src/assets/css/',
// src: ['main.css', 'vitality-blue.css'],
// dest: 'dist/css/',
// ext: '.css'
// },
// },
// htmlmin: { // Task
// dist: { // Target
// options: { // Target options
// removeComments: true,
// collapseWhitespace: true
// },
// files: { // Dictionary of files
// 'dist/index.html': 'src/index.html', // 'destination': 'source'
// }
// }
// },
imageoptim: {
myTask: {
src: 'src/assets/img/*'
}
},
sync: {
main: {
files: [{
cwd: 'src',
src: [
'assets/**',
// 'js/**',
// 'css/**',
],
dest: 'dist'
}],
verbose: true
}
},
//- Notify when task is complete
notify: {
app_change: {
options: {
title: 'Javascript',
message: 'Concatenatated and minifed successfully',
}
},
css_complete: {
options: {
title: 'SASS -> CSS',
message: 'Compiled, prefixed, and moved successfully',
}
}
},
// //- Sass
// sass: {
// options: {
// sourceMap: true
// },
// dist: {
// files: {
// 'dist/css/main.css': 'src/css/index.scss'
// }
// }
// },
//- Watchers
watch: {
grunt: {
files: ['gruntfile.js'],
tasks: ['default'],
},
css: {
files: ['src/css/*.css'],
tasks: ['notify:css_complete', 'default'],
}
}
});
//- REGISTER ALL OUR GRUNT TASKS
grunt.task.run('notify_hooks');
grunt.registerTask('default', ['concat', 'autoprefixer', 'cssmin', 'htmlmin', 'sync', 'watch']);
grunt.registerTask('app_change', ['concat:app', 'uglify:app', 'uglify:main']);
grunt.registerTask('concat_change', ['uglify:app']);
grunt.registerTask('css_prefixed', ['autoprefixer']);
grunt.registerTask('css_min', ['cssmin']);
grunt.registerTask('sync_files', ['sync']);
grunt.registerTask('imageoptimize', ['imageoptim']);
};
<file_sep>//===============ROTATE WORDS================//
var html = '';
var words = [
{Title: ' Web Designer.'},
{Title: ' Ski Coach.'},
{Title: ' Longboarder.'},
{Title: ' Problem-Solver.'},
{Title: ' Baltimorean.'},
{Title: ' Do-It-Yourselfer.'},
{Title: ' Innovator.'},
{Title: ' Technologist.'}
];
function rotateWord(word) {
var ret = '';
ret += '<span id="animateWord" class="rotating-word">' + word.Title + '</span>';
return ret;
}
for (var i = 0; i < words.length; i++) {
html += rotateWord(words[i]);
}
$('#rotateWord').html(html);
$(document).ready(function() {
$('#rotateWord span:nth-child(1)').addClass('active-word');
$('#rotateWord span:nth-child(1)').removeClass('rotating-word');
});
setInterval(function() {
var active = $('.active-word');
var lastChild = $('.active-word').is('#animateWord:last-child');
if (lastChild) {
active.removeClass('active-word');
active.addClass('rotating-word');
$('#animateWord:first-child').addClass('active-word');
$('#animateWord:first-child').removeClass('rotating-word');
return true;
} else {
active.removeClass('active-word');
active.addClass('rotating-word');
active.next().removeClass('rotating-word');
active.next().addClass('active-word');
return true;
}
}, 3500);
| a97ba6bec7591cce16d367a835ffb96b99121ac2 | [
"JavaScript"
] | 3 | JavaScript | berziiii/off-piste-redesign | f101c1f527a95b847e33b3aee85de8304426b056 | 87c62a153d444d0036fa279aa4b6a86fe20ecfb4 |
refs/heads/master | <file_sep>๏ปฟusing Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Services;
namespace KendoUIAppDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
//Helpful Article: http://www.telerik.com/forums/connect-grid-to-mvc-controller-method
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public JsonResult GetVendors(string requestData)
{
//Response.ContentType = "application/json";
return Json(GetUsers(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetUsers()
{
var jsonObj = new JsonResult();
jsonObj.ContentType = "application/json";
List<Employee> eList = new List<Employee>();
Employee e = new Employee();
for (int i = 0; i < 50; i++)
{
e.ContactTitle = "Mr.";
e.CompanyName = "Demo";
e.ContactName = "A " + i;
eList.Add(e);
}
//Response.ContentType = "applicatin/json";
return Json(eList, JsonRequestBehavior.AllowGet);
//Helpful
//http://www.telerik.com/forums/mvc-controller-grid-databind
}
}
public class Employee
{
public string ContactName { get; set; }
public string CompanyName { get; set; }
public string ContactTitle { get; set; }
}
}
| 554fd5add85c2ae041263fbf7ac8befdf66518bb | [
"C#"
] | 1 | C# | nikkipunjabi/KendoUIPOC | 144573cf4cc75e1cc27cfd2c16d461d0a7a8c6e4 | a1170b85bbaf7c886c99f2cfa6e22c783cb2d2be |
refs/heads/master | <file_sep>from banner.models import Order, Place, Place_owner, Tadbirkor
from django.shortcuts import render, redirect, get_object_or_404
from banner.forms import CreateUserForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from banner.decorators import unauthenticated_user, allowed_users, admin_only
from datetime import date
def change_posts_status():
Place.objects.filter(busy='Band', end_date__lt=date.today()).update(busy="Bo'sh")
def change_order_status():
Order.objects.filter(status='Active', end_date__lt=date.today()).update(status='NotActive')
def change_history():
orders = Order.objects.filter(status='NotActive')
for ord in orders:
pl = ord.place
pl.busy = "Bo'sh"
pl.save()
@unauthenticated_user
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
group = Group.objects.get(name='owner')
user.groups.add(group)
messages.success(
request, f'Yangi hisob {username} uchun yaratildi')
return redirect('login')
context = {'form': form}
return render(request, 'register/register.html', context)
@unauthenticated_user
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=<PASSWORD>)
if user is not None:
login(request, user)
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group == 'owner':
return redirect('user_page')
elif group == 'admin':
return redirect('home')
else:
messages.info(request, 'Parol yoki foydalanuvchi nomi hato!')
context = {}
return render(request, 'register/login.html', context)
def logOutUser(request):
logout(request)
return redirect('login')
@login_required(login_url='login')
@admin_only
def home(request):
change_posts_status()
change_order_status()
orders = Order.objects.all()
active = orders.filter(status='Active')
egasi = Place_owner.objects.filter(is_staff=False)
egalari = []
for eg in egasi:
places_count = eg.place_set.all().count()
dt = {"id": eg.id,
"username": eg.username,
"phone": eg.phone,
"places_count": places_count}
egalari.append(dt)
places = Place.objects.all()
free_places = places.filter(busy="Bo'sh").count()
busy_places = places.filter(busy="Band").count()
total_places = places.count()
total_orders = orders.count()
total_owners = egasi.count()
context = {
'active': active,
'places': places,
'egalari': egalari,
'free_places': free_places,
'busy_places': busy_places,
'total_places': total_places,
'total_orders': total_orders,
'total_owners': total_owners
}
return render(request, 'dashboard.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def order(request):
change_posts_status()
change_order_status()
orders = Order.objects.all()
history = orders.filter(status='NotActive')
current_orders = orders.filter(status='Active')
now_count = current_orders.count()
history_count = history.count()
context = {'orders': orders,
'now_count': now_count,
'history_count': history_count,
'history': history,
'current_orders': current_orders,
}
return render(request, 'orders.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def tadbirkor(request):
tadbirkorlar = Tadbirkor.objects.all()
tadbirkorlar_soni = tadbirkorlar.count()
return render(request, 'tadbirkor.html', {'tadbirkorlar': tadbirkorlar, 'tadbirkorlar_soni': tadbirkorlar_soni})
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def tadbirkor_detail(request, pk):
tadbirkor = get_object_or_404(Tadbirkor, id=pk)
orders = tadbirkor.order_set.all()
orders_count = tadbirkor.order_set.all().count()
context = {
'tadbirkor': tadbirkor,
'orders': orders,
'orders_count': orders_count}
return render(request, 'tad_detail.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def owners(request):
change_posts_status()
change_order_status()
places = Place.objects.all()
free_places = places.filter(busy="Bo'sh").count()
busy_places = places.filter(busy="Band").count()
total_places = places.count()
egalari = Place_owner.objects.filter(is_staff=False)
total_owners = egalari.count()
egasi = []
for ega in egalari:
places_count = ega.place_set.all().count()
dt = {
"id": ega.id,
"username": ega.username,
"phone": ega.phone,
"places_count": places_count
}
egasi.append(dt)
context = {
'places': places,
'egasi': egasi,
'free_places': free_places,
'busy_places': busy_places,
'total_places': total_places,
'total_owners': total_owners,
}
return render(request, 'owners.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def owner_detail(request, pk):
change_posts_status()
change_order_status()
egasi = get_object_or_404(Place_owner, id=pk, is_staff=False)
places = egasi.place_set.all()
places_count = places.count()
context = {
'egasi': egasi,
'places': places,
'places_count': places_count,
}
return render(request, 'owner_detail.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def joylar(request):
change_posts_status()
change_order_status()
change_history()
places = Place.objects.all()
free_places = places.filter(busy="Bo'sh")
busy_places = places.filter(busy="Band")
free_places_count = free_places.count()
busy_places_count = busy_places.count()
total_places_count = places.count()
context = {
'places': places,
'free_places': free_places,
'busy_places': busy_places,
'free_places_count': free_places_count,
'busy_places_count': busy_places_count,
'total_places_count': total_places_count,
}
return render(request, 'joylar.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def joy_detail(request, pk):
change_posts_status()
change_order_status()
change_history()
place = get_object_or_404(Place, id=pk)
orders = place.order_set.all()
active = orders.filter(status='Active')
not_active = orders.filter(status='NotActive')
context = {
'place': place,
'orders': orders,
'active': active,
'not_active': not_active,
}
return render(request, 'joy_detail.html', context)
# User
@login_required(login_url='login')
@allowed_users(allowed_roles=['owner', 'admin'])
def userPage(request):
change_posts_status()
change_order_status()
change_history()
places = request.user.place_set.all()
places_count = places.count()
free_places = places.filter(busy="Bo'sh")
busy_places = places.filter(busy="Band")
free_places_count = free_places.count()
busy_places_count = busy_places.count()
orders = Order.objects.filter(place__owner = request.user)
active_count = orders.filter(status='Active').count()
active = orders.filter(status='Active')
history = orders.filter(status='NotActive')
context = {
'places': places,
'free_places': free_places,
'busy_places': busy_places,
'places_count': places_count,
'free_places_count': free_places_count,
'busy_places_count': busy_places_count,
'active':active,
'history': history,
'active_count': active_count,
}
return render(request, 'user-place.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['owner', 'admin'])
def detailPage(request, pk):
change_posts_status()
change_order_status()
change_history()
place = get_object_or_404(Place, id=pk)
orders = place.order_set.all()
active = orders.filter(status='Active')
not_active = orders.filter(status='NotActive')
context = {
'place': place,
'orders': orders,
'active': active,
'not_active': not_active,
}
return render(request, 'user_detail.html', context) | b6a151e08ca79ecd0c789bf2cb9445273e70a949 | [
"Python"
] | 1 | Python | MeBobur/ban | 9cd89eadd3b721bd702d69d86c26f90f62bbbc71 | 3d4dd82f2043f6cc0ba2dd55cffdc280902d6beb |
refs/heads/master | <file_sep><body>
<h1>
Understanding Routing!
</h1>
<ul>
<li>
<a href="/items">
<div>
/items
</div>
</a>
</li>
<li>
<a href="/items/1">/items/1</a>
</li>
<li>
<a href="/items/2">/items/2</a>
</li>
<li>
<a href="/bogus">/bogus</a>
</li>
</ul>
<form action="/items/create" method="post">
<input type="submit" name="" id="" value="Save" />
</form>
</body>
<file_sep>if (Meteor.isClient) {
Router.map(function () {
this.route('home', {path: '/'});
});
Router.onBeforeAction(function loadingHook (pause) {
if (Session.get('isLoading')) {
this.render('loading');
pause();
}
}, {only: ['home']});
HomeController = RouteController.extend({
action: function () {
this.render();
}
});
}
<file_sep>if (Meteor.isClient) {
Router.configure({autoStart: true});
MyCustomController = RouteController.extend({
template: 'other'
});
Router.map(function () {
this.route('home', {
path: '/',
controller: MyCustomController
});
});
}
<file_sep>if (Meteor.isClient) {
Router.configure({autoStart: false});
Router.run = function (controller) {
console.log('run controller: ', controller);
};
Router.map(function () {
this.route('home', {path: '/'});
this.route('items', {path: '/items'});
this.route('items.show', {path: '/items/:_id'});
});
}
<file_sep>if (Meteor.isClient) {
Router.configure({autoRender: false, autoStart: false});
Deps.autorun(function () {
var currentPath = IronLocation.path();
console.log('currentPath: ', currentPath);
});
IronLocation.start();
}
<file_sep>**Class link:**
https://www.eventedmind.com/classes/iron-router-inside-iron-router/iron-router-introduction
<file_sep>Package.describe({
name: 'log-requests',
summary: 'Log http requests to Meteor WebApp'
});
Npm.depends({'cli-color': '0.2.3'});
Package.on_use(function (api) {
/* Use or imply other packages.
* Example:
* api.use('ui', 'client');
* api.use('iron-router', ['client', 'server']);
*/
api.use('webapp');
api.use('logging');
/*
* Add files that should be used with this
* package.
*/
api.add_files('log-requests.js', ['server']);
/*
* Export global symbols.
*
* Example:
* api.export('GlobalSymbol');
*/
});
Package.on_test(function (api) {
api.use('log-requests');
api.use('tinytest');
api.add_files('log-requests_tests.js');
});
| 90a63c594f063d5064f385781f565cccfb5c841c | [
"JavaScript",
"HTML",
"Markdown"
] | 7 | HTML | eventedmind/class-inside-iron-router | 327964ed0c8a662192929f6d16ec8245f5460d68 | e51a50415c2a7a7a2503c3d5b66b596bbdb1f838 |
refs/heads/master | <repo_name>lingmumu/react-simple-demo<file_sep>/webpack.config.js
module.exports={
entry:'./build/App.js',/**่ฎพ็ฝฎไฝ webpack็ๅ
ฅๅฃ*/
output:{/**่พๅบ*/
path:'./js',/**่พๅบ็่ทฏๅพๅฃ*/
filename:'bundle.js'/**่พๅบ็ๅๅญ ventor*/
},
module:{
loaders:[
{
test: /\.js$/,
loader: "jsx-loader"/**ๅฏไปฅๆๅ
coffeeScript-load css-load jsx-load*/
}
]
}
}
/**webpackๅจreactไธญๅฎ็ฐไธคไธชๅ่ฝ ไธไธชๆฏๅฐ็ถๅญ็ปไปถไน้ด่ฟ่กไพ่ต็ๅๅนถ*/
/**ๅฐjsxไน้ด็ผ่ฏๆjs ่ฟ่ก่งฃๆ*/<file_sep>/build/App.js
var React = require('react');
var ReactDOM = require('react-dom');
var ComponentHeader = require("./ComponentHeader.js");
var ComponentList = require("./ComponentList.js");
var ComponentFooter = require("./ComponentFooter.js");
var App = React.createClass({
render:function(){
return (
<div>
<header>
<ComponentHeader/>
</header>
<section>
<ComponentList/>
</section>
<footer>
<ComponentFooter/>
</footer>
</div>
)
}
})
var HeaderTest = React.createClass({
render:function(){
return (
<div>
<h2 className="title">ๅฅฝๅธ
็ฝๅๅฐ็ฎก็</h2>
<ul className="nav1">
<li>้ฆ้กต</li>
<li>ไบงๅ้กต</li>
<li>่ฏฆ็ป้กต</li>
<li>ๅพ่กจ้กต</li>
<li>่ฎพ็ฝฎ้กต</li>
</ul>
</div>
)
}
})
var NavTest = React.createClass({
render:function(){
return (
<ul className="nav2">
<li>้ฆ้กต</li>
<li>ไบงๅ้กต</li>
<li>่ฏฆ็ป้กต</li>
<li>ๅพ่กจ้กต</li>
<li>่ฎพ็ฝฎ้กต</li>
</ul>
)
}
})
var ConTest = React.createClass({
componentDidMount:function(){
getInfo();
}
render:function(){
return (
<div>
<App/>
</div>
)
}
})
function getInfo(){
$.ajax({
type:"get",
url:"",
async:true,
success:function(data){
}
});
}
ReactDOM.render(<HeaderTest/>,document.getElementById("header"));
ReactDOM.render(<NavTest/>,document.getElementById("nav"));
ReactDOM.render(<ConTest/>,document.getElementById("content"));<file_sep>/build/ComponentHeader.js
var React = require('react');
var ComponentHeader = React.createClass({
render:function(){
return (<div>this is head123</div>)
}
})
module.exports = ComponentHeader
| c51873ab881a26c00a8d44b2744adb28fb4365c9 | [
"JavaScript"
] | 3 | JavaScript | lingmumu/react-simple-demo | 2852e55c3eb4e772d2600e785a15f86285795c32 | 8776aa7a8234cac0c3e2f9c4fa57a5e835a25d16 |
refs/heads/master | <repo_name>SistemasTecTlaxiaco/Prestadores-de-servicio-EGAL-<file_sep>/sistema/detalle_persona.php
<?php
session_start();
include ("correo.php");
?>
<?php
if (!isset($_GET["codigo"])) {
exit();
}
$codigo = $_GET["codigo"];
require_once "../conexion.php";
$query = mysqli_query($conection,'SELECT * FROM registro where id_registro=?');
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<?php include "includes/scripts.php" ?>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta charset="UTF-8">
<title>Prestadores de Servicio EGAL</title>
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css">
</head>
<body>
<?php include "includes/header.php" ?>
<br>
<br>
<br>
<br>
<br>
<div class="container">
<?php
require_once "../conexion.php";
$query = mysqli_query($conection,"SELECT * FROM registro where id_registro='$codigo' ");
foreach ($query as $conection){
}
?>
<div class="col-md-6">
<img src="../img/<?php echo $conection['foto']; ?>" >
</div>
<div class="col-md-6">
<h1><center style="background-color: #EDB214"> <?php echo $conection['tipo_servicio']; ?></center></h1>
<h2> <?php echo $conection['nombreCompleto']; ?> </h2>
<h3>Direcciรณn: <?php echo $conection['direccion']; ?></h3>
<h3>Gmail: <?php echo $conection['email']; ?></h3>
<h3 >Contacto: <a href="https://api.whatsapp.com/send/?phone=+52 <?php echo $conection['telefono']; ?>%&text=Hola,%20Bienvenid@%20al%20sistema%20EGAL,%20en%20que%20podemos%20servirle." target="_blank">
<img src="./img/logo-whatsapp.png" width="20" height="20"><?php echo $conection['telefono']; ?></a>
</h3>
<h3>Sueldo Aprox: <?php echo $conection['pago']; ?></h3>
<br>
<h3> <center><?php echo $conection['descripcion']; ?></center></h3>
</div>
<form method=post name="formx" id="myForm">
<table width="300px">
<h4 class="sent-notification">
<tr>
<td valign="top">
<label for="emaildestino">Destino</label>
</td>
<td valign="top">
<input placelholder="Para" type="email" id="emaildestino" name="emaildestino" maxlength="50" size="30" required value ="<?= $conection['email']; ?>" >
</td>
</tr>
<tr>
<td valign="top">
<label for="Apellido">Nombre</label>
</td>
<td valign="top">
<input placelholder="Apellido" type="text" id="Apellido" name="Apellido" maxlength="50" size="30" required="" placeholder="Ingrese su nombre">
</td>
</tr>
<td valign="top">
<label for="emaildestino">Gmail</label>
</td>
<td valign="top">
<input placelholder="Para" type="email" id="micorreo" name="micorreo" maxlength="50" size="30" required="" placeholder="Ingrese su correo" >
</td>
</tr>
<tr>
<td valign="top">
<label for="asunto">Asunto</label>
</td>
<td valign="top">
<input placelholder="asunto" type="text" id="asunto" name="asunto" maxlength="70" size="30" required="">
</td>
</tr>
<tr>
<td valign="top">
<label for="comentario">Mensaje</label>
</td>
<td valign="top">
<textarea placelholder="comentario" id="comentario" name="comentario" maxlength="1000" cols="30" rows="6" required=""></textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input class="btn_search" type="submit" onclick="sendEmail()" value="Enviar" name="enviar">
<div class="alert">
<?php echo $alert; ?>
</div>
</td>
<script type="text/javascript">
if(window.history.replaceState){
window.history.replaceState(null,null,window.location.href);
}
</script>
</table>
</form>
</div>
</body>
<style>
.btn_search {
background: #0a4661;
color: #fff;
padding: 10 60px;
border:30;
cursor:pointer;
margin-left: 20px;
}
.alert {
color: Red;
}
</style>
</html>
<file_sep>/sistema/includes/scripts.php
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/responsive.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css">
<script type="text/javascript" src="js/functions.js"></script>
<?php include "functions.php" ?><file_sep>/index.php
<?php
$alert = '';
session_start();
if (!empty($_SESSION['active'])) {
header('location: sistema/');
}else{
if (!empty($_POST)) {
if (empty($_POST['usuario']) || empty($_POST['clave'])) {
$alert = 'Ingrese su usuario y su clave';
}else{
require_once "conexion.php";
$user = mysqli_real_escape_string($conection,$_POST['usuario']);
$pass = md5(mysqli_real_escape_string($conection,$_POST['clave']));
$query = mysqli_query($conection,"SELECT * FROM usuario WHERE usuario = '$user' AND clave = '$pass'");
$result = mysqli_num_rows($query);
if ($result > 0) {
$data = mysqli_fetch_array($query);
$_SESSION['active'] = true;
$_SESSION['idUser'] = $data['idusuario'];
$_SESSION['nombre'] = $data['nombre'];
$_SESSION['email'] = $data['email'];
$_SESSION['user'] = $data['usuario'];
$_SESSION['rol'] = $data['rol'];
header('location: sistema/');
}else{
$alert = 'El usuario o la clave son incorrectos';
session_destroy();
}
}
}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="witdh=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>Login | Sistema Prestadores Egal</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="sistema/css/style.css">
</head>
<body>
<section id="container">
<form action="" method="post">
<h3>Prestadores de Servicio EGAL</h3>
<img src="img/login.jpg" alt="Login">
<input type="text" name="usuario" placeholder="Usuario">
<input type="password" name="clave" placeholder="<PASSWORD>">
<div class="alert"><?php echo isset($alert)? $alert : ''; ?></div>
<input type="submit" value="INICIAR SESIรN">
<a href="sistema/registro_usuario.php" class="btn_new">Registrarse</a><br><br>
<a href="sistema/recuperar.php" class="btn_res">ยฟSe te olvidรณ tu contraseรฑa?</a>
</form>
</section>
</body>
</html><file_sep>/sistema/nosotros.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<?php include "includes/scripts.php" ?>
<title>Misiรณn</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<?php include "includes/header.php" ?>
<br>
<br>
<br>
<div class="container">
<div class="item">
<div class="item-text">
<h1><center><font color="#1A33BC">MISIรN</center></font></h1>
<img src="../img/misionn.jpg">
<p>Garantizar la calidad en la prestaciรณn de servicios subcontrados a todos nuestros
clientes mediante el desarrollo relaciones de transparentes y duraderas. A travรฉs de
la excelencia en el servicio, gane el mercado y ofrezca nuevas oportunidades de trabajos.
</div>
</div>
<div class="item">
<div class="item-text">
<h1><center><font color="#1A33BC">VISIรN</center></font></h1>
<img src="../img/visionn.jpg">
<p>Crear oportunidades econรณmicas para cada miembro del mercado laboral global
gracias al desarrollo continuo del primer grรกfico econรณmico del mundo.
</div>
</div>
<div class="item">
<div class="item-text">
<h1><center><font color="#1A33BC">VALORES</center></font></h1>
<img src="../img/values.jpg">
<li>Compromiso</li>
<li>Honestidad</li>
<li>Respeto</li>
<li>Responsabilidad</li>
<li>Transparencia</li>
<li>Diligencia</li>
</div>
</div>
</div>
<?php include "includes/footer.php" ?>
</body>
</html><file_sep>/sistema/registrar.php
<?php
session_start();
include "../conexion.php";
if (!empty($_POST)) {
$alert='';
if (empty($_POST['nombreCompleto']) || empty($_POST['descripcion']) || empty($_POST['direccion']) || empty($_POST['email']) || empty($_POST['pago']) || empty($_POST['telefono']) || empty($_POST['tipo_servicio'])) {
$alert='<p class="msg_error">Todos los campos son obligatorios.</p>';
}else{
$nombreCompleto=$_POST['nombreCompleto'];
$descripcion=$_POST['descripcion'];
$direccion=$_POST['direccion'];
$email=$_POST['email'];
$telefono=$_POST['telefono'];
$tipo_servicio=$_POST['tipo_servicio'];
$pago=$_POST['pago'];
$ss=mysqli_query($conection, "SELECT MAX(id_registro) as id_maximo FROM registro");
if($rr=mysqli_fetch_array($ss)){
$id_maximo=$rr['id_maximo'];
}
$diretorio="../img/";
$nameimagen=$_FILES['foto']['name'];
$tmpimagen=$_FILES['foto']['tmp_name'];
$urlnueva="".$diretorio. "foto_".$id_maximo. ".jpg";
if(is_uploaded_file($tmpimagen)){
copy($tmpimagen,$urlnueva);
$alert='imagen cargado con exito';
}
else{
$alert= 'error al cargar imagen :(';
}
$query = mysqli_query($conection,"SELECT * FROM registro WHERE email = '$email' ");
$result = mysqli_fetch_array($query);
if ($result > 0) {
$alert='<p class="msg_error">El correo ya exixte</p>';
}else{
$query_insert= mysqli_query($conection,"INSERT INTO registro(nombreCompleto,descripcion,direccion,email,pago,telefono,tipo_servicio,foto)
Values ('$nombreCompleto', '$descripcion', '$direccion','$email','$pago','$telefono','$tipo_servicio','$urlnueva')");
if ($query_insert) {
$alert='<p class="msg_save">se ha publicado correctamente</p>';
}else{
$alert='<p class="msg_error">Error al crear la publicacion </p>';
}
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<?php include "includes/scripts.php" ?>
<title>Nuevo Registro</title>
</head>
<body>
<?php include "includes/header.php" ?>
<section id="container">
<div class="form_register">
<h1><i class="fas fa-user-plus"></i> Nuevo Registro</h1>
<hr>
<div class="alert"><?php echo isset($alert)? $alert : ''; ?></div>
<form action="" method="post" enctype="multipart/form-data">
<label for="nombreCompleto">Nombre completo :</label>
<input type="text" id="nombreCompleto" name="nombreCompleto">
<label for="descripcion">Descripcion:</label>
<input type="text" id="descripcion" name="descripcion">
<label for="direccion">Direccion:</label>
<input type="text" id="direccion" name="direccion">
<label for="email">Correo electrรณnico:</label>
<input type="email" id="email" name="email">
<label for="telefono">Telefono:</label>
<input type="text" id="telefono" name="telefono">
<label for="tipo_servicio">Tipo de servicio:</label>
<input type="text" id="tipo_servicio" name="tipo_servicio">
<label for="pago">Forma de pago:</label>
<input type="text" id="pago" name="pago">
<p>
<label for="foto">Fotografia</label><br>
<input type="file" name="foto" id="foto" required>
</p>
<input type="submit" value="Registrar" class="btn_save">
</form>
</div>
</section>
</body>
</html><file_sep>/sistema/index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php include "includes/scripts.php" ?>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta charset="UTF-8">
<title>Prestadores de Servicio EGAL</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<?php include "includes/header.php"?>
<br>
<br>
<br>
<br>
<br>
<div class="mb-3">
<form action="buscar_usuario.php" method="get" class="form_search" >
<input type="text" name="busqueda" id="busqueda" placeholder="Buscar">
<input type="submit" value="Buscar" class="btn_search">
</form>
</div>
<div class="container">
<?php
require_once "../conexion.php";
$query = mysqli_query($conection,'SELECT * FROM registro');
foreach ($query as $conection){
?>
<div class="item">
<a href="detalle_persona.php?codigo=<?php echo $conection['id_registro'] ?>"> <img src="../img/<?php echo $conection['foto'];?>" class="item-img">
<h3><?php echo $conection['nombreCompleto'];?></h3>
<p><?php echo $conection['tipo_servicio'];?></p>
<a href='detalle_persona.php?codigo=<?php echo $conection['id_registro'] ?>' class="btn btn-primary" ><center style="background-color: #FF9900">Mas informacion </center> </a>
<div class="item-text"></div>
</div>
<?php
}
?>
</div>
<?php include "includes/footer.php" ?>
</body>
</html><file_sep>/sistema/mapa.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<?php include "includes/scripts.php" ?>
<title>Mapa</title>
</head>
<body>
<?php include "includes/header.php" ?>
<section id="container">
<div class="form_register">
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d15239.874648164487!2d-97.679629!3d17.268751!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x85c62ec3c9440fc7%3A0x60a4dadf5a38797e!2s69800%20Tlaxco%2C%20Oax.!5e0!3m2!1ses!2smx!4v1639287812514!5m2!1ses!2smx"
width="100%" height="500" style="border:0;" allowfullscreen="" loading="lazy"></iframe>
</div>
</section>
<?php include "includes/footer.php" ?>
</body>
</html><file_sep>/sistema/correo.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$alert='';
if(isset($_POST['emaildestino']) && isset($_POST['Apellido'])){
$emaildestino=$_POST['emaildestino'];
$Apellido=$_POST['Apellido'];
$micorreo=$_POST['micorreo'];
$asunto=$_POST['asunto'];
$comentario=$_POST['comentario'];
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/SMTP.php";
require_once "PHPMailer/Exception.php";
$mail =new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->SMTPAuth = true;
$mail->Username = '<EMAIL>';
$mail->Password = '<PASSWORD>';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail-> isHTML(TRUE);
$mail->setFrom('<EMAIL>', 'Prestadores de servicios EGAL');
$mail->addAddress($emaildestino, $asunto);
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->isHTML(true);
$mail->Subject = 'Correo de contacto';
$mail->Body = 'Nombre: ' . $Apellido .'<br/>Enviรณ:'.$micorreo.'<br/>Asunto:'.$asunto. '<br/>Correo: ' . $emaildestino . '<br/>' . $comentario;
if($mail->send()){
$alert='<div class="alert-success">
<span>Mensaje enviado correctamente!! </span>
</div>';
}
else{
$alert='<div class="alert-success">
<span>Error al enviar!! </span>
</div>';
}
}
<file_sep>/sistema/notificaciones.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<?php include "includes/scripts.php" ?>
<title>Notificaciones</title>
</head>
<body>
<?php include "includes/header.php" ?>
<section id="container">
<div class="form_register">
<form action="" method="post">
<h1>NOTIFICACIONES</h1>
<img src="../img/not.jpg"/>
<h3>
No tienes ninguna notificaciรณn. Ponte en contacto con alguien.
</h3>
</form>
</div>
</section>
<?php include "includes/footer.php" ?>
</body>
</html><file_sep>/sistema/recuperar.php
<?php
include "../conexion.php";
if (!empty($_POST)) {
$alert='';
if (empty($_POST['correo']) || empty($_POST['usuario'])) {
$alert='<p class="msg_error">El campo es obligatorio.</p>';
}else{
$email = $_POST['correo'];
$query = mysqli_query($conection,"SELECT * FROM usuario WHERE correo = '$email'");
$result = mysqli_fetch_array($query);
if ($result > 0) {
$alert='<p class="msg_error">Revise su correo electrรณnico.</p>';
}else{
$query_insert = mysqli_query($conection,"INSERT INTO usuario(nombre,correo,usuario,clave,rol)
VALUES('$nombre','$email','$user','$clave','$rol')");
if ($query_insert) {
$alert='<p class="msg_save">Usuario creado correctamente.</p>';
}else{
$alert='<p class="msg_error">Error al crear el usuario.</p>';
}
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="witdh=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<?php include "includes/scripts.php" ?>
<title>Recuperar contraseรฑa</title>
</head>
<body>
<section id="contenedor">
<div class="form_register">
<form action="" method="post">
<h1>Recuperar</h1>
<div class="alert"><?php echo isset($alert)? $alert : ''; ?></div>
<label for="correo">Correo Electrรณnico</label>
<input type="email" name="correo" id="correo" placeholder="Correo electrรณnico">
<input type="submit" value="Enviar" class="btn_save">
</form>
</div>
</section>
<?php include "includes/footer.php" ?>
</body>
</html><file_sep>/sistema/lista_usuarios.php
<?php
session_start();
include "../conexion.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<?php include "includes/scripts.php" ?>
<title>Mi Perfil</title>
</head>
<body>
<?php include "includes/header.php" ?>
<section id="container">
<h1> Mi Perfil</h1>
<?php
//Mostrar mis Datos
$query = mysqli_query($conection,"SELECT u.idusuario, u.nombre, u.correo, u.usuario, r.rol FROM usuario u INNER JOIN rol r ON u.rol = r.idrol");
mysqli_close($conection);
$result = mysqli_num_rows($query);
if ($result > 0) {
$data = mysqli_fetch_array($query)
?>
<td>ID: <?php echo $data["idusuario"]; ?></td><br>
<td>Nombre: <?php echo $data["nombre"]; ?></td><br>
<td> Correo: <?php echo $data["correo"]; ?></td><br>
<td>Usuario: <?php echo $data["usuario"]; ?></td><br>
<td> Rol: <?php echo $data["rol"]; ?></td><br>
<td>
<a class="link_edit" href="actualizar_perfil.php?id=<?php echo $data["idusuario"]; ?>"><i class="fas fa-edit"></i> Editar</a>
</td>
<?php
}
?>
</section>
</body>
</html><file_sep>/imagen README.md
# Fundamentos-Ing-software
<file_sep>/README.md
# PRESTADORES DE SERVICIOS "EGAL"
Prestadores de servicio "EGAL" es una pรกgina web para prestadores de servicios como albaรฑilerรญa, plomeros, carpinteros, niรฑeras, cocineras, de limpieza etc. Esta plataforma es un medio para poder brindarle al cliente el mejor servicio a travรฉs de una pรกgina web para su uso cotidiano, al mismo tiempo ayudar a los prestadores de servicio para que puedan conseguir trabajo de una manera facil, confiable y segura.
.jpg)
### LIDER DE EQUIPO
<NAME>
### TALENTOS
* AGUILAR AVENDAรO EVA
* <NAME>
* <NAME>
| d9150b3b137ce15df02b025cc5546830f505ec33 | [
"Markdown",
"PHP"
] | 13 | PHP | SistemasTecTlaxiaco/Prestadores-de-servicio-EGAL- | 0a3146b4cf6eeb9eb6de0190b7c8b9e2a741558f | c6cc73881aa459daabe2be1dc95ddd520e2c447b |
refs/heads/master | <repo_name>gitter-badger/emerald-js<file_sep>/lib/rpc/jsonrpc.js
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.jsonrpc = mod.exports;
}
})(this, function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var JsonRpc = function () {
function JsonRpc(transport) {
_classCallCheck(this, JsonRpc);
this.transport = transport;
this.requestSeq = 1;
}
/**
* This call analyses JSON RPC response.
* It returns promise which resolves whether 'result' field found
* or reject in case 'error' field found.
*
* @returns {Promise}
*/
_createClass(JsonRpc, [{
key: 'call',
value: function call(method, params) {
var request = this.newRequest(method, params);
return this.transport.request(request).then(function (json) {
if (json.result || json.result === false || json.result === null) {
return json.result;
} else if (json.error) {
throw new Error(json);
} else {
throw new Error('Unknown JSON RPC response: ' + JSON.stringify(json) + ',\n method: ' + method + ',\n params: ' + JSON.stringify(params));
}
}).catch(function (error) {
throw error;
});
}
}, {
key: 'batch',
value: function batch(requests) {
// build map id -> handler
var handlers = {};
requests.forEach(function (r) {
handlers[r.request.id] = r.handler;
});
return this.transport.request(requests.map(function (r) {
return r.request;
})).then(function (responses) {
// call handler associated with request
responses.forEach(function (response) {
if (typeof handlers[response.id] === 'function') {
handlers[response.id](response);
}
});
return responses;
}).catch(function (error) {
throw error;
});
}
}, {
key: 'newBatchRequest',
value: function newBatchRequest(method, params, handler) {
return {
request: this.newRequest(method, params),
handler: handler
};
}
}, {
key: 'newRequest',
value: function newRequest(method, params) {
var request = {
jsonrpc: '2.0',
method: method,
params: params,
id: this.requestSeq
};
this.requestSeq += 1;
return request;
}
}]);
return JsonRpc;
}();
exports.default = JsonRpc;
});<file_sep>/src/convert.test.js
import BigNumber from 'bignumber.js';
import convert from './convert';
const { toNumber, separateThousands, toHex } = convert;
test('toNumber should convert hex string to number', () => {
expect(toNumber('0x01')).toBe(1);
expect(toNumber('0x')).toBe(0);
expect(toNumber('0xF')).toBe(15);
});
test('toNumber should convert number to number', () => {
expect(toNumber(1)).toBe(1);
expect(toNumber(0)).toBe(0);
expect(toNumber(15)).toBe(15);
});
test('format number with separated thousands', () => {
expect(separateThousands(123456789, ' ')).toEqual('123 456 789');
expect(separateThousands(123456789, '*')).toEqual('123*456*789');
});
describe('toHex', () => {
it('convert decimal number to hex', () => {
expect(toHex(10000000000)).toEqual('0x02540be400');
expect(toHex('21000')).toEqual('0x5208');
});
it('convert BigNumber to hex', () => {
expect(toHex(new BigNumber(21000))).toEqual('0x5208');
});
});
<file_sep>/lib/convert.js
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', 'bignumber.js'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('bignumber.js'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.bignumber);
global.convert = mod.exports;
}
})(this, function (exports, _bignumber) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _bignumber2 = _interopRequireDefault(_bignumber);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
/**
* Convert hex string to number
*
* @param value
* @returns {number}
*/
function toNumber(value) {
if (value === null) {
return 0;
}
if (typeof value === 'number') {
return value;
}
if (typeof value !== 'string') {
throw new Error('Invalid argument type ' + (typeof value === 'undefined' ? 'undefined' : _typeof(value)));
}
if (value === '0x') {
return 0;
}
return parseInt(value.substring(2), 16);
}
function separateThousands(value, separator) {
return value.toLocaleString('en').split(',').join(separator);
}
function toHex(val) {
var hex = new _bignumber2.default(val).toString(16);
return '0x' + (hex.length % 2 !== 0 ? '0' + hex : hex);
}
function hexToBigNumber(val, defaultValue) {
if (val === null || val === '0x') {
return defaultValue;
}
return new _bignumber2.default(val, 16);
}
exports.default = {
toNumber: toNumber,
separateThousands: separateThousands,
toHex: toHex,
hexToBigNumber: hexToBigNumber
};
});<file_sep>/lib/index.js
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', './convert', './wei', './rpc/jsonrpc', './rpc/transport'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('./convert'), require('./wei'), require('./rpc/jsonrpc'), require('./rpc/transport'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.convert, global.wei, global.jsonrpc, global.transport);
global.index = mod.exports;
}
})(this, function (exports, _convert, _wei, _jsonrpc, _transport) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, 'convert', {
enumerable: true,
get: function () {
return _interopRequireDefault(_convert).default;
}
});
Object.defineProperty(exports, 'Wei', {
enumerable: true,
get: function () {
return _interopRequireDefault(_wei).default;
}
});
Object.defineProperty(exports, 'JsonRpc', {
enumerable: true,
get: function () {
return _interopRequireDefault(_jsonrpc).default;
}
});
Object.defineProperty(exports, 'HttpTransport', {
enumerable: true,
get: function () {
return _transport.HttpTransport;
}
});
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
});<file_sep>/lib/jsonrpc.js
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', 'isomorphic-fetch'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('isomorphic-fetch'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.isomorphicFetch);
global.jsonrpc = mod.exports;
}
})(this, function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var baseHeaders = {
'Content-Type': 'application/json'
};
var JsonRpc = function () {
function JsonRpc(url) {
_classCallCheck(this, JsonRpc);
this.requestSeq = 1;
this.url = url;
}
/**
* This call analyses JSON RPC response.
* It returns promise which resolves whether 'result' field found
* or reject in case 'error' field found.
*
* @returns {Promise}
*/
_createClass(JsonRpc, [{
key: 'call',
value: function call(method, params, headers) {
var _this = this;
return new Promise(function (resolve, reject) {
if (typeof method !== 'string') {
reject(new Error('RPC call method must be a string, got:\n method: ' + method + ',\n params: ' + JSON.stringify(params) + ',\n headers: ' + JSON.stringify(headers)));
return;
}
_this.post(method, params, headers).then(function (json) {
if (json.result || json.result === false || json.result === null) {
resolve(json.result);
} else if (json.error) {
reject(json.error);
} else {
reject(new Error('Unknown JSON RPC response: ' + JSON.stringify(json) + ',\n method: ' + method + ',\n params: ' + JSON.stringify(params)));
}
}).catch(reject);
});
}
}, {
key: 'post',
value: function post(name, params, headers) {
var data = this.newRequest(name, params);
var opt = {
method: 'POST',
headers: Object.assign(baseHeaders, headers),
body: JSON.stringify(data)
};
return fetch(this.url, opt).then(function (response) {
if (response.status >= 400) {
throw new Error('Bad RPC response: ' + response.status);
}
return response.json();
});
}
}, {
key: 'newRequest',
value: function newRequest(method, params) {
var request = {
jsonrpc: '2.0',
method: method,
params: params,
id: this.requestSeq
};
this.requestSeq += 1;
return request;
}
}]);
return JsonRpc;
}();
exports.default = JsonRpc;
});<file_sep>/README.md
# emerald-js
`npm run setup` | 4b60439f10ab189557eeefa49e899b0cacea7ac7 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | gitter-badger/emerald-js | 21bb8f7a8a94f641ae86d631bcd35d1e9109e6b2 | 12f162eb616993de2a92d4eb8e66e270dba8f041 |
refs/heads/master | <repo_name>taruti/ultimateq<file_sep>/data/user_test.go
package data
import (
"fmt"
. "launchpad.net/gocheck"
)
func (s *s) TestUser_Create(c *C) {
u := CreateUser("")
c.Check(u, IsNil)
u = CreateUser("nick")
c.Check(u, NotNil)
c.Check(u.GetNick(), Equals, "nick")
c.Check(u.GetFullhost(), Equals, "nick")
u = CreateUser("nick!user@host")
c.Check(u, NotNil)
c.Check(u.GetNick(), Equals, "nick")
c.Check(u.GetUsername(), Equals, "user")
c.Check(u.GetHost(), Equals, "host")
c.Check(u.GetFullhost(), Equals, "nick!user@host")
}
func (s *s) TestUser_Realname(c *C) {
u := CreateUser("nick!user@host")
u.Realname("realname realname")
c.Check(u.GetRealname(), Equals, "realname realname")
}
func (s *s) TestUser_String(c *C) {
u := CreateUser("nick")
str := fmt.Sprint(u)
c.Check(str, Equals, "nick")
u = CreateUser("nick!user@host")
str = fmt.Sprint(u)
c.Check(str, Equals, "nick nick!user@host")
u = CreateUser("nick")
u.Realname("realname realname")
str = fmt.Sprint(u)
c.Check(str, Equals, "nick realname realname")
u = CreateUser("nick!user@host")
u.Realname("realname realname")
str = fmt.Sprint(u)
c.Check(str, Equals, "nick nick!user@host realname realname")
}
<file_sep>/dispatch/dispatch.go
/*
dispatch package is used to dispatch irc messages to event handlers in an
asynchronous fashion. It supports various event handling types to easily
extract information from events, as well as define more succint handlers.
*/
package dispatch
import (
"errors"
"github.com/aarondl/ultimateq/irc"
"math/rand"
"strings"
"sync"
)
var (
// errProtoCapsMissing is returned by CreateRichDispatch if nil is provided
// instead of a irc.ProtoCaps pointer.
errProtoCapsMissing = errors.New(
"dispatch: Protocaps missing in CreateRichDispatch")
)
// EventHandler is the basic interface that will deal with handling any message
// as a raw IrcMessage event. However there are other message types are specific
// to very common irc events that are more helpful than this interface.
type EventHandler interface {
HandleRaw(event *irc.IrcMessage, endpoint irc.Endpoint)
}
type (
// eventTable is the storage used to keep id -> interface{} mappings in the
// eventTableStore map.
eventTable map[int]interface{}
// eventTableStore is the map used to hold the event handlers for an event
eventTableStore map[string]eventTable
)
// Dispatcher is made for handling bot-local dispatching of irc
// events.
type Dispatcher struct {
events eventTableStore
finder *irc.ChannelFinder
chans []string
waiter sync.WaitGroup
// Protects all state variables.
protect sync.RWMutex
}
// CreateDispatcher initializes an empty dispatcher ready to register events.
func CreateDispatcher() *Dispatcher {
return &Dispatcher{
events: make(eventTableStore),
}
}
// CreateRichDispatcher initializes empty dispatcher ready to register events
// and additionally creates a channelfinder from a set of irc.ProtoCaps in order
// to properly send Privmsg(User|Channel)/Notice(User|Channel) events. If
// activeChannels is not nil, (Privmsg|Notice)Channel events are filtered on
// the list of channels.
func CreateRichDispatcher(caps *irc.ProtoCaps,
activeChannels []string) (*Dispatcher, error) {
if caps == nil {
return nil, errProtoCapsMissing
}
d := &Dispatcher{
events: make(eventTableStore),
}
err := d.protocaps(caps)
if err != nil {
return nil, err
}
d.channels(activeChannels)
return d, nil
}
// Protocaps sets the protocaps for this dispatcher.
func (d *Dispatcher) Protocaps(caps *irc.ProtoCaps) (err error) {
d.protect.Lock()
defer d.protect.Unlock()
err = d.protocaps(caps)
return
}
// protocaps sets the protocaps for this dispatcher. Not thread safe.
func (d *Dispatcher) protocaps(caps *irc.ProtoCaps) (err error) {
d.finder, err = irc.CreateChannelFinder(caps.Chantypes())
return
}
// Channels sets the active channels for this dispatcher.
func (d *Dispatcher) Channels(chans []string) {
d.protect.Lock()
d.channels(chans)
d.protect.Unlock()
}
// GetChannels gets the active channels for this dispatcher.
func (d *Dispatcher) GetChannels() (chans []string) {
d.protect.Lock()
defer d.protect.Unlock()
if d.chans == nil {
return
}
chans = make([]string, len(d.chans))
copy(chans, d.chans)
return
}
// AddChannels adds channels to the active channels for this dispatcher.
func (d *Dispatcher) AddChannels(chans ...string) {
if 0 == len(chans) {
return
}
d.protect.Lock()
defer d.protect.Unlock()
if d.chans == nil {
d.chans = make([]string, 0, len(chans))
}
for i := 0; i < len(chans); i++ {
addchan := strings.ToLower(chans[i])
found := false
for j, length := 0, len(d.chans); j < length; j++ {
if d.chans[j] == addchan {
found = true
break
}
}
if !found {
d.chans = append(d.chans, addchan)
}
}
}
// RemoveChannels removes channels to the active channels for this dispatcher.
func (d *Dispatcher) RemoveChannels(chans ...string) {
if 0 == len(chans) {
return
}
d.protect.Lock()
defer d.protect.Unlock()
if d.chans == nil || 0 == len(d.chans) {
return
}
for i := 0; i < len(chans); i++ {
removechan := strings.ToLower(chans[i])
for j, length := 0, len(d.chans); j < length; j++ {
if d.chans[j] == removechan {
if length == 1 {
d.chans = nil
return
}
if j < length-1 {
d.chans[j], d.chans[length-1] =
d.chans[length-1], d.chans[j]
}
d.chans = d.chans[:length-1]
length--
}
}
}
}
// channels sets the active channels for this dispatcher. Not thread
// safe.
func (d *Dispatcher) channels(chans []string) {
length := len(chans)
if length == 0 {
d.chans = nil
} else {
d.chans = make([]string, length)
for i := 0; i < length; i++ {
d.chans[i] = strings.ToLower(chans[i])
}
}
}
// Register registers an event handler to a particular event. In return a
// unique identifer is given to later pass into Unregister in case of a need
// to unregister the event handler.
func (d *Dispatcher) Register(event string, handler interface{}) int {
event = strings.ToUpper(event)
id := rand.Int()
d.protect.Lock()
defer d.protect.Unlock()
if ev, ok := d.events[event]; !ok {
d.events[event] = make(eventTable)
} else {
for _, has := ev[id]; has; id = rand.Int() {
}
}
d.events[event][id] = handler
return id
}
// Unregister uses the event name, and the identifier returned by Register to
// unregister a callback from the Dispatcher. If the callback was removed it
// returns true, false if it could not be found.
func (d *Dispatcher) Unregister(event string, id int) bool {
event = strings.ToUpper(event)
d.protect.Lock()
defer d.protect.Unlock()
if ev, ok := d.events[event]; ok {
if _, ok := ev[id]; ok {
delete(ev, id)
return true
}
}
return false
}
// Dispatch an IrcMessage to event handlers handling event also ensures all raw
// handlers receive all messages. Returns false if no eventtable was found for
// the primary sent event.
func (d *Dispatcher) Dispatch(msg *irc.IrcMessage, ep irc.Endpoint) bool {
event := strings.ToUpper(msg.Name)
d.protect.RLock()
defer d.protect.RUnlock()
handled := d.dispatchHelper(event, msg, ep)
d.dispatchHelper(irc.RAW, msg, ep)
return handled
}
// WaitForCompletion waits on all active event handlers to return. Bad event
// handlers may never return.
func (d *Dispatcher) WaitForCompletion() {
d.waiter.Wait()
}
// dispatchHelper locates a handler and attempts to resolve it with
// resolveHandler. It returns true if it was able to find an event table.
func (d *Dispatcher) dispatchHelper(event string,
msg *irc.IrcMessage, ep irc.Endpoint) bool {
if evtable, ok := d.events[event]; ok {
for _, handler := range evtable {
d.waiter.Add(1)
go d.resolveHandler(handler, event, msg, ep)
}
return true
}
return false
}
// resolveHandler checks the type of the handler passed in, resolves it to a
// real type, coerces the IrcMessage in whatever way necessary and then
// calls that handlers primary dispatch method with the coerced message.
func (d *Dispatcher) resolveHandler(
handler interface{}, event string, msg *irc.IrcMessage, ep irc.Endpoint) {
switch t := handler.(type) {
case PrivmsgHandler, PrivmsgUserHandler, PrivmsgChannelHandler:
if channelHandler, ok := t.(PrivmsgChannelHandler); ok &&
d.shouldDispatch(true, msg) {
channelHandler.PrivmsgChannel(&irc.Message{msg}, ep)
} else if userHandler, ok := t.(PrivmsgUserHandler); ok &&
d.shouldDispatch(false, msg) {
userHandler.PrivmsgUser(&irc.Message{msg}, ep)
} else if privmsgHandler, ok := t.(PrivmsgHandler); ok {
privmsgHandler.Privmsg(&irc.Message{msg}, ep)
}
case NoticeHandler, NoticeUserHandler, NoticeChannelHandler:
if channelHandler, ok := t.(NoticeChannelHandler); ok &&
d.shouldDispatch(true, msg) {
channelHandler.NoticeChannel(&irc.Message{msg}, ep)
} else if userHandler, ok := t.(NoticeUserHandler); ok &&
d.shouldDispatch(false, msg) {
userHandler.NoticeUser(&irc.Message{msg}, ep)
} else if noticeHandler, ok := t.(NoticeHandler); ok {
noticeHandler.Notice(&irc.Message{msg}, ep)
}
case EventHandler:
t.HandleRaw(msg, ep)
}
d.waiter.Done()
}
// shouldDispatch checks if we should dispatch this event. Works for user and
// channel based messages.
func (d *Dispatcher) shouldDispatch(channel bool, msg *irc.IrcMessage) bool {
d.protect.RLock()
defer d.protect.RUnlock()
return d.finder != nil && channel == d.finder.IsChannel(msg.Args[0]) &&
(!channel || d.checkChannels(msg))
}
// filterChannelDispatch is used for any channel-specific message handlers
// that exist. It scans the list of targets given to CreateRichDispatch to
// check if this event should be dispatched.
func (d *Dispatcher) checkChannels(msg *irc.IrcMessage) bool {
if d.chans == nil {
return true
}
targ := strings.ToLower(msg.Args[0])
for i := 0; i < len(d.chans); i++ {
if targ == d.chans[i] {
return true
}
}
return false
}
<file_sep>/config/config_test.go
package config
import (
"bytes"
. "launchpad.net/gocheck"
"log"
"os"
"testing"
)
func Test(t *testing.T) { TestingT(t) } //Hook into testing package
type s struct{}
var _ = Suite(&s{})
func init() {
setLogger() // This had to be done for DisplayErrors' test
}
func setLogger() {
f, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
if err != nil {
log.Println("Could not set logger:", err)
} else {
log.SetOutput(f)
}
}
func reqErr(name string) string {
return `.*Requires.*` + name + `.*`
}
func invErr(name string) string {
return `.*Invalid.*` + name + `.*`
}
var srv1 = &Server{
Name: "irc1",
Host: "irc.gamesurge.net",
Port: 5555,
Ssl: "true",
VerifyCert: "false",
NoState: "false",
FloodProtectBurst: "5",
FloodProtectTimeout: "3.5",
FloodProtectStep: "5.5",
NoReconnect: "false",
ReconnectTimeout: "10",
Nick: "n1",
Altnick: "a1",
Username: "u1",
Userhost: "h1",
Realname: "r1",
Prefix: "p1",
Channels: []string{"#chan1", "#chan2"},
}
var srv2 = &Server{
Name: "irc2",
Host: "irc.gamesurge.com",
Port: 6666,
Ssl: "false",
VerifyCert: "true",
NoState: "true",
FloodProtectBurst: "6",
FloodProtectTimeout: "4.5",
FloodProtectStep: "6.5",
NoReconnect: "true",
ReconnectTimeout: "100",
Nick: "n2",
Altnick: "a2",
Username: "u2",
Userhost: "h2",
Realname: "r2",
Prefix: "p2",
Channels: []string{"#chan2"},
}
func (s *s) TestConfig(c *C) {
config := CreateConfig()
c.Check(config.Servers, NotNil)
c.Check(config.Global, NotNil)
}
func (s *s) TestConfig_Fallbacks(c *C) {
config := CreateConfig()
host, name := "irc.gamesurge.net", "gamesurge"
srv := *srv1
config.Global = &srv
server := &Server{parent: config, Name: name, Host: host}
config.Servers[name] = server
c.Check(server.GetHost(), Equals, host)
c.Check(server.GetName(), Equals, name)
c.Check(server.GetPort(), Equals, config.Global.GetPort())
c.Check(server.GetSsl(), Equals, config.Global.GetSsl())
c.Check(server.GetVerifyCert(), Equals, config.Global.GetVerifyCert())
c.Check(server.GetNoState(), Equals, config.Global.GetNoState())
c.Check(server.GetFloodProtectBurst(), Equals,
config.Global.GetFloodProtectBurst())
c.Check(server.GetFloodProtectTimeout(), Equals,
config.Global.GetFloodProtectTimeout())
c.Check(server.GetFloodProtectStep(), Equals,
config.Global.GetFloodProtectStep())
c.Check(server.GetNoReconnect(), Equals, config.Global.GetNoReconnect())
c.Check(server.GetReconnectTimeout(), Equals,
config.Global.GetReconnectTimeout())
c.Check(server.GetNick(), Equals, config.Global.GetNick())
c.Check(server.GetAltnick(), Equals, config.Global.GetAltnick())
c.Check(server.GetUsername(), Equals, config.Global.GetUsername())
c.Check(server.GetUserhost(), Equals, config.Global.GetUserhost())
c.Check(server.GetRealname(), Equals, config.Global.GetRealname())
c.Check(server.GetPrefix(), Equals, config.Global.GetPrefix())
c.Check(len(server.GetChannels()), Equals, len(config.Global.Channels))
for i, v := range server.GetChannels() {
c.Check(v, Equals, config.Global.Channels[i])
}
}
func (s *s) TestConfig_Fluent(c *C) {
srv2host := "znc.gamesurge.net"
conf := CreateConfig().
// Setting Globals
Host(""). // Should not break anything
Port(srv2.GetPort()).
Ssl(srv2.GetSsl()).
VerifyCert(srv2.GetVerifyCert()).
NoState(srv2.GetNoState()).
FloodProtectBurst(srv2.GetFloodProtectBurst()).
FloodProtectTimeout(srv2.GetFloodProtectTimeout()).
FloodProtectStep(srv2.GetFloodProtectStep()).
NoReconnect(srv2.GetNoReconnect()).
ReconnectTimeout(srv2.GetReconnectTimeout()).
Nick(srv2.GetNick()).
Altnick(srv2.GetAltnick()).
Username(srv2.GetUsername()).
Userhost(srv2.GetUserhost()).
Realname(srv2.GetRealname()).
Prefix(srv2.GetPrefix()).
Channels(srv2.GetChannels()...).
// Server 1
Server(srv1.GetName()).
Host(srv1.GetHost()).
Port(srv1.GetPort()).
Ssl(srv1.GetSsl()).
VerifyCert(srv1.GetVerifyCert()).
NoState(srv1.GetNoState()).
FloodProtectBurst(srv1.GetFloodProtectBurst()).
FloodProtectTimeout(srv1.GetFloodProtectTimeout()).
FloodProtectStep(srv1.GetFloodProtectStep()).
NoReconnect(srv1.GetNoReconnect()).
ReconnectTimeout(srv1.GetReconnectTimeout()).
Nick(srv1.GetNick()).
Altnick(srv1.GetAltnick()).
Username(srv1.GetUsername()).
Userhost(srv1.GetUserhost()).
Realname(srv1.GetRealname()).
Prefix(srv1.GetPrefix()).
Channels(srv1.GetChannels()...).
// Server 2 using defaults
Server(srv2host)
server := conf.GetServer(srv1.Name)
server2 := conf.GetServer(srv2host)
c.Check(server.GetHost(), Equals, srv1.GetHost())
c.Check(server.GetName(), Equals, srv1.GetName())
c.Check(server.GetPort(), Equals, srv1.GetPort())
c.Check(server.GetSsl(), Equals, srv1.GetSsl())
c.Check(server.GetVerifyCert(), Equals, srv1.GetVerifyCert())
c.Check(server.GetNoState(), Equals, srv1.GetNoState())
c.Check(server.GetFloodProtectBurst(), Equals, srv1.GetFloodProtectBurst())
c.Check(server.GetFloodProtectTimeout(), Equals,
srv1.GetFloodProtectTimeout())
c.Check(server.GetFloodProtectStep(), Equals, srv1.GetFloodProtectStep())
c.Check(server.GetNoReconnect(), Equals, srv1.GetNoReconnect())
c.Check(server.GetReconnectTimeout(), Equals, srv1.GetReconnectTimeout())
c.Check(server.GetNick(), Equals, srv1.GetNick())
c.Check(server.GetAltnick(), Equals, srv1.GetAltnick())
c.Check(server.GetUsername(), Equals, srv1.GetUsername())
c.Check(server.GetUserhost(), Equals, srv1.GetUserhost())
c.Check(server.GetRealname(), Equals, srv1.GetRealname())
c.Check(server.GetPrefix(), Equals, srv1.GetPrefix())
c.Check(len(server.GetChannels()), Equals, len(srv1.Channels))
for i, v := range server.GetChannels() {
c.Check(v, Equals, srv1.Channels[i])
}
c.Check(server2.GetHost(), Equals, srv2host)
c.Check(server2.GetPort(), Equals, srv2.GetPort())
c.Check(server2.GetSsl(), Equals, srv2.GetSsl())
c.Check(server2.GetVerifyCert(), Equals, srv2.GetVerifyCert())
c.Check(server2.GetNoState(), Equals, srv2.GetNoState())
c.Check(server2.GetFloodProtectBurst(), Equals, srv2.GetFloodProtectBurst())
c.Check(server2.GetFloodProtectTimeout(), Equals,
srv2.GetFloodProtectTimeout())
c.Check(server2.GetFloodProtectStep(), Equals, srv2.GetFloodProtectStep())
c.Check(server2.GetNoReconnect(), Equals, srv2.GetNoReconnect())
c.Check(server2.GetReconnectTimeout(), Equals, srv2.GetReconnectTimeout())
c.Check(server2.GetNick(), Equals, srv2.GetNick())
c.Check(server2.GetAltnick(), Equals, srv2.GetAltnick())
c.Check(server2.GetUsername(), Equals, srv2.GetUsername())
c.Check(server2.GetUserhost(), Equals, srv2.GetUserhost())
c.Check(server2.GetRealname(), Equals, srv2.GetRealname())
c.Check(server2.GetPrefix(), Equals, srv2.GetPrefix())
c.Check(len(server2.GetChannels()), Equals, len(srv2.Channels))
for i, v := range server2.GetChannels() {
c.Check(v, Equals, srv2.Channels[i])
}
}
func (s *s) TestConfig_Defaults(c *C) {
conf := CreateConfig().
Nick(srv1.Nick).
Realname(srv1.Realname).
Username(srv1.Username).
Userhost(srv1.Userhost).
Server(srv1.GetName())
srv := conf.GetServer(srv1.GetName())
c.Check(srv.GetPort(), Equals, defaultIrcPort)
c.Check(srv.GetSsl(), Equals, false)
c.Check(srv.GetVerifyCert(), Equals, false)
c.Check(srv.GetNoState(), Equals, false)
c.Check(srv.GetFloodProtectBurst(), Equals, defaultFloodProtectBurst)
c.Check(srv.GetFloodProtectTimeout(), Equals, defaultFloodProtectTimeout)
c.Check(srv.GetFloodProtectStep(), Equals, defaultFloodProtectStep)
c.Check(srv.GetNoReconnect(), Equals, false)
c.Check(srv.GetReconnectTimeout(), Equals, defaultReconnectTimeout)
}
func (s *s) TestConfig_InvalidValues(c *C) {
conf := CreateConfig().
Nick(srv1.Nick).
Realname(srv1.Realname).
Username(srv1.Username).
Userhost(srv1.Userhost).
Server(srv1.GetName())
srv := conf.GetServer(srv1.GetName())
srv.Ssl = "x"
srv.FloodProtectBurst = "x"
srv.FloodProtectStep = "x"
srv.FloodProtectTimeout = "x"
srv.VerifyCert = "x"
srv.NoState = "x"
srv.NoReconnect = "x"
srv.ReconnectTimeout = "x"
c.Check(srv.GetSsl(), Equals, false)
c.Check(srv.GetVerifyCert(), Equals, false)
c.Check(srv.GetNoState(), Equals, false)
c.Check(srv.GetFloodProtectBurst(), Equals, defaultFloodProtectBurst)
c.Check(srv.GetFloodProtectTimeout(), Equals, defaultFloodProtectTimeout)
c.Check(srv.GetFloodProtectStep(), Equals, defaultFloodProtectStep)
c.Check(srv.GetNoReconnect(), Equals, false)
c.Check(srv.GetReconnectTimeout(), Equals, defaultReconnectTimeout)
c.Check(conf.IsValid(), Equals, false)
c.Check(len(conf.Errors), Equals, 8)
c.Check(conf.Errors[0].Error(), Matches, invErr(errSsl))
c.Check(conf.Errors[1].Error(), Matches, invErr(errVerifyCert))
c.Check(conf.Errors[2].Error(), Matches, invErr(errNoState))
c.Check(conf.Errors[3].Error(), Matches, invErr(errFloodProtectBurst))
c.Check(conf.Errors[4].Error(), Matches, invErr(errFloodProtectTimeout))
c.Check(conf.Errors[5].Error(), Matches, invErr(errFloodProtectStep))
c.Check(conf.Errors[6].Error(), Matches, invErr(errNoReconnect))
c.Check(conf.Errors[7].Error(), Matches, invErr(errReconnectTimeout))
}
func (s *s) TestConfig_ValidationEmpty(c *C) {
conf := CreateConfig()
c.Check(conf.IsValid(), Equals, false)
c.Check(len(conf.Errors), Equals, 1)
c.Check(conf.Errors[0].Error(), Equals, errMsgServersRequired)
}
func (s *s) TestConfig_ValidationNoHost(c *C) {
conf := CreateConfig().
Server("").
Port(srv1.Port)
c.Check(len(conf.Servers), Equals, 0)
c.Check(conf.Global.Port, Equals, uint16(srv1.Port))
c.Check(conf.IsValid(), Equals, false)
c.Check(len(conf.Errors), Equals, 2)
c.Check(conf.Errors[0].Error(), Matches, reqErr(errHost))
c.Check(conf.Errors[1].Error(), Equals, errMsgServersRequired)
}
func (s *s) TestConfig_ValidationInvalidHost(c *C) {
conf := CreateConfig().
Nick(srv1.Nick).
Realname(srv1.Realname).
Username(srv1.Username).
Userhost(srv1.Userhost).
Server("%")
c.Check(conf.IsValid(), Equals, false)
c.Check(len(conf.Errors), Equals, 1)
c.Check(conf.Errors[0].Error(), Matches, invErr(errHost))
}
func (s *s) TestConfig_ValidationNoHostInternal(c *C) {
conf := CreateConfig().
Server(srv1.Host).
Nick(srv1.Nick).
Channels(srv1.Channels...).
Username(srv1.Username).
Userhost(srv1.Userhost).
Realname(srv1.Realname)
conf.Servers[srv1.Host].Host = ""
c.Check(conf.IsValid(), Equals, false)
c.Check(len(conf.Errors), Equals, 1) // Internal No host
c.Check(conf.Errors[0].Error(), Matches, reqErr(errHost))
}
func (s *s) TestConfig_ValidationDuplicateName(c *C) {
conf := CreateConfig().
Nick(srv1.Nick).
Realname(srv1.Realname).
Username(srv1.Username).
Userhost(srv1.Userhost).
Server("a.com").
Server("a.com")
c.Check(len(conf.Servers), Equals, 1)
c.Check(conf.IsValid(), Equals, false)
c.Check(len(conf.Errors), Equals, 1)
c.Check(conf.Errors[0].Error(), Equals, errMsgDuplicateServer)
}
func (s *s) TestConfig_ValidationMissing(c *C) {
conf := CreateConfig().
Server(srv1.Host)
c.Check(conf.IsValid(), Equals, false)
// Missing: Nick, Username, Userhost, Realname
c.Check(len(conf.Errors), Equals, 4)
c.Check(conf.Errors[0].Error(), Matches, reqErr(errNick))
c.Check(conf.Errors[1].Error(), Matches, reqErr(errUsername))
c.Check(conf.Errors[2].Error(), Matches, reqErr(errUserhost))
c.Check(conf.Errors[3].Error(), Matches, reqErr(errRealname))
}
func (s *s) TestConfig_ValidationRegex(c *C) {
conf := CreateConfig().
Server(srv1.Host).
Nick(`@Nick`). // no special chars
Channels(`chan`). // must start with valid prefix
Username(`spaces in here`). // no spaces
Userhost(`~#@#$@!`). // must be a host
Realname(`@ !`) // no special chars
c.Check(conf.IsValid(), Equals, false)
c.Check(len(conf.Errors), Equals, 5)
c.Check(conf.Errors[0].Error(), Matches, invErr(errNick))
c.Check(conf.Errors[1].Error(), Matches, invErr(errUsername))
c.Check(conf.Errors[2].Error(), Matches, invErr(errUserhost))
c.Check(conf.Errors[3].Error(), Matches, invErr(errRealname))
c.Check(conf.Errors[4].Error(), Matches, invErr(errChannel))
}
func (s *s) TestConfig_DisplayErrors(c *C) {
buf := &bytes.Buffer{}
log.SetOutput(buf)
c.Check(buf.Len(), Equals, 0)
conf := CreateConfig().
Server("localhost")
c.Check(conf.IsValid(), Equals, false)
c.Check(len(conf.Errors), Equals, 4)
conf.DisplayErrors()
c.Check(buf.Len(), Not(Equals), 0)
setLogger() // Reset the logger
}
func (s *s) TestConfig_GetServer(c *C) {
conf := CreateConfig()
conf.Servers[srv1.GetName()] = srv1
conf.Servers[srv2.GetName()] = srv2
c.Check(conf.GetServer(srv1.GetName()), Equals, srv1)
c.Check(conf.GetServer(srv2.GetName()), Equals, srv2)
}
func (s *s) TestConfig_RemoveServer(c *C) {
conf := CreateConfig()
conf.Servers[srv1.GetName()] = srv1
conf.Servers[srv2.GetName()] = srv2
c.Check(conf.GetServer(srv1.GetName()), Equals, srv1)
c.Check(conf.GetServer(srv2.GetName()), Equals, srv2)
conf.ServerContext(srv1.GetName())
c.Check(conf.context, NotNil)
conf.RemoveServer(srv1.GetName())
c.Check(conf.IsValid(), Equals, true)
c.Check(conf.context, IsNil)
c.Check(conf.GetServer(srv1.GetName()), IsNil)
c.Check(conf.GetServer(srv2.GetName()), Equals, srv2)
}
func (s *s) TestConfig_SetContext(c *C) {
conf := CreateConfig()
srv := *srv1
conf.Servers[srv1.GetName()] = &srv
var p1, p2, p3 uint16 = 1, 2, 3
conf.Port(p1) // Should set global context
c.Check(conf.Global.GetPort(), Equals, p1)
conf.ServerContext(srv1.GetName())
conf.Port(p2)
conf.GlobalContext()
conf.Port(p3)
c.Check(conf.GetServer(srv1.GetName()).GetPort(), Equals, p2)
c.Check(conf.Global.GetPort(), Equals, p3)
c.Check(len(conf.Errors), Equals, 0)
conf.ServerContext("")
c.Check(len(conf.Errors), Equals, 1)
c.Check(conf.IsValid(), Equals, false)
c.Check(conf.Errors[0].Error(), Matches, fmtErrServerNotFound[:33]+".*")
}
func (s *s) TestValidNames(c *C) {
goodNicks := []string{`a1bc`, `a5bc`, `a9bc`, `MyNick`, `[MyNick`,
`My[Nick`, `]MyNick`, `My]Nick`, `\MyNick`, `My\Nick`, "MyNick",
"My`Nick", `_MyNick`, `My_Nick`, `^MyNick`, `My^Nick`, `{MyNick`,
`My{Nick`, `|MyNick`, `My|Nick`, `}MyNick`, `My}Nick`,
}
badNicks := []string{`My Name`, `My!Nick`, `My"Nick`, `My#Nick`, `My$Nick`,
`My%Nick`, `My&Nick`, `My'Nick`, `My/Nick`, `My(Nick`, `My)Nick`,
`My*Nick`, `My+Nick`, `My,Nick`, `My-Nick`, `My.Nick`, `My/Nick`,
`My;Nick`, `My:Nick`, `My<Nick`, `My=Nick`, `My>Nick`, `My?Nick`,
`My@Nick`, `1abc`, `5abc`, `9abc`, `@ChanServ`,
}
for i := 0; i < len(goodNicks); i++ {
if !rgxNickname.MatchString(goodNicks[i]) {
c.Errorf("Good nick failed regex: %v\n", goodNicks[i])
}
}
for i := 0; i < len(badNicks); i++ {
if rgxNickname.MatchString(badNicks[i]) {
c.Errorf("Bad nick passed regex: %v\n", badNicks[i])
}
}
}
func (s *s) TestConfig_Clone(c *C) {
conf := CreateConfig()
srv := *srv1
srv.parent = conf
name := srv1.Name
filename := "file.yaml"
conf.filename = filename
conf.Servers[name] = &srv
var globalPort, serverPort uint16 = 1, 2
newconf := conf.Clone().
GlobalContext().
Port(globalPort).
ServerContext(name).
Port(0)
c.Check(newconf.GetFilename(), Equals, conf.GetFilename())
newconf.GlobalContext()
c.Check(conf.Global.Port, Not(Equals), globalPort)
c.Check(srv1.Port, Not(Equals), globalPort)
c.Check(newconf.GetServer(name).GetPort(), Equals, globalPort)
newconf.
ServerContext(srv1.Name).
Port(serverPort)
c.Check(conf.Global.Port, Not(Equals), serverPort)
c.Check(srv1.Port, Not(Equals), serverPort)
c.Check(newconf.GetServer(name).GetPort(), Equals, serverPort)
}
func (s *s) TestConfig_Filename(c *C) {
conf := CreateConfig()
filename := "file.yaml"
c.Check(conf.GetFilename(), Equals, defaultConfigFileName)
conf.filename = filename
c.Check(conf.GetFilename(), Equals, filename)
}
func (s *s) TestValidChannels(c *C) {
// Check that the first letter must be {#+!&}
goodChannels := []string{"#ValidChannel", "+ValidChannel", "&ValidChannel",
"!12345", "#c++"}
badChannels := []string{"#Invalid Channel", "#Invalid,Channel",
"#Invalid\aChannel", "#", "+", "&", "InvalidChannel"}
for i := 0; i < len(goodChannels); i++ {
if !rgxChannel.MatchString(goodChannels[i]) {
c.Errorf("Good chan failed regex: %v\n", goodChannels[i])
}
}
for i := 0; i < len(badChannels); i++ {
if rgxChannel.MatchString(badChannels[i]) {
c.Errorf("Bad chan passed regex: %v\n", badChannels[i])
}
}
}
<file_sep>/data/data.go
/*
data package is used to turn irc.IrcMessages into a stateful database.
*/
package data
import (
"github.com/aarondl/ultimateq/irc"
"strings"
)
// Self is the bot's user, he's a special case since he has to hold a Modeset.
type Self struct {
*User
*ChannelModes
}
// Store is the main data container. It represents the state on a server
// including all channels, users, and self.
type Store struct {
Self Self
channels map[string]*Channel
users map[string]*User
channelUsers map[string]map[string]*ChannelUser
userChannels map[string]map[string]*UserChannel
selfkinds *ChannelModeKinds
kinds *ChannelModeKinds
umodes *UserModeKinds
cfinder *irc.ChannelFinder
}
// CreateStore creates a store from an irc protocaps instance.
func CreateStore(caps *irc.ProtoCaps) (*Store, error) {
store := &Store{}
err := store.Protocaps(caps)
if err != nil {
return nil, err
}
store.Self.ChannelModes = CreateChannelModes(store.selfkinds)
store.channels = make(map[string]*Channel)
store.users = make(map[string]*User)
store.channelUsers = make(map[string]map[string]*ChannelUser)
store.userChannels = make(map[string]map[string]*UserChannel)
return store, nil
}
// Protocaps updates the protocaps of the store.
func (s *Store) Protocaps(caps *irc.ProtoCaps) error {
selfkinds := CreateChannelModeKinds("", "", "", caps.Usermodes())
kinds, err := CreateChannelModeKindsCSV(caps.Chanmodes())
if err != nil {
return err
}
modes, err := CreateUserModeKinds(caps.Prefix())
if err != nil {
return err
}
cfinder, err := irc.CreateChannelFinder(caps.Chantypes())
if err != nil {
return err
}
s.selfkinds = selfkinds
s.kinds = kinds
s.umodes = modes
s.cfinder = cfinder
return nil
}
// GetUser returns the user if he exists.
func (s *Store) GetUser(nickorhost string) *User {
nick := strings.ToLower(irc.Mask(nickorhost).GetNick())
return s.users[nick]
}
// GetChannel returns the channel if it exists.
func (s *Store) GetChannel(channel string) *Channel {
return s.channels[strings.ToLower(channel)]
}
// GetUserByChannel fetches a user based
func (s *Store) GetUsersChannelModes(nickorhost, channel string) *UserModes {
nick := strings.ToLower(irc.Mask(nickorhost).GetNick())
channel = strings.ToLower(channel)
if nicks, ok := s.channelUsers[channel]; ok {
if cu, ok := nicks[nick]; ok {
return cu.UserModes
}
}
return nil
}
// GetNUsers returns the number of users in the database.
func (s *Store) GetNUsers() int {
return len(s.users)
}
// GetNChannels returns the number of channels in the database.
func (s *Store) GetNChannels() int {
return len(s.channels)
}
// GetNUserChans returns the number of channels for a user in the database.
func (s *Store) GetNUserChans(nickorhost string) (n int) {
nick := strings.ToLower(irc.Mask(nickorhost).GetNick())
if ucs, ok := s.userChannels[nick]; ok {
n = len(ucs)
}
return
}
// GetNChanUsers returns the number of users for a channel in the database.
func (s *Store) GetNChanUsers(channel string) (n int) {
channel = strings.ToLower(channel)
if cus, ok := s.channelUsers[channel]; ok {
n = len(cus)
}
return
}
// EachUser iterates through the users.
func (s *Store) EachUser(fn func(*User)) {
for _, u := range s.users {
fn(u)
}
}
// EachChannel iterates through the channels.
func (s *Store) EachChannel(fn func(*Channel)) {
for _, c := range s.channels {
fn(c)
}
}
// EachUserChan iterates through the channels a user is on.
func (s *Store) EachUserChan(nickorhost string, fn func(*UserChannel)) {
nick := strings.ToLower(irc.Mask(nickorhost).GetNick())
if ucs, ok := s.userChannels[nick]; ok {
for _, uc := range ucs {
fn(uc)
}
}
return
}
// EachChanUser iterates through the users on a channel.
func (s *Store) EachChanUser(channel string, fn func(*ChannelUser)) {
channel = strings.ToLower(channel)
if cus, ok := s.channelUsers[channel]; ok {
for _, cu := range cus {
fn(cu)
}
}
return
}
// GetUser returns a string array of all the users.
func (s *Store) GetUsers() []string {
ret := make([]string, 0, len(s.users))
for _, u := range s.users {
ret = append(ret, u.GetFullhost())
}
return ret
}
// GetChannels returns a string array of all the channels.
func (s *Store) GetChannels() []string {
ret := make([]string, 0, len(s.channels))
for _, c := range s.channels {
ret = append(ret, c.GetName())
}
return ret
}
// GetUserChans returns a string array of the channels a user is on.
func (s *Store) GetUserChans(nickorhost string) []string {
nick := strings.ToLower(irc.Mask(nickorhost).GetNick())
if ucs, ok := s.userChannels[nick]; ok {
ret := make([]string, 0, len(ucs))
for _, uc := range ucs {
ret = append(ret, uc.Channel.GetName())
}
return ret
}
return nil
}
// GetChanUsers returns a string array of the users on a channel.
func (s *Store) GetChanUsers(channel string) []string {
channel = strings.ToLower(channel)
if cus, ok := s.channelUsers[channel]; ok {
ret := make([]string, 0, len(cus))
for _, cu := range cus {
ret = append(ret, cu.User.GetFullhost())
}
return ret
}
return nil
}
// IsOn checks if a user is on a specific channel.
func (s *Store) IsOn(nickorhost, channel string) bool {
nick := strings.ToLower(irc.Mask(nickorhost).GetNick())
channel = strings.ToLower(channel)
if chans, ok := s.userChannels[nick]; ok {
if _, ok = chans[channel]; ok {
return true
}
}
return false
}
// addUser adds a user to the database.
func (s *Store) addUser(nickorhost string) *User {
excl, at, per := false, false, false
for i := 0; i < len(nickorhost); i++ {
switch nickorhost[i] {
case '!':
excl = true
case '@':
at = true
case '.':
per = true
}
}
if per && !(excl && at) {
return nil
}
nick := strings.ToLower(irc.Mask(nickorhost).GetNick())
var user *User
var ok bool
if user, ok = s.users[nick]; ok {
if excl && at && user.GetFullhost() != nickorhost {
user.mask = irc.Mask(nickorhost)
}
} else {
user = CreateUser(nickorhost)
s.users[nick] = user
}
return user
}
// removeUser deletes a user from the database.
func (s *Store) removeUser(nickorhost string) {
nick := strings.ToLower(irc.Mask(nickorhost).GetNick())
for _, cus := range s.channelUsers {
delete(cus, nick)
}
delete(s.userChannels, nick)
delete(s.users, nick)
}
// addChannel adds a channel to the database.
func (s *Store) addChannel(channel string) *Channel {
chankey := strings.ToLower(channel)
var ch *Channel
if ch, ok := s.channels[chankey]; !ok {
ch = CreateChannel(channel, s.kinds)
s.channels[chankey] = ch
}
return ch
}
// removeChannel deletes a channel from the database.
func (s *Store) removeChannel(channel string) {
channel = strings.ToLower(channel)
for _, cus := range s.userChannels {
delete(cus, channel)
}
delete(s.channelUsers, channel)
delete(s.channels, channel)
}
// addToChannel adds a user by nick or fullhost to the channel
func (s *Store) addToChannel(nickorhost, channel string) {
var user *User
var ch *Channel
var cu map[string]*ChannelUser
var uc map[string]*UserChannel
var ok, cuhas, uchas bool
nick := strings.ToLower(irc.Mask(nickorhost).GetNick())
channel = strings.ToLower(channel)
if user, ok = s.users[nick]; !ok {
return
}
if ch, ok = s.channels[channel]; !ok {
return
}
if cu, ok = s.channelUsers[channel]; !ok {
cu = make(map[string]*ChannelUser, 1)
} else {
_, cuhas = s.channelUsers[channel][nick]
}
if uc, ok = s.userChannels[nick]; !ok {
uc = make(map[string]*UserChannel, 1)
} else {
_, uchas = s.userChannels[nick][channel]
}
if cuhas || uchas {
return
}
modes := CreateUserModes(s.umodes)
cu[nick] = CreateChannelUser(user, modes)
uc[channel] = CreateUserChannel(ch, modes)
s.channelUsers[channel] = cu
s.userChannels[nick] = uc
}
// removeFromChannel removes a user by nick or fullhost from the channel
func (s *Store) removeFromChannel(nickorhost, channel string) {
var cu map[string]*ChannelUser
var uc map[string]*UserChannel
var ok bool
nick := strings.ToLower(irc.Mask(nickorhost).GetNick())
channel = strings.ToLower(channel)
if cu, ok = s.channelUsers[channel]; ok {
delete(cu, nick)
}
if uc, ok = s.userChannels[nick]; ok {
delete(uc, channel)
}
}
// Update uses the irc.IrcMessage to modify the database accordingly.
func (s *Store) Update(m *irc.IrcMessage) {
s.addUser(m.Sender)
switch m.Name {
case irc.NICK:
s.nick(m)
case irc.JOIN:
s.join(m)
case irc.PART:
s.part(m)
case irc.QUIT:
s.quit(m)
case irc.KICK:
s.kick(m)
case irc.MODE:
s.mode(m)
case irc.TOPIC:
s.topic(m)
case irc.RPL_TOPIC:
s.rpl_topic(m)
case irc.PRIVMSG, irc.NOTICE:
s.msg(m)
case irc.RPL_WELCOME:
s.rpl_welcome(m)
case irc.RPL_NAMREPLY:
s.rpl_namereply(m)
case irc.RPL_WHOREPLY:
s.rpl_whoreply(m)
case irc.RPL_CHANNELMODEIS:
s.rpl_channelmodeis(m)
case irc.RPL_BANLIST:
s.rpl_banlist(m)
// TODO: Handle Whois
}
}
// nick alters the state of the database when a NICK message is received.
func (s *Store) nick(m *irc.IrcMessage) {
nick, username, host := irc.Mask(m.Sender).SplitFullhost()
newnick := m.Args[0]
newuser := irc.Mask(newnick + "!" + username + "@" + host)
nick = strings.ToLower(nick)
newnick = strings.ToLower(newnick)
var ok bool
if _, ok = s.users[nick]; !ok {
s.addUser(string(newuser))
} else {
newnicklow := strings.ToLower(newnick)
s.userChannels[newnicklow] = s.userChannels[nick]
delete(s.userChannels, nick)
s.users[newnicklow] = s.users[nick]
delete(s.users, nick)
}
}
// join alters the state of the database when a JOIN message is received.
func (s *Store) join(m *irc.IrcMessage) {
if m.Sender == s.Self.GetFullhost() {
s.addChannel(m.Args[0])
}
s.addToChannel(m.Sender, m.Args[0])
}
// part alters the state of the database when a PART message is received.
func (s *Store) part(m *irc.IrcMessage) {
if m.Sender == s.Self.GetFullhost() {
s.removeChannel(m.Args[0])
} else {
s.removeFromChannel(m.Sender, m.Args[0])
}
}
// quit alters the state of the database when a QUIT message is received.
func (s *Store) quit(m *irc.IrcMessage) {
if m.Sender != s.Self.GetFullhost() {
s.removeUser(m.Sender)
}
}
// kick alters the state of the database when a KICK message is received.
func (s *Store) kick(m *irc.IrcMessage) {
if m.Args[1] == s.Self.GetNick() {
s.removeChannel(m.Args[0])
} else {
s.removeFromChannel(m.Args[1], m.Args[0])
}
}
// mode alters the state of the database when a MODE message is received.
func (s *Store) mode(m *irc.IrcMessage) {
target := strings.ToLower(m.Args[0])
if s.cfinder.IsChannel(target) {
if ch, ok := s.channels[target]; ok {
pos, neg := ch.Apply(strings.Join(m.Args[1:], " "))
for i := 0; i < len(pos); i++ {
nick := strings.ToLower(pos[i].Arg)
s.channelUsers[target][nick].SetMode(pos[i].Mode)
}
for i := 0; i < len(neg); i++ {
nick := strings.ToLower(neg[i].Arg)
s.channelUsers[target][nick].UnsetMode(neg[i].Mode)
}
}
} else if target == s.Self.GetNick() {
s.Self.Apply(m.Args[1])
}
}
// topic alters the state of the database when a TOPIC message is received.
func (s *Store) topic(m *irc.IrcMessage) {
chname := strings.ToLower(m.Args[0])
if ch, ok := s.channels[chname]; ok {
ch.Topic(m.Args[1])
}
}
// rpl_topic alters the state of the database when a RPL_TOPIC message is
// received.
func (s *Store) rpl_topic(m *irc.IrcMessage) {
chname := strings.ToLower(m.Args[1])
if ch, ok := s.channels[chname]; ok {
ch.Topic(m.Args[2])
}
}
// msg alters the state of the database when a PRIVMSG or NOTICE message is
// received.
func (s *Store) msg(m *irc.IrcMessage) {
if s.cfinder.IsChannel(m.Args[0]) {
s.addToChannel(m.Sender, m.Args[0])
}
}
// rpl_welcome alters the state of the database when a RPL_WELCOME message is
// received.
func (s *Store) rpl_welcome(m *irc.IrcMessage) {
splits := strings.Fields(m.Args[1])
host := splits[len(splits)-1]
if !strings.ContainsRune(host, '!') || !strings.ContainsRune(host, '@') {
host = m.Args[0]
}
user := CreateUser(host)
s.Self.User = user
s.users[user.GetNick()] = user
}
// rpl_namereply alters the state of the database when a RPL_NAMEREPLY
// message is received.
func (s *Store) rpl_namereply(m *irc.IrcMessage) {
channel := m.Args[2]
users := strings.Fields(m.Args[3])
for i := 0; i < len(users); i++ {
j := 0
mode := rune(0)
for ; j < len(s.umodes.modeInfo); j++ {
if s.umodes.modeInfo[j][1] == rune(users[i][0]) {
mode = s.umodes.modeInfo[j][0]
break
}
}
if j < len(s.umodes.modeInfo) {
nick := users[i][1:]
s.addUser(nick)
s.addToChannel(nick, channel)
s.GetUsersChannelModes(nick, channel).SetMode(mode)
} else {
s.addUser(users[i])
s.addToChannel(users[i], channel)
}
}
}
// rpl_whoreply alters the state of the database when a RPL_WHOREPLY message
// is received.
func (s *Store) rpl_whoreply(m *irc.IrcMessage) {
channel := m.Args[1]
fullhost := m.Args[5] + "!" + m.Args[2] + "@" + m.Args[3]
modes := m.Args[6]
realname := strings.SplitN(m.Args[7], " ", 2)[1]
s.addUser(fullhost)
s.addToChannel(fullhost, channel)
s.GetUser(fullhost).Realname(realname)
for _, modechar := range modes {
if mode := s.umodes.GetMode(modechar); mode != 0 {
s.GetUsersChannelModes(fullhost, channel).SetMode(mode)
}
}
}
// rpl_channelmodeis alters the state of the database when a RPL_CHANNELMODEIS
// message is received.
func (s *Store) rpl_channelmodeis(m *irc.IrcMessage) {
channel := m.Args[1]
modes := strings.Join(m.Args[2:], " ")
s.GetChannel(channel).Apply(modes)
}
// rpl_banlist alters the state of the database when a RPL_BANLIST message is
// received.
func (s *Store) rpl_banlist(m *irc.IrcMessage) {
channel := m.Args[1]
s.GetChannel(channel).AddBan(m.Args[2])
}
<file_sep>/placeholder.go
// The ultimateq bot framework.
package main
import (
"bytes"
"github.com/aarondl/ultimateq/bot"
"github.com/aarondl/ultimateq/config"
"github.com/aarondl/ultimateq/irc"
"log"
"math/rand"
"os"
"strings"
"sync"
"time"
)
type Handler struct {
}
func (h Handler) PrivmsgUser(m *irc.Message, endpoint irc.Endpoint) {
if strings.Split(m.Sender, "!")[0] == "Aaron" {
endpoint.Send(m.Message())
}
}
func (h Handler) PrivmsgChannel(m *irc.Message, endpoint irc.Endpoint) {
if m.Message() == "hello" {
endpoint.Privmsg(m.Target(), "Hello to you too!")
} else {
lock.Lock()
chain.Build(
bytes.NewBuffer(
[]byte(m.Message()),
),
)
endpoint.Privmsg(m.Target(), chain.Generate(100))
lock.Unlock()
}
}
func conf(c *config.Config) *config.Config {
c. // Defaults
Nick("nobody__").
Altnick("nobody_").
Realname("there").
Username("guy").
Userhost("friend").
NoReconnect(true)
c. // First server
Server("irc.gamesurge.net1").
Host("localhost").
Nick("Aaron").
Altnick("nobody1").
ReconnectTimeout(5)
c. // Second Server
Server("irc.gamesurge.net2").
Host("localhost").
Nick("nobody2")
return c
}
var chain = NewChain(2)
var lock = sync.Mutex{}
func main() {
rand.Seed(time.Now().UnixNano()) // Seed the random number generator.
log.SetOutput(os.Stdout)
b, err := bot.CreateBot(bot.ConfigureFunction(conf))
if err != nil {
log.Println(err)
}
b.Register(irc.PRIVMSG, Handler{})
ers := b.Connect()
if len(ers) != 0 {
log.Println(ers)
return
}
b.Start()
<-time.After(20 * time.Second)
c := conf(config.CreateConfig())
c.RemoveServer("irc.gamesurge.net1")
c.GlobalContext().
Channels("#test").
Server("irc.gamesurge.net3").
Host("localhost").
Nick("super").
ServerContext("irc.gamesurge.net2").
Nick("heythere").
Channels("#hithere")
if !c.IsValid() {
c.DisplayErrors()
log.Fatal("Config error")
}
//b.ReplaceConfig(c)
b.WaitForHalt()
b.Stop()
b.Disconnect()
<-time.After(10 * time.Second)
}
<file_sep>/inet/client.go
/*
inet package handles connecting to an irc server and reading and writing to
the connection
*/
package inet
import (
"bytes"
"io"
"log"
"net"
"sync"
"time"
)
const (
// bufferSize is the size of the buffer to be allocated for writes
bufferSize = 16348
// nBufferedWrites is how many writes can succeed before blocking
nBufferedWrites = 25
// defaultTimeScale is the default scale of the sleeps and timeouts.
defaultTimeScale = time.Second
)
var (
// pong allows replies from pong to write directly without waiting on sleeps
pong = []byte("PONG")
// logger to use, can be set to customize logging for this package
Log = func(format string, args ...interface{}) {
log.Printf(format, args...)
}
)
// Format strings for errors and logging output
const (
fmtDiscarded = "(%v) <- (DISCARDED) %s\n"
fmtWrite = "(%v) <- %s\n"
fmtWriteErr = "(%v) <- (%v) %s\n"
fmtRead = "(%v) -> %s\n"
fmtErrSiphonReadError = "inet: (%v) read socket error (%s)\n"
fmtErrPumpReadError = "inet: (%v) write socket error (%s)\n"
fmtErrSiphonClosed = "inet: (%v) siphon closed (%s)\n"
fmtErrPumpClosed = "inet: (%v) pump closed (%s)\n"
errMsgShutdown = "Shut Down"
)
// IrcClient represents a connection to an irc server. It uses a queueing system
// to throttle writes to the server. And it implements ReadWriteCloser interface
type IrcClient struct {
isShutdown bool
isShutdownProtect sync.RWMutex
conn net.Conn
siphonchan chan []byte
pumpchan chan []byte
pumpservice chan chan []byte
killpump chan int
killsiphon chan int
queue Queue
// The name of the connection for logging
name string
// write throttling
nThrottled int
lastwrite time.Time
scale time.Duration
burst int
timeout time.Duration
step time.Duration
// buffering for io.Reader interface
readbuf []byte
pos int
}
// CreateIrcClient initializes the required fields in the IrcClient
func CreateIrcClient(conn net.Conn, name string) *IrcClient {
return &IrcClient{
name: name,
conn: conn,
siphonchan: make(chan []byte),
pumpchan: make(chan []byte),
pumpservice: make(chan chan []byte),
lastwrite: time.Time{},
scale: defaultTimeScale,
}
}
// CreateIrcClientFloodProtect creates an irc client and sets up the variables
// required for flood protection. The timeout and step variables are in seconds.
func CreateIrcClientFloodProtect(conn net.Conn, name string, burst, timeout,
step int, scale time.Duration) *IrcClient {
c := CreateIrcClient(conn, name)
if scale != 0 {
c.scale = scale
}
c.burst = burst
c.timeout = time.Duration(timeout) * c.scale
c.step = time.Duration(step) * c.scale
return c
}
// SpawnWorkers creates two goroutines, one that is constantly reading using
// Siphon, and one that is constantly working on eliminating the write queue by
// writing. Also sets up the instances kill channels.
func (c *IrcClient) SpawnWorkers(pump, siphon bool) {
c.isShutdownProtect.Lock()
defer c.isShutdownProtect.Unlock()
c.isShutdown = false
if pump {
c.killpump = make(chan int)
go c.pump()
}
if siphon {
c.killsiphon = make(chan int)
go c.siphon()
}
}
// calcSleepTime calculates the sleep time required by the flood protection
// given a time of write.
func (c *IrcClient) calcSleepTime(t time.Time) time.Duration {
if c.timeout == 0 || c.step == 0 {
return 0
}
dur := t.Sub(c.lastwrite)
if dur < 0 {
dur = 0
}
if dur > c.timeout {
c.nThrottled = 1
} else {
if c.nThrottled >= c.burst {
return c.step
}
c.nThrottled++
}
return 0
}
// pump enqueues the messages given to Write and writes them to the connection.
// It also sleeps a don't-get-glined amount of time between writes.
func (c *IrcClient) pump() {
var err error
var sleeper <-chan time.Time
defer close(c.pumpservice)
for err == nil {
select {
case c.pumpservice <- c.pumpchan:
message := <-c.pumpchan
if len(message) == 0 {
break
}
if bytes.HasPrefix(message, pong) {
if err = c.writeMessage(message); err != nil {
break
}
} else if sleeper == nil {
sleepTime := c.calcSleepTime(time.Now())
if sleepTime == 0 {
if err = c.writeMessage(message); err != nil {
break
}
} else {
c.queue.Enqueue(message)
sleeper = time.After(sleepTime)
}
} else {
c.queue.Enqueue(message)
}
case <-sleeper:
if err = c.writeMessage(c.queue.Dequeue()); err != nil {
break
}
if c.queue.length > 0 {
sleepTime := c.calcSleepTime(time.Now())
sleeper = time.After(sleepTime)
} else {
sleeper = nil
}
case <-c.killpump:
Log(fmtErrPumpClosed, c.name, errMsgShutdown)
return
}
}
<-c.killpump
}
// writeMessage writes a byte array out to the socket, sets the last write time.
func (c *IrcClient) writeMessage(msg []byte) error {
var n int
var err error
for written := 0; written < len(msg); written += n {
n, err = c.conn.Write(msg[written:])
wrote := msg[written : len(msg)-2]
if err != nil {
Log(fmtWriteErr, c.name, err, wrote)
return err
}
Log(fmtWrite, c.name, wrote)
c.lastwrite = time.Now()
}
return nil
}
// Siphon takes messages from the connection given to the IrcClient and then
// uses extractMessages to send them to the readchan.
func (c *IrcClient) siphon() {
buf := make([]byte, bufferSize)
var err error = nil
var shutdown bool
var position, n = 0, 0
for err == nil {
n, err = c.conn.Read(buf[position:])
if n > 0 && (err == nil || err == io.EOF) {
position, shutdown = c.extractMessages(buf[:n+position])
if shutdown {
return
}
}
if err != nil {
Log(fmtErrSiphonReadError, c.name, err)
break
}
}
close(c.siphonchan)
<-c.killsiphon
}
// extractMessages takes the information in a buffer and splits on \r\n pairs.
// When it encounters a pair, it creates a copy of the data from start to the
// pair and passes it into the readchan from the IrcClient. If no \r\n is found
// but data is still present in the buffer, it moves this data to the front of
// the buffer and returns an index from which the next read should be started at
//
// Note:
// the reason for the copy is because of the threadedness, the buffer pointed to
// by the slice can be immediately filled with new information once this
// function returns and therefore a copy must be made for thread safety.
func (c *IrcClient) extractMessages(buf []byte) (int, bool) {
send := func(chunk []byte) bool {
cpy := make([]byte, len(chunk)-2)
copy(cpy, chunk[:len(chunk)-2])
select {
case c.siphonchan <- cpy:
Log(fmtRead, c.name, cpy)
return false
case <-c.killsiphon:
return true
}
}
start, remaining, abort := findChunks(buf, send)
if abort {
return 0, true
} else if remaining {
copy(buf[:len(buf)-start], buf[start:])
return len(buf) - start, false
}
return 0, false
}
// Close closes the socket, sets an all-consuming dequeuer routine to
// eat all the waiting-to-write goroutines, and then waits to acquire a mutex
// that will allow it to safely close the writer channel and set a shutdown var.
func (c *IrcClient) Close() error {
if c.IsClosed() {
return nil
}
err := c.conn.Close()
c.isShutdownProtect.Lock()
c.isShutdown = true
if c.killpump != nil {
c.killpump <- 0
}
if c.killsiphon != nil {
c.killsiphon <- 0
}
c.isShutdownProtect.Unlock()
return err
}
// IsClosed returns true if the IrcClient has been closed.
func (c *IrcClient) IsClosed() bool {
c.isShutdownProtect.RLock()
defer c.isShutdownProtect.RUnlock()
return c.isShutdown
}
// Reads a message from the read channel in it's entirety. More efficient than
// read because read requires you to allocate your own buffer, but since we're
// dealing in routines and splitting the buffer the reality is another buffer
// has been already allocated to copy the bytes recieved anyways.
func (c *IrcClient) ReadMessage() ([]byte, bool) {
ret, ok := <-c.siphonchan
if !ok {
return nil, ok
}
return ret, ok
}
// Retrieves the channel that's used to read.
func (c *IrcClient) ReadChannel() <-chan []byte {
return c.siphonchan
}
// Read implements the io.Reader interface, but this method is just here for
// convenience. It is not efficient and should probably not even be used.
// Instead use ReadMessage as it it has already allocated a buffer and copied
// the contents into it. Using this method requires an extra buffer allocation
// and extra copying.
func (c *IrcClient) Read(buf []byte) (int, error) {
if c.pos == 0 {
var ok bool
c.readbuf, ok = c.ReadMessage()
if !ok {
return 0, io.EOF
}
}
n := copy(buf, c.readbuf[c.pos:])
c.pos += n
if c.pos == len(c.readbuf) {
c.readbuf = nil
c.pos = 0
}
return n, nil
}
// Write implements the io.Writer interface and is the preferred way to write
// to the socket. Returns EOF if the client has been closed. The buffer
// is split based on \r\n and each message is queued, then the Pump is signaled
// through the channel with the number of messages queued. A read lock on a
// mutex is required to write to the channel to ensure any other thread
// cannot close the channel while someone is attempting to write to it.
func (c *IrcClient) Write(buf []byte) (int, error) {
n := len(buf)
if n == 0 {
return 0, nil
}
write := func(msg []byte) bool {
copybuf := make([]byte, len(msg))
copy(copybuf, msg)
service, ok := <-c.pumpservice
if !ok {
return true
}
service <- copybuf
return false
}
start, remaining, abort := findChunks(buf, write)
if abort {
return 0, io.EOF
} else if remaining {
if write(append(buf[start:], []byte{'\r', '\n'}...)) {
return start, io.EOF
}
}
return n, nil
}
// findChunks calls a callback for each \r\n encountered.
// if there is still a remaining chunk to be dealt with that did not end with
// \r\n the bool return value will be true.
func findChunks(buf []byte, block func([]byte) bool) (int, bool, bool) {
var start, i int
for start, i = 0, 1; i < len(buf); i++ {
if buf[i-1] == '\r' && buf[i] == '\n' {
i++
if block(buf[start:i]) {
return start, false, true
}
if i == len(buf) {
return start, false, false
}
start = i
}
}
return start, true, false
}
<file_sep>/dispatch/dispatch_test.go
package dispatch
import (
"github.com/aarondl/ultimateq/irc"
. "launchpad.net/gocheck"
"testing"
)
func Test(t *testing.T) { TestingT(t) } //Hook into testing package
type s struct{}
var _ = Suite(&s{})
//===========================================================
// Set up a type that can be used to mock irc.Endpoint
//===========================================================
type testPoint struct {
*irc.Helper
}
func (tsender testPoint) GetKey() string {
return ""
}
//===========================================================
// Set up a type that can be used to mock a callback for raw.
//===========================================================
type testCallback func(msg *irc.IrcMessage, ep irc.Endpoint)
type testHandler struct {
callback testCallback
}
func (handler testHandler) HandleRaw(msg *irc.IrcMessage, ep irc.Endpoint) {
if handler.callback != nil {
handler.callback(msg, ep)
}
}
//===========================================================
// Tests
//===========================================================
func (s *s) TestDispatcher(c *C) {
d := CreateDispatcher()
c.Check(d, NotNil)
c.Check(d.events, NotNil)
d, err := CreateRichDispatcher(nil, nil)
c.Check(err, Equals, errProtoCapsMissing)
p := irc.CreateProtoCaps()
p.ParseISupport(&irc.IrcMessage{Args: []string{"nick", "CHANTYPES=H"}})
d, err = CreateRichDispatcher(p, nil)
c.Check(err, NotNil)
}
func (s *s) TestDispatcher_Registration(c *C) {
d := CreateDispatcher()
cb := testHandler{}
id := d.Register(irc.PRIVMSG, cb)
c.Check(id, Not(Equals), 0)
id2 := d.Register(irc.PRIVMSG, cb)
c.Check(id2, Not(Equals), id)
ok := d.Unregister("privmsg", id)
c.Check(ok, Equals, true)
ok = d.Unregister("privmsg", id)
c.Check(ok, Equals, false)
}
func (s *s) TestDispatcher_Dispatching(c *C) {
var msg1, msg2, msg3 *irc.IrcMessage
var s1, s2, s3 irc.Endpoint
h1 := testHandler{func(m *irc.IrcMessage, s irc.Endpoint) {
msg1 = m
s1 = s
}}
h2 := testHandler{func(m *irc.IrcMessage, s irc.Endpoint) {
msg2 = m
s2 = s
}}
h3 := testHandler{func(m *irc.IrcMessage, s irc.Endpoint) {
msg3 = m
s3 = s
}}
d := CreateDispatcher()
send := testPoint{&irc.Helper{}}
d.Register(irc.PRIVMSG, h1)
d.Register(irc.PRIVMSG, h2)
d.Register(irc.QUIT, h3)
privmsg := &irc.IrcMessage{Name: irc.PRIVMSG}
quitmsg := &irc.IrcMessage{Name: irc.QUIT}
d.Dispatch(privmsg, send)
d.WaitForCompletion()
c.Check(msg1.Name, Equals, irc.PRIVMSG)
c.Check(msg1, Equals, msg2)
c.Check(s1, NotNil)
c.Check(s1, Equals, s2)
c.Check(msg3, IsNil)
d.Dispatch(quitmsg, send)
d.WaitForCompletion()
c.Check(msg3.Name, Equals, irc.QUIT)
}
func (s *s) TestDispatcher_RawDispatch(c *C) {
var msg1, msg2 *irc.IrcMessage
h1 := testHandler{func(m *irc.IrcMessage, send irc.Endpoint) {
msg1 = m
}}
h2 := testHandler{func(m *irc.IrcMessage, send irc.Endpoint) {
msg2 = m
}}
d := CreateDispatcher()
send := testPoint{&irc.Helper{}}
d.Register(irc.PRIVMSG, h1)
d.Register(irc.RAW, h2)
privmsg := &irc.IrcMessage{Name: irc.PRIVMSG}
d.Dispatch(privmsg, send)
d.WaitForCompletion()
c.Check(msg1, Equals, privmsg)
c.Check(msg1, Equals, msg2)
}
// ================================
// Testing types
// ================================
type testCallbackMsg func(*irc.Message, irc.Endpoint)
type testPrivmsgHandler struct {
callback testCallbackMsg
}
type testPrivmsgUserHandler struct {
callback testCallbackMsg
}
type testPrivmsgChannelHandler struct {
callback testCallbackMsg
}
type testPrivmsgAllHandler struct {
testCallbackNormal, testCallbackUser, testCallbackChannel testCallbackMsg
}
type testNoticeHandler struct {
callback testCallbackMsg
}
type testNoticeUserHandler struct {
callback testCallbackMsg
}
type testNoticeChannelHandler struct {
callback testCallbackMsg
}
type testNoticeAllHandler struct {
testCallbackNormal, testCallbackUser, testCallbackChannel testCallbackMsg
}
// ================================
// Testing Callbacks
// ================================
func (t testPrivmsgHandler) Privmsg(msg *irc.Message, ep irc.Endpoint) {
t.callback(msg, ep)
}
func (t testPrivmsgUserHandler) PrivmsgUser(
msg *irc.Message, ep irc.Endpoint) {
t.callback(msg, ep)
}
func (t testPrivmsgChannelHandler) PrivmsgChannel(
msg *irc.Message, ep irc.Endpoint) {
t.callback(msg, ep)
}
func (t testPrivmsgAllHandler) Privmsg(
msg *irc.Message, ep irc.Endpoint) {
t.testCallbackNormal(msg, ep)
}
func (t testPrivmsgAllHandler) PrivmsgUser(
msg *irc.Message, ep irc.Endpoint) {
t.testCallbackUser(msg, ep)
}
func (t testPrivmsgAllHandler) PrivmsgChannel(
msg *irc.Message, ep irc.Endpoint) {
t.testCallbackChannel(msg, ep)
}
func (t testNoticeHandler) Notice(msg *irc.Message, ep irc.Endpoint) {
t.callback(msg, ep)
}
func (t testNoticeUserHandler) NoticeUser(
msg *irc.Message, ep irc.Endpoint) {
t.callback(msg, ep)
}
func (t testNoticeChannelHandler) NoticeChannel(
msg *irc.Message, ep irc.Endpoint) {
t.callback(msg, ep)
}
func (t testNoticeAllHandler) Notice(
msg *irc.Message, ep irc.Endpoint) {
t.testCallbackNormal(msg, ep)
}
func (t testNoticeAllHandler) NoticeUser(
msg *irc.Message, ep irc.Endpoint) {
t.testCallbackUser(msg, ep)
}
func (t testNoticeAllHandler) NoticeChannel(
msg *irc.Message, ep irc.Endpoint) {
t.testCallbackChannel(msg, ep)
}
var privChanmsg = &irc.IrcMessage{
Name: irc.PRIVMSG,
Args: []string{"#chan", "msg"},
Sender: "nick!<EMAIL>",
}
var privUsermsg = &irc.IrcMessage{
Name: irc.PRIVMSG,
Args: []string{"user", "msg"},
Sender: "nick!<EMAIL>",
}
func (s *s) TestDispatcher_Privmsg(c *C) {
var p, pu, pc *irc.Message
ph := testPrivmsgHandler{func(m *irc.Message, _ irc.Endpoint) {
p = m
}}
puh := testPrivmsgUserHandler{func(m *irc.Message, _ irc.Endpoint) {
pu = m
}}
pch := testPrivmsgChannelHandler{func(m *irc.Message, _ irc.Endpoint) {
pc = m
}}
d, err := CreateRichDispatcher(irc.CreateProtoCaps(), nil)
c.Check(err, IsNil)
d.Register(irc.PRIVMSG, ph)
d.Register(irc.PRIVMSG, puh)
d.Register(irc.PRIVMSG, pch)
d.Dispatch(privUsermsg, nil)
d.WaitForCompletion()
c.Check(p, NotNil)
c.Check(pu.IrcMessage, Equals, p.IrcMessage)
p, pu, pc = nil, nil, nil
d.Dispatch(privChanmsg, nil)
d.WaitForCompletion()
c.Check(p, NotNil)
c.Check(pc.IrcMessage, Equals, p.IrcMessage)
}
func (s *s) TestDispatcher_PrivmsgMultiple(c *C) {
var p, pu, pc *irc.Message
pall := testPrivmsgAllHandler{
func(m *irc.Message, _ irc.Endpoint) {
p = m
},
func(m *irc.Message, _ irc.Endpoint) {
pu = m
},
func(m *irc.Message, _ irc.Endpoint) {
pc = m
},
}
d, err := CreateRichDispatcher(irc.CreateProtoCaps(), nil)
c.Check(err, IsNil)
d.Register(irc.PRIVMSG, pall)
p, pu, pc = nil, nil, nil
d.Dispatch(privChanmsg, nil)
d.WaitForCompletion()
c.Check(p, IsNil)
c.Check(pu, IsNil)
c.Check(pc, NotNil)
p, pu, pc = nil, nil, nil
d.Dispatch(privUsermsg, nil)
d.WaitForCompletion()
c.Check(p, IsNil)
c.Check(pu, NotNil)
c.Check(pc, IsNil)
d = CreateDispatcher()
d.Dispatch(privChanmsg, nil)
d.Register(irc.PRIVMSG, pall)
p, pu, pc = nil, nil, nil
d.Dispatch(privUsermsg, nil)
d.WaitForCompletion()
c.Check(p, NotNil)
c.Check(pu, IsNil)
c.Check(pc, IsNil)
}
var noticeChanmsg = &irc.IrcMessage{
Name: irc.NOTICE,
Args: []string{"#chan", "msg"},
Sender: "nick!<EMAIL>",
}
var noticeUsermsg = &irc.IrcMessage{
Name: irc.NOTICE,
Args: []string{"user", "msg"},
Sender: "nick!<EMAIL>",
}
func (s *s) TestDispatcher_Notice(c *C) {
var n, nu, nc *irc.Message
nh := testNoticeHandler{func(m *irc.Message, _ irc.Endpoint) {
n = m
}}
nuh := testNoticeUserHandler{func(m *irc.Message, _ irc.Endpoint) {
nu = m
}}
nch := testNoticeChannelHandler{func(m *irc.Message, _ irc.Endpoint) {
nc = m
}}
d, err := CreateRichDispatcher(irc.CreateProtoCaps(), nil)
c.Check(err, IsNil)
d.Register(irc.NOTICE, nh)
d.Register(irc.NOTICE, nuh)
d.Register(irc.NOTICE, nch)
d.Dispatch(noticeUsermsg, nil)
d.WaitForCompletion()
c.Check(n, NotNil)
c.Check(nu.IrcMessage, Equals, n.IrcMessage)
n, nu, nc = nil, nil, nil
d.Dispatch(noticeChanmsg, nil)
d.WaitForCompletion()
c.Check(n, NotNil)
c.Check(nc.IrcMessage, Equals, n.IrcMessage)
}
func (s *s) TestDispatcher_NoticeMultiple(c *C) {
var n, nu, nc *irc.Message
nall := testNoticeAllHandler{
func(m *irc.Message, _ irc.Endpoint) {
n = m
},
func(m *irc.Message, _ irc.Endpoint) {
nu = m
},
func(m *irc.Message, _ irc.Endpoint) {
nc = m
},
}
d, err := CreateRichDispatcher(irc.CreateProtoCaps(), nil)
c.Check(err, IsNil)
d.Register(irc.NOTICE, nall)
n, nu, nc = nil, nil, nil
d.Dispatch(noticeChanmsg, nil)
d.WaitForCompletion()
c.Check(n, IsNil)
c.Check(nu, IsNil)
c.Check(nc, NotNil)
n, nu, nc = nil, nil, nil
d.Dispatch(noticeUsermsg, nil)
d.WaitForCompletion()
c.Check(n, IsNil)
c.Check(nu, NotNil)
c.Check(nc, IsNil)
d = CreateDispatcher()
d.Dispatch(noticeChanmsg, nil)
d.Register(irc.NOTICE, nall)
n, nu, nc = nil, nil, nil
d.Dispatch(noticeUsermsg, nil)
d.WaitForCompletion()
c.Check(n, NotNil)
c.Check(nu, IsNil)
c.Check(nc, IsNil)
}
func (s *s) TestDispatcher_Sender(c *C) {
d := CreateDispatcher()
send := testPoint{&irc.Helper{}}
msg := &irc.IrcMessage{
Name: irc.PRIVMSG,
Args: []string{"#chan", "msg"},
Sender: "nick!<EMAIL>",
}
d.Register(irc.PRIVMSG, func(msg *irc.IrcMessage, point irc.Endpoint) {
c.Check(point.GetKey(), NotNil)
c.Check(point.Sendln(""), IsNil)
})
d.Dispatch(msg, send)
}
func (s *s) TestDispatcher_FilterPrivmsgChannels(c *C) {
chanmsg2 := &irc.IrcMessage{
Name: irc.PRIVMSG,
Args: []string{"#chan2", "msg"},
Sender: "nick!<EMAIL>",
}
var p, pc *irc.Message
ph := testPrivmsgHandler{func(m *irc.Message, _ irc.Endpoint) {
p = m
}}
pch := testPrivmsgChannelHandler{func(m *irc.Message, _ irc.Endpoint) {
pc = m
}}
d, err := CreateRichDispatcher(
irc.CreateProtoCaps(), []string{"#CHAN"})
c.Check(err, IsNil)
d.Register(irc.PRIVMSG, ph)
d.Register(irc.PRIVMSG, pch)
d.Dispatch(privChanmsg, nil)
d.WaitForCompletion()
c.Check(p, NotNil)
c.Check(pc.IrcMessage, Equals, p.IrcMessage)
p, pc = nil, nil
d.Dispatch(chanmsg2, nil)
d.WaitForCompletion()
c.Check(p, NotNil)
c.Check(pc, IsNil)
}
func (s *s) TestDispatcher_FilterNoticeChannels(c *C) {
chanmsg2 := &irc.IrcMessage{
Name: irc.NOTICE,
Args: []string{"#chan2", "msg"},
Sender: "nick!<EMAIL>",
}
var u, uc *irc.Message
uh := testNoticeHandler{func(m *irc.Message, _ irc.Endpoint) {
u = m
}}
uch := testNoticeChannelHandler{func(m *irc.Message, _ irc.Endpoint) {
uc = m
}}
d, err := CreateRichDispatcher(
irc.CreateProtoCaps(), []string{"#CHAN"})
c.Check(err, IsNil)
d.Register(irc.NOTICE, uh)
d.Register(irc.NOTICE, uch)
d.Dispatch(noticeChanmsg, nil)
d.WaitForCompletion()
c.Check(u, NotNil)
c.Check(uc.IrcMessage, Equals, u.IrcMessage)
u, uc = nil, nil
d.Dispatch(chanmsg2, nil)
d.WaitForCompletion()
c.Check(u, NotNil)
c.Check(uc, IsNil)
}
func (s *s) TestDispatcher_AddRemoveChannels(c *C) {
chans := []string{"#chan1", "#chan2", "#chan3"}
d, err := CreateRichDispatcher(irc.CreateProtoCaps(), chans)
c.Check(err, IsNil)
c.Check(len(d.chans), Equals, len(chans))
for i, v := range chans {
c.Check(d.chans[i], Equals, v)
}
d.RemoveChannels(chans...)
c.Check(d.chans, IsNil)
d.RemoveChannels(chans...)
c.Check(d.chans, IsNil)
d.RemoveChannels()
c.Check(d.chans, IsNil)
d.Channels(chans)
d.RemoveChannels(chans[1:]...)
c.Check(len(d.chans), Equals, len(chans)-2)
for i, v := range chans[:1] {
c.Check(d.chans[i], Equals, v)
}
d.AddChannels(chans[1:]...)
c.Check(len(d.chans), Equals, len(chans))
for i, v := range chans {
c.Check(d.chans[i], Equals, v)
}
d.AddChannels(chans[0])
d.AddChannels()
c.Check(len(d.chans), Equals, len(chans))
d.RemoveChannels(chans...)
d.AddChannels(chans...)
c.Check(len(d.chans), Equals, len(chans))
}
func (s *s) TestDispatcher_GetChannels(c *C) {
d, err := CreateRichDispatcher(irc.CreateProtoCaps(), nil)
c.Check(err, IsNil)
c.Check(d.GetChannels(), IsNil)
chans := []string{"#chan1", "#chan2"}
d.Channels(chans)
for i, ch := range d.GetChannels() {
c.Check(d.chans[i], Equals, ch)
}
first := d.GetChannels()
first[0] = "#chan3"
for i, ch := range d.GetChannels() {
c.Check(d.chans[i], Equals, ch)
}
}
func (s *s) TestDispatcher_UpdateChannels(c *C) {
d, err := CreateRichDispatcher(irc.CreateProtoCaps(), nil)
c.Check(err, IsNil)
chans := []string{"#chan1", "#chan2"}
d.Channels(chans)
c.Check(len(d.chans), Equals, len(chans))
for i, v := range chans {
c.Check(d.chans[i], Equals, v)
}
d.Channels([]string{})
c.Check(len(d.chans), Equals, 0)
d.Channels(chans)
c.Check(len(d.chans), Equals, len(chans))
d.Channels(nil)
c.Check(len(d.chans), Equals, 0)
}
func (s *s) TestDispatcher_UpdateProtoCaps(c *C) {
p := irc.CreateProtoCaps()
p.ParseISupport(&irc.IrcMessage{Args: []string{"nick", "CHANTYPES=#"}})
d, err := CreateRichDispatcher(p, nil)
c.Check(err, IsNil)
var should bool
should = d.shouldDispatch(true, &irc.IrcMessage{Args: []string{"#chan"}})
c.Check(should, Equals, true)
should = d.shouldDispatch(true, &irc.IrcMessage{Args: []string{"&chan"}})
c.Check(should, Equals, false)
p = irc.CreateProtoCaps()
p.ParseISupport(&irc.IrcMessage{Args: []string{"nick", "CHANTYPES=&"}})
err = d.Protocaps(p)
c.Check(err, IsNil)
should = d.shouldDispatch(true, &irc.IrcMessage{Args: []string{"#chan"}})
c.Check(should, Equals, false)
should = d.shouldDispatch(true, &irc.IrcMessage{Args: []string{"&chan"}})
c.Check(should, Equals, true)
}
func (s *s) TestDispatcher_shouldDispatch(c *C) {
d, err := CreateRichDispatcher(irc.CreateProtoCaps(), nil)
c.Check(err, IsNil)
var should bool
should = d.shouldDispatch(true, &irc.IrcMessage{Args: []string{"#chan"}})
c.Check(should, Equals, true)
should = d.shouldDispatch(false, &irc.IrcMessage{Args: []string{"#chan"}})
c.Check(should, Equals, false)
should = d.shouldDispatch(true, &irc.IrcMessage{Args: []string{"chan"}})
c.Check(should, Equals, false)
should = d.shouldDispatch(false, &irc.IrcMessage{Args: []string{"chan"}})
c.Check(should, Equals, true)
}
func (s *s) TestDispatcher_filterChannelDispatch(c *C) {
d, err := CreateRichDispatcher(
irc.CreateProtoCaps(), []string{"#CHAN"})
c.Check(err, IsNil)
c.Check(d.chans, NotNil)
var should bool
should = d.checkChannels(&irc.IrcMessage{Args: []string{"#chan"}})
c.Check(should, Equals, true)
should = d.checkChannels(&irc.IrcMessage{Args: []string{"#chan2"}})
c.Check(should, Equals, false)
}
<file_sep>/irc/protocaps_test.go
package irc
import (
. "launchpad.net/gocheck"
"strings"
)
func (s *s) TestProtoCaps(c *C) {
p := CreateProtoCaps()
serverId := "irc.gamesurge.net"
s0 := "irc.test.net testircd-1.2 acCior beiIklmnoOPrR"
s1 := `NICK RFC8812 IRCD=gIRCd CASEMAPPING=scii PREFIX=(v)+ ` +
`CHANTYPES=#& CHANMODES=eI,k,l,imnOPRstz CHANLIMIT=#&+:10`
s2 := `NICK CHANNELLEN=49 NICKLEN=8 TOPICLEN=489 AWAYLEN=126 KICKLEN=399 ` +
`MODES=4 MAXLIST=beI:49 EXCEPTS=e INVEX=I PENALTY`
msg0 := &IrcMessage{
Name: RPL_MYINFO,
Args: strings.Split(s0, " "),
Sender: serverId,
}
msg1 := &IrcMessage{
Name: RPL_ISUPPORT,
Args: append(strings.Split(s1, " "), "are supported by this server"),
Sender: serverId,
}
msg2 := &IrcMessage{
Name: RPL_ISUPPORT,
Args: append(strings.Split(s2, " "), "are supported by this server"),
Sender: serverId,
}
p.ParseMyInfo(msg0)
p.ParseISupport(msg1)
p.ParseISupport(msg2)
c.Check(p.ServerName(), Equals, "irc.test.net")
c.Check(p.IrcdVersion(), Equals, "testircd-1.2")
c.Check(p.Usermodes(), Equals, "acCior")
c.Check(p.LegacyChanmodes(), Equals, "beiIklmnoOPrR")
c.Check(p.RFC(), Equals, "RFC8812")
c.Check(p.IRCD(), Equals, "gIRCd")
c.Check(p.Casemapping(), Equals, "scii")
c.Check(p.Prefix(), Equals, "(v)+")
c.Check(p.Chantypes(), Equals, "#&")
c.Check(p.Chanmodes(), Equals, "eI,k,l,imnOPRstz")
c.Check(p.Chanlimit(), Equals, 10)
c.Check(p.Channellen(), Equals, 49)
c.Check(p.Nicklen(), Equals, 8)
c.Check(p.Topiclen(), Equals, 489)
c.Check(p.Awaylen(), Equals, 126)
c.Check(p.Kicklen(), Equals, 399)
c.Check(p.Modes(), Equals, 4)
c.Check(p.Extra("EXCEPTS"), Equals, "e")
c.Check(p.Extra("PENALTY"), Equals, "true")
c.Check(p.Extra("INVEX"), Equals, "I")
c.Check(p.Extra("NICK"), Equals, "")
}
<file_sep>/bot/server_test.go
package bot
import (
"bytes"
"github.com/aarondl/ultimateq/data"
"github.com/aarondl/ultimateq/irc"
"github.com/aarondl/ultimateq/mocks"
. "launchpad.net/gocheck"
"net"
)
func (s *s) TestServerSender(c *C) {
b, err := createBot(fakeConfig, nil, nil, false)
c.Check(err, IsNil)
srv := b.servers[serverId]
srvendpoint := createServerEndpoint(srv)
c.Check(srvendpoint.GetKey(), Equals, serverId)
}
func (s *s) TestServerSender_OpenStore(c *C) {
b, err := createBot(fakeConfig, nil, nil, false)
c.Check(err, IsNil)
srv := b.servers[serverId]
srvendpoint := createServerEndpoint(srv)
c.Check(srvendpoint.GetKey(), Equals, serverId)
called := false
reportCalled := false
reportCalled = srvendpoint.OpenStore(func(*data.Store) {
called = true
})
c.Check(called, Equals, true)
c.Check(reportCalled, Equals, true)
srv.store = nil
called = false
reportCalled = false
reportCalled = srvendpoint.OpenStore(func(*data.Store) {
called = true
})
c.Check(called, Equals, false)
c.Check(reportCalled, Equals, false)
}
func (s *s) TestServer_Write(c *C) {
str := "PONG :msg\r\n"
conn := mocks.CreateConn()
connProvider := func(srv string) (net.Conn, error) {
return conn, nil
}
b, err := createBot(fakeConfig, nil, connProvider, false)
c.Check(err, IsNil)
srv := b.servers[serverId]
_, err = srv.Write([]byte{})
c.Check(err, Equals, errNotConnected)
ers := b.Connect()
c.Check(len(ers), Equals, 0)
b.start(true, false)
err = srv.Writeln(str)
c.Check(bytes.Compare(conn.Receive(len(str), nil), []byte(str)), Equals, 0)
c.Check(err, IsNil)
_, err = srv.Write([]byte(str))
c.Check(bytes.Compare(conn.Receive(len(str), nil), []byte(str)), Equals, 0)
c.Check(err, IsNil)
err = b.Writeln("notrealserver", str)
c.Check(err, NotNil)
b.WaitForHalt()
b.Disconnect()
}
func (s *s) TestServer_Protocaps(c *C) {
caps := irc.CreateProtoCaps()
srv := &Server{
caps: caps,
}
err := srv.createStore()
c.Check(err, IsNil)
err = srv.createDispatcher(nil)
c.Check(err, IsNil)
c.Check(srv.caps.Usermodes(), Not(Equals), "q")
c.Check(srv.caps.Chantypes(), Not(Equals), "!")
c.Check(srv.caps.Chanmodes(), Not(Equals), ",,,q")
c.Check(srv.caps.Prefix(), Not(Equals), "(q)@")
fakeCaps := &irc.ProtoCaps{}
fakeCaps.ParseISupport(&irc.IrcMessage{Args: []string{
"NICK", "CHANTYPES=!", "PREFIX=(q)@", "CHANMODES=,,,q",
}})
fakeCaps.ParseMyInfo(&irc.IrcMessage{Args: []string{
"irc.test.net", "test-12", "q", "abc",
}})
err = srv.protocaps(fakeCaps)
c.Check(err, IsNil)
c.Check(srv.caps.Usermodes(), Equals, "q")
c.Check(srv.caps.Chantypes(), Equals, "!")
c.Check(srv.caps.Chanmodes(), Equals, ",,,q")
c.Check(srv.caps.Prefix(), Equals, "(q)@")
// Check that there's a copy
c.Check(srv.caps, Not(Equals), fakeCaps)
// Check errors
fakeCaps = &irc.ProtoCaps{}
fakeCaps.ParseISupport(&irc.IrcMessage{Args: []string{
"NICK", "CHANTYPES=H",
}})
err = srv.protocaps(fakeCaps)
c.Check(err, NotNil)
fakeCaps = &irc.ProtoCaps{}
fakeCaps.ParseISupport(&irc.IrcMessage{Args: []string{
"NICK", "CHANTYPES=!",
}})
err = srv.protocaps(fakeCaps)
c.Check(err, NotNil)
}
func (s *s) TestServer_State(c *C) {
srv := &Server{}
srv.setStarted(true, false)
c.Check(srv.IsStarted(), Equals, true)
srv.setStarted(false, false)
c.Check(srv.IsStarted(), Equals, false)
srv.setStarted(true, true)
c.Check(srv.IsStarted(), Equals, true)
srv.setStarted(false, true)
c.Check(srv.IsStarted(), Equals, false)
srv.setReading(true, false)
c.Check(srv.IsReading(), Equals, true)
c.Check(srv.IsStarted(), Equals, true)
srv.setReading(false, false)
c.Check(srv.IsReading(), Equals, false)
c.Check(srv.IsStarted(), Equals, false)
srv.setReading(true, true)
c.Check(srv.IsReading(), Equals, true)
c.Check(srv.IsStarted(), Equals, true)
srv.setReading(false, true)
c.Check(srv.IsReading(), Equals, false)
c.Check(srv.IsStarted(), Equals, false)
srv.setWriting(true, false)
c.Check(srv.IsWriting(), Equals, true)
c.Check(srv.IsStarted(), Equals, true)
srv.setWriting(false, false)
c.Check(srv.IsWriting(), Equals, false)
c.Check(srv.IsStarted(), Equals, false)
srv.setWriting(true, true)
c.Check(srv.IsWriting(), Equals, true)
c.Check(srv.IsStarted(), Equals, true)
srv.setWriting(false, true)
c.Check(srv.IsWriting(), Equals, false)
c.Check(srv.IsStarted(), Equals, false)
srv.setConnected(true, false)
c.Check(srv.IsConnected(), Equals, true)
srv.setConnected(false, false)
c.Check(srv.IsConnected(), Equals, false)
srv.setConnected(true, true)
c.Check(srv.IsConnected(), Equals, true)
srv.setConnected(false, true)
c.Check(srv.IsConnected(), Equals, false)
srv.setReconnecting(true, false)
c.Check(srv.IsReconnecting(), Equals, true)
srv.setReconnecting(false, false)
c.Check(srv.IsReconnecting(), Equals, false)
srv.setReconnecting(true, true)
c.Check(srv.IsReconnecting(), Equals, true)
srv.setReconnecting(false, true)
c.Check(srv.IsReconnecting(), Equals, false)
}
<file_sep>/config/config.go
/*
config package provides inline fluent configuration, validation, file
input/output, as well as configuration diffs.
*/
package config
import (
"errors"
"fmt"
"log"
"regexp"
"strconv"
)
const (
// nAssumedServers is the typcial number of configured servers for a bot
nAssumedServers = 1
// defaultIrcPort is IRC Server's default tcp port.
defaultIrcPort = uint16(6667)
// defaultFloodProtectBurst is how many messages can be sent before spam
// filters set in.
defaultFloodProtectBurst = uint(3)
// defaultFloodProtectTimeout is how many seconds between messages before
// the flood protection resets itself.
defaultFloodProtectTimeout = float64(3)
// defaultFloodProtectStep is the number of seconds between messages once
// flood protection has been activated.
defaultFloodProtectStep = float64(3)
// defaultReconnectTimeout is how many seconds to wait between reconns.
defaultReconnectTimeout = uint(20)
// botDefaultPrefix is the command prefix by default
defaultPrefix = "."
// maxHostSize is the biggest hostname possible
maxHostSize = 255
)
// The following format strings are for formatting various config errors.
const (
fmtErrInvalid = "config(%v): Invalid %v, given: %v"
fmtErrMissing = "config(%v): Requires %v, but nothing was given."
fmtErrServerNotFound = "config: Server not found, given: %v"
errMsgServersRequired = "config: At least one server is required."
errMsgDuplicateServer = "config: Server names must be unique, use .Host()"
)
// The following is for mapping config setting names to strings
const (
errHost = "host"
errPort = "port"
errSsl = "ssl"
errVerifyCert = "verifycert"
errNoState = "nostate"
errFloodProtectBurst = "floodprotectburst"
errFloodProtectTimeout = "floodprotecttimeout"
errFloodProtectStep = "floodprotectstep"
errNoReconnect = "noreconnect"
errReconnectTimeout = "reconnecttimeout"
errNick = "nickname"
errAltnick = "alternate nickname"
errRealname = "realname"
errUsername = "username"
errUserhost = "userhost"
errPrefix = "prefix"
errChannel = "channel"
)
var (
// From the RFC:
// nickname = ( letter / special ) *8( letter / digit / special / "-" )
// letter = %x41-5A / %x61-7A ; A-Z / a-z
// digit = %x30-39 ; 0-9
// special = %x5B-60 / %x7B-7D ; [ ] \ ` _ ^ { | }
// We make an excemption to the 9 char limit since few servers today
// enforce it, and the RFC also states that clients should handle longer
// names.
// Test that the name is a valid IRC nickname
rgxNickname = regexp.MustCompile(`^(?i)[a-z\[\]{}|^_\\` + "`]" +
`[a-z0-9\[\]{}|^_\\` + "`" + `]{0,30}$`)
/* Channels names are strings (beginning with a '&', '#', '+' or '!'
character) of length up to fifty (50) characters. Apart from the
requirement that the first character is either '&', '#', '+' or '!',
the only restriction on a channel name is that it SHALL NOT contain
any spaces (' '), a control G (^G or ASCII 7), a comma (','). Space
is used as parameter separator and command is used as a list item
separator by the protocol). A colon (':') can also be used as a
delimiter for the channel mask. Channel names are case insensitive.
Grammar:
channelid = 5( %x41-5A / digit ) ; 5( A-Z / 0-9 )
chanstring = any octet except NUL, BELL, CR, LF, " ", "," and ":"
channel = ( "#" / "+" / ( "!" channelid ) / "&" ) chanstring
[ ":" chanstring ] */
rgxChannel = regexp.MustCompile(
`^(?i)[#&+!][^\s\000\007,]{1,49}$`)
// rgxHost matches hostnames
rgxHost = regexp.MustCompile(
`(?i)^[0-9a-z](?:(?:[0-9a-z]|-){0,61}[0-9a-z])?` +
`(?:\.[0-9a-z](?:(?:[0-9a-z]|-){0,61}[0-9a-z])?)*\.?$`)
// rgxUsername matches usernames, insensitive all chars without spaces.
rgxUsername = regexp.MustCompile(`^[A-Za-z0-9]+$`)
// rgxRealname matches real names, insensitive all chars with spaces.
rgxRealname = regexp.MustCompile(`^[A-Za-z0-9 ]+$`)
)
// Config holds all the information related to the bot including global settings
// default settings, and server specific settings.
type Config struct {
Servers map[string]*Server
Global *Server
context *Server
filename string
Errors []error "-"
}
// CreateConfig initializes a Config object.
func CreateConfig() *Config {
return &Config{
Global: &Server{},
Servers: make(map[string]*Server, nAssumedServers),
Errors: make([]error, 0),
}
}
// Clone deep copies a configuration object.
func (c *Config) Clone() *Config {
global := *c.Global
newconf := &Config{
Global: &global,
Servers: make(map[string]*Server, len(c.Servers)),
Errors: make([]error, 0),
filename: c.filename,
}
for name, srv := range c.Servers {
newsrv := *srv
newsrv.parent = newconf
newconf.Servers[name] = &newsrv
}
return newconf
}
// addError builds an error object and returns it using Sprintf.
func (c *Config) addError(format string, args ...interface{}) {
c.Errors = append(
c.Errors,
errors.New(fmt.Sprintf(format, args...)),
)
}
// IsValid checks to see if the configuration is valid. If errors are found in
// the config the Config.Errors property is filled with the validation errors.
// These can be used to display to the user. See DisplayErrors for a display
// helper.
func (c *Config) IsValid() bool {
if len(c.Servers) == 0 {
c.addError(errMsgServersRequired)
return false
}
c.validateServer(c.Global, false)
for _, s := range c.Servers {
c.validateServer(s, true)
}
return len(c.Errors) == 0
}
// validateServer checks a server for errors and adds to the error collection
// if any are found.
func (c *Config) validateServer(s *Server, missingIsError bool) {
name := s.GetName()
if len(s.Ssl) != 0 {
if _, err := strconv.ParseBool(s.Ssl); err != nil {
c.addError(fmtErrInvalid, name, errSsl, s.Ssl)
}
}
if len(s.VerifyCert) != 0 {
if _, err := strconv.ParseBool(s.VerifyCert); err != nil {
c.addError(fmtErrInvalid, name, errVerifyCert, s.VerifyCert)
}
}
if len(s.NoState) != 0 {
if _, err := strconv.ParseBool(s.NoState); err != nil {
c.addError(fmtErrInvalid, name, errNoState, s.NoState)
}
}
if len(s.FloodProtectBurst) != 0 {
if _, err :=
strconv.ParseUint(s.FloodProtectBurst, 10, 32); err != nil {
c.addError(fmtErrInvalid, name, errFloodProtectBurst,
s.FloodProtectBurst)
}
}
if len(s.FloodProtectTimeout) != 0 {
if _, err := strconv.ParseFloat(s.FloodProtectTimeout, 32); err != nil {
c.addError(fmtErrInvalid, name, errFloodProtectTimeout,
s.FloodProtectTimeout)
}
}
if len(s.FloodProtectStep) != 0 {
if _, err := strconv.ParseFloat(s.FloodProtectStep, 32); err != nil {
c.addError(fmtErrInvalid, name, errFloodProtectStep,
s.FloodProtectStep)
}
}
if len(s.NoReconnect) != 0 {
if _, err := strconv.ParseBool(s.NoReconnect); err != nil {
c.addError(fmtErrInvalid, name, errNoReconnect,
s.NoReconnect)
}
}
if len(s.ReconnectTimeout) != 0 {
if _, err := strconv.ParseUint(s.ReconnectTimeout, 10, 32); err != nil {
c.addError(fmtErrInvalid, name, errReconnectTimeout,
s.ReconnectTimeout)
}
}
if host := s.GetHost(); len(host) == 0 {
if missingIsError {
c.addError(fmtErrMissing, name, errHost)
}
} else if !rgxHost.MatchString(host) || len(host) > maxHostSize {
c.addError(fmtErrInvalid, name, errHost, host)
}
if nick := s.GetNick(); len(nick) == 0 {
if missingIsError {
c.addError(fmtErrMissing, name, errNick)
}
} else if !rgxNickname.MatchString(nick) {
c.addError(fmtErrInvalid, name, errNick, nick)
}
if username := s.GetUsername(); len(username) == 0 {
if missingIsError {
c.addError(fmtErrMissing, name, errUsername)
}
} else if !rgxUsername.MatchString(username) {
c.addError(fmtErrInvalid, name, errUsername, username)
}
if userhost := s.GetUserhost(); len(userhost) == 0 {
if missingIsError {
c.addError(fmtErrMissing, name, errUserhost)
}
} else if !rgxHost.MatchString(userhost) {
c.addError(fmtErrInvalid, name, errUserhost, userhost)
}
if realname := s.GetRealname(); len(realname) == 0 {
if missingIsError {
c.addError(fmtErrMissing, name, errRealname)
}
} else if !rgxRealname.MatchString(realname) {
c.addError(fmtErrInvalid, name, errRealname, realname)
}
for _, channel := range s.GetChannels() {
if !rgxChannel.MatchString(channel) {
c.addError(fmtErrInvalid, name, errChannel, channel)
}
}
}
// DisplayErrors is a helper function to log the output of all config to the
// standard logger.
func (c *Config) DisplayErrors() {
for _, e := range c.Errors {
log.Println(e.Error())
}
}
// GlobalContext clears the configs server context
func (c *Config) GlobalContext() *Config {
c.context = nil
return c
}
// ServerContext the configs server context, adds an error if the if server
// key is not found.
func (c *Config) ServerContext(name string) *Config {
if srv, ok := c.Servers[name]; ok {
c.context = srv
} else {
c.addError(fmtErrServerNotFound, name)
}
return c
}
// GetContext retrieves the current configuration context, if no context has
// been set, returns the global setting object.
func (c *Config) GetContext() *Server {
if c.context != nil {
return c.context
}
return c.Global
}
// GetServer retrieves the server by name if it exists, nil if not.
func (c *Config) GetServer(name string) *Server {
return c.Servers[name]
}
// Server fluently creates a server object and sets the context on the Config to
// the current instance. This automatically sets the Host() parameter to the
// same thing. If you have multiple servers connecting to the same host, you
// will have to use this to name the server, and Host() to set the host.
func (c *Config) Server(name string) *Config {
if len(name) != 0 {
if _, ok := c.Servers[name]; !ok {
c.context = &Server{parent: c, Name: name, Host: name}
c.Servers[name] = c.context
} else {
c.addError(errMsgDuplicateServer)
}
} else {
c.addError(fmtErrMissing, "<NONE>", errHost)
}
return c
}
// RemoveServer removes a server by name. Note that this does not work on
// host if a name has been set on the server.
func (c *Config) RemoveServer(name string) (deleted bool) {
if _, deleted := c.Servers[name]; deleted {
delete(c.Servers, name)
c.context = nil
}
return
}
// Host fluently sets the host for the current config context
func (c *Config) Host(host string) *Config {
if c.context != nil {
c.context.Host = host
}
return c
}
// Port fluently sets the port for the current config context
func (c *Config) Port(port uint16) *Config {
c.GetContext().Port = port
return c
}
// Ssl fluently sets the ssl for the current config context
func (c *Config) Ssl(ssl bool) *Config {
c.GetContext().Ssl = strconv.FormatBool(ssl)
return c
}
// VerifyCert fluently sets the verifyCert for the current config context
func (c *Config) VerifyCert(verifyCert bool) *Config {
c.GetContext().VerifyCert = strconv.FormatBool(verifyCert)
return c
}
// NoState fluently sets reconnection for the current config context,
// this turns off the irc state database (data package).
func (c *Config) NoState(nostate bool) *Config {
c.GetContext().NoState = strconv.FormatBool(nostate)
return c
}
// FloodProtectBurst fluently sets flood burst for the current config context,
// this is how many messages will be bursted through without enabling flood
// protection.
func (c *Config) FloodProtectBurst(floodburst uint) *Config {
c.GetContext().FloodProtectBurst =
strconv.FormatUint(uint64(floodburst), 10)
return c
}
// FloodProtectTimeout fluently sets flood timeout for the current config
// context, this is how long flood protect will stay enabled after being
// enabled.
func (c *Config) FloodProtectTimeout(floodtimeout float64) *Config {
c.GetContext().FloodProtectTimeout =
strconv.FormatFloat(floodtimeout, 'e', -1, 64)
return c
}
// FloodProtectStep fluently sets flood protect step for the current config
// context, this is how many seconds to put in between messages after flood
// protect has been activated (after FloodProtectBurst messages).
func (c *Config) FloodProtectStep(floodstep float64) *Config {
c.GetContext().FloodProtectStep =
strconv.FormatFloat(floodstep, 'e', -1, 64)
return c
}
// NoReconnect fluently sets reconnection for the current config context
func (c *Config) NoReconnect(noreconnect bool) *Config {
c.GetContext().NoReconnect = strconv.FormatBool(noreconnect)
return c
}
// ReconnectTimeout fluently sets the port for the current config context
func (c *Config) ReconnectTimeout(seconds uint) *Config {
c.GetContext().ReconnectTimeout = strconv.FormatUint(uint64(seconds), 10)
return c
}
// Nick fluently sets the nick for the current config context
func (c *Config) Nick(nick string) *Config {
c.GetContext().Nick = nick
return c
}
// Altnick fluently sets the altnick for the current config context
func (c *Config) Altnick(altnick string) *Config {
c.GetContext().Altnick = altnick
return c
}
// Username fluently sets the username for the current config context
func (c *Config) Username(username string) *Config {
c.GetContext().Username = username
return c
}
// Userhost fluently sets the userhost for the current config context
func (c *Config) Userhost(userhost string) *Config {
c.GetContext().Userhost = userhost
return c
}
// Realname fluently sets the realname for the current config context
func (c *Config) Realname(realname string) *Config {
c.GetContext().Realname = realname
return c
}
// Prefix fluently sets the prefix for the current config context
func (c *Config) Prefix(prefix string) *Config {
c.GetContext().Prefix = prefix
return c
}
// Channels fluently sets the channels for the current config context
func (c *Config) Channels(channels ...string) *Config {
if len(channels) > 0 {
context := c.GetContext()
context.Channels = make([]string, len(channels))
copy(context.Channels, channels)
}
return c
}
// ServerConfig stores the all the details necessary to connect to an irc server
// Although all of these are exported so they can be deserialized into a yaml
// file, they are not for direct reading and the helper methods should ALWAYS
// be used to preserve correct global-value resolution.
type Server struct {
parent *Config
// Name of this connection
Name string
// Irc Server connection info
Host string
Port uint16
Ssl string
VerifyCert string
// State tracking
NoState string
// Flood Protection
FloodProtectBurst string
FloodProtectTimeout string
FloodProtectStep string
// Auto reconnection
NoReconnect string
ReconnectTimeout string
// Irc User data
Nick string
Altnick string
Username string
Userhost string
Realname string
// Dispatching options
Prefix string
Channels []string
}
// GetFilename returns fileName of the configuration, or the default.
func (c *Config) GetFilename() (filename string) {
filename = defaultConfigFileName
if len(c.filename) > 0 {
filename = c.filename
}
return
}
// GetHost gets s.host
func (s *Server) GetHost() string {
return s.Host
}
// GetName gets s.name
func (s *Server) GetName() string {
return s.Name
}
// GetPort returns gets Port of the server, or the global port, or
// ircDefaultPort
func (s *Server) GetPort() (port uint16) {
port = defaultIrcPort
if s.Port != 0 {
port = s.Port
} else if s.parent != nil && s.parent.Global.Port != 0 {
port = s.parent.Global.Port
}
return
}
// GetSsl returns Ssl of the server, or the global ssl, or false
func (s *Server) GetSsl() (ssl bool) {
var err error
if len(s.Ssl) != 0 {
ssl, err = strconv.ParseBool(s.Ssl)
} else if s.parent != nil && len(s.parent.Global.Ssl) != 0 {
ssl, err = strconv.ParseBool(s.parent.Global.Ssl)
}
if err != nil {
ssl = false
}
return
}
// GetVerifyCert gets VerifyCert of the server, or the global verifyCert, or
// false
func (s *Server) GetVerifyCert() (verifyCert bool) {
var err error
if len(s.VerifyCert) != 0 {
verifyCert, err = strconv.ParseBool(s.VerifyCert)
} else if s.parent != nil && len(s.parent.Global.VerifyCert) != 0 {
verifyCert, err = strconv.ParseBool(s.parent.Global.VerifyCert)
}
if err != nil {
verifyCert = false
}
return
}
// GetNoState gets NoState of the server, or the global nostate, or
// false
func (s *Server) GetNoState() (nostate bool) {
var err error
if len(s.NoState) != 0 {
nostate, err = strconv.ParseBool(s.NoState)
} else if s.parent != nil && len(s.parent.Global.NoState) != 0 {
nostate, err = strconv.ParseBool(s.parent.Global.NoState)
}
if err != nil {
nostate = false
}
return
}
// GetNoReconnect gets NoReconnect of the server, or the global noReconnect, or
// false
func (s *Server) GetNoReconnect() (noReconnect bool) {
var err error
if len(s.NoReconnect) != 0 {
noReconnect, err = strconv.ParseBool(s.NoReconnect)
} else if s.parent != nil && len(s.parent.Global.NoReconnect) != 0 {
noReconnect, err = strconv.ParseBool(s.parent.Global.NoReconnect)
}
if err != nil {
noReconnect = false
}
return
}
// GetFloodProtectBurst gets FloodProtectBurst of the server, or the global
// floodProtectBurst, or defaultFloodProtectBurst
func (s *Server) GetFloodProtectBurst() (floodBurst uint) {
var err error
var u uint64
var notset bool
floodBurst = defaultFloodProtectBurst
if len(s.FloodProtectBurst) != 0 {
u, err = strconv.ParseUint(s.FloodProtectBurst, 10, 32)
} else if s.parent != nil && len(s.parent.Global.FloodProtectBurst) != 0 {
u, err = strconv.ParseUint(s.parent.Global.FloodProtectBurst, 10, 32)
} else {
notset = true
}
if err != nil {
floodBurst = defaultFloodProtectBurst
} else if !notset {
floodBurst = uint(u)
}
return
}
// GetFloodProtectTimeout gets FloodProtectTimeout of the server, or the global
// floodProtectTimeout, or defaultFloodProtectTimeout
func (s *Server) GetFloodProtectTimeout() (floodTimeout float64) {
var err error
floodTimeout = defaultFloodProtectTimeout
if len(s.FloodProtectTimeout) != 0 {
floodTimeout, err =
strconv.ParseFloat(s.FloodProtectTimeout, 32)
} else if s.parent != nil && len(s.parent.Global.FloodProtectTimeout) != 0 {
floodTimeout, err =
strconv.ParseFloat(s.parent.Global.FloodProtectTimeout, 32)
}
if err != nil {
floodTimeout = defaultFloodProtectTimeout
}
return
}
// GetFloodProtectStep gets FloodProtectStep of the server, or the global
// floodProtectStep, or defaultFloodProtectStep
func (s *Server) GetFloodProtectStep() (floodStep float64) {
var err error
floodStep = defaultFloodProtectStep
if len(s.FloodProtectStep) != 0 {
floodStep, err =
strconv.ParseFloat(s.FloodProtectStep, 32)
} else if s.parent != nil && len(s.parent.Global.FloodProtectStep) != 0 {
floodStep, err =
strconv.ParseFloat(s.parent.Global.FloodProtectStep, 32)
}
if err != nil {
floodStep = defaultFloodProtectStep
}
return
}
// GetReconnectTimeout gets ReconnectTimeout of the server, or the global
// reconnectTimeout, or defaultReconnectTimeout
func (s *Server) GetReconnectTimeout() (reconnTimeout uint) {
var notset bool
var err error
var u uint64
reconnTimeout = defaultReconnectTimeout
if len(s.ReconnectTimeout) != 0 {
u, err = strconv.ParseUint(s.ReconnectTimeout, 10, 32)
} else if s.parent != nil && len(s.parent.Global.ReconnectTimeout) != 0 {
u, err = strconv.ParseUint(s.parent.Global.ReconnectTimeout, 10, 32)
} else {
notset = true
}
if err != nil {
reconnTimeout = defaultReconnectTimeout
} else if !notset {
reconnTimeout = uint(u)
}
return
}
// GetNick gets Nick of the server, or the global nick, or empty string.
func (s *Server) GetNick() (nick string) {
if len(s.Nick) > 0 {
nick = s.Nick
} else if s.parent != nil && len(s.parent.Global.Nick) > 0 {
nick = s.parent.Global.Nick
}
return
}
// GetAltnick gets Altnick of the server, or the global altnick, or empty
// string.
func (s *Server) GetAltnick() (altnick string) {
if len(s.Altnick) > 0 {
altnick = s.Altnick
} else if s.parent != nil && len(s.parent.Global.Altnick) > 0 {
altnick = s.parent.Global.Altnick
}
return
}
// GetUsername gets Username of the server, or the global username, or empty
// string.
func (s *Server) GetUsername() (username string) {
if len(s.Username) > 0 {
username = s.Username
} else if s.parent != nil && len(s.parent.Global.Username) > 0 {
username = s.parent.Global.Username
}
return
}
// GetUserhost gets Userhost of the server, or the global userhost, or empty
// string.
func (s *Server) GetUserhost() (userhost string) {
if len(s.Userhost) > 0 {
userhost = s.Userhost
} else if s.parent != nil && len(s.parent.Global.Userhost) > 0 {
userhost = s.parent.Global.Userhost
}
return
}
// GetRealname gets Realname of the server, or the global realname, or empty
// string.
func (s *Server) GetRealname() (realname string) {
if len(s.Realname) > 0 {
realname = s.Realname
} else if s.parent != nil && len(s.parent.Global.Realname) > 0 {
realname = s.parent.Global.Realname
}
return
}
// GetPrefix gets Prefix of the server, or the global prefix, or defaultPrefix.
func (s *Server) GetPrefix() (prefix string) {
prefix = defaultPrefix
if len(s.Prefix) > 0 {
prefix = s.Prefix
} else if s.parent != nil && len(s.parent.Global.Prefix) > 0 {
prefix = s.parent.Global.Prefix
}
return
}
// GetChannels gets Channels of the server, or the global channels, or nil
// slice of string (check the length!).
func (s *Server) GetChannels() (channels []string) {
if len(s.Channels) > 0 {
channels = s.Channels
} else if s.parent != nil && len(s.parent.Global.Channels) > 0 {
channels = s.parent.Global.Channels
}
return
}
<file_sep>/irc/channelfinder_test.go
package irc
import . "launchpad.net/gocheck"
func (s *s) TestChannelFinder(c *C) {
finder, err := CreateChannelFinder(`~&*+?[]()-^`)
c.Check(err, IsNil)
c.Check(finder.channelRegexp, NotNil)
c.Check(len(finder.FindChannels(")channel")), Equals, 1)
c.Check(finder.IsChannel(")channel"), Equals, true)
}
func (s *s) TestChannelFinder_Error(c *C) {
_, err := CreateChannelFinder(`H`)
c.Check(err, NotNil)
}
<file_sep>/irc/mask_test.go
package irc
import (
. "launchpad.net/gocheck"
)
func (s *s) TestMask(c *C) {
var mask Mask = "nick!user@host"
c.Check(mask.GetNick(), Equals, "nick")
c.Check(mask.GetUsername(), Equals, "user")
c.Check(mask.GetHost(), Equals, "host")
c.Check(mask.GetFullhost(), Equals, string(mask))
mask = "nick@user!host"
c.Check(mask.GetNick(), Equals, "nick")
c.Check(mask.GetUsername(), Equals, "")
c.Check(mask.GetHost(), Equals, "")
c.Check(mask.GetFullhost(), Equals, string(mask))
mask = "nick"
c.Check(mask.GetNick(), Equals, "nick")
c.Check(mask.GetUsername(), Equals, "")
c.Check(mask.GetHost(), Equals, "")
c.Check(mask.GetFullhost(), Equals, string(mask))
}
func (s *s) TestMask_SplitHost(c *C) {
var nick, user, host string
nick, user, host = Mask("").SplitFullhost()
c.Check(nick, Equals, "")
c.Check(user, Equals, "")
c.Check(host, Equals, "")
nick, user, host = Mask("nick").SplitFullhost()
c.Check(nick, Equals, "nick")
c.Check(user, Equals, "")
c.Check(host, Equals, "")
nick, user, host = Mask("nick!").SplitFullhost()
c.Check(nick, Equals, "nick")
c.Check(user, Equals, "")
c.Check(host, Equals, "")
nick, user, host = Mask("nick@").SplitFullhost()
c.Check(nick, Equals, "nick")
c.Check(user, Equals, "")
c.Check(host, Equals, "")
nick, user, host = Mask("nick@host!user").SplitFullhost()
c.Check(nick, Equals, "nick")
c.Check(user, Equals, "")
c.Check(host, Equals, "")
nick, user, host = Mask("nick!user@host").SplitFullhost()
c.Check(nick, Equals, "nick")
c.Check(user, Equals, "user")
c.Check(host, Equals, "host")
}
func (s *s) TestWildMask_Match(c *C) {
var wmask WildMask = ""
var mask Mask = ""
c.Check(wmask.Match(mask), Equals, true)
c.Check(WildMask("nick!*@*").Match("nick!@"), Equals, true)
mask = "nick!user@host"
positiveMasks := []WildMask{
// Default
`nick!user@host`,
// *'s
`*`, `*!*@*`, `**!**@**`, `*@host`, `**@host`,
`nick!*`, `nick!**`, `*nick!user@host`, `**nick!user@host`,
`nick!user@host*`, `nick!user@host**`,
// ?'s
`ni?k!us?r@ho?st`, `ni??k!us??r@ho??st`, `????!????@????`,
`?ick!user@host`, `??ick!user@host`, `?nick!user@host`,
`??nick!user@host`, `nick!user@hos?`, `nick!user@hos??`,
`nick!user@host?`, `nick!user@host??`,
// Combination
`?*nick!user@host`, `*?nick!user@host`, `??**nick!user@host`,
`**??nick!user@host`,
`nick!user@host?*`, `nick!user@host*?`, `nick!user@host??**`,
`nick!user@host**??`, `nick!u?*?ser@host`, `nick!u?*?ser@host`,
}
for i := 0; i < len(positiveMasks); i++ {
if !positiveMasks[i].Match(mask) {
c.Errorf("Expected: %v to match %v", positiveMasks[i], mask)
}
}
negativeMasks := []WildMask{
``, `?nq******c?!*@*`, `nick2!*@*`, `*!*@hostfail`, `*!*@failhost`,
}
for i := 0; i < len(negativeMasks); i++ {
if negativeMasks[i].Match(mask) {
c.Errorf("Expected: %v not to match %v", negativeMasks[i], mask)
}
}
}
<file_sep>/irc/common.go
/*
irc package defines types and classes to be used by most other packages in
the ultimateq system. It is small and comprised mostly of helper like types
and constants.
*/
package irc
import (
"fmt"
"io"
"strings"
)
const (
// The maximum length for an irc message.
IRC_MAX_LENGTH = 510
// A format string to create privmsg headers.
fmtPrivmsgHeader = PRIVMSG + " %v :"
// A format string to create notice headers.
fmtNoticeHeader = NOTICE + " %v :"
// A format string to create joins.
fmtJoin = JOIN + " :%v"
// A format string to create parts.
fmtPart = PART + " :%v"
// A format string to create quits.
fmtQuit = QUIT + " :%v"
)
// IRC Messages, these messages are 1-1 constant to string lookups for ease of
// use when registering handlers etc.
const (
JOIN = "JOIN"
KICK = "KICK"
MODE = "MODE"
NICK = "NICK"
NOTICE = "NOTICE"
PART = "PART"
PING = "PING"
PONG = "PONG"
PRIVMSG = "PRIVMSG"
QUIT = "QUIT"
TOPIC = "TOPIC"
)
// IRC Reply and Error Messages. These are sent in reply to a previous message.
const (
RPL_WELCOME = "001"
RPL_YOURHOST = "002"
RPL_CREATED = "003"
RPL_MYINFO = "004"
RPL_ISUPPORT = "005"
RPL_BOUNCE = "005"
RPL_USERHOST = "302"
RPL_ISON = "303"
RPL_AWAY = "301"
RPL_UNAWAY = "305"
RPL_NOWAWAY = "306"
RPL_WHOISUSER = "311"
RPL_WHOISSERVER = "312"
RPL_WHOISOPERATOR = "313"
RPL_WHOISIDLE = "317"
RPL_ENDOFWHOIS = "318"
RPL_WHOISCHANNELS = "319"
RPL_WHOWASUSER = "314"
RPL_ENDOFWHOWAS = "369"
RPL_LISTSTART = "321"
RPL_LIST = "322"
RPL_LISTEND = "323"
RPL_UNIQOPIS = "325"
RPL_CHANNELMODEIS = "324"
RPL_NOTOPIC = "331"
RPL_TOPIC = "332"
RPL_INVITING = "341"
RPL_SUMMONING = "342"
RPL_INVITELIST = "346"
RPL_ENDOFINVITELIST = "347"
RPL_EXCEPTLIST = "348"
RPL_ENDOFEXCEPTLIST = "349"
RPL_VERSION = "351"
RPL_WHOREPLY = "352"
RPL_ENDOFWHO = "315"
RPL_NAMREPLY = "353"
RPL_ENDOFNAMES = "366"
RPL_LINKS = "364"
RPL_ENDOFLINKS = "365"
RPL_BANLIST = "367"
RPL_ENDOFBANLIST = "368"
RPL_INFO = "371"
RPL_ENDOFINFO = "374"
RPL_MOTDSTART = "375"
RPL_MOTD = "372"
RPL_ENDOFMOTD = "376"
RPL_YOUREOPER = "381"
RPL_REHASHING = "382"
RPL_YOURESERVICE = "383"
RPL_TIME = "391"
RPL_USERSSTART = "392"
RPL_USERS = "393"
RPL_ENDOFUSERS = "394"
RPL_NOUSERS = "395"
RPL_TRACELINK = "200"
RPL_TRACECONNECTING = "201"
RPL_TRACEHANDSHAKE = "202"
RPL_TRACEUNKNOWN = "203"
RPL_TRACEOPERATOR = "204"
RPL_TRACEUSER = "205"
RPL_TRACESERVER = "206"
RPL_TRACESERVICE = "207"
RPL_TRACENEWTYPE = "208"
RPL_TRACECLASS = "209"
RPL_TRACERECONNECT = "210"
RPL_TRACELOG = "261"
RPL_TRACEEND = "262"
RPL_STATSLINKINFO = "211"
RPL_STATSCOMMANDS = "212"
RPL_ENDOFSTATS = "219"
RPL_STATSUPTIME = "242"
RPL_STATSOLINE = "243"
RPL_UMODEIS = "221"
RPL_SERVLIST = "234"
RPL_SERVLISTEND = "235"
RPL_LUSERCLIENT = "251"
RPL_LUSEROP = "252"
RPL_LUSERUNKNOWN = "253"
RPL_LUSERCHANNELS = "254"
RPL_LUSERME = "255"
RPL_ADMINME = "256"
RPL_ADMINLOC1 = "257"
RPL_ADMINLOC2 = "258"
RPL_ADMINEMAIL = "259"
RPL_TRYAGAIN = "263"
ERR_NOSUCHNICK = "401"
ERR_NOSUCHSERVER = "402"
ERR_NOSUCHCHANNEL = "403"
ERR_CANNOTSENDTOCHAN = "404"
ERR_TOOMANYCHANNELS = "405"
ERR_WASNOSUCHNICK = "406"
ERR_TOOMANYTARGETS = "407"
ERR_NOSUCHSERVICE = "408"
ERR_NOORIGIN = "409"
ERR_NORECIPIENT = "411"
ERR_NOTEXTTOSEND = "412"
ERR_NOTOPLEVEL = "413"
ERR_WILDTOPLEVEL = "414"
ERR_BADMASK = "415"
ERR_UNKNOWNCOMMAND = "421"
ERR_NOMOTD = "422"
ERR_NOADMININFO = "423"
ERR_FILEERROR = "424"
ERR_NONICKNAMEGIVEN = "431"
ERR_ERRONEUSNICKNAME = "432"
ERR_NICKNAMEINUSE = "433"
ERR_NICKCOLLISION = "436"
ERR_UNAVAILRESOURCE = "437"
ERR_USERNOTINCHANNEL = "441"
ERR_NOTONCHANNEL = "442"
ERR_USERONCHANNEL = "443"
ERR_NOLOGIN = "444"
ERR_SUMMONDISABLED = "445"
ERR_USERSDISABLED = "446"
ERR_NOTREGISTERED = "451"
ERR_NEEDMOREPARAMS = "461"
ERR_ALREADYREGISTRED = "462"
ERR_NOPERMFORHOST = "463"
ERR_PASSWDMISMATCH = "464"
ERR_YOUREBANNEDCREEP = "465"
ERR_YOUWILLBEBANNED = "466"
ERR_KEYSET = "467"
ERR_CHANNELISFULL = "471"
ERR_UNKNOWNMODE = "472"
ERR_INVITEONLYCHAN = "473"
ERR_BANNEDFROMCHAN = "474"
ERR_BADCHANNELKEY = "475"
ERR_BADCHANMASK = "476"
ERR_NOCHANMODES = "477"
ERR_BANLISTFULL = "478"
ERR_NOPRIVILEGES = "481"
ERR_CHANOPRIVSNEEDED = "482"
ERR_CANTKILLSERVER = "483"
ERR_RESTRICTED = "484"
ERR_UNIQOPPRIVSNEEDED = "485"
ERR_NOOPERHOST = "491"
ERR_UMODEUNKNOWNFLAG = "501"
ERR_USERSDONTMATCH = "502"
)
// Pseudo Messages, these messages are not real messages defined by the irc
// protocol but the bot provides them to allow for additional messages to be
// handled such as connect or disconnects which the irc protocol has no protocol
// defined for.
const (
RAW = "RAW"
CONNECT = "CONNECT"
DISCONNECT = "DISCONNECT"
)
// Endpoint represents the source of an event, and should allow replies on a
// writing interface as well as a way to identify itself.
type Endpoint interface {
// An embedded io.Writer that can write back to the source of the event.
io.Writer
// Retrieves a key to identify the source of the event.
GetKey() string
// Send sends a string with spaces between non-strings.
Send(...interface{}) error
// Sendln sends a string with spaces between everything.
// Does not send newline.
Sendln(...interface{}) error
// Sendf sends a formatted string.
Sendf(string, ...interface{}) error
// Privmsg sends a string with spaces between non-strings.
Privmsg(string, ...interface{}) error
// Privmsgln sends a privmsg with spaces between everything.
// Does not send newline.
Privmsgln(string, ...interface{}) error
// Privmsgf sends a formatted privmsg.
Privmsgf(string, string, ...interface{}) error
// Notice sends a string with spaces between non-strings.
Notice(string, ...interface{}) error
// Noticeln sends a notice with spaces between everything.
// Does not send newline.
Noticeln(string, ...interface{}) error
// Noticef sends a formatted notice.
Noticef(string, string, ...interface{}) error
// Sends a join message to the endpoint.
Join(...string) error
// Sends a part message to the endpoint.
Part(...string) error
// Sends a quit message to the endpoint.
Quit(string) error
}
// IrcMessage contains all the information broken out of an irc message.
type IrcMessage struct {
// Name of the message. Uppercase constant name or numeric.
Name string
// The server or user that sent the message, a fullhost if one was supplied.
Sender string
// The args split by space delimiting.
Args []string
}
// Split splits string arguments. A convenience method to avoid having to call
// splits and import strings.
func (m *IrcMessage) Split(index int) []string {
return strings.Split(m.Args[index], ",")
}
// Message type provides a view around an IrcMessage to access it's parts in a
// more convenient way.
type Message struct {
// The underlying irc message.
*IrcMessage
}
// Target retrieves the channel or user this message was sent to.
func (p *Message) Target() string {
return p.Args[0]
}
// Message retrieves the message sent to the user or channel.
func (p *Message) Message() string {
return p.Args[1]
}
// Helper fullfills the Endpoint's many interface requirements.
type Helper struct {
io.Writer
}
// Send sends a string with spaces between non-strings.
func (h *Helper) Send(args ...interface{}) error {
_, err := fmt.Fprint(h, args...)
return err
}
// Sendln sends a string with spaces between everything. Does not send newline.
func (h *Helper) Sendln(args ...interface{}) error {
str := fmt.Sprintln(args...)
_, err := h.Write([]byte(str[:len(str)-1]))
return err
}
// Sendf sends a formatted string.
func (h *Helper) Sendf(format string, args ...interface{}) error {
_, err := fmt.Fprintf(h, format, args...)
return err
}
// Privmsg sends a string with spaces between non-strings.
func (h *Helper) Privmsg(target string, args ...interface{}) error {
header := []byte(fmt.Sprintf(fmtPrivmsgHeader, target))
msg := []byte(fmt.Sprint(args...))
return h.splitSend(header, msg)
}
// Privmsgln sends a privmsg with spaces between everything.
// Does not send newline.
func (h *Helper) Privmsgln(target string, args ...interface{}) error {
header := []byte(fmt.Sprintf(fmtPrivmsgHeader, target))
str := fmt.Sprintln(args...)
str = str[:len(str)-1]
return h.splitSend(header, []byte(str))
}
// Privmsgf sends a formatted privmsg.
func (h *Helper) Privmsgf(target, format string, args ...interface{}) error {
header := []byte(fmt.Sprintf(fmtPrivmsgHeader, target))
msg := []byte(fmt.Sprintf(format, args...))
return h.splitSend(header, msg)
}
// Notice sends a string with spaces between non-strings.
func (h *Helper) Notice(target string, args ...interface{}) error {
header := []byte(fmt.Sprintf(fmtNoticeHeader, target))
msg := []byte(fmt.Sprint(args...))
return h.splitSend(header, msg)
}
// Noticeln sends a notice with spaces between everything.
// Does not send newline.
func (h *Helper) Noticeln(target string, args ...interface{}) error {
header := []byte(fmt.Sprintf(fmtNoticeHeader, target))
str := fmt.Sprintln(args...)
str = str[:len(str)-1]
return h.splitSend(header, []byte(str))
}
// Noticef sends a formatted notice.
func (h *Helper) Noticef(target, format string, args ...interface{}) error {
header := []byte(fmt.Sprintf(fmtNoticeHeader, target))
msg := []byte(fmt.Sprintf(format, args...))
return h.splitSend(header, msg)
}
// Sends a join message to the endpoint.
func (h *Helper) Join(targets ...string) error {
if len(targets) == 0 {
return nil
}
_, err := fmt.Fprintf(h, fmtJoin, strings.Join(targets, ","))
return err
}
// Sends a part message to the endpoint.
func (h *Helper) Part(targets ...string) error {
if len(targets) == 0 {
return nil
}
_, err := fmt.Fprintf(h, fmtPart, strings.Join(targets, ","))
return err
}
// Sends a quit message to the endpoint.
func (h *Helper) Quit(msg string) error {
_, err := fmt.Fprintf(h, fmtQuit, msg)
return err
}
// splitSend breaks a message down into irc-digestable chunks based on
// IRC_MAX_LENGTH, and appends the header to each message.
func (h *Helper) splitSend(header, msg []byte) error {
var err error
ln, lnh := len(msg), len(header)
msgMax := IRC_MAX_LENGTH - lnh
if ln <= msgMax {
_, err = h.Write(append(header, msg...))
return err
}
var size int
buf := make([]byte, IRC_MAX_LENGTH)
for ln > 0 {
size = msgMax
if ln < msgMax {
size = ln
}
copy(buf, header)
copy(buf[lnh:], msg[:size])
_, err = h.Write(buf[:lnh+size])
if err != nil {
return err
}
msg = msg[size:]
ln, lnh = len(msg), len(header)
}
return nil
}
<file_sep>/dispatch/handlers.go
package dispatch
import "github.com/aarondl/ultimateq/irc"
// PrivmsgHandler is for handling privmsgs going to channel or user targets.
type PrivmsgHandler interface {
Privmsg(*irc.Message, irc.Endpoint)
}
// PrivmsgUserHandler is for handling privmsgs going to user targets.
type PrivmsgUserHandler interface {
PrivmsgUser(*irc.Message, irc.Endpoint)
}
// PrivmsgChannelHandler is for handling privmsgs going to channel targets.
type PrivmsgChannelHandler interface {
PrivmsgChannel(*irc.Message, irc.Endpoint)
}
// NoticeHandler is for handling privmsgs going to channel or user targets.
type NoticeHandler interface {
Notice(*irc.Message, irc.Endpoint)
}
// NoticeUserHandler is for handling privmsgs going to user targets.
type NoticeUserHandler interface {
NoticeUser(*irc.Message, irc.Endpoint)
}
// NoticeChannelHandler is for handling privmsgs going to channel targets.
type NoticeChannelHandler interface {
NoticeChannel(*irc.Message, irc.Endpoint)
}
<file_sep>/README.md
#ultimateq
An irc bot written in Go.
ultimateq is designed as a distributed irc bot framework. Where a bot can be
just one file, or a collection of extensions running alongside the bot. A
key feature in this bot is that the extensions are actually processes
themselves which will connect to a bot, or allow bots to connect to them
via unix or tcp sockets using RPC mechanisms to communicate.
There are two advantages behind this model. One is that several bots can use
a single extension. This has advantages if the extension is holding a
database meant to be shared (although for scalability you might consider
database level scaling with replication, but this is just an example).
The other advantage is that the bot has failure isolation. Because each
extension is running in it's own process, even a fatal and unrecoverable
crash in an extension means nothing to the bot. This adds a resilency to
this bot that not many other bots share.
Here's a sample taste of what the bot api might look like for some do-nothing
connection to an irc server.
```go
import bot "github.com/aarondl/ultimateq"
func main() {
bot.Nick("mybot").Channels("#C++").Run()
}
```
##Packages
###bot
This package ties all the low level plumbing together, using this package's
helpers it should be easy to create a bot and deploy him into the dying world
of irc.
###irc
This package houses the common irc constants and types necessary throughout
the bot. It's supposed to remain a small and dependency-less package that all
packages can utilize.
###config
Config package is used to present a fluent style configuration builder for an
irc bot. It also provides some validation, and file reading/writing.
###parse
This package deals with parsing irc protocols. It is able to consume irc
protocol messages using the Parse method, returning the common IrcMessage
type from the irc package.
###dispatch
Dispatch package is meant to register callbacks and dispatch IrcMessages onto
them in an asynchronous method. It also presents many handler types that will
be easy to use for bot-writers.
###inet
Implements the actual connection to an irc server, handles buffering, \r\n
splitting and appending, and logarithmic write-speed throttling.
###extension
This package defines helpers to create an extension for the bot. It should
expose a way to connect/allow connections to the bot via TCP or Unix socket.
And have simple helpers for some network RPC mechanism.
###data
This package holds data for irc based services. It supplies information
about channels, and users that the bot is aware of.
Persistence may need some attention. Does this bot have built-in user
levels and modes for users? Does it have arbitrary key-value
store for extensions? How do extensions keep this data up to date? Will
they have their own copy of the data or do they need to query the data on the
master bot all the time?
<file_sep>/data/data_test.go
package data
import (
"github.com/aarondl/ultimateq/irc"
. "launchpad.net/gocheck"
"testing"
)
func Test(t *testing.T) { TestingT(t) } //Hook into testing package
type s struct{}
var _ = Suite(&s{})
var server = "irc.server.net"
var users = []string{"nick1!user1@host1", "nick2!user2@host2"}
var nicks = []string{"nick1", "nick2"}
var channels = []string{"#CHAN1", "#CHAN2"}
var self = Self{
User: CreateUser("me!<EMAIL>"),
}
func (s *s) TestStore(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(st, NotNil)
c.Check(err, IsNil)
c.Check(st.Self.ChannelModes, NotNil)
// Should die on creating kinds
fakeCaps := &irc.ProtoCaps{}
fakeCaps.ParseISupport(&irc.IrcMessage{Args: []string{
"NICK", "CHANTYPES=#&", "PREFIX=(ov)@+",
}})
st, err = CreateStore(fakeCaps)
c.Check(st, IsNil)
c.Check(err, NotNil)
// Should die on creating user modes
fakeCaps = &irc.ProtoCaps{}
fakeCaps.ParseISupport(&irc.IrcMessage{Args: []string{
"NICK", "CHANTYPES=#&", "CHANMODES=a,b,c,d",
}})
st, err = CreateStore(fakeCaps)
c.Check(st, IsNil)
c.Check(err, NotNil)
// Should die on creating ChannelFinder
fakeCaps = &irc.ProtoCaps{}
fakeCaps.ParseISupport(&irc.IrcMessage{Args: []string{
"NICK", "CHANTYPES=H", "PREFIX=(ov)@+", "CHANMODES=a,b,c,d",
}})
st, err = CreateStore(fakeCaps)
c.Check(st, IsNil)
c.Check(err, NotNil)
}
func (s *s) TestStore_UpdateProtoCaps(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
fakeCaps := &irc.ProtoCaps{}
fakeCaps.ParseISupport(&irc.IrcMessage{Args: []string{
"NICK", "CHANTYPES=!", "PREFIX=(q)@", "CHANMODES=,,,q",
}})
fakeCaps.ParseMyInfo(&irc.IrcMessage{Args: []string{
"irc.test.net", "test-12", "q", "abc",
}})
c.Assert(st.selfkinds.kinds['q'], Equals, 0)
c.Assert(st.kinds.kinds['q'], Equals, 0)
c.Assert(st.umodes.GetModeBit('q'), Equals, 0)
c.Assert(st.cfinder.IsChannel("!"), Equals, false)
st.Protocaps(fakeCaps)
c.Assert(st.selfkinds.kinds['q'], Not(Equals), 0)
c.Assert(st.kinds.kinds['q'], Not(Equals), 0)
c.Assert(st.umodes.GetModeBit('q'), Not(Equals), 0)
c.Assert(st.cfinder.IsChannel("!"), Equals, true)
}
func (s *s) TestStore_GetUser(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
c.Check(st.GetUser(users[0]), IsNil)
c.Check(st.GetUser(users[1]), IsNil)
st.addUser(users[0])
c.Check(st.GetUser(users[0]), NotNil)
c.Check(st.GetUser(users[1]), IsNil)
st.addUser(users[1])
c.Check(st.GetUser(users[0]), NotNil)
c.Check(st.GetUser(users[1]), NotNil)
st, err = CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
oldHost := "nick!<EMAIL>"
newHost := "nick!<EMAIL>"
st.addUser(oldHost)
c.Check(st.GetUser(oldHost).GetFullhost(), Equals, oldHost)
c.Check(st.GetUser(newHost).GetFullhost(), Not(Equals), newHost)
st.addUser(newHost)
c.Check(st.GetUser(oldHost).GetFullhost(), Not(Equals), oldHost)
c.Check(st.GetUser(newHost).GetFullhost(), Equals, newHost)
}
func (s *s) TestStore_GetChannel(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
c.Check(st.GetChannel(channels[0]), IsNil)
c.Check(st.GetChannel(channels[1]), IsNil)
st.addChannel(channels[0])
c.Check(st.GetChannel(channels[0]), NotNil)
c.Check(st.GetChannel(channels[1]), IsNil)
st.addChannel(channels[1])
c.Check(st.GetChannel(channels[0]), NotNil)
c.Check(st.GetChannel(channels[1]), NotNil)
}
func (s *s) TestStore_GetUsersChannelModes(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
st.addUser(users[0])
c.Check(st.GetUsersChannelModes(users[0], channels[0]), IsNil)
st.addChannel(channels[0])
c.Check(st.GetUsersChannelModes(users[0], channels[0]), IsNil)
st.addToChannel(users[0], channels[0])
c.Check(st.GetUsersChannelModes(users[0], channels[0]), NotNil)
}
func (s *s) TestStore_GetNUsers(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
c.Check(st.GetNUsers(), Equals, 0)
st.addUser(users[0])
st.addUser(users[0]) // Test that adding a user twice does nothing.
c.Check(st.GetNUsers(), Equals, 1)
st.addUser(users[1])
c.Check(st.GetNUsers(), Equals, 2)
}
func (s *s) TestStore_GetNChannels(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
c.Check(st.GetNChannels(), Equals, 0)
st.addChannel(channels[0])
st.addChannel(channels[0]) // Test that adding a channel twice does nothing.
c.Check(st.GetNChannels(), Equals, 1)
st.addChannel(channels[1])
c.Check(st.GetNChannels(), Equals, 2)
}
func (s *s) TestStore_GetNUserChans(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
c.Check(st.GetNUserChans(users[0]), Equals, 0)
c.Check(st.GetNUserChans(users[0]), Equals, 0)
st.addChannel(channels[0])
st.addChannel(channels[1])
c.Check(st.GetNUserChans(users[0]), Equals, 0)
c.Check(st.GetNUserChans(users[0]), Equals, 0)
st.addUser(users[0])
st.addUser(users[1])
st.addToChannel(users[0], channels[0])
st.addToChannel(users[0], channels[0]) // Test no duplicate adds.
st.addToChannel(users[0], channels[1])
st.addToChannel(users[1], channels[0])
c.Check(st.GetNUserChans(users[0]), Equals, 2)
c.Check(st.GetNUserChans(users[1]), Equals, 1)
}
func (s *s) TestStore_GetNChanUsers(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
c.Check(st.GetNChanUsers(channels[0]), Equals, 0)
c.Check(st.GetNChanUsers(channels[0]), Equals, 0)
st.addChannel(channels[0])
st.addChannel(channels[1])
c.Check(st.GetNChanUsers(channels[0]), Equals, 0)
c.Check(st.GetNChanUsers(channels[0]), Equals, 0)
st.addUser(users[0])
st.addUser(users[1])
st.addToChannel(users[0], channels[0])
st.addToChannel(users[0], channels[1])
st.addToChannel(users[1], channels[0])
c.Check(st.GetNChanUsers(channels[0]), Equals, 2)
c.Check(st.GetNChanUsers(channels[1]), Equals, 1)
}
func (s *s) TestStore_EachUser(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
st.addUser(users[0])
st.addUser(users[1])
i := 0
st.EachUser(func(u *User) {
c.Check(users[i], Equals, u.GetFullhost())
i++
})
c.Check(i, Equals, 2)
}
func (s *s) TestStore_EachChannel(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
st.addChannel(channels[0])
st.addChannel(channels[1])
i := 0
st.EachChannel(func(ch *Channel) {
c.Check(channels[i], Equals, ch.String())
i++
})
c.Check(i, Equals, 2)
}
func (s *s) TestStore_EachUserChan(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
st.addUser(users[0])
st.addChannel(channels[0])
st.addChannel(channels[1])
st.addToChannel(users[0], channels[0])
st.addToChannel(users[0], channels[1])
i := 0
st.EachUserChan(users[0], func(uc *UserChannel) {
c.Check(channels[i], Equals, uc.Channel.String())
i++
})
c.Check(i, Equals, 2)
}
func (s *s) TestStore_EachChanUser(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
st.addUser(users[0])
st.addUser(users[1])
st.addChannel(channels[0])
st.addToChannel(users[0], channels[0])
st.addToChannel(users[1], channels[0])
i := 0
st.EachChanUser(channels[0], func(cu *ChannelUser) {
c.Check(users[i], Equals, cu.User.GetFullhost())
i++
})
c.Check(i, Equals, 2)
}
func (s *s) TestStore_GetUsers(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
st.addUser(users[0])
st.addUser(users[1])
c.Check(len(st.GetUsers()), Equals, 2)
for i, user := range st.GetUsers() {
c.Check(users[i], Equals, user)
}
}
func (s *s) TestStore_GetChannels(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
st.addChannel(channels[0])
st.addChannel(channels[1])
c.Check(len(st.GetChannels()), Equals, 2)
for i, channel := range st.GetChannels() {
c.Check(channels[i], Equals, channel)
}
}
func (s *s) TestStore_GetUserChans(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
c.Check(st.GetUserChans(users[0]), IsNil)
st.addUser(users[0])
st.addChannel(channels[0])
st.addChannel(channels[1])
st.addToChannel(users[0], channels[0])
st.addToChannel(users[0], channels[1])
c.Check(len(st.GetUserChans(users[0])), Equals, 2)
for i, channel := range st.GetUserChans(users[0]) {
c.Check(channels[i], Equals, channel)
}
}
func (s *s) TestStore_GetChanUsers(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
c.Check(st.GetChanUsers(channels[0]), IsNil)
st.addUser(users[0])
st.addUser(users[1])
st.addChannel(channels[0])
st.addToChannel(users[0], channels[0])
st.addToChannel(users[1], channels[0])
c.Check(len(st.GetChanUsers(channels[0])), Equals, 2)
for i, user := range st.GetChanUsers(channels[0]) {
c.Check(users[i], Equals, user)
}
}
func (s *s) TestStore_IsOn(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
c.Check(st.IsOn(users[0], channels[0]), Equals, false)
st.addChannel(channels[0])
c.Check(st.IsOn(users[0], channels[0]), Equals, false)
st.addUser(users[0])
st.addToChannel(users[0], channels[0])
c.Check(st.IsOn(users[0], channels[0]), Equals, true)
}
func (s *s) TestStore_UpdateNick(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.NICK,
Sender: users[0],
Args: []string{nicks[1]},
}
st.addUser(users[0])
st.addChannel(channels[0])
st.addToChannel(users[0], channels[0])
c.Check(st.GetUser(users[0]), NotNil)
c.Check(st.GetUser(users[1]), IsNil)
c.Check(st.IsOn(users[0], channels[0]), Equals, true)
c.Check(st.IsOn(users[1], channels[0]), Equals, false)
st.Update(m)
c.Check(st.GetUser(users[0]), IsNil)
c.Check(st.GetUser(users[1]), NotNil)
c.Check(st.IsOn(users[0], channels[0]), Equals, false)
c.Check(st.IsOn(users[1], channels[0]), Equals, true)
m.Sender = users[0]
m.Args = []string{"newnick"}
st.Update(m)
c.Check(st.GetUser("newnick"), NotNil)
c.Check(st.GetUser(nicks[0]), IsNil)
}
func (s *s) TestStore_UpdateJoin(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.JOIN,
Sender: users[0],
Args: []string{channels[0]},
}
st.addChannel(channels[0])
c.Check(st.IsOn(users[0], channels[0]), Equals, false)
st.Update(m)
c.Check(st.IsOn(users[0], channels[0]), Equals, true)
st, _ = CreateStore(irc.CreateProtoCaps())
st.Self = self
st.addChannel(channels[0])
c.Check(st.IsOn(users[0], channels[0]), Equals, false)
st.Update(m)
c.Check(st.IsOn(users[0], channels[0]), Equals, true)
}
func (s *s) TestStore_UpdateJoinSelf(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.JOIN,
Sender: string(self.mask),
Args: []string{channels[0]},
}
c.Check(st.GetChannel(channels[0]), IsNil)
c.Check(st.IsOn(st.Self.GetNick(), channels[0]), Equals, false)
st.Update(m)
c.Check(st.GetChannel(channels[0]), NotNil)
c.Check(st.IsOn(st.Self.GetNick(), channels[0]), Equals, true)
}
func (s *s) TestStore_UpdatePart(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.PART,
Sender: users[0],
Args: []string{channels[0]},
}
st.addUser(users[0])
st.addUser(users[1])
// Test coverage, make sure adding to a channel that doesn't exist does
// nothing.
st.addToChannel(users[0], channels[0])
c.Check(st.IsOn(users[0], channels[0]), Equals, false)
st.addChannel(channels[0])
st.addChannel(channels[1])
st.addToChannel(users[0], channels[0])
st.addToChannel(users[1], channels[0])
st.addToChannel(users[0], channels[1])
c.Check(st.IsOn(users[0], channels[0]), Equals, true)
c.Check(st.IsOn(users[1], channels[0]), Equals, true)
c.Check(st.IsOn(users[0], channels[1]), Equals, true)
c.Check(st.IsOn(users[1], channels[1]), Equals, false)
st.Update(m)
c.Check(st.IsOn(users[0], channels[0]), Equals, false)
c.Check(st.IsOn(users[1], channels[0]), Equals, true)
c.Check(st.IsOn(users[0], channels[1]), Equals, true)
c.Check(st.IsOn(users[1], channels[1]), Equals, false)
m.Sender = users[1]
st.Update(m)
c.Check(st.IsOn(users[0], channels[0]), Equals, false)
c.Check(st.IsOn(users[1], channels[0]), Equals, false)
c.Check(st.IsOn(users[0], channels[1]), Equals, true)
c.Check(st.IsOn(users[1], channels[1]), Equals, false)
m.Sender = users[0]
m.Args[0] = channels[1]
st.Update(m)
c.Check(st.IsOn(users[0], channels[0]), Equals, false)
c.Check(st.IsOn(users[1], channels[0]), Equals, false)
c.Check(st.IsOn(users[0], channels[1]), Equals, false)
c.Check(st.IsOn(users[1], channels[1]), Equals, false)
}
func (s *s) TestStore_UpdatePartSelf(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.PART,
Sender: string(self.mask),
Args: []string{channels[0]},
}
st.addUser(users[0])
st.addUser(self.GetFullhost())
st.addChannel(channels[0])
st.addChannel(channels[1])
st.addToChannel(users[0], channels[0])
st.addToChannel(users[0], channels[1])
st.addToChannel(self.GetNick(), channels[0])
c.Check(st.IsOn(users[0], channels[0]), Equals, true)
c.Check(st.IsOn(users[0], channels[1]), Equals, true)
c.Check(st.IsOn(self.GetNick(), channels[0]), Equals, true)
st.Update(m)
c.Check(st.IsOn(users[0], channels[0]), Equals, false)
c.Check(st.IsOn(users[0], channels[1]), Equals, true)
c.Check(st.IsOn(self.GetNick(), channels[0]), Equals, false)
}
func (s *s) TestStore_UpdateQuit(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.QUIT,
Sender: users[0],
Args: []string{"quit message"},
}
// Test Quitting when we don't know the user
st.Update(m)
c.Check(st.GetUser(users[0]), IsNil)
st.addUser(users[0])
st.addUser(users[1])
st.addChannel(channels[0])
st.addToChannel(users[0], channels[0])
st.addToChannel(users[1], channels[0])
c.Check(st.IsOn(users[0], channels[0]), Equals, true)
c.Check(st.GetUser(users[0]), NotNil)
c.Check(st.IsOn(users[1], channels[0]), Equals, true)
c.Check(st.GetUser(users[1]), NotNil)
st.Update(m)
c.Check(st.IsOn(users[0], channels[0]), Equals, false)
c.Check(st.GetUser(users[0]), IsNil)
c.Check(st.IsOn(users[1], channels[0]), Equals, true)
c.Check(st.GetUser(users[1]), NotNil)
m.Sender = users[1]
st.Update(m)
c.Check(st.IsOn(users[1], channels[0]), Equals, false)
c.Check(st.GetUser(users[1]), IsNil)
}
func (s *s) TestStore_UpdateKick(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.KICK,
Sender: users[1],
Args: []string{channels[0], users[0]},
}
st.addUser(users[0])
st.addUser(users[1])
st.addChannel(channels[0])
st.addToChannel(users[0], channels[0])
c.Check(st.IsOn(users[0], channels[0]), Equals, true)
st.Update(m)
c.Check(st.IsOn(users[0], channels[0]), Equals, false)
}
func (s *s) TestStore_UpdateKickSelf(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.KICK,
Sender: users[1],
Args: []string{channels[0], st.Self.GetNick()},
}
st.addUser(st.Self.GetFullhost())
st.addChannel(channels[0])
st.addToChannel(users[0], channels[0])
c.Check(st.GetChannel(channels[0]), NotNil)
st.Update(m)
c.Check(st.GetChannel(channels[0]), IsNil)
}
func (s *s) TestStore_UpdateMode(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.MODE,
Sender: users[0],
Args: []string{channels[0],
"+ovmb-vn", nicks[0], nicks[0], "*!*mask", nicks[1],
},
}
fail := st.GetUsersChannelModes(users[0], channels[0])
c.Check(fail, IsNil)
st.addChannel(channels[0])
st.addUser(users[0])
st.addUser(users[1])
st.addToChannel(users[0], channels[0])
st.addToChannel(users[1], channels[0])
u1modes := st.GetUsersChannelModes(users[0], channels[0])
u2modes := st.GetUsersChannelModes(users[1], channels[0])
u2modes.SetMode('v')
st.GetChannel(channels[0]).Set("n")
c.Check(st.GetChannel(channels[0]).IsSet("n"), Equals, true)
c.Check(st.GetChannel(channels[0]).IsSet("mb"), Equals, false)
c.Check(u1modes.HasMode('o'), Equals, false)
c.Check(u1modes.HasMode('v'), Equals, false)
c.Check(u2modes.HasMode('v'), Equals, true)
st.Update(m)
c.Check(st.GetChannel(channels[0]).IsSet("n"), Equals, false)
c.Check(st.GetChannel(channels[0]).IsSet("mb *!*mask"), Equals, true)
c.Check(u1modes.HasMode('o'), Equals, true)
c.Check(u1modes.HasMode('v'), Equals, true)
c.Check(u2modes.HasMode('v'), Equals, false)
}
func (s *s) TestStore_UpdateModeSelf(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self.User = self.User
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.MODE,
Sender: self.GetFullhost(),
Args: []string{self.GetNick(), "+i-o"},
}
st.Self.Set("o")
c.Check(st.Self.IsSet("i"), Equals, false)
c.Check(st.Self.IsSet("o"), Equals, true)
st.Update(m)
c.Check(st.Self.IsSet("i"), Equals, true)
c.Check(st.Self.IsSet("o"), Equals, false)
}
func (s *s) TestStore_UpdateTopic(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.TOPIC,
Sender: users[1],
Args: []string{channels[0], "topic topic"},
}
st.addChannel(channels[0])
c.Check(st.GetChannel(channels[0]).GetTopic(), Equals, "")
st.Update(m)
c.Check(st.GetChannel(channels[0]).GetTopic(), Equals, "topic topic")
}
func (s *s) TestStore_UpdateRplTopic(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.RPL_TOPIC,
Sender: server,
Args: []string{self.GetNick(), channels[0], "topic topic"},
}
st.addChannel(channels[0])
c.Check(st.GetChannel(channels[0]).GetTopic(), Equals, "")
st.Update(m)
c.Check(st.GetChannel(channels[0]).GetTopic(), Equals, "topic topic")
}
func (s *s) TestStore_UpdatePrivmsg(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.PRIVMSG,
Sender: users[0],
Args: []string{channels[0]},
}
st.addChannel(channels[0])
c.Check(st.GetUser(users[0]), IsNil)
c.Check(st.GetUsersChannelModes(users[0], channels[0]), IsNil)
st.Update(m)
c.Check(st.GetUser(users[0]), NotNil)
c.Check(st.GetUsersChannelModes(users[0], channels[0]), NotNil)
m.Sender = server
size := len(st.users)
st.Update(m)
c.Check(len(st.users), Equals, size)
}
func (s *s) TestStore_UpdateNotice(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.NOTICE,
Sender: users[0],
Args: []string{channels[0]},
}
st.addChannel(channels[0])
c.Check(st.GetUser(users[0]), IsNil)
c.Check(st.GetUsersChannelModes(users[0], channels[0]), IsNil)
st.Update(m)
c.Check(st.GetUser(users[0]), NotNil)
c.Check(st.GetUsersChannelModes(users[0], channels[0]), NotNil)
m.Sender = server
size := len(st.users)
st.Update(m)
c.Check(len(st.users), Equals, size)
}
func (s *s) TestStore_UpdateWelcome(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.RPL_WELCOME,
Sender: server,
Args: []string{nicks[1], "Welcome to"},
}
st.Update(m)
c.Check(st.Self.GetFullhost(), Equals, nicks[1])
c.Check(st.users[nicks[1]].GetFullhost(), Equals, st.Self.GetFullhost())
m = &irc.IrcMessage{
Name: irc.RPL_WELCOME,
Sender: server,
Args: []string{nicks[1], "Welcome to " + users[1]},
}
st.Update(m)
c.Check(st.Self.GetFullhost(), Equals, users[1])
c.Check(st.users[nicks[1]].GetFullhost(), Equals, st.Self.GetFullhost())
}
func (s *s) TestStore_UpdateRplNamereply(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.RPL_NAMREPLY,
Sender: server,
Args: []string{
self.GetNick(), "=", channels[0],
"@" + nicks[0] + " +" + nicks[1] + " " + self.GetNick(),
},
}
st.addChannel(channels[0])
c.Check(st.GetUsersChannelModes(users[0], channels[0]), IsNil)
c.Check(st.GetUsersChannelModes(users[1], channels[0]), IsNil)
c.Check(st.GetUsersChannelModes(self.GetNick(), channels[0]), IsNil)
st.Update(m)
c.Check(
st.GetUsersChannelModes(users[0], channels[0]).String(), Equals, "o")
c.Check(
st.GetUsersChannelModes(users[1], channels[0]).String(), Equals, "v")
c.Check(st.GetUsersChannelModes(
self.GetNick(), channels[0]).String(), Equals, "")
}
func (s *s) TestStore_RplWhoReply(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.RPL_WHOREPLY,
Sender: server,
Args: []string{
self.GetNick(), channels[0], irc.Mask(users[0]).GetUsername(),
irc.Mask(users[0]).GetHost(), "*.server.net", nicks[0], "Hx@d",
"3 real name",
},
}
st.addChannel(channels[0])
c.Check(st.GetUser(users[0]), IsNil)
c.Check(st.GetUsersChannelModes(users[0], channels[0]), IsNil)
st.Update(m)
c.Check(st.GetUser(users[0]), NotNil)
c.Check(st.GetUser(users[0]).GetFullhost(), Equals, users[0])
c.Check(st.GetUser(users[0]).GetRealname(), Equals, "real name")
c.Check(
st.GetUsersChannelModes(users[0], channels[0]).String(), Equals, "o")
}
func (s *s) TestStore_UpdateRplMode(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.RPL_CHANNELMODEIS,
Sender: server,
Args: []string{self.GetNick(), channels[0], "+ntzl", "10"},
}
st.addChannel(channels[0])
c.Check(st.GetChannel(channels[0]).IsSet("ntzl 10"), Equals, false)
st.Update(m)
c.Check(st.GetChannel(channels[0]).IsSet("ntzl 10"), Equals, true)
}
func (s *s) TestStore_UpdateRplBanlist(c *C) {
st, err := CreateStore(irc.CreateProtoCaps())
st.Self = self
c.Check(err, IsNil)
m := &irc.IrcMessage{
Name: irc.RPL_BANLIST,
Sender: server,
Args: []string{self.GetNick(), channels[0], nicks[0] + "!*@*", nicks[1],
"1367197165"},
}
st.addChannel(channels[0])
c.Check(st.GetChannel(channels[0]).HasBan(nicks[0]+"!*@*"), Equals, false)
st.Update(m)
c.Check(st.GetChannel(channels[0]).HasBan(nicks[0]+"!*@*"), Equals, true)
}
<file_sep>/irc/mask.go
package irc
import (
"strings"
)
// Mask is a type that represents an irc hostmask. nickname!mask@hostname
type Mask string
// WildMask is an irc hostmask that contains wildcard characters ? and *
type WildMask string
func (w WildMask) Match(m Mask) bool {
ws, ms := string(w), string(m)
wl, ml := len(ws), len(ms)
if wl == 0 {
return ml == 0
}
var i, j, consume = 0, 0, 0
for i < wl && j < ml {
switch ws[i] {
case '?', '*':
star := false
consume = 0
for i < wl && (ws[i] == '*' || ws[i] == '?') {
star = star || ws[i] == '*'
i++
consume++
}
if star {
consume = -1
}
case ms[j]:
consume = 0
i++
j++
default:
if consume != 0 {
consume--
j++
} else {
return false
}
}
}
for i < wl && (ws[i] == '?' || ws[i] == '*') {
i++
}
if consume < 0 {
consume = ml - j
}
j += consume
if i < wl || j < ml {
return false
}
return true
}
// GetNick returns the nick of this mask.
func (m Mask) GetNick() string {
nick := string(m)
index := strings.IndexAny(nick, "!@")
if index >= 0 {
return nick[:index]
}
return nick
}
// GetUser returns the maskname of this mask.
func (m Mask) GetUsername() string {
_, mask, _ := m.SplitFullhost()
return mask
}
// GetHost returns the host of this mask.
func (m Mask) GetHost() string {
_, _, host := m.SplitFullhost()
return host
}
// GetFullhost returns the fullhost of this mask.
func (m Mask) GetFullhost() string {
return string(m)
}
func (m Mask) SplitFullhost() (nick, user, host string) {
fullhost := string(m)
if len(fullhost) == 0 {
return
}
userIndex := strings.IndexRune(fullhost, '!')
hostIndex := strings.IndexRune(fullhost, '@')
if userIndex <= 0 || hostIndex <= 0 || hostIndex < userIndex {
min := len(fullhost)
if userIndex < min && userIndex > 0 {
min = userIndex
}
if hostIndex < min && hostIndex > 0 {
min = hostIndex
}
nick = fullhost[:min]
return
}
nick = fullhost[:userIndex]
user = fullhost[userIndex+1 : hostIndex]
host = fullhost[hostIndex+1:]
return
}
<file_sep>/irc/common_test.go
package irc
import (
"bytes"
"fmt"
. "launchpad.net/gocheck"
"strings"
"testing"
)
func Test(t *testing.T) { TestingT(t) } //Hook into testing package
type s struct{}
var _ = Suite(&s{})
func (s *s) TestIrcMessage_Test(c *C) {
args := []string{"#chan1", "#chan2"}
msg := IrcMessage{
Args: []string{strings.Join(args, ",")},
}
for i, v := range msg.Split(0) {
c.Check(args[i], Equals, v)
}
}
func (s *s) TestMsgTypes_Privmsg(c *C) {
args := []string{"#chan", "msg arg"}
pmsg := &Message{&IrcMessage{
Name: PRIVMSG,
Args: args,
Sender: "<EMAIL>",
}}
c.Check(pmsg.Target(), Equals, args[0])
c.Check(pmsg.Message(), Equals, args[1])
}
func (s *s) TestMsgTypes_Notice(c *C) {
args := []string{"#chan", "msg arg"}
notice := &Message{&IrcMessage{
Name: NOTICE,
Args: args,
Sender: "<EMAIL>",
}}
c.Check(notice.Target(), Equals, args[0])
c.Check(notice.Message(), Equals, args[1])
}
type fakeHelper struct {
*Helper
}
func (f *fakeHelper) GetKey() string {
return ""
}
func (s *s) TestHelper_Send(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
format := "PRIVMSG %v :%v"
target := "#chan"
msg := "msg"
h.Send(format, target, msg)
c.Check(string(buf.Bytes()), Equals, fmt.Sprint(format, target, msg))
}
func (s *s) TestHelper_Sendln(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
header := "PRIVMSG"
target := "#chan"
msg := "msg"
h.Sendln(header, target, msg)
expect := fmt.Sprintln(header, target, msg)
c.Check(string(buf.Bytes()), Equals, expect[:len(expect)-1])
}
func (s *s) TestHelper_Sendf(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
format := "PRIVMSG %v :%v"
target := "#chan"
msg := "msg"
h.Sendf(format, target, msg)
c.Check(string(buf.Bytes()), Equals, fmt.Sprintf(format, target, msg))
}
func (s *s) TestHelper_Privmsg(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
ch := "#chan"
s1, s2 := "string1", "string2"
h.Privmsg(ch, s1, s2)
c.Check(string(buf.Bytes()), Equals, fmt.Sprintf("%v %v :%v",
PRIVMSG, ch, fmt.Sprint(s1, s2)))
}
func (s *s) TestHelper_Privmsgln(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
ch := "#chan"
s1, s2 := "string1", "string2"
expect := fmt.Sprintln(s1, s2)
h.Privmsgln(ch, s1, s2)
c.Check(string(buf.Bytes()), Equals, fmt.Sprintf("%v %v :%v",
PRIVMSG, ch, expect[:len(expect)-1]))
}
func (s *s) TestHelper_Privmsgf(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
ch := "#chan"
format := "%v - %v"
s1, s2 := "string1", "string2"
h.Privmsgf(ch, format, s1, s2)
c.Check(string(buf.Bytes()), Equals, fmt.Sprintf("%v %v :%v",
PRIVMSG, ch, fmt.Sprintf(format, s1, s2)))
}
func (s *s) TestHelper_Notice(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
ch := "#chan"
s1, s2 := "string1", "string2"
h.Notice(ch, s1, s2)
c.Check(string(buf.Bytes()), Equals, fmt.Sprintf("%v %v :%v",
NOTICE, ch, fmt.Sprint(s1, s2)))
}
func (s *s) TestHelper_Noticeln(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
ch := "#chan"
s1, s2 := "string1", "string2"
expect := fmt.Sprintln(s1, s2)
h.Noticeln(ch, s1, s2)
c.Check(string(buf.Bytes()), Equals, fmt.Sprintf("%v %v :%v",
NOTICE, ch, expect[:len(expect)-1]))
}
func (s *s) TestHelper_Noticef(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
ch := "#chan"
format := "%v - %v"
s1, s2 := "string1", "string2"
h.Noticef(ch, format, s1, s2)
c.Check(string(buf.Bytes()), Equals, fmt.Sprintf("%v %v :%v",
NOTICE, ch, fmt.Sprintf(format, s1, s2)))
}
func (s *s) TestHelper_Join(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
ch := "#chan"
h.Join()
c.Check(buf.Len(), Equals, 0)
h.Join(ch)
c.Check(string(buf.Bytes()), Equals, fmt.Sprintf("%v :%v", JOIN, ch))
buf = bytes.Buffer{}
h.Writer = &buf
h.Join(ch, ch)
c.Check(string(buf.Bytes()), Equals, fmt.Sprintf("%v :%v,%v", JOIN, ch, ch))
}
func (s *s) TestHelper_Part(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
ch := "#chan"
h.Part()
c.Check(buf.Len(), Equals, 0)
h.Part(ch)
c.Check(string(buf.Bytes()), Equals, fmt.Sprintf("%v :%v", PART, ch))
buf = bytes.Buffer{}
h.Writer = &buf
h.Part(ch, ch)
c.Check(string(buf.Bytes()), Equals, fmt.Sprintf("%v :%v,%v", PART, ch, ch))
}
func (s *s) TestHelper_Quit(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
msg := "quitting"
h.Quit(msg)
c.Check(string(buf.Bytes()), Equals, fmt.Sprintf("%v :%v", QUIT, msg))
}
func (s *s) TestHelper_splitSend(c *C) {
buf := bytes.Buffer{}
h := &Helper{&buf}
header := "PRIVMSG #chan :"
s0 := "message"
h.splitSend([]byte(header), []byte(s0))
c.Check(buf.Len(), Equals, len(header)+len(s0))
buf = bytes.Buffer{}
h = &Helper{&buf}
header = "PRIVMSG #chan :"
s1 := strings.Repeat("a", 510)
s2 := strings.Repeat("b", 510)
s3 := strings.Repeat("c", 200)
err := h.splitSend([]byte(header), []byte(s1+s2+s3))
c.Check(err, IsNil)
c.Check(buf.Len(), Equals, len(header)*3+len(s1)+len(s2)+len(s3))
}
<file_sep>/irc/channelfinder.go
package irc
import "regexp"
const (
// nStringsAssumed is the number of channels assumed to be in each irc
// message if this number is too small, there could be memory thrashing
// due to append
nChannelsAssumed = 1
)
// ChannelFinder stores a cached regexp generated by CreateChannelFinder in
// order to scan a string for potential channel entries.
type ChannelFinder struct {
channelRegexp *regexp.Regexp
}
// CreateChannelFinder safely builds a regex from the Chantypes that are passed
// in. For flexibility it can be initialized with a string, but ideally
// ProtoCaps.Chantypes parsed from the server's message will be used.
func CreateChannelFinder(types string) (*ChannelFinder, error) {
c := &ChannelFinder{}
safetypes := ""
for _, c := range types {
safetypes += string(`\`) + string(c)
}
regex, err := regexp.Compile(`[` + safetypes + `][^\s,]*`)
if err == nil {
c.channelRegexp = regex
return c, nil
}
return nil, err
}
// FindChannels retrieves all the channels in the string using a cached regex.
// Calls to this will fail if the ChannelFinder was not initialized with
// CreateChannelFinder
func (c *ChannelFinder) FindChannels(str string) []string {
channels := make([]string, 0, nChannelsAssumed)
for _, v := range c.channelRegexp.FindAllString(str, -1) {
channels = append(channels, v)
}
return channels
}
// IsChannel tests a string with the cached regex to determine whether or not
// it's a valid channel. The regex must first be created with
// CreateChannelFinder
func (c *ChannelFinder) IsChannel(msg string) bool {
return c.channelRegexp.MatchString(msg)
}
<file_sep>/data/user.go
package data
import (
"github.com/aarondl/ultimateq/irc"
)
// User encapsulates all the data associated with a user.
type User struct {
mask irc.Mask
name string
}
// CreateUser creates a user object from a nickname or fullhost.
func CreateUser(nickorhost string) *User {
if len(nickorhost) == 0 {
return nil
}
u := &User{}
u.mask = irc.Mask(nickorhost)
return u
}
// GetNick returns the nick of this user.
func (u *User) GetNick() string {
return u.mask.GetNick()
}
// GetUser returns the username of this user.
func (u *User) GetUsername() string {
return u.mask.GetUsername()
}
// GetHost returns the host of this user.
func (u *User) GetHost() string {
return u.mask.GetHost()
}
// GetFullhost returns the fullhost of this user.
func (u *User) GetFullhost() string {
return u.mask.GetFullhost()
}
// Realname sets the real name of this user.
func (u *User) Realname(realname string) {
u.name = realname
}
// GetRealname returns the real name of this user.
func (u *User) GetRealname() string {
return u.name
}
// String returns a one-line representation of this user.
func (u *User) String() string {
str := u.mask.GetNick()
if fh := u.mask.GetFullhost(); len(fh) > 0 && str != fh {
str += " " + fh
}
if len(u.name) > 0 {
str += " " + u.name
}
return str
}
<file_sep>/bot/server.go
package bot
import (
"errors"
"fmt"
"github.com/aarondl/ultimateq/config"
"github.com/aarondl/ultimateq/data"
"github.com/aarondl/ultimateq/dispatch"
"github.com/aarondl/ultimateq/inet"
"github.com/aarondl/ultimateq/irc"
"net"
"strconv"
"sync"
"time"
)
// Server States
const (
STATE_NEW = 0x0
STATE_CONNECTED = 0x1
STATE_READING = 0x2
STATE_WRITING = 0x4
STATE_RECONNECTING = 0x8
MASK_STARTED = STATE_READING | STATE_WRITING
)
const (
// errServerAlreadyConnected occurs if a server has not been shutdown
// before another attempt to connect to it is made.
errFmtAlreadyConnected = "bot: %v already connected.\n"
)
var (
// errNotConnected happens when a write occurs to a disconnected server.
errNotConnected = errors.New("bot: Server not connected")
// temporary error until ssl is fixed.
errSslNotImplemented = errors.New("bot: Ssl not implemented")
)
// Server is all the details around a specific server connection. Also contains
// the connection and configuration for the specific server.
type Server struct {
bot *Bot
name string
state int
dispatcher *dispatch.Dispatcher
client *inet.IrcClient
conf *config.Server
caps *irc.ProtoCaps
store *data.Store
reconnScale time.Duration
killdispatch chan int
killreconn chan int
handlerId int
handler *coreHandler
// protects client reading/writing
protect sync.RWMutex
// protects the caps from reading and writing.
protectCaps sync.RWMutex
// protects the store from reading and writing.
protectStore sync.RWMutex
}
// ServerEndpoint implements the Endpoint interface.
type ServerEndpoint struct {
*irc.Helper
server *Server
}
// createServerEndpoint creates a ServerEndpoint with a helper.
func createServerEndpoint(srv *Server) *ServerEndpoint {
return &ServerEndpoint{&irc.Helper{srv}, srv}
}
// GetKey returns the server id of the current server.
func (s *ServerEndpoint) GetKey() string {
return s.server.name
}
// OpenStore calls a callback if this ServerEndpoint can present a data store
// object. The returned boolean is whether or not the function was called.
func (s *ServerEndpoint) OpenStore(fn func(*data.Store)) bool {
if s.server.store != nil {
s.server.protectStore.RLock()
fn(s.server.store)
s.server.protectStore.RUnlock()
return true
} else {
return false
}
}
// Writeln writes to the server's IrcClient.
func (s *Server) Writeln(args ...interface{}) error {
_, err := s.Write([]byte(fmt.Sprint(args...)))
return err
}
// Write writes to the server's IrcClient.
func (s *Server) Write(buf []byte) (int, error) {
s.protect.RLock()
defer s.protect.RUnlock()
if s.isConnected() {
return s.client.Write(buf)
}
return 0, errNotConnected
}
// createDispatcher uses the server's current ProtoCaps to create a dispatcher.
func (s *Server) createDispatcher(channels []string) (err error) {
s.dispatcher, err = dispatch.CreateRichDispatcher(s.caps, channels)
return err
}
// createStore uses the server's current ProtoCaps to create a store.
func (s *Server) createStore() (err error) {
s.store, err = data.CreateStore(s.caps)
return err
}
// createIrcClient connects to the configured server, and creates an IrcClient
// for use with that connection.
func (s *Server) createIrcClient() error {
var conn net.Conn
var err error
if s.client != nil {
return errors.New(fmt.Sprintf(errFmtAlreadyConnected, s.name))
}
port := strconv.Itoa(int(s.conf.GetPort()))
server := s.conf.GetHost() + ":" + port
if s.bot.connProvider == nil {
if s.conf.GetSsl() {
//TODO: Implement SSL
return errSslNotImplemented
} else {
if conn, err = net.Dial("tcp", server); err != nil {
return err
}
}
} else {
if conn, err = s.bot.connProvider(server); err != nil {
return err
}
}
s.client = inet.CreateIrcClientFloodProtect(conn, s.name,
int(s.conf.GetFloodProtectBurst()),
int(s.conf.GetFloodProtectTimeout()*1000.0),
int(s.conf.GetFloodProtectStep()*1000.0),
time.Millisecond)
return nil
}
// protocaps sets the protocaps for the given server. If an error is returned
// no update was done.
func (s *Server) protocaps(caps *irc.ProtoCaps) error {
tmp := *caps
s.protectCaps.Lock()
s.caps = &tmp
s.protectCaps.Unlock()
return s.rehashProtocaps()
}
// rehashProtocaps rehashes protocaps from the servers current protocaps.
func (s *Server) rehashProtocaps() error {
var err error
if err = s.dispatcher.Protocaps(s.caps); err != nil {
return err
}
s.protectStore.Lock()
if s.store != nil {
err = s.store.Protocaps(s.caps)
if err != nil {
return err
}
}
s.protectStore.Unlock()
return nil
}
// IsConnected checks to see if the server is connected.
func (s *Server) IsConnected() bool {
s.protect.RLock()
defer s.protect.RUnlock()
return s.isConnected()
}
// isConnected checks to see if the server is connected without locking
func (s *Server) isConnected() bool {
return STATE_CONNECTED == s.state&STATE_CONNECTED
}
// setConnected sets the server's connected flag.
func (s *Server) setConnected(value, lock bool) {
if lock {
s.protect.Lock()
defer s.protect.Unlock()
}
if value {
s.state |= STATE_CONNECTED
} else {
s.state &= ^STATE_CONNECTED
}
}
// IsStarted checks to see if the the server is currently reading or writing.
func (s *Server) IsStarted() bool {
s.protect.RLock()
defer s.protect.RUnlock()
return s.isStarted()
}
// isStarted checks to see if the the server is currently reading or writing
// without locking.
func (s *Server) isStarted() bool {
return 0 != s.state&MASK_STARTED
}
// setStarted sets the server's reading and writing flags simultaneously.
func (s *Server) setStarted(value, lock bool) {
if lock {
s.protect.Lock()
defer s.protect.Unlock()
}
if value {
s.state |= MASK_STARTED
} else {
s.state &= ^MASK_STARTED
}
}
// IsReading checks to see if the dispatcher read-loop is running on the server.
func (s *Server) IsReading() bool {
s.protect.RLock()
defer s.protect.RUnlock()
return s.isReading()
}
// isReading checks to see if the dispatcher read-loop is running on the server
// without locking.
func (s *Server) isReading() bool {
return STATE_READING == s.state&STATE_READING
}
// setReading sets the server's reading flag.
func (s *Server) setReading(value, lock bool) {
if lock {
s.protect.Lock()
defer s.protect.Unlock()
}
if value {
s.state |= STATE_READING
} else {
s.state &= ^STATE_READING
}
}
// IsWriting checks to see if the server's write loop has been activated.
func (s *Server) IsWriting() bool {
s.protect.RLock()
defer s.protect.RUnlock()
return s.isWriting()
}
// isWriting checks to see if the server's write loop has been activated without
// locking.
func (s *Server) isWriting() bool {
return STATE_WRITING == s.state&STATE_WRITING
}
// setWriting sets the server's writing flag.
func (s *Server) setWriting(value, lock bool) {
if lock {
s.protect.Lock()
defer s.protect.Unlock()
}
if value {
s.state |= STATE_WRITING
} else {
s.state &= ^STATE_WRITING
}
}
// IsReconnecting checks to see if the dispatcher is waiting to reconnect the
// server.
func (s *Server) IsReconnecting() bool {
s.protect.RLock()
defer s.protect.RUnlock()
return s.isReconnecting()
}
// isReconnecting checks to see if the dispatcher is waiting to reconnect the
// without locking.
func (s *Server) isReconnecting() bool {
return STATE_RECONNECTING == s.state&STATE_RECONNECTING
}
// setStarted sets the server's reconnecting flag.
func (s *Server) setReconnecting(value, lock bool) {
if lock {
s.protect.Lock()
defer s.protect.Unlock()
}
if value {
s.state |= STATE_RECONNECTING
} else {
s.state &= ^STATE_RECONNECTING
}
}
<file_sep>/bot/botconfig_test.go
package bot
import (
"bytes"
"github.com/aarondl/ultimateq/config"
"github.com/aarondl/ultimateq/irc"
"github.com/aarondl/ultimateq/mocks"
"io"
. "launchpad.net/gocheck"
"net"
)
var zeroConnProvider = func(srv string) (net.Conn, error) {
return nil, nil
}
func (s *s) TestBot_ReadConfig(c *C) {
b, err := createBot(fakeConfig, nil, nil, false)
c.Check(err, IsNil)
b.ReadConfig(func(conf *config.Config) {
c.Check(
conf.Servers[serverId].GetNick(),
Equals,
fakeConfig.Servers[serverId].GetNick(),
)
})
}
func (s *s) TestBot_WriteConfig(c *C) {
b, err := createBot(fakeConfig, nil, nil, false)
c.Check(err, IsNil)
b.WriteConfig(func(conf *config.Config) {
c.Check(
conf.Servers[serverId].GetNick(),
Equals,
fakeConfig.Servers[serverId].GetNick(),
)
})
}
func (s *s) TestBot_ReplaceConfig(c *C) {
nick := []byte(irc.NICK + " :newnick\r\n")
conns := make(map[string]*mocks.Conn)
connProvider := func(srv string) (net.Conn, error) {
conn := mocks.CreateConn()
conns[srv[:len(srv)-5]] = conn //Remove port
return conn, nil
}
chans1 := []string{"#chan1", "#chan2", "#chan3"}
chans2 := []string{"#chan1", "#chan3"}
chans3 := []string{"#chan1"}
c1 := fakeConfig.Clone().
GlobalContext().
Channels(chans1...).
Server("newserver")
c2 := fakeConfig.Clone().
GlobalContext().
NoState(true).
Channels(chans2...).
ServerContext(serverId).
Nick("newnick").
Channels(chans3...).
Server("anothernewserver")
c3 := &config.Config{}
b, err := createBot(c1, nil, connProvider, false)
c.Check(err, IsNil)
c.Check(len(b.servers), Equals, 2)
oldsrv1, oldsrv2 := b.servers[serverId], b.servers["newserver"]
errs := b.Connect()
c.Check(len(errs), Equals, 0)
b.start(true, false)
c.Check(elementsEquals(b.conf.Global.Channels, chans1), Equals, true)
c.Check(elementsEquals(oldsrv1.conf.GetChannels(), chans1), Equals, true)
c.Check(elementsEquals(oldsrv2.conf.GetChannels(), chans1), Equals, true)
c.Check(elementsEquals(b.dispatcher.GetChannels(), chans1), Equals, true)
c.Check(elementsEquals(oldsrv1.dispatcher.GetChannels(), chans1),
Equals, true)
c.Check(elementsEquals(oldsrv2.dispatcher.GetChannels(), chans1),
Equals, true)
c.Check(oldsrv1.store, NotNil)
servers := b.ReplaceConfig(c3) // Invalid Config
c.Check(len(servers), Equals, 0)
servers = b.ReplaceConfig(c2)
c.Check(len(servers), Equals, 1)
c.Check(len(b.servers), Equals, 2)
c.Check(elementsEquals(b.conf.Global.Channels, chans2), Equals, true)
c.Check(elementsEquals(oldsrv1.conf.GetChannels(), chans3), Equals, true)
c.Check(elementsEquals(servers[0].server.conf.GetChannels(), chans2),
Equals, true)
c.Check(elementsEquals(b.dispatcher.GetChannels(), chans2), Equals, true)
c.Check(elementsEquals(oldsrv1.dispatcher.GetChannels(), chans3),
Equals, true)
c.Check(elementsEquals(servers[0].server.dispatcher.GetChannels(), chans2),
Equals, true)
c.Check(oldsrv1.store, IsNil)
c.Check(servers[0].Err, IsNil)
c.Check(servers[0].ServerName, Equals, "anothernewserver")
c.Check(
bytes.Compare(conns[serverId].Receive(len(nick), nil), nick),
Equals,
0,
)
server := servers[0].server
c.Check(server, NotNil)
errs = b.Connect()
c.Check(len(errs), Equals, 2)
c.Check(errs[0].Error(), Matches, ".*already connected.\n")
c.Check(oldsrv1.IsConnected(), Equals, true)
c.Check(server.IsConnected(), Equals, true)
conns["anothernewserver"].Send([]byte{}, 0, io.EOF)
b.Stop()
b.Disconnect()
b.WaitForHalt()
}
func (s *s) TestBot_testElementEquals(c *C) {
a := []string{"a", "b"}
b := []string{"b", "a"}
c.Check(elementsEquals(a, b), Equals, true)
a = []string{"a", "b", "c"}
c.Check(elementsEquals(a, b), Equals, false)
a = []string{"x", "y"}
c.Check(elementsEquals(a, b), Equals, false)
a = []string{}
b = []string{}
c.Check(elementsEquals(a, b), Equals, true)
b = []string{"a"}
c.Check(elementsEquals(a, b), Equals, false)
a = []string{"a"}
b = []string{}
c.Check(elementsEquals(a, b), Equals, false)
}
<file_sep>/bot/botconfig.go
package bot
import (
"github.com/aarondl/ultimateq/config"
"github.com/aarondl/ultimateq/irc"
)
type configCallback func(*config.Config)
type NewServer struct {
ServerName string
server *Server
Err error
}
// ReadConfig opens the config for reading, for the duration of the callback
// the config is synchronized.
func (b *Bot) ReadConfig(fn configCallback) {
b.configsProtect.RLock()
defer b.configsProtect.RUnlock()
fn(b.conf)
}
// WriteConfig opens the config for writing, for the duration of the callback
// the config is synchronized.
func (b *Bot) WriteConfig(fn configCallback) {
b.configsProtect.Lock()
defer b.configsProtect.Unlock()
fn(b.conf)
}
// ReplaceConfig replaces the current configuration for the bot. Running
// servers not present in the new config will be shut down immediately, while
// new servers will be connected to any ready to start. Updates active channels
// for all dispatchers as well as sends nick messages to the servers with
// updates for nicknames.
func (b *Bot) ReplaceConfig(newConfig *config.Config) []NewServer {
if !newConfig.IsValid() {
return nil
}
servers := make([]NewServer, 0)
b.serversProtect.Lock()
b.configsProtect.Lock()
defer b.serversProtect.Unlock() // LIFO
defer b.configsProtect.Unlock()
for k, s := range b.servers {
if serverConf := newConfig.GetServer(k); nil == serverConf {
b.stopServer(s)
b.disconnectServer(s)
delete(b.servers, k)
} else {
setNick := s.conf.GetNick() != serverConf.GetNick()
setChannels :=
!elementsEquals(s.conf.GetChannels(), serverConf.GetChannels())
if !s.conf.GetNoState() && serverConf.GetNoState() {
s.protectStore.Lock()
s.store = nil
s.protectStore.Unlock()
}
s.conf = serverConf
if setNick {
s.Writeln(irc.NICK + " :" + s.conf.GetNick())
}
if setChannels {
s.dispatcher.Channels(s.conf.GetChannels())
}
}
}
if !elementsEquals(b.conf.Global.GetChannels(),
newConfig.Global.GetChannels()) {
b.dispatcher.Channels(newConfig.Global.GetChannels())
}
for k, s := range newConfig.Servers {
if serverConf := b.conf.GetServer(k); nil == serverConf {
server, err := b.createServer(s)
b.servers[k] = server
if err == nil {
err = b.connectServer(server)
if err == nil {
b.startServer(server, true, true)
}
}
servers = append(servers, NewServer{k, server, err})
}
}
b.conf = newConfig
return servers
}
// Rehash loads the config from a file. It attempts to use the previously read
// config file name if loaded from a file... If not it will use a default file
// name. It then calls Bot.ReplaceConfig.
func (b *Bot) Rehash() error {
b.configsProtect.RLock()
name := b.conf.GetFilename()
b.configsProtect.RUnlock()
conf := config.CreateConfigFromFile(name)
if !CheckConfig(conf) {
return errInvalidConfig
}
b.ReplaceConfig(conf)
return nil
}
// DumpConfig dumps the config to a file. It attempts to use the previously read
// config file name if loaded from a file... If not it will use a default file
// name.
func (b *Bot) DumpConfig() (err error) {
b.configsProtect.RLock()
defer b.configsProtect.RUnlock()
err = config.FlushConfigToFile(b.conf, b.conf.GetFilename())
return
}
// elementsEquals checks that the string arrays contain the same elements.
func elementsEquals(a, b []string) bool {
lena, lenb := len(a), len(b)
if lena != lenb {
return false
}
for i := 0; i < lena; i++ {
j := 0
for ; j < lenb; j++ {
if a[i] == b[j] {
break
}
}
if j >= lenb {
return false
}
}
return true
}
<file_sep>/bot/bot_test.go
package bot
import (
"github.com/aarondl/ultimateq/config"
"github.com/aarondl/ultimateq/irc"
"github.com/aarondl/ultimateq/mocks"
"io"
. "launchpad.net/gocheck"
"log"
"net"
"os"
"sync"
"testing"
"time"
)
func Test(t *testing.T) { TestingT(t) } //Hook into testing package
type s struct{}
var _ = Suite(&s{})
type testHandler struct {
callback func(*irc.IrcMessage, irc.Endpoint)
}
func (h testHandler) HandleRaw(m *irc.IrcMessage, send irc.Endpoint) {
if h.callback != nil {
h.callback(m, send)
}
}
func init() {
f, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
if err != nil {
log.Println("Could not set logger:", err)
} else {
log.SetOutput(f)
}
}
var serverId = "irc.gamesurge.net"
var fakeConfig = Configure().
Nick("nobody").
Altnick("nobody1").
Username("nobody").
Userhost("bitforge.ca").
Realname("ultimateq").
NoReconnect(true).
Ssl(true).
Server(serverId)
//==================================
// Tests begin
//==================================
func (s *s) TestCreateBot(c *C) {
bot, err := CreateBot(fakeConfig)
c.Check(bot, NotNil)
c.Check(err, IsNil)
_, err = CreateBot(Configure())
c.Check(err, Equals, errInvalidConfig)
_, err = CreateBot(ConfigureFunction(
func(conf *config.Config) *config.Config {
return fakeConfig
}),
)
c.Check(err, IsNil)
}
func (s *s) TestBot_StartStop(c *C) {
conn := mocks.CreateConn()
connProvider := func(srv string) (net.Conn, error) {
return conn, nil
}
b, err := createBot(fakeConfig, nil, connProvider, false)
c.Check(err, IsNil)
ers := b.Connect()
c.Check(len(ers), Equals, 0)
b.Start()
b.Start() // This shouldn't do anything, test cov
conn.Send([]byte{}, 0, io.EOF)
b.Stop()
b.Disconnect()
b.WaitForHalt()
}
func (s *s) TestBot_StartStopServer(c *C) {
conn := mocks.CreateConn()
connProvider := func(srv string) (net.Conn, error) {
return conn, nil
}
b, err := createBot(fakeConfig, nil, connProvider, false)
c.Check(err, IsNil)
srv := b.servers[serverId]
c.Check(srv.IsStarted(), Equals, false)
c.Check(srv.IsConnected(), Equals, false)
_, err = b.ConnectServer(serverId)
c.Check(err, IsNil)
c.Check(srv.IsConnected(), Equals, true)
_, err = b.ConnectServer(serverId)
c.Check(err, NotNil)
b.StartServer(serverId)
c.Check(srv.IsStarted(), Equals, true)
c.Check(srv.IsReading(), Equals, true)
c.Check(srv.IsWriting(), Equals, true)
b.StopServer(serverId)
c.Check(srv.IsStarted(), Equals, true)
c.Check(srv.IsReading(), Equals, false)
c.Check(srv.IsWriting(), Equals, true)
conn.Send([]byte{}, 0, io.EOF)
b.DisconnectServer(serverId)
c.Check(srv.IsConnected(), Equals, false)
c.Check(srv.IsWriting(), Equals, false)
b.WaitForHalt()
_, err = b.ConnectServer(serverId)
conn.ResetDeath()
c.Check(err, IsNil)
b.DisconnectServer(serverId)
}
func (s *s) TestBot_Reconnecting(c *C) {
conf := Configure().Nick("nobody").Altnick("nobody1").Username("nobody").
Userhost("bitforge.ca").Realname("ultimateq").NoReconnect(false).
ReconnectTimeout(1).Ssl(true).Server(serverId)
cumutex := sync.Mutex{}
conn := mocks.CreateConn()
waiter := sync.WaitGroup{}
ndisc := 0
var b *Bot
connProvider := func(srv string) (net.Conn, error) {
cumutex.Lock()
defer cumutex.Unlock()
defer waiter.Done()
ndisc++
switch ndisc {
case 1:
return conn, nil
case 2:
return nil, io.EOF
case 3:
go func() {
b.servers[serverId].killreconn <- 0
}()
return conn, nil
}
c.Fatal("Unexpected reconnect occured.")
return nil, nil
}
var err error
b, err = createBot(conf, nil, connProvider, false)
c.Check(err, IsNil)
srv := b.servers[serverId]
srv.reconnScale = time.Microsecond
waiter.Add(1)
b.Connect()
b.start(false, true)
waiter.Wait()
waiter.Add(1)
conn.Send([]byte{}, 0, io.EOF)
conn.WaitForDeath()
conn.ResetDeath()
waiter.Wait()
waiter.Add(1)
conn.Send([]byte{}, 0, io.EOF)
conn.WaitForDeath()
conn.ResetDeath()
waiter.Wait()
b.WaitForHalt()
cumutex.Lock()
c.Check(ndisc, Equals, 3)
cumutex.Unlock()
}
func (s *s) TestBot_InterruptReconnect(c *C) {
conf := Configure().Nick("nobody").Altnick("nobody1").Username("nobody").
Userhost("bitforge.ca").Realname("ultimateq").NoReconnect(false).
ReconnectTimeout(1).Ssl(true).Server(serverId)
cumutex := sync.Mutex{}
conn := mocks.CreateConn()
ndisc := 0
var b *Bot
connProvider := func(srv string) (net.Conn, error) {
cumutex.Lock()
defer cumutex.Unlock()
ndisc++
return conn, nil
}
var err error
b, err = createBot(conf, nil, connProvider, false)
c.Check(err, IsNil)
srv := b.servers[serverId]
b.connectServer(srv)
b.startServer(srv, false, true)
conn.Send([]byte{}, 0, io.EOF)
conn.WaitForDeath()
c.Check(b.InterruptReconnect(serverId), Equals, true)
cumutex.Lock()
c.Check(ndisc, Equals, 1)
cumutex.Unlock()
}
func (s *s) TestBot_Dispatching(c *C) {
str := []byte("PRIVMSG #chan :msg\r\n#\r\n")
conn := mocks.CreateConn()
connProvider := func(srv string) (net.Conn, error) {
return conn, nil
}
waiter := sync.WaitGroup{}
waiter.Add(1)
b, err := createBot(fakeConfig, nil, connProvider, false)
b.Register(irc.PRIVMSG, &testHandler{
func(m *irc.IrcMessage, _ irc.Endpoint) {
waiter.Done()
},
})
c.Check(err, IsNil)
ers := b.Connect()
c.Check(len(ers), Equals, 0)
b.start(false, true)
conn.Send(str, len(str), io.EOF)
waiter.Wait()
b.Stop()
b.WaitForHalt()
b.Disconnect()
}
func (s *s) TestBot_Register(c *C) {
conn := mocks.CreateConn()
connProvider := func(srv string) (net.Conn, error) {
return conn, nil
}
b, err := createBot(fakeConfig, nil, connProvider, false)
gid := b.Register(irc.PRIVMSG, &coreHandler{})
id, err := b.RegisterServer(serverId, irc.PRIVMSG, &coreHandler{})
c.Check(err, IsNil)
c.Check(b.Unregister(irc.PRIVMSG, id), Equals, false)
c.Check(b.Unregister(irc.PRIVMSG, gid), Equals, true)
ok, err := b.UnregisterServer(serverId, irc.PRIVMSG, gid)
c.Check(ok, Equals, false)
ok, err = b.UnregisterServer(serverId, irc.PRIVMSG, id)
c.Check(ok, Equals, true)
_, err = b.RegisterServer("", "", &coreHandler{})
c.Check(err, Equals, errUnknownServerId)
_, err = b.UnregisterServer("", "", 0)
c.Check(err, Equals, errUnknownServerId)
}
func (s *s) TestBot_createBot(c *C) {
capsProvider := func() *irc.ProtoCaps {
return irc.CreateProtoCaps()
}
conn := mocks.CreateConn()
connProvider := func(srv string) (net.Conn, error) {
return conn, nil
}
b, err := createBot(fakeConfig, capsProvider, connProvider, false)
c.Check(b, NotNil)
c.Check(err, IsNil)
c.Check(len(b.servers), Equals, 1)
c.Check(b.caps, NotNil)
c.Check(b.capsProvider, NotNil)
c.Check(b.connProvider, NotNil)
}
func (s *s) TestBot_createServer(c *C) {
b, err := createBot(fakeConfig, nil, nil, true)
c.Check(err, IsNil)
srv := b.servers[serverId]
c.Check(srv.dispatcher, NotNil)
c.Check(srv.store, NotNil)
c.Check(srv.handler, NotNil)
cnf := fakeConfig.Clone()
cnf.GlobalContext().NoState(true)
b, err = createBot(cnf, nil, nil, false)
c.Check(err, IsNil)
srv = b.servers[serverId]
c.Check(srv.dispatcher, NotNil)
c.Check(srv.store, IsNil)
c.Check(srv.handler, IsNil)
}
func (s *s) TestBot_Providers(c *C) {
capsProv := func() *irc.ProtoCaps {
p := irc.CreateProtoCaps()
p.ParseISupport(&irc.IrcMessage{Args: []string{"nick", "CHANTYPES=H"}})
return p
}
connProv := func(s string) (net.Conn, error) {
return nil, net.ErrWriteToConnected
}
b, err := createBot(fakeConfig, capsProv, connProv, false)
c.Check(err, NotNil)
c.Check(err, Not(Equals), net.ErrWriteToConnected)
b, err = createBot(fakeConfig, nil, connProv, false)
ers := b.Connect()
c.Check(ers[0], Equals, net.ErrWriteToConnected)
}
func (s *s) TestBot_createIrcClient(c *C) {
b, err := createBot(fakeConfig, nil, nil, false)
c.Check(err, IsNil)
ers := b.Connect()
c.Check(ers[0], Equals, errSslNotImplemented)
}
func (s *s) TestBot_createDispatcher(c *C) {
_, err := createBot(fakeConfig, func() *irc.ProtoCaps {
return nil
}, nil, false)
c.Check(err, NotNil)
}
<file_sep>/bot/bot.go
/*
Package bot implements the top-level package that any non-extension
will use to start a bot instance.
*/
package bot
import (
"errors"
"fmt"
"github.com/aarondl/ultimateq/config"
"github.com/aarondl/ultimateq/dispatch"
"github.com/aarondl/ultimateq/irc"
"github.com/aarondl/ultimateq/parse"
"log"
"net"
"sync"
"time"
)
const (
// nAssumedServers is how many servers a bot typically connects to.
nAssumedServers = 1
// defaultReconnScale is how the config's ReconnTimeout is scaled.
defaultReconnScale = time.Second
// errFmtParsingIrcMessage is when the bot fails to parse a message
// during it's dispatch loop.
errFmtParsingIrcMessage = "bot: Failed to parse irc message (%v) (%s)\n"
// errFmtReaderClosed is when a write fails due to a closed socket or
// a shutdown on the client.
errFmtReaderClosed = "bot: %v reader closed\n"
// errFmtClosingServer is when a IrcClient.Close returns an error.
errFmtClosingServer = "bot: Error closing server (%v)\n"
// fmtFailedConnecting shows when the bot is unable to connect to a server.
fmtFailedConnecting = "bot: %v failed to connect (%v)"
// fmtDisconnected shows when the bot is disconnected
fmtDisconnected = "bot: %v disconnected"
// fmtReconnecting shows when the bot is reconnecting
fmtReconnecting = "bot: %v reconnecting in %v..."
)
var (
// errInvalidConfig is when CreateBot was given an invalid configuration.
errInvalidConfig = errors.New("bot: Invalid Configuration")
// errInvalidServerId occurs when the user passes in an unknown
// server id to a method requiring a server id.
errUnknownServerId = errors.New("bot: Unknown Server id.")
)
type (
// CapsProvider returns a usable ProtoCaps to start the bot with
CapsProvider func() *irc.ProtoCaps
// ConnProvider transforms a "server:port" string into a net.Conn
ConnProvider func(string) (net.Conn, error)
)
// Bot is a main type that joins together all the packages into a functioning
// irc bot. It should be able to carry out most major functions that a bot would
// need through it's exported functions.
type Bot struct {
servers map[string]*Server
conf *config.Config
caps *irc.ProtoCaps
dispatcher *dispatch.Dispatcher
// IoC and DI components mostly for testing.
attachHandlers bool
capsProvider CapsProvider
connProvider ConnProvider
msgDispatchers sync.WaitGroup
// servers
serversProtect sync.RWMutex
// configs (including server configs)
configsProtect sync.RWMutex
}
// Configure starts a configuration by calling CreateConfig. Alias for
// config.CreateConfig
func Configure() *config.Config {
return config.CreateConfig()
}
// ConfigureFile starts a configuration by reading in a file. Alias for
// config.CreateConfigFromFile
func ConfigureFile(filename string) *config.Config {
return config.CreateConfigFromFile(filename)
}
// ConfigureFunction creates a blank configuration and passes it into a function
func ConfigureFunction(cnf func(*config.Config) *config.Config) *config.Config {
return cnf(config.CreateConfig())
}
// Check config checks a bots config for validity.
func CheckConfig(c *config.Config) bool {
if !c.IsValid() {
c.DisplayErrors()
return false
}
return true
}
// CreateBot simplifies the call to createBotFull by using default
// caps and conn provider functions.
func CreateBot(conf *config.Config) (*Bot, error) {
if !CheckConfig(conf) {
return nil, errInvalidConfig
}
return createBot(conf, nil, nil, true)
}
// Connect creates the connections and the IrcClient objects, as well as
// connects the bot to all defined servers.
func (b *Bot) Connect() []error {
var ers = make([]error, 0, nAssumedServers)
b.serversProtect.RLock()
for _, srv := range b.servers {
err := b.connectServer(srv)
if err != nil {
ers = append(ers, err)
}
}
b.serversProtect.RUnlock()
if len(ers) > 0 {
return ers
}
return nil
}
// ConnectServer creates the connection and IrcClient object for the given
// serverId.
func (b *Bot) ConnectServer(serverId string) (found bool, err error) {
b.serversProtect.RLock()
if srv, ok := b.servers[serverId]; ok {
err = b.connectServer(srv)
found = true
}
b.serversProtect.RUnlock()
return
}
// connectServer creates the connection and IrcClient object for the given
// server.
func (b *Bot) connectServer(srv *Server) (err error) {
if srv.IsConnected() {
return errors.New(fmt.Sprintf(errFmtAlreadyConnected, srv.name))
}
srv.protect.Lock()
err = srv.createIrcClient()
if err == nil {
srv.setConnected(true, false)
}
srv.protect.Unlock()
return
}
// Start begins message pumps on all defined and connected servers.
func (b *Bot) Start() {
b.start(true, true)
}
// StartServer begins message pumps on a server by id.
func (b *Bot) StartServer(serverId string) (found bool) {
b.serversProtect.RLock()
if srv, ok := b.servers[serverId]; ok {
b.startServer(srv, true, true)
found = true
}
b.serversProtect.RUnlock()
return
}
// start begins the called for routines on all servers
func (b *Bot) start(writing, reading bool) {
b.serversProtect.RLock()
for _, srv := range b.servers {
b.startServer(srv, writing, reading)
}
b.serversProtect.RUnlock()
}
// startServer begins the called for routines on the specific server
func (b *Bot) startServer(srv *Server, writing, reading bool) {
if srv.IsStarted() {
return
}
srv.protect.Lock()
defer srv.protect.Unlock()
if srv.isConnected() && srv.client != nil {
if writing {
srv.setWriting(true, false)
}
if reading {
srv.setReading(true, false)
}
srv.client.SpawnWorkers(writing, reading)
b.dispatchMessage(srv, &irc.IrcMessage{Name: irc.CONNECT})
if reading {
b.msgDispatchers.Add(1)
go b.dispatchMessages(srv)
}
}
}
// Stop shuts down all dispatch routines.
func (b *Bot) Stop() {
b.serversProtect.RLock()
for _, srv := range b.servers {
b.stopServer(srv)
}
b.serversProtect.RUnlock()
}
// StopServer shuts down the dispatch routine of the given server by id.
func (b *Bot) StopServer(serverId string) (found bool) {
b.serversProtect.RLock()
if srv, ok := b.servers[serverId]; ok {
b.stopServer(srv)
found = true
}
b.serversProtect.RUnlock()
return
}
// stopServer stops dispatcher on the given server.
func (b *Bot) stopServer(srv *Server) {
if srv.IsReading() {
srv.killdispatch <- 0
srv.setReading(false, true)
}
}
// Disconnect closes all connections to the servers
func (b *Bot) Disconnect() {
b.serversProtect.RLock()
for _, srv := range b.servers {
b.disconnectServer(srv)
}
b.serversProtect.RUnlock()
}
// DisconnectServer disconnects the given server by id.
func (b *Bot) DisconnectServer(serverId string) (found bool) {
b.serversProtect.RLock()
if srv, ok := b.servers[serverId]; ok {
b.disconnectServer(srv)
found = true
}
b.serversProtect.RUnlock()
return
}
// disconnectServer disconnects the given server.
func (b *Bot) disconnectServer(srv *Server) {
srv.protect.RLock()
if !srv.isConnected() || srv.client == nil {
srv.protect.RUnlock()
return
}
srv.client.Close()
srv.protect.RUnlock()
srv.protect.Lock()
defer srv.protect.Unlock()
srv.client = nil
srv.setWriting(false, false)
srv.setConnected(false, false)
}
// InterruptReconnect stops reconnecting the given server by id.
func (b *Bot) InterruptReconnect(serverId string) (found bool) {
b.serversProtect.RLock()
if srv, ok := b.servers[serverId]; ok {
b.interruptReconnect(srv)
found = true
}
b.serversProtect.RUnlock()
return
}
// interruptReconnect stops reconnecting the given server.
func (b *Bot) interruptReconnect(srv *Server) {
if srv.IsReconnecting() {
srv.killreconn <- 0
}
}
// WaitForHalt waits for all servers to halt.
func (b *Bot) WaitForHalt() {
b.msgDispatchers.Wait()
b.dispatcher.WaitForCompletion()
b.serversProtect.RLock()
for _, srv := range b.servers {
srv.dispatcher.WaitForCompletion()
}
b.serversProtect.RUnlock()
}
// Register adds an event handler to the bot's global dispatcher.
func (b *Bot) Register(event string, handler interface{}) int {
return b.dispatcher.Register(event, handler)
}
// Register adds an event handler to a server specific dispatcher.
func (b *Bot) RegisterServer(
server string, event string, handler interface{}) (int, error) {
b.serversProtect.RLock()
defer b.serversProtect.RUnlock()
if s, ok := b.servers[server]; ok {
s.protect.RLock()
defer s.protect.RUnlock()
return s.dispatcher.Register(event, handler), nil
}
return 0, errUnknownServerId
}
// Unregister removes an event handler from the bot's global dispatcher
func (b *Bot) Unregister(event string, id int) bool {
return b.dispatcher.Unregister(event, id)
}
// Unregister removes an event handler from a server specific dispatcher.
func (b *Bot) UnregisterServer(
server string, event string, id int) (bool, error) {
b.serversProtect.RLock()
defer b.serversProtect.RUnlock()
if s, ok := b.servers[server]; ok {
s.protect.RLock()
defer s.protect.RUnlock()
return s.dispatcher.Unregister(event, id), nil
}
return false, errUnknownServerId
}
// dispatchMessages is a constant read-dispatch from the server to the
// dispatcher.
func (b *Bot) dispatchMessages(s *Server) {
s.protect.RLock()
read := s.client.ReadChannel()
stop, disconnect := false, false
for !stop {
select {
case msg, ok := <-read:
if !ok {
log.Printf(errFmtReaderClosed, s.name)
b.dispatchMessage(s, &irc.IrcMessage{Name: irc.DISCONNECT})
stop, disconnect = true, true
break
}
ircMsg, err := parse.Parse(msg)
if err != nil {
log.Printf(errFmtParsingIrcMessage, err, msg)
} else {
s.protectStore.Lock()
if s.store != nil {
s.store.Update(ircMsg)
}
s.protectStore.Unlock()
b.dispatchMessage(s, ircMsg)
}
case <-s.killdispatch:
log.Printf(errFmtReaderClosed, s.name)
stop = true
break
}
}
s.protect.RUnlock()
var reconn bool
var scale time.Duration
var timeout uint
b.ReadConfig(func(c *config.Config) {
cserver := c.GetServer(s.name)
if cserver != nil {
reconn = disconnect && !cserver.GetNoReconnect()
scale = s.reconnScale
timeout = cserver.GetReconnectTimeout()
}
})
if !reconn {
b.msgDispatchers.Done()
}
log.Printf(fmtDisconnected, s.name)
if reconn {
for {
dur := time.Duration(timeout) * scale
log.Printf(fmtReconnecting, s.name, dur)
b.disconnectServer(s)
s.protect.Lock()
s.setStarted(false, false)
s.setReconnecting(true, false)
s.protect.Unlock()
select {
case <-time.After(dur):
s.setReconnecting(false, true)
break
case <-s.killreconn:
s.setReconnecting(false, true)
b.msgDispatchers.Done()
return
}
err := b.connectServer(s)
if err != nil {
log.Printf(fmtFailedConnecting, s.name, err)
continue
} else {
b.startServer(s, true, true)
break
}
}
b.msgDispatchers.Done()
} else if disconnect {
<-s.killdispatch
}
}
// Writeln writes a string to the given server's IrcClient.
func (b *Bot) Writeln(server, message string) error {
b.serversProtect.RLock()
defer b.serversProtect.RUnlock()
if srv, ok := b.servers[server]; !ok {
return errUnknownServerId
} else {
return srv.Writeln(message)
}
}
// dispatch sends a message to both the bot's dispatcher and the given servers
func (b *Bot) dispatchMessage(s *Server, msg *irc.IrcMessage) {
endpoint := createServerEndpoint(s)
b.dispatcher.Dispatch(msg, endpoint)
s.dispatcher.Dispatch(msg, endpoint)
}
// createBot creates a bot from the given configuration, using the providers
// given to create connections and protocol caps.
func createBot(conf *config.Config, capsProv CapsProvider,
connProv ConnProvider, attachHandlers bool) (*Bot, error) {
b := &Bot{
conf: conf,
servers: make(map[string]*Server, nAssumedServers),
capsProvider: capsProv,
connProvider: connProv,
attachHandlers: attachHandlers,
}
if capsProv == nil {
b.caps = irc.CreateProtoCaps()
} else {
b.caps = capsProv()
}
var err error
if err = b.createDispatcher(conf.Global.GetChannels()); err != nil {
return nil, err
}
for name, srv := range conf.Servers {
server, err := b.createServer(srv)
if err != nil {
return nil, err
}
b.servers[name] = server
}
return b, nil
}
// createServer creates a dispatcher, and an irc client to connect to this
// server.
func (b *Bot) createServer(conf *config.Server) (*Server, error) {
var copyCaps irc.ProtoCaps = *b.caps
s := &Server{
bot: b,
name: conf.GetName(),
caps: ©Caps,
conf: conf,
killdispatch: make(chan int),
killreconn: make(chan int),
reconnScale: defaultReconnScale,
}
if err := s.createDispatcher(conf.GetChannels()); err != nil {
return nil, err
}
if !conf.GetNoState() {
if err := s.createStore(); err != nil {
return nil, err
}
}
if b.attachHandlers {
s.handler = &coreHandler{bot: b}
s.handlerId =
s.dispatcher.Register(irc.RAW, s.handler)
}
return s, nil
}
// createDispatcher uses the bot's current ProtoCaps to create a dispatcher.
func (b *Bot) createDispatcher(channels []string) error {
var err error
b.dispatcher, err = dispatch.CreateRichDispatcher(b.caps, channels)
if err != nil {
return err
}
return nil
}
| 72941fee559de03f68b53e0c6b76f5f7d886dda1 | [
"Markdown",
"Go"
] | 25 | Go | taruti/ultimateq | 8b980c2141591d28eb1859ed5e12695637c5fc08 | 395745b92295bf7df730b94389696930119e1c1d |
refs/heads/master | <file_sep>package scripts;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Functions {
public static void main(String[] args) throws IOException {
String path_file_url = "uuu";
ArrayList<String> li = new ArrayList<String>();
int i = 1;
Scanner scanner = new Scanner(new File(path_file_url));
FileWriter file_job_liste = new FileWriter("id_url_uniq.txt");
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(!li.contains(line)){
li.add(line);
file_job_liste.write(i+ " "+line+ " \n");
i++;
}
}
scanner.close();
file_job_liste.close();
}
}
| db992a39d9d88b58487c6e951ede94fc6bc6c1b4 | [
"Java"
] | 1 | Java | NawalOuldamer/Deleicious_cogo | 1c98d1dc5d8eac75e4df41331eb48b9ed61460cb | 8dd842127cddce74b1751b1837bb2d8a69ac8111 |
refs/heads/main | <repo_name>rochyscarlata/SuperHeroesSearch<file_sep>/src/components/login/Login.js
import React, { useState, useEffect } from "react";
import Mujerm from "../../assets/img/mujerm.jpg";
import swal from "sweetalert";
import { useHistory, Redirect } from "react-router-dom";
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [, forceUpdate] = useState(false);
const history = useHistory();
const handleLogin = () =>{
history.push("/heroes")
}
// const handleLogin = async (e) => {
// e.preventDefault();
// fetch('https://challenge-react.alkemy.org/', {
// method: 'POST',
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify({
// email: email,
// password: <PASSWORD>,
// })
// }).then(res => {
// return res.json()
// }).then(res => {
// if(res["error"]){swal({
// title: "Error!",
// text: "Email or password invalid",
// icon: "error",
// });}
// else{
// localStorage.setItem('token', res["token"]);
// history.push("/home")
// }
// })
// }
// const data = { email, password };
// fetch('http://challenge-react.alkemy.org', {
// method: 'POST',
// headers: {
// "Content-Type": "application/json",
// 'Accept': "application/json",
// },
// body: JSON.stringify(data),
// }
// // localStorage.setItem("token", JSON.stringify(response));
// // response = await response.json();
// // if (response === 200) {
// // history.replace("/home");
// // }
// // else {
// // console.log("error");
// // }
// }
return (
<div class="container is-fluid">
<div className="container is-mobile is-centered mt-6" id="container-log">
{" "}
<div className="columns is-centered ">
<div className="column is-6">
<div className="content ">
<form className="box" onSubmit={handleLogin}>
<div className="field">
<h2 className="level-item has-text-centered">WELCOME!</h2>
<div className="block has-text-centered">
<figure className="image is-128x128 is-inline-block">
<img className="is-centered" src={Mujerm} />
</figure>
</div>
<label className="label">Email</label>
<div className="control">
<p className="control has-icons-left has-icons-right">
<input
className="input"
type="email"
placeholder="Enter your email"
onChange={(e) => {setEmail(e.target.value)}}
required
/>
<span className="icon is-small is-left">
<i className="fas fa-user"></i>
</span>
</p>
</div>
</div>
<div className="field">
<label className="label">Password</label>
<div className="control">
<p className="control has-icons-left">
<input
className="input"
type="password"
placeholder="********"
onChange={(e) => {setPassword(e.target.value)}}
required
/>
<span className="icon is-small is-left">
<i className="fas fa-lock"></i>
</span>
</p>
</div>
</div>
<button className="button is-primary" >
Sign in
</button>
</form>
{/* {localStorage.getItem('token') !== "none" ? <Redirect to="/home" /> : ""} */}
</div>
</div>
</div>
</div>
</div>
);
};
export default Login;
<file_sep>/src/components/search/HeroeView.js
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { Link } from "react-router-dom";
import "./HeroesStyle.css";
const HeroeView = ({history}) => {
const { id } = useParams();
console.log(id);
const [chara, setChara] = useState([]);
const apiKey = "10226116298680536";
const url = "https://www.superheroapi.com/api.php";
// por el id obtengo los datos
useEffect(() => {
const dataHero = async () => {
const data = await fetch(
`${url}/${apiKey}/${id}`
);
const res = await data.json();
setChara(res);
console.log(res);
};
dataHero();
}, [id]);
function handleReturn(){
history.push('/heroes');
}
return (
<>
<div className="container is-max-desktop">
<div className="container ">
{/* <img className="" src={chara.image?.url} alt="" /> */}
<div class="columns is-mobile is-multiline">
<div class="column animate__animated animate__zoomInUp">
<figure className="image ">
<img src={chara.image?.url} alt={`${chara.name} Snapshot`} />
</figure>
</div>
<div class="column animate__animated animate__zoomInUp">
<div className="content">
<h2 className="title is-2">{chara.name}</h2>
<p >
<span className="has-text-primary">Full Name:</span> {chara.biography?.["full-name"]}
</p>
<p >
<span className="has-text-primary">Also know as:</span> {chara.biography?.aliases[0]}
</p>
<p >
<span className="has-text-primary">Height:</span> {chara.appearance?.height[1]}{" "}
- {chara.appearance?.weight[1]}
</p>
<p >
<span className="has-text-primary">Weight:</span>{chara.appearance?.weight[1]}
</p>
<p >
<span className="has-text-primary">Eye color:</span> {chara.appearance?.["eye-color"]}
</p>
<p >
<span className="has-text-primary">Hair color:</span> {chara.appearance?.["hair-color"]}
</p>
<p >
<span className="has-text-primary">Work:</span> {chara.work?.occupation}
</p>
<p >
<span className="has-text-primary">First Appearance was in</span>{" "}
{chara.biography?.["first-appearance"]}{" "}
<span>and Published for</span> {chara.biography?.publisher}
</p>
<h4 class="subtitle is-4">PowerStats</h4>
<p>
<span>Intelligence: {chara.powerstats?.intelligence}%</span>
<progress
class="progress is-small is-primary"
value={chara.powerstats?.intelligence}
max="100"
></progress>
</p><p>
<span>strength: {chara.powerstats?.strength}%</span>
<progress
class="progress is-small is-link"
value={chara.powerstats?.strength}
max="100"
></progress>
</p><p>
<span>Speed: {chara.powerstats?.speed}%</span>
<progress
class="progress is-small is-info"
value={chara.powerstats?.speed}
max="100"
></progress>
</p><p>
<span>Durability: {chara.powerstats?.durability}%</span>
<progress
class="progress is-small is-success"
value={chara.powerstats?.durability}
max="100"
></progress>
</p>
<p>
<span>Power: {chara.powerstats?.power}%</span>{" "}
<progress
class="progress is-small is-warning"
value={chara.powerstats?.power}
max="100"
></progress>
</p>
<p>
<span>Combat: {chara.powerstats?.combat}%</span>{" "}
<progress
class="progress is-small is-danger"
value={chara.powerstats?.combat}
max="100"
></progress>
</p>
</div>
<nav class="level is-mobile">
<div class="level-left">
<Link to="/heroes" class="level-item" aria-label="undo" onclick={handleReturn}>
<span class="icon is-small">
<i class="fas fa-undo" aria-hidden="true"></i>
</span>
Back
</Link>
</div>
</nav>
</div>
</div>
</div>
{/* <div className="">
<div className="character-div-title">
<h2 className="character-title">{chara.name}</h2>
<p className="character-text">
<span>Full Name:</span> {chara.biography?.["full-name"]}
</p>
<p className="character-text">
<span>Also know as:</span> {chara.biography?.aliases[0]}
</p>
<p className="character-text">
<span>Height and Weight:</span> {chara.appearance?.height[1]} -{" "}
{chara.appearance?.weight[1]}
</p>
<p className="character-text">
<span>Eye color:</span> {chara.appearance?.["eye-color"]}
</p>
<p className="character-text">
<span>Hair color:</span> {chara.appearance?.["hair-color"]}
</p>
<p className="character-text">
<span>Work:</span> {chara.work?.occupation}
</p>
<p className="character-text">
<span>First Appearance was in</span>{" "}
{chara.biography?.["first-appearance"]}{" "}
<span>and Published for</span> {chara.biography?.publisher}
</p>
</div>
<Link to="/heroes">
<button className="character-button">Back </button>
</Link>
</div> */}
</div>
</>
);
};
export default HeroeView;
<file_sep>/src/components/ui/Header.js
import React, { useState, useEffect } from "react";
import { Link, NavLink, useHistory } from "react-router-dom";
import superLogo from '../../assets/logo/logoM.jpg'
export default function Header() {
const [isActive, setisActive] = React.useState(false);
const history = useHistory();
console.log(history)
const handleLogout=()=>{
localStorage.removeItem('token')
history.replace('/login')
}
return (
<nav className="navbar is-white " role="navigation" aria-label="main navigation">
<div className="navbar-brand">
<Link class="navbar-item" href="https://bulma.io">
<img src={superLogo} width="90" height="70x"/> </Link>
<a
onClick={() => {
setisActive(!isActive);
}}
role="button"
className={`navbar-burger burger ${isActive ? "is-active" : ""}`}
aria-label="menu"
aria-expanded="false"
data-target="navbarBasicExample"
>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</a>
</div>
<div
id="navbarBasicExample"
className={`navbar-menu ${isActive ? "is-active" : ""}`}
>
<div className="navbar-start">
{/* <NavLink className="navbar-item" to="./home">
Home
</NavLink> */}
<NavLink className="navbar-item" to="/Heroes">
Heroes
</NavLink>
</div>
<div class="navbar-end">
<div class="navbar-item">
<div class="buttons">
<NavLink class="button is-primary" to="/login" onClick={handleLogout}>
<strong>Logout</strong>
</NavLink>
</div>
</div>
</div>
</div>
</nav>
);
}
<file_sep>/src/components/Home.js
import React, { useState, useEffect } from "react";
import swal from "sweetalert";
const Home = () => {
const [equipo, setEquipo] = useState([]);
const [totalCombat, setTotalCombat] = useState(0.0);
const [totalDurability, setTotalDurability] = useState(0.0);
const [totalIntelligence, setTotalIntelligence] = useState(0.0);
const [totalPower, setTotalPower] = useState(0.0);
const [totalSpeed, setTotalSpeed] = useState(0.0);
const [totalStrength, setTotalStrength] = useState(0.0);
const [promedioPeso, setpromedioPeso] = useState(0.0);
const [promedioAltura, setpromedioAltura] = useState(0.0);
const [mayorStat, setMayorStat] = useState("");
const [chara, setChara] = useState([]);
const validarAgregar = (chara) => {
if (equipo.length === 6) {
return "No puede agregar mรกs de 6 miembros al equipo";
}
if (equipo.find((charas) => charas.id === chara.id)) {
return "Ya agregรณ al hรฉroe al equipo";
}
if (
equipo.filter((charas) => charas.biography.alignment === "good")
.length === 3
) {
return "No puede haber mรกs de 3 heroes con orientaciรณn buena";
}
if (
equipo.filter((charas) => charas.biography.alignment === "bad").length ===
3
) {
return "No puede haber mรกs de 3 heroes con orientaciรณn mala";
}
return "";
};
useEffect(() => {
let powerstats = {
combat: 0,
durability: 0,
intelligence: 0,
power: 0,
speed: 0,
strength: 0,
};
let peso = 0.0;
let altura = 0.0;
equipo.forEach((chara) => {
if (chara.appearance.weight[1]) {
//peso en kg
const pesoHero = parseFloat(
chara.appearance.weight[1].replace(" kg", "")
);
peso = peso + pesoHero;
}
if (chara.appearance.height[1]) {
//altura en cm
const alturaHero = parseFloat(
chara.appearance.height[1].replace(" cm", "")
);
altura = altura + alturaHero;
}
Object.keys(chara.powerstats).forEach((key) => {
if (chara.powerstats[key] !== "null") {
powerstats[key] = powerstats[key] + parseInt(chara.powerstats[key]);
}
});
});
setTotalCombat(powerstats.combat);
setTotalDurability(powerstats.durability);
setTotalIntelligence(powerstats.intelligence);
setTotalPower(powerstats.power);
setTotalSpeed(powerstats.speed);
setTotalStrength(powerstats.strength);
//ordeno las stats de mayor a menor
const statsOrdenadas = Object.entries(powerstats).sort(
(a, b) => b[1] - a[1]
);
if (statsOrdenadas[0][1] !== 0) {
// seteo la primera si es distinto de 0
setMayorStat(statsOrdenadas[0][0]);
}
if (peso !== 0) {
setpromedioPeso((peso / equipo.length).toFixed(2));
}
if (altura !== 0) {
setpromedioAltura((altura / equipo.length).toFixed(2));
}
}, [equipo]);
const addToTeam = (chara) => {
const resultadoValidacion = validarAgregar(chara);
if (resultadoValidacion === "") {
const copiaDeEquipo = [...equipo];
copiaDeEquipo.push(chara);
setEquipo(copiaDeEquipo);
// calcularEstadisticas();
} else {
swal.fire({
icon: "error",
title: resultadoValidacion,
});
}
};
const sacarDelEquipo = (chara) => {
const equipoFiltrado = equipo.filter((charas) => charas.id !== chara.id);
setEquipo(equipoFiltrado);
// calcularEstadisticas();
};
return (
<div className="container is-max-desktop">
<div className="container is-mobile">
<div class="columns is-mobile is-centered">
<div class="column is-half">
<div class="block">
<h3 className="title is-3 ">
<strong>YOUR TEAM</strong>
</h3>
</div>
<table class="table">
<thead>
<tr>
<th>Photo</th>
<th>Hero</th>
<th>Stats</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{equipo.map((chara) => (
<tr>
<th>
<figure class="image is-64x64">
<img
class="is-rounded"
src="https://bulma.io/images/placeholders/128x128.png"
/>
</figure>
</th>
<td>{chara.name}</td>
<td>
<span class="tag is-primary is-light">
Intelligence: {chara.powerstats.intelligence}
</span>
<span class="tag is-link is-light">
strength:{chara.powerstats.strength}
</span>
<span class="tag is-info is-light">
Speed:{chara.powerstats.speed}
</span>
<span class="tag is-success is-light">
Durability:{chara.powerstats.durability}
</span>
<span class="tag is-warning is-light">
Power:{chara.powerstats.power}
</span>
<span class="tag is-danger is-light">
{" "}
Combat:{chara.powerstats.combat}
</span>
</td>
<td>
<button
class="button is-danger"
onClick={() => sacarDelEquipo(chara)}
>
<span class="icon">
<i class="fas fa-trash"></i>
</span>
</button>
</td>
</tr>
))}
</tbody>
</table>
<div class="notification is-danger is-light">
This section is not available yet, please go to
<a href="./heroes"> heroes</a>
</div>
<div>
<br></br>
</div>
</div>
</div>
</div>
</div>
);
};
export default Home;
<file_sep>/src/components/ui/Footer.js
import React from 'react'
import { Link } from "react-router-dom";
import './footer.css'
export const Footer = () => {
return (
<footer class="footer">
<div class="content has-text-centered">
<p>
<strong>Super Heroes</strong> by <a href="https://rosarioscarlatadev.netlify.app/" target="_blank"><NAME></a>.
</p>
</div>
</footer>
)
}
<file_sep>/src/components/search/Heroes.js
import React, { Component } from "react";
import axios from "axios";
import "./HeroesStyle.css";
import Qs from "qs";
import swal from "sweetalert";
import { Link } from "react-router-dom";
const apiKey = "921664605275424";
let heroArray = [];
let searchResults = "";
export default class Search extends Component {
constructor() {
super();
this.state = {
searchResults: [],
chosenCharacter: {},
};
}
searchChar = (e) => {
let charString = document.getElementById("searchInput").value;
e.preventDefault();
axios({
method: "GET",
url: "https://proxy.hackeryou.com",
dataResponse: "json",
paramsSerializer: function (params) {
return Qs.stringify(params, { arrayFormat: "brackets" });
},
params: {
reqUrl: `https://superheroapi.com/api/${apiKey}/search/${charString}`,
},
xmlToJSON: false,
}).then((res) => {
console.log(res);
heroArray = res.data.results;
if (!heroArray) {
swal({
title: "error",
text: `${charString} returns no results. Please try a another character.`,
icon: "error",
button: {
className: "sweetButton",
},
});
} else {
console.log(heroArray);
heroArray.forEach((chara) => {
for (let stat in chara.powerstats) {
// change null number values to 0
if (chara.powerstats[stat] === "null") {
chara.powerstats[stat] = "0";
}
}
});
this.setState({
searchResults: heroArray,
});
}
});
};
addToTeam(){
swal({
title: "Sorry!",
text: "This action is not available yet!",
icon: "error",
});
}
render() {
return (
<div className="container is-max-desktop">
<div className="container is-mobile">
<div class="columns is-mobile is-centered">
<div class="column is-half">
<div class="block">
<h3 className="title is-3 ">
FIND YOUR <strong>HERO</strong>
</h3>
</div>
<div class="modal">
<div class="modal-background"></div>
<div class="modal-content"></div>
<button
class="modal-close is-large"
aria-label="close"
></button>
</div>
<form
className="search"
onSubmit={this.searchChar}
onClick={this.changeClassName}
>
<div className="field has-addons">
<div className="control">
<input
className="input"
type="text"
autoComplete="off"
placeholder="Seeks a hero"
id="searchInput"
/>
</div>
<div className="control">
<button
type="submit"
className="button is-primary"
value="Search"
>
Search
</button>
</div>
</div>
</form>
<div>
<br></br>
</div>
</div>
</div>
</div>
<section class="section is-small">
<div className="container is-max-desktop ">
<div class="columns is-mobile is-multiline">
{heroArray.map((chara, i) => {
return (
<div className="colum is-4 animate__animated animate__fadeIn">
<div key={chara.id} className=" card card-equal-height">
<div class="card-content">
<header class="card-header">
<img
className="is-4by3"
src={chara.image.url}
alt={`${chara.name} Snapshot`}
/>
</header>
<div class="card-content">
<h4 className="title is-4">{chara.name}</h4>
<h4 className="subtitle">{chara.biography.alignment}</h4>
<p class="card-header-title">Powerstats: </p>
<span class="tag is-primary is-light">
Intelligence: {chara.powerstats.intelligence}
</span>
<span class="tag is-link is-light">
strength:{chara.powerstats.strength}
</span>
<span class="tag is-info is-light">
Speed:{chara.powerstats.speed}
</span>
<span class="tag is-success is-light">
Durability:{chara.powerstats.durability}
</span>
<span class="tag is-warning is-light">
Power:{chara.powerstats.power}
</span>
<span class="tag is-danger is-light">
{" "}
Combat:{chara.powerstats.combat}
</span>
</div>
<footer class="card-footer has-background-primary-light">
<a href="#" class="card-footer-item" onClick={() => this.addToTeam(i)}>
Add to my team
</a>
<Link
class="card-footer-item"
to={`./heroeView/${chara.id}`}
>
View
</Link>
</footer>
</div>
</div>
<br></br>
</div>
);
})}
</div>
</div>
</section>
</div>
);
}
}
// export default Heroes;
<file_sep>/src/routers/DashboardRoutes.js
import React from 'react'
import { Redirect, Route, Switch } from 'react-router';
import Home from '../components/Home';
import Header from "../components/ui/Header";
import Heroes from '../components/search/Heroes'
import HeroeView from '../components/search/HeroeView';
import { Footer } from '../components/ui/Footer';
export default function DashboardRoutes ({history}) {
return (
<>
<Header history={history}/>
<div style={{height: 'auto'}}>
<Switch>
<Route exact path="/home" component={Home}/>
<Route exact path="/heroes" component={Heroes}/>
<Route exact path="/heroeView/:id" component={HeroeView}/>
<Redirect to="/login"/>
</Switch>
</div>
</>
)
}
| 87f12cc4312cf7bc709bd509c70aa99c26d270f9 | [
"JavaScript"
] | 7 | JavaScript | rochyscarlata/SuperHeroesSearch | 02c086bdbd12f86861afdb1cb8363d6f26133aef | d792f5b51b01fdcb42fe362f245f5b29af298ce0 |
refs/heads/master | <file_sep>package com.ucucs.mybatis;
import lombok.Getter;
import lombok.Setter;
import java.util.Properties;
@Getter
@Setter
public class MybatisPlusConfig {
private String dbType;
private String dbUrl;
private String driverClassName;
private String userName;
private String password;
private String projectName;
private String packageName;
private String moduleName;
private String author;
private String[] tableNames;
private boolean useServiceSuffix;
private String projectPath;
private String basePath;
private String mapperPath;
public static MybatisPlusConfig loadConfig(Properties properties) {
MybatisPlusConfig config = new MybatisPlusConfig();
config.setDbType(properties.getProperty("dbtype"));
config.setDbUrl(properties.getProperty("jdbc.connectionURL"));
config.setDriverClassName(properties.getProperty("jdbc.driverClass"));
config.setUserName(properties.getProperty("jdbc.userId"));
config.setPassword(properties.getProperty("jdbc.password"));
config.setProjectName(properties.getProperty("projectName"));
config.setPackageName(properties.getProperty("packageBase"));
config.setModuleName(properties.getProperty("moduleName"));
config.setAuthor(properties.getProperty("author"));
config.setUseServiceSuffix(properties.getProperty("useServiceSuffix").equalsIgnoreCase("true"));
config.setTableNames(new String[] {properties.getProperty("tableName")});
config.setProjectPath(System.getProperty("user.dir"));
config.setBasePath(properties.getProperty("basePath"));
config.setMapperPath(properties.getProperty("mapperPath"));
return config;
}
}
<file_sep>CREATE TABLE `adjust_salary` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '่ชๅขID',
`as_date` date DEFAULT NULL COMMENT '่ฐ่ชๆฅๆ',
`before_salary` int DEFAULT NULL COMMENT '่ฐๅ่ช่ต',
`after_salary` int DEFAULT NULL COMMENT '่ฐๅ่ช่ต',
`reason` varchar(255) DEFAULT NULL COMMENT '่ฐ่ชๅๅ ',
`remark` varchar(255) DEFAULT NULL COMMENT 'ๅคๆณจ',
PRIMARY KEY (`id`)
);<file_sep>package com.ucucs.mybatis.service;
import com.ucucs.mybatis.model.AdjustSalary;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* ๆๅก็ฑป
* </p>
*
* @author
* @since 2020-08-28
*/
public interface AdjustSalaryService extends IService<AdjustSalary> {
}
<file_sep># mybatis-codegen
Mybatis General Code
่ฟ็จๅๆฏ่ทๆฌๅฐๅๆฏ็ปๅฎๅฝไปค
git branch --set-upstream-to origin/master master
Mybatis็ๆ
็ดๆฅ่ฟ่กmavenๆไปถ้็generateๅณๅฏ
Mybatis-Plus็ๆ
ๆง่กๅๅ
ๆต่ฏๅณๅฏ
<file_sep>package com.ucucs.mybatis.mapper;
import com.ucucs.mybatis.model.AdjustSalary;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper ๆฅๅฃ
* </p>
*
* @author
* @since 2020-08-28
*/
public interface AdjustSalaryMapper extends BaseMapper<AdjustSalary> {
}
| 1c7f6cc45e64fa2a633e9870bdc0e75af078ceca | [
"Markdown",
"Java",
"SQL"
] | 5 | Java | ucucs/mybatis-codegen | c01c5991596cd1b38ef2084cd92aa0c1e4e583fa | 3b4ff692c41756536b650c9db9b52c450283e35c |
refs/heads/master | <repo_name>Sukhadia1/Springboard_DSC<file_sep>/README.md
# Springboard_DSC
Springboard_DSC This repository contains all the data and ipython notebooks for all the springboard data science course exercises. It also has a directory for the capstone project.
<file_sep>/Exercises/titanic_datascience/titanic/__init__.py
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 23 19:57:30 2020
@author: <NAME>
"""
<file_sep>/Exercises/water-pumps/pumps_package/pumps_package/__init__.py
def yay():
print("YAY!")
<file_sep>/Exercises/water-pumps/src/models/train_model.py
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
def logistic(df):
X = pd.get_dummies(df.drop('status_group', axis=1))
y = df.status_group
lr = LogisticRegression()
params = {'C': [0.1, 1, 10]}
clf = GridSearchCV(lr,params, cv=3)
return clf.fit(X,y)
| c3fbfa270bae95fe26acd070d9acc825d5d1f0bc | [
"Markdown",
"Python"
] | 4 | Markdown | Sukhadia1/Springboard_DSC | 17489633ffb9b0df798b9bb79100e075e3ceb8a3 | 0636ab59005a0292a84471c6464ef83304473543 |
refs/heads/master | <file_sep>package simulator.tests;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import junit.framework.TestCase;
import simulator.enumerators.JobType;
import simulator.enumerators.UserType;
import simulator.exceptions.InvalidParametersException;
import simulator.source.Job;
import simulator.source.Request;
import simulator.source.User;
public class UserTest extends TestCase {
public UserTest() {
super();
}
@BeforeAll
static void setUpBeforeClass() throws Exception {
}
@AfterAll
static void tearDownAfterClass() throws Exception {
}
@Override
@BeforeEach
public void setUp() throws Exception {
}
@Override
@AfterEach
public void tearDown() throws Exception {
}
@Test
public void testUserConstructorEmptyName() {
Assertions.assertThrows(InvalidParametersException.class, () -> {
new User("", UserType.Small);
});
}
@Test
public void testUserRequestCreation() {
// SMALL USER CASE
JobType expectedJobType1 = JobType.Short;
User user1 = new User("user1", UserType.Small);
Request q1 = user1.createRequest(0);
Job j1 = q1.getAssociatedJob();
JobType type1 = j1.getType();
Assertions.assertNotNull(j1, "The job associated to the user's created request is null.");
Assertions.assertEquals(expectedJobType1, type1);
// MEDIUM USER CASE
JobType expectedJobType2 = JobType.Medium;
User user2 = new User("user2", UserType.Medium);
Request q2 = user2.createRequest(0);
Job j2 = q2.getAssociatedJob();
JobType type2 = j2.getType();
Assertions.assertNotNull(j2, "The job associated to the user's created request is null.");
Assertions.assertEquals(expectedJobType2, type2);
// BIG USER CASE
User user3 = new User("user3", UserType.Big);
Request q3 = user3.createRequest(0);
Job j3 = q3.getAssociatedJob();
JobType type3 = j3.getType();
Assertions.assertNotNull(j3, "The job associated to the user's created request is null.");
Assertions.assertNotEquals(expectedJobType1, type3);
Assertions.assertNotEquals(expectedJobType2, type3);
}
}
<file_sep>package simulator.enumerators;
public enum UserType {
Small, Medium, Big;
}
<file_sep>package simulator.enumerators;
public enum JobType {
Short, Medium, Large, Huge;
}
<file_sep>package simulator.source;
public class Main {
public static void main(String[] args) {
Simulator sys = new Simulator();
sys.initialize();
Input.receiveParametersFromUser(sys);
Auxiliary.dumpQueueToExecution(sys);
Output.printResults(sys);
// NEXT LINE IS RELATED TO TESTS
// uncomment to run tests after program execution. (except performance tests due
// to the execution time increasing significantly)
// JUnitCore.main("simulator.tests.AllTests");
}
}
<file_sep>package simulator.source;
import simulator.exceptions.InvalidParametersException;
public class Group {
private String name;
private Double capBudget;
public Group(String name, Double budget) {
if (name.isEmpty())
throw new InvalidParametersException("The name of the group is empty.");
if (budget < 0)
throw new InvalidParametersException("The group budget must be positive.");
this.name = name;
capBudget = budget;
}
public String getName() {
return name;
}
public Double getRemainingBudget() {
return capBudget;
}
public void charge(Double cost) {
capBudget -= cost;
}
}
<file_sep>package simulator.source;
import simulator.exceptions.InvalidParametersException;
public class Curriculum {
private String name;
private Double capBudget;
public Curriculum(String name, Double budget) {
if (name.isEmpty())
throw new InvalidParametersException("The name of the curriculum is empty.");
if (budget < 0)
throw new InvalidParametersException("The curriculum budget must be positive.");
this.name = name;
capBudget = budget;
}
public String getName() {
return name;
}
public Double getRemainingBudget() {
return capBudget;
}
public void charge(Double cost) {
capBudget -= cost;
}
}
<file_sep>package simulator.source;
import simulator.enumerators.JobType;
import simulator.exceptions.InvalidParametersException;
public class Job {
private JobType type;
private Integer nodesNeeded;
private Integer hoursNeeded;
private Integer expectedStartingTime;
private Integer actualStartingTime;
public Job(JobType type, Integer nodes, Integer hours, Integer expectedStart) {
if (nodes <= 0 || nodes > 128)
throw new InvalidParametersException("The number of cores is not valid.");
if (hours <= 0)
throw new InvalidParametersException("The number of hours is invalid.");
if (expectedStart < 0)
throw new InvalidParametersException("The expected start time for this job must be greater than 0.");
this.type = type;
nodesNeeded = nodes;
hoursNeeded = hours;
expectedStartingTime = expectedStart;
actualStartingTime = 100000;
}
public JobType getType() {
return type;
}
public Integer getNodesNeeded() {
return nodesNeeded;
}
public Integer getHoursNeeded() {
return hoursNeeded;
}
public Integer getExpectedStartingTime() {
return expectedStartingTime;
}
public Integer getEndTime() {
return actualStartingTime + hoursNeeded;
}
public Integer getActualStartingTime() {
return actualStartingTime;
}
public Double getTurnaroundTime() {
Double time = (double) (((double) this.getEndTime() - (double) expectedStartingTime) / (double) hoursNeeded);
return (double) Math.round(time * 100) / 100;
}
public void rescheduleStartingTime(Integer time) {
actualStartingTime = time;
}
}
<file_sep>package simulator.tests;
import org.junit.Assert;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import junit.framework.TestCase;
import simulator.enumerators.JobType;
import simulator.enumerators.UserType;
import simulator.source.Auxiliary;
import simulator.source.ITSupport;
import simulator.source.Job;
import simulator.source.Request;
import simulator.source.Simulator;
public class SystemTest extends TestCase {
public SystemTest() {
super();
}
@BeforeAll
static void setUpBeforeClass() throws Exception {
}
@AfterAll
static void tearDownAfterClass() throws Exception {
}
@Override
@BeforeEach
public void setUp() throws Exception {
}
@Override
@AfterEach
public void tearDown() throws Exception {
}
@Test
public void testScenarioGeneration() {
Simulator sys = new Simulator();
sys.initialize();
Integer numberOfUsers = 100;
Double groupBudgets = 1000.0;
Auxiliary.generateScenario(sys, numberOfUsers, groupBudgets);
Assertions.assertFalse(sys.getUserList().isEmpty());
}
@Test
public void testSimulatorInitialization() {
Integer expectedNumberOfQueues = 4;
Integer expectedNumberOfNodes = 128;
Simulator sys = new Simulator();
sys.initialize();
Integer actualNumberOfQueues = sys.getQueueList().size();
Integer actualNumberOfNodes = sys.getNodeList().size();
Assert.assertEquals(
"The expected number of queues generated is " + expectedNumberOfQueues + " but the actual number was "
+ actualNumberOfQueues,
expectedNumberOfQueues, actualNumberOfQueues);
Assert.assertEquals(
"The expected number of nodes generated is " + expectedNumberOfNodes + " but the actual number was "
+ actualNumberOfNodes,
expectedNumberOfNodes, actualNumberOfNodes);
}
@Test
public void testSystemNoJobs() {
Integer numJobsExpected = 0;
Integer totalMachineHoursExpected = 0;
Double totalPaidByUsersExpected = 0.0;
Integer averageWaitingTime = 0;
Double averageTurnaroundTime = 0.0;
Double economicBalance = 10000.0;
Simulator sys = new Simulator();
sys.initialize();
Auxiliary.dumpQueueToExecution(sys);
Integer actualNumJobsProcessed = 0;
Integer actualTotalMachineHours = 0;
Double actualTotalPaidByUsers = 0.0;
Integer actualAverageWaitingTime = 0;
Double actualAverageTurnaroundTime = sys.getAverageTurnAroundTime();
Double actualEconomicBalance = (double) Math.round(sys.getEconomicBalance() * 100) / 100;
for (int i = 0; i < sys.getQueueList().size(); i++) {
actualNumJobsProcessed += sys.getQueueList().get(i).getNumJobsProcessed();
actualTotalMachineHours += sys.getQueueList().get(i).getTotalMachineHours();
actualTotalPaidByUsers += sys.getQueueList().get(i).getTotalPaidByUsers();
if (!sys.getQueueList().get(i).getJobList().isEmpty())
actualAverageWaitingTime += sys.getWaitingTimes()[i] / sys.getQueueList().get(i).getJobList().size();
else
actualAverageWaitingTime += 0;
}
Assert.assertEquals("The expected number of jobs processed is " + numJobsExpected
+ " but the number of jobs processed was " + actualNumJobsProcessed, numJobsExpected,
actualNumJobsProcessed);
Assert.assertEquals(
"The expected total machine hours consumed is " + totalMachineHoursExpected
+ " but the actual number of machine hours consumed was " + actualTotalMachineHours,
totalMachineHoursExpected, actualTotalMachineHours);
Assert.assertEquals(
"The expected total paid by users is " + totalPaidByUsersExpected
+ " but the actual total paid by users was " + actualTotalPaidByUsers,
totalPaidByUsersExpected, actualTotalPaidByUsers);
Assert.assertEquals(
"The expected average waiting time is " + averageWaitingTime
+ " but the actual average waiting time was " + actualAverageWaitingTime,
averageWaitingTime, actualAverageWaitingTime);
Assert.assertEquals(
"The expected average turnaround time is " + averageTurnaroundTime
+ " but the actual average turnaround time was " + actualAverageTurnaroundTime,
averageTurnaroundTime, actualAverageTurnaroundTime);
Assert.assertEquals(
"The expected economic balance of the centre is " + economicBalance
+ " but the actual economic balance was " + actualEconomicBalance,
economicBalance, actualEconomicBalance);
}
@Test
public void testSystem2ShortJobs() {
Integer numJobsExpected = 2;
Integer totalMachineHoursExpected = 2;
Double totalPaidByUsersExpected = 0.4;
Integer averageWaitingTime = 0;
Double averageTurnaroundTime = 1.0;
Double economicBalance = 10000.38;
Simulator sys = new Simulator();
ITSupport u1 = new ITSupport("user1", UserType.Small);
Job j1 = new Job(JobType.Short, 1, 1, 0);
Job j2 = new Job(JobType.Short, 1, 1, 0);
Request rq1 = new Request(j1, u1);
Request rq2 = new Request(j2, u1);
sys.initialize();
sys.getQueueList().get(0).processRequest(sys, rq1);
sys.getQueueList().get(0).processRequest(sys, rq2);
Auxiliary.dumpQueueToExecution(sys);
Integer actualNumJobsProcessed = 0;
Integer actualTotalMachineHours = 0;
Double actualTotalPaidByUsers = 0.0;
Integer actualAverageWaitingTime = 0;
Double actualAverageTurnaroundTime = sys.getAverageTurnAroundTime();
Double actualEconomicBalance = (double) Math.round(sys.getEconomicBalance() * 100) / 100;
for (int i = 0; i < sys.getQueueList().size(); i++) {
actualNumJobsProcessed += sys.getQueueList().get(i).getNumJobsProcessed();
actualTotalMachineHours += sys.getQueueList().get(i).getTotalMachineHours();
actualTotalPaidByUsers += sys.getQueueList().get(i).getTotalPaidByUsers();
if (!sys.getQueueList().get(i).getJobList().isEmpty())
actualAverageWaitingTime += sys.getWaitingTimes()[i] / sys.getQueueList().get(i).getJobList().size();
else
actualAverageWaitingTime += 0;
}
Assert.assertEquals("The expected number of jobs processed is " + numJobsExpected
+ " but the number of jobs processed was " + actualNumJobsProcessed, numJobsExpected,
actualNumJobsProcessed);
Assert.assertEquals(
"The expected total machine hours consumed is " + totalMachineHoursExpected
+ " but the actual number of machine hours consumed was "
+ actualTotalMachineHours,
totalMachineHoursExpected, actualTotalMachineHours);
Assert.assertEquals(
"The expected total paid by users is " + totalPaidByUsersExpected
+ " but the actual total paid by users was " + actualTotalPaidByUsers,
totalPaidByUsersExpected, actualTotalPaidByUsers);
Assert.assertEquals(
"The expected average waiting time is " + averageWaitingTime
+ " but the actual average waiting time was " + actualAverageWaitingTime,
averageWaitingTime, actualAverageWaitingTime);
Assert.assertEquals(
"The expected average turnaround time is " + averageTurnaroundTime
+ " but the actual average turnaround time was " + actualAverageTurnaroundTime,
averageTurnaroundTime, actualAverageTurnaroundTime);
Assert.assertEquals(
"The expected economic balance of the centre is " + economicBalance
+ " but the actual economic balance was " + actualEconomicBalance,
economicBalance, actualEconomicBalance);
}
@Test
public void testSystem2MediumJobs() {
Integer numJobsExpected = 2;
Integer totalMachineHoursExpected = 197;
Double totalPaidByUsersExpected = 4.4;
Integer averageWaitingTime = 1;
Double averageTurnaroundTime = 1.145;
Double economicBalance = 10002.43;
Simulator sys = new Simulator();
ITSupport u1 = new ITSupport("user1", UserType.Medium);
Job j1 = new Job(JobType.Medium, 37, 4, 25);
Job j2 = new Job(JobType.Medium, 7, 7, 27);
Request rq1 = new Request(j1, u1);
Request rq2 = new Request(j2, u1);
sys.initialize();
sys.getQueueList().get(1).processRequest(sys, rq1);
sys.getQueueList().get(1).processRequest(sys, rq2);
Auxiliary.dumpQueueToExecution(sys);
Integer actualNumJobsProcessed = 0;
Integer actualTotalMachineHours = 0;
Double actualTotalPaidByUsers = 0.0;
Integer actualAverageWaitingTime = 0;
Double actualAverageTurnaroundTime = sys.getAverageTurnAroundTime();
Double actualEconomicBalance = (double) Math.round(sys.getEconomicBalance() * 100) / 100;
for (int i = 0; i < sys.getQueueList().size(); i++) {
actualNumJobsProcessed += sys.getQueueList().get(i).getNumJobsProcessed();
actualTotalMachineHours += sys.getQueueList().get(i).getTotalMachineHours();
actualTotalPaidByUsers += sys.getQueueList().get(i).getTotalPaidByUsers();
if (!sys.getQueueList().get(i).getJobList().isEmpty())
actualAverageWaitingTime += sys.getWaitingTimes()[i] / sys.getQueueList().get(i).getJobList().size();
else
actualAverageWaitingTime += 0;
}
Assert.assertEquals("The expected number of jobs processed is " + numJobsExpected
+ " but the number of jobs processed was " + actualNumJobsProcessed, numJobsExpected,
actualNumJobsProcessed);
Assert.assertEquals(
"The expected total machine hours consumed is " + totalMachineHoursExpected
+ " but the actual number of machine hours consumed was " + actualTotalMachineHours,
totalMachineHoursExpected, actualTotalMachineHours);
Assert.assertEquals(
"The expected total paid by users is " + totalPaidByUsersExpected
+ " but the actual total paid by users was " + actualTotalPaidByUsers,
totalPaidByUsersExpected, actualTotalPaidByUsers);
Assert.assertEquals(
"The expected average waiting time is " + averageWaitingTime
+ " but the actual average waiting time was " + actualAverageWaitingTime,
averageWaitingTime, actualAverageWaitingTime);
Assert.assertEquals(
"The expected average turnaround time is " + averageTurnaroundTime
+ " but the actual average turnaround time was " + actualAverageTurnaroundTime,
averageTurnaroundTime, actualAverageTurnaroundTime);
Assert.assertEquals(
"The expected economic balance of the centre is " + economicBalance
+ " but the actual economic balance was " + actualEconomicBalance,
economicBalance, actualEconomicBalance);
}
@Test
public void testSystem2LargeJobs() {
Integer numJobsExpected = 2;
Integer totalMachineHoursExpected = 745;
Double totalPaidByUsersExpected = 12.0;
Integer averageWaitingTime = 3;
Double averageTurnaroundTime = 1.7;
Double economicBalance = 10004.55;
Simulator sys = new Simulator();
ITSupport u1 = new ITSupport("user1", UserType.Big);
Job j1 = new Job(JobType.Large, 60, 10, 42);
Job j2 = new Job(JobType.Large, 29, 5, 45);
Request rq1 = new Request(j1, u1);
Request rq2 = new Request(j2, u1);
sys.initialize();
sys.getQueueList().get(2).processRequest(sys, rq1);
sys.getQueueList().get(2).processRequest(sys, rq2);
Auxiliary.dumpQueueToExecution(sys);
Integer actualNumJobsProcessed = 0;
Integer actualTotalMachineHours = 0;
Double actualTotalPaidByUsers = 0.0;
Integer actualAverageWaitingTime = 0;
Double actualAverageTurnaroundTime = sys.getAverageTurnAroundTime();
Double actualEconomicBalance = (double) Math.round(sys.getEconomicBalance() * 100) / 100;
for (int i = 0; i < sys.getQueueList().size(); i++) {
actualNumJobsProcessed += sys.getQueueList().get(i).getNumJobsProcessed();
actualTotalMachineHours += sys.getQueueList().get(i).getTotalMachineHours();
actualTotalPaidByUsers += sys.getQueueList().get(i).getTotalPaidByUsers();
if (!sys.getQueueList().get(i).getJobList().isEmpty())
actualAverageWaitingTime += sys.getWaitingTimes()[i] / sys.getQueueList().get(i).getJobList().size();
else
actualAverageWaitingTime += 0;
}
Assert.assertEquals("The expected number of jobs processed is " + numJobsExpected
+ " but the number of jobs processed was " + actualNumJobsProcessed, numJobsExpected,
actualNumJobsProcessed);
Assert.assertEquals(
"The expected total machine hours consumed is " + totalMachineHoursExpected
+ " but the actual number of machine hours consumed was " + actualTotalMachineHours,
totalMachineHoursExpected, actualTotalMachineHours);
Assert.assertEquals(
"The expected total paid by users is " + totalPaidByUsersExpected
+ " but the actual total paid by users was " + actualTotalPaidByUsers,
totalPaidByUsersExpected, actualTotalPaidByUsers);
Assert.assertEquals(
"The expected average waiting time is " + averageWaitingTime
+ " but the actual average waiting time was " + actualAverageWaitingTime,
averageWaitingTime, actualAverageWaitingTime);
Assert.assertEquals(
"The expected average turnaround time is " + averageTurnaroundTime
+ " but the actual average turnaround time was " + actualAverageTurnaroundTime,
averageTurnaroundTime, actualAverageTurnaroundTime);
Assert.assertEquals(
"The expected economic balance of the centre is " + economicBalance
+ " but the actual economic balance was " + actualEconomicBalance,
economicBalance, actualEconomicBalance);
}
@Test
public void testSystem2HugeJobs() {
Integer numJobsExpected = 2;
Integer totalMachineHoursExpected = 4757;
Double totalPaidByUsersExpected = 64.0;
Integer averageWaitingTime = 6;
Double averageTurnaroundTime = 1.31;
Double economicBalance = 10016.43;
Simulator sys = new Simulator();
ITSupport u1 = new ITSupport("user1", UserType.Big);
ITSupport u2 = new ITSupport("user2", UserType.Big);
Job j1 = new Job(JobType.Huge, 110, 19, 104);
Job j2 = new Job(JobType.Huge, 127, 21, 110);
Request rq1 = new Request(j1, u1);
Request rq2 = new Request(j2, u2);
sys.initialize();
sys.getQueueList().get(3).processRequest(sys, rq1);
sys.getQueueList().get(3).processRequest(sys, rq2);
Auxiliary.dumpQueueToExecution(sys);
Integer actualNumJobsProcessed = 0;
Integer actualTotalMachineHours = 0;
Double actualTotalPaidByUsers = 0.0;
Integer actualAverageWaitingTime = 0;
Double actualAverageTurnaroundTime = sys.getAverageTurnAroundTime();
Double actualEconomicBalance = (double) Math.round(sys.getEconomicBalance() * 100) / 100;
for (int i = 0; i < sys.getQueueList().size(); i++) {
actualNumJobsProcessed += sys.getQueueList().get(i).getNumJobsProcessed();
actualTotalMachineHours += sys.getQueueList().get(i).getTotalMachineHours();
actualTotalPaidByUsers += sys.getQueueList().get(i).getTotalPaidByUsers();
if (!sys.getQueueList().get(i).getJobList().isEmpty())
actualAverageWaitingTime += sys.getWaitingTimes()[i] / sys.getQueueList().get(i).getJobList().size();
else
actualAverageWaitingTime += 0;
}
Assert.assertEquals("The expected number of jobs processed is " + numJobsExpected
+ " but the number of jobs processed was " + actualNumJobsProcessed, numJobsExpected,
actualNumJobsProcessed);
Assert.assertEquals(
"The expected total machine hours consumed is " + totalMachineHoursExpected
+ " but the actual number of machine hours consumed was " + actualTotalMachineHours,
totalMachineHoursExpected, actualTotalMachineHours);
Assert.assertEquals(
"The expected total paid by users is " + totalPaidByUsersExpected
+ " but the actual total paid by users was " + actualTotalPaidByUsers,
totalPaidByUsersExpected, actualTotalPaidByUsers);
Assert.assertEquals(
"The expected average waiting time is " + averageWaitingTime
+ " but the actual average waiting time was " + actualAverageWaitingTime,
averageWaitingTime, actualAverageWaitingTime);
Assert.assertEquals(
"The expected average turnaround time is " + averageTurnaroundTime
+ " but the actual average turnaround time was " + actualAverageTurnaroundTime,
averageTurnaroundTime, actualAverageTurnaroundTime);
Assert.assertEquals(
"The expected economic balance of the centre is " + economicBalance
+ " but the actual economic balance was " + actualEconomicBalance,
economicBalance, actualEconomicBalance);
}
@Test
public void testSystem1JobOfEachType() {
Integer numJobsExpected = 4;
Integer totalMachineHoursExpected = 3115;
Double totalPaidByUsersExpected = 62.6;
Integer averageWaitingTime = 0;
Double averageTurnaroundTime = 1.0;
Double economicBalance = 10031.45;
Simulator sys = new Simulator();
ITSupport u1 = new ITSupport("user1", UserType.Small);
ITSupport u2 = new ITSupport("user2", UserType.Medium);
ITSupport u3 = new ITSupport("user3", UserType.Big);
ITSupport u4 = new ITSupport("user4", UserType.Big);
Job j1 = new Job(JobType.Short, 1, 1, 96);
Job j2 = new Job(JobType.Medium, 9, 6, 15);
Job j3 = new Job(JobType.Large, 46, 15, 37);
Job j4 = new Job(JobType.Huge, 79, 30, 105);
Request rq1 = new Request(j1, u1);
Request rq2 = new Request(j2, u2);
Request rq3 = new Request(j3, u3);
Request rq4 = new Request(j4, u4);
sys.initialize();
sys.getQueueList().get(0).processRequest(sys, rq1);
sys.getQueueList().get(1).processRequest(sys, rq2);
sys.getQueueList().get(2).processRequest(sys, rq3);
sys.getQueueList().get(3).processRequest(sys, rq4);
Auxiliary.dumpQueueToExecution(sys);
Integer actualNumJobsProcessed = 0;
Integer actualTotalMachineHours = 0;
Double actualTotalPaidByUsers = 0.0;
Integer actualAverageWaitingTime = 0;
Double actualAverageTurnaroundTime = sys.getAverageTurnAroundTime();
Double actualEconomicBalance = (double) Math.round(sys.getEconomicBalance() * 100) / 100;
for (int i = 0; i < sys.getQueueList().size(); i++) {
actualNumJobsProcessed += sys.getQueueList().get(i).getNumJobsProcessed();
actualTotalMachineHours += sys.getQueueList().get(i).getTotalMachineHours();
actualTotalPaidByUsers += sys.getQueueList().get(i).getTotalPaidByUsers();
if (!sys.getQueueList().get(i).getJobList().isEmpty())
actualAverageWaitingTime += sys.getWaitingTimes()[i] / sys.getQueueList().get(i).getJobList().size();
else
actualAverageWaitingTime += 0;
}
Assert.assertEquals("The expected number of jobs processed is " + numJobsExpected
+ " but the number of jobs processed was " + actualNumJobsProcessed, numJobsExpected,
actualNumJobsProcessed);
Assert.assertEquals(
"The expected total machine hours consumed is " + totalMachineHoursExpected
+ " but the actual number of machine hours consumed was " + actualTotalMachineHours,
totalMachineHoursExpected, actualTotalMachineHours);
Assert.assertEquals(
"The expected total paid by users is " + totalPaidByUsersExpected
+ " but the actual total paid by users was " + actualTotalPaidByUsers,
totalPaidByUsersExpected, actualTotalPaidByUsers);
Assert.assertEquals(
"The expected average waiting time is " + averageWaitingTime
+ " but the actual average waiting time was " + actualAverageWaitingTime,
averageWaitingTime, actualAverageWaitingTime);
Assert.assertEquals(
"The expected average turnaround time is " + averageTurnaroundTime
+ " but the actual average turnaround time was " + actualAverageTurnaroundTime,
averageTurnaroundTime, actualAverageTurnaroundTime);
Assert.assertEquals(
"The expected economic balance of the centre is " + economicBalance
+ " but the actual economic balance was " + actualEconomicBalance,
economicBalance, actualEconomicBalance);
}
}
<file_sep>package simulator.exceptions;
public class InvalidParametersException extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidParametersException() {
super();
}
public InvalidParametersException(String s) {
super(s);
}
}
<file_sep>package simulator.source;
import simulator.enumerators.UserType;
import simulator.exceptions.InvalidParametersException;
public class Researcher extends User {
private Group group;
private Double additionalBudget;
public Researcher(String username, Group group, Double grant, UserType type) {
super(username, type);
if (username.isEmpty())
throw new InvalidParametersException("The username of the researcher user is empty.");
if (group == null)
throw new InvalidParametersException("The group this researcher belongs to can not be null.");
if (grant < 0.0)
throw new InvalidParametersException(
"The additional resources granted to the researcher must be positive.");
this.group = group;
additionalBudget = grant;
totalBudget = grant + group.getRemainingBudget();
}
public Group getGroup() {
return group;
}
public Double getGrantQty() {
return additionalBudget;
}
@Override
public void charge(Double cost) {
if (group.getRemainingBudget() < cost && additionalBudget > cost) {
additionalBudget -= cost;
totalBudget -= cost;
} else if (group.getRemainingBudget() < cost && additionalBudget < cost)
System.out.println(this.getName() + " does not have sufficient funds.");
else {
group.charge(cost);
totalBudget -= cost;
}
}
}
<file_sep>package simulator.tests;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import junit.framework.TestCase;
import simulator.enumerators.UserType;
import simulator.exceptions.InvalidParametersException;
import simulator.source.ITSupport;
public class ITSupportTest extends TestCase {
public ITSupportTest() {
super();
}
@BeforeAll
static void setUpBeforeClass() throws Exception {
}
@AfterAll
static void tearDownAfterClass() throws Exception {
}
@Override
@BeforeEach
public void setUp() throws Exception {
}
@Override
@AfterEach
public void tearDown() throws Exception {
}
@Test
public void testITSupportConstructorEmptyName() {
Assertions.assertThrows(InvalidParametersException.class, () -> {
new ITSupport("", UserType.Small);
});
}
}
<file_sep>package simulator.source;
import java.util.Locale;
import java.util.Scanner;
import simulator.exceptions.InvalidParametersException;
public class Input {
public static void receiveParametersFromUser(Simulator sys) {
Integer usrNum;
Double budgets;
Scanner sc = new Scanner(System.in);
sc.useLocale(Locale.US);// so the input allows a dot instead of a comma for expressing doubles.
System.out.println("Insert the number of users desired: ");
usrNum = sc.nextInt();
checkNumberOfUSers(usrNum);
System.out.println("Insert the budget for groups and curriculums: ");
budgets = sc.nextDouble();
checkBudgets(budgets);
sc.close();
Auxiliary.generateScenario(sys, usrNum, budgets);
}
public static void checkNumberOfUSers(Integer usrNum) {
if (usrNum < 0)
throw new InvalidParametersException("The number of users should be positive.");
}
public static void checkBudgets(Double budgets) {
if (budgets < 0.0)
throw new InvalidParametersException("The budgets for groups and curriculums should be positive.");
}
}
<file_sep>package simulator.source;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import simulator.enumerators.JobType;
import simulator.enumerators.UserType;
public class Auxiliary {
public static void generateScenario(Simulator sys, Integer numberOfUsers, Double groupBudgets) {
Random randomGen = new Random();
Group g = new Group("Group 1", groupBudgets);
Curriculum c = new Curriculum("Computational Methods", groupBudgets);
Integer nextJobStartTime = 0;
for (int i = 0; i < numberOfUsers; i++) {
Integer userType = randomGen.nextInt(3);
Integer userRole = randomGen.nextInt(3);
Integer numJobsPerUser = (int) (getNextExpDistr(2) + 1); // let's say that on average, each user sends 2 job
// requests. We add 1 because we want to make
// sure that no user sends 0 requests.
nextJobStartTime = (nextJobStartTime % 103) + (int) (getNextExpDistr(3).longValue()); // here, we make sure
// that the start
// hours don't go
// over the cutoff
// time by reducing
// the previous
// nextJobStartTime
// with the module
// of the start
// time.
switch(userRole) {
case 0:
ITSupport it;
if (userType == 0)
it = new ITSupport("user" + i, UserType.Small);
else if (userType == 1)
it = new ITSupport("user" + i, UserType.Medium);
else
it = new ITSupport("user" + i, UserType.Big);
for (int j = 0; j < numJobsPerUser; j++) {
scheduler(sys, it.createRequest(nextJobStartTime));
nextJobStartTime = (nextJobStartTime % 103) + (int) (getNextExpDistr(3).longValue());
}
sys.addUser(it);
break;
case 1:
Researcher r;
if (userType == 0)
r = new Researcher("user" + i, g, 5.0, UserType.Small);
else if (userType == 1)
r = new Researcher("user" + i, g, 5.0, UserType.Medium);
else
r = new Researcher("user" + i, g, 5.0, UserType.Big);
for (int j = 0; j < numJobsPerUser; j++) {
scheduler(sys, r.createRequest(nextJobStartTime));
nextJobStartTime = (nextJobStartTime % 103) + (int) (getNextExpDistr(3).longValue());
}
sys.addUser(r);
break;
default:
Student s;
if (userType == 0)
s = new Student("user" + i, c, UserType.Small);
else if (userType == 1)
s = new Student("user" + i, c, UserType.Medium);
else
s = new Student("user" + i, c, UserType.Big);
for (int j = 0; j < numJobsPerUser; j++) {
scheduler(sys, s.createRequest(nextJobStartTime));
nextJobStartTime = (nextJobStartTime % 103) + (int) (getNextExpDistr(3).longValue());
}
sys.addUser(s);
break;
}
}
}
public static void scheduler(Simulator sys, Request r) {
Integer designatedQueue = 0;
switch(r.getAssociatedJob().getType().toString()) { //The queues are referenced by their position in the queueList in the System.
case "Short":
designatedQueue = 0;
break;
case "Medium":
designatedQueue = 1;
break;
case "Large":
designatedQueue = 2;
break;
case "Huge":
designatedQueue = 3;
break;
}
sys.getQueueList().get(designatedQueue).processRequest(sys, r);
sortQueues(sys); // The first-come first-serve sorting is carried out by this function. If the
// criterion for preference of request processing is to be modified, the sorting
// function should replace this one.
}
public static void sortQueues(Simulator sys) { // Essentially,this function sorts the jobs by the start date
// attribute.
for(int i = 0; i < sys.getQueueList().size(); i++) {
Queue currentQueue = sys.getQueueList().get(i);
sys.getQueueList().get(i).updateJobList(currentQueue.getJobList().stream()
.sorted((x, y) -> x.getExpectedStartingTime().compareTo(y.getExpectedStartingTime()))
.collect(Collectors.toList()));
}
}
public static void dumpQueueToExecution(Simulator sys) {
List<List<Job>> allJobs = sys.getQueueList().stream().map(x -> x.getJobList()).collect(Collectors.toList());
List<Job> currentQueue;
for (int i = 0; i < allJobs.size(); i++) {
Integer currentStartTime = 0;
currentQueue = allJobs.get(i);
if (currentQueue.isEmpty()) {
continue;
}
if (i == 3)
currentStartTime = 103;
Job currentJob = currentQueue.get(0);
for (int j = 0; j < currentQueue.size(); j++) {
currentJob = currentQueue.get(j);
if (currentJob.getType() != JobType.Huge && currentStartTime + currentJob.getHoursNeeded() > 103) {
System.out.println(
currentJob.getType() + " job " + j + " will go over the cut off time after waiting.");
currentQueue.remove(j);
sys.getQueueList().get(i).removeJobFromQueue(currentJob);
} else if (currentJob.getType() == JobType.Huge
&& currentStartTime + currentJob.getHoursNeeded() > 167) {
System.out.println(
currentJob.getType() + " job " + j + " will go over the weekend queue time after waiting.");
currentQueue.remove(j);
sys.getQueueList().get(i).removeJobFromQueue(currentJob);
} else if (checkAvailability(sys, currentStartTime, currentJob, currentQueue, i)
&& currentStartTime >= currentJob.getExpectedStartingTime()) {
Integer previousActualStartTime = currentQueue.get(j).getActualStartingTime();
currentQueue.get(j).rescheduleStartingTime(currentStartTime);
if (checkAvailability(sys, currentStartTime, currentJob, currentQueue, i)) {
sys.getQueueList().get(i).getJobList().get(j).rescheduleStartingTime(currentStartTime);
sys.increaseWaitingTimeForQueue(i,
currentJob.getActualStartingTime() - currentJob.getExpectedStartingTime());
sys.increaseTurnAroundtime(currentJob.getTurnaroundTime());
// THIS COMMENT BLOCK CAN BE USEFUL TO SEE ALL TASKS IN EXECUTION
// System.out.println(currentJob.getActualStartingTime() + " " +
// currentJob.getEndTime() + " "
// + currentJob.getType() + " " + currentJob.getHoursNeeded() + " "
// + currentJob.getNodesNeeded());
} else {
currentQueue.get(j).rescheduleStartingTime(previousActualStartTime);
j--;
currentStartTime++;
}
} else {
j--;
currentStartTime++;
}
}
sys.receivePayment(sys.getQueueList().get(i).getTotalPaidByUsers());
sys.addToExecution(currentQueue);
}
sys.applyOperationalCosts();
}
public static Boolean checkAvailability(Simulator sys, Integer currentStartTime, Job currentJob,
List<Job> currentQueue, Integer queueNumber) {
Integer coresBeingUsed = 0;
Boolean availability = true;
for (int i = 0; i < currentQueue.size(); i++) {
if (currentQueue.get(i).getEndTime() > currentStartTime
&& currentQueue.get(i).getActualStartingTime() <= currentStartTime) {
coresBeingUsed += currentQueue.get(i).getNodesNeeded();
}
}
switch (queueNumber) {
case 0:
if (coresBeingUsed > 12)
availability = false;
break;
case 1:
if (coresBeingUsed > 38)
availability = false;
break;
case 2:
if (coresBeingUsed > 64)
availability = false;
break;
case 3:
if (coresBeingUsed > 128)
availability = false;
break;
}
return availability;
}
public static Double getNextExpDistr(Integer range) {
Random rand = new Random();
return (Math.log(1 - rand.nextDouble()) / (-1)) * range;
}
}
<file_sep>package simulator.tests;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import junit.framework.TestCase;
import simulator.source.Auxiliary;
import simulator.source.Output;
import simulator.source.Simulator;
public class PerformanceTest extends TestCase {
public PerformanceTest() {
super();
}
@BeforeAll
static void setUpBeforeClass() throws Exception {
}
@AfterAll
static void tearDownAfterClass() throws Exception {
}
@Override
@BeforeEach
public void setUp() throws Exception {
}
@Override
@AfterEach
public void tearDown() throws Exception {
}
@Test
public void test1000Users() {
Double startTime = 0.0;
Double endTime = 0.0;
startTime = (double) System.currentTimeMillis();
Simulator sys = new Simulator();
sys.initialize();
Auxiliary.generateScenario(sys, 1000, 15000.0);
Auxiliary.dumpQueueToExecution(sys);
Output.printResults(sys);
endTime = (double) System.currentTimeMillis();
Double timeSpent = (endTime - startTime) / 1000.0;
System.out.println("The program took " + timeSpent + " seconds to finish.");
}
@Test
public void test5000Users() {
Double startTime = 0.0;
Double endTime = 0.0;
startTime = (double) System.currentTimeMillis();
Simulator sys = new Simulator();
sys.initialize();
Auxiliary.generateScenario(sys, 5000, 15000.0);
Auxiliary.dumpQueueToExecution(sys);
Output.printResults(sys);
endTime = (double) System.currentTimeMillis();
Double timeSpent = (endTime - startTime) / 1000.0;
System.out.println("The program took " + timeSpent + " seconds to finish.");
}
@Test
public void test9000Users() {
Double startTime = 0.0;
Double endTime = 0.0;
startTime = (double) System.currentTimeMillis();
Simulator sys = new Simulator();
sys.initialize();
Auxiliary.generateScenario(sys, 9000, 15000.0);
Auxiliary.dumpQueueToExecution(sys);
Output.printResults(sys);
endTime = (double) System.currentTimeMillis();
Double timeSpent = (endTime - startTime) / 1000.0;
System.out.println("The program took " + timeSpent + " seconds to finish.");
}
@Test
public void test12000Users() {
Double startTime = 0.0;
Double endTime = 0.0;
startTime = (double) System.currentTimeMillis();
Simulator sys = new Simulator();
sys.initialize();
Auxiliary.generateScenario(sys, 12000, 15000.0);
Auxiliary.dumpQueueToExecution(sys);
Output.printResults(sys);
endTime = (double) System.currentTimeMillis();
Double timeSpent = (endTime - startTime) / 1000.0;
System.out.println("The program took " + timeSpent + " seconds to finish.");
}
}<file_sep>package simulator.source;
import simulator.enumerators.UserType;
import simulator.exceptions.InvalidParametersException;
public class Student extends User {
private Curriculum curriculum;
public Student(String username, Curriculum curriculum, UserType type) {
super(username, type);
if (username.isEmpty())
throw new InvalidParametersException("The username of the student user is empty.");
if (curriculum == null)
throw new InvalidParametersException("The curriculum this student belongs to can not be null.");
this.curriculum = curriculum;
totalBudget = curriculum.getRemainingBudget();
}
public Curriculum getCurriculum() {
return curriculum;
}
@Override
public void charge(Double cost) {
if (curriculum.getRemainingBudget() < cost) {
System.out.println(this.getName() + " does not have sufficient funds.");
} else {
curriculum.charge(cost);
totalBudget -= cost;
}
}
}
<file_sep>package simulator.enumerators;
public enum QueueType {
Short, Medium, Large, Huge;
}
| 6f599670e78cb3ab6fdef1cbed4d139e5ee5ef37 | [
"Java"
] | 16 | Java | aleruirod/BatchSystemSimulator | b7db85e0974aa82fab9fc595fcef3f9ff13dccd3 | c3e4ea5dfde014cd93cee9f2ff90ce623c908f2e |
refs/heads/main | <repo_name>mlukow/floating_point<file_sep>/fp_wrong.swift
import Metal
func test(device: MTLDevice) {
print("Testing on \(device.name)")
let url = URL(fileURLWithPath: "library.metallib")
guard let library = try? device.makeLibrary(URL: url) else {
return print("Could not create library")
}
guard let function = library.makeFunction(name: "iter") else {
return print("Could not create function")
}
do {
let state = try device.makeComputePipelineState(function: function)
guard let queue = device.makeCommandQueue() else {
return print("Could not create queue")
}
guard let commandBuffer = queue.makeCommandBuffer() else {
return print("Could not create command buffer")
}
guard let commandEncoder = commandBuffer.makeComputeCommandEncoder() else {
return print("Could not create compute command encoder")
}
commandEncoder.setComputePipelineState(state)
var data = [Float](repeating: 0, count: 32)
data[0] = 2
data[1] = -4
guard let input = device.makeBuffer(bytes: &data, length: data.count * MemoryLayout<Float>.size, options: .storageModeShared) else {
return print("Could not create buffer")
}
commandEncoder.setBuffer(input, offset: 0, index: 0)
let size = MTLSizeMake(1, 1, 1)
commandEncoder.dispatchThreads(MTLSizeMake(32, 1, 1), threadsPerThreadgroup: size)
commandEncoder.endEncoding()
commandBuffer.commit()
commandBuffer.waitUntilCompleted()
let nsData = NSData(bytesNoCopy: input.contents(), length: data.count * MemoryLayout<Float>.size, freeWhenDone: false)
data = [Float].init(repeating: 0, count: data.count)
nsData.getBytes(&data, length:data.count * MemoryLayout<Float>.size)
print("\(data[data.count - 1])")
} catch {
return print("Could not create state: \(error)")
}
}
MTLCopyAllDevices().forEach { device in
test(device: device)
}
<file_sep>/README.md
# floating_point
Kahan-Muller test for hardware floating point implementation
<file_sep>/fp_wrong.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
float u = 2.0f;
float v = -4.0f;
for (size_t i = 0; i < 90; i++) {
float w = 111.0f - 1130.f / v + 3000.0f / (u * v);
u = v;
v = w;
}
printf("%-16.12f\n", v);
return EXIT_SUCCESS;
}
<file_sep>/fp_wrong128.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
long double u = 2.0L;
long double v = -4.0L;
for (size_t i = 0; i < 90; i++) {
long double w = 111.0L - 1130.0L / v + 3000.0L / (u * v);
u = v;
v = w;
}
printf("%-16.12Lf\n", v);
return EXIT_SUCCESS;
}
<file_sep>/make_library.sh
#!/bin/sh
xcrun -sdk macosx metal -c library.metal -o library.air && xcrun -sdk macosx metallib library.air -o library.metallib && rm library.air
<file_sep>/fp_wrongcl.c
#include <stdio.h>
#include <stdlib.h>
#include <OpenCL/opencl.h>
const char *KernelSource =
"__kernel void iter(__global long double *input, const size_t count) { \n" \
" for (size_t i = 2; i < count; i++) { \n" \
" input[i] = 111.0L - 1130.0L / input[i - 1] + 3000.0L / (input[i - 2] * input[i - 1]); \n" \
" } \n" \
"}";
int main(void) {
int err;
cl_device_id device_id;
clGetDeviceIDs(NULL, CL_DEVICE_TYPE_GPU, 1, &device_id, NULL);
cl_context context = clCreateContext(0, 1, &device_id, NULL, NULL, &err);
if (err != CL_SUCCESS) {
printf("failed to create context\n");
return err;
}
cl_command_queue commands = clCreateCommandQueue(context, device_id, 0, &err);
if (err != CL_SUCCESS) {
printf("failed to create command queue\n");
return err;
}
cl_program program = clCreateProgramWithSource(context, 1, &KernelSource, NULL, &err);
if (err != CL_SUCCESS) {
printf("failed to create program\n");
return err;
}
err = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
if (err != CL_SUCCESS) {
printf("failed to build program\n");
return err;
}
cl_kernel kernel = clCreateKernel(program, "iter", &err);
if (err != CL_SUCCESS) {
printf("failed to create kernel\n");
return err;
}
size_t count = 32;
cl_mem input = clCreateBuffer(context, CL_MEM_READ_ONLY, count * sizeof(long double), NULL, NULL);
long double data[count];
data[0] = 2.0L;
data[1] = -4.0L;
err = clEnqueueWriteBuffer(commands, input, CL_TRUE, 0, count * sizeof(long double), data, 0, NULL, NULL);
if (err != CL_SUCCESS) {
printf("failed to enqueue write buffer\n");
return err;
}
clSetKernelArg(kernel, 0, sizeof(cl_mem), &input);
clSetKernelArg(kernel, 1, sizeof(size_t), &count);
err = clEnqueueTask(commands, kernel, 0, NULL, NULL);
if (err != CL_SUCCESS) {
printf("failed to enqueue task\n");
return err;
}
clFinish(commands);
long double results[count];
clEnqueueReadBuffer(commands, input, CL_TRUE, 0, count * sizeof(long double), results, 0, NULL, NULL);
for (size_t i = 0; i < count; i++) {
printf("u[%2zu] = %-16.12Le\n", i, results[i]);
}
clReleaseMemObject(input);
clReleaseProgram(program);
clReleaseKernel(kernel);
clReleaseCommandQueue(commands);
clReleaseContext(context);
return EXIT_SUCCESS;
}
| 9abd6f00c65b04cd36896103ef1141452d72a54c | [
"Swift",
"C",
"Markdown",
"Shell"
] | 6 | Swift | mlukow/floating_point | 18dd1b3d786b3d648feafe67fe2eb04dfa1b6e03 | 7e4a0d5d97b3bec5959651858b517602f3cb2cbb |
refs/heads/master | <file_sep># todoapp
A simple ToDo app with html, css, js and jQuery.
Site is published at https://prosperevergreen.github.io/todoapp/
<file_sep>
$("ul").on("click", ".todo-text", function () {
$(this).toggleClass("completed");
$(this).siblings().toggleClass("completed");
})
$("ul").on("click", ".delete", function (event) {
$(this).parent().fadeOut(500, function () {
$(this).remove();
});
event.stopPropagation();
})
var todoTextBegin = '<li><span class="delete"><i class="far fa-trash-alt"></i></span><span class="todo-text">';
var todoTextEnd = '</span>';
var todoDate = '<span class="todo-date">@';
var listEnd = '</span></li>';
$(".fa-plus").on("click", function (event) {
var newTodoText = $(".new-todo").val();
var newDate = $(".new-date").val();
if (newDate === "" || newTodoText === "") {
if (newDate === "") {
errrorField($(".new-date"));
}
if (newTodoText === "") {
errrorField($(".new-todo"));
}
}
else {
$(".new-todo").val("");
$(".new-date").val("");
$("ul").append(todoTextBegin + newTodoText + todoTextEnd + todoDate + newDate + listEnd);
}
})
$(".todo-input").children().on("focus", function () {
$(this).removeClass("error");
})
function errrorField(field) {
field.toggleClass("error");
}
| 8170947182bd87f083341061b2541345b02b571b | [
"Markdown",
"JavaScript"
] | 2 | Markdown | prosperevergreen/todoapp | 2431d2df54c3cbc002b4227a12e836171f220a2b | ff5ef3c798d814e29d2ae4fb8309e314cac9402c |
refs/heads/master | <file_sep>import Home from './pages/Home'
import About from './pages/About'
import Contact from './pages/Contact'
export default [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact }
]
<file_sep>
## Project Wyvern Main Website
[](https://opensource.org/licenses/MIT)
Automatically published to [projectwyvern.com](https://projectwyvern.com).
<file_sep>import Vue from 'vue'
import Vuetify from 'vuetify'
import VueMeta from 'vue-meta'
import VueRouter from 'vue-router'
import 'vue-awesome/icons'
import Icon from 'vue-awesome/components/Icon'
import VueAnalytics from 'vue-analytics'
import VueScrollTo from 'vue-scrollto'
import App from './App.vue'
import routes from './routes.js'
import '../node_modules/vuetify/dist/vuetify.min.css'
Vue.component('icon', Icon)
Vue.use(Vuetify)
Vue.use(VueRouter)
Vue.use(VueMeta)
Vue.use(VueScrollTo)
const router = new VueRouter({ routes: routes, mode: 'history' })
Vue.use(VueAnalytics, {
id: 'UA-98270549-3',
router
})
/* eslint-disable no-new */
new Vue({
router,
el: '#app',
render: h => h(App)
})
| 21a3d66f868b0f3560031d63fdcd62cc8bcc323d | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | ProjectWyvern/projectwyvern.com | 585c448e4970f47b1161e2056ee3ec5dfd842dad | 693963011edc01dedb36dd8fa6879e9a914c5ee5 |
refs/heads/master | <file_sep>How to import
=============
**NOTE: THIS DOCUMENT IS A WORK IN PROGRESS**
**ALSO: THE IMPORT HAS NOT YET BEEN APPROVED BY THE OPENSTREETMAP COMMUNITY**
**DO NOT IMPORT ANY DATA UNTIL THESE INSTRUCTIONS HAVE BEEN FINALIZED AND THE IMPORT HAS BEEN APPROVED**
## Getting started
### Creating an import account
* OSM best practices require that you do not use your normal OSM account for the imports. Create a new account for this purpose.
Usually, it's your existing OSM username followed by `_imports` (e.g. `maning_imports)`.
Post your import account username in this [ticket](http://github.com/osmlab/labuildings/issues/40).
### Getting familiar with JOSM
To contribute to this project, you need to use the JOSM editor. Here are some resources to get you started:
* LearnOSM - http://learnosm.org/en/josm/
* Mapbox Mapping wiki - https://www.mapbox.com/blog/making-the-most-josm/
### Check out a task on the tasking manager
* Tasks will be available on this **[Tasking Manager](http://172.16.58.3:6543/project/15 link soon)**.
* Priority: we are working on Los Angeles City first, which is broken down by census block groups. Each task performed is one block group within the city boundaries.
* why? because different parts of the county have different data problems to watch out for. If we all run into the same problems at the same time, it will be easier for us to help each other and improve the processing scripts and the import workflow.
## Import workflow
* Choose which area you want to work on. (Browse the tasking manager and visualization of existing building and address data).
* Load the `.osm` file from the tasking manager.

* Review the `.osm` file for inconsistencies and FIXME tags.
* Run JOSM **Validator**, fix the data.

* Download the current OSM data for the bounding box of the `.osm` file.

* Compare both data for conflicts.
* If there are any problems you don't know how to deal with, do not proceed. Instead flag the `.osm` file for a more advanced user to look at. (Use github [issues](http://github.com/osmlab/labuildings/issues) to flag concerns, and/or create [OSM notes](http://wiki.openstreetmap.org/wiki/Notes)). Then unlock your task on the tasking manager and pick a new area to work on.
* Manually merge the layers together: preserve the work of previous mappers wherever possible. Copy address information and building height to existing building shapes if they are of higher quality.
* Use **Replace geometry** to merge.

* Run JOSM Validator again, fix the data.
### Finally, upload it
* Add the tag `#labuildings` to your changesets.

## What to watch out for
### Validate the import with your eyes before uploading!
* Run the [JOSM validator](http://wiki.openstreetmap.org/wiki/JOSM/Validator). Check for any errors it detects.
* Look for any [FIXME](http://wiki.openstreetmap.org/wiki/Key:fixme) tags that the processing scripts generated. These are areas that need human oversight.
* Check for small building parts that should be joined to the main building. We've already found a few examples of these in the data (see [issue #19](https://github.com/osmlab/labuildings/issues/19)), so make sure you keep an eye out for these.
* Inspect everything else with a critical eye! Don't trust that the validator or FIXME tags will catch everything. There may be other bugs that only you can detect. Use your human smarts!
### Conflating with existing data
* Look for any overlaps with existing buildings. Existing buildings in OSM are probably _more_ up-to-date than our imported data. Do not assume the imported data is better, mostly likely it is worse!
* Carefully combine the import data with the existing OSM data. If you aren't sure about some tags, ask someone! Especially ask the original mapper!
### How to ground-truth the data
* Up-to-date aerial imagery... try several sources
* See if the street is on [Mapillary](http://www.mapillary.com/map/im/bbox/33.65806700735439/34.410308669603495/-119.10278320312499/-117.3504638671875)
* Go out and check it out yourself! Take a field trip!
* **DO NOT USE GOOGLE MAPS OR GOOGLE STREET VIEW**
### Identifying New Buildings with imported and existing data
* Aerial Imagery used as a basemap should help to identify and draw newer buildings not found in the imported an existing data.
* Newer building should be identified and flagged. (This process should not be done, pending approval and recommendations from the OSM Community.)
## Communicate communicate communicate!
### How to ask for help
* Create [issues](http://github.com/osmlab/labuildings/issues) on this github repo.
* Ask questions on the [gitter channel](http://gitter.im/osmlab/labuildings).
* Contact [@almccon](http://twitter.com/almccon), [@cityhubla](http://twitter.com/cityhubla), [@jschleuss](http://twitter.com/jschleuss), [@maningsambale](http://twitter.com/maningsambale).
### How to share your progress
* Make sure you close your task on the tasking manager
### How to communicate with other mappers
* JOSM [GeoChat](http://wiki.openstreetmap.org/wiki/JOSM/Plugins/GeoChat) feature
* Twitter hashtag (TBD)
* Befriend other mappers on openstreetmap.com
<file_sep>LA Buildings
===========
[](https://gitter.im/osmlab/labuildings?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
Los Angeles County building and address import
Generates an OSM file of buildings with addresses per census block groups,
ready to be used in JOSM for a manual review and upload to OpenStreetMap. This repository is based heavily on the [NYC building import](https://github.com/osmlab/nycbuildings)
This README is about data conversion. See also the [page on the OSM wiki](https://wiki.openstreetmap.org/wiki/Los_angeles,_California/Buildings_Import).
**HOW YOU CAN GET INVOLVED:** You may want to browse the [issues](https://github.com/osmlab/labuildings/issues) and/or "watch" this repo (see button at the top of this page) to follow along with the discussion. Also join the chat room on [Gitter](https://gitter.im/osmlab/labuildings)!
| Phase | Task | Contact |
| ------------- |:-------------:| -----:|
| Attributes to be Imported | Select which fields will be imported and prepend (associate) with an OSM tag [Google Spreadsheet](https://docs.google.com/spreadsheets/d/1A3whba04_-3K0z77nGHYavIwYpWjnyAaInwWie3HSVA/edit#gid=1971401153), list is displayed below as well| Request access to spreadsheet from [@cityhubla](https://github.com/cityhubla) or discuss in Issue [#3] (https://github.com/osmlab/labuildings/issues/3) |
| Python Scripting | Process datasets to OSM files | Questions? Discuss in Issue [#9](https://github.com/osmlab/labuildings/issues/9) |
| Import Guidelines | Prepare guidelines for import | Discuss in Issue [#10](https://github.com/osmlab/labuildings/issues/10) |

Sample .osm files (**not ready for import yet**) are in this [zip file](https://github.com/osmlab/labuildings/blob/master/venice_osm.zip?raw=true).
Browse a slippy map of the data [here](http://stamen.cartodb.com/u/stamen-org/viz/ff53ba6e-9788-11e4-945a-f23c91504230/public_map)
## Prerequisites
Python 2.7.x
pip
virtualenv
libxml2
libxslt
spatialindex
GDAL
### Installing prerequisites on Mac OSX
# install brew http://brew.sh
brew install libxml2
brew install libxslt
brew install spatialindex
brew install gdal
### Installing prerequisites on Ubuntu
apt-get install python-pip
apt-get install python-virtualenv
apt-get install gdal-bin
apt-get install libgdal-dev
apt-get install libxml2-dev
apt-get install libxslt-dev
apt-get install python-lxml
apt-get install python-dev
apt-get install libspatialindex-dev
apt-get install unzip
## Set up Python virtualenv and get dependencies
# may need to easy_install pip and pip install virtualenv
virtualenv ~/venvs/labuildings
source ~/venvs/labuildings/bin/activate
pip install -r requirements.txt
## Usage
Run all stages:
# Download all files and process them into a building
# and an address .osm file per district.
make
You can run stages separately, like so:
# Download and expand all files, reproject
make download
# Chunk address and building files by census block group
# (this will take a long time)
make chunks
# Generate importable .osm files.
# This will populate the osm/ directory with one .osm file per
# census block group.
make osm
# Clean up all intermediary files:
make clean
# For testing it's useful to convert just a single district.
# For instance, convert block group 060372735024:
make chunks # will take a while
python merge.py 060372735024 # Should be fast
python convert.py merged/buildings-addresses-060372735024.geojson # Fast
## Features
- Cleans address names
- Exports one OSM XML building and address file per LA county block group
- Conflates buildings and addresses (only when there is one address point inside a building polygon)
- Exports remaining addresses as points (for buildings with more than one address, or addresses not on a building)
- Handles multipolygons
- Simplifies building shapes
## Attribute mapping
See the `convert.py` script to see the implementation of these transformations.
### Address attributes
| Attribute | OSM Equivalent | Dataset used| Description | Add/Ignore? | Notes |
|------------|------------------|--------------------------|---------------------------------------------------------------------------------------------------------------|--------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| AIN | | LA County Address Points | Parcel this address falls inside | Ignore | |
| Numprefix | `addr:housenumber` | LA County Address Points | Number prefix | Add | These are extremely rare (only 33 of them), mainly showing up for addresses in Lakewood Center Mall, Lakewood CA. Handling these would require treating `addr:housenumber` as a string, not an integer. However, the OSM wiki says this is permitted. |
| Number | `addr:housenumber` | LA County Address Points | House Number | Add | |
| NumSuffix | `addr:housenumber` | LA County Address Points | House Number Suffix (1/2, 3/4 etc) | Add | |
| PreMod | `addr:street` | LA County Address Points | Prefix Modifier | Add | Examples: OLD RANCH ROAD, LOWER ASUZA ROAD |
| PreDir | `addr:street` | LA County Address Points | Prefix Direction (E, S, W, N) | Add | Examples: SOUTH RANCH ROAD |
| PreType | `addr:street` | LA County Address Points | Prefix Type (Ave, Avenida, etc) | Add | Examples: NORTH VIA SORRENTO, RUE DE LA PIERRE |
| STArticle | `addr:street` | LA County Address Points | Street Article (de la, les, etc) | Add | Examples: RUE DE LA PIERRE. Change to titlecase |
| StreetName | `addr:street` | LA County Address Points | Street Name | Add | Change to titlecase (but full lowercase on numeral suffixes "st", "nd", "rd", "th") |
| PostType | `addr:street` | LA County Address Points | Post Type (Ave, St, Dr, Blvd, etc) | Add | Change to titlecase |
| PostDir | `addr:street` | LA County Address Points | Post Direction (N, S, E, W) | Add | Examples: MARINA DRIVE SOUTH. Note: the data is already expanded into "NORTH", "SOUTH", etc. We do not condense into "N", "S". Change to Titlecase |
| PostMod | `addr:street` | LA County Address Points | Post Modifier (OLD, etc) | Add | Note: this is always null in the current data. Treat like PreMod for consistency. Change to titlecase |
| UnitType | | LA County Address Points | Unit Type (#, Apt, etc) - where these are known | | Ignore??? |
| UnitName | `addr:unit` | LA County Address Points | Unit Name (A, 1, 100, etc) | Add | |
| Zipcode | `addr:postcode` | LA County Address Points | Zipcode | Add | |
| Zip4 | | LA County Address Points | Not currently filled out | Ignore | |
| LegalComm | `is_in:city` | LA County Address Points | Legal City or primary postal city in Unincorporated Areas | Add | Fall back to this if `PCITY1` is null. Potentially could map this to `is_in:city`, but given that OSM already has good city boundaries this seems unnecessary. |
| PostComm1 | `addr:city` | LA County Address Points | Primary Postal Community | Ignore | |
| PostComm2 | | LA County Address Points | Secondary Postal Community | Ignore | |
| PostComm3 | | LA County Address Points | Third Postal Community | Ignore | |
| Source | | LA County Address Points | source of the address point, one of: Assessor, LACity, Regional Planning, other | Ignore | this generally corresponds to whichever city the address falls within |
| SourceID | | LA County Address Points | ID of the Address in the source system | Ignore | |
| MADrank | | LA County Address Points | Method Accuracy Description (MAD) provides a number between 1 and 100 detailing the accuracy of the location. | Ignore | |
| PCITY1 | `addr:city` | | 1st postal city (from the USPS) | add | this is null for 1469 records. When null, fall back to `LegalComm`. Change to titlecase |
| PCITY2 | | | 2nd postal city (from the USPS) | ignore | mostly null or same as LegalComm. Always null when `PCITY1` is null. |
| PCITY3 | | | 3rd postal city (from the USPS) | ignore | mostly null. Always null when `PCITY1` is null. |
### Building attributes
| Attribute | OSM Equivalent | Dataset used| Description | Add/Ignore? | Notes |
|--------------------|-----------------|-------------------|-----------------------------------------------------------------------------------------------------------------|--------|-----------------------------------------------------------------------------------------------------------------------------|
| CODE | | | | Ignore | Note: only CODE=`Building` is used for this import. We ignore CODE='Courtyard'. This filtering step happens in the Makefile |
| BLD_ID | `lacounty:bld_id` | Building Outlines | Unique Building ID | Add | Special OSM Tag |
| HEIGHT | `height` | Building Outlines | The height of the highest major feature of the building (not including roof objects like antennas and chimneys) | Add | map to tag, only if height >0 |
| ELEV | `elevation` | Building Outlines | The elevation of the building | Add | map to elevation, only if elevation > 0 |
| AREA | | Building Outlines | Roof Area | Ignore | Mostly null |
| SOURCE | | Building Outlines | The data source (either LARIAC2, Pasadena, Palmdale, or Glendale) | Ignore | |
| AIN | | Building Outlines | The parcel ID number | Ignore | Used to map stray addresses to buildings and link datasets |
| Shape_Leng | | Building Outlines | | Ignore | |
| Shape_Area | `area` | Building Outlines | | Ignore | |
| GeneralUseType | building | Assessor 2015 | General use type of the property | Add | |
| SpecificUseType | building:use | Assessor 2015 | More specific use type of the property | Add | |
| YearBuilt | `start_date` | Assessor 2015 | Year property was originally built | Add | |
| EffectiveYearBuilt | | Assessor 2015 | Effective year built taking into account subsequent construction, remodeling, building maintenance, etc. | | what is this? |
| SpecificUseDetail1 | amenity | Assessor 2015 | More specific use type of the property | Add | |
| SpecificUseDetail2 | | Assessor 2015 | Additional property usage detail | | |
| SQFTmain | | Assessor 2015 | Total square footage of the main structure(s), | Ignore | |
| Bedrooms | | Assessor 2015 | Total number of bedrooms. | | |
| Bathrooms | | Assessor 2015 | Total number of bathrooms. | | |
| Units | `building:units` | Assessor 2015 | Total number of living units. | Add | |
<file_sep># Merge addresses into buildings they intersect with
# Write them to merged/
from fiona import collection
from rtree import index
from shapely.geometry import asShape, Point, LineString
import re
from sys import argv
from glob import glob
from multiprocessing import Pool
import json
useAINs = True
def merge(buildingIn, addressIn, mergedOut):
addresses = []
with collection(addressIn, "r") as input:
for address in input:
shape = asShape(address['geometry'])
shape.original = address
addresses.append(shape)
geoid = re.match('^.*-(\d+)\.shp$', buildingIn).groups(0)[0]
#print "loaded", len(addresses), "addresses"
# Load and index all buildings.
buildings = []
buildingShapes = []
buildingIdx = index.Index()
with collection(buildingIn, "r") as input:
for building in input:
shape = asShape(building['geometry'])
building['properties']['addresses'] = []
buildings.append(building)
buildingShapes.append(shape)
buildingIdx.add(len(buildings) - 1, shape.bounds)
#print "loaded", len(buildings), "buildings"
addressIntersections = {}
addressesOnBuildings = 0
# Map addresses to buildings.
# Note, if there are multiple address points within a building, this
# adds each one as an array
for address in addresses:
if address not in addressIntersections:
addressIntersections[address] = 0
for i in buildingIdx.intersection(address.bounds):
if buildingShapes[i].contains(address):
addressesOnBuildings += 1
addressIntersections[address] += 1
buildings[i]['properties']['addresses'].append(
address.original)
# Display the number of buildings that have 0 addresses, 1 address, 2 addresses, and so on...
numberOfAddressesCounter = {}
for building in buildings:
numberOfAddresses = len(building['properties']['addresses'])
if numberOfAddresses in numberOfAddressesCounter:
numberOfAddressesCounter[numberOfAddresses] += 1
else:
numberOfAddressesCounter[numberOfAddresses] = 1
strayAddresses = []
for addressKey in addressIntersections:
if addressIntersections[addressKey] > 1:
# Sanity check for addresses that intersected more than one building
print "address", addressKey, "interesected", addressIntersections[addressKey], "buildings"
if addressIntersections[addressKey] == 0:
# This address didn't hit any buildings. We need to export it separately
strayAddresses.append(addressKey.original)
buildingsWithAtLeastOneAddress = 0
for key in sorted(numberOfAddressesCounter.keys()):
#print numberOfAddressesCounter[key], "building(s) had", key, "address(es)"
if key > 0:
buildingsWithAtLeastOneAddress += numberOfAddressesCounter[key]
# Print an informative one-line message
statusmessage = str(geoid) + ": " + str(addressesOnBuildings) + "/" + str(len(addresses))
if len(addresses) > 0:
statusmessage += " (" + str(addressesOnBuildings*100/len(addresses)) + "%)"
statusmessage += " addrs hit bldgs, " + str(buildingsWithAtLeastOneAddress) + "/" + str(len(buildings))
if len(buildings) > 0:
statusmessage += " (" + str(buildingsWithAtLeastOneAddress*100/len(buildings)) + "%)"
statusmessage += " bldgs have at least one addr"
print statusmessage
if useAINs:
# Now try to join on AIN to match buildings and addresses on the same parcel.
# Only try this if the following conditions are true:
# 1. The building doesn't already have at least one address
# 2. The AIN is present on only one building (ignore parcels w/ house + garage)
# 3. The AIN is present on only one address node (ignore multi-address parcels)
ainMatches = 0;
# First populate our AIN lookup
AINs = {}
for building in buildings:
buildingAIN = building['properties']['AIN']
# Make sure AIN is not null
if buildingAIN:
if buildingAIN not in AINs:
AINs[buildingAIN] = {}
if 'buildings' not in AINs[buildingAIN]:
AINs[buildingAIN]['buildings'] = []
AINs[buildingAIN]['buildings'].append(building)
# only populate with stray addresses
for address in strayAddresses:
addressAIN = address['properties']['AIN']
# Make sure AIN is not null
if addressAIN:
if addressAIN not in AINs:
AINs[addressAIN] = {}
if 'addresses' not in AINs[addressAIN]:
AINs[addressAIN]['addresses'] = []
AINs[addressAIN]['addresses'].append(address)
# Now look for buildings that don't yet have addresses
for building in buildings:
if len(building['properties']['addresses']) < 1:
ain = building['properties']['AIN']
# And confirm AIN is only on one address and one building
if ain in AINs and 'buildings' in AINs[ain] and len(AINs[ain]['buildings']) == 1 and 'addresses' in AINs[ain] and len(AINs[ain]['addresses']) == 1:
ainMatches += 1;
foundAddress = AINs[ain]['addresses'][0]
# Now we assign the address to the building
building['properties']['addresses'].append(foundAddress)
if foundAddress in strayAddresses:
strayAddresses.remove(foundAddress)
else:
print foundAddress, "not in strayAddresses! We just matched it to", building
print geoid + ": using AINs matched", ainMatches, "more addresses"
# Note: previous versions of this script would only export buildings,
# but now we append the list of stray (nonintersecting) addresses.
# convert.py has been modified as well, to accept the new format
with open(mergedOut, 'w') as outFile:
outFile.writelines(json.dumps(buildings+strayAddresses, indent=4))
#print 'Exported ' + mergedOut
def prep(fil3):
matches = re.match('^.*-(\d+)\.shp$', fil3).groups(0)
merge(fil3,
'chunks/addresses-%s.shp' % matches[0],
'merged/buildings-addresses-%s.geojson' % matches[0])
if __name__ == '__main__':
# Run merges. Expects an chunks/addresses-[block group geoid].shp for each
# chunks/buildings-[block group geoid].shp. Optionally convert only one block group.
if (len(argv) == 2):
merge('chunks/buildings-%s.shp' % argv[1],
'chunks/addresses-%s.shp' % argv[1],
'merged/buildings-addresses-%s.geojson' % argv[1])
else:
buildingFiles = glob("chunks/buildings-*.shp")
pool = Pool()
pool.map(prep, buildingFiles)
pool.close()
pool.join()
<file_sep>s3cmd put --acl-public -r chunks s3://data.openstreetmap.us/imports/la/
<file_sep>all: BldgPly/buildings.shp AddressPt/addresses.shp BlockGroupPly/blockgroups.shp directories chunks merged osm
clean:
rm -f BldgPly.zip
rm -f AddressPt.zip
rm -f BlockGroupPly.zip
BldgPly.zip:
curl -L "http://latimes-graphics-media.s3.amazonaws.com/jon-temp/lariac_buildings_2008.zip" -o BldgPly.zip
AddressPt.zip:
curl -L "http://egis3.lacounty.gov/dataportal/wp-content/uploads/2012/06/lacounty_address_points.zip" -o AddressPt.zip
BlockGroupPly.zip:
curl -L "http://www2.census.gov/geo/tiger/TIGER2014/BG/tl_2014_06_bg.zip" -o BlockGroupPly.zip
# Other potential data sources
# LA City Community Plan Areas: https://data.lacity.org/api/geospatial/pu8r-72kk?method=export&format=Shapefile
BldgPly: BldgPly.zip
rm -rf BldgPly
unzip BldgPly.zip -d BldgPly
AddressPt: AddressPt.zip
rm -rf AddressPt
unzip AddressPt.zip -d AddressPt
# NOTE: this downloads block groups for all of California. ogr2ogr selects & creates BlockGroupPolyshp with LA County only.
BlockGroupPly: BlockGroupPly.zip
rm -rf BlockGroupPly
unzip BlockGroupPly.zip -d BlockGroupPly
BlockGroupPly/BlockGroupPly.shp: BlockGroupPly
rm -rf BlockGroupPly/BlockGroupPly.*
ogr2ogr -where "COUNTYFP='037'" BlockGroupPly/BlockGroupPly.shp BlockGroupPly/tl_2014_06_bg.shp
BldgPly/buildings.shp: BldgPly
rm -f BldgPly/buildings.*
ogr2ogr -where "(CODE='Building') AND (SOURCE NOT IN ('Pasadena'))" -simplify 0.2 \
-s_srs '+proj=lcc +lat_1=35.46666666666667 +lat_2=34.03333333333333 +lat_0=33.5 +lon_0=-118 +x_0=2000000.000101601 +y_0=500000.0001016002 +ellps=GRS80 +towgs84=-0.9956,1.9013,0.5215,0.025915,0.009426,0.011599,-0.00062 +units=us-ft +no_defs' \
-t_srs EPSG:4326 -overwrite BldgPly/buildings.shp BldgPly/merged-buildings-state-plane.shp
AddressPt/addresses.shp: AddressPt
rm -f AddressPt/addresses.*
ogr2ogr -where "Source <> 'PASADENA.GIS'" \
-s_srs '+proj=lcc +lat_1=35.46666666666667 +lat_2=34.03333333333333 +lat_0=33.5 +lon_0=-118 +x_0=2000000.000101601 +y_0=500000.0001016002 +ellps=GRS80 +towgs84=-0.9956,1.9013,0.5215,0.025915,0.009426,0.011599,-0.00062 +units=us-ft +no_defs' \
-t_srs EPSG:4326 -overwrite AddressPt/addresses.shp AddressPt/lacounty_address_points.shp
BlockGroupPly/blockgroups.shp: BlockGroupPly/BlockGroupPly.shp
rm -f BlockGroupPly/blockgroups.*
ogr2ogr -t_srs EPSG:4326 BlockGroupPly/blockgroups.shp BlockGroupPly/BlockGroupPly.shp
BlockGroupPly/blockgroups.geojson: BlockGroupPly/BlockGroupPly.shp
rm -f BlockGroupPly/blockgroups.geojson
rm -f BlockGroupPly/blockgroups-4326.geojson
ogr2ogr -t_srs EPSG:4326 -f "GeoJSON" BlockGroupPly/blockgroups-4326.geojson BlockGroupPly/BlockGroupPly.shp
# python tasks.py BlockGroupPly/blockgroups-4326.geojson > BlockGroupPly/blockgroups.geojson
chunks: directories AddressPt/addresses.shp BldgPly/buildings.shp
python chunk.py AddressPt/addresses.shp BlockGroupPly/blockgroups.shp chunks/addresses-%s.shp GEOID
python chunk.py BldgPly/buildings.shp BlockGroupPly/blockgroups.shp chunks/buildings-%s.shp GEOID
merged: directories
# python merge.py
osm: merged
# python convert.py merged/*
directories:
mkdir -p chunks
mkdir -p merged
mkdir -p osm
# Make TileMill 1 project
tilemill:
mkdir -p ${HOME}/Documents/MapBox/project
ln -sf "`pwd`" ${HOME}/Documents/MapBox/project/labuildings
# Load database for Mapbox Studio
database: AddressPt/addresses.shp BldgPly/buildings.shp BlockGroupPly/blockgroups.shp
createdb labuildings
psql labuildings -c "CREATE EXTENSION postgis;"
shp2pgsql AddressPt/address.shp | psql labuildings
shp2pgsql BldgPly/buildings.shp | psql labuildings
shp2pgsql BlockGroupPly/blockgroups.shp | psql labuildings
<file_sep>import csv
import json
from os.path import join
CSV_PATH = 'mappings_csv/'
GENERAL_USE_CSV = open(join(CSV_PATH, 'GeneralUse.csv'))
SPECIFIC_1_CSV = open(join(CSV_PATH, 'Specific_1.csv'))
SPECIFIC_USE_CSV = open(join(CSV_PATH, 'SpecificUs.csv'))
mappings = {}
def csv_to_json(mapping_name, csv_file):
reader = csv.reader(csv_file)
reader.next() # skip header row
mappings[mapping_name] = {}
for row in reader:
if row[1] != '' and row[2] != '':
mappings[mapping_name][row[0]] = {
'key1': row[1],
'val1': row[2]
}
csv_to_json('GeneralUse', GENERAL_USE_CSV)
csv_to_json('Specific_1', SPECIFIC_1_CSV)
csv_to_json('SpecificUs', SPECIFIC_USE_CSV)
# print json.dumps(mappings, indent=2)
def get_osm_tags(feature):
osm_tags = {
'building': 'yes'
}
props = feature['properties']
order = ['GeneralUse', 'Specific_1', 'SpecificUs']
for o in order:
if props.has_key(o) and props[o] is not None:
if mappings[o].has_key(props[o]):
key = mappings[o][props[o]]['key1']
val = mappings[o][props[o]]['val1']
osm_tags[key] = val
return osm_tags
<file_sep># chunk.py
# Exports intersections between two shapefile's objects as separate files.
from fiona import collection
from rtree import index
from shapely.geometry import asShape
from shapely import speedups
from sys import argv
from pprint import pprint
speedups.enable()
# Exports given features into shapefiles by sections
def chunk(featureFileName, sectionFileName, pattern, key = None):
# Load and index
with collection(featureFileName, "r") as featureFile:
featureIdx = index.Index()
features = []
for feature in featureFile:
try:
shape = asShape(feature['geometry'])
features.append(feature)
featureIdx.add(len(features) - 1, shape.bounds)
except ValueError:
print "Error parsing feature"
pprint(feature)
# Break up by sections and export
with collection(sectionFileName, "r") as sectionFile:
i = 0
for section in sectionFile:
fileName = pattern % i
if key:
fileName = pattern % section['properties'][key]
properties = {}
try:
with collection(fileName, 'w', 'ESRI Shapefile',
schema = featureFile.schema,
crs = featureFile.crs) as output:
sectionShape = asShape(section['geometry'])
for j in featureIdx.intersection(sectionShape.bounds):
if asShape(features[j]['geometry']).intersects(sectionShape):
properties = features[j]['properties']
output.write(features[j])
print "Exported %s" % fileName
i = i + 1
except ValueError:
print "Error exporting " + fileName
pprint(properties)
pprint(featureFile.schema)
usage = """
chunk.py
========
Exports intersections between two shapefile's objects as separate files.
Usage: python chunk.py featuresfile sectionfile outputfilepattern [attributekey]
Example:
python chunk.py manysmallfeatures.shp sections.shp export/features-by-section-%s.shp
If you specify an attribute key that can be found in the sections file it will be used for naming output files:
python chunk.py manysmallfeatures.shp sections.shp export/features-by-section-%s.shp STATECODE
"""
if len(argv) == 4:
chunk(argv[1], argv[2], argv[3])
elif len(argv) == 5:
chunk(argv[1], argv[2], argv[3], argv[4])
else:
print usage
<file_sep># Convert LA building footprints and addresses into importable OSM files.
from lxml import etree
from lxml.etree import tostring
from shapely.geometry import asShape, Point, LineString
from sys import argv, exit, stderr
from glob import glob
from merge import merge
import re
from decimal import Decimal, getcontext
from multiprocessing import Pool
import json
from rtree import index
import ntpath
import osm_tags
debug = True
# Adjust precision for buffer operations
getcontext().prec = 16
# Converts given buildings into corresponding OSM XML files.
def convert(buildingsFile, osmOut):
with open(buildingsFile) as f:
features = json.load(f)
allAddresses = {}
buildings = []
buildingShapes = []
buildingIdx = index.Index()
# Returns the coordinates for this address
def keyFromAddress(address):
return str(address['geometry']['coordinates'][0]) + "," + str(address['geometry']['coordinates'][1])
for feature in features:
if feature['geometry']['type'] == 'Polygon' or feature['geometry']['type'] == 'MultiPolygon':
extra_tags = osm_tags.get_osm_tags(feature)
feature['properties']['osm'] = extra_tags
buildings.append(feature)
shape = asShape(feature['geometry'])
buildingShapes.append(shape)
buildingIdx.add(len(buildingShapes) - 1, shape.bounds)
# These are the addresses that don't overlap any buildings
elif feature['geometry']['type'] == 'Point':
# The key is the coordinates of this address. Track how many addresses share these coords.
key = keyFromAddress(feature)
if key in allAddresses:
allAddresses[key].append(feature)
else:
allAddresses[key] = [feature]
else:
print "geometry of unknown type:", feature['geometry']['type']
# Generates a new osm id.
osmIds = dict(node = -1, way = -1, rel = -1)
def newOsmId(type):
osmIds[type] = osmIds[type] - 1
return osmIds[type]
## Formats multi part house numbers
def formatHousenumber(p):
def suffix(part1, part2, hyphen_type=None):
#part1 = stripZeroes(part1)
if not part2:
return str(part1)
#part2 = stripZeroes(part2)
return str(part1) + ' ' + str(part2)
#def stripZeroes(addr): # strip leading zeroes from numbers
# if addr.isdigit():
# addr = str(int(addr))
# if '-' in addr:
# try:
# addr2 = addr.split('-')
# if len(addr2) == 2:
# addr = str(int(addr2[0])) + '-' + str(int(addr2[1])).zfill(2)
# except:
# pass
# return addr
number = suffix(p['Number'], p['NumSuffix'])
if p['NumPrefix']:
number = p['NumPrefix'] + number
return number
# Converts an address
def convertAddress(address):
result = dict()
if all (k in address for k in ('Number', 'StreetName')):
if address['Number']:
result['addr:housenumber'] = formatHousenumber(address)
if address['StreetName']:
# Titlecase
streetname = address['StreetName'].title()
if address['StArticle']:
streetname = address['StArticle'].title() + " " + streetname
if address['PreType']:
streetname = address['PreType'].title() + " " + streetname
if address['PreDir']:
streetname = address['PreDir'].title() + " " + streetname
if address['PreMod']:
streetname = address['PreMod'].title() + " " + streetname
if address['PostType']:
streetname = streetname + " " + address['PostType'].title()
if address['PostDir']:
streetname = streetname + " " + address['PostDir'].title()
if address['PostMod']:
streetname = streetname + " " + address['PostMod'].title()
# Fix titlecase on 1St, 2Nd, 3Rd, 4Th, etc
streetname = re.sub(r"(.*)(\d+)St\s*(.*)", r"\1\2st \3", streetname)
streetname = re.sub(r"(.*)(\d+)Nd\s*(.*)", r"\1\2nd \3", streetname)
streetname = re.sub(r"(.*)(\d+)Rd\s*(.*)", r"\1\2rd \3", streetname)
streetname = re.sub(r"(.*)(\d+)Th\s*(.*)", r"\1\2th \3", streetname)
# Expand 'St ' -> 'Saint'
# relevant for:
# 'St Clair'
# 'St Louis'
# 'St James'
# 'St <NAME>'
# 'St Andrews'
# 'St Nicolas'
# 'St Cloud'
# 'St Ambrose'
# 'St Bonaventure'
# 'St Joseph'
# 'St Tropez'
if streetname[0:3] == 'St ': streetname = 'Saint ' + streetname[3:]
# Middle name expansions
streetname = streetname.replace(' St ', ' Street ')
streetname = streetname.replace(' Rd ', ' Road ')
streetname = streetname.replace(' Blvd ', ' Boulevard ')
result['addr:street'] = streetname
if address['PCITY1']:
result['addr:city'] = address['PCITY1'].title()
elif address['LegalComm']:
result['addr:city'] = address['LegalComm'].title()
if address['ZipCode']:
result['addr:postcode'] = str(int(address['ZipCode']))
if address['UnitName']:
result['addr:unit'] = address['UnitName']
return result
# Distills coincident addresses into one address where possible.
# Takes an array of addresses and returns an array of 1 or more addresses
def distillAddresses(addresses):
# Only distill addresses if the following conditions are true:
# 1) the addresses share the same coordinates.
# AND
# 2a) all the attributes are the same _except_ the unit number/name
# OR
# 2b) the street number is the same but the street names are referring to the same thing
outputAddresses = []
# First, group the addresses into separate lists for each unique location
addressesByCoords = {}
for address in addresses:
key = keyFromAddress(address)
if key in addressesByCoords:
addressesByCoords[key].append(address)
else:
addressesByCoords[key] = [address]
# loop over unique coordinates
for key in addressesByCoords:
# Here see if we can collapse any of these addresses at the same coords.
# addressesByCoords[key] is an array of addresses at this location.
# We are only looking for the 2 possibilities above (2a) and (2b).
# If the situation is more complicated, change nothing.
outputAddresses.extend(distillAddressesAtPoint(addressesByCoords[key]))
return outputAddresses
# This function is called by distillAddresses.
# It assumes all addresses are at the same coordinates.
# Returns an array of 1 or more addresses
def distillAddressesAtPoint(addresses):
if len(addresses) == 1:
return addresses
firstAddress = addresses[0]
# (2a) If the first address is an apartment, see if all the rest are too.
# NOTE: sometimes an apartment building has a few address points that lack a UnitName...
# ...so checking for the presence of UnitName in firstAddress wouldn't always work.
props = firstAddress['properties']
if debug: print "Testing to see if these are apartments...", '\t'.join([str(props['Number']), str(props['NumSuffix']), str(props['PreType']), str(props['StreetName']), str(props['PostType']), str(props['UnitName'])])
# Compare subsequent addresses in the array to the first address.
# Hence, range starts at 1.
for i in range(1, len(addresses)):
if not areSameAddressExceptUnit(firstAddress, addresses[i]):
props = addresses[i]['properties']
if debug: print "No, this address was different...........", '\t'.join([str(props['Number']), str(props['NumSuffix']), str(props['PreType']), str(props['StreetName']), str(props['PostType']), str(props['UnitName'])])
#print firstAddress
#print addresses[i]
break
# else, keep going
else: # else for the `for` statement. Executes only if `break` never did.
# We checked them all, and they're all the same except UnitName.
# In this case the apartment data is useless to OSM because the
# apartment nodes are all on top of each other.
# So, discard the unit information and return just one address.
firstAddress['properties']['UnitName'] = None
if debug: print "Yes they were apartments! Collapsed", len(addresses), "into one"
return [firstAddress]
# (2b) Check if the street number is all the same.
# For this, we use a list of alternative names (like HWY 1, etc)...
# ...and we need to know which canonical name to keep.
if debug: print "Testing to see if the street names are synonyms.."
canonicalStreetName = None
for i in range(1, len(addresses)):
props = addresses[i]['properties']
if not areSameAddressExceptStreet(firstAddress, addresses[i]):
if debug: print "No, this address was different...........", '\t'.join([str(props['Number']), str(props['NumSuffix']), str(props['PreType']), str(props['StreetName']), str(props['PostType']), str(props['UnitName'])])
#print firstAddress
#print addresses[i]
break
compoundStreetName = (str(props['PreType']),str(props['StreetName']),str(props['PostType']))
currentCanonicalStreetName = getCanonicalName(compoundStreetName)
if currentCanonicalStreetName:
if debug: print "found canonical name", currentCanonicalStreetName
if ((currentCanonicalStreetName == canonicalStreetName) or (canonicalStreetName == None)):
canonicalStreetName = currentCanonicalStreetName
else:
if debug: print "canonicalStreetNames didn't match:", canonicalStreetName, currentCanonicalStreetName
break
else:
print "couldn't find canonicalStreetName for", compoundStreetName
break
else: # else for the `for` statement. Executes only if `break` never did.
# We checked them all, and they're all the same except StreetName.
# If we can determine that they are all the same synonym, we can
# overwrite the other streetname information and return just one address.
firstAddress['properties']['PreType'] = canonicalStreetName[0]
firstAddress['properties']['StreetName'] = canonicalStreetName[1]
firstAddress['properties']['PostType'] = canonicalStreetName[2]
if debug: print "Yes they were synonyms! Collapsed", len(addresses), "into one"
return [firstAddress]
# This is only excuted if neither of the two `else` statements executed
# for the two `for` statements above. That means we were unable to collapse
# separate apartments into one, or collapse synonymous street names into one.
# So, instead of returning just one address, we fail and return all of them.
return addresses
def areSameAddressExceptUnit(a1, a2):
for key in ['NumPrefix', 'Number', 'NumSuffix', 'PreMod', 'PreDir', 'PreType', 'StArticle', 'StreetName', 'PostType', 'PostDir', 'PostMod', 'ZipCode', 'LegalComm', 'PCITY1']:
if a1['properties'][key] != a2['properties'][key]:
#print key, a1['properties'][key], "!=", a2['properties'][key]
return False
return True
def areSameAddressExceptStreet(a1, a2):
for key in ['NumPrefix', 'Number', 'NumSuffix', 'PreMod', 'PreDir', 'StArticle', 'UnitName', 'PostDir', 'PostMod', 'ZipCode', 'LegalComm', 'PCITY1']:
if a1['properties'][key] != a2['properties'][key]:
#print key, a1['properties'][key], "!=", a2['properties'][key]
return False
return True
# Sometimes we have identical addresses that differ only by street name.
# Usually these are because the street name is also a highway. We want to
# remove all the highway names and only use the street name for the address
canonicalNames = {
("None", "LINCOLN", "BOULEVARD"): (None, "LINCOLN", "BOULEVARD"),
("ROUTE", "1", "None"): (None, "LINCOLN", "BOULEVARD"),
("HIGHWAY", "1", "None"): (None, "LINCOLN", "BOULEVARD"),
("None", "SR-1", "None"): (None, "LINCOLN", "BOULEVARD"),
("None", "PCH", "None"): (None, "LINCOLN", "BOULEVARD"),
}
def getCanonicalName(compoundStreetName):
result = None
try:
result = canonicalNames[compoundStreetName]
except KeyError:
return None
return result
# Appends new node or returns existing if exists.
nodes = {}
def appendNewNode(coords, osmXml):
rlon = int(float(coords[0]*10**7))
rlat = int(float(coords[1]*10**7))
if (rlon, rlat) in nodes:
return nodes[(rlon, rlat)]
node = etree.Element('node', visible = 'true', id = str(newOsmId('node')))
node.set('lon', str(Decimal(coords[0])*Decimal(1)))
node.set('lat', str(Decimal(coords[1])*Decimal(1)))
nodes[(rlon, rlat)] = node
osmXml.append(node)
return node
# Sometimes we want to force overlapping nodes, such as with addresses.
# This way they'll show up in JOSM and the contributor can deal with them manually.
# Otherwise, we might try to apply multiple address tags to the same node...
# ...which is also incorrect, but harder to detect.
def appendNewNodeIgnoringExisting(coords, osmXml):
rlon = int(float(coords[0]*10**7))
rlat = int(float(coords[1]*10**7))
#if (rlon, rlat) in nodes:
# return nodes[(rlon, rlat)]
node = etree.Element('node', visible = 'true', id = str(newOsmId('node')))
node.set('lon', str(Decimal(coords[0])*Decimal(1)))
node.set('lat', str(Decimal(coords[1])*Decimal(1)))
nodes[(rlon, rlat)] = node
osmXml.append(node)
return node
def appendNewWay(coords, intersects, osmXml):
way = etree.Element('way', visible='true', id=str(newOsmId('way')))
firstNid = 0
for i, coord in enumerate(coords):
if i == 0: continue # the first and last coordinate are the same
node = appendNewNode(coord, osmXml)
if i == 1: firstNid = node.get('id')
way.append(etree.Element('nd', ref=node.get('id')))
# Check each way segment for intersecting nodes
int_nodes = {}
try:
line = LineString([coord, coords[i+1]])
except IndexError:
line = LineString([coord, coords[1]])
for idx, c in enumerate(intersects):
if line.buffer(0.000001).contains(Point(c[0], c[1])) and c not in coords:
t_node = appendNewNode(c, osmXml)
for n in way.iter('nd'):
if n.get('ref') == t_node.get('id'):
break
else:
int_nodes[t_node.get('id')] = Point(c).distance(Point(coord))
for n in sorted(int_nodes, key=lambda key: int_nodes[key]): # add intersecting nodes in order
way.append(etree.Element('nd', ref=n))
way.append(etree.Element('nd', ref=firstNid)) # close way
osmXml.append(way)
return way
# Appends an address to a given node or way.
def appendAddress(address, element):
# # Need to check if these tags already exist on this element
for k, v in convertAddress(address['properties']).iteritems():
# TODO: is this doing anything useful?
#for child in element:
# if child.tag == 'tag':
# #print k, v
# if child.attrib.get('k') == k:
# print "found key", k
# if child.attrib.get('v') == v:
# print "found matching value", v
element.append(etree.Element('tag', k=k, v=v))
# Appends a building to a given OSM xml document.
def appendBuilding(building, shape, address, osmXml):
# Check for intersecting buildings
intersects = []
for i in buildingIdx.intersection(shape.bounds):
try:
for c in buildingShapes[i].exterior.coords:
if Point(c[0], c[1]).buffer(0.000001).intersects(shape):
intersects.append(c)
except AttributeError:
for c in buildingShapes[i][0].exterior.coords:
if Point(c[0], c[1]).buffer(0.000001).intersects(shape):
intersects.append(c)
# Export building, create multipolygon if there are interior shapes.
interiors = []
try:
way = appendNewWay(list(shape.exterior.coords), intersects, osmXml)
for interior in shape.interiors:
interiors.append(appendNewWay(list(interior.coords), [], osmXml))
except AttributeError:
way = appendNewWay(list(shape[0].exterior.coords), intersects, osmXml)
for interior in shape[0].interiors:
interiors.append(appendNewWay(list(interior.coords), [], osmXml))
if len(interiors) > 0:
relation = etree.Element('relation', visible='true', id=str(newOsmId('way')))
relation.append(etree.Element('member', type='way', role='outer', ref=way.get('id')))
for interior in interiors:
relation.append(etree.Element('member', type='way', role='inner', ref=interior.get('id')))
relation.append(etree.Element('tag', k='type', v='multipolygon'))
osmXml.append(relation)
way = relation
for tag in building['properties']['osm']:
value = building['properties']['osm'][tag]
way.append(etree.Element('tag', k=tag, v=value))
# if 'GeneralUse' in building['properties']:
# way.append(etree.Element('tag', k='building', v=building['properties']['GeneralUse']))
# else:
# way.append(etree.Element('tag', k='building', v='yes'))
# if 'SpecificUs' in building['properties']:
# way.append(etree.Element('tag', k='building:use', v=building['properties']['GeneralUse']))
if 'YearBuilt' in building['properties'] and building['properties']['YearBuilt'] is not None:
YearBuilt = int(building['properties']['YearBuilt'])
if YearBuilt > 0:
way.append(etree.Element('tag', k='start_date', v=str(YearBuilt)))
# if 'Specific_1' in building['properties']:
# way.append(etree.Element('tag', k='amenity', v=building['properties']['Specific_1']))
if 'Units' in building['properties'] and building['properties']['Units'] is not None:
units = int(round(float(building['properties']['Units']), 0))
if units > 0:
way.append(etree.Element('tag', k='building:units', v=str(units)))
if 'HEIGHT' in building['properties']:
height = round(((building['properties']['HEIGHT'] * 12) * 0.0254), 1)
if height > 0:
way.append(etree.Element('tag', k='height', v=str(height)))
if 'ELEV' in building['properties']:
elevation = round(((building['properties']['ELEV'] * 12) * 0.0254), 1)
if elevation > 0:
way.append(etree.Element('tag', k='elevation', v=str(elevation)))
if 'BLD_ID' in building['properties']:
way.append(etree.Element('tag', k='lacounty:bld_id', v=str(building['properties']['BLD_ID'])))
# if address:
# appendAddress(address, way)
# Export buildings & addresses. Only export address with building if there is exactly
# one address per building. Export remaining addresses as individual nodes.
# The remaining addresses are added to a dictionary hashed by their coordinates.
# This way we catch any addresses that have the same coordinates.
osmXml = etree.Element('osm', version='0.6', generator='<EMAIL>')
for i in range(0, len(buildings)):
buildingAddresses = []
for address in buildings[i]['properties']['addresses']:
buildingAddresses.append(address)
address = None
if len(buildingAddresses) == 1:
# There's only one address in the building footprint
address = buildingAddresses[0]
elif len(buildingAddresses) > 1:
# If there are multiple addresses, first try to distill them.
# If we can distill them to one address, we can still add it to this building.
distilledAddresses = distillAddresses(buildingAddresses)
if len(distilledAddresses) == 1:
# We distilled down to one address. Add it to the building.
address = distilledAddresses[0]
else:
# We could not distilled down to one address. Instead export as nodes.
for address in distilledAddresses:
# The key is the coordinates of this address. Track how many addresses share these coords.
key = keyFromAddress(address)
if key in allAddresses:
allAddresses[key].append(address)
else:
allAddresses[key] = [address]
appendBuilding(buildings[i], buildingShapes[i], address, osmXml)
# Export any addresses that aren't the only address for a building.
if (len(allAddresses) > 0):
# Iterate over the list of distinct coordinates found in the address data
for coordskey in allAddresses:
# if a distinct coordinate has only one associated address,
# then export that address as a new node
if len(allAddresses[coordskey]) == 1:
address = allAddresses[coordskey][0]
coordinates = address['geometry']['coordinates']
# node = appendNewNode(coordinates, osmXml) # returns old node if one exists at these coords
# appendAddress(address, node)
# If there is more than one address at these coordinates, do something.
# ...but do what exactly?
else:
distilledAddresses = distillAddresses(allAddresses[coordskey])
if len(distilledAddresses) == 1:
# We distilled down to one address. Append it.
address = distilledAddresses[0]
coordinates = address['geometry']['coordinates']
# node = appendNewNode(coordinates, osmXml) # returns old node if one exists at these coords
# appendAddress(address, node)
else:
if debug: print "found duplicate coordinates that could not be distilled:", coordskey, "has", len(allAddresses[coordskey]), "addresses"
if debug: print '\t'.join(["num", "numsufx", "pretype", "street", "posttype", "unit"])
for address in distilledAddresses:
# TODO: do something smart here. These are overlapping addresses that we couldn't distill.
# TODO: maybe jitter them, or leave stacked but with FIXME?
# TODO: For now, we use appendNewNodeIgnoringExisting to pile the nodes on top of each other.
#print address
props = address['properties']
if debug: print '\t'.join([str(props['Number']), str(props['NumSuffix']), str(props['PreType']), str(props['StreetName']), str(props['PostType']), str(props['UnitName'])])
coordinates = address['geometry']['coordinates']
# node = appendNewNodeIgnoringExisting(coordinates, osmXml) # Force overlapping nodes so JOSM will catch them
# appendAddress(address, node)
with open(osmOut, 'w') as outFile:
outFile.writelines(tostring(osmXml, pretty_print=True, xml_declaration=True, encoding='UTF-8'))
print 'Exported ' + osmOut
def prep(fil3):
matches = re.match('^(.*)\..*?$', ntpath.basename(fil3)).groups(0)
convert(fil3, 'osm/%s.osm' % matches[0])
if __name__ == '__main__':
# for easier debugging
for filename in argv[1:]:
prep(filename)
# pool = Pool()
# pool.map(prep, argv[1:])
# pool.close()
# pool.join()
| 4ac21ac0398073fbd8cb9020852f66125b590a36 | [
"Markdown",
"Python",
"Makefile",
"Shell"
] | 8 | Markdown | batpad/labuildings | 4227099d3ce99b4e3afb99a7211760a4fc1cbc22 | d4fe72a8f4d92557d51a6421381c7dc3f8bff97f |
refs/heads/master | <repo_name>gronula/balls<file_sep>/src/helpers/utils.js
export const getRandomBoolean = () => {
return Boolean(Math.round(Math.random()))
}
export const getRandomFloat = (min, max) => {
return Math.random() * (max - min) + min
}
export const getRandomInt = (min, max) => {
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min + 1)) + min
}
export const getRandomDate = (start, end, startHour, endHour) => {
const date = new Date(+start + Math.random() * (end - start))
const hour = startHour + Math.random() * (endHour - startHour) | 0
return date.setHours(hour)
}
export const getArrayOfSpecifiedLength = (dataGetter, length) => {
const array = new Array(length).fill(``)
array.forEach((item, i) => {
array[i] = dataGetter()
})
return array
}
export const getRandomArray = (array) => {
array = shuffleArray(array)
array.length = getRandomInt(1, 2)
return array
}
export const getRandomArrayElement = (array) => {
const randomIndex = getRandomInt(0, array.length - 1)
return array[randomIndex]
}
export const shuffleArray = (array) => {
const newArray = array.slice()
for (let i = newArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[newArray[i], newArray[j]] = [newArray[j], newArray[i]]
}
return newArray
}
export const deepMerge = (target, source) => {
const isObject = (obj) => obj && typeof obj === `object`
if (!isObject(target) && !isObject(source)) {
return source
}
Object.keys(source).forEach((key) => {
const targetValue = target[key]
const sourceValue = source[key]
if (
isObject(targetValue) && !Array.isArray(targetValue) &&
isObject(sourceValue) && !Array.isArray(sourceValue)
) {
target[key] = deepMerge(Object.assign({}, targetValue), sourceValue)
} else {
target[key] = sourceValue
}
})
return target
}
| d7b5e657c9e3d19a3942f2b57d43153fa9cb9a06 | [
"JavaScript"
] | 1 | JavaScript | gronula/balls | 374c21558aa8101d6b9a01d9214284e4c9fde28c | 6f395fd4d9e975f2026b4aff88598f76ae01f5dd |
refs/heads/master | <repo_name>richstu/jb_utils<file_sep>/libs/ask.py
#!/usr/bin/env python
def ask_key(question, valids, default=None):
answer = raw_input(question)
if '' not in valids: valids.append('')
if answer not in valids:
print('[Error] Did not enter valid key: '+', '.join(valids))
return ask_key(question, valids, default)
if answer == '':
if default == None:
print('[Error] Did not enter valid key: '+', '.join(valids))
return ask_key(question, valids, default)
else:
return default
return answer
def ask_yn(question, default=None):
return ask_key(question, ['y','n'], default)
<file_sep>/libs/nested_dict.py
import json
def fill_dict(target_dict, key, item):
if key not in target_dict:
target_dict[key] = item
else:
if target_dict[key] != item:
print('[Error] fill_dict: target_dict['+key+']:'+target_dict[key]+' is different with item:'+item)
def fill_nested_dict(target_dict, keys, item):
if len(keys) == 0:
print ('[Error] fill_nested_dict: keys:'+str(keys)+' length is 0.')
elif len(keys) != 1:
if keys[0] not in target_dict:
target_dict[keys[0]] = {}
fill_nested_dict(target_dict[keys[0]], keys[1:], item)
else:
fill_dict(target_dict, keys[0], item)
def fill_empty_nested_dict(target_dict, keys):
keys.append(None)
fill_nested_dict(target_dict, keys, {})
def get_item_nested_dict(target_dict, keys):
if len(keys) == 1:
return target_dict[keys[0]]
return get_item_nested_dict(target_dict[keys[0]], keys[1:])
def get_nested_dict(target_dict, keys):
out_dict = {}
if is_nested_dict(target_dict, keys):
fill_nested_dict(out_dict, keys, get_item_nested_dict(target_dict, keys))
return out_dict
def get_from_nested_dict(target_dict, target_key):
if isinstance(target_dict, dict):
if target_key in target_dict:
return target_dict[target_key]
else:
for key in target_dict:
target_item = get_from_nested_dict(target_dict[key], target_key)
if target_item != None:
return target_item
else: return None
def remove_key_nested_dict(target_dict, target_key):
if isinstance(target_dict, dict):
if target_key in target_dict:
target_dict.pop(target_key)
for key in target_dict:
remove_key_nested_dict(target_dict[key], target_key)
remove_empty_nested_dict(target_dict)
def remove_empty_nested_dict(target_dict):
if not isinstance(target_dict, dict): return
empty_dict_keys = []
for key in target_dict:
remove_empty_nested_dict(target_dict[key])
# Remove empty dict
if isinstance(target_dict[key], dict):
if len(target_dict[key]) == 0:
empty_dict_keys.append(key)
# Remove empty dict
for remove_key in empty_dict_keys:
del target_dict[remove_key]
def remove_keys_nested_dict(target_dict, keys):
if not isinstance(target_dict, dict): return
if len(keys) == 0:
print ('[Error] remove_keys_nested_dict: keys:'+str(keys)+' length is 0.')
elif len(keys) != 1:
if keys[0] in target_dict:
remove_keys_nested_dict(target_dict[keys[0]], keys[1:])
else:
if keys[0] in target_dict:
del target_dict[keys[0]]
remove_empty_nested_dict(target_dict)
def check_key_nested_dict(target_dict, target_key):
if isinstance(target_dict, dict):
if target_key in target_dict:
print(target_key+' is in target_dict')
for key in target_dict:
check_key_nested_dict(target_dict[key], target_key)
def is_nested_dict(target_dict, keys):
if len(keys) == 0:
print ('[Error] is_nested_dict: keys:'+str(keys)+' length is 0.')
elif len(keys) != 1:
#print(str(keys)+' len!=1')
if keys[0] not in target_dict:
#print(str(keys[0])+' keys not in target_dict len!=1')
return False
return is_nested_dict(target_dict[keys[0]], keys[1:])
else:
#print(str(keys)+','+str(target_dict)+' len==1')
if keys[0] not in target_dict:
#print(str(keys[0])+' keys not in target_dict len==1')
return False
else:
#print(target_dict)
#print(str(keys[0])+' in target_dict len==1')
return True
def save_json_file(dict_name, json_filename):
with open(json_filename,'w') as json_file:
json.dump(dict_name, json_file, indent=2)
print('Saved '+json_filename)
def ascii_encode_dict(data):
ascii_encode = lambda x: x.encode('ascii') if isinstance(x, unicode) else x
return dict(map(ascii_encode, pair) for pair in data.items())
def convert_to_ascii(out_dict):
if isinstance(out_dict, list):
for key, value in enumerate(out_dict):
if isinstance(value, unicode): out_dict[key] = value.encode('ascii')
if isinstance(value, (list, dict)): convert_to_ascii(out_dict[key])
elif isinstance(out_dict, dict):
for key in out_dict:
value = out_dict[key]
if isinstance(value, unicode): out_dict[key] = value.encode('ascii')
if isinstance(value, (list, dict)): convert_to_ascii(out_dict[key])
elif isinstance(out_dict, unicode): out_dict = value.encode('ascii')
def load_json_file(json_filename, no_null=True):
with open(json_filename) as json_file:
out_dict = json.load(json_file, object_hook=ascii_encode_dict)
#nested_dict.check_key_nested_dict(out_dict, 'null')
convert_to_ascii(out_dict)
if no_null:
remove_key_nested_dict(out_dict, 'null')
check_key_nested_dict(out_dict, 'null')
check_key_nested_dict(out_dict, None)
return out_dict
<file_sep>/libs/argparse_helper.py
#!/usr/bin/env python
import argparse
def initialize_arguments(args, list_args = []):
# Get rid non list_args
for key in args:
if key in list_args: continue
if isinstance(args[key], list) and len(args[key])==1:
args[key] = args[key][0]
#print(args)
# Convert comma to list
for key in args:
if args[key] == None: continue
if len(args[key]) != 1 : continue
if key not in list_args: continue
if "," in args[key][0]:
args[key] = args[key][0].split(',')
## Convert to int
#for key in args:
# if isinstance(args[key], list):
# for index, item in enumerate(args[key]):
# if unicode(item).isnumeric():
# args[key][index] = int(item)
# if isinstance(args[key], basestring):
# if unicode(args[key]).isnumeric():
# args[key] = int(args[key])
def set_default(args, key, value):
if not args[key]:
args[key] = value
def is_valid(args, key, valid_list):
if isinstance(args[key], list):
for item in args[key]:
if item not in valid_list:
return False
if isinstance(args[key], basestring):
if args[key] not in valid_list:
return False
return True
<file_sep>/set_env.sh
#!/bin/bash
export JB_UTILS_DIR=$(dirname $(readlink -e "$BASH_SOURCE"))
export PYTHONPATH=$JB_UTILS_DIR/libs:$PYTHONPATH
| fa809c36e296e15e873721f0e47239074f5c0434 | [
"Python",
"Shell"
] | 4 | Python | richstu/jb_utils | 7f263b0b9b18cf59bf55642f76d45777e3ab21ab | 39cb7d2f4789cd2b154d7676c662bf057d67a063 |
refs/heads/master | <repo_name>venkatbhargava/FavouriteFoodSpot<file_sep>/FavouriteFoodSpot/Extensions/NavigationController+Ext.swift
//
// NavigationController+Ext.swift
// FavouriteFoodSpot
//
// Created by <NAME> on 03/07/20.
// Copyright ยฉ 2020 <NAME>. All rights reserved.
//
import UIKit
extension UINavigationController {
open override var childForStatusBarStyle: UIViewController? {
return topViewController
}
}
<file_sep>/README.md
# FavouriteFoodSpot





| 591e21e4d16cd2188fd25b88f9d83a6a5ee3fa47 | [
"Swift",
"Markdown"
] | 2 | Swift | venkatbhargava/FavouriteFoodSpot | 85a58c6c8317b39fccc6b16cb0557b481112c2f8 | c1bdcc746b11c267b39855026baae0012246ba28 |
refs/heads/master | <file_sep>#!/bin/bash
set -e
echo "devops.sh controls deployment for a docker swarm cluster"
if (( $# != 1 ))
then
echo "Usage : ./devops.sh [deploy | stop | restart | redeploy] [version] " 1>&2
echo "ex : ./devops.sh deploy v1" 1>&2
exit 1
fi
CMD=$1
#VERSION=$2
case "$CMD" in
init)
echo "Initializing docker swarm"
docker swarm init
# source gradle-build.sh ${VERSION}
# source docker-build.sh ${VERSION}
;;
deploy)
echo "deploy"
docker stack deploy -c docker-compose.yml --resolve-image=always mydemoapp
;;
stop)
echo "stop"
docker stack rm mydemoapp
;;
restart)
echo "restart"
docker stack rm mydemoapp
sleep 30
docker stack deploy -c docker-compose.yml mydemoapp
;;
redeploy)
echo "redeploy"
# source gradle-build.sh ${VERSION}
# source docker-build.sh ${VERSION}
docker stack deploy -c docker-compose.yml --resolve-image=changed mydemoapp
;;
*)
echo "Error: unknown command "$1" for "devops.sh""
;;
esac
<file_sep>#!/bin/bash
set -e
echo "Blue-Green Deployment started..."
echo "Route to secondary"
cat conf/nginx/nginx.conf_sec > conf/nginx/nginx.conf
CID=$(docker ps | awk '{print $NF}' | grep nginx)
for cid in $CID; do
docker exec -it $cid nginx -s reload
done
sleep 10
echo "Deploy new application to primary"
docker stack deploy -c docker-compose.blue.yml --resolve-image=changed mydemoapp
sleep 60
echo "Route to primary"
cat conf/nginx/nginx.conf_pri > conf/nginx/nginx.conf
CID=$(docker ps | awk '{print $NF}' | grep nginx)
for cid in $CID; do
docker exec -it $cid nginx -s reload
done
sleep 10
echo "Deploy new application to secondary"
docker stack deploy -c docker-compose.green.yml --resolve-image=changed mydemoapp
sleep 60
echo "Route round robin"
cat conf/nginx/nginx.conf_rr > conf/nginx/nginx.conf
CID=$(docker ps | awk '{print $NF}' | grep nginx)
for cid in $CID; do
docker exec -it $cid nginx -s reload
done
echo "New application deployment finished"<file_sep>#!/bin/bash
set -e
if (( $# != 1 ))
then
echo "Usage : ./docker-build.sh [version] " 1>&2
echo "ex : ./docker-build.sh v1 " 1>&2
exit 1
fi
VERSION=$1
echo ${VERSION}
docker build --no-cache --build-arg APP_VERSION=${VERSION} -f Dockerfile-webapp -t blackdog0403/webapp:${VERSION} .
#docker build --no-cache --build-arg APP_VERSION=${VERSION} -f Dockerfile-nginx -t blackdog0403/nginx:${VERSION} .
# docker build --no-cache --build-arg APP_VERSION=v1 -f Dockerfile-redis -t blackdog0403/redis:v1 .
<file_sep>buildscript {
ext {
springBootVersion = '2.0.2.RELEASE'
}
repositories {
maven { url "http://repo.maven.apache.org/maven2" }
jcenter ()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
group = 'org.springframework.boot'
if (!project.hasProperty("projVersion")) {
ext.projVersion = "v1"
}
version = project.property('projVersion')
description = """Spring Boot Web UI Sample"""
sourceCompatibility = 1.8
targetCompatibility = 1.8
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
repositories {
maven { url "http://repo.maven.apache.org/maven2" }
jcenter()
}
dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version:'2.0.3.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version:'2.0.2.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator', version: '2.0.2.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis', version: '2.0.3.RELEASE'
compile group: 'org.springframework.session', name: 'spring-session-data-redis', version: '2.0.2.RELEASE'
compile group: 'org.apache.commons', name: 'commons-pool2', version: '2.0'
compile group: 'redis.clients', name: 'jedis', version: '2.9.0'
// testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis', version: '2.0.3.RELEASE'
// testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version:'2.0.2.RELEASE'
// testCompile group: 'org.springframework.session', name: 'spring-session-data-redis', version: '2.0.2.RELEASE'
}
<file_sep># Prequesitions
- ๋ฆฌ๋
์ค ํน์ ๋งฅ
- docker 17.05-ce ์ด์ ๋ฒ์ ์ค์น
- JDK 8 ์ด์ ๋ฒ์ ์ค์น (๋ก์ปฌ๋น๋๊ฐ ํ์ํ๋ค๋ฉด)
# How to use
## 1. Docker swarm ์ค๋นํ๊ธฐ
- ์๋์ ๋ช
๋ น์ด๋ฅผ ์คํํ์ฌ docker swarm์ ํด๋น ์์ปค๋
ธ๋๋ฅผ ์ถ๊ฐํ๋ค.
```bash
$ docker swarm init
Initializing docker swarm and build docker images for deployments
Swarm initialized: current node (ru00t2xst3g2sekdjip393j5e) is now a manager.
To add a worker to this swarm, run the following command:
docker swarm join --token <KEY> 192.168.65.3:2377
To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.
```
- ์์ ๊ฐ์ด ์ ์์ ์ผ๋ก swarm ๋
ธ๋๊ฐ ์ถ๊ฐ๋๋์ง ํ์ธํ๋ค.
## 2. ๋ฐฐํฌํ๊ธฐ
- ์๋์ ๋ช
๋ น์ด๋ก ๋ฐฐํฌ, ์ญ์ , ์ฌ์์, ์ฌ๋ฐฐํฌ๋ฅผ ํ ์ ์๋ค.
```bash
$ ./devops.sh [ deploy | stop | restart | redeploy ]
```
- deploy : ์ปจํ
์ด๋ ์ ์ฒด ํ๊ฒฝ ์คํ
- stop : ์ปจํ
์ด๋ ์ ์ฒด ํ๊ฒฝ ์ค์ง
- restart : ์ปจํ
์ด๋ ์ ์ฒด ํ๊ฒฝ ์ฌ์์
- redeploy : ๋ณ๊ฒฝ๋ docker-compose ์ํ(Desire state)๋ก ๋ฌด์ค๋จ์ฌ๋ฐฐํฌ(Rolling update)
### 1) devops.sh ํ์ผ ์ด์ฉํ๊ธฐ
- ๋ค์์ ๋ช
๋ น์ด๋ก mydemoapp์ ์คํํ๋ค.
```bash
$ ./devops.sh deploy
```
### 2) ๋ฐฐํฌ ์ํ ํ์ธํ๊ธฐ
- ๋ค์์ ๋ช
๋ น์ด๋ก ๋ฐฐํฌ๊ฐ ๋ ํ์ ์ํ๋ฅผ ํ์ธํ ์ ์๋ค
```bash
$ docker stack services mydemoapp
$ curl http://localhost
```
### 3) docker stack ๋ช
๋ น์ด ์ด์ฉํ๊ธฐ
- docker-compose.yml ํ์ผ์ ์ํ๋ ๊ตฌ์ฑ์ผ๋ก ์์ ํ ๋ค์์ ๋ช
๋ น์ด๋ฅผ ์ํํ ์ ์๋ค.
```bash
docker stack deploy -c docker-compose.yml --resolve-image=changed mydemoapp
```
## 3. Explicit Blue-Green Deployment Demo
- v1 ๋ฒ์ ์ผ๋ก ๋ฐฐํฌํ ์ฑ์ v2๋ก ๋ฌด์ค๋จ ๋ฐฐํฌํ๋ demo
### 1) docker-compose.yml์ webapp ์ด๋ฏธ์ง๋ค์ tag๋ฅผ v1์ผ๋ก ์์ ํ๊ณ 2.1 ์ ๋ช
๋ น์ด๋ก ๋ฐฐํฌํ๋ค.
```bash
$ ./devops.sh deploy
```
### 2) ๋ค์์ ๋ช
๋ น์ด๋ก Blue-Green ์ ๋ต์ผ๋ก ๋ฐฐํฌ๋ฅผ ํ๋ค.
```bash
$ ./blue-green-deploy.sh
```
### 3) ์น ํ๋ก์ฐ์ ๋ฐ bash shell๋ก ์ํ๋ฅผ ๋ชจ๋ํฐ๋ง ํด๋ณด๋๋ก ํ์.
- watch๋ก ์ํ๋ฅผ ํ์ธํ๋ค.(mac os์ ์ค์น๊ฐ ๋์ด์์ง ์๋ค๋ฉด 'brew install watch' ๋ก ์ค์นํ๋๋ก ํ๋ค.)
```bash
$ watch "docker ps"
```
###
<file_sep>#!/bin/bash
set -e
if (( $# != 1 ))
then
echo "Usage : ./gradle-build.sh [version] " 1>&2
echo "ex : ./gradle-build.sh v1 " 1>&2
exit 1
fi
APP_VERSION=$1
./gradlew clean build -PprojVersion=${APP_VERSION}
| 434c97b3405e54c3e95cb4cd7f66f8148a776f96 | [
"Markdown",
"Shell",
"Gradle"
] | 6 | Shell | blackdog0403/spring-boot-gradle-web | 7553b69537c17534b1448f40646204c78c45392e | 139d79d9d1b392812dd38372692c0bccca9c010a |
refs/heads/master | <file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UserControlDemo
{
public partial class MainForm : Form
{
List<Infomations> mainList = new List<Infomations>();
public static bool logged = false;
int index, i = 1;
public MainForm()
{
InitializeComponent();
dgvInfomations.AutoGenerateColumns = false;
//button control
buttonControlMain.AddUser += AddUser;
buttonControlMain.EditUser += EditUser;
buttonControlMain.DeleteUser += DeleteUser;
//infomations control
infomationsControlMain.TextChangedHanlder += TextChangedHanlder;
}
protected void AddUser(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure?", "Notification",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Infomations newInfo = new Infomations();
newInfo.Id = i++;
newInfo.Ten = infomationsControlMain.Ten;
newInfo.NgaySinh = infomationsControlMain.NgaySinh;
newInfo.GioiTinh = infomationsControlMain.GioiTinh;
newInfo.NgheNghiep = infomationsControlMain.NgheNghiep;
newInfo.DiaChi = infomationsControlMain.DiaChi;
mainList.Add(newInfo);
updateDgv();
xoaTrang();
}
}
public void xoaTrang()
{
infomationsControlMain.Ten="";
infomationsControlMain.NgaySinh=DateTime.Now;
infomationsControlMain.NgheNghiep="";
infomationsControlMain.DiaChi="";
buttonControlMain.BtnXoa.Enabled = false;
buttonControlMain.BtnThem.Enabled = false;
buttonControlMain.BtnSua.Enabled = false;
}
private void updateDgv()
{
dgvInfomations.DataSource = null;
dgvInfomations.DataSource = mainList;
}
protected void EditUser(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure?", "Notification",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dgvInfomations.SelectedCells[0].OwningRow.Cells[0].Value.ToString());
Infomations foundpr1 = mainList.Find((Infomations k) => { return (k.Id == id); });
int index = mainList.IndexOf(foundpr1);
mainList[index].Ten = infomationsControlMain.Ten;
mainList[index].NgaySinh = infomationsControlMain.NgaySinh;
mainList[index].GioiTinh = infomationsControlMain.GioiTinh;
mainList[index].NgheNghiep = infomationsControlMain.NgheNghiep;
mainList[index].DiaChi = infomationsControlMain.DiaChi;
updateDgv();
xoaTrang();
}
}
protected void DeleteUser(object sender, EventArgs e)
{
if(logged)
{
int count = dgvInfomations.Rows.Count;
if (count > 0)
{
if (MessageBox.Show("Are you sure?", "Notification",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dgvInfomations.SelectedCells[0].OwningRow.Cells[0].Value.ToString());
Infomations foundpr1 = mainList.Find((Infomations k) => { return (k.Id == id); });
mainList.Remove(foundpr1);
updateDgv();
xoaTrang();
}
}
}
else
{
MessageBox.Show("You must login again to delete users", "Login Validation",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
LoginAgain loginAgain = new LoginAgain();
loginAgain.ShowDialog();
}
}
private void dgvInfomations_CellClick(object sender, DataGridViewCellEventArgs e)
{
buttonControlMain.BtnSua.Enabled = true;
buttonControlMain.BtnXoa.Enabled = true;
int count = dgvInfomations.Rows.Count;
if (count > 0) {
index = dgvInfomations.CurrentRow.Index;
DataGridViewRow selectedRow = dgvInfomations.Rows[index];
infomationsControlMain.Ten = selectedRow.Cells[1].Value.ToString();
infomationsControlMain.NgheNghiep = selectedRow.Cells[2].Value.ToString();
infomationsControlMain.NgaySinh = (DateTime)selectedRow.Cells[3].Value;
infomationsControlMain.GioiTinh = selectedRow.Cells[4].Value.ToString();
infomationsControlMain.DiaChi = selectedRow.Cells[5].Value.ToString();
}
}
public bool kiemtra()
{
if (infomationsControlMain.Ten == "" ||
infomationsControlMain.NgheNghiep == "" ||
infomationsControlMain.DiaChi == ""
)
{
return false;
}
else
{
return true;
}
}
private void MainForm_Load(object sender, EventArgs e)
{
}
private void buttonControlMain_Load(object sender, EventArgs e)
{
}
private void TextChangedHanlder(object sender, EventArgs e)
{
if (kiemtra())
{
buttonControlMain.BtnThem.Enabled = true;
} else
buttonControlMain.BtnThem.Enabled = false;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UserControlDemo
{
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
loginControl.LoginFailed += LoginFailed;
loginControl.LoginSuccess += LoginSuccess;
}
// This Event is fired by the Login Validation User Control
private void LoginFailed(object sender, EventArgs e)
{
MessageBox.Show("Login falied ....", "Login Validation",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
// This Event is fired by the Login Validation User Control
private void LoginSuccess(object sender, EventArgs e)
{
MainForm main = new MainForm();
this.Hide();
main.ShowDialog();
this.Close();
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UserControlDemo
{
public partial class InfomationsControl : UserControl
{
public InfomationsControl()
{
InitializeComponent();
}
// ฤแบกi diแปn cho cรกc hร m cรณ kiแปu TextChangedHandler (sender, e) -> (EventHandler)
public delegate void TextChangedHandler(object sender, EventArgs e);
public event TextChangedHandler TextChangedHanlder;
private void Infomations_Load(object sender, EventArgs e)
{
cbGioiTinh.Items.Add("Nam");
cbGioiTinh.Items.Add("Nแปฏ");
cbGioiTinh.SelectedIndex = 0;
}
public String Ten
{
get { return txtTen.Text; }
set { txtTen.Text = value; }
}
public String NgheNghiep
{
get { return txtNgheNghiep.Text; }
set { txtNgheNghiep.Text = value; }
}
public DateTime NgaySinh
{
get { return dtpNgaySinh.Value.Date; }
set { dtpNgaySinh.Value = value; }
}
public String GioiTinh
{
get { return cbGioiTinh.Text; }
set { cbGioiTinh.Text = value; }
}
public String DiaChi
{
get { return txtDiaChi.Text; }
set { txtDiaChi.Text = value; }
}
protected virtual void txt_TextChanged(object sender, EventArgs e)
{
if (this.TextChangedHanlder != null)
{
TextChangedHanlder(sender, e);
}
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UserControlDemo
{
public partial class ButtonControl : UserControl
{
public ButtonControl()
{
InitializeComponent();
}
public delegate void ButtonClickedHandler(object sender, EventArgs e);
public event ButtonClickedHandler AddUser;
public event ButtonClickedHandler EditUser;
public event ButtonClickedHandler DeleteUser;
public Button BtnThem
{
get { return btnThem; }
set { btnThem = value; }
}
public Button BtnSua
{
get { return btnSua; }
set { btnSua = value; }
}
public Button BtnXoa
{
get { return btnXoa; }
set { btnXoa = value; }
}
protected void btnThem_Click(object sender, EventArgs e)
{
if (this.AddUser != null)
{
AddUser(sender, e);
}
}
protected void btnSua_Click(object sender, EventArgs e)
{
if (this.EditUser != null)
{
EditUser(sender, e);
}
}
protected void btnXoa_Click(object sender, EventArgs e)
{
if (this.DeleteUser != null)
{
DeleteUser(sender, e);
}
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UserControlDemo
{
public partial class LoginAgain : Form
{
public LoginAgain()
{
InitializeComponent();
loginAgainControl.LoginFailed += this.LoginFailed;
loginAgainControl.LoginSuccess += this.LoginSuccess;
}
// This Event is fired by the Login Validation User Control
private void LoginFailed(object sender, EventArgs e)
{
MessageBox.Show("Login falied ....", "Login Validation",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
// This Event is fired by the Login Validation User Control
private void LoginSuccess(object sender, EventArgs e)
{
MessageBox.Show("Login success you can delete users", "Login Validation",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
MainForm.logged = true;
this.Close();
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UserControlDemo
{
public class Infomations
{
private int id;
private string ten;
private string ngheNghiep;
private DateTime ngaySinh;
private string gioiTinh;
private string diaChi;
public Infomations() {
}
public Infomations(int id,string ten , String ngheNghiep ,DateTime ngaySinh , String gioiTinh,String diaChi)
{
this.id = id;
this.ten = ten;
this.ngheNghiep = ngheNghiep;
this.ngaySinh = ngaySinh;
this.gioiTinh = gioiTinh;
this.diaChi = diaChi;
}
public int Id { get => id; set => id = value; }
public string Ten { get => ten; set => ten = value; }
public string NgheNghiep { get => ngheNghiep; set => ngheNghiep = value; }
public DateTime NgaySinh { get => ngaySinh; set => ngaySinh = value; }
public string GioiTinh { get => gioiTinh; set => gioiTinh = value; }
public string DiaChi { get => diaChi; set => diaChi = value; }
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UserControlDemo
{
public partial class LoginControl : UserControl
{
public LoginControl()
{
InitializeComponent();
}
public delegate void EventHandler(Object sender, EventArgs e);
public event EventHandler LoginSuccess;
public event EventHandler LoginFailed;
// This is the very simple Login Check Validation
// The Password must be ... "<PASSWORD>" .....
private bool LoginCheck(string pName, string pPassword)
{
return pPassword.Equals("secret");
}
// Validate Login, in any case call the LoginSuccess or
// LoginFailed event, which will notify the Application's
// Event Handlers.
private void btnLogIn_Click(object sender, EventArgs e)
{
// User Name Validation
if (txtUserName.Text.Length == 0)
{
erpLoginError.SetError(txtUserName, "Please enter a user name");
return;
}
else
{
erpLoginError.SetError(txtUserName, "");
}
// Password Validation
if (txtPassword.Text.Length == 0)
{
erpLoginError.SetError(txtPassword, "Please enter a password");
return;
}
else
{
erpLoginError.SetError(txtPassword, "");
}
// Check Password
if (LoginCheck(txtUserName.Text, txtPassword.Text))
{
// If there any Subscribers for the LoginSuccess
// Event, notify them ...
if (LoginSuccess != null)
{
LoginSuccess(this, new System.EventArgs());
}
}
else
{
// If there any Subscribers for the LoginFailed
// Event, notify them ...
if (LoginFailed != null)
{
LoginFailed(this, new System.EventArgs());
}
}
}
// Read-Write Property for User Name Label
public string LabelName
{
get
{
return lblUserName.Text;
}
set
{
lblUserName.Text = value;
}
}
// Read-Write Property for User Name Password
public string LabelPassword
{
get
{
return lblPassword.Text;
}
set
{
lblPassword.Text = value;
}
}
// Read-Write Property for Login Button Text
public string LoginButtonText
{
get
{
return btnLogin.Text;
}
set
{
btnLogin.Text = value;
}
}
// Read-Only Property for User Name
[Browsable(false)]
public string UserName
{
set
{
txtUserName.Text = value;
}
}
// Read-Only Property for Password
[Browsable(false)]
public string Password
{
set
{
txtPassword.Text = value;
}
}
private void TextBoxKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnLogIn_Click(sender, e);
}
}
}
}
| fcb0e6d614720cee3c8a7428ae421ca87f6f55b7 | [
"C#"
] | 7 | C# | nguyenngockha2904/usercontrol_csharp | 827ae300e1e70b3a286bb3e12ce9bf1c2bb065f5 | cd7212bf762d00f4e036d4527a666b8c85b749e8 |
refs/heads/master | <repo_name>kehv1n/kehv1n.github.io<file_sep>/assets/js/about.js
const data = [
{
"exerpt": "A man cannot build a reputation on what he is going to do.",
"author": "<NAME>"
},
{
"exerpt": "My mother said to me, 'If you are a soldier, you will become a general. If you are a monk, you will become the Pope.' Instead, I was a painter, and became Picasso.",
"author": "<NAME>"
},
{
"exerpt": "We are what we repeatedly do. Excellence then, is not an act, but a habit.",
"author": "Aristotle"
},
{
"exerpt": "A great man shows his greatness by the wayย he treats little men.",
"author": "<NAME>"
},
{
"exerpt": "A computer would deserve to be called intelligent if it could deceive a human into believing that it was human.",
"author": "<NAME>"
},
{
"exerpt": "Believe you can and you're halfway there.",
"author": "<NAME>"
},
{
"exerpt": "I am still learning.",
"author": "<NAME>"
},
]
// const mydata = JSON.parse(data);
// every 10 seconds, swap quote with quote randomly selected from above
// var quoteSwap = () => {
// // select random quote
// let arr_width = data.length();
// console.log(arr_width);
//
// // put onto screen
// // take width of div
// // adjust width of div = width of span
// // fill in quote author
// }
<file_sep>/README.md
# Fourth-Portfolio
Fourth one, lets see if we don't lose interest here..
The previous four sites did a poor job at having _some_ representation of who I am.. Lets see how this one turns out!
## Check out the live link:
https://www.kehv1n.github.io
| 47e2b25be0338ce3d5559c4ac1d808cf49a69a78 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | kehv1n/kehv1n.github.io | 7c379095f7ad00d164ced8a62d27a56eb36aef3d | 23a882d1bf65d5d7b290f9d5fb3da95cbf743fbd |
refs/heads/master | <repo_name>danisolo91/battleship-game<file_sep>/src/components/GameBoards.js
import { useContext, useEffect } from "react";
import { GameContext } from "../contexts/GameContext";
import GameBoard from '../factories/GameBoard';
import ComputerBoard from "./ComputerBoard";
import PlayerBoard from "./PlayerBoard";
import ShipsBoard from "./ShipsBoard";
const GameBoards = () => {
const [game, setGame] = useContext(GameContext);
useEffect(() => {
if (game.boards.length === 0) {
const board = GameBoard();
board.init();
setGame(prevState => {
return {
...prevState,
boards: [board],
};
});
}
// Computer attack
if (game.turn === 1 && game.gameOver === false) {
const computer = game.players[1];
const cell = computer.shoot();
if (cell != null) {
const playerBoard = game.boards[0];
playerBoard.receiveAttack(cell);
let turn = 0;
let gameOver = false;
if (playerBoard.hasLost()) {
turn = 1;
gameOver = true;
}
setTimeout(() => {
setGame(prevState => {
return {
...prevState,
gameOver: gameOver,
turn: turn,
players: [
prevState.players[0],
computer,
],
boards: [
playerBoard,
prevState.boards[1],
]
};
});
}, 1000);
}
}
});
const restart = () => {
const player = game.players[0];
player.clearShotsHistory();
setGame({
gameOver: false,
turn: 0,
players: [player],
boards: [],
});
}
return (
<>
<div className="boards">
{game.boards.length === 1 ?
<ShipsBoard /> :
game.boards.length === 2 &&
<>
<PlayerBoard />
<ComputerBoard />
</>
}
</div>
{game.gameOver === true &&
<>
<h3>Game Over</h3>
<p>{game.turn === 0 ? 'Congratulations, You have won!' : 'Computer wins'}</p>
<button onClick={restart}>Play again</button>
</>
}
</>
);
};
export default GameBoards;<file_sep>/src/factories/Player.js
const Player = (nickname) => {
let shotsHistory = [];
/**
* Registers on shotsHistory the cell position
* of the enemy's board when the player shoots
*/
const shoot = (cell = null) => {
let result = cell;
/**
* If the function is called without a cell position
* means that is Computer's turn, so run a randomShoot
*/
if (result === null) result = randomShot();
if (isValidShot(result)) {
shotsHistory.push(result);
} else {
result = null;
}
return result;
};
// For computer player only
const randomShot = () => {
let cell = Math.floor(Math.random() * 100);
while (!isValidShot(cell)) cell = Math.floor(Math.random() * 100);
return cell;
};
const isValidShot = (cell) => {
return (!shotsHistory.includes(cell) && cell >= 0 && cell < 100);
};
const clearShotsHistory = () => shotsHistory = [];
return { nickname, clearShotsHistory, shoot };
};
export default Player;<file_sep>/src/App.js
import { useContext } from "react";
import GameBoards from "./components/GameBoards";
import Nickname from "./components/Nickname"
import { GameContext } from "./contexts/GameContext";
const App = () => {
const game = useContext(GameContext)[0];
return (
<>
<h1>Battleship</h1>
<div className="container">
{game.players.length === 0 ?
<Nickname /> :
<GameBoards />
}
</div>
</>
);
};
export default App;<file_sep>/src/tests/GameBoard.test.js
import GameBoard from '../factories/GameBoard';
import Ship from '../factories/Ship';
const ship1 = Ship('Carrier', 5);
const ship2 = Ship('Battleship', 4);
const ship3 = Ship('Cruiser', 3);
const ship32 = Ship('Cruiser', 3);
const ship4 = Ship('Submarine', 3);
const ship5 = Ship('Destroyer', 2);
const ships = [ship1, ship2, ship32, ship4, ship5];
const gameBoard = GameBoard();
const gameBoard2 = GameBoard();
describe('GameBoard factory tests', () => {
test('init() populates the board with 100 false elements', () => {
let mockBoard = [];
for (let i = 0; i < 100; i++) {
mockBoard.push(false);
}
gameBoard.init();
expect(gameBoard.getBoard()).toStrictEqual(mockBoard);
});
test('getShips() initially returns an empty array', () => {
expect(gameBoard.getShips()).toStrictEqual([]);
});
test('getShips() returns an array with a ship after running addShip()', () => {
gameBoard.addShip([65, 66, 67], ship3)
expect(gameBoard.getShips()).toStrictEqual([ship3]);
});
test('getPlace() returns empty array when places are already occuped', () => {
expect(gameBoard.getPlace(63, 'X', ship3)).toStrictEqual([]);
});
test('getPlace() returns places when ship fits on X axis', () => {
expect(gameBoard.getPlace(23, 'X', ship3)).toStrictEqual([23, 24, 25]);
});
test('getPlace() returns empty array when ship doesn\'t fit on X axis', () => {
expect(gameBoard.getPlace(28, 'X', ship3)).toStrictEqual([]);
});
test('getPlace() returns places when ship fits on Y axis', () => {
expect(gameBoard.getPlace(22, 'Y', ship3)).toStrictEqual([22, 32, 42]);
});
test('getPlace() returns empty array when ship desn\'t fit on Y axis', () => {
expect(gameBoard.getPlace(82, 'Y', ship3)).toStrictEqual([]);
});
test('placeShipsRandomly() fills gameBoard.ships with ships', () => {
gameBoard2.placeShipsRandomly(ships);
expect(gameBoard2.getShips()).toStrictEqual(ships);
});
test('receiveAttack() updates hitted cell on "board" property', () => {
gameBoard.receiveAttack(66);
expect(gameBoard.getBoard()[66]).toBeTruthy();
});
test('receiveAttack() updates ship hitted cell on "ships" property', () => {
let ship = gameBoard.getShips().find(s => s.hasPosition(66));
let position = ship.getPositions().find(p => p.cell === 66);
expect(position.isHit).toBeTruthy();
});
});<file_sep>/src/contexts/GameContext.js
import { createContext, useState } from "react";
export const GameContext = createContext();
export const GameProvider = (props) => {
const [game, setGame] = useState({
gameOver: false,
turn: 0, // position in players array (0: human, 1: computer)
players : [],
boards: [],
});
return (
<GameContext.Provider value={[game, setGame]}>
{props.children}
</GameContext.Provider>
);
};<file_sep>/src/components/PlayerBoard.js
import { useContext } from "react";
import { GameContext } from "../contexts/GameContext";
const PlayerBoard = () => {
const game = useContext(GameContext)[0];
return (
<div>
<h2>{game.players[0].nickname}</h2>
<div className="board">
{game.boards[0].getBoard().map((cell, i) => {
let print;
if (cell === false) {
print = <div key={i} className="cell"></div>
} else if (cell === true) {
print = <div key={i} className="cell water"></div>
} else if (cell === 's') {
print = <div key={i} className="cell ship"></div>
} else if (cell === 'sh') {
print = <div key={i} className="cell hit"></div>
}
return print;
})}
</div>
</div>
);
};
export default PlayerBoard;<file_sep>/src/components/Nickname.js
import { useContext, useState } from "react";
import { GameContext } from "../contexts/GameContext";
import Player from '../factories/Player';
const Nickname = () => {
const setGame = useContext(GameContext)[1];
const [player, setPlayer] = useState(Player(""));
const changeNickname = (e) => {
setPlayer(prevState => {
return { ...prevState, [e.target.name]: e.target.value };
});
}
const submitPlayer = (e) => {
e.preventDefault();
setGame(prevState => {
return {
...prevState,
players: [player],
};
});
};
return (
<>
<form onSubmit={submitPlayer}>
<input type="text" name="nickname" placeholder="Enter your nickname..."
value={player.nickname} maxLength="15" minLength="2" required
onChange={changeNickname} />
<button type="submit">Next</button>
</form>
</>
);
};
export default Nickname;<file_sep>/src/factories/Ship.js
const Ship = (name, length) => {
/** Cells occupied by the ship on a GameBoard */
let positions = [];
const getPositions = () => {
return positions;
};
const addPosition = (cell) => {
positions.push({
cell: cell,
isHit: false,
});
};
/** Check if the ship occupies a given cell */
const hasPosition = (cell) => {
return positions.some(c => c.cell === cell);
}
/**
* Change isHit to true if the Ship receives a hit
* on a occupied cell
*/
const hit = (cell) => {
positions.forEach(p => {
if (p.cell === cell) p.isHit = true;
return p
});
}
/** Check if the ship is sunk */
const isSunk = () => {
let result = true;
for (let p of positions) {
if (p.isHit === false) {
result = false;
break;
}
}
return result;
};
return {
name,
length,
getPositions,
addPosition,
hasPosition,
hit,
isSunk,
};
};
export default Ship;<file_sep>/README.md
# Battleship Game
This is my Battleship Game made with React and Jest (for unit tests), for TheOdinProject curriculum.
Live demo: https://danisolo91.github.io/battleship-game/<file_sep>/src/factories/GameBoard.js
const GameBoard = () => {
let board = [];
let ships = [];
/**
* Populate board[] with 100 false elements.
* A true element means it has been shooted by the enemy.
*/
const init = () => {
for (let i = 0; i < 100; i++) {
board.push(false);
}
}
const getBoard = () => {
return board;
};
const getShips = () => {
return ships;
};
const addShip = (place, ship) => {
place.forEach(cell => {
ship.addPosition(cell);
board[cell] = 's';
});
ships.push(ship);
};
/**
* Place is an array containing the cells occuped
* by the ship. If the ship does not fit on that
* cells, it returns an empty array
*/
const getPlace = (cell, axis, ship) => {
let place = [];
if (axis === 'X') {
place = getHorizontalCells(cell, ship);
} else if (axis === 'Y') {
place = getVerticalCells(cell, ship);
}
/**
* Check if there is a ship already occuping
* any cell from place array
*/
if (place.length > 0 && placeIsOccuped(place)) {
place = [];
}
return place;
};
const getHorizontalCells = (cell, ship) => {
let selectedRow = Math.floor(cell / 10);
let placeRow = Math.floor((cell + ship.length - 1) / 10);
let cells = [];
/**
* If the ship fits in the selected row, populate
* cells with the corresponding positions
*/
if (placeRow === selectedRow) {
for (let i = cell; i <= cell + ship.length - 1; i++) {
cells.push(i);
}
}
return cells;
};
const getVerticalCells = (cell, ship) => {
let placeColumn = cell + (ship.length * 10) - 10;
let cells = [];
/** If the ship fits in the selected column, populate
* cells with the corresponding positions
*/
if (placeColumn < 100) {
for (let i = cell; i <= placeColumn; i += 10) {
cells.push(i);
}
}
return cells;
};
const placeIsOccuped = (place) => {
let result = false;
for (let cell of place) {
if (ships.some(s => s.hasPosition(cell))) {
result = true;
break;
}
};
return result;
};
/**
* Receive an array of ships, and places them
* on the board randomly.
*/
const placeShipsRandomly = (shipsArr) => {
shipsArr.forEach(ship => {
let place = [];
while (place.length === 0) {
const axis = Math.floor(Math.random() * 2) ? 'X' : 'Y';
const cell = Math.floor(Math.random() * 100);
place = getPlace(cell, axis, ship);
}
addShip(place, ship);
});
};
const receiveAttack = (cell) => {
if(board[cell] === false) {
board[cell] = true;
} else if(board[cell] === 's') {
board[cell] = 'sh';
}
const ship = ships.find(ship => ship.hasPosition(cell));
if (ship) ship.hit(cell);
};
const hasLost = () => {
const result = ships.filter(ship => ship.isSunk());
return (result.length === 5);
};
return {
init,
getBoard,
getShips,
getPlace,
addShip,
placeShipsRandomly,
receiveAttack,
hasLost,
};
};
export default GameBoard;<file_sep>/src/components/ComputerBoard.js
import { useContext } from "react";
import { GameContext } from "../contexts/GameContext";
const ComputerBoard = () => {
const [game, setGame] = useContext(GameContext);
// Player attack
const shoot = (cell) => {
const player = game.players[0];
const c = player.shoot(cell);
if (c != null) {
const computerBoard = game.boards[1];
computerBoard.receiveAttack(c);
let turn = 1;
let gameOver = false;
if (computerBoard.hasLost()) {
turn = 0;
gameOver = true;
}
setGame(prevState => {
return {
...prevState,
gameOver: gameOver,
turn: turn,
players: [
player,
prevState.players[1],
],
boards: [
prevState.boards[0],
computerBoard,
],
};
});
}
};
return (
<div>
<h2>{game.players[1].nickname}</h2>
{(game.turn === 0 && game.gameOver === false) ?
<div className="board has-turn active">
{game.boards[1].getBoard().map((cell, i) => {
let print;
if (cell === false) {
print = <div key={i} onClick={() => shoot(i)} className="cell normal"></div>
} else if (cell === true) {
print = <div key={i} className="cell water"></div>
} else if (cell === 's') {
print = <div key={i} onClick={() => shoot(i)} className="cell normal"></div>
} else if (cell === 'sh') {
print = <div key={i} className="cell hit"></div>
}
return print;
})}
</div> :
<div className="board">
{game.boards[1].getBoard().map((cell, i) => {
let print;
if (cell === false) {
print = <div key={i} className="cell"></div>
} else if (cell === true) {
print = <div key={i} className="cell water"></div>
} else if (cell === 's') {
print = <div key={i} className="cell"></div>
} else if (cell === 'sh') {
print = <div key={i} className="cell hit"></div>
}
return print;
})}
</div>
}
</div>
);
};
export default ComputerBoard; | 40a46008570df67aa8ef3dee6d9f2154fca84685 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | danisolo91/battleship-game | 5b13790c9d90c7d9d0c09bf61fe0c60af46339c3 | dcad04f7c3ceba302421c5b95958ece03b45d289 |
refs/heads/master | <repo_name>victorsens/vote-no-restaurante<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/java/br/com/bluesoft/votenorestaurante/domain/validation/ValidCandidatesValidator.java
package br.com.bluesoft.votenorestaurante.domain.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import br.com.bluesoft.votenorestaurante.domain.Vote;
public class ValidCandidatesValidator implements ConstraintValidator<ValidCandidates, Vote> {
@Override
public void initialize(ValidCandidates constraintAnnotation) {
}
@Override
public boolean isValid(Vote vote, ConstraintValidatorContext context) {
if(vote.getCandidate1() == null || vote.getCandidate2() == null ) {
return true;
}
if(vote.getVotedRestaurant() == null) {
return true;
}
if(vote.getCandidate1().getId() == vote.getCandidate2().getId()) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate( "{ValidCandidatesValidator.candidate1.equals.candidate2}" ).addPropertyNode( "candidate2" ).addConstraintViolation();
return false;
}
if(vote.getVotedRestaurant().getId() != vote.getCandidate1().getId() && vote.getVotedRestaurant().getId() != vote.getCandidate2().getId() ) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate( "{ValidCandidatesValidator.votedRestaurant.notEquals.candidade1.or.candidate2}" ).addPropertyNode( "votedRestaurant" ).addConstraintViolation();
return false;
}
return true;
}
}
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/java/br/com/bluesoft/votenorestaurante/domain/rest/dto/RestaurantDTO.java
package br.com.bluesoft.votenorestaurante.domain.rest.dto;
import org.springframework.hateoas.ResourceSupport;
import br.com.bluesoft.votenorestaurante.domain.Restaurant;
public class RestaurantDTO extends ResourceSupport {
private Long id;
private String name;
private String description;
private int totalVotes;
public RestaurantDTO() {
super();
}
public RestaurantDTO(Restaurant restaurant) {
this.id = restaurant.getId();
this.name = restaurant.getName();
this.description = restaurant.getDescription();
this.totalVotes = restaurant.getTotalVotes();
}
/**
* @return the id
*/
public Long getRestaurantId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
public int getTotalVotes() {
return totalVotes;
}
public void setTotalVotes(int totalVotes) {
this.totalVotes = totalVotes;
}
}
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/webapp/resources/js/vote-area.js
(function() {
var app = angular.module('vote-area', []);
app.voteController = [ '$http',function($http) {
var vote = this;
vote.session = [];
vote.votedRestaurant = {};
vote.votePosition = 0;
vote.results = [];
vote.viewMode = 'vote';
vote.addVote = function() {
vote.session.votesList[vote.votePosition].votedRestaurant = vote.getRestaurant(vote.session.votesList[vote.votePosition]);
vote.votePosition++;
if(vote.votePosition >= vote.session.votesList.length ) {
vote.viewMode = 'user';
}
vote.votedRestaurant ={}
};
$http.post( _context+'app/votingSession/new').success(function(data) {
vote.session = data;
});
vote.sendData = function() {
$http.post( _context+'app/votingSession/add', vote.session ).success(function(data) {
console.info('dados enviados');
vote.getResults();
});
};
vote.getResults = function() {
$http.get(_context+'app/restaurant/list').success(function(data) {
vote.results = data;
vote.viewMode = 'result';
});
};
vote.isVote = function() {
return vote.viewMode == 'vote'
}
vote.isUser = function() {
return vote.viewMode == 'user'
}
vote.isResult = function() {
return vote.viewMode == 'result'
};
vote.totalIndividualVotes = function(id_restaurant) {
total = 0;
for (i in vote.session.votesList) {
if(vote.session.votesList[i].votedRestaurant.id == id_restaurant) {
total++;
}
}
return total;
}
vote.getRestaurant = function(voted) {
console.info('getRestaurant');
if(voted.candidate1.id == vote.votedRestaurant) {
return voted.candidate1;
} else {
return voted.candidate2;
}
};
}];
app.directive('voteArea', function() {
return {
restrict: 'E',
templateUrl:_context+'pages/vote-area.html',
controller: app.voteController,
controllerAs: 'vote'
}
});
app.directive('voteResult', function() {
return {
restrict: 'E',
templateUrl:_context+'pages/vote-result.html',
controller: app.voteController,
controllerAs: 'resultArea'
}
});
})();<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/webapp/resources/js/application.js
var _context = /vote-no-restaurante-server/; //RESOLVER E TORNAR DINAMICO
(function() {
var app = angular.module('vote-no-restaurante', ['vote-area']);
app.controller("MenuController", function() {
this.menu = 1;
this.isMenu = function(checkMenu) {
return this.menu === checkMenu;
};
this.setMenu = function(setMenu) {
this.menu = setMenu;
};
});
app.directive('aboutArea', function() {
return {
restrict: 'E',
templateUrl: _context+'pages/about-area.html',
}
});
app.directive('contactArea', function() {
return {
restrict: 'E',
templateUrl: _context+'pages/contact-area.html',
}
});
})();<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/java/br/com/bluesoft/votenorestaurante/domain/service/imp/UserServiceImpl.java
package br.com.bluesoft.votenorestaurante.domain.service.imp;
import java.util.List;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.bluesoft.votenorestaurante.dao.UserDao;
import br.com.bluesoft.votenorestaurante.domain.User;
import br.com.bluesoft.votenorestaurante.domain.service.UserService;
@Service
public class UserServiceImpl implements UserService {
private UserDao userDao;
@Override
@Transactional
public User getForUsername(String username) {
return userDao.getForUsername(username);
}
@Override
public List<User> getUserList() {
return userDao.getUserList();
}
@Override
@Transactional(value=TxType.REQUIRED)
public void addUser(User user) {
userDao.addUser(user);
}
@Override
@Transactional
public void removeUser(Long id) {
userDao.removerUser(id);
}
@Override
public User getById(Long id) {
return userDao.getById(id);
}
/**
* @param userDao the userDao to set
*/
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>br.com.bluesoft.votenorestaurante.server</groupId>
<artifactId>vote-no-restaurante-server</artifactId>
<packaging>war</packaging>
<parent>
<groupId>br.com.bluesoft.votenorestaurante</groupId>
<artifactId>vote-no-restaurante</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<name>vote-no-restaurante-server</name>
<properties>
<!-- Spring version -->
<version.spring>4.1.2.RELEASE</version.spring>
<!-- Spring Third Party dependencies -->
<version.aopalliance>1.0</version.aopalliance>
<!-- Third Party dependencies -->
<version.standard.taglibs>1.1.2</version.standard.taglibs>
<version.commons.logging>1.1.1</version.commons.logging>
<!-- JBoss AS plugin for deployment -->
<version.jboss.as.maven.plugin>7.0.2.Final</version.jboss.as.maven.plugin>
<!-- Hibernate -->
<!-- <hibernate.version>3.3.2.GA</hibernate.version> -->
<hibernate.version>4.3.7.Final</hibernate.version>
<!-- Gson verson -->
<gson-version>2.3.1</gson-version>
<junit-version>4.12</junit-version>
<mockito-version>2.0.31-beta</mockito-version>
<javax.validation>1.1.0.Final</javax.validation>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-web-6.0</artifactId>
<version>3.0.0.Beta1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring dependencies -->
<!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-asm</artifactId>
<version>${version.spring}</version> </dependency> -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
<version>0.16.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson-version}</version>
</dependency>
<!-- Third Party dependencies -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>${version.aopalliance}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${version.standard.taglibs}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${version.commons.logging}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Import the JPA API using the provided scope It is included in JBoss
AS 7 / EAP 6 -->
<!-- <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId>
</dependency> -->
<!-- Import Spring dependencies, these are either from community or versions
certified in WFK2 -->
<!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-asm</artifactId>
</dependency> -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
</dependency>
<!-- Gson dependency -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<!-- Other community dependencies -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</dependency>
<!-- Hibernate dependencies -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>el-impl</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>vote-no-restaurante-server</finalName>
<plugins>
<!-- Force Java 6 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- Deployent on AS from console -->
<plugin>
<groupId>org.jboss.as.plugins</groupId>
<artifactId>jboss-as-maven-plugin</artifactId>
<version>${version.jboss.as.maven.plugin}</version>
</plugin>
<!-- Surefire plugin before 2.9 version is buggy -->
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<configuration>
<jvmArgs>-XX:PermSize=1024M -XX:MaxPermSize=512M
-XX:+HeapDumpOnOutOfMemoryError</jvmArgs>
<scanIntervalSeconds>10</scanIntervalSeconds>
<!-- Configure the webapp -->
<contextPath>/vote-no-restaurante-server</contextPath>
<!-- configure the container -->
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8089</port>
<maxIdleTime>60000</maxIdleTime>
</connector>
</connectors>
<requestLog implementation="org.mortbay.jetty.NCSARequestLog">
<filename>target/yyyy_mm_dd.gfconfig.log</filename>
<retainDays>90</retainDays>
<append>true</append>
<extended>false</extended>
<logTimeZone>GMT</logTimeZone>
</requestLog>
<systemProperties>
<systemProperty>
<name>logback.configurationFile</name>
<value>jetty.xml</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/test/java/br/com/bluesoft/votenorestaurante/domain/service/imp/UserServiceImplTest.java
package br.com.bluesoft.votenorestaurante.domain.service.imp;
import java.util.List;
import javax.validation.ConstraintViolation;
import org.junit.Assert;
import org.junit.Test;
import br.com.bluesoft.votenorestaurante.domain.User;
import br.com.bluesoft.votenorestaurante.test.BaseTest;
public class UserServiceImplTest extends BaseTest<User> {
@Test
public void nullNameTest() {
User user = new User();
user.setEmail("<EMAIL>");
List<ConstraintViolation<User>> list = super.validate(user);
Assert.assertEquals(list.get(0).getPropertyPath().toString(), "nome");
user.setNome("nome");
list = super.validate(user);
Assert.assertEquals(list.size(), 0);
}
@Test
public void nullEmailTest() {
User user = new User();
user.setNome("12345");
List<ConstraintViolation<User>> list = super.validate(user);
Assert.assertEquals(list.get(0).getPropertyPath().toString(), "email");
user.setEmail("<EMAIL>");
list = super.validate(user);
Assert.assertEquals(list.size(), 0);
}
@Test
public void emailformaterTest() {
User user = new User();
user.setNome("nome");
user.setEmail("teste");
List<ConstraintViolation<User>> list = super.validate(user);
Assert.assertEquals(list.get(0).getPropertyPath().toString(), "email");
user.setEmail("teste@");
list = super.validate(user);
Assert.assertEquals(list.get(0).getPropertyPath().toString(), "email");
user.setEmail("<EMAIL>");
list = super.validate(user);
Assert.assertEquals(list.get(0).getPropertyPath().toString(), "email");
user.setEmail("<EMAIL>");
list = super.validate(user);
Assert.assertEquals(list.size(), 0);
}
}
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/java/br/com/bluesoft/votenorestaurante/web/RestaurantController.java
package br.com.bluesoft.votenorestaurante.web;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import br.com.bluesoft.votenorestaurante.domain.Restaurant;
import br.com.bluesoft.votenorestaurante.domain.rest.dto.RestaurantDTO;
import br.com.bluesoft.votenorestaurante.domain.service.RestaurantService;
@RestController
@RequestMapping
public class RestaurantController {
private RestaurantService restaurantService;
@Autowired
public RestaurantController(RestaurantService restaurantService) {
this.restaurantService = restaurantService;
}
@RequestMapping(value = "/restaurant/list", method = RequestMethod.GET, produces = { "application/json" }) // , "application/xml"
@ResponseStatus(HttpStatus.OK)
public List<RestaurantDTO> getUserList() {
List<Restaurant> restaurants = restaurantService.getAll();
List<RestaurantDTO> restaurantDTOs = new ArrayList<RestaurantDTO>(restaurants.size());
for (Restaurant restaurant : restaurants) {
restaurantDTOs.add(new RestaurantDTO(restaurant));
}
return restaurantDTOs;
}
}
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/java/br/com/bluesoft/votenorestaurante/domain/service/RestaurantService.java
package br.com.bluesoft.votenorestaurante.domain.service;
import java.util.List;
import br.com.bluesoft.votenorestaurante.domain.Restaurant;
public interface RestaurantService {
List<Restaurant> getAll();
}
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/test/java/br/com/bluesoft/votenorestaurante/domain/service/imp/VotingSessionServiceImplTest.java
package br.com.bluesoft.votenorestaurante.domain.service.imp;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import javax.validation.ConstraintViolation;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import br.com.bluesoft.votenorestaurante.dao.VotingSessionDAO;
import br.com.bluesoft.votenorestaurante.domain.Restaurant;
import br.com.bluesoft.votenorestaurante.domain.User;
import br.com.bluesoft.votenorestaurante.domain.Vote;
import br.com.bluesoft.votenorestaurante.domain.VotingSession;
import br.com.bluesoft.votenorestaurante.domain.service.RestaurantService;
import br.com.bluesoft.votenorestaurante.test.BaseTest;
public class VotingSessionServiceImplTest extends BaseTest<VotingSession> {
private VotingSessionServiceImpl votingSessionService;
@Before
public void initializeMocks() {
VotingSessionDAO dao = mock(VotingSessionDAO.class);
RestaurantService restaurantService = mock(RestaurantService.class);
votingSessionService = new VotingSessionServiceImpl(dao);
votingSessionService.setRestaurantService(restaurantService);
when(restaurantService.getAll()).thenReturn(restaurants);
}
//calcula todas as possibildiades de votos que o sistema tem que gerar
private int calcQuantityVotes() {
int total = 0;
for (int i = 0; i < TOTAL_RESTAURANTS; i++) {
total+=i;
}
return total;
}
/**
* testar se o nรบmero de votos gerados contempla todas as possibilidades
*/
@Test
public void quantityVotesGenerated() {
VotingSession session = votingSessionService.createVotingSession();
Assert.assertEquals(session.getVotesList().size(), calcQuantityVotes());
}
/**
* Tenta persistir um VotingSession sem USER, e verifica se a validaรงรฃo pega
*/
@Test
public void nullVoteInSessionValidateTest() {
VotingSession session = new VotingSession();
session.setUser(null);
List<ConstraintViolation<VotingSession>> constraintViolations = super.validate(session);
ConstraintViolation<VotingSession> contraint = constraintViolations.get(0);
Assert.assertEquals(contraint.getPropertyPath().toString(), "user");
}
/**
* Verifica se o validador aceita o objeto dentro da especificacao.
*/
@Test
public void validationEntityTest() {
VotingSession session = new VotingSession();
session.setUser(new User());
List<ConstraintViolation<VotingSession>> constraintViolations = super.validate(session);
Assert.assertEquals(constraintViolations.size(), 0);
}
@Test
public void notNullVotesTest() {
VotingSession session = votingSessionService.createVotingSession();
Assert.assertNotNull(session.getVotesList());
for (Vote vote: session.getVotesList()) {
Assert.assertNotNull(vote);
}
}
/**
* testar se cada restaurante esta sendo votado o n๏ฟฝmero m๏ฟฝnimo de vezes
*/
@Test
public void quantityVotesOfEachRetaurant() {
int totalOfEachRestaurant = TOTAL_RESTAURANTS -1;
VotingSession session = votingSessionService.createVotingSession();
for (Vote vote : session.getVotesList()) {
Restaurant rest = getRestaurantById(vote.getCandidate1().getId());
Assert.assertNotNull(rest);
rest.setTotalVotes(rest.getTotalVotes()+1);
rest = getRestaurantById(vote.getCandidate2().getId());
Assert.assertNotNull(rest);
rest.setTotalVotes(rest.getTotalVotes()+1);
}
for (Restaurant restaurant : restaurants) {
Assert.assertEquals(totalOfEachRestaurant, restaurant.getTotalVotes());
}
}
}
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/java/br/com/bluesoft/votenorestaurante/dao/imp/UserDaoImpl.java
package br.com.bluesoft.votenorestaurante.dao.imp;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import br.com.bluesoft.votenorestaurante.dao.UserDao;
import br.com.bluesoft.votenorestaurante.domain.User;
@Repository
public class UserDaoImpl implements UserDao {
@PersistenceContext
private EntityManager entityManager;
public User getForUsername(String username) {
try {
Query query = entityManager
.createQuery("select u from User u where u.username = ?");
query.setParameter(1, username);
return (User) query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
@SuppressWarnings("unchecked")
@Override
public List<User> getUserList() {
Query query = entityManager.createQuery("from User");
return query.getResultList();
}
@Override
public void addUser(User user) {
entityManager.merge(user);
}
@Override
public void removerUser(Long id) {
Query query = entityManager
.createQuery("delete from User u where u.id = ? ");
query.setParameter(1, id);
query.executeUpdate();
}
@Override
public User getById(Long id) {
try {
Query query = entityManager
.createQuery("select u from User u where u.id = ?");
query.setParameter(1, id);
return (User) query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
}<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/java/br/com/bluesoft/votenorestaurante/dao/UserDao.java
package br.com.bluesoft.votenorestaurante.dao;
import java.util.List;
import br.com.bluesoft.votenorestaurante.domain.User;
public interface UserDao
{
User getForUsername(String username);
List<User> getUserList();
void addUser(User user);
void removerUser(Long id);
User getById(Long id);
}<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/java/br/com/bluesoft/votenorestaurante/domain/service/imp/VoteServiceImpl.java
package br.com.bluesoft.votenorestaurante.domain.service.imp;
import java.util.List;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.bluesoft.votenorestaurante.dao.VoteDAO;
import br.com.bluesoft.votenorestaurante.domain.Vote;
import br.com.bluesoft.votenorestaurante.domain.service.VoteService;
@Service
public class VoteServiceImpl implements VoteService {
private VoteDAO dao;
@Autowired
public VoteServiceImpl(VoteDAO dao) {
this.dao = dao;
}
@Override
@Transactional(value=TxType.REQUIRED)
public void saveVotesList(List<Vote> votesList) {
dao.saveVotesList(votesList);
}
}
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/java/br/com/bluesoft/votenorestaurante/domain/service/imp/VotingSessionServiceImpl.java
package br.com.bluesoft.votenorestaurante.domain.service.imp;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.bluesoft.votenorestaurante.dao.VotingSessionDAO;
import br.com.bluesoft.votenorestaurante.domain.Restaurant;
import br.com.bluesoft.votenorestaurante.domain.User;
import br.com.bluesoft.votenorestaurante.domain.Vote;
import br.com.bluesoft.votenorestaurante.domain.VotingSession;
import br.com.bluesoft.votenorestaurante.domain.service.RestaurantService;
import br.com.bluesoft.votenorestaurante.domain.service.UserService;
import br.com.bluesoft.votenorestaurante.domain.service.VoteService;
import br.com.bluesoft.votenorestaurante.domain.service.VotingSessionService;
@Service
public class VotingSessionServiceImpl implements VotingSessionService {
private VotingSessionDAO dao;
private RestaurantService restaurantService;
private VoteService voteService;
private UserService userService;
@Autowired
public VotingSessionServiceImpl(VotingSessionDAO dao) {
this.dao = dao;
}
@Override
public VotingSession getById(long id) {
return dao.getByid(id);
}
/**
* Cria a sessรฃo de votos com todos as combinaรงรตes de votos jรก incluidas.
* porรฉm nรฃo persiste nada ainda, somente quando o primeiro voto for submetido.
*/
@Override
@Transactional(value=TxType.REQUIRED)
public VotingSession createVotingSession() {
VotingSession session = new VotingSession();
List<Restaurant> restaurants = restaurantService.getAll();
List<Vote> votes = new ArrayList<Vote>();
Vote vote = null;
for (int i = 0; i < restaurants.size(); i++) {
for (int j = i+1; j < restaurants.size(); j++) {
vote = new Vote();
vote.setCandidate1(restaurants.get(i));
vote.setCandidate2(restaurants.get(j));
vote.setSession(session);
votes.add(vote);
}
}
session.setVotesList(votes);
User user = new User();
session.setUser(user);
return session;
}
/**
* @param restaurantService the restaurantService to set
*/
@Autowired
public void setRestaurantService(RestaurantService restaurantService) {
this.restaurantService = restaurantService;
}
@Override
@Transactional(value=TxType.REQUIRED)
public void save(@Valid VotingSession session) {
for (Vote vote : session.getVotesList()) {
vote.setSession(session);
}
userService.addUser(session.getUser());
session.setUser(userService.getById(session.getUser().getId())); //TODO corrigir isto.
dao.save(session);
voteService.saveVotesList(session.getVotesList());
}
@Autowired
public void setVoteService(VoteService voteService) {
this.voteService = voteService;
}
/**
* @param userService the userService to set
*/
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
}
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/java/br/com/bluesoft/votenorestaurante/domain/service/imp/RestaurantServiceImpl.java
package br.com.bluesoft.votenorestaurante.domain.service.imp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.bluesoft.votenorestaurante.dao.RestaurantDAO;
import br.com.bluesoft.votenorestaurante.domain.Restaurant;
import br.com.bluesoft.votenorestaurante.domain.service.RestaurantService;
@Service
public class RestaurantServiceImpl implements RestaurantService {
private RestaurantDAO restaurantDao;
@Autowired
public RestaurantServiceImpl(RestaurantDAO restaurantDao) {
this.restaurantDao = restaurantDao;
}
@Override
public List<Restaurant> getAll() {
return restaurantDao.getAll();
}
}
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/test/java/br/com/bluesoft/votenorestaurante/test/BaseTest.java
package br.com.bluesoft.votenorestaurante.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.Before;
import br.com.bluesoft.votenorestaurante.domain.BaseEntity;
import br.com.bluesoft.votenorestaurante.domain.Restaurant;
public class BaseTest<T extends BaseEntity> {
protected static final int TOTAL_RESTAURANTS = 3;
private Validator localValidatorFactory;
protected List<Restaurant> restaurants ;
@Before
public void initializeValidation() {
createRestaurantList();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
localValidatorFactory = factory.getValidator();
}
@SuppressWarnings("unchecked")
public List<ConstraintViolation<T>> validate( T entity) {
Set<ConstraintViolation<T>> errors = localValidatorFactory.validate(entity);
ConstraintViolation<T>[] array = new ConstraintViolation[] {};
array = errors.toArray(array);
List<ConstraintViolation<T>> list = Arrays.asList(array);
return list;
}
public Restaurant getRestaurantById(Long id) {
for (Restaurant restaurant : restaurants) {
if(restaurant.getId().equals(id)) {
return restaurant;
}
}
return null;
}
private void createRestaurantList() {
restaurants = new ArrayList<Restaurant>(TOTAL_RESTAURANTS);
Restaurant restaurant = new Restaurant();
restaurant.setId(1L);
restaurant.setName("MacDonalds");
restaurant.setDescription("fastfood");
restaurants.add(restaurant);
restaurant = new Restaurant();
restaurant.setId(2L);
restaurant.setName("OutBack");
restaurant.setDescription("casual dining");
restaurants.add(restaurant);
restaurant = new Restaurant();
restaurant.setId(3L);
restaurant.setName("Subway");
restaurant.setDescription(" sanduรญches e saladas");
restaurants.add(restaurant);
}
}
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/resources/init-db.sql
drop table tb_user if exists;
drop table tb_vote if exists;
drop table tb_voting_session if exists;
drop table tb_restaurant if exists;
create table tb_restaurant (id_restarurant bigint not null, nm_description varchar(255), nm_name varchar(255), primary key (id_restarurant));
create table tb_user (id bigint not null, email varchar(255), nome varchar(255), primary key (id));
create table tb_vote (id_vote bigint not null, id_candidate_restaurant1 bigint not null, id_candidate_restaurant2 bigint not null, Id_session bigint not null, id_voted_restaurant bigint not null, primary key (id_vote));
create table tb_voting_session (id_voting_session bigint not null, id_user bigint not null, primary key (id_voting_session));
alter table tb_vote add constraint FK_iryh1ueg8k1srget720icn1q3 foreign key (id_candidate_restaurant1) references tb_restaurant;
alter table tb_vote add constraint FK_qs3hrlxtq39seemduusobqnbb foreign key (id_candidate_restaurant2) references tb_restaurant;
alter table tb_vote add constraint FK_rsifdsn6wqvdukh7f2tqgo04k foreign key (Id_session) references tb_voting_session;
alter table tb_vote add constraint FK_axvde0q4r1hinl4ujrjeehhh7 foreign key (id_voted_restaurant) references tb_restaurant;
alter table tb_voting_session add constraint FK_cxwt5e9gqmda1xm1iwp45wmq foreign key (id_user) references tb_user;
INSERT INTO "PUBLIC"."TB_RESTAURANT"
( "ID_RESTARURANT", "NM_DESCRIPTION", "NM_NAME" )
VALUES ( 1, 'Maior cadeia mundial de restaurantes de fast food de hambรบrguer.', 'McDonalds');
INSERT INTO "PUBLIC"."TB_RESTAURANT"
( "ID_RESTARURANT", "NM_DESCRIPTION", "NM_NAME" )
VALUES ( 2, 'Cadeia de restaurantes norte-americana de casual dining.', 'Outback');
INSERT INTO "PUBLIC"."TB_RESTAURANT"
( "ID_RESTARURANT", "NM_DESCRIPTION", "NM_NAME" )
VALUES (3 , 'rede norte-americana de restaurantes, que tem como especialidade a venda de sanduรญches e saladas.', 'Subway');
INSERT INTO "PUBLIC"."TB_RESTAURANT"
( "ID_RESTARURANT", "NM_DESCRIPTION", "NM_NAME" )
VALUES (4 ,' The Best Burguer in the World.','Madero');
INSERT INTO "PUBLIC"."TB_RESTAURANT"
( "ID_RESTARURANT", "NM_DESCRIPTION", "NM_NAME" )
VALUES (5 , 'รฉ uma rede de restaurantes especializada em fast-food,', 'Burger King');
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/test/java/br/com/bluesoft/votenorestaurante/domain/service/imp/RestaurantServiceImplTest.java
package br.com.bluesoft.votenorestaurante.domain.service.imp;
import java.util.List;
import javax.validation.ConstraintViolation;
import org.junit.Assert;
import org.junit.Test;
import br.com.bluesoft.votenorestaurante.domain.Restaurant;
import br.com.bluesoft.votenorestaurante.test.BaseTest;
public class RestaurantServiceImplTest extends BaseTest<Restaurant> {
@Test
public void validateNullNameTest() {
Restaurant restaurant = new Restaurant();
List<ConstraintViolation<Restaurant>> listErros = super.validate(restaurant);
Assert.assertEquals(listErros.get(0).getPropertyPath().toString(), "name");
}
}
<file_sep>/vote-no-restaurante/vote-no-restaurante-server/src/main/java/br/com/bluesoft/votenorestaurante/web/UserRestController.java
//package br.com.bluesoft.votenorestaurante.web;
//
//import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
//import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
//
//import java.util.ArrayList;
//import java.util.List;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.hateoas.Link;
//import org.springframework.http.HttpStatus;
//import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.ResponseStatus;
//import org.springframework.web.bind.annotation.RestController;
//
//import br.com.bluesoft.votenorestaurante.domain.ReturnMessage;
//import br.com.bluesoft.votenorestaurante.domain.User;
//import br.com.bluesoft.votenorestaurante.domain.ReturnMessage.MESSAGE_TYPE;
//import br.com.bluesoft.votenorestaurante.domain.rest.dto.UserDTO;
//import br.com.bluesoft.votenorestaurante.domain.service.UserService;
//
//@RestController
//@RequestMapping
//public class UserRestController {
//
// @Autowired
// private UserService userService;
//
// @RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = {"application/json" }) //, "application/xml"
// @ResponseStatus(HttpStatus.OK)
// public UserDTO getUser(@PathVariable Long id) {
// User user = userService.getById(id);
// UserDTO userDto = new UserDTO(user);
// userDto.add(linkTo(methodOn(UserRestController.class).getUser(userDto.getUserId())).withSelfRel());
// return userDto;
// }
//
//
// @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE, produces = {"application/json" }) //, "application/xml"
// public ReturnMessage removeUser(@PathVariable Long id) {
// ReturnMessage retorno = new ReturnMessage();
// try {
// userService.removeUser(id);
// retorno.setMessageType(MESSAGE_TYPE.SUCCESS);
// retorno.setUserMessageBundle("userDelete.success");
// } catch(Exception e) {
// retorno.setMessageType(MESSAGE_TYPE.ERROR);
// retorno.setErrorMessage(e.getMessage());
// retorno.setUserMessageBundle("userDelete.error");
// }
// return retorno;
// }
//
// @RequestMapping(value = "/user/list", method = RequestMethod.GET, produces = { "application/json" }) // , "application/xml"
// @ResponseStatus(HttpStatus.OK)
// public List<UserDTO> getUserList() {
// List<User> users = userService.getUserList();
// List<UserDTO> usersDto = new ArrayList<UserDTO>(users.size());
// for (User entity : users) {
// UserDTO userdto = new UserDTO(entity);
// userdto.add(linkTo(methodOn(UserRestController.class).getUser(userdto.getUserId())).withSelfRel());
// usersDto.add(userdto);
// }
// return usersDto;
// }
//
//
// @RequestMapping(value = "/user/info", method = RequestMethod.GET, produces = { "application/json" }) // , "application/xml"
// @ResponseStatus(HttpStatus.OK)
// public List<Link> getInfo() throws Exception {
// List<Link> links = new ArrayList<Link>();
// links.add(linkTo(methodOn(UserRestController.class).getUserList()).withRel("list"));
// links.add(linkTo(methodOn(UserRestController.class).addUser(null)).withRel("create"));
// return links;
// }
//
//
// @RequestMapping(value = "/user", method = RequestMethod.POST, produces = { "application/json" }) // , "application/xml"
// @ResponseStatus(HttpStatus.OK)
// public ReturnMessage addUser(@RequestBody User user) throws Exception {
// ReturnMessage retorno = new ReturnMessage();
// try {
// userService.addUser(user);
// retorno.setMessageType(MESSAGE_TYPE.SUCCESS);
// retorno.setUserMessageBundle("userAdd.success");
// } catch(Exception e) {
// e.printStackTrace();
// retorno.setMessageType(MESSAGE_TYPE.ERROR);
// retorno.setErrorMessage(e.getMessage());
// retorno.setUserMessageBundle("userAdd.error");
// }
// return retorno;
// }
//
//}
| 9c79e92432382321a41c2927492b225b2031d7e6 | [
"JavaScript",
"Java",
"Maven POM",
"SQL"
] | 19 | Java | victorsens/vote-no-restaurante | a2d064297e4a1f83b3e25f8e00bb62fc7a37bb8f | 76cc2d2f1890096af781d9c727c16a57e6525765 |
refs/heads/master | <repo_name>feliperufin0/cadastro<file_sep>/conec.php
<?php
$servername = "localhost";
$username = "root";
$password ="<PASSWORD>";
$bd = "estoque_prod";
$con = mysqli_connect($servername, $username, $password, $bd);
?><file_sep>/cd.php
<?php
/*
$servername = "localhost";
$username = "root";
$password ="<PASSWORD>";
$bd = "estoque_prod";
$con = mysqli_connect($servername, $username, $password, $bd);*/
include 'conec.php';
$nome = $_POST['nomeprod'];
$num = $_POST['numprod'];
$forn = $_POST['forn'];
$categ = $_POST['categ'];
$sql = "INSERT INTO estoque ( nomeprod , numprod,forn,categ)VALUES('$nome', $num,'$forn','$categ')";
mysqli_query($con, $sql) ;
?>
<!DOCTYPE html>
<html>
<head>
<title>Sucesso</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Oswald&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="container" style="width: 500px;margin-top: 90px;">
<center><h4>Produto cadastrado com sucesso</h4></center>
<center><a href="adicionar.php" class="btn btn-primary" style="margin-right: 97px;margin-top: 19px;">cadastar outro produto</a></center>
<center><a href="index.php" class="btn btn-dark" style="margin-right:10px;background-color: #092E12; border-color: #031006 ">Voltar</a></center>
</div>
</body>
</html>
<file_sep>/lista_produtos.php
<!DOCTYPE html>
<html>
<head>
<title>Lista de produtos</title>
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Oswald&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="conatiner" style="width: 700px;margin-top: 70px;font-family: 'Oswald'">
<H3 >Lista de produtos</H3>
<table class="table table-striped" style="margin-top: 40px;font-family:'roboto Condensed' ">
<thead>
<tr>
<th scope="col">Nรบmero</th>
<th scope="col">Produto</th>
<th scope="col">Fornecedor</th>
<th scope="col">Categoria</th>
</tr>
</thead>
<tr>
<?php
include 'conec.php';
$sql = "SELECT * FROM estoque ";
$busca = mysqli_query($con , $sql);
while ($array= mysqli_fetch_array($busca)) {
//$id_estoque = $array['id-estoque'];
$nome = $array['nomeprod'];
$num = $array['numprod'];
$forn = $array['forn'];
$categ = $array['categ'];
?>
<tr>
<td><?php echo $num ?></td>
<td><?php echo $nome ?></td>
<td><?php echo $forn ?></td>
<td><?php echo $categ ?></td>
</tr>
<?php }?>
</table>
</div>
<!-- ------------------SCRIPTS BOOTSTRAP----------------------- >
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
| d82ded415973b71d5e41fd4b13f0648346e5e46f | [
"PHP"
] | 3 | PHP | feliperufin0/cadastro | 4ff0ed7e48b75f6645f71da5738434912f7e2548 | c058c3ce537ff3eb016526bcee0a11ab11a87280 |
refs/heads/master | <repo_name>kingntop/mrp<file_sep>/sftpclient.py
import paramiko
import datetime, os
import glob
from sftpconn import sftpconn
import shutil
import json
now = datetime.datetime.now() - datetime.timedelta(minutes=10)
YMD = now.strftime("%Y%m%d")
HMD = now.strftime("%Y%M")
YMD = '20200620'
JSON_BASE = '/home/mrp/Script/'
PLOG = '/home/mrp/Script/paramiko.log'
LOCAL = '/home/mrp/Script/logs/'
REMOTE = '/logs/uplus'
DIRS = ['/arentService11/tloLog/', '/arentService12/tloLog/']
def set_Env():
with open(JSON_BASE + "mrp/env.json") as json_file:
json_data = json.load(json_file)
global HOSTS, USERNAME, PASSWORD
HOSTS = json_data["server"]
USERNAME = json_data["id"]
PASSWORD = json_data["pwd"]
print (HOSTS)
def check_dir(PATH):
try:
os.makedirs(PATH)
except OSError:
pass
def remove_dir(PATH):
try:
os.makedirs(LOCAL + YMD)
except OSError:
pass
def remove_basefile(PATH):
fileList = glob.glob(PATH + '*.log')
# shutil.rmtree(PATH)
print('remove_basefile_filelist', fileList)
for filePath in fileList:
try:
os.remove(filePath)
except:
print("Error while deleting file : ", filePath)
def concatFiles(PATH, filename):
file_list = glob.glob(PATH+'*.log')
with open(PATH + filename, 'a') as merge_file :
print ('concate file lsit ', file_list)
for fname in file_list:
with open(fname, 'r') as f:
for line in f:
merge_file.write(line)
def localfile_list (PATH):
arr = os.listdir(PATH)
print('file', arr)
return arr
if __name__ == "__main__":
set_Env()
local_base = LOCAL + YMD + '/';
remove_basefile(local_base);
for host in HOSTS :
try :
f = sftpconn(PLOG, USERNAME, PASSWORD, host, '22', False);
for servicenum in DIRS :
local_host = local_base + '/' + host + '/'
check_dir(local_host)
print(local_host)
lfiles = localfile_list(local_host)
f.get(lfiles, local_host, local_base, REMOTE + servicenum + YMD + '/')
f.close()
except Exception as e:
print(e)
concatFiles(local_base, YMD + HMD + '.txt')<file_sep>/sftpconn.py
import paramiko, os
from os import path, access, R_OK
class sftpconn(object):
rsa_private_key = r'/path/to/your/rsa.key'
def __init__(self, logfile, username, password, host, port, ssh_key):
paramiko.util.log_to_file(logfile)
print ('Establishing SSH connection to:', host, port, '...')
self.transport = paramiko.Transport((host, int(port)))
if ssh_key == True:
sshkey = paramiko.RSAKey.from_private_key_file(self.rsa_private_key)
self.transport.connect(username = username, pkey = sshkey)
else:
self.transport.connect(username = username, password = <PASSWORD>)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
# check if the file exists
def check_file(self, PATH):
if path.exists(PATH) and path.isfile(PATH) and access(PATH, R_OK):
return 0
else:
return 1
# this function will allow the use of wildcards in between underscores, eg: file_*_name.txt
def is_match(self, a, b):
aa = a.split('_')
bb = b.split('_')
if len(aa) != len(bb): return False
for x, y in zip(aa, bb):
if not (x == y or x == '*' or y == '*'): return False
return True
def get(self, file_formats, local_dir, local_base_dir, remote_dir):
files_copied = 0
errors = 0
summary = ''
actual_files = []
remote_files = []
print ('local_dir:', local_dir)
print ('local_base_dir:', local_base_dir)
try:
for f in self.sftp.listdir(remote_dir):
remote_files.append(f)
difference = list(set(remote_files).difference(file_formats))
# print(difference)
# for file_format in file_formats:
for f in difference:
actual_files.append(remote_dir+f)
for actual_file in actual_files:
print ('actual_file:', actual_file)
base_file = actual_file.replace(remote_dir, '')
self.sftp.get(actual_file, local_dir + base_file)
self.sftp.get(actual_file, local_base_dir + base_file)
files_copied += 1
summary += "[Copied] " + local_dir + base_file + '\n'
if errors > 0 or files_copied == 0:
print ('summary:', summary)
if files_copied == 0:
return [summary, "No files available for transfer.", 'No Files']
else:
return [summary, "This transaction failed with "+ str(errors) +" error/s:\n\n" + summary, 'Failed']
else:
return [summary, "Total file/s copied: %s. Summary: %s" % (str(files_copied), summary), 'Success']
except Exception as e:
print ('exception:', e)
return [summary, "Error while copying file : " + str(e), 'Failed']
def chdir(self, dir):
self.sftp.chdir(dir)
def ls(self, remote):
return self.sftp.listdir(remote)
def close(self):
if self.transport.is_active():
self.sftp.close()
self.transport.close()
def __enter__(self):
return self
def __exit__(self, type, value, tb):
self.close()
# def mput(self, local, remote):
# files_copied = 0
# summary = ''
# try:
# for root, dirs, files in os.walk(local):
# print files
# for name in sorted(files):
# filename = os.path.join(root, name)
# self.sftp.put(filename, remote + name)
# files_copied += 1
# summary = summary + "Copied: " + remote + name + "\n"
# return [summary, "Total file/s copied: " + str(files_copied), 'Success']
# except Exception, e:
# return [summary, "Error: " + str(e), 'Failed']
def mget(self, lfile, local, remote):
files_copied = 0
summary = ''
try:
for f in self.sftp.listdir(remote):
print (f)
self.sftp.get(remote+f, local+f)
files_copied += 1
summary = summary + "Copied: " + remote + f + "\n"
print (summary)
return [summary, "Total file/s copied: " + str(files_copied), 'Success']
except Exception as e:
print (e)
return [summary, "Error: " + str(e), 'Failed']
| 51b1cc87b52ce6c78ab54ba9304498f8d8c005d1 | [
"Python"
] | 2 | Python | kingntop/mrp | 513e386daf9d35c6e725b68ab12bfd304fa75e2e | a716f395992684b7a5f107171e5a6e07561e3866 |
refs/heads/master | <file_sep>#!/bin/bash
testing=1
path="$1"
shift
if [[ "$path" = "" ]]; then
echo "no path specified"
exit 1
fi
realpath=$(realpath $path)
dir=$(dirname $realpath)
file=$(echo $realpath | sed -e "s@$dir/@@")
devdir=$(echo $dir | sed -e "s@/$USER/@/dev/@")
echo "Running tests for $realpath"
# echo "dir=$dir"
# echo "file=$file"
# echo "devdir=$devdir"
run.sh bash -c "cd $devdir && go test -race -count=1 -v --vmodule=*=0 -failfast $* ." 2>&1 | sed -re "s@/dev/@/$USER/@" -re "s@^ *\./@$dir/@" -re "s@^ *\.\./@$dir/../@" -re "s@^ *([^/]+\.go):@$dir/\\1:@"
if [ $? -ne 0 ]; then
echo "build failed"
exit 1
fi
echo "Running lint in $devdir"
run.sh bash -c "cd $devdir && /home/dev/go/bin/golangci-lint run --color never ." 2>&1 | sed -re "s@/dev/@/$USER/@" -re "s@^ *\./@$dir/@" -re "s@^ *\.\./@$dir/../@" -re "s@^ *([^/]+\.go):@$dir/\\1:@"
if [ $? -ne 0 ]; then
echo "lint failed"
exit 1
fi
<file_sep>#!/bin/bash
#
# To install on a fresh new machine/instance:
#
# git clone <EMAIL>:jwatte/vim-colors
# ./vim-colors/setup.sh
set -e
set -x
cd "$(dirname $0)"
git submodule init
git submodule update
rm -f ~/.vimrc
ln -s ~/vim-colors/vimrc ~/.vimrc
rm -rf ~/.vim
ln -s ~/vim-colors ~/.vim
rm -f ~/build-go.sh
ln -s ~/vim-colors/build-go.sh ~/build-go.sh
if [ "$(uname)" = 'Darwin' ]; then
SHELLRC=~/.zshrc
[ -x /opt/homebrew/bin/brew ] || /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
[ -x /opt/homebrew/bin/rg ] || brew install ripgrep
else
SHELLRC=~/.bashrc
[ -x /usr/bin/rg ] || sudo apt-get install -y ripgrep
fi
if [ -z "$(grep /usr/bin/vim "${SHELLRC}")" ]; then
echo 'export EDITOR=/usr/bin/vim' >> "${SHELLRC}"
echo 'export VISUAL=/usr/bin/vim' >> "${SHELLRC}"
fi
if [ -d "$HOME/observe" ]; then
echo 'export PATH="$PATH:$HOME/observe/s"' >> "${SHELLRC}"
fi
| a2559bcc6a432bfb5fa43689f1932763206538fc | [
"Shell"
] | 2 | Shell | jwatte/vim-colors | afecd96e25a5777f746abe81eb24f7371e44d425 | 31fad2729a7ac351359596a98b821a9d80f599ce |
refs/heads/master | <file_sep>source 'https://rubygems.org'
gem 'github-pages'
gem 'jekyll-github-metadata'
gem 'jekyll-relative-links'
gem 'jekyll-seo-tag'
gem 'jekyll-sitemap'
gem 'jekyll-redirect-from'
gem 'jekyll-include-cache'
gem 'jekyll-remote-theme'
gem 'jekyll-paginate'
gem 'jekyll-feed'
gem 'wai-website-plugin'
gem 'liquid', github: 'Shopify/liquid', branch: 'master'
gem 'liquid-c', github: 'Shopify/liquid-c', branch: 'master' | 37b898e347cde5604489b572efc4cc0706028e03 | [
"Ruby"
] | 1 | Ruby | yogayya7/wai-website | 5066a3fbcf22b2a0e0f3fd8fad10b38baadaa6ba | 96b48773f4e47a893d0b04a03a7f91c3f0ffde72 |
refs/heads/master | <file_sep>def add(add1, add2):
return add1 + add2
print(add(1, 2))
def subtract(sub1, sub2):
return sub1 - sub2
print(subtract(4, 1))
def divide(divi1, divi2):
return divi1 / divi2
print(divide(8, 2))
<file_sep>from pymongo import MongoClient
import pprint
import datetime
client = MongoClient('localhost', 27017)
db = client.web335
user = {
"first_name": "Clark",
"last_name": "Kent",
"email": "<EMAIL>",
"employee_id": "04181938",
"date_created": datetime.datetime.utcnow()
}
user_id = db.users.insert_one(user).inserted_id
print(user_id)
pprint.pprint(db.users.find_one({"employee_id": "04181938"}))<file_sep># web-335
Repository for WEB 335
| 98850cf52e08afe2b7226a6162ae0ff0bad6e17c | [
"Markdown",
"Python"
] | 3 | Python | TLBU/web-335 | 982475599d0417e3c0b9fb78b4c7256c7405ff8d | a4e4bffef659505457d4551a73a994517b86928e |
refs/heads/master | <file_sep>package gojava.module8.practice;
public class Rectangle extends Shape {
private int height;
private int width;
public Rectangle(Point startPoint, int height, int width) {
super(startPoint);
this.height = height;
this.width = width;
}
@Override
public double getArea() {
return height * width;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Rectangle{");
sb.append(super.toString());
sb.append(", height=").append(height);
sb.append(", width=").append(width);
sb.append('}');
return sb.toString();
}
}
<file_sep>package gojava.module1.homework.task1;
/**
* Class FirstClass prints a single line of text
*
* @author <NAME>
*/
public class FirstClass {
public static void main(String[] args) {
System.out.println("ะัะน ะฟะตััะธะน ะผะตัะพะด ะฝะฐ java");
}
}
<file_sep>package gojava.module5.homework;
import java.util.ArrayList;
import java.util.List;
public class DaoImpl implements Dao {
private List<Room> myRoomsList = new ArrayList();
@Override
public Room save(Room room) {
System.out.println("Saving " + room);
myRoomsList.add(room);
return room;
}
@Override
public boolean delete(Room room) {
System.out.println("Deleting " + room);
if (myRoomsList.contains(room)) {
myRoomsList.remove(room);
return true;
}
System.out.println("Error! Room not found!");
return false;
}
@Override
public Room update(Room room) {
boolean roomFound = false;
System.out.println("Updating " + room);
Room foundRoom = findById(room.getId());
if (foundRoom != null) {
myRoomsList.remove(foundRoom);
myRoomsList.add(room);
roomFound = true;
}
if (!roomFound) {
System.out.println("Error! Room not found!");
}
return room;
}
@Override
public Room findById(long id) {
System.out.println("Searching for room id: " + id);
for (Room room : myRoomsList) {
if (room.getId() == id) {
return room;
}
}
return null;
}
@Override
public List<Room> getAll() {
return myRoomsList;
}
}
<file_sep># GoJava5
[](https://travis-ci.org/Sheptytskyid/GoJava5)
[](https://coveralls.io/github/Sheptytskyid/JavaCoreFinalProjectGroup6?branch=coveralls_integration)
<file_sep>package gojava.module3.practice;
public class Triangles {
private int x1Coordinate;
private int y1Coordinate;
private int x2Coordinate;
private int y2Coordinate;
private int x3Coordinate;
private int y3Coordinate;
public Triangles(int x1Coordinate, int y1Coordinate, int x2Coordinate, int y2Coordinate, int x3Coordinate,
int y3Coordinate) {
this.x1Coordinate = x1Coordinate;
this.y1Coordinate = y2Coordinate;
this.x2Coordinate = x2Coordinate;
this.y2Coordinate = y2Coordinate;
this.x3Coordinate = x3Coordinate;
this.y3Coordinate = y3Coordinate;
if (Double.compare(area(), 0) == 0) {
System.out.println("points are on the same line");
}
}
public double perimeter() {
double line1 = Math.sqrt(Math.pow(x1Coordinate - x2Coordinate, 2) + Math.pow(y1Coordinate - y2Coordinate, 2));
double line2 = Math.sqrt(Math.pow(x2Coordinate - x3Coordinate, 2) + Math.pow(y2Coordinate - y3Coordinate, 2));
double line3 = Math.sqrt(Math.pow(x3Coordinate - x1Coordinate, 2) + Math.pow(y3Coordinate - y1Coordinate, 2));
double perimeter = line1 + line2 + line3;
return perimeter;
}
double area() {
double line1 = Math.sqrt(Math.pow(x1Coordinate - x2Coordinate, 2) + Math.pow(y1Coordinate - y2Coordinate, 2));
double line2 = Math.sqrt(Math.pow(x2Coordinate - x3Coordinate, 2) + Math.pow(y2Coordinate - y3Coordinate, 2));
double line3 = Math.sqrt(Math.pow(x3Coordinate - x1Coordinate, 2) + Math.pow(y3Coordinate - y1Coordinate, 2));
double s = (line1 + line2 + line3) / 2;
double area = Math.sqrt(s * (s - line1) * (s - line2) * (s - line3));
return area;
}
public int getX1Coordinate() {
return x1Coordinate;
}
public void setX1Coordinate(int x1Coordinate) {
if (Double.compare(area(), 0) != 0) {
System.out.println("points are on the same line");
return;
}
this.x1Coordinate = x1Coordinate;
}
public int getY1Coordinate() {
return y1Coordinate;
}
public void setY1Coordinate(int y1Coordinate) {
if (Double.compare(area(), 0) != 0) {
System.out.println("points are on the same line");
return;
}
this.y1Coordinate = y1Coordinate;
}
public int getX2Coordinate() {
return x2Coordinate;
}
public void setX2Coordinate(int x2Coordinate) {
if (Double.compare(area(), 0) != 0) {
System.out.println("points are on the same line");
return;
}
this.x2Coordinate = x2Coordinate;
}
public int getY2Coordinate() {
return y2Coordinate;
}
public void setY2Coordinate(int y2Coordinate) {
if (Double.compare(area(), 0) != 0) {
System.out.println("points are on the same line");
return;
}
this.y2Coordinate = y2Coordinate;
}
public int getX3Coordinate() {
return x3Coordinate;
}
public void setX3Coordinate(int x3Coordinate) {
if (Double.compare(area(), 0) != 0) {
System.out.println("points are on the same line");
return;
}
this.x3Coordinate = x3Coordinate;
}
public int getY3Coordinate() {
return y3Coordinate;
}
public void setY3Coordinate(int y3Coordinate) {
if (Double.compare(area(), 0) != 0) {
System.out.println("points are on the same line");
return;
}
this.y3Coordinate = y3Coordinate;
}
}
<file_sep>package gojava.module6.homework;
import java.util.Arrays;
public final class ArraysUtils {
public static int sum(int[] array) {
int sum = 0;
for (int arrayElement : array) {
sum += arrayElement;
}
return sum;
}
public static int min(int[] array) {
int min = array[0];
for (int arrayElement : array) {
min = arrayElement < min ? arrayElement : min;
}
return min;
}
public static int max(int[] array) {
int max = array[0];
for (int arrayElement : array) {
max = arrayElement > max ? arrayElement : max;
}
return max;
}
public static int maxPositive(int[] array) {
int max = array[0];
for (int arrayElement : array) {
max = arrayElement > max ? arrayElement : max;
}
if (max < 0) {
throw new ArithmeticException("Error: this array contains no positive elements");
}
return max;
}
public static int multiplication(int[] array) {
int mult = 1;
for (int arrayElement : array) {
mult *= arrayElement;
}
return mult;
}
public static int modulus(int[] array) {
return array[0] % array[array.length - 1];
}
public static int secondLargest(int[] array) {
int[] sortedArray = Arrays.copyOf(array, array.length);
Arrays.sort(sortedArray);
return sortedArray[sortedArray.length - 2]; //return the second largest element in a sorted array
}
public static int[] reverse(int[] array) {
int[] reversedArray = new int[array.length];
for (int i = 0; i < array.length; i++) {
reversedArray[reversedArray.length - 1 - i] = array[i];
}
return reversedArray;
}
public static int[] findEvenElements(int[] array) {
int numberOfEvenElements = 0;
for (int element : array) {
if (element % 2 == 0) {
numberOfEvenElements++;
}
}
int[] arrayOfEvenElements = new int[numberOfEvenElements];
int arrayIndex = 0;
for (int element : array) {
if (element % 2 == 0) {
arrayOfEvenElements[arrayIndex] = element;
arrayIndex++;
}
}
return arrayOfEvenElements;
}
}<file_sep>package gojava.module7.practice;
import java.util.ArrayList;
import java.util.List;
public class ComparingObjects {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 200; i++) {
list.add(i);
}
for (int i = 0; i < 200; i++) {
System.out.print(i);
System.out.println(list.get(i) == Integer.valueOf(i));
}
}
}
<file_sep>package gojava.module10.homework.task4;
import gojava.module10.homework.task2.MyException;
public class ExceptionTestingUtils {
public static void methodF() throws MySecondException {
try {
methodG();
} catch (MyException e) {
throw new MySecondException("My Second Exception", e);
}
}
public static void methodG() throws MyException {
throw new MyException("My Exception");
}
}
<file_sep>Use ArraysDemo.java to run the program and demonstrate its functionality.
The original methods required by the hometask are in Arrays.java.
For demonstration purpose Arrays.java declares two more methods called "caller"
that were not required by the hometask.
<file_sep>package gojava.module5.practice.strings;
public class ReplacerDemo {
public static void main(String[] args) {
System.out.println(Replacer.replaceInString("This is a new string", "i"));
}
}
<file_sep>package gojava.module6.homework;
import java.util.Arrays;
public class ArraysUtilsDemo {
public static void main(String[] args) {
int[] array = {-14, 26, 3, 1, 12, -17, 5, 8, -1, 2};
System.out.println("Initial array:\n" + Arrays.toString(array));
System.out.println("Reversed initial array:\n" + Arrays.toString(ArraysUtils.reverse(array)));
System.out.println("Even elements:\n" + Arrays.toString(ArraysUtils.findEvenElements(array)));
System.out.println("Max element: " + ArraysUtils.max(array));
System.out.println("Min element: " + ArraysUtils.min(array));
System.out.print("MaxPositive element: ");
try {
System.out.println(ArraysUtils.maxPositive(array));
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
System.out.println("Sum of all elements: " + ArraysUtils.sum(array));
System.out.println("Product of all elements: " + ArraysUtils.multiplication(array));
System.out.print("Modulus of the first and the last element: ");
try {
System.out.println(ArraysUtils.modulus(array));
} catch (ArithmeticException e) {
System.out.println("Error: division by zero occurred");
}
System.out.println("Second largest element: " + ArraysUtils.secondLargest(array));
}
}
<file_sep>package gojava.module10.homework.task4;
public class MySecondException extends Exception {
public MySecondException(String message) {
super(message);
}
public MySecondException() {
super();
}
public MySecondException(String message, Throwable cause) {
super(message, cause);
}
}
<file_sep>package gojava.module10.homework.task3;
public class TestClassDemo {
public static void main(String[] args) {
TestClass testClass = null;
try {
testClass.testMethod();
} catch (NullPointerException e) {
System.out.println("Caught exception: " + e);
}
}
}
<file_sep>package gojava.module5.practice;
import java.util.UUID;
public class Main {
public static void main(String[] args) {
User user1 = new User(UUID.randomUUID().getMostSignificantBits(), "User1");
user1.setConnection1(Connection.getInstance());
}
}
<file_sep>package gojava.module6.practice.task2;
public final class Triangle extends View {
private boolean isShown = false;
@Override
public void show() {
if (!isShown) {
System.out.println("Showing Triangle");
isShown = true;
} else {
System.out.println("Triangle already shown");
}
}
@Override
public void hide() {
if (isShown) {
System.out.println("Hiding Triangle");
isShown = false;
} else {
System.out.println("Triangle already hidden");
}
}
}
<file_sep>package gojava.module7.homework;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
public class Task2 {
public static void main(String[] args) {
List<User> users = new ArrayList<>();
users.add(new User(getPositiveRandId(), "Denys", "Sheptytskyi", "Kyiv", 1000));
users.add(new User(getPositiveRandId(), "Roman", "Syroyizhka", "Lviv", 1100));
users.add(new User(getPositiveRandId(), "Vasyl", "Kozak", "Ternopil", 1200));
users.add(new User(getPositiveRandId(), "Orest", "Melnyk", "Kyiv", 1300));
users.add(new User(getPositiveRandId(), "Dmytro", "Kozak", "Lviv", 1400));
users.add(new User(getPositiveRandId(), "Petro", "Fedus", "Ternopil", 1500));
users.add(new User(getPositiveRandId(), "Ivan", "Fedus", "Kyiv", 1600));
users.add(new User(getPositiveRandId(), "Roman", "Kulish", "Lviv", 1700));
users.add(new User(getPositiveRandId(), "Sergii", "Kryvonis", "Ternopil", 1800));
users.add(new User(getPositiveRandId(), "Roman", "Demchuk", "Kyiv", 1900));
List<Order> ordersList = new ArrayList<>();
ordersList.add(new Order(getPositiveRandId(), 1000, Currency.UAH, "Pen", "Office Supplies", users.get(0)));
ordersList.add(new Order(getPositiveRandId(), 1500, Currency.USD, "Ruler", "Office Supplies", users.get(1)));
ordersList.add(new Order(getPositiveRandId(), 1000, Currency.UAH, "Pencil", "Office Supplies", users.get(2)));
ordersList.add(new Order(getPositiveRandId(), 1000, Currency.USD, "Notebook", "Office Supplies", users.get(3)));
ordersList.add(new Order(getPositiveRandId(), 1000, Currency.UAH, "Ball", "Sport Store", users.get(4)));
ordersList.add(new Order(getPositiveRandId(), 1800, Currency.USD, "Snowboard", "Sport Store", users.get(5)));
ordersList.add(new Order(Integer.MAX_VALUE, 1200, Currency.UAH, "Skis", "Sport Store", users.get(6)));
ordersList.add(new Order(getPositiveRandId(), 1700, Currency.UAH, "Pen", "Office Supplies", users.get(7)));
ordersList.add(new Order(getPositiveRandId(), 1700, Currency.USD, "Pencil", "Office Supplies", users.get(8)));
ordersList.add(new Order(Integer.MAX_VALUE, 1200, Currency.UAH, "Skis", "Sport Store", users.get(6)));
System.out.println("Initial list:\n" + ordersList + "\n");
//reversed sorting by order prices
ordersList.sort(Comparator.comparing(Order::getPrice).reversed());
System.out.println("Sorted by prices in descending order:\n" + ordersList + "\n");
//sorting by order prices and by user cities
ordersList.sort(Comparator.comparing(Order::getPrice)
.thenComparing(order -> order.getUser().getCity()));
System.out.println("Sorted by prices and user cities:\n" + ordersList + "\n");
//sorting by Order itemName AND ShopIdentificator AND User city
ordersList.sort(Comparator.comparing(Order::getItemName)
.thenComparing(Order::getShopIdentificator)
.thenComparing(order -> order.getUser().getCity())
);
System.out.println("Sorted by item, shop ID and user city:\n" + ordersList + "\n");
//remove duplicates
List<Order> uniqueOrders = ordersList.stream().distinct().collect(Collectors.toList());
System.out.println("Unique orders:\n" + uniqueOrders + "\n");
//remove ordersList with price below 1500
List<Order> highPriceOrders = ordersList.stream()
.filter(order -> order.getPrice() > 1500)
.collect(Collectors.toList());
System.out.println("Orders with prices above 1500:\n" + highPriceOrders + "\n");
//split ordersList by currencies
Map<Currency, List<Order>> ordersByCurrencies = ordersList.stream()
.collect(Collectors.groupingBy(Order::getCurrency));
System.out.println("Orders split by currencies:\n" + ordersByCurrencies + "\n");
//split ordersList by cities
Map<String, List<Order>> ordersByCities = ordersList.stream()
.collect(Collectors.groupingBy(order -> order.getUser().getCity()));
System.out.println("Orders split by user cities:\n" + ordersByCities + "\n");
}
public static long getPositiveRandId() {
long id = UUID.randomUUID().getMostSignificantBits();
if (id < 0) {
id = getPositiveRandId();
}
return id;
}
}
<file_sep>package gojava.module3.homework.task3;
import java.util.Date;
public class Solution {
public static void main(String[] args) {
Course Java1 = new Course(new Date(), "Java 1");
Course Java2 = new Course(35, "Java 2", "<NAME>");
Course Java3 = new Course(40, "Java 3", "<NAME>");
Course Java4 = new Course(new Date(), "Java 4");
Course QA1 = new Course(15, "QA 1", "<NAME>");
Course[] coursesTakenByClintonH = {Java1, QA1};
Course[] coursesTakenByLeghornF = {Java2, Java3, QA1};
Course[] coursesTakenByRitchieD = {Java4, QA1};
Student Sheptytskyid = new Student("Denys", "Sheptytskyi", 5);
Student ClintonH = new Student("Clinton", coursesTakenByClintonH);
CollegeStudent GonzalesS = new CollegeStudent("Speedy", "Gonzales", 2);
CollegeStudent LeghornF = new CollegeStudent("Leghorn", coursesTakenByLeghornF);
CollegeStudent PorkyP = new CollegeStudent("Pig", "Porky", 4, "GoIT", 10, 65535);
SpecialStudent GoslingJ = new SpecialStudent("James", "Gosling", 5);
SpecialStudent RitchieD = new SpecialStudent("Ritchie", coursesTakenByRitchieD);
SpecialStudent BhattA = new SpecialStudent("Ajay", "Bjatt", 5, 123456789);
System.out.println("Sheptytskyi's group is: " + Sheptytskyid.getGroup());
BhattA.setEmail("<EMAIL>");
System.out.println("Bhatt's email is: " + BhattA.getEmail());
System.out.println("Java 1 course start date is: " + Java1.getStartDate());
}
}
<file_sep>package gojava.module8.practice;
public class UseShapes {
public static void main(String[] args) {
Point startPoint = new Point(6, 7);
Rectangle rectangle1 = new Rectangle(startPoint, 14, 7);
Rectangle rectangle2 = new Rectangle(startPoint, 1, 5);
Rectangle rectangle3 = new Rectangle(startPoint, 4, 4);
Square square = new Square(startPoint, 14);
Circle circle = new Circle(startPoint, 14);
Group<Shape> shapes = new Group<>();
shapes.add(rectangle1);
shapes.add(rectangle2);
shapes.add(rectangle3);
shapes.add(circle);
shapes.getAll().forEach(System.out::println);
}
}
<file_sep>package gojava.module10.practice.task1;
public class Main {
public static void main(String[] args) {
Integer numerator = new Integer(4);
Number denominator = 0;
try {
Integer result = numerator.intValue() / denominator.intValue();
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>package gojava.module6.practice.task1;
import java.util.Arrays;
import java.util.Random;
public class RandomArray {
public static void main(String[] args) {
int lowerBound = 10;
int upperBound = 50;
int[] randomArray = new int[20];
for (int i = 0; i < randomArray.length; i++) {
randomArray[i] = getRandomInt(lowerBound, upperBound);
}
Math.random();
System.out.println(Arrays.toString(randomArray));
}
private static int getRandomInt(int lowerBound, int upperBound) {
Random rand = new Random();
return rand.nextInt(upperBound - lowerBound + 1) + lowerBound;
}
}
<file_sep>package gojava.module7.practice;
import java.util.Comparator;
public class UsersComparator implements Comparator<User> {
@Override
public int compare(User o1, User o2) {
if (o1.getFirstName().equals(o2.getFirstName())) {
return o1.getLastName().compareTo(o2.getLastName());
}
return o1.getFirstName().compareTo(o2.getFirstName());
}
}
<file_sep>package gojava.module4.homework;
import java.util.UUID;
public class Main {
public static void main(String[] args) {
ChinaBank chinBan = new ChinaBank(getPositiveLongRandomId(), "China", Currency.USD,
1000, 112, 5, 500000, "ChinBan");
EuBank raiffeisenBank = new EuBank(getPositiveLongRandomId(), "Austria", Currency.EUR,
800, 115, 4, 400000, "Raiffeisen Bank");
UsBank bankOfAmerica = new UsBank(getPositiveLongRandomId(), "US", Currency.USD,
600, 119, 3, 300000, "Bank Of America");
User[] users = new User[6];
users[0] = new User(getPositiveLongRandomId(), "<NAME>", 2000.0, 106,
"LLC \"AMC \"OTP Capital\"", 100, raiffeisenBank);
users[1] = new User(getPositiveLongRandomId(), "<NAME>", 5000.0, 12,
"LLC \"Amigo\"", 50, raiffeisenBank);
users[2] = new User(getPositiveLongRandomId(), "<NAME>", 1000.0, 24,
"LLC \"New Technologies\"", 180, bankOfAmerica);
users[3] = new User(getPositiveLongRandomId(), "<NAME>", 3000.0, 18,
"LLC \"Open Source\"", 160, bankOfAmerica);
users[4] = new User(getPositiveLongRandomId(), "<NAME>", 50.0, 2,
"LLC \"Vesta\"", 109, chinBan);
users[5] = new User(getPositiveLongRandomId(), "<NAME>", 30.0, 10,
"LLC \"Office Solutions\"", 155, chinBan);
BankSystemImpl system1 = new BankSystemImpl();
System.out.println("Users' objects:");
for (User user : users) {
System.out.println(user);
System.out.println("\n");
}
System.out.println("============================================\n");
for (User user : users) {
int fundingAmount = 200;
int transferAmount = 1000;
int withdrawAmount = 2000;
System.out.println("Performing operations with user " + user.getName());
System.out.println("Funding " + user.getBank().getCurrency() + " " + fundingAmount);
system1.fundUser(user, fundingAmount);
System.out.println("Transferring " + user.getBank().getCurrency() + " " + transferAmount);
system1.transferMoney(user, users[4], transferAmount);
System.out.println("Paying Salary " + user.getBank().getCurrency() + " " + user.getSalary());
system1.paySalary(user);
System.out.println("Withdrawing " + user.getBank().getCurrency() + " " + withdrawAmount);
system1.withdrawOfUser(user, withdrawAmount);
System.out.println("Balance: " + user.getBank().getCurrency() + " " + user.getBalance());
System.out.println("\n");
}
}
public static long getPositiveLongRandomId() {
long id = UUID.randomUUID().getMostSignificantBits();
if (id < 0) {
id = getPositiveLongRandomId();
}
return id;
}
}
<file_sep>package gojava.module5.homework;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class TripAdvisorApi extends AbstractApi {
private List<Room> rooms = new ArrayList<>();
public TripAdvisorApi() {
rooms.add(new Room(getPositiveLongRandomId(), 850, 2, LocalDate.of(2001, 11, 1), "Rubin", "Truskavets"));
rooms.add(new Room(getPositiveLongRandomId(), 950, 3, LocalDate.of(2001, 11, 3), "Cristal", "Truskavets"));
rooms.add(new Room(getPositiveLongRandomId(), 1400, 3, LocalDate.of(2001, 11, 14), "Ibis", "Kyiv"));
rooms.add(new Room(getPositiveLongRandomId(), 1500, 4, LocalDate.of(2001, 11, 16), "Intercontinental", "Kyiv"));
rooms.add(new Room(getPositiveLongRandomId(), 1600, 4, LocalDate.of(2001, 11, 18), "Mir", "Kyiv"));
}
@Override
public List<Room> getAll() {
return rooms;
}
}
<file_sep>package gojava.module6.homework;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
User[] users = {
new User(1, "Roman", "Malysh", 1200, 1000),
new User(1, "Roman", "Malysh", 1200, 1000),
new User(User.getPositiveLongRandomId(), "Ivan", "Klym", 900, 100),
new User(User.getPositiveLongRandomId(), "Petro", "Sivach", 1000, 700),
new User(2, "Vasyl", "Kozak", 200, 1300),
new User(User.getPositiveLongRandomId(), "Orest", "Bobak", 1000, 1000),
new User(2, "Vasyl", "Kozak", 200, 1300),
new User(2, "Vasyl", "Kozak", 200, 1300),
};
System.out.println("Users' IDs:\n" + Arrays.toString(UserUtils.getUsersId(users)));
User[] uniqueUsers = UserUtils.uniqueUsers(users);
System.out.println("Unique users:\n" + Arrays.toString(uniqueUsers));
System.out.println("Users with balance of 1000:\n"
+ Arrays.toString(UserUtils.usersWithConditionalBalance(uniqueUsers, 1000)));
System.out.println("Paying salaries...\n" + Arrays.toString(UserUtils.paySalaryToUsers(uniqueUsers)));
}
}
<file_sep>package gojava.module2.homework.task2;
public class Bank {
private double balance;
private String clientName;
public Bank(double balance, String clientName) {
this.balance = balance;
this.clientName = clientName;
}
void withdraw(double withdrawal) {
System.out.println(clientName);
if (withdrawal * 1.05 <= balance) { //checks if balance is sufficient for withdrawal + fee
System.out.println("OK " + (withdrawal * 0.05) + " " + (balance -= withdrawal * 1.05) + "\n");
} else {
System.out.println("NO\n");
}
}
}<file_sep>package gojava.module11.practice;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.stream.Collectors;
public class ReplaceWordsInFile {
public static void main(String[] args) {
URL url = null;
try {
url = new URL("http://google.com");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try (BufferedReader urlReader = new BufferedReader(new InputStreamReader(url.openStream()));
BufferedWriter bufferedFileWriter = new BufferedWriter(new FileWriter("google.html"))) {
bufferedFileWriter.write(urlReader.lines().map(p -> p.replaceAll("google", "yandex").replaceAll("Google",
"Yandex")).collect(Collectors
.joining()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>package gojava.module5.practice;
public class User {
private long id;
private String name;
private Connection connection1;
public User(long id, String name) {
this.id = id;
this.name = name;
}
public void setConnection1(Connection connection1) {
this.connection1 = connection1;
}
}
<file_sep>package gojava.module2.homework.task3;
public class Clients {
private static int[] clientBalances = {1200, 250, 2000, 500, 3200};
private static String[] clientNames = {"Jane", "Ann", "Jack", "Oww", "Lane"};
public static void withdraw(String clientName, double withdrawal) {
int clientIndex = 0;
while (!clientName.equals(clientNames[clientIndex])) {
clientIndex++;
if (clientIndex == clientNames.length) {
System.out.println(clientName + ": Name not found\n");
return;
}
}
if (withdrawal * 1.05 <= clientBalances[clientIndex]) {
System.out.println(clientName + " " + withdrawal + " "
+ (clientBalances[clientIndex] -= withdrawal * 1.05));
System.out.println();
} else {
System.out.println(clientNames[clientIndex] + " NO\n");
}
}
}
<file_sep>Use BankDemo.java to run the program and demonstrate its functionality
original method required by the hometask is in Bank.java
<file_sep>package gojava.module8.practice;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Group<T extends Shape> {
private List<T> shapes = new ArrayList<>();
public void add(T shape) {
shapes.add(shape);
}
public List<T> getAll() {
return shapes;
}
public double getSumArea() {
double sum = 0;
for (T shape : shapes) {
sum += shape.getArea();
}
return new BigDecimal(sum).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/*public Map<Class<? extends Shape>, Group<T>> shapesSeparatedByType() {
Map<Class<? extends Shape>, Group<T>> map = new HashMap<>();
for (T shape : shapes) {
Class<? extends Shape> aClass = shape.getClass();
if(map.get(aClass) == null) {
map.put(aClass, new Group());
map.get(aClass).add(shape);
}
}
}*/
/*public Group<T> shapesSeparatedByType(Class<T> clazz) {
}*/
}
<file_sep>package gojava.module5.homework;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class AbstractApiTest {
@Test
public void idIsGenerated() {
assertTrue(AbstractApi.getPositiveLongRandomId() > 0);
}
}<file_sep>package gojava.module5.homework;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public abstract class AbstractApi implements Api {
@Override
public List<Room> findRooms(int price, int persons, String city, String hotel) {
List<Room> listOfRoomsFound = new ArrayList<>();
for (Room room : getAll()) {
if (room.getPrice() == price
&& room.getPersons() == persons
&& room.getCityName().equals(city)
&& room.getHotelName().equals(hotel)) {
listOfRoomsFound.add(room);
}
}
return listOfRoomsFound;
}
public static long getPositiveLongRandomId() {
long id = UUID.randomUUID().getMostSignificantBits();
if (id < 0) {
id = getPositiveLongRandomId();
}
return id;
}
}
<file_sep>package gojava.module5.homework;
import java.util.ArrayList;
import java.util.List;
public class Controller {
private List<Api> apis = new ArrayList<>();
private DaoImpl dao = new DaoImpl();
public Controller() {
apis.add(new BookingComApi());
apis.add(new GoogleApi());
apis.add(new TripAdvisorApi());
}
public List<Room> requestRooms(int price, int persons, String city, String hotel) {
System.out.println("Requesting room...");
List<Room> listOfRoomsRequested = new ArrayList();
for (Api api : apis) {
listOfRoomsRequested.addAll(api.findRooms(price, persons, city, hotel));
}
System.out.println(listOfRoomsRequested.size()
+ (listOfRoomsRequested.size() == 1 ? " room " : " rooms ")
+ "found!");
return listOfRoomsRequested;
}
public List<Room> check(Api api1, Api api2) {
System.out.println("Checking for equal rooms in " + api1.getClass().getSimpleName()
+ " and " + api2.getClass().getSimpleName());
List<Room> listOfEqualRooms = new ArrayList();
for (Room room1 : api1.getAll()) {
for (Room room2 : api2.getAll()) {
if (room1.equals(room2)) {
listOfEqualRooms.add(room1);
listOfEqualRooms.add(room2);
}
}
}
System.out.println(listOfEqualRooms.size() + " equal rooms found!");
return listOfEqualRooms;
}
public List<Api> getApis() {
return apis;
}
public DaoImpl getDao() {
return dao;
}
}
<file_sep>package gojava.module2.practice;
import java.util.Arrays;
public class CountArray {
static int[] array = {1, 5, 1, 6, 8, 1, 5, 2, 1, 11};
public static void main(String[] args) {
printNumberOfTimes(countNumberOfTimes(1));
printNumberOfTimes(countNumberOfTimes(11));
printNumberOfTimes(countNumberOfTimes(0));
System.out.println(Arrays.toString(bubbleSortArray(array)));
}
private static int countNumberOfTimes(int item) {
int numberOfTimes = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
numberOfTimes++;
}
}
return numberOfTimes;
}
static void printNumberOfTimes(int item) {
if (item == 0) {
System.out.println("NO");
} else if (item == 1) {
System.out.println("YES");
} else {
System.out.println(item);
}
}
static int[] bubbleSortArray(int[] array) {
for (int a = 1; a < array.length; a++) {
for (int b = array.length - 1; b >= a; b--) {
if (array[b - 1] > array[b]) {
int t = array[b - 1];
array[b - 1] = array[b];
array[b] = t;
}
}
}
return array;
}
}
<file_sep>package gojava.module10.homework.task3;
public class TestClass {
public void testMethod() {
System.out.println("Inside testMethod");
}
}
<file_sep>package gojava.module2.homework.task4;
class Clients2 {
private static int[] clientBalances = {1200, 250, 2000, 500, 3200};
private static String[] clientNames = {"Jane", "Ann", "Jack", "Oww", "Lane"};
static void fund(String clientName, double sum) {
int clientIndex = 0;
while (!clientName.equals(clientNames[clientIndex])) {
clientIndex++;
if (clientIndex == clientNames.length) {
System.out.println(clientName + ": Name not found\n");
return;
}
}
System.out.println(clientName + " "
+ (clientBalances[clientIndex] += sum));
System.out.println();
}
}
<file_sep>package gojava.module3.homework.task2;
public class Demo {
public static void main(String[] args) {
Integer a = 10;
Integer b = 20;
System.out.println(Arithmetic.add(a, b));
System.out.println(Adder.check(a, b));
}
}
<file_sep>package gojava.module10.homework.task4;
public class Main {
public static void main(String[] args) {
try {
ExceptionTestingUtils.methodF();
} catch (MySecondException e) {
System.out.println("Caught exception: " + e.getMessage());
System.out.println("caused by: " + e.getCause().getMessage());
}
}
}
<file_sep>Use Clients2Demo.java to run the program and demonstrate its functionality
original method required by the hometask is in Clients2.java<file_sep>package gojava.module10.practice.task2;
public interface PersonDao {
public Person save(Person person) throws Exception;
public Person findByEmail(Person person);
}
| 43cb9c718e016441ddacbbeb92ff4b8e2c95e967 | [
"Markdown",
"Java",
"Text"
] | 40 | Java | Sheptytskyid/GoJava5 | 29231d58e4a190f45e0fb398c584a313572fe637 | c6a40a792b5fd1de970454107407d4eca8cac036 |
refs/heads/master | <repo_name>xuyue1231/MG5-heavy-Higgs<file_sep>/LHC_HH_2lep_rw/SubProcesses/P2_qq_zhh_z_qq_hh_llqq/coloramps.inc
LOGICAL ICOLAMP(1,1,12)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,12),I=1,1)/.TRUE./
<file_sep>/PROCNLO_HC_NLO_X0_UFO_0_1/Events/run_02/alllogs_0.html
<HTML><BODY>
<font face="courier" size=2><a name=/P0_uux_zx0_zepemz_no_a/GF1></a>
<font color="red">
<br>LOG file for integration channel /P0_uux_zx0_zepemz_no_a/GF1, 0 <br></font>
<PRE>
===============================================================
INFO: MadFKS read these parameters from FKS_params.dat
===============================================================
> IRPoleCheckThreshold = 1.0000000000000001E-005
> PrecisionVirtualAtRunTime = 1.0000000000000000E-003
> NHelForMCoverHels = 4
> VirtualFraction = 1.0000000000000000
> MinVirtualFraction = 5.0000000000000001E-003
===============================================================
A PDF is used, so alpha_s(MZ) is going to be modified
Old value of alpha_s from param_card: 0.11799999999999999
****************************************
NNPDFDriver version 1.0.3
Grid: NNPDF23nlo_as_0119_qed_mem0.grid
****************************************
New value of alpha_s from PDF nn23nlo: 0.11899999999999999
*****************************************************
* MadGraph/MadEvent *
* -------------------------------- *
* http://madgraph.hep.uiuc.edu *
* http://madgraph.phys.ucl.ac.be *
* http://madgraph.roma2.infn.it *
* -------------------------------- *
* *
* PARAMETER AND COUPLING VALUES *
* *
*****************************************************
External Params
---------------------------------
MU_R = 91.188000000000002
aEWM1 = 132.50700000000001
mdl_Gf = 1.1663900000000000E-005
aS = 0.11799999999999999
mdl_ymb = 4.7000000000000002
mdl_ymt = 173.00000000000000
mdl_ymtau = 1.7769999999999999
mdl_MT = 173.00000000000000
mdl_MB = 4.7000000000000002
mdl_MZ = 91.188000000000002
mdl_MTA = 1.7769999999999999
mdl_WT = 1.4915000000000000
mdl_WZ = 2.4414039999999999
mdl_WW = 2.0476000000000001
mdl_MX0 = 300.00000000000000
mdl_WX0 = 1.0604700000000000
mdl_Lambda = 5000.0000000000000
mdl_cosa = 1.0000000000000000
mdl_kSM = 5.0000000000000003E-002
mdl_kHtt = 0.0000000000000000
mdl_kAtt = 0.0000000000000000
mdl_kHbb = 0.0000000000000000
mdl_kAbb = 0.0000000000000000
mdl_kHll = 0.0000000000000000
mdl_kAll = 0.0000000000000000
mdl_kHaa = 0.0000000000000000
mdl_kAaa = 0.0000000000000000
mdl_kHza = 0.0000000000000000
mdl_kAza = 0.0000000000000000
mdl_kHzz = 8.1561199999999996
mdl_kAzz = 0.0000000000000000
mdl_kHww = 10.496200000000000
mdl_kAww = 0.0000000000000000
mdl_kHda = 0.0000000000000000
mdl_kHdz = 0.0000000000000000
mdl_kHdwR = 0.0000000000000000
mdl_kHdwI = 0.0000000000000000
Internal Params
---------------------------------
mdl_CKM11 = 1.0000000000000000
mdl_conjg__CKM3x3 = 1.0000000000000000
mdl_conjg__CKM11 = 1.0000000000000000
mdl_lhv = 1.0000000000000000
mdl_CKM3x3 = 1.0000000000000000
mdl_conjg__CKM33 = 1.0000000000000000
mdl_Ncol = 3.0000000000000000
mdl_CA = 3.0000000000000000
mdl_TF = 0.50000000000000000
mdl_CF = 1.3333333333333333
mdl_complexi = ( 0.0000000000000000 , 1.0000000000000000 )
mdl_MZ__exp__2 = 8315.2513440000002
mdl_MZ__exp__4 = 69143404.913893804
mdl_sqrt__2 = 1.4142135623730951
mdl_MX0__exp__2 = 90000.000000000000
mdl_cosa__exp__2 = 1.0000000000000000
mdl_sina = 0.0000000000000000
mdl_kHdw = ( 0.0000000000000000 , 0.0000000000000000 )
mdl_nb__2__exp__0_75 = 1.6817928305074290
mdl_Ncol__exp__2 = 9.0000000000000000
mdl_MB__exp__2 = 22.090000000000003
mdl_MT__exp__2 = 29929.000000000000
mdl_conjg__kHdw = ( 0.0000000000000000 , -0.0000000000000000 )
mdl_aEW = 7.5467711139788835E-003
mdl_MW = 80.419002445756163
mdl_sqrt__aEW = 8.6872153846781555E-002
mdl_ee = 0.30795376724436879
mdl_MW__exp__2 = 6467.2159543705357
mdl_sw2 = 0.22224648578577766
mdl_cw = 0.88190334743339216
mdl_sqrt__sw2 = 0.47143025548407230
mdl_sw = 0.47143025548407230
mdl_g1 = 0.34919219678733299
mdl_gw = 0.65323293034757990
mdl_vev = 246.21845810181637
mdl_vev__exp__2 = 60623.529110035903
mdl_lam = 0.74228605065735920
mdl_yb = 2.6995554250465490E-002
mdl_yt = 0.99366614581500623
mdl_ytau = 1.0206617000654717E-002
mdl_muH = 212.13203435596427
mdl_AxialZUp = -0.18517701861793787
mdl_AxialZDown = 0.18517701861793787
mdl_VectorZUp = 7.5430507588273299E-002
mdl_VectorZDown = -0.13030376310310560
mdl_VectorAUp = 0.20530251149624587
mdl_VectorADown = -0.10265125574812294
mdl_VectorWmDxU = 0.23095271737156670
mdl_AxialWmDxU = -0.23095271737156670
mdl_VectorWpUxD = 0.23095271737156670
mdl_AxialWpUxD = -0.23095271737156670
mdl_I1x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_I2x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I3x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I4x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_Vector_tbGp = (-0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGp = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_Vector_tbGm = ( 0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGm = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_ee__exp__2 = 9.4835522759998875E-002
mdl_gAaa = 1.3008566310666950E-005
mdl_cw__exp__2 = 0.77775351421422245
mdl_gAza = 4.7794971072590281E-006
mdl_gHaa = 2.5475109025056106E-005
mdl_gHza = 3.9182129211851395E-005
mdl_gw__exp__2 = 0.42671326129048615
mdl_sw__exp__2 = 0.22224648578577769
Internal Params evaluated point by point
----------------------------------------
mdl_sqrt__aS = 0.34351128074635334
mdl_G__exp__2 = 1.4828317324943823
mdl_G__exp__4 = 2.1987899468922913
mdl_R2MixedFactor_FIN_ = -2.5040377713124864E-002
mdl_GWcft_UV_b_1EPS_ = -3.1300472141406080E-003
mdl_GWcft_UV_t_1EPS_ = -3.1300472141406080E-003
mdl_bWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_tWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_G__exp__3 = 1.8056676068262196
mdl_MU_R__exp__2 = 8315.2513440000002
mdl_GWcft_UV_b_FIN_ = -1.8563438626678915E-002
mdl_GWcft_UV_t_FIN_ = 4.0087659331150384E-003
mdl_bWcft_UV_FIN_ = -0.13642100947319838
mdl_tWcft_UV_FIN_ = -9.8778211443463623E-004
mdl_gAgg = 7.6274879753643885E-005
mdl_gHgg = -5.0849919835762592E-005
Couplings of HC_NLO_X0_UFO
---------------------------------
R2_UUZ_V2 = -0.00000E+00 -0.72127E-02
R2_UUZ_V5 = 0.00000E+00 0.68702E-03
GC_5 = 0.00000E+00 0.12177E+01
GC_3007a = -0.00000E+00 -0.00000E+00
GC_3007h2 = -0.00000E+00 -0.16312E-02
GC_3007h3 = -0.00000E+00 -0.00000E+00
GC_22 = 0.00000E+00 0.28804E+00
GC_23 = -0.00000E+00 -0.27437E-01
GC_24 = 0.00000E+00 0.82310E-01
GC_3007h1 = 0.00000E+00 0.33772E+01
Collider parameters:
--------------------
Running at P P machine @ 13000.000000000000 GeV
PDF set = nn23nlo
alpha_s(Mz)= 0.1190 running at 2 loops.
alpha_s(Mz)= 0.1190 running at 2 loops.
Renormalization scale set on event-by-event basis
Factorization scale set on event-by-event basis
Diagram information for clustering has been set-up for nFKSprocess 1
Diagram information for clustering has been set-up for nFKSprocess 2
Diagram information for clustering has been set-up for nFKSprocess 3
Diagram information for clustering has been set-up for nFKSprocess 4
getting user params
Enter number of events and iterations:
Number of events and iterations -1 12
Enter desired fractional accuracy:
Desired fractional accuracy: 2.9999999999999999E-002
Enter alpha, beta for G_soft
Enter alpha<0 to set G_soft=1 (no ME soft)
for G_soft: alpha= 1.0000000000000000 , beta= -0.10000000000000001
Enter alpha, beta for G_azi
Enter alpha>0 to set G_azi=0 (no azi corr)
for G_azi: alpha= -1.0000000000000000 , beta= -0.10000000000000001
Doing the S and H events together
Suppress amplitude (0 no, 1 yes)?
Using suppressed amplitude.
Exact helicity sum (0 yes, n = number/event)?
Do MC over helicities for the virtuals
Enter Configuration Number:
Running Configuration Number: 1
Enter running mode for MINT:
0 to set-up grids, 1 to integrate, 2 to generate events
MINT running mode: 0
Set the three folding parameters for MINT
xi_i, phi_i, y_ij
1 1 1
'all ', 'born', 'real', 'virt', 'novi' or 'grid'?
Enter 'born0' or 'virt0' to perform
a pure n-body integration (no S functions)
doing the all of this channel
Normal integration (Sfunction != 1)
about to integrate 13 -1 12 1
imode is 0
channel 1 : 1 T 0 0 0.1000E+01 0.0000E+00 0.1000E+01
+----------------------------------------------------------------+
| |
| Ninja - version 1.2.0 |
| |
| Author: <NAME> |
| |
| Based on: |
| |
| <NAME>, <NAME> and <NAME>, |
| "Integrand reduction of one-loop scattering amplitudes |
| through Laurent series expansion," |
| JHEP 1206 (2012) 095 [arXiv:1203.0291 [hep-ph]]. |
| |
| <NAME>, |
| "Ninja: Automated Integrand Reduction via Laurent |
| Expansion for One-Loop Amplitudes," |
| Comput.Phys.Commun. 185 (2014) [arXiv:1403.1229 [hep-ph]] |
| |
+----------------------------------------------------------------+
------- iteration 1
Update # PS points (even): 1040 --> 1040
Using random seed offsets: 1 , 1 , 0
with seed 34
Ranmar initialization seeds 13168 9409
Total number of FKS directories is 4
FKS process map (sum= 3 ) :
1 --> 2 : 1 3
2 --> 2 : 2 4
================================
process combination map (specified per FKS dir):
1 map 1 2 3 4
1 inv. map 1 2 3 4
2 map 1 2 3 4
2 inv. map 1 2 3 4
3 map 1 2 3 4
3 inv. map 1 2 3 4
4 map 1 2 3 4
4 inv. map 1 2 3 4
================================
tau_min 1 1 : 0.18238E+03 -- 0.39119E+03
tau_min 2 1 : 0.18238E+03 -- 0.39119E+03
tau_min 3 1 : 0.18238E+03 -- 0.39119E+03
tau_min 4 1 : 0.18238E+03 -- 0.39119E+03
bpower is 0.0000000000000000
Scale values (may change event by event):
muR, muR_reference: 0.173261D+03 0.173261D+03 1.00
muF1, muF1_reference: 0.173261D+03 0.173261D+03 1.00
muF2, muF2_reference: 0.173261D+03 0.173261D+03 1.00
QES, QES_reference: 0.173261D+03 0.173261D+03 1.00
muR_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF1_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF2_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
QES_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
alpha_s= 0.10843325855174672
alpha_s value used for the virtuals is (for the first PS point): 0.10843325855174672
==========================================================================================
{ }
{ [32m [0m }
{ [32m ,, [0m }
{ [32m`7MMM. ,MMF' `7MM `7MMF' [0m }
{ [32m MMMb dPMM MM MM [0m }
{ [32m M YM ,M MM ,6"Yb. ,M""bMM MM ,pW"Wq. ,pW"Wq.`7MMpdMAo. [0m }
{ [32m M Mb M' MM 8) MM ,AP MM MM 6W' `Wb 6W' `Wb MM `Wb [0m }
{ [32m M YM.P' MM ,pm9MM 8MI MM MM , 8M M8 8M M8 MM M8 [0m }
{ [32m M `YM' MM 8M MM `Mb MM MM ,M YA. ,A9 YA. ,A9 MM ,AP [0m }
{ [32m.JML. `' .JMML.`Moo9^Yo.`Wbmd"MML..JMMmmmmMMM `Ybmd9' `Ybmd9' MMbmmd' [0m }
{ [32m MM [0m }
{ [32m .JMML. [0m }
{ [32m[0mv2.6.6 (2018-06-28), Ref: arXiv:1103.0621v2, arXiv:1405.0301[32m [0m }
{ [32m [0m }
{ }
==========================================================================================
===============================================================
INFO: MadLoop read these parameters from ../MadLoop5_resources/MadLoopParams.dat
===============================================================
> MLReductionLib = 6|7|1
> CTModeRun = -1
> MLStabThres = 1.0000000000000000E-003
> NRotations_DP = 0
> NRotations_QP = 0
> CTStabThres = 1.0000000000000000E-002
> CTLoopLibrary = 2
> CTModeInit = 1
> CheckCycle = 3
> MaxAttempts = 10
> UseLoopFilter = F
> HelicityFilterLevel = 2
> ImprovePSPoint = 2
> DoubleCheckHelicityFilter = T
> LoopInitStartOver = F
> HelInitStartOver = F
> ZeroThres = 1.0000000000000001E-009
> OSThres = 1.0000000000000000E-008
> WriteOutFilters = T
> UseQPIntegrandForNinja = T
> UseQPIntegrandForCutTools = T
> IREGIMODE = 2
> IREGIRECY = T
> COLLIERMode = 1
> COLLIERRequiredAccuracy = 1.0000000000000000E-008
> COLLIERCanOutput = F
> COLLIERComputeUVpoles = T
> COLLIERComputeIRpoles = T
> COLLIERGlobalCache = -1
> COLLIERUseCacheForPoles = F
> COLLIERUseInternalStabilityTest = T
===============================================================
------------------------------------------------------------------------
| You are using CutTools - Version 1.9.3 |
| Authors: <NAME>, <NAME>, <NAME> |
| Published in JHEP 0803:042,2008 |
| http://www.ugr.es/~pittau/CutTools |
| |
| Compiler with 34 significant digits detetected |
----------------------------------------------------------------------
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
---- POLES CANCELLED ----
ABS integral = 0.4630E-03 +/- 0.3648E-04 ( 7.879 %)
Integral = 0.4328E-03 +/- 0.3571E-04 ( 8.252 %)
Virtual = 0.3071E-04 +/- 0.2583E-05 ( 8.409 %)
Virtual ratio = 0.5251E+01 +/- 0.1555E-01 ( 0.296 %)
ABS virtual = 0.3072E-04 +/- 0.2583E-05 ( 8.408 %)
Born*ao2pi = 0.6065E-05 +/- 0.5112E-06 ( 8.429 %)
Chi^2 per d.o.f. 0.0000E+00
accumulated results ABS integral = 0.4630E-03 +/- 0.3648E-04 ( 7.879 %)
accumulated results Integral = 0.4328E-03 +/- 0.3571E-04 ( 8.252 %)
accumulated results Virtual = 0.3071E-04 +/- 0.2583E-05 ( 8.409 %)
accumulated results Virtual ratio = 0.5251E+01 +/- 0.1555E-01 ( 0.296 %)
accumulated results ABS virtual = 0.3072E-04 +/- 0.2583E-05 ( 8.408 %)
accumulated results Born*ao2pi = 0.6065E-05 +/- 0.5112E-06 ( 8.429 %)
accumulated result Chi^2 per DoF = 0.0000E+00
1: 0 1 2
channel 1 : 1 T 2080 0 0.4630E-03 0.4328E-03 0.2500E+00
------- iteration 2
Update # PS points (even): 2080 --> 2080
ABS integral = 0.5147E-03 +/- 0.1301E-04 ( 2.528 %)
Integral = 0.4784E-03 +/- 0.1237E-04 ( 2.586 %)
Virtual = -.5215E-06 +/- 0.4819E-06 ( 92.407 %)
Virtual ratio = 0.5102E+01 +/- 0.3713E-01 ( 0.728 %)
ABS virtual = 0.3604E-05 +/- 0.4787E-06 ( 13.282 %)
Born*ao2pi = 0.6575E-05 +/- 0.4395E-06 ( 6.684 %)
Chi^2= 0.1093E+01
accumulated results ABS integral = 0.5011E-03 +/- 0.1226E-04 ( 2.446 %)
accumulated results Integral = 0.4667E-03 +/- 0.1169E-04 ( 2.505 %)
accumulated results Virtual = 0.4390E-05 +/- 0.4737E-06 ( 10.791 %)
accumulated results Virtual ratio = 0.5207E+01 +/- 0.1434E-01 ( 0.275 %)
accumulated results ABS virtual = 0.7844E-05 +/- 0.4707E-06 ( 6.001 %)
accumulated results Born*ao2pi = 0.6339E-05 +/- 0.3333E-06 ( 5.257 %)
accumulated result Chi^2 per DoF = 0.1093E+01
1: 0 1 2
channel 1 : 1 T 4160 2080 0.5011E-03 0.4667E-03 0.6250E-01
------- iteration 3
Update # PS points (even): 4160 --> 4160
ABS integral = 0.5212E-03 +/- 0.6052E-05 ( 1.161 %)
Integral = 0.4825E-03 +/- 0.5820E-05 ( 1.206 %)
Virtual = -.8303E-06 +/- 0.6428E-06 ( 77.419 %)
Virtual ratio = 0.5056E+01 +/- 0.4750E-01 ( 0.939 %)
ABS virtual = 0.3965E-05 +/- 0.6414E-06 ( 16.179 %)
Born*ao2pi = 0.6415E-05 +/- 0.3947E-06 ( 6.153 %)
Chi^2= 0.1204E+01
accumulated results ABS integral = 0.5146E-03 +/- 0.5426E-05 ( 1.055 %)
accumulated results Integral = 0.4773E-03 +/- 0.5210E-05 ( 1.092 %)
accumulated results Virtual = 0.2175E-05 +/- 0.3813E-06 ( 17.532 %)
accumulated results Virtual ratio = 0.5172E+01 +/- 0.1373E-01 ( 0.265 %)
accumulated results ABS virtual = 0.6202E-05 +/- 0.3795E-06 ( 6.119 %)
accumulated results Born*ao2pi = 0.6374E-05 +/- 0.2546E-06 ( 3.995 %)
accumulated result Chi^2 per DoF = 0.1149E+01
1: 0 1 2
channel 1 : 1 T 8320 4160 0.5146E-03 0.4773E-03 0.1562E-01
------- iteration 4
Update # PS points (even): 8320 --> 8320
ABS integral = 0.5407E-03 +/- 0.7134E-05 ( 1.319 %)
Integral = 0.4986E-03 +/- 0.5999E-05 ( 1.203 %)
Virtual = -.7973E-06 +/- 0.6427E-06 ( 80.604 %)
Virtual ratio = 0.5011E+01 +/- 0.6693E-01 ( 1.336 %)
ABS virtual = 0.4042E-05 +/- 0.6420E-06 ( 15.881 %)
Born*ao2pi = 0.6239E-05 +/- 0.4533E-06 ( 7.267 %)
Chi^2= 0.4330E+01
accumulated results ABS integral = 0.5259E-03 +/- 0.4319E-05 ( 0.821 %)
accumulated results Integral = 0.4872E-03 +/- 0.3934E-05 ( 0.807 %)
accumulated results Virtual = 0.1068E-05 +/- 0.3280E-06 ( 30.703 %)
accumulated results Virtual ratio = 0.5144E+01 +/- 0.1345E-01 ( 0.261 %)
accumulated results ABS virtual = 0.5400E-05 +/- 0.3267E-06 ( 6.050 %)
accumulated results Born*ao2pi = 0.6325E-05 +/- 0.2220E-06 ( 3.510 %)
accumulated result Chi^2 per DoF = 0.2209E+01
accumulated results last 3 iterations ABS integral = 0.5285E-03 +/- 0.4350E-05 ( 0.823 %)
accumulated results last 3 iterations Integral = 0.4893E-03 +/- 0.3958E-05 ( 0.809 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.1516E+01
1: 0 1 2
Found desired accuracy
channel 1 : 1 T 16650 8320 0.5259E-03 0.4872E-03 0.5000E-02
-------
Final result [ABS]: 5.2585729033730782E-004 +/- 4.3189336152947953E-006
Final result: 4.8718570714759613E-004 +/- 3.9335437128944616E-006
chi**2 per D.o.F.: 2.2091980135109406
Satistics from MadLoop:
Total points tried: 3252
Stability unknown: 0
Stable PS point: 3252
Unstable PS point (and rescued): 0
Exceptional PS point (unstable and not rescued): 0
Double precision used: 3252
Quadruple precision used: 0
Initialization phase-space points: 0
Unknown return code (100): 0
Unknown return code (10): 0
Unit return code distribution (1):
#Unit 6 = 3252
Time spent in Born : 3.25908089
Time spent in PS_Generation : 0.00000000
Time spent in Reals_evaluation: 13.9862041
Time spent in MCsubtraction : 10.2227907
Time spent in Counter_terms : 7.46814156
Time spent in Integrated_CT : 0.245314360
Time spent in Virtuals : 0.273464561
Time spent in FxFx_cluster : 0.00000000
Time spent in Nbody_prefactor : 3.36851645
Time spent in N1body_prefactor : 3.40365648
Time spent in Adding_alphas_pdf : 0.652192354
Time spent in Reweight_scale : 0.00000000
Time spent in Reweight_pdf : 0.00000000
Time spent in Filling_plots : 0.00000000
Time spent in Applying_cuts : 0.182071432
Time spent in Sum_ident_contr : 5.56288511E-02
Time spent in Pick_unwgt : 0.00000000
Time spent in Write_events : 0.00000000
Time spent in Other_tasks : 1.53346252
Time spent in Total : 44.6505241
Time in seconds: 45
</PRE><br>
<a name=/P0_uux_zx0_zepemz_no_a/GF2></a>
<font color="red">
<br>LOG file for integration channel /P0_uux_zx0_zepemz_no_a/GF2, 0 <br></font>
<PRE>
===============================================================
INFO: MadFKS read these parameters from FKS_params.dat
===============================================================
> IRPoleCheckThreshold = 1.0000000000000001E-005
> PrecisionVirtualAtRunTime = 1.0000000000000000E-003
> NHelForMCoverHels = 4
> VirtualFraction = 1.0000000000000000
> MinVirtualFraction = 5.0000000000000001E-003
===============================================================
A PDF is used, so alpha_s(MZ) is going to be modified
Old value of alpha_s from param_card: 0.11799999999999999
****************************************
NNPDFDriver version 1.0.3
Grid: NNPDF23nlo_as_0119_qed_mem0.grid
****************************************
New value of alpha_s from PDF nn23nlo: 0.11899999999999999
*****************************************************
* MadGraph/MadEvent *
* -------------------------------- *
* http://madgraph.hep.uiuc.edu *
* http://madgraph.phys.ucl.ac.be *
* http://madgraph.roma2.infn.it *
* -------------------------------- *
* *
* PARAMETER AND COUPLING VALUES *
* *
*****************************************************
External Params
---------------------------------
MU_R = 91.188000000000002
aEWM1 = 132.50700000000001
mdl_Gf = 1.1663900000000000E-005
aS = 0.11799999999999999
mdl_ymb = 4.7000000000000002
mdl_ymt = 173.00000000000000
mdl_ymtau = 1.7769999999999999
mdl_MT = 173.00000000000000
mdl_MB = 4.7000000000000002
mdl_MZ = 91.188000000000002
mdl_MTA = 1.7769999999999999
mdl_WT = 1.4915000000000000
mdl_WZ = 2.4414039999999999
mdl_WW = 2.0476000000000001
mdl_MX0 = 300.00000000000000
mdl_WX0 = 1.0604700000000000
mdl_Lambda = 5000.0000000000000
mdl_cosa = 1.0000000000000000
mdl_kSM = 5.0000000000000003E-002
mdl_kHtt = 0.0000000000000000
mdl_kAtt = 0.0000000000000000
mdl_kHbb = 0.0000000000000000
mdl_kAbb = 0.0000000000000000
mdl_kHll = 0.0000000000000000
mdl_kAll = 0.0000000000000000
mdl_kHaa = 0.0000000000000000
mdl_kAaa = 0.0000000000000000
mdl_kHza = 0.0000000000000000
mdl_kAza = 0.0000000000000000
mdl_kHzz = 8.1561199999999996
mdl_kAzz = 0.0000000000000000
mdl_kHww = 10.496200000000000
mdl_kAww = 0.0000000000000000
mdl_kHda = 0.0000000000000000
mdl_kHdz = 0.0000000000000000
mdl_kHdwR = 0.0000000000000000
mdl_kHdwI = 0.0000000000000000
Internal Params
---------------------------------
mdl_CKM11 = 1.0000000000000000
mdl_conjg__CKM3x3 = 1.0000000000000000
mdl_conjg__CKM11 = 1.0000000000000000
mdl_lhv = 1.0000000000000000
mdl_CKM3x3 = 1.0000000000000000
mdl_conjg__CKM33 = 1.0000000000000000
mdl_Ncol = 3.0000000000000000
mdl_CA = 3.0000000000000000
mdl_TF = 0.50000000000000000
mdl_CF = 1.3333333333333333
mdl_complexi = ( 0.0000000000000000 , 1.0000000000000000 )
mdl_MZ__exp__2 = 8315.2513440000002
mdl_MZ__exp__4 = 69143404.913893804
mdl_sqrt__2 = 1.4142135623730951
mdl_MX0__exp__2 = 90000.000000000000
mdl_cosa__exp__2 = 1.0000000000000000
mdl_sina = 0.0000000000000000
mdl_kHdw = ( 0.0000000000000000 , 0.0000000000000000 )
mdl_nb__2__exp__0_75 = 1.6817928305074290
mdl_Ncol__exp__2 = 9.0000000000000000
mdl_MB__exp__2 = 22.090000000000003
mdl_MT__exp__2 = 29929.000000000000
mdl_conjg__kHdw = ( 0.0000000000000000 , -0.0000000000000000 )
mdl_aEW = 7.5467711139788835E-003
mdl_MW = 80.419002445756163
mdl_sqrt__aEW = 8.6872153846781555E-002
mdl_ee = 0.30795376724436879
mdl_MW__exp__2 = 6467.2159543705357
mdl_sw2 = 0.22224648578577766
mdl_cw = 0.88190334743339216
mdl_sqrt__sw2 = 0.47143025548407230
mdl_sw = 0.47143025548407230
mdl_g1 = 0.34919219678733299
mdl_gw = 0.65323293034757990
mdl_vev = 246.21845810181637
mdl_vev__exp__2 = 60623.529110035903
mdl_lam = 0.74228605065735920
mdl_yb = 2.6995554250465490E-002
mdl_yt = 0.99366614581500623
mdl_ytau = 1.0206617000654717E-002
mdl_muH = 212.13203435596427
mdl_AxialZUp = -0.18517701861793787
mdl_AxialZDown = 0.18517701861793787
mdl_VectorZUp = 7.5430507588273299E-002
mdl_VectorZDown = -0.13030376310310560
mdl_VectorAUp = 0.20530251149624587
mdl_VectorADown = -0.10265125574812294
mdl_VectorWmDxU = 0.23095271737156670
mdl_AxialWmDxU = -0.23095271737156670
mdl_VectorWpUxD = 0.23095271737156670
mdl_AxialWpUxD = -0.23095271737156670
mdl_I1x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_I2x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I3x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I4x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_Vector_tbGp = (-0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGp = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_Vector_tbGm = ( 0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGm = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_ee__exp__2 = 9.4835522759998875E-002
mdl_gAaa = 1.3008566310666950E-005
mdl_cw__exp__2 = 0.77775351421422245
mdl_gAza = 4.7794971072590281E-006
mdl_gHaa = 2.5475109025056106E-005
mdl_gHza = 3.9182129211851395E-005
mdl_gw__exp__2 = 0.42671326129048615
mdl_sw__exp__2 = 0.22224648578577769
Internal Params evaluated point by point
----------------------------------------
mdl_sqrt__aS = 0.34351128074635334
mdl_G__exp__2 = 1.4828317324943823
mdl_G__exp__4 = 2.1987899468922913
mdl_R2MixedFactor_FIN_ = -2.5040377713124864E-002
mdl_GWcft_UV_b_1EPS_ = -3.1300472141406080E-003
mdl_GWcft_UV_t_1EPS_ = -3.1300472141406080E-003
mdl_bWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_tWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_G__exp__3 = 1.8056676068262196
mdl_MU_R__exp__2 = 8315.2513440000002
mdl_GWcft_UV_b_FIN_ = -1.8563438626678915E-002
mdl_GWcft_UV_t_FIN_ = 4.0087659331150384E-003
mdl_bWcft_UV_FIN_ = -0.13642100947319838
mdl_tWcft_UV_FIN_ = -9.8778211443463623E-004
mdl_gAgg = 7.6274879753643885E-005
mdl_gHgg = -5.0849919835762592E-005
Couplings of HC_NLO_X0_UFO
---------------------------------
R2_UUZ_V2 = -0.00000E+00 -0.72127E-02
R2_UUZ_V5 = 0.00000E+00 0.68702E-03
GC_5 = 0.00000E+00 0.12177E+01
GC_3007a = -0.00000E+00 -0.00000E+00
GC_3007h2 = -0.00000E+00 -0.16312E-02
GC_3007h3 = -0.00000E+00 -0.00000E+00
GC_22 = 0.00000E+00 0.28804E+00
GC_23 = -0.00000E+00 -0.27437E-01
GC_24 = 0.00000E+00 0.82310E-01
GC_3007h1 = 0.00000E+00 0.33772E+01
Collider parameters:
--------------------
Running at P P machine @ 13000.000000000000 GeV
PDF set = nn23nlo
alpha_s(Mz)= 0.1190 running at 2 loops.
alpha_s(Mz)= 0.1190 running at 2 loops.
Renormalization scale set on event-by-event basis
Factorization scale set on event-by-event basis
Diagram information for clustering has been set-up for nFKSprocess 1
Diagram information for clustering has been set-up for nFKSprocess 2
Diagram information for clustering has been set-up for nFKSprocess 3
Diagram information for clustering has been set-up for nFKSprocess 4
getting user params
Enter number of events and iterations:
Number of events and iterations -1 12
Enter desired fractional accuracy:
Desired fractional accuracy: 2.9999999999999999E-002
Enter alpha, beta for G_soft
Enter alpha<0 to set G_soft=1 (no ME soft)
for G_soft: alpha= 1.0000000000000000 , beta= -0.10000000000000001
Enter alpha, beta for G_azi
Enter alpha>0 to set G_azi=0 (no azi corr)
for G_azi: alpha= -1.0000000000000000 , beta= -0.10000000000000001
Doing the S and H events together
Suppress amplitude (0 no, 1 yes)?
Using suppressed amplitude.
Exact helicity sum (0 yes, n = number/event)?
Do MC over helicities for the virtuals
Enter Configuration Number:
Running Configuration Number: 2
Enter running mode for MINT:
0 to set-up grids, 1 to integrate, 2 to generate events
MINT running mode: 0
Set the three folding parameters for MINT
xi_i, phi_i, y_ij
1 1 1
'all ', 'born', 'real', 'virt', 'novi' or 'grid'?
Enter 'born0' or 'virt0' to perform
a pure n-body integration (no S functions)
doing the all of this channel
Normal integration (Sfunction != 1)
about to integrate 13 -1 12 2
imode is 0
channel 1 : 2 T 0 0 0.1000E+01 0.0000E+00 0.1000E+01
+----------------------------------------------------------------+
| |
| Ninja - version 1.2.0 |
| |
| Author: <NAME> |
| |
| Based on: |
| |
| <NAME>, <NAME> and <NAME>, |
| "Integrand reduction of one-loop scattering amplitudes |
| through Laurent series expansion," |
| JHEP 1206 (2012) 095 [arXiv:1203.0291 [hep-ph]]. |
| |
| <NAME>, |
| "Ninja: Automated Integrand Reduction via Laurent |
| Expansion for One-Loop Amplitudes," |
| Comput.Phys.Commun. 185 (2014) [arXiv:1403.1229 [hep-ph]] |
| |
+----------------------------------------------------------------+
------- iteration 1
Update # PS points (even): 1040 --> 1040
Using random seed offsets: 2 , 1 , 0
with seed 34
Ranmar initialization seeds 13169 9409
Total number of FKS directories is 4
FKS process map (sum= 3 ) :
1 --> 2 : 1 3
2 --> 2 : 2 4
================================
process combination map (specified per FKS dir):
1 map 1 2 3 4
1 inv. map 1 2 3 4
2 map 1 2 3 4
2 inv. map 1 2 3 4
3 map 1 2 3 4
3 inv. map 1 2 3 4
4 map 1 2 3 4
4 inv. map 1 2 3 4
================================
tau_min 1 1 : 0.18238E+03 -- 0.39119E+03
tau_min 2 1 : 0.18238E+03 -- 0.39119E+03
tau_min 3 1 : 0.18238E+03 -- 0.39119E+03
tau_min 4 1 : 0.18238E+03 -- 0.39119E+03
bpower is 0.0000000000000000
Scale values (may change event by event):
muR, muR_reference: 0.450880D+03 0.450880D+03 1.00
muF1, muF1_reference: 0.450880D+03 0.450880D+03 1.00
muF2, muF2_reference: 0.450880D+03 0.450880D+03 1.00
QES, QES_reference: 0.450880D+03 0.450880D+03 1.00
muR_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF1_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF2_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
QES_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
alpha_s= 9.5813336350209180E-002
alpha_s value used for the virtuals is (for the first PS point): 9.5813336350209180E-002
==========================================================================================
{ }
{ [32m [0m }
{ [32m ,, [0m }
{ [32m`7MMM. ,MMF' `7MM `7MMF' [0m }
{ [32m MMMb dPMM MM MM [0m }
{ [32m M YM ,M MM ,6"Yb. ,M""bMM MM ,pW"Wq. ,pW"Wq.`7MMpdMAo. [0m }
{ [32m M Mb M' MM 8) MM ,AP MM MM 6W' `Wb 6W' `Wb MM `Wb [0m }
{ [32m M YM.P' MM ,pm9MM 8MI MM MM , 8M M8 8M M8 MM M8 [0m }
{ [32m M `YM' MM 8M MM `Mb MM MM ,M YA. ,A9 YA. ,A9 MM ,AP [0m }
{ [32m.JML. `' .JMML.`Moo9^Yo.`Wbmd"MML..JMMmmmmMMM `Ybmd9' `Ybmd9' MMbmmd' [0m }
{ [32m MM [0m }
{ [32m .JMML. [0m }
{ [32m[0mv2.6.6 (2018-06-28), Ref: arXiv:1103.0621v2, arXiv:1405.0301[32m [0m }
{ [32m [0m }
{ }
==========================================================================================
===============================================================
INFO: MadLoop read these parameters from ../MadLoop5_resources/MadLoopParams.dat
===============================================================
> MLReductionLib = 6|7|1
> CTModeRun = -1
> MLStabThres = 1.0000000000000000E-003
> NRotations_DP = 0
> NRotations_QP = 0
> CTStabThres = 1.0000000000000000E-002
> CTLoopLibrary = 2
> CTModeInit = 1
> CheckCycle = 3
> MaxAttempts = 10
> UseLoopFilter = F
> HelicityFilterLevel = 2
> ImprovePSPoint = 2
> DoubleCheckHelicityFilter = T
> LoopInitStartOver = F
> HelInitStartOver = F
> ZeroThres = 1.0000000000000001E-009
> OSThres = 1.0000000000000000E-008
> WriteOutFilters = T
> UseQPIntegrandForNinja = T
> UseQPIntegrandForCutTools = T
> IREGIMODE = 2
> IREGIRECY = T
> COLLIERMode = 1
> COLLIERRequiredAccuracy = 1.0000000000000000E-008
> COLLIERCanOutput = F
> COLLIERComputeUVpoles = T
> COLLIERComputeIRpoles = T
> COLLIERGlobalCache = -1
> COLLIERUseCacheForPoles = F
> COLLIERUseInternalStabilityTest = T
===============================================================
------------------------------------------------------------------------
| You are using CutTools - Version 1.9.3 |
| Authors: <NAME>, <NAME>, <NAME> |
| Published in JHEP 0803:042,2008 |
| http://www.ugr.es/~pittau/CutTools |
| |
| Compiler with 34 significant digits detetected |
----------------------------------------------------------------------
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
---- POLES CANCELLED ----
ABS integral = 0.1016E-02 +/- 0.7706E-04 ( 7.586 %)
Integral = 0.9358E-03 +/- 0.7277E-04 ( 7.776 %)
Virtual = 0.6328E-04 +/- 0.4846E-05 ( 7.658 %)
Virtual ratio = 0.5245E+01 +/- 0.1574E-01 ( 0.300 %)
ABS virtual = 0.6329E-04 +/- 0.4846E-05 ( 7.657 %)
Born*ao2pi = 0.1292E-04 +/- 0.1017E-05 ( 7.871 %)
Chi^2 per d.o.f. 0.0000E+00
accumulated results ABS integral = 0.1016E-02 +/- 0.7706E-04 ( 7.586 %)
accumulated results Integral = 0.9358E-03 +/- 0.7277E-04 ( 7.776 %)
accumulated results Virtual = 0.6328E-04 +/- 0.4846E-05 ( 7.658 %)
accumulated results Virtual ratio = 0.5245E+01 +/- 0.1574E-01 ( 0.300 %)
accumulated results ABS virtual = 0.6329E-04 +/- 0.4846E-05 ( 7.657 %)
accumulated results Born*ao2pi = 0.1292E-04 +/- 0.1017E-05 ( 7.871 %)
accumulated result Chi^2 per DoF = 0.0000E+00
1: 0 1 2
channel 1 : 2 T 2080 0 0.1016E-02 0.9358E-03 0.2500E+00
------- iteration 2
Update # PS points (even): 2080 --> 2080
ABS integral = 0.1014E-02 +/- 0.2388E-04 ( 2.356 %)
Integral = 0.9437E-03 +/- 0.2289E-04 ( 2.426 %)
Virtual = -.8212E-06 +/- 0.1260E-05 ( 153.397 %)
Virtual ratio = 0.4994E+01 +/- 0.3991E-01 ( 0.799 %)
ABS virtual = 0.9227E-05 +/- 0.1252E-05 ( 13.564 %)
Born*ao2pi = 0.1318E-04 +/- 0.8784E-06 ( 6.664 %)
Chi^2= 0.3788E-03
accumulated results ABS integral = 0.1014E-02 +/- 0.2281E-04 ( 2.249 %)
accumulated results Integral = 0.9418E-03 +/- 0.2184E-04 ( 2.318 %)
accumulated results Virtual = 0.1240E-04 +/- 0.1219E-05 ( 9.828 %)
accumulated results Virtual ratio = 0.5174E+01 +/- 0.1464E-01 ( 0.283 %)
accumulated results ABS virtual = 0.2032E-04 +/- 0.1212E-05 ( 5.963 %)
accumulated results Born*ao2pi = 0.1306E-04 +/- 0.6647E-06 ( 5.090 %)
accumulated result Chi^2 per DoF = 0.3788E-03
1: 0 1 2
channel 1 : 2 T 4160 2080 0.1014E-02 0.9418E-03 0.6250E-01
------- iteration 3
Update # PS points (even): 4160 --> 4160
ABS integral = 0.1017E-02 +/- 0.1242E-04 ( 1.221 %)
Integral = 0.9446E-03 +/- 0.1211E-04 ( 1.282 %)
Virtual = 0.5068E-06 +/- 0.1658E-05 ( 327.093 %)
Virtual ratio = 0.5019E+01 +/- 0.5583E-01 ( 1.113 %)
ABS virtual = 0.9265E-05 +/- 0.1655E-05 ( 17.859 %)
Born*ao2pi = 0.1309E-04 +/- 0.9963E-06 ( 7.614 %)
Chi^2= 0.5473E-02
accumulated results ABS integral = 0.1016E-02 +/- 0.1091E-04 ( 1.074 %)
accumulated results Integral = 0.9436E-03 +/- 0.1059E-04 ( 1.123 %)
accumulated results Virtual = 0.7362E-05 +/- 0.9821E-06 ( 13.340 %)
accumulated results Virtual ratio = 0.5142E+01 +/- 0.1416E-01 ( 0.275 %)
accumulated results ABS virtual = 0.1565E-04 +/- 0.9776E-06 ( 6.248 %)
accumulated results Born*ao2pi = 0.1307E-04 +/- 0.5529E-06 ( 4.231 %)
accumulated result Chi^2 per DoF = 0.2926E-02
1: 0 1 2
channel 1 : 2 T 8320 4160 0.1016E-02 0.9436E-03 0.1668E-01
------- iteration 4
Update # PS points (even): 8320 --> 8320
ABS integral = 0.1012E-02 +/- 0.6112E-05 ( 0.604 %)
Integral = 0.9353E-03 +/- 0.5583E-05 ( 0.597 %)
Virtual = 0.1036E-05 +/- 0.8201E-06 ( 79.184 %)
Virtual ratio = 0.5036E+01 +/- 0.5295E-01 ( 1.051 %)
ABS virtual = 0.7171E-05 +/- 0.8182E-06 ( 11.411 %)
Born*ao2pi = 0.1228E-04 +/- 0.8792E-06 ( 7.161 %)
Chi^2= 0.4660E-01
accumulated results ABS integral = 0.1014E-02 +/- 0.5332E-05 ( 0.526 %)
accumulated results Integral = 0.9382E-03 +/- 0.4939E-05 ( 0.526 %)
accumulated results Virtual = 0.3915E-05 +/- 0.6295E-06 ( 16.081 %)
accumulated results Virtual ratio = 0.5119E+01 +/- 0.1368E-01 ( 0.267 %)
accumulated results ABS virtual = 0.1103E-04 +/- 0.6275E-06 ( 5.687 %)
accumulated results Born*ao2pi = 0.1276E-04 +/- 0.4681E-06 ( 3.667 %)
accumulated result Chi^2 per DoF = 0.1748E-01
accumulated results last 3 iterations ABS integral = 0.1014E-02 +/- 0.5345E-05 ( 0.527 %)
accumulated results last 3 iterations Integral = 0.9384E-03 +/- 0.4950E-05 ( 0.528 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.2495E-01
1: 0 1 2
Found desired accuracy
channel 1 : 2 T 16632 8320 0.1014E-02 0.9382E-03 0.5000E-02
-------
Final result [ABS]: 1.0136584616549980E-003 +/- 5.3321417818656855E-006
Final result: 9.3817259912303778E-004 +/- 4.9389426522606367E-006
chi**2 per D.o.F.: 1.7482288963021946E-002
Satistics from MadLoop:
Total points tried: 3328
Stability unknown: 0
Stable PS point: 3328
Unstable PS point (and rescued): 0
Exceptional PS point (unstable and not rescued): 0
Double precision used: 3328
Quadruple precision used: 0
Initialization phase-space points: 0
Unknown return code (100): 0
Unknown return code (10): 0
Unit return code distribution (1):
#Unit 6 = 3328
Time spent in Born : 3.29830909
Time spent in PS_Generation : 0.00000000
Time spent in Reals_evaluation: 14.2534561
Time spent in MCsubtraction : 10.1572752
Time spent in Counter_terms : 7.56552982
Time spent in Integrated_CT : 0.250928938
Time spent in Virtuals : 0.285149872
Time spent in FxFx_cluster : 0.00000000
Time spent in Nbody_prefactor : 3.42999411
Time spent in N1body_prefactor : 3.44777632
Time spent in Adding_alphas_pdf : 0.720293164
Time spent in Reweight_scale : 0.00000000
Time spent in Reweight_pdf : 0.00000000
Time spent in Filling_plots : 0.00000000
Time spent in Applying_cuts : 0.189888567
Time spent in Sum_ident_contr : 5.70689589E-02
Time spent in Pick_unwgt : 0.00000000
Time spent in Write_events : 0.00000000
Time spent in Other_tasks : 1.53979874
Time spent in Total : 45.1954689
Time in seconds: 46
</PRE><br>
<a name=/P0_ddx_zx0_zepemz_no_a/GF1></a>
<font color="red">
<br>LOG file for integration channel /P0_ddx_zx0_zepemz_no_a/GF1, 0 <br></font>
<PRE>
===============================================================
INFO: MadFKS read these parameters from FKS_params.dat
===============================================================
> IRPoleCheckThreshold = 1.0000000000000001E-005
> PrecisionVirtualAtRunTime = 1.0000000000000000E-003
> NHelForMCoverHels = 4
> VirtualFraction = 1.0000000000000000
> MinVirtualFraction = 5.0000000000000001E-003
===============================================================
A PDF is used, so alpha_s(MZ) is going to be modified
Old value of alpha_s from param_card: 0.11799999999999999
****************************************
NNPDFDriver version 1.0.3
Grid: NNPDF23nlo_as_0119_qed_mem0.grid
****************************************
New value of alpha_s from PDF nn23nlo: 0.11899999999999999
*****************************************************
* MadGraph/MadEvent *
* -------------------------------- *
* http://madgraph.hep.uiuc.edu *
* http://madgraph.phys.ucl.ac.be *
* http://madgraph.roma2.infn.it *
* -------------------------------- *
* *
* PARAMETER AND COUPLING VALUES *
* *
*****************************************************
External Params
---------------------------------
MU_R = 91.188000000000002
aEWM1 = 132.50700000000001
mdl_Gf = 1.1663900000000000E-005
aS = 0.11799999999999999
mdl_ymb = 4.7000000000000002
mdl_ymt = 173.00000000000000
mdl_ymtau = 1.7769999999999999
mdl_MT = 173.00000000000000
mdl_MB = 4.7000000000000002
mdl_MZ = 91.188000000000002
mdl_MTA = 1.7769999999999999
mdl_WT = 1.4915000000000000
mdl_WZ = 2.4414039999999999
mdl_WW = 2.0476000000000001
mdl_MX0 = 300.00000000000000
mdl_WX0 = 1.0604700000000000
mdl_Lambda = 5000.0000000000000
mdl_cosa = 1.0000000000000000
mdl_kSM = 5.0000000000000003E-002
mdl_kHtt = 0.0000000000000000
mdl_kAtt = 0.0000000000000000
mdl_kHbb = 0.0000000000000000
mdl_kAbb = 0.0000000000000000
mdl_kHll = 0.0000000000000000
mdl_kAll = 0.0000000000000000
mdl_kHaa = 0.0000000000000000
mdl_kAaa = 0.0000000000000000
mdl_kHza = 0.0000000000000000
mdl_kAza = 0.0000000000000000
mdl_kHzz = 8.1561199999999996
mdl_kAzz = 0.0000000000000000
mdl_kHww = 10.496200000000000
mdl_kAww = 0.0000000000000000
mdl_kHda = 0.0000000000000000
mdl_kHdz = 0.0000000000000000
mdl_kHdwR = 0.0000000000000000
mdl_kHdwI = 0.0000000000000000
Internal Params
---------------------------------
mdl_CKM11 = 1.0000000000000000
mdl_conjg__CKM3x3 = 1.0000000000000000
mdl_conjg__CKM11 = 1.0000000000000000
mdl_lhv = 1.0000000000000000
mdl_CKM3x3 = 1.0000000000000000
mdl_conjg__CKM33 = 1.0000000000000000
mdl_Ncol = 3.0000000000000000
mdl_CA = 3.0000000000000000
mdl_TF = 0.50000000000000000
mdl_CF = 1.3333333333333333
mdl_complexi = ( 0.0000000000000000 , 1.0000000000000000 )
mdl_MZ__exp__2 = 8315.2513440000002
mdl_MZ__exp__4 = 69143404.913893804
mdl_sqrt__2 = 1.4142135623730951
mdl_MX0__exp__2 = 90000.000000000000
mdl_cosa__exp__2 = 1.0000000000000000
mdl_sina = 0.0000000000000000
mdl_kHdw = ( 0.0000000000000000 , 0.0000000000000000 )
mdl_nb__2__exp__0_75 = 1.6817928305074290
mdl_Ncol__exp__2 = 9.0000000000000000
mdl_MB__exp__2 = 22.090000000000003
mdl_MT__exp__2 = 29929.000000000000
mdl_conjg__kHdw = ( 0.0000000000000000 , -0.0000000000000000 )
mdl_aEW = 7.5467711139788835E-003
mdl_MW = 80.419002445756163
mdl_sqrt__aEW = 8.6872153846781555E-002
mdl_ee = 0.30795376724436879
mdl_MW__exp__2 = 6467.2159543705357
mdl_sw2 = 0.22224648578577766
mdl_cw = 0.88190334743339216
mdl_sqrt__sw2 = 0.47143025548407230
mdl_sw = 0.47143025548407230
mdl_g1 = 0.34919219678733299
mdl_gw = 0.65323293034757990
mdl_vev = 246.21845810181637
mdl_vev__exp__2 = 60623.529110035903
mdl_lam = 0.74228605065735920
mdl_yb = 2.6995554250465490E-002
mdl_yt = 0.99366614581500623
mdl_ytau = 1.0206617000654717E-002
mdl_muH = 212.13203435596427
mdl_AxialZUp = -0.18517701861793787
mdl_AxialZDown = 0.18517701861793787
mdl_VectorZUp = 7.5430507588273299E-002
mdl_VectorZDown = -0.13030376310310560
mdl_VectorAUp = 0.20530251149624587
mdl_VectorADown = -0.10265125574812294
mdl_VectorWmDxU = 0.23095271737156670
mdl_AxialWmDxU = -0.23095271737156670
mdl_VectorWpUxD = 0.23095271737156670
mdl_AxialWpUxD = -0.23095271737156670
mdl_I1x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_I2x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I3x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I4x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_Vector_tbGp = (-0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGp = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_Vector_tbGm = ( 0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGm = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_ee__exp__2 = 9.4835522759998875E-002
mdl_gAaa = 1.3008566310666950E-005
mdl_cw__exp__2 = 0.77775351421422245
mdl_gAza = 4.7794971072590281E-006
mdl_gHaa = 2.5475109025056106E-005
mdl_gHza = 3.9182129211851395E-005
mdl_gw__exp__2 = 0.42671326129048615
mdl_sw__exp__2 = 0.22224648578577769
Internal Params evaluated point by point
----------------------------------------
mdl_sqrt__aS = 0.34351128074635334
mdl_G__exp__2 = 1.4828317324943823
mdl_G__exp__4 = 2.1987899468922913
mdl_R2MixedFactor_FIN_ = -2.5040377713124864E-002
mdl_GWcft_UV_b_1EPS_ = -3.1300472141406080E-003
mdl_GWcft_UV_t_1EPS_ = -3.1300472141406080E-003
mdl_bWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_tWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_G__exp__3 = 1.8056676068262196
mdl_MU_R__exp__2 = 8315.2513440000002
mdl_GWcft_UV_b_FIN_ = -1.8563438626678915E-002
mdl_GWcft_UV_t_FIN_ = 4.0087659331150384E-003
mdl_bWcft_UV_FIN_ = -0.13642100947319838
mdl_tWcft_UV_FIN_ = -9.8778211443463623E-004
mdl_gAgg = 7.6274879753643885E-005
mdl_gHgg = -5.0849919835762592E-005
Couplings of HC_NLO_X0_UFO
---------------------------------
R2_UUZ_V2 = -0.00000E+00 -0.72127E-02
R2_UUZ_V5 = 0.00000E+00 0.68702E-03
GC_5 = 0.00000E+00 0.12177E+01
GC_3007a = -0.00000E+00 -0.00000E+00
GC_3007h2 = -0.00000E+00 -0.16312E-02
GC_3007h3 = -0.00000E+00 -0.00000E+00
GC_22 = 0.00000E+00 0.28804E+00
GC_23 = -0.00000E+00 -0.27437E-01
GC_24 = 0.00000E+00 0.82310E-01
GC_3007h1 = 0.00000E+00 0.33772E+01
Collider parameters:
--------------------
Running at P P machine @ 13000.000000000000 GeV
PDF set = nn23nlo
alpha_s(Mz)= 0.1190 running at 2 loops.
alpha_s(Mz)= 0.1190 running at 2 loops.
Renormalization scale set on event-by-event basis
Factorization scale set on event-by-event basis
Diagram information for clustering has been set-up for nFKSprocess 1
Diagram information for clustering has been set-up for nFKSprocess 2
Diagram information for clustering has been set-up for nFKSprocess 3
Diagram information for clustering has been set-up for nFKSprocess 4
getting user params
Enter number of events and iterations:
Number of events and iterations -1 12
Enter desired fractional accuracy:
Desired fractional accuracy: 2.9999999999999999E-002
Enter alpha, beta for G_soft
Enter alpha<0 to set G_soft=1 (no ME soft)
for G_soft: alpha= 1.0000000000000000 , beta= -0.10000000000000001
Enter alpha, beta for G_azi
Enter alpha>0 to set G_azi=0 (no azi corr)
for G_azi: alpha= -1.0000000000000000 , beta= -0.10000000000000001
Doing the S and H events together
Suppress amplitude (0 no, 1 yes)?
Using suppressed amplitude.
Exact helicity sum (0 yes, n = number/event)?
Do MC over helicities for the virtuals
Enter Configuration Number:
Running Configuration Number: 1
Enter running mode for MINT:
0 to set-up grids, 1 to integrate, 2 to generate events
MINT running mode: 0
Set the three folding parameters for MINT
xi_i, phi_i, y_ij
1 1 1
'all ', 'born', 'real', 'virt', 'novi' or 'grid'?
Enter 'born0' or 'virt0' to perform
a pure n-body integration (no S functions)
doing the all of this channel
Normal integration (Sfunction != 1)
about to integrate 13 -1 12 1
imode is 0
channel 1 : 1 T 0 0 0.1000E+01 0.0000E+00 0.1000E+01
+----------------------------------------------------------------+
| |
| Ninja - version 1.2.0 |
| |
| Author: <NAME> |
| |
| Based on: |
| |
| <NAME>, <NAME> and <NAME>, |
| "Integrand reduction of one-loop scattering amplitudes |
| through Laurent series expansion," |
| JHEP 1206 (2012) 095 [arXiv:1203.0291 [hep-ph]]. |
| |
| <NAME>, |
| "Ninja: Automated Integrand Reduction via Laurent |
| Expansion for One-Loop Amplitudes," |
| Comput.Phys.Commun. 185 (2014) [arXiv:1403.1229 [hep-ph]] |
| |
+----------------------------------------------------------------+
------- iteration 1
Update # PS points (even): 1040 --> 1040
Using random seed offsets: 1 , 2 , 0
with seed 34
Ranmar initialization seeds 13168 9410
Total number of FKS directories is 4
FKS process map (sum= 3 ) :
1 --> 2 : 1 3
2 --> 2 : 2 4
================================
process combination map (specified per FKS dir):
1 map 1 2 3 4
1 inv. map 1 2 3 4
2 map 1 2 3 4
2 inv. map 1 2 3 4
3 map 1 2 3 4
3 inv. map 1 2 3 4
4 map 1 2 3 4
4 inv. map 1 2 3 4
================================
tau_min 1 1 : 0.18238E+03 -- 0.39119E+03
tau_min 2 1 : 0.18238E+03 -- 0.39119E+03
tau_min 3 1 : 0.18238E+03 -- 0.39119E+03
tau_min 4 1 : 0.18238E+03 -- 0.39119E+03
bpower is 0.0000000000000000
Scale values (may change event by event):
muR, muR_reference: 0.192088D+03 0.192088D+03 1.00
muF1, muF1_reference: 0.192088D+03 0.192088D+03 1.00
muF2, muF2_reference: 0.192088D+03 0.192088D+03 1.00
QES, QES_reference: 0.192088D+03 0.192088D+03 1.00
muR_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF1_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF2_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
QES_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
alpha_s= 0.10691101519581141
alpha_s value used for the virtuals is (for the first PS point): 0.10691101519581141
==========================================================================================
{ }
{ [32m [0m }
{ [32m ,, [0m }
{ [32m`7MMM. ,MMF' `7MM `7MMF' [0m }
{ [32m MMMb dPMM MM MM [0m }
{ [32m M YM ,M MM ,6"Yb. ,M""bMM MM ,pW"Wq. ,pW"Wq.`7MMpdMAo. [0m }
{ [32m M Mb M' MM 8) MM ,AP MM MM 6W' `Wb 6W' `Wb MM `Wb [0m }
{ [32m M YM.P' MM ,pm9MM 8MI MM MM , 8M M8 8M M8 MM M8 [0m }
{ [32m M `YM' MM 8M MM `Mb MM MM ,M YA. ,A9 YA. ,A9 MM ,AP [0m }
{ [32m.JML. `' .JMML.`Moo9^Yo.`Wbmd"MML..JMMmmmmMMM `Ybmd9' `Ybmd9' MMbmmd' [0m }
{ [32m MM [0m }
{ [32m .JMML. [0m }
{ [32m[0mv2.6.6 (2018-06-28), Ref: arXiv:1103.0621v2, arXiv:1405.0301[32m [0m }
{ [32m [0m }
{ }
==========================================================================================
===============================================================
INFO: MadLoop read these parameters from ../MadLoop5_resources/MadLoopParams.dat
===============================================================
> MLReductionLib = 6|7|1
> CTModeRun = -1
> MLStabThres = 1.0000000000000000E-003
> NRotations_DP = 0
> NRotations_QP = 0
> CTStabThres = 1.0000000000000000E-002
> CTLoopLibrary = 2
> CTModeInit = 1
> CheckCycle = 3
> MaxAttempts = 10
> UseLoopFilter = F
> HelicityFilterLevel = 2
> ImprovePSPoint = 2
> DoubleCheckHelicityFilter = T
> LoopInitStartOver = F
> HelInitStartOver = F
> ZeroThres = 1.0000000000000001E-009
> OSThres = 1.0000000000000000E-008
> WriteOutFilters = T
> UseQPIntegrandForNinja = T
> UseQPIntegrandForCutTools = T
> IREGIMODE = 2
> IREGIRECY = T
> COLLIERMode = 1
> COLLIERRequiredAccuracy = 1.0000000000000000E-008
> COLLIERCanOutput = F
> COLLIERComputeUVpoles = T
> COLLIERComputeIRpoles = T
> COLLIERGlobalCache = -1
> COLLIERUseCacheForPoles = F
> COLLIERUseInternalStabilityTest = T
===============================================================
------------------------------------------------------------------------
| You are using CutTools - Version 1.9.3 |
| Authors: <NAME>, <NAME>, <NAME> |
| Published in JHEP 0803:042,2008 |
| http://www.ugr.es/~pittau/CutTools |
| |
| Compiler with 34 significant digits detetected |
----------------------------------------------------------------------
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
---- POLES CANCELLED ----
ABS integral = 0.3950E-03 +/- 0.3234E-04 ( 8.185 %)
Integral = 0.3746E-03 +/- 0.3149E-04 ( 8.405 %)
Virtual = 0.2619E-04 +/- 0.2102E-05 ( 8.029 %)
Virtual ratio = 0.5199E+01 +/- 0.2237E-01 ( 0.430 %)
ABS virtual = 0.2622E-04 +/- 0.2102E-05 ( 8.018 %)
Born*ao2pi = 0.5410E-05 +/- 0.4605E-06 ( 8.512 %)
Chi^2 per d.o.f. 0.0000E+00
accumulated results ABS integral = 0.3950E-03 +/- 0.3234E-04 ( 8.185 %)
accumulated results Integral = 0.3746E-03 +/- 0.3149E-04 ( 8.405 %)
accumulated results Virtual = 0.2619E-04 +/- 0.2102E-05 ( 8.029 %)
accumulated results Virtual ratio = 0.5199E+01 +/- 0.2237E-01 ( 0.430 %)
accumulated results ABS virtual = 0.2622E-04 +/- 0.2102E-05 ( 8.018 %)
accumulated results Born*ao2pi = 0.5410E-05 +/- 0.4605E-06 ( 8.512 %)
accumulated result Chi^2 per DoF = 0.0000E+00
1: 0 1 2
channel 1 : 1 T 2080 0 0.3950E-03 0.3746E-03 0.2500E+00
------- iteration 2
Update # PS points (even): 2080 --> 2080
ABS integral = 0.4209E-03 +/- 0.1015E-04 ( 2.411 %)
Integral = 0.3938E-03 +/- 0.9810E-05 ( 2.491 %)
Virtual = 0.1076E-05 +/- 0.3234E-06 ( 30.049 %)
Virtual ratio = 0.5098E+01 +/- 0.2984E-01 ( 0.585 %)
ABS virtual = 0.3730E-05 +/- 0.3186E-06 ( 8.542 %)
Born*ao2pi = 0.6313E-05 +/- 0.3924E-06 ( 6.215 %)
Chi^2= 0.3693E+00
accumulated results ABS integral = 0.4147E-03 +/- 0.9683E-05 ( 2.335 %)
accumulated results Integral = 0.3893E-03 +/- 0.9366E-05 ( 2.406 %)
accumulated results Virtual = 0.4423E-05 +/- 0.3196E-06 ( 7.225 %)
accumulated results Virtual ratio = 0.5156E+01 +/- 0.1790E-01 ( 0.347 %)
accumulated results ABS virtual = 0.6689E-05 +/- 0.3150E-06 ( 4.709 %)
accumulated results Born*ao2pi = 0.5898E-05 +/- 0.2987E-06 ( 5.064 %)
accumulated result Chi^2 per DoF = 0.3693E+00
1: 0 1 2
channel 1 : 1 T 4160 2080 0.4147E-03 0.3893E-03 0.6250E-01
------- iteration 3
Update # PS points (even): 4160 --> 4160
ABS integral = 0.4395E-03 +/- 0.5719E-05 ( 1.301 %)
Integral = 0.4045E-03 +/- 0.5281E-05 ( 1.306 %)
Virtual = 0.6607E-06 +/- 0.2475E-06 ( 37.456 %)
Virtual ratio = 0.5097E+01 +/- 0.4200E-01 ( 0.824 %)
ABS virtual = 0.2563E-05 +/- 0.2460E-06 ( 9.597 %)
Born*ao2pi = 0.5213E-05 +/- 0.3232E-06 ( 6.199 %)
Chi^2= 0.2589E+01
accumulated results ABS integral = 0.4303E-03 +/- 0.4925E-05 ( 1.144 %)
accumulated results Integral = 0.3990E-03 +/- 0.4600E-05 ( 1.153 %)
accumulated results Virtual = 0.2303E-05 +/- 0.1957E-06 ( 8.497 %)
accumulated results Virtual ratio = 0.5138E+01 +/- 0.1646E-01 ( 0.320 %)
accumulated results ABS virtual = 0.4372E-05 +/- 0.1939E-06 ( 4.434 %)
accumulated results Born*ao2pi = 0.5569E-05 +/- 0.2193E-06 ( 3.939 %)
accumulated result Chi^2 per DoF = 0.1479E+01
1: 0 1 2
channel 1 : 1 T 8320 4160 0.4303E-03 0.3990E-03 0.1562E-01
------- iteration 4
Update # PS points (even): 8320 --> 8320
ABS integral = 0.4422E-03 +/- 0.3546E-05 ( 0.802 %)
Integral = 0.4082E-03 +/- 0.3208E-05 ( 0.786 %)
Virtual = -.7030E-06 +/- 0.5754E-06 ( 81.842 %)
Virtual ratio = 0.4970E+01 +/- 0.7042E-01 ( 1.417 %)
ABS virtual = 0.3590E-05 +/- 0.5747E-06 ( 16.009 %)
Born*ao2pi = 0.5292E-05 +/- 0.4178E-06 ( 7.895 %)
Chi^2= 0.1984E+01
accumulated results ABS integral = 0.4372E-03 +/- 0.2878E-05 ( 0.658 %)
accumulated results Integral = 0.4044E-03 +/- 0.2631E-05 ( 0.651 %)
accumulated results Virtual = 0.1540E-05 +/- 0.1853E-06 ( 12.030 %)
accumulated results Virtual ratio = 0.5106E+01 +/- 0.1603E-01 ( 0.314 %)
accumulated results ABS virtual = 0.4175E-05 +/- 0.1837E-06 ( 4.400 %)
accumulated results Born*ao2pi = 0.5473E-05 +/- 0.1942E-06 ( 3.548 %)
accumulated result Chi^2 per DoF = 0.1647E+01
accumulated results last 3 iterations ABS integral = 0.4383E-03 +/- 0.2889E-05 ( 0.659 %)
accumulated results last 3 iterations Integral = 0.4052E-03 +/- 0.2641E-05 ( 0.652 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.1301E+01
1: 0 1 2
Found desired accuracy
channel 1 : 1 T 16642 8320 0.4372E-03 0.4044E-03 0.5070E-02
-------
Final result [ABS]: 4.3721675613682696E-004 +/- 2.8777972547857651E-006
Final result: 4.0444422364801597E-004 +/- 2.6313909629926319E-006
chi**2 per D.o.F.: 1.6474283670214618
Satistics from MadLoop:
Total points tried: 3369
Stability unknown: 0
Stable PS point: 3369
Unstable PS point (and rescued): 0
Exceptional PS point (unstable and not rescued): 0
Double precision used: 3369
Quadruple precision used: 0
Initialization phase-space points: 0
Unknown return code (100): 0
Unknown return code (10): 0
Unit return code distribution (1):
#Unit 6 = 3369
Time spent in Born : 3.25914741
Time spent in PS_Generation : 0.00000000
Time spent in Reals_evaluation: 13.9685230
Time spent in MCsubtraction : 10.0264072
Time spent in Counter_terms : 7.38569641
Time spent in Integrated_CT : 0.239198208
Time spent in Virtuals : 0.260783613
Time spent in FxFx_cluster : 0.00000000
Time spent in Nbody_prefactor : 3.36753154
Time spent in N1body_prefactor : 3.40364814
Time spent in Adding_alphas_pdf : 0.639984727
Time spent in Reweight_scale : 0.00000000
Time spent in Reweight_pdf : 0.00000000
Time spent in Filling_plots : 0.00000000
Time spent in Applying_cuts : 0.179325581
Time spent in Sum_ident_contr : 5.54771870E-02
Time spent in Pick_unwgt : 0.00000000
Time spent in Write_events : 0.00000000
Time spent in Other_tasks : 1.52951050
Time spent in Total : 44.3152351
Time in seconds: 45
</PRE><br>
<a name=/P0_ddx_zx0_zepemz_no_a/GF2></a>
<font color="red">
<br>LOG file for integration channel /P0_ddx_zx0_zepemz_no_a/GF2, 0 <br></font>
<PRE>
===============================================================
INFO: MadFKS read these parameters from FKS_params.dat
===============================================================
> IRPoleCheckThreshold = 1.0000000000000001E-005
> PrecisionVirtualAtRunTime = 1.0000000000000000E-003
> NHelForMCoverHels = 4
> VirtualFraction = 1.0000000000000000
> MinVirtualFraction = 5.0000000000000001E-003
===============================================================
A PDF is used, so alpha_s(MZ) is going to be modified
Old value of alpha_s from param_card: 0.11799999999999999
****************************************
NNPDFDriver version 1.0.3
Grid: NNPDF23nlo_as_0119_qed_mem0.grid
****************************************
New value of alpha_s from PDF nn23nlo: 0.11899999999999999
*****************************************************
* MadGraph/MadEvent *
* -------------------------------- *
* http://madgraph.hep.uiuc.edu *
* http://madgraph.phys.ucl.ac.be *
* http://madgraph.roma2.infn.it *
* -------------------------------- *
* *
* PARAMETER AND COUPLING VALUES *
* *
*****************************************************
External Params
---------------------------------
MU_R = 91.188000000000002
aEWM1 = 132.50700000000001
mdl_Gf = 1.1663900000000000E-005
aS = 0.11799999999999999
mdl_ymb = 4.7000000000000002
mdl_ymt = 173.00000000000000
mdl_ymtau = 1.7769999999999999
mdl_MT = 173.00000000000000
mdl_MB = 4.7000000000000002
mdl_MZ = 91.188000000000002
mdl_MTA = 1.7769999999999999
mdl_WT = 1.4915000000000000
mdl_WZ = 2.4414039999999999
mdl_WW = 2.0476000000000001
mdl_MX0 = 300.00000000000000
mdl_WX0 = 1.0604700000000000
mdl_Lambda = 5000.0000000000000
mdl_cosa = 1.0000000000000000
mdl_kSM = 5.0000000000000003E-002
mdl_kHtt = 0.0000000000000000
mdl_kAtt = 0.0000000000000000
mdl_kHbb = 0.0000000000000000
mdl_kAbb = 0.0000000000000000
mdl_kHll = 0.0000000000000000
mdl_kAll = 0.0000000000000000
mdl_kHaa = 0.0000000000000000
mdl_kAaa = 0.0000000000000000
mdl_kHza = 0.0000000000000000
mdl_kAza = 0.0000000000000000
mdl_kHzz = 8.1561199999999996
mdl_kAzz = 0.0000000000000000
mdl_kHww = 10.496200000000000
mdl_kAww = 0.0000000000000000
mdl_kHda = 0.0000000000000000
mdl_kHdz = 0.0000000000000000
mdl_kHdwR = 0.0000000000000000
mdl_kHdwI = 0.0000000000000000
Internal Params
---------------------------------
mdl_CKM11 = 1.0000000000000000
mdl_conjg__CKM3x3 = 1.0000000000000000
mdl_conjg__CKM11 = 1.0000000000000000
mdl_lhv = 1.0000000000000000
mdl_CKM3x3 = 1.0000000000000000
mdl_conjg__CKM33 = 1.0000000000000000
mdl_Ncol = 3.0000000000000000
mdl_CA = 3.0000000000000000
mdl_TF = 0.50000000000000000
mdl_CF = 1.3333333333333333
mdl_complexi = ( 0.0000000000000000 , 1.0000000000000000 )
mdl_MZ__exp__2 = 8315.2513440000002
mdl_MZ__exp__4 = 69143404.913893804
mdl_sqrt__2 = 1.4142135623730951
mdl_MX0__exp__2 = 90000.000000000000
mdl_cosa__exp__2 = 1.0000000000000000
mdl_sina = 0.0000000000000000
mdl_kHdw = ( 0.0000000000000000 , 0.0000000000000000 )
mdl_nb__2__exp__0_75 = 1.6817928305074290
mdl_Ncol__exp__2 = 9.0000000000000000
mdl_MB__exp__2 = 22.090000000000003
mdl_MT__exp__2 = 29929.000000000000
mdl_conjg__kHdw = ( 0.0000000000000000 , -0.0000000000000000 )
mdl_aEW = 7.5467711139788835E-003
mdl_MW = 80.419002445756163
mdl_sqrt__aEW = 8.6872153846781555E-002
mdl_ee = 0.30795376724436879
mdl_MW__exp__2 = 6467.2159543705357
mdl_sw2 = 0.22224648578577766
mdl_cw = 0.88190334743339216
mdl_sqrt__sw2 = 0.47143025548407230
mdl_sw = 0.47143025548407230
mdl_g1 = 0.34919219678733299
mdl_gw = 0.65323293034757990
mdl_vev = 246.21845810181637
mdl_vev__exp__2 = 60623.529110035903
mdl_lam = 0.74228605065735920
mdl_yb = 2.6995554250465490E-002
mdl_yt = 0.99366614581500623
mdl_ytau = 1.0206617000654717E-002
mdl_muH = 212.13203435596427
mdl_AxialZUp = -0.18517701861793787
mdl_AxialZDown = 0.18517701861793787
mdl_VectorZUp = 7.5430507588273299E-002
mdl_VectorZDown = -0.13030376310310560
mdl_VectorAUp = 0.20530251149624587
mdl_VectorADown = -0.10265125574812294
mdl_VectorWmDxU = 0.23095271737156670
mdl_AxialWmDxU = -0.23095271737156670
mdl_VectorWpUxD = 0.23095271737156670
mdl_AxialWpUxD = -0.23095271737156670
mdl_I1x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_I2x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I3x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I4x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_Vector_tbGp = (-0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGp = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_Vector_tbGm = ( 0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGm = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_ee__exp__2 = 9.4835522759998875E-002
mdl_gAaa = 1.3008566310666950E-005
mdl_cw__exp__2 = 0.77775351421422245
mdl_gAza = 4.7794971072590281E-006
mdl_gHaa = 2.5475109025056106E-005
mdl_gHza = 3.9182129211851395E-005
mdl_gw__exp__2 = 0.42671326129048615
mdl_sw__exp__2 = 0.22224648578577769
Internal Params evaluated point by point
----------------------------------------
mdl_sqrt__aS = 0.34351128074635334
mdl_G__exp__2 = 1.4828317324943823
mdl_G__exp__4 = 2.1987899468922913
mdl_R2MixedFactor_FIN_ = -2.5040377713124864E-002
mdl_GWcft_UV_b_1EPS_ = -3.1300472141406080E-003
mdl_GWcft_UV_t_1EPS_ = -3.1300472141406080E-003
mdl_bWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_tWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_G__exp__3 = 1.8056676068262196
mdl_MU_R__exp__2 = 8315.2513440000002
mdl_GWcft_UV_b_FIN_ = -1.8563438626678915E-002
mdl_GWcft_UV_t_FIN_ = 4.0087659331150384E-003
mdl_bWcft_UV_FIN_ = -0.13642100947319838
mdl_tWcft_UV_FIN_ = -9.8778211443463623E-004
mdl_gAgg = 7.6274879753643885E-005
mdl_gHgg = -5.0849919835762592E-005
Couplings of HC_NLO_X0_UFO
---------------------------------
R2_UUZ_V2 = -0.00000E+00 -0.72127E-02
R2_UUZ_V5 = 0.00000E+00 0.68702E-03
GC_5 = 0.00000E+00 0.12177E+01
GC_3007a = -0.00000E+00 -0.00000E+00
GC_3007h2 = -0.00000E+00 -0.16312E-02
GC_3007h3 = -0.00000E+00 -0.00000E+00
GC_22 = 0.00000E+00 0.28804E+00
GC_23 = -0.00000E+00 -0.27437E-01
GC_24 = 0.00000E+00 0.82310E-01
GC_3007h1 = 0.00000E+00 0.33772E+01
Collider parameters:
--------------------
Running at P P machine @ 13000.000000000000 GeV
PDF set = nn23nlo
alpha_s(Mz)= 0.1190 running at 2 loops.
alpha_s(Mz)= 0.1190 running at 2 loops.
Renormalization scale set on event-by-event basis
Factorization scale set on event-by-event basis
Diagram information for clustering has been set-up for nFKSprocess 1
Diagram information for clustering has been set-up for nFKSprocess 2
Diagram information for clustering has been set-up for nFKSprocess 3
Diagram information for clustering has been set-up for nFKSprocess 4
getting user params
Enter number of events and iterations:
Number of events and iterations -1 12
Enter desired fractional accuracy:
Desired fractional accuracy: 2.9999999999999999E-002
Enter alpha, beta for G_soft
Enter alpha<0 to set G_soft=1 (no ME soft)
for G_soft: alpha= 1.0000000000000000 , beta= -0.10000000000000001
Enter alpha, beta for G_azi
Enter alpha>0 to set G_azi=0 (no azi corr)
for G_azi: alpha= -1.0000000000000000 , beta= -0.10000000000000001
Doing the S and H events together
Suppress amplitude (0 no, 1 yes)?
Using suppressed amplitude.
Exact helicity sum (0 yes, n = number/event)?
Do MC over helicities for the virtuals
Enter Configuration Number:
Running Configuration Number: 2
Enter running mode for MINT:
0 to set-up grids, 1 to integrate, 2 to generate events
MINT running mode: 0
Set the three folding parameters for MINT
xi_i, phi_i, y_ij
1 1 1
'all ', 'born', 'real', 'virt', 'novi' or 'grid'?
Enter 'born0' or 'virt0' to perform
a pure n-body integration (no S functions)
doing the all of this channel
Normal integration (Sfunction != 1)
about to integrate 13 -1 12 2
imode is 0
channel 1 : 2 T 0 0 0.1000E+01 0.0000E+00 0.1000E+01
+----------------------------------------------------------------+
| |
| Ninja - version 1.2.0 |
| |
| Author: <NAME> |
| |
| Based on: |
| |
| <NAME>, <NAME> and <NAME>, |
| "Integrand reduction of one-loop scattering amplitudes |
| through Laurent series expansion," |
| JHEP 1206 (2012) 095 [arXiv:1203.0291 [hep-ph]]. |
| |
| <NAME>, |
| "Ninja: Automated Integrand Reduction via Laurent |
| Expansion for One-Loop Amplitudes," |
| Comput.Phys.Commun. 185 (2014) [arXiv:1403.1229 [hep-ph]] |
| |
+----------------------------------------------------------------+
------- iteration 1
Update # PS points (even): 1040 --> 1040
Using random seed offsets: 2 , 2 , 0
with seed 34
Ranmar initialization seeds 13169 9410
Total number of FKS directories is 4
FKS process map (sum= 3 ) :
1 --> 2 : 1 3
2 --> 2 : 2 4
================================
process combination map (specified per FKS dir):
1 map 1 2 3 4
1 inv. map 1 2 3 4
2 map 1 2 3 4
2 inv. map 1 2 3 4
3 map 1 2 3 4
3 inv. map 1 2 3 4
4 map 1 2 3 4
4 inv. map 1 2 3 4
================================
tau_min 1 1 : 0.18238E+03 -- 0.39119E+03
tau_min 2 1 : 0.18238E+03 -- 0.39119E+03
tau_min 3 1 : 0.18238E+03 -- 0.39119E+03
tau_min 4 1 : 0.18238E+03 -- 0.39119E+03
bpower is 0.0000000000000000
Scale values (may change event by event):
muR, muR_reference: 0.183302D+03 0.183302D+03 1.00
muF1, muF1_reference: 0.183302D+03 0.183302D+03 1.00
muF2, muF2_reference: 0.183302D+03 0.183302D+03 1.00
QES, QES_reference: 0.183302D+03 0.183302D+03 1.00
muR_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF1_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF2_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
QES_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
alpha_s= 0.10759651900658443
alpha_s value used for the virtuals is (for the first PS point): 0.10759651900658443
==========================================================================================
{ }
{ [32m [0m }
{ [32m ,, [0m }
{ [32m`7MMM. ,MMF' `7MM `7MMF' [0m }
{ [32m MMMb dPMM MM MM [0m }
{ [32m M YM ,M MM ,6"Yb. ,M""bMM MM ,pW"Wq. ,pW"Wq.`7MMpdMAo. [0m }
{ [32m M Mb M' MM 8) MM ,AP MM MM 6W' `Wb 6W' `Wb MM `Wb [0m }
{ [32m M YM.P' MM ,pm9MM 8MI MM MM , 8M M8 8M M8 MM M8 [0m }
{ [32m M `YM' MM 8M MM `Mb MM MM ,M YA. ,A9 YA. ,A9 MM ,AP [0m }
{ [32m.JML. `' .JMML.`Moo9^Yo.`Wbmd"MML..JMMmmmmMMM `Ybmd9' `Ybmd9' MMbmmd' [0m }
{ [32m MM [0m }
{ [32m .JMML. [0m }
{ [32m[0mv2.6.6 (2018-06-28), Ref: arXiv:1103.0621v2, arXiv:1405.0301[32m [0m }
{ [32m [0m }
{ }
==========================================================================================
===============================================================
INFO: MadLoop read these parameters from ../MadLoop5_resources/MadLoopParams.dat
===============================================================
> MLReductionLib = 6|7|1
> CTModeRun = -1
> MLStabThres = 1.0000000000000000E-003
> NRotations_DP = 0
> NRotations_QP = 0
> CTStabThres = 1.0000000000000000E-002
> CTLoopLibrary = 2
> CTModeInit = 1
> CheckCycle = 3
> MaxAttempts = 10
> UseLoopFilter = F
> HelicityFilterLevel = 2
> ImprovePSPoint = 2
> DoubleCheckHelicityFilter = T
> LoopInitStartOver = F
> HelInitStartOver = F
> ZeroThres = 1.0000000000000001E-009
> OSThres = 1.0000000000000000E-008
> WriteOutFilters = T
> UseQPIntegrandForNinja = T
> UseQPIntegrandForCutTools = T
> IREGIMODE = 2
> IREGIRECY = T
> COLLIERMode = 1
> COLLIERRequiredAccuracy = 1.0000000000000000E-008
> COLLIERCanOutput = F
> COLLIERComputeUVpoles = T
> COLLIERComputeIRpoles = T
> COLLIERGlobalCache = -1
> COLLIERUseCacheForPoles = F
> COLLIERUseInternalStabilityTest = T
===============================================================
------------------------------------------------------------------------
| You are using CutTools - Version 1.9.3 |
| Authors: <NAME>, <NAME>, <NAME> |
| Published in JHEP 0803:042,2008 |
| http://www.ugr.es/~pittau/CutTools |
| |
| Compiler with 34 significant digits detetected |
----------------------------------------------------------------------
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
---- POLES CANCELLED ----
ABS integral = 0.8187E-03 +/- 0.5713E-04 ( 6.978 %)
Integral = 0.7607E-03 +/- 0.5501E-04 ( 7.232 %)
Virtual = 0.5287E-04 +/- 0.3809E-05 ( 7.205 %)
Virtual ratio = 0.5215E+01 +/- 0.2017E-01 ( 0.387 %)
ABS virtual = 0.5332E-04 +/- 0.3806E-05 ( 7.138 %)
Born*ao2pi = 0.1068E-04 +/- 0.7813E-06 ( 7.316 %)
Chi^2 per d.o.f. 0.0000E+00
accumulated results ABS integral = 0.8187E-03 +/- 0.5713E-04 ( 6.978 %)
accumulated results Integral = 0.7607E-03 +/- 0.5501E-04 ( 7.232 %)
accumulated results Virtual = 0.5287E-04 +/- 0.3809E-05 ( 7.205 %)
accumulated results Virtual ratio = 0.5215E+01 +/- 0.2017E-01 ( 0.387 %)
accumulated results ABS virtual = 0.5332E-04 +/- 0.3806E-05 ( 7.138 %)
accumulated results Born*ao2pi = 0.1068E-04 +/- 0.7813E-06 ( 7.316 %)
accumulated result Chi^2 per DoF = 0.0000E+00
1: 0 1 2
channel 1 : 2 T 2080 0 0.8187E-03 0.7607E-03 0.2500E+00
------- iteration 2
Update # PS points (even): 2080 --> 2080
ABS integral = 0.8495E-03 +/- 0.1801E-04 ( 2.120 %)
Integral = 0.7922E-03 +/- 0.1739E-04 ( 2.195 %)
Virtual = 0.4196E-06 +/- 0.6802E-06 ( 162.088 %)
Virtual ratio = 0.5024E+01 +/- 0.4339E-01 ( 0.864 %)
ABS virtual = 0.6073E-05 +/- 0.6737E-06 ( 11.093 %)
Born*ao2pi = 0.1044E-04 +/- 0.5417E-06 ( 5.190 %)
Chi^2= 0.1680E+00
accumulated results ABS integral = 0.8421E-03 +/- 0.1717E-04 ( 2.039 %)
accumulated results Integral = 0.7846E-03 +/- 0.1658E-04 ( 2.113 %)
accumulated results Virtual = 0.8367E-05 +/- 0.6696E-06 ( 8.003 %)
accumulated results Virtual ratio = 0.5155E+01 +/- 0.1829E-01 ( 0.355 %)
accumulated results ABS virtual = 0.1318E-04 +/- 0.6634E-06 ( 5.034 %)
accumulated results Born*ao2pi = 0.1054E-04 +/- 0.4452E-06 ( 4.225 %)
accumulated result Chi^2 per DoF = 0.1680E+00
1: 0 1 2
channel 1 : 2 T 4160 2080 0.8421E-03 0.7846E-03 0.6250E-01
------- iteration 3
Update # PS points (even): 4160 --> 4160
ABS integral = 0.8618E-03 +/- 0.1115E-04 ( 1.294 %)
Integral = 0.8027E-03 +/- 0.1082E-04 ( 1.348 %)
Virtual = -.2061E-05 +/- 0.1052E-05 ( 51.051 %)
Virtual ratio = 0.4975E+01 +/- 0.5076E-01 ( 1.020 %)
ABS virtual = 0.7707E-05 +/- 0.1049E-05 ( 13.612 %)
Born*ao2pi = 0.1079E-04 +/- 0.6727E-06 ( 6.235 %)
Chi^2= 0.4805E+00
accumulated results ABS integral = 0.8540E-03 +/- 0.9355E-05 ( 1.095 %)
accumulated results Integral = 0.7956E-03 +/- 0.9060E-05 ( 1.139 %)
accumulated results Virtual = 0.4311E-05 +/- 0.5649E-06 ( 13.103 %)
accumulated results Virtual ratio = 0.5107E+01 +/- 0.1721E-01 ( 0.337 %)
accumulated results ABS virtual = 0.1106E-04 +/- 0.5607E-06 ( 5.070 %)
accumulated results Born*ao2pi = 0.1064E-04 +/- 0.3712E-06 ( 3.490 %)
accumulated result Chi^2 per DoF = 0.3242E+00
1: 0 1 2
channel 1 : 2 T 8320 4160 0.8540E-03 0.7956E-03 0.1562E-01
------- iteration 4
Update # PS points (even): 8320 --> 8320
ABS integral = 0.8517E-03 +/- 0.5616E-05 ( 0.659 %)
Integral = 0.7883E-03 +/- 0.5178E-05 ( 0.657 %)
Virtual = 0.7708E-06 +/- 0.9514E-06 ( 123.436 %)
Virtual ratio = 0.5013E+01 +/- 0.7763E-01 ( 1.549 %)
ABS virtual = 0.6671E-05 +/- 0.9500E-06 ( 14.241 %)
Born*ao2pi = 0.1076E-04 +/- 0.7834E-06 ( 7.280 %)
Chi^2= 0.2471E-01
accumulated results ABS integral = 0.8526E-03 +/- 0.4815E-05 ( 0.565 %)
accumulated results Integral = 0.7909E-03 +/- 0.4495E-05 ( 0.568 %)
accumulated results Virtual = 0.2992E-05 +/- 0.4857E-06 ( 16.233 %)
accumulated results Virtual ratio = 0.5090E+01 +/- 0.1680E-01 ( 0.330 %)
accumulated results ABS virtual = 0.9430E-05 +/- 0.4829E-06 ( 5.120 %)
accumulated results Born*ao2pi = 0.1068E-04 +/- 0.3355E-06 ( 3.142 %)
accumulated result Chi^2 per DoF = 0.2244E+00
accumulated results last 3 iterations ABS integral = 0.8537E-03 +/- 0.4832E-05 ( 0.566 %)
accumulated results last 3 iterations Integral = 0.7920E-03 +/- 0.4510E-05 ( 0.569 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.1522E+00
1: 0 1 2
Found desired accuracy
channel 1 : 2 T 16637 8320 0.8526E-03 0.7909E-03 0.5294E-02
-------
Final result [ABS]: 8.5256316445060914E-004 +/- 4.8149454157702134E-006
Final result: 7.9093937940868323E-004 +/- 4.4954025175488180E-006
chi**2 per D.o.F.: 0.22438230160429218
Satistics from MadLoop:
Total points tried: 3295
Stability unknown: 0
Stable PS point: 3295
Unstable PS point (and rescued): 0
Exceptional PS point (unstable and not rescued): 0
Double precision used: 3295
Quadruple precision used: 0
Initialization phase-space points: 0
Unknown return code (100): 0
Unknown return code (10): 0
Unit return code distribution (1):
#Unit 6 = 3295
Time spent in Born : 3.31179667
Time spent in PS_Generation : 0.00000000
Time spent in Reals_evaluation: 14.1898899
Time spent in MCsubtraction : 10.1271725
Time spent in Counter_terms : 7.53523540
Time spent in Integrated_CT : 0.243765682
Time spent in Virtuals : 0.260209769
Time spent in FxFx_cluster : 0.00000000
Time spent in Nbody_prefactor : 3.45504022
Time spent in N1body_prefactor : 3.45714521
Time spent in Adding_alphas_pdf : 0.679253161
Time spent in Reweight_scale : 0.00000000
Time spent in Reweight_pdf : 0.00000000
Time spent in Filling_plots : 0.00000000
Time spent in Applying_cuts : 0.184831753
Time spent in Sum_ident_contr : 5.80444783E-02
Time spent in Pick_unwgt : 0.00000000
Time spent in Write_events : 0.00000000
Time spent in Other_tasks : 1.54787064
Time spent in Total : 45.0502586
Time in seconds: 45
</PRE><br>
<a name=/P0_uxu_zx0_zepemz_no_a/GF1></a>
<font color="red">
<br>LOG file for integration channel /P0_uxu_zx0_zepemz_no_a/GF1, 0 <br></font>
<PRE>
===============================================================
INFO: MadFKS read these parameters from FKS_params.dat
===============================================================
> IRPoleCheckThreshold = 1.0000000000000001E-005
> PrecisionVirtualAtRunTime = 1.0000000000000000E-003
> NHelForMCoverHels = 4
> VirtualFraction = 1.0000000000000000
> MinVirtualFraction = 5.0000000000000001E-003
===============================================================
A PDF is used, so alpha_s(MZ) is going to be modified
Old value of alpha_s from param_card: 0.11799999999999999
****************************************
NNPDFDriver version 1.0.3
Grid: NNPDF23nlo_as_0119_qed_mem0.grid
****************************************
New value of alpha_s from PDF nn23nlo: 0.11899999999999999
*****************************************************
* MadGraph/MadEvent *
* -------------------------------- *
* http://madgraph.hep.uiuc.edu *
* http://madgraph.phys.ucl.ac.be *
* http://madgraph.roma2.infn.it *
* -------------------------------- *
* *
* PARAMETER AND COUPLING VALUES *
* *
*****************************************************
External Params
---------------------------------
MU_R = 91.188000000000002
aEWM1 = 132.50700000000001
mdl_Gf = 1.1663900000000000E-005
aS = 0.11799999999999999
mdl_ymb = 4.7000000000000002
mdl_ymt = 173.00000000000000
mdl_ymtau = 1.7769999999999999
mdl_MT = 173.00000000000000
mdl_MB = 4.7000000000000002
mdl_MZ = 91.188000000000002
mdl_MTA = 1.7769999999999999
mdl_WT = 1.4915000000000000
mdl_WZ = 2.4414039999999999
mdl_WW = 2.0476000000000001
mdl_MX0 = 300.00000000000000
mdl_WX0 = 1.0604700000000000
mdl_Lambda = 5000.0000000000000
mdl_cosa = 1.0000000000000000
mdl_kSM = 5.0000000000000003E-002
mdl_kHtt = 0.0000000000000000
mdl_kAtt = 0.0000000000000000
mdl_kHbb = 0.0000000000000000
mdl_kAbb = 0.0000000000000000
mdl_kHll = 0.0000000000000000
mdl_kAll = 0.0000000000000000
mdl_kHaa = 0.0000000000000000
mdl_kAaa = 0.0000000000000000
mdl_kHza = 0.0000000000000000
mdl_kAza = 0.0000000000000000
mdl_kHzz = 8.1561199999999996
mdl_kAzz = 0.0000000000000000
mdl_kHww = 10.496200000000000
mdl_kAww = 0.0000000000000000
mdl_kHda = 0.0000000000000000
mdl_kHdz = 0.0000000000000000
mdl_kHdwR = 0.0000000000000000
mdl_kHdwI = 0.0000000000000000
Internal Params
---------------------------------
mdl_CKM11 = 1.0000000000000000
mdl_conjg__CKM3x3 = 1.0000000000000000
mdl_conjg__CKM11 = 1.0000000000000000
mdl_lhv = 1.0000000000000000
mdl_CKM3x3 = 1.0000000000000000
mdl_conjg__CKM33 = 1.0000000000000000
mdl_Ncol = 3.0000000000000000
mdl_CA = 3.0000000000000000
mdl_TF = 0.50000000000000000
mdl_CF = 1.3333333333333333
mdl_complexi = ( 0.0000000000000000 , 1.0000000000000000 )
mdl_MZ__exp__2 = 8315.2513440000002
mdl_MZ__exp__4 = 69143404.913893804
mdl_sqrt__2 = 1.4142135623730951
mdl_MX0__exp__2 = 90000.000000000000
mdl_cosa__exp__2 = 1.0000000000000000
mdl_sina = 0.0000000000000000
mdl_kHdw = ( 0.0000000000000000 , 0.0000000000000000 )
mdl_nb__2__exp__0_75 = 1.6817928305074290
mdl_Ncol__exp__2 = 9.0000000000000000
mdl_MB__exp__2 = 22.090000000000003
mdl_MT__exp__2 = 29929.000000000000
mdl_conjg__kHdw = ( 0.0000000000000000 , -0.0000000000000000 )
mdl_aEW = 7.5467711139788835E-003
mdl_MW = 80.419002445756163
mdl_sqrt__aEW = 8.6872153846781555E-002
mdl_ee = 0.30795376724436879
mdl_MW__exp__2 = 6467.2159543705357
mdl_sw2 = 0.22224648578577766
mdl_cw = 0.88190334743339216
mdl_sqrt__sw2 = 0.47143025548407230
mdl_sw = 0.47143025548407230
mdl_g1 = 0.34919219678733299
mdl_gw = 0.65323293034757990
mdl_vev = 246.21845810181637
mdl_vev__exp__2 = 60623.529110035903
mdl_lam = 0.74228605065735920
mdl_yb = 2.6995554250465490E-002
mdl_yt = 0.99366614581500623
mdl_ytau = 1.0206617000654717E-002
mdl_muH = 212.13203435596427
mdl_AxialZUp = -0.18517701861793787
mdl_AxialZDown = 0.18517701861793787
mdl_VectorZUp = 7.5430507588273299E-002
mdl_VectorZDown = -0.13030376310310560
mdl_VectorAUp = 0.20530251149624587
mdl_VectorADown = -0.10265125574812294
mdl_VectorWmDxU = 0.23095271737156670
mdl_AxialWmDxU = -0.23095271737156670
mdl_VectorWpUxD = 0.23095271737156670
mdl_AxialWpUxD = -0.23095271737156670
mdl_I1x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_I2x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I3x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I4x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_Vector_tbGp = (-0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGp = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_Vector_tbGm = ( 0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGm = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_ee__exp__2 = 9.4835522759998875E-002
mdl_gAaa = 1.3008566310666950E-005
mdl_cw__exp__2 = 0.77775351421422245
mdl_gAza = 4.7794971072590281E-006
mdl_gHaa = 2.5475109025056106E-005
mdl_gHza = 3.9182129211851395E-005
mdl_gw__exp__2 = 0.42671326129048615
mdl_sw__exp__2 = 0.22224648578577769
Internal Params evaluated point by point
----------------------------------------
mdl_sqrt__aS = 0.34351128074635334
mdl_G__exp__2 = 1.4828317324943823
mdl_G__exp__4 = 2.1987899468922913
mdl_R2MixedFactor_FIN_ = -2.5040377713124864E-002
mdl_GWcft_UV_b_1EPS_ = -3.1300472141406080E-003
mdl_GWcft_UV_t_1EPS_ = -3.1300472141406080E-003
mdl_bWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_tWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_G__exp__3 = 1.8056676068262196
mdl_MU_R__exp__2 = 8315.2513440000002
mdl_GWcft_UV_b_FIN_ = -1.8563438626678915E-002
mdl_GWcft_UV_t_FIN_ = 4.0087659331150384E-003
mdl_bWcft_UV_FIN_ = -0.13642100947319838
mdl_tWcft_UV_FIN_ = -9.8778211443463623E-004
mdl_gAgg = 7.6274879753643885E-005
mdl_gHgg = -5.0849919835762592E-005
Couplings of HC_NLO_X0_UFO
---------------------------------
R2_UUZ_V2 = -0.00000E+00 -0.72127E-02
R2_UUZ_V5 = 0.00000E+00 0.68702E-03
GC_5 = 0.00000E+00 0.12177E+01
GC_3007a = -0.00000E+00 -0.00000E+00
GC_3007h2 = -0.00000E+00 -0.16312E-02
GC_3007h3 = -0.00000E+00 -0.00000E+00
GC_22 = 0.00000E+00 0.28804E+00
GC_23 = -0.00000E+00 -0.27437E-01
GC_24 = 0.00000E+00 0.82310E-01
GC_3007h1 = 0.00000E+00 0.33772E+01
Collider parameters:
--------------------
Running at P P machine @ 13000.000000000000 GeV
PDF set = nn23nlo
alpha_s(Mz)= 0.1190 running at 2 loops.
alpha_s(Mz)= 0.1190 running at 2 loops.
Renormalization scale set on event-by-event basis
Factorization scale set on event-by-event basis
Diagram information for clustering has been set-up for nFKSprocess 1
Diagram information for clustering has been set-up for nFKSprocess 2
Diagram information for clustering has been set-up for nFKSprocess 3
Diagram information for clustering has been set-up for nFKSprocess 4
getting user params
Enter number of events and iterations:
Number of events and iterations -1 12
Enter desired fractional accuracy:
Desired fractional accuracy: 2.9999999999999999E-002
Enter alpha, beta for G_soft
Enter alpha<0 to set G_soft=1 (no ME soft)
for G_soft: alpha= 1.0000000000000000 , beta= -0.10000000000000001
Enter alpha, beta for G_azi
Enter alpha>0 to set G_azi=0 (no azi corr)
for G_azi: alpha= -1.0000000000000000 , beta= -0.10000000000000001
Doing the S and H events together
Suppress amplitude (0 no, 1 yes)?
Using suppressed amplitude.
Exact helicity sum (0 yes, n = number/event)?
Do MC over helicities for the virtuals
Enter Configuration Number:
Running Configuration Number: 1
Enter running mode for MINT:
0 to set-up grids, 1 to integrate, 2 to generate events
MINT running mode: 0
Set the three folding parameters for MINT
xi_i, phi_i, y_ij
1 1 1
'all ', 'born', 'real', 'virt', 'novi' or 'grid'?
Enter 'born0' or 'virt0' to perform
a pure n-body integration (no S functions)
doing the all of this channel
Normal integration (Sfunction != 1)
about to integrate 13 -1 12 1
imode is 0
channel 1 : 1 T 0 0 0.1000E+01 0.0000E+00 0.1000E+01
+----------------------------------------------------------------+
| |
| Ninja - version 1.2.0 |
| |
| Author: <NAME> |
| |
| Based on: |
| |
| <NAME>, <NAME> and <NAME>, |
| "Integrand reduction of one-loop scattering amplitudes |
| through Laurent series expansion," |
| JHEP 1206 (2012) 095 [arXiv:1203.0291 [hep-ph]]. |
| |
| <NAME>, |
| "Ninja: Automated Integrand Reduction via Laurent |
| Expansion for One-Loop Amplitudes," |
| Comput.Phys.Commun. 185 (2014) [arXiv:1403.1229 [hep-ph]] |
| |
+----------------------------------------------------------------+
------- iteration 1
Update # PS points (even): 1040 --> 1040
Using random seed offsets: 1 , 3 , 0
with seed 34
Ranmar initialization seeds 13168 9411
Total number of FKS directories is 4
FKS process map (sum= 3 ) :
1 --> 2 : 1 3
2 --> 2 : 2 4
================================
process combination map (specified per FKS dir):
1 map 1 2 3 4
1 inv. map 1 2 3 4
2 map 1 2 3 4
2 inv. map 1 2 3 4
3 map 1 2 3 4
3 inv. map 1 2 3 4
4 map 1 2 3 4
4 inv. map 1 2 3 4
================================
tau_min 1 1 : 0.18238E+03 -- 0.39119E+03
tau_min 2 1 : 0.18238E+03 -- 0.39119E+03
tau_min 3 1 : 0.18238E+03 -- 0.39119E+03
tau_min 4 1 : 0.18238E+03 -- 0.39119E+03
bpower is 0.0000000000000000
Scale values (may change event by event):
muR, muR_reference: 0.292151D+03 0.292151D+03 1.00
muF1, muF1_reference: 0.292151D+03 0.292151D+03 1.00
muF2, muF2_reference: 0.292151D+03 0.292151D+03 1.00
QES, QES_reference: 0.292151D+03 0.292151D+03 1.00
muR_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF1_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF2_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
QES_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
alpha_s= 0.10114732928415542
alpha_s value used for the virtuals is (for the first PS point): 0.10114732928415542
==========================================================================================
{ }
{ [32m [0m }
{ [32m ,, [0m }
{ [32m`7MMM. ,MMF' `7MM `7MMF' [0m }
{ [32m MMMb dPMM MM MM [0m }
{ [32m M YM ,M MM ,6"Yb. ,M""bMM MM ,pW"Wq. ,pW"Wq.`7MMpdMAo. [0m }
{ [32m M Mb M' MM 8) MM ,AP MM MM 6W' `Wb 6W' `Wb MM `Wb [0m }
{ [32m M YM.P' MM ,pm9MM 8MI MM MM , 8M M8 8M M8 MM M8 [0m }
{ [32m M `YM' MM 8M MM `Mb MM MM ,M YA. ,A9 YA. ,A9 MM ,AP [0m }
{ [32m.JML. `' .JMML.`Moo9^Yo.`Wbmd"MML..JMMmmmmMMM `Ybmd9' `Ybmd9' MMbmmd' [0m }
{ [32m MM [0m }
{ [32m .JMML. [0m }
{ [32m[0mv2.6.6 (2018-06-28), Ref: arXiv:1103.0621v2, arXiv:1405.0301[32m [0m }
{ [32m [0m }
{ }
==========================================================================================
===============================================================
INFO: MadLoop read these parameters from ../MadLoop5_resources/MadLoopParams.dat
===============================================================
> MLReductionLib = 6|7|1
> CTModeRun = -1
> MLStabThres = 1.0000000000000000E-003
> NRotations_DP = 0
> NRotations_QP = 0
> CTStabThres = 1.0000000000000000E-002
> CTLoopLibrary = 2
> CTModeInit = 1
> CheckCycle = 3
> MaxAttempts = 10
> UseLoopFilter = F
> HelicityFilterLevel = 2
> ImprovePSPoint = 2
> DoubleCheckHelicityFilter = T
> LoopInitStartOver = F
> HelInitStartOver = F
> ZeroThres = 1.0000000000000001E-009
> OSThres = 1.0000000000000000E-008
> WriteOutFilters = T
> UseQPIntegrandForNinja = T
> UseQPIntegrandForCutTools = T
> IREGIMODE = 2
> IREGIRECY = T
> COLLIERMode = 1
> COLLIERRequiredAccuracy = 1.0000000000000000E-008
> COLLIERCanOutput = F
> COLLIERComputeUVpoles = T
> COLLIERComputeIRpoles = T
> COLLIERGlobalCache = -1
> COLLIERUseCacheForPoles = F
> COLLIERUseInternalStabilityTest = T
===============================================================
------------------------------------------------------------------------
| You are using CutTools - Version 1.9.3 |
| Authors: <NAME>, <NAME>, <NAME> |
| Published in JHEP 0803:042,2008 |
| http://www.ugr.es/~pittau/CutTools |
| |
| Compiler with 34 significant digits detetected |
----------------------------------------------------------------------
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
---- POLES CANCELLED ----
ABS integral = 0.5968E-03 +/- 0.4651E-04 ( 7.794 %)
Integral = 0.5545E-03 +/- 0.4509E-04 ( 8.131 %)
Virtual = 0.3555E-04 +/- 0.2866E-05 ( 8.062 %)
Virtual ratio = 0.5195E+01 +/- 0.2075E-01 ( 0.399 %)
ABS virtual = 0.3711E-04 +/- 0.2856E-05 ( 7.696 %)
Born*ao2pi = 0.7627E-05 +/- 0.6189E-06 ( 8.115 %)
Chi^2 per d.o.f. 0.0000E+00
accumulated results ABS integral = 0.5968E-03 +/- 0.4651E-04 ( 7.794 %)
accumulated results Integral = 0.5545E-03 +/- 0.4509E-04 ( 8.131 %)
accumulated results Virtual = 0.3555E-04 +/- 0.2866E-05 ( 8.062 %)
accumulated results Virtual ratio = 0.5195E+01 +/- 0.2075E-01 ( 0.399 %)
accumulated results ABS virtual = 0.3711E-04 +/- 0.2856E-05 ( 7.696 %)
accumulated results Born*ao2pi = 0.7627E-05 +/- 0.6189E-06 ( 8.115 %)
accumulated result Chi^2 per DoF = 0.0000E+00
1: 0 1 2
channel 1 : 1 T 2080 0 0.5968E-03 0.5545E-03 0.2500E+00
------- iteration 2
Update # PS points (even): 2080 --> 2080
ABS integral = 0.5286E-03 +/- 0.1149E-04 ( 2.174 %)
Integral = 0.4896E-03 +/- 0.1098E-04 ( 2.243 %)
Virtual = 0.2156E-05 +/- 0.4253E-06 ( 19.725 %)
Virtual ratio = 0.5038E+01 +/- 0.3850E-01 ( 0.764 %)
ABS virtual = 0.5099E-05 +/- 0.4192E-06 ( 8.220 %)
Born*ao2pi = 0.6907E-05 +/- 0.3642E-06 ( 5.273 %)
Chi^2= 0.1381E+01
accumulated results ABS integral = 0.5421E-03 +/- 0.1116E-04 ( 2.058 %)
accumulated results Integral = 0.5023E-03 +/- 0.1067E-04 ( 2.125 %)
accumulated results Virtual = 0.6471E-05 +/- 0.4206E-06 ( 6.501 %)
accumulated results Virtual ratio = 0.5140E+01 +/- 0.1827E-01 ( 0.355 %)
accumulated results ABS virtual = 0.9196E-05 +/- 0.4147E-06 ( 4.510 %)
accumulated results Born*ao2pi = 0.7174E-05 +/- 0.3139E-06 ( 4.375 %)
accumulated result Chi^2 per DoF = 0.1381E+01
1: 0 1 2
channel 1 : 1 T 4160 2080 0.5421E-03 0.5023E-03 0.6250E-01
------- iteration 3
Update # PS points (even): 4160 --> 4160
ABS integral = 0.5488E-03 +/- 0.1820E-04 ( 3.316 %)
Integral = 0.5098E-03 +/- 0.1795E-04 ( 3.522 %)
Virtual = 0.4982E-07 +/- 0.5645E-06 ( ******* %)
Virtual ratio = 0.4979E+01 +/- 0.4706E-01 ( 0.945 %)
ABS virtual = 0.5891E-05 +/- 0.5608E-06 ( 9.520 %)
Born*ao2pi = 0.7797E-05 +/- 0.5021E-06 ( 6.440 %)
Chi^2= 0.5180E-01
accumulated results ABS integral = 0.5447E-03 +/- 0.9510E-05 ( 1.746 %)
accumulated results Integral = 0.5051E-03 +/- 0.9174E-05 ( 1.816 %)
accumulated results Virtual = 0.3729E-05 +/- 0.3373E-06 ( 9.045 %)
accumulated results Virtual ratio = 0.5095E+01 +/- 0.1703E-01 ( 0.334 %)
accumulated results ABS virtual = 0.7791E-05 +/- 0.3334E-06 ( 4.280 %)
accumulated results Born*ao2pi = 0.7413E-05 +/- 0.2662E-06 ( 3.590 %)
accumulated result Chi^2 per DoF = 0.7166E+00
1: 0 1 2
channel 1 : 1 T 8320 4160 0.5447E-03 0.5051E-03 0.1562E-01
------- iteration 4
Update # PS points (even): 8320 --> 8320
ABS integral = 0.5261E-03 +/- 0.5646E-05 ( 1.073 %)
Integral = 0.4847E-03 +/- 0.4829E-05 ( 0.996 %)
Virtual = 0.1424E-05 +/- 0.4059E-06 ( 28.504 %)
Virtual ratio = 0.5123E+01 +/- 0.5708E-01 ( 1.114 %)
ABS virtual = 0.3560E-05 +/- 0.4051E-06 ( 11.378 %)
Born*ao2pi = 0.6415E-05 +/- 0.4820E-06 ( 7.514 %)
Chi^2= 0.1494E+01
accumulated results ABS integral = 0.5330E-03 +/- 0.4855E-05 ( 0.911 %)
accumulated results Integral = 0.4917E-03 +/- 0.4273E-05 ( 0.869 %)
accumulated results Virtual = 0.2683E-05 +/- 0.2594E-06 ( 9.669 %)
accumulated results Virtual ratio = 0.5101E+01 +/- 0.1632E-01 ( 0.320 %)
accumulated results ABS virtual = 0.5881E-05 +/- 0.2574E-06 ( 4.378 %)
accumulated results Born*ao2pi = 0.7058E-05 +/- 0.2330E-06 ( 3.301 %)
accumulated result Chi^2 per DoF = 0.9758E+00
accumulated results last 3 iterations ABS integral = 0.5299E-03 +/- 0.4882E-05 ( 0.921 %)
accumulated results last 3 iterations Integral = 0.4890E-03 +/- 0.4292E-05 ( 0.878 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.4557E+00
1: 0 1 2
Found desired accuracy
channel 1 : 1 T 16634 8320 0.5330E-03 0.4917E-03 0.5000E-02
-------
Final result [ABS]: 5.3303827585267653E-004 +/- 4.8550554921196801E-006
Final result: 4.9174374883373536E-004 +/- 4.2727969051743965E-006
chi**2 per D.o.F.: 0.97577301743949896
Satistics from MadLoop:
Total points tried: 3401
Stability unknown: 0
Stable PS point: 3401
Unstable PS point (and rescued): 0
Exceptional PS point (unstable and not rescued): 0
Double precision used: 3401
Quadruple precision used: 0
Initialization phase-space points: 0
Unknown return code (100): 0
Unknown return code (10): 0
Unit return code distribution (1):
#Unit 6 = 3401
Time spent in Born : 3.25215173
Time spent in PS_Generation : 0.00000000
Time spent in Reals_evaluation: 14.0027113
Time spent in MCsubtraction : 9.75164509
Time spent in Counter_terms : 7.44129372
Time spent in Integrated_CT : 0.243600398
Time spent in Virtuals : 0.266637057
Time spent in FxFx_cluster : 0.00000000
Time spent in Nbody_prefactor : 3.35723758
Time spent in N1body_prefactor : 3.40452337
Time spent in Adding_alphas_pdf : 0.657151759
Time spent in Reweight_scale : 0.00000000
Time spent in Reweight_pdf : 0.00000000
Time spent in Filling_plots : 0.00000000
Time spent in Applying_cuts : 0.182355821
Time spent in Sum_ident_contr : 5.69117516E-02
Time spent in Pick_unwgt : 0.00000000
Time spent in Write_events : 0.00000000
Time spent in Other_tasks : 1.52748489
Time spent in Total : 44.1436996
Time in seconds: 44
</PRE><br>
<a name=/P0_uxu_zx0_zepemz_no_a/GF2></a>
<font color="red">
<br>LOG file for integration channel /P0_uxu_zx0_zepemz_no_a/GF2, 0 <br></font>
<PRE>
===============================================================
INFO: MadFKS read these parameters from FKS_params.dat
===============================================================
> IRPoleCheckThreshold = 1.0000000000000001E-005
> PrecisionVirtualAtRunTime = 1.0000000000000000E-003
> NHelForMCoverHels = 4
> VirtualFraction = 1.0000000000000000
> MinVirtualFraction = 5.0000000000000001E-003
===============================================================
A PDF is used, so alpha_s(MZ) is going to be modified
Old value of alpha_s from param_card: 0.11799999999999999
****************************************
NNPDFDriver version 1.0.3
Grid: NNPDF23nlo_as_0119_qed_mem0.grid
****************************************
New value of alpha_s from PDF nn23nlo: 0.11899999999999999
*****************************************************
* MadGraph/MadEvent *
* -------------------------------- *
* http://madgraph.hep.uiuc.edu *
* http://madgraph.phys.ucl.ac.be *
* http://madgraph.roma2.infn.it *
* -------------------------------- *
* *
* PARAMETER AND COUPLING VALUES *
* *
*****************************************************
External Params
---------------------------------
MU_R = 91.188000000000002
aEWM1 = 132.50700000000001
mdl_Gf = 1.1663900000000000E-005
aS = 0.11799999999999999
mdl_ymb = 4.7000000000000002
mdl_ymt = 173.00000000000000
mdl_ymtau = 1.7769999999999999
mdl_MT = 173.00000000000000
mdl_MB = 4.7000000000000002
mdl_MZ = 91.188000000000002
mdl_MTA = 1.7769999999999999
mdl_WT = 1.4915000000000000
mdl_WZ = 2.4414039999999999
mdl_WW = 2.0476000000000001
mdl_MX0 = 300.00000000000000
mdl_WX0 = 1.0604700000000000
mdl_Lambda = 5000.0000000000000
mdl_cosa = 1.0000000000000000
mdl_kSM = 5.0000000000000003E-002
mdl_kHtt = 0.0000000000000000
mdl_kAtt = 0.0000000000000000
mdl_kHbb = 0.0000000000000000
mdl_kAbb = 0.0000000000000000
mdl_kHll = 0.0000000000000000
mdl_kAll = 0.0000000000000000
mdl_kHaa = 0.0000000000000000
mdl_kAaa = 0.0000000000000000
mdl_kHza = 0.0000000000000000
mdl_kAza = 0.0000000000000000
mdl_kHzz = 8.1561199999999996
mdl_kAzz = 0.0000000000000000
mdl_kHww = 10.496200000000000
mdl_kAww = 0.0000000000000000
mdl_kHda = 0.0000000000000000
mdl_kHdz = 0.0000000000000000
mdl_kHdwR = 0.0000000000000000
mdl_kHdwI = 0.0000000000000000
Internal Params
---------------------------------
mdl_CKM11 = 1.0000000000000000
mdl_conjg__CKM3x3 = 1.0000000000000000
mdl_conjg__CKM11 = 1.0000000000000000
mdl_lhv = 1.0000000000000000
mdl_CKM3x3 = 1.0000000000000000
mdl_conjg__CKM33 = 1.0000000000000000
mdl_Ncol = 3.0000000000000000
mdl_CA = 3.0000000000000000
mdl_TF = 0.50000000000000000
mdl_CF = 1.3333333333333333
mdl_complexi = ( 0.0000000000000000 , 1.0000000000000000 )
mdl_MZ__exp__2 = 8315.2513440000002
mdl_MZ__exp__4 = 69143404.913893804
mdl_sqrt__2 = 1.4142135623730951
mdl_MX0__exp__2 = 90000.000000000000
mdl_cosa__exp__2 = 1.0000000000000000
mdl_sina = 0.0000000000000000
mdl_kHdw = ( 0.0000000000000000 , 0.0000000000000000 )
mdl_nb__2__exp__0_75 = 1.6817928305074290
mdl_Ncol__exp__2 = 9.0000000000000000
mdl_MB__exp__2 = 22.090000000000003
mdl_MT__exp__2 = 29929.000000000000
mdl_conjg__kHdw = ( 0.0000000000000000 , -0.0000000000000000 )
mdl_aEW = 7.5467711139788835E-003
mdl_MW = 80.419002445756163
mdl_sqrt__aEW = 8.6872153846781555E-002
mdl_ee = 0.30795376724436879
mdl_MW__exp__2 = 6467.2159543705357
mdl_sw2 = 0.22224648578577766
mdl_cw = 0.88190334743339216
mdl_sqrt__sw2 = 0.47143025548407230
mdl_sw = 0.47143025548407230
mdl_g1 = 0.34919219678733299
mdl_gw = 0.65323293034757990
mdl_vev = 246.21845810181637
mdl_vev__exp__2 = 60623.529110035903
mdl_lam = 0.74228605065735920
mdl_yb = 2.6995554250465490E-002
mdl_yt = 0.99366614581500623
mdl_ytau = 1.0206617000654717E-002
mdl_muH = 212.13203435596427
mdl_AxialZUp = -0.18517701861793787
mdl_AxialZDown = 0.18517701861793787
mdl_VectorZUp = 7.5430507588273299E-002
mdl_VectorZDown = -0.13030376310310560
mdl_VectorAUp = 0.20530251149624587
mdl_VectorADown = -0.10265125574812294
mdl_VectorWmDxU = 0.23095271737156670
mdl_AxialWmDxU = -0.23095271737156670
mdl_VectorWpUxD = 0.23095271737156670
mdl_AxialWpUxD = -0.23095271737156670
mdl_I1x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_I2x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I3x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I4x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_Vector_tbGp = (-0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGp = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_Vector_tbGm = ( 0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGm = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_ee__exp__2 = 9.4835522759998875E-002
mdl_gAaa = 1.3008566310666950E-005
mdl_cw__exp__2 = 0.77775351421422245
mdl_gAza = 4.7794971072590281E-006
mdl_gHaa = 2.5475109025056106E-005
mdl_gHza = 3.9182129211851395E-005
mdl_gw__exp__2 = 0.42671326129048615
mdl_sw__exp__2 = 0.22224648578577769
Internal Params evaluated point by point
----------------------------------------
mdl_sqrt__aS = 0.34351128074635334
mdl_G__exp__2 = 1.4828317324943823
mdl_G__exp__4 = 2.1987899468922913
mdl_R2MixedFactor_FIN_ = -2.5040377713124864E-002
mdl_GWcft_UV_b_1EPS_ = -3.1300472141406080E-003
mdl_GWcft_UV_t_1EPS_ = -3.1300472141406080E-003
mdl_bWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_tWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_G__exp__3 = 1.8056676068262196
mdl_MU_R__exp__2 = 8315.2513440000002
mdl_GWcft_UV_b_FIN_ = -1.8563438626678915E-002
mdl_GWcft_UV_t_FIN_ = 4.0087659331150384E-003
mdl_bWcft_UV_FIN_ = -0.13642100947319838
mdl_tWcft_UV_FIN_ = -9.8778211443463623E-004
mdl_gAgg = 7.6274879753643885E-005
mdl_gHgg = -5.0849919835762592E-005
Couplings of HC_NLO_X0_UFO
---------------------------------
R2_UUZ_V2 = -0.00000E+00 -0.72127E-02
R2_UUZ_V5 = 0.00000E+00 0.68702E-03
GC_5 = 0.00000E+00 0.12177E+01
GC_3007a = -0.00000E+00 -0.00000E+00
GC_3007h2 = -0.00000E+00 -0.16312E-02
GC_3007h3 = -0.00000E+00 -0.00000E+00
GC_22 = 0.00000E+00 0.28804E+00
GC_23 = -0.00000E+00 -0.27437E-01
GC_24 = 0.00000E+00 0.82310E-01
GC_3007h1 = 0.00000E+00 0.33772E+01
Collider parameters:
--------------------
Running at P P machine @ 13000.000000000000 GeV
PDF set = nn23nlo
alpha_s(Mz)= 0.1190 running at 2 loops.
alpha_s(Mz)= 0.1190 running at 2 loops.
Renormalization scale set on event-by-event basis
Factorization scale set on event-by-event basis
Diagram information for clustering has been set-up for nFKSprocess 1
Diagram information for clustering has been set-up for nFKSprocess 2
Diagram information for clustering has been set-up for nFKSprocess 3
Diagram information for clustering has been set-up for nFKSprocess 4
getting user params
Enter number of events and iterations:
Number of events and iterations -1 12
Enter desired fractional accuracy:
Desired fractional accuracy: 2.9999999999999999E-002
Enter alpha, beta for G_soft
Enter alpha<0 to set G_soft=1 (no ME soft)
for G_soft: alpha= 1.0000000000000000 , beta= -0.10000000000000001
Enter alpha, beta for G_azi
Enter alpha>0 to set G_azi=0 (no azi corr)
for G_azi: alpha= -1.0000000000000000 , beta= -0.10000000000000001
Doing the S and H events together
Suppress amplitude (0 no, 1 yes)?
Using suppressed amplitude.
Exact helicity sum (0 yes, n = number/event)?
Do MC over helicities for the virtuals
Enter Configuration Number:
Running Configuration Number: 2
Enter running mode for MINT:
0 to set-up grids, 1 to integrate, 2 to generate events
MINT running mode: 0
Set the three folding parameters for MINT
xi_i, phi_i, y_ij
1 1 1
'all ', 'born', 'real', 'virt', 'novi' or 'grid'?
Enter 'born0' or 'virt0' to perform
a pure n-body integration (no S functions)
doing the all of this channel
Normal integration (Sfunction != 1)
about to integrate 13 -1 12 2
imode is 0
channel 1 : 2 T 0 0 0.1000E+01 0.0000E+00 0.1000E+01
+----------------------------------------------------------------+
| |
| Ninja - version 1.2.0 |
| |
| Author: <NAME> |
| |
| Based on: |
| |
| <NAME>, <NAME> and <NAME>, |
| "Integrand reduction of one-loop scattering amplitudes |
| through Laurent series expansion," |
| JHEP 1206 (2012) 095 [arXiv:1203.0291 [hep-ph]]. |
| |
| <NAME>, |
| "Ninja: Automated Integrand Reduction via Laurent |
| Expansion for One-Loop Amplitudes," |
| Comput.Phys.Commun. 185 (2014) [arXiv:1403.1229 [hep-ph]] |
| |
+----------------------------------------------------------------+
------- iteration 1
Update # PS points (even): 1040 --> 1040
Using random seed offsets: 2 , 3 , 0
with seed 34
Ranmar initialization seeds 13169 9411
Total number of FKS directories is 4
FKS process map (sum= 3 ) :
1 --> 2 : 1 3
2 --> 2 : 2 4
================================
process combination map (specified per FKS dir):
1 map 1 2 3 4
1 inv. map 1 2 3 4
2 map 1 2 3 4
2 inv. map 1 2 3 4
3 map 1 2 3 4
3 inv. map 1 2 3 4
4 map 1 2 3 4
4 inv. map 1 2 3 4
================================
tau_min 1 1 : 0.18238E+03 -- 0.39119E+03
tau_min 2 1 : 0.18238E+03 -- 0.39119E+03
tau_min 3 1 : 0.18238E+03 -- 0.39119E+03
tau_min 4 1 : 0.18238E+03 -- 0.39119E+03
bpower is 0.0000000000000000
Scale values (may change event by event):
muR, muR_reference: 0.118506D+03 0.118506D+03 1.00
muF1, muF1_reference: 0.118506D+03 0.118506D+03 1.00
muF2, muF2_reference: 0.118506D+03 0.118506D+03 1.00
QES, QES_reference: 0.118506D+03 0.118506D+03 1.00
muR_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF1_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF2_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
QES_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
alpha_s= 0.11444169587635816
alpha_s value used for the virtuals is (for the first PS point): 0.11444169587635816
==========================================================================================
{ }
{ [32m [0m }
{ [32m ,, [0m }
{ [32m`7MMM. ,MMF' `7MM `7MMF' [0m }
{ [32m MMMb dPMM MM MM [0m }
{ [32m M YM ,M MM ,6"Yb. ,M""bMM MM ,pW"Wq. ,pW"Wq.`7MMpdMAo. [0m }
{ [32m M Mb M' MM 8) MM ,AP MM MM 6W' `Wb 6W' `Wb MM `Wb [0m }
{ [32m M YM.P' MM ,pm9MM 8MI MM MM , 8M M8 8M M8 MM M8 [0m }
{ [32m M `YM' MM 8M MM `Mb MM MM ,M YA. ,A9 YA. ,A9 MM ,AP [0m }
{ [32m.JML. `' .JMML.`Moo9^Yo.`Wbmd"MML..JMMmmmmMMM `Ybmd9' `Ybmd9' MMbmmd' [0m }
{ [32m MM [0m }
{ [32m .JMML. [0m }
{ [32m[0mv2.6.6 (2018-06-28), Ref: arXiv:1103.0621v2, arXiv:1405.0301[32m [0m }
{ [32m [0m }
{ }
==========================================================================================
===============================================================
INFO: MadLoop read these parameters from ../MadLoop5_resources/MadLoopParams.dat
===============================================================
> MLReductionLib = 6|7|1
> CTModeRun = -1
> MLStabThres = 1.0000000000000000E-003
> NRotations_DP = 0
> NRotations_QP = 0
> CTStabThres = 1.0000000000000000E-002
> CTLoopLibrary = 2
> CTModeInit = 1
> CheckCycle = 3
> MaxAttempts = 10
> UseLoopFilter = F
> HelicityFilterLevel = 2
> ImprovePSPoint = 2
> DoubleCheckHelicityFilter = T
> LoopInitStartOver = F
> HelInitStartOver = F
> ZeroThres = 1.0000000000000001E-009
> OSThres = 1.0000000000000000E-008
> WriteOutFilters = T
> UseQPIntegrandForNinja = T
> UseQPIntegrandForCutTools = T
> IREGIMODE = 2
> IREGIRECY = T
> COLLIERMode = 1
> COLLIERRequiredAccuracy = 1.0000000000000000E-008
> COLLIERCanOutput = F
> COLLIERComputeUVpoles = T
> COLLIERComputeIRpoles = T
> COLLIERGlobalCache = -1
> COLLIERUseCacheForPoles = F
> COLLIERUseInternalStabilityTest = T
===============================================================
------------------------------------------------------------------------
| You are using CutTools - Version 1.9.3 |
| Authors: <NAME>, <NAME>, <NAME> |
| Published in JHEP 0803:042,2008 |
| http://www.ugr.es/~pittau/CutTools |
| |
| Compiler with 34 significant digits detetected |
----------------------------------------------------------------------
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
---- POLES CANCELLED ----
ABS integral = 0.9707E-03 +/- 0.7444E-04 ( 7.668 %)
Integral = 0.9012E-03 +/- 0.7167E-04 ( 7.953 %)
Virtual = 0.6463E-04 +/- 0.5264E-05 ( 8.145 %)
Virtual ratio = 0.5236E+01 +/- 0.1666E-01 ( 0.318 %)
ABS virtual = 0.6469E-04 +/- 0.5263E-05 ( 8.136 %)
Born*ao2pi = 0.1270E-04 +/- 0.1046E-05 ( 8.237 %)
Chi^2 per d.o.f. 0.0000E+00
accumulated results ABS integral = 0.9707E-03 +/- 0.7444E-04 ( 7.668 %)
accumulated results Integral = 0.9012E-03 +/- 0.7167E-04 ( 7.953 %)
accumulated results Virtual = 0.6463E-04 +/- 0.5264E-05 ( 8.145 %)
accumulated results Virtual ratio = 0.5236E+01 +/- 0.1666E-01 ( 0.318 %)
accumulated results ABS virtual = 0.6469E-04 +/- 0.5263E-05 ( 8.136 %)
accumulated results Born*ao2pi = 0.1270E-04 +/- 0.1046E-05 ( 8.237 %)
accumulated result Chi^2 per DoF = 0.0000E+00
1: 0 1 2
channel 1 : 2 T 2080 0 0.9707E-03 0.9012E-03 0.2500E+00
------- iteration 2
Update # PS points (even): 2080 --> 2080
ABS integral = 0.1008E-02 +/- 0.2212E-04 ( 2.194 %)
Integral = 0.9229E-03 +/- 0.2016E-04 ( 2.184 %)
Virtual = -.1178E-05 +/- 0.6329E-06 ( 53.735 %)
Virtual ratio = 0.5093E+01 +/- 0.3842E-01 ( 0.754 %)
ABS virtual = 0.6374E-05 +/- 0.6254E-06 ( 9.812 %)
Born*ao2pi = 0.1257E-04 +/- 0.6648E-06 ( 5.291 %)
Chi^2= 0.1519E+00
accumulated results ABS integral = 0.9997E-03 +/- 0.2121E-04 ( 2.121 %)
accumulated results Integral = 0.9181E-03 +/- 0.1940E-04 ( 2.113 %)
accumulated results Virtual = 0.5885E-05 +/- 0.6284E-06 ( 10.677 %)
accumulated results Virtual ratio = 0.5193E+01 +/- 0.1528E-01 ( 0.294 %)
accumulated results ABS virtual = 0.1257E-04 +/- 0.6210E-06 ( 4.942 %)
accumulated results Born*ao2pi = 0.1262E-04 +/- 0.5611E-06 ( 4.447 %)
accumulated result Chi^2 per DoF = 0.1519E+00
1: 0 1 2
channel 1 : 2 T 4160 2080 0.9997E-03 0.9181E-03 0.6250E-01
------- iteration 3
Update # PS points (even): 4160 --> 4160
ABS integral = 0.1008E-02 +/- 0.1049E-04 ( 1.040 %)
Integral = 0.9336E-03 +/- 0.1007E-04 ( 1.079 %)
Virtual = -.2752E-05 +/- 0.1395E-05 ( 50.709 %)
Virtual ratio = 0.4923E+01 +/- 0.6383E-01 ( 1.297 %)
ABS virtual = 0.8977E-05 +/- 0.1392E-05 ( 15.510 %)
Born*ao2pi = 0.1345E-04 +/- 0.8073E-06 ( 6.003 %)
Chi^2= 0.7054E-01
accumulated results ABS integral = 0.1005E-02 +/- 0.9402E-05 ( 0.935 %)
accumulated results Integral = 0.9283E-03 +/- 0.8940E-05 ( 0.963 %)
accumulated results Virtual = 0.3203E-05 +/- 0.5730E-06 ( 17.886 %)
accumulated results Virtual ratio = 0.5141E+01 +/- 0.1486E-01 ( 0.289 %)
accumulated results ABS virtual = 0.1146E-04 +/- 0.5672E-06 ( 4.949 %)
accumulated results Born*ao2pi = 0.1296E-04 +/- 0.4608E-06 ( 3.555 %)
accumulated result Chi^2 per DoF = 0.1112E+00
1: 0 1 2
channel 1 : 2 T 8320 4160 0.1005E-02 0.9283E-03 0.1663E-01
------- iteration 4
Update # PS points (even): 8320 --> 8320
ABS integral = 0.1012E-02 +/- 0.6106E-05 ( 0.603 %)
Integral = 0.9358E-03 +/- 0.5925E-05 ( 0.633 %)
Virtual = -.1788E-05 +/- 0.1312E-05 ( 73.362 %)
Virtual ratio = 0.4947E+01 +/- 0.7469E-01 ( 1.510 %)
ABS virtual = 0.8832E-05 +/- 0.1310E-05 ( 14.832 %)
Born*ao2pi = 0.1345E-04 +/- 0.9660E-06 ( 7.183 %)
Chi^2= 0.1991E+00
accumulated results ABS integral = 0.1010E-02 +/- 0.5121E-05 ( 0.507 %)
accumulated results Integral = 0.9328E-03 +/- 0.4939E-05 ( 0.529 %)
accumulated results Virtual = 0.1686E-05 +/- 0.5250E-06 ( 31.142 %)
accumulated results Virtual ratio = 0.5109E+01 +/- 0.1458E-01 ( 0.285 %)
accumulated results ABS virtual = 0.1067E-04 +/- 0.5205E-06 ( 4.880 %)
accumulated results Born*ao2pi = 0.1312E-04 +/- 0.4159E-06 ( 3.170 %)
accumulated result Chi^2 per DoF = 0.1405E+00
accumulated results last 3 iterations ABS integral = 0.1011E-02 +/- 0.5133E-05 ( 0.508 %)
accumulated results last 3 iterations Integral = 0.9335E-03 +/- 0.4951E-05 ( 0.530 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.3410E-01
1: 0 1 2
Found desired accuracy
channel 1 : 2 T 16639 8320 0.1010E-02 0.9328E-03 0.7144E-02
-------
Final result [ABS]: 1.0095669884954382E-003 +/- 5.1207128004096554E-006
Final result: 9.3279927444510997E-004 +/- 4.9387723865812819E-006
chi**2 per D.o.F.: 0.14051328408451980
Satistics from MadLoop:
Total points tried: 3365
Stability unknown: 0
Stable PS point: 3365
Unstable PS point (and rescued): 0
Exceptional PS point (unstable and not rescued): 0
Double precision used: 3365
Quadruple precision used: 0
Initialization phase-space points: 0
Unknown return code (100): 0
Unknown return code (10): 0
Unit return code distribution (1):
#Unit 6 = 3365
Time spent in Born : 3.27877855
Time spent in PS_Generation : 0.00000000
Time spent in Reals_evaluation: 13.9937134
Time spent in MCsubtraction : 9.88479996
Time spent in Counter_terms : 7.35782623
Time spent in Integrated_CT : 0.241152853
Time spent in Virtuals : 0.268707126
Time spent in FxFx_cluster : 0.00000000
Time spent in Nbody_prefactor : 3.39516973
Time spent in N1body_prefactor : 3.40431213
Time spent in Adding_alphas_pdf : 0.640185177
Time spent in Reweight_scale : 0.00000000
Time spent in Reweight_pdf : 0.00000000
Time spent in Filling_plots : 0.00000000
Time spent in Applying_cuts : 0.182109773
Time spent in Sum_ident_contr : 5.60605526E-02
Time spent in Pick_unwgt : 0.00000000
Time spent in Write_events : 0.00000000
Time spent in Other_tasks : 1.53992844
Time spent in Total : 44.2427444
Time in seconds: 45
</PRE><br>
<a name=/P0_dxd_zx0_zepemz_no_a/GF1></a>
<font color="red">
<br>LOG file for integration channel /P0_dxd_zx0_zepemz_no_a/GF1, 0 <br></font>
<PRE>
===============================================================
INFO: MadFKS read these parameters from FKS_params.dat
===============================================================
> IRPoleCheckThreshold = 1.0000000000000001E-005
> PrecisionVirtualAtRunTime = 1.0000000000000000E-003
> NHelForMCoverHels = 4
> VirtualFraction = 1.0000000000000000
> MinVirtualFraction = 5.0000000000000001E-003
===============================================================
A PDF is used, so alpha_s(MZ) is going to be modified
Old value of alpha_s from param_card: 0.11799999999999999
****************************************
NNPDFDriver version 1.0.3
Grid: NNPDF23nlo_as_0119_qed_mem0.grid
****************************************
New value of alpha_s from PDF nn23nlo: 0.11899999999999999
*****************************************************
* MadGraph/MadEvent *
* -------------------------------- *
* http://madgraph.hep.uiuc.edu *
* http://madgraph.phys.ucl.ac.be *
* http://madgraph.roma2.infn.it *
* -------------------------------- *
* *
* PARAMETER AND COUPLING VALUES *
* *
*****************************************************
External Params
---------------------------------
MU_R = 91.188000000000002
aEWM1 = 132.50700000000001
mdl_Gf = 1.1663900000000000E-005
aS = 0.11799999999999999
mdl_ymb = 4.7000000000000002
mdl_ymt = 173.00000000000000
mdl_ymtau = 1.7769999999999999
mdl_MT = 173.00000000000000
mdl_MB = 4.7000000000000002
mdl_MZ = 91.188000000000002
mdl_MTA = 1.7769999999999999
mdl_WT = 1.4915000000000000
mdl_WZ = 2.4414039999999999
mdl_WW = 2.0476000000000001
mdl_MX0 = 300.00000000000000
mdl_WX0 = 1.0604700000000000
mdl_Lambda = 5000.0000000000000
mdl_cosa = 1.0000000000000000
mdl_kSM = 5.0000000000000003E-002
mdl_kHtt = 0.0000000000000000
mdl_kAtt = 0.0000000000000000
mdl_kHbb = 0.0000000000000000
mdl_kAbb = 0.0000000000000000
mdl_kHll = 0.0000000000000000
mdl_kAll = 0.0000000000000000
mdl_kHaa = 0.0000000000000000
mdl_kAaa = 0.0000000000000000
mdl_kHza = 0.0000000000000000
mdl_kAza = 0.0000000000000000
mdl_kHzz = 8.1561199999999996
mdl_kAzz = 0.0000000000000000
mdl_kHww = 10.496200000000000
mdl_kAww = 0.0000000000000000
mdl_kHda = 0.0000000000000000
mdl_kHdz = 0.0000000000000000
mdl_kHdwR = 0.0000000000000000
mdl_kHdwI = 0.0000000000000000
Internal Params
---------------------------------
mdl_CKM11 = 1.0000000000000000
mdl_conjg__CKM3x3 = 1.0000000000000000
mdl_conjg__CKM11 = 1.0000000000000000
mdl_lhv = 1.0000000000000000
mdl_CKM3x3 = 1.0000000000000000
mdl_conjg__CKM33 = 1.0000000000000000
mdl_Ncol = 3.0000000000000000
mdl_CA = 3.0000000000000000
mdl_TF = 0.50000000000000000
mdl_CF = 1.3333333333333333
mdl_complexi = ( 0.0000000000000000 , 1.0000000000000000 )
mdl_MZ__exp__2 = 8315.2513440000002
mdl_MZ__exp__4 = 69143404.913893804
mdl_sqrt__2 = 1.4142135623730951
mdl_MX0__exp__2 = 90000.000000000000
mdl_cosa__exp__2 = 1.0000000000000000
mdl_sina = 0.0000000000000000
mdl_kHdw = ( 0.0000000000000000 , 0.0000000000000000 )
mdl_nb__2__exp__0_75 = 1.6817928305074290
mdl_Ncol__exp__2 = 9.0000000000000000
mdl_MB__exp__2 = 22.090000000000003
mdl_MT__exp__2 = 29929.000000000000
mdl_conjg__kHdw = ( 0.0000000000000000 , -0.0000000000000000 )
mdl_aEW = 7.5467711139788835E-003
mdl_MW = 80.419002445756163
mdl_sqrt__aEW = 8.6872153846781555E-002
mdl_ee = 0.30795376724436879
mdl_MW__exp__2 = 6467.2159543705357
mdl_sw2 = 0.22224648578577766
mdl_cw = 0.88190334743339216
mdl_sqrt__sw2 = 0.47143025548407230
mdl_sw = 0.47143025548407230
mdl_g1 = 0.34919219678733299
mdl_gw = 0.65323293034757990
mdl_vev = 246.21845810181637
mdl_vev__exp__2 = 60623.529110035903
mdl_lam = 0.74228605065735920
mdl_yb = 2.6995554250465490E-002
mdl_yt = 0.99366614581500623
mdl_ytau = 1.0206617000654717E-002
mdl_muH = 212.13203435596427
mdl_AxialZUp = -0.18517701861793787
mdl_AxialZDown = 0.18517701861793787
mdl_VectorZUp = 7.5430507588273299E-002
mdl_VectorZDown = -0.13030376310310560
mdl_VectorAUp = 0.20530251149624587
mdl_VectorADown = -0.10265125574812294
mdl_VectorWmDxU = 0.23095271737156670
mdl_AxialWmDxU = -0.23095271737156670
mdl_VectorWpUxD = 0.23095271737156670
mdl_AxialWpUxD = -0.23095271737156670
mdl_I1x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_I2x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I3x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I4x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_Vector_tbGp = (-0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGp = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_Vector_tbGm = ( 0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGm = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_ee__exp__2 = 9.4835522759998875E-002
mdl_gAaa = 1.3008566310666950E-005
mdl_cw__exp__2 = 0.77775351421422245
mdl_gAza = 4.7794971072590281E-006
mdl_gHaa = 2.5475109025056106E-005
mdl_gHza = 3.9182129211851395E-005
mdl_gw__exp__2 = 0.42671326129048615
mdl_sw__exp__2 = 0.22224648578577769
Internal Params evaluated point by point
----------------------------------------
mdl_sqrt__aS = 0.34351128074635334
mdl_G__exp__2 = 1.4828317324943823
mdl_G__exp__4 = 2.1987899468922913
mdl_R2MixedFactor_FIN_ = -2.5040377713124864E-002
mdl_GWcft_UV_b_1EPS_ = -3.1300472141406080E-003
mdl_GWcft_UV_t_1EPS_ = -3.1300472141406080E-003
mdl_bWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_tWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_G__exp__3 = 1.8056676068262196
mdl_MU_R__exp__2 = 8315.2513440000002
mdl_GWcft_UV_b_FIN_ = -1.8563438626678915E-002
mdl_GWcft_UV_t_FIN_ = 4.0087659331150384E-003
mdl_bWcft_UV_FIN_ = -0.13642100947319838
mdl_tWcft_UV_FIN_ = -9.8778211443463623E-004
mdl_gAgg = 7.6274879753643885E-005
mdl_gHgg = -5.0849919835762592E-005
Couplings of HC_NLO_X0_UFO
---------------------------------
R2_UUZ_V2 = -0.00000E+00 -0.72127E-02
R2_UUZ_V5 = 0.00000E+00 0.68702E-03
GC_5 = 0.00000E+00 0.12177E+01
GC_3007a = -0.00000E+00 -0.00000E+00
GC_3007h2 = -0.00000E+00 -0.16312E-02
GC_3007h3 = -0.00000E+00 -0.00000E+00
GC_22 = 0.00000E+00 0.28804E+00
GC_23 = -0.00000E+00 -0.27437E-01
GC_24 = 0.00000E+00 0.82310E-01
GC_3007h1 = 0.00000E+00 0.33772E+01
Collider parameters:
--------------------
Running at P P machine @ 13000.000000000000 GeV
PDF set = nn23nlo
alpha_s(Mz)= 0.1190 running at 2 loops.
alpha_s(Mz)= 0.1190 running at 2 loops.
Renormalization scale set on event-by-event basis
Factorization scale set on event-by-event basis
Diagram information for clustering has been set-up for nFKSprocess 1
Diagram information for clustering has been set-up for nFKSprocess 2
Diagram information for clustering has been set-up for nFKSprocess 3
Diagram information for clustering has been set-up for nFKSprocess 4
getting user params
Enter number of events and iterations:
Number of events and iterations -1 12
Enter desired fractional accuracy:
Desired fractional accuracy: 2.9999999999999999E-002
Enter alpha, beta for G_soft
Enter alpha<0 to set G_soft=1 (no ME soft)
for G_soft: alpha= 1.0000000000000000 , beta= -0.10000000000000001
Enter alpha, beta for G_azi
Enter alpha>0 to set G_azi=0 (no azi corr)
for G_azi: alpha= -1.0000000000000000 , beta= -0.10000000000000001
Doing the S and H events together
Suppress amplitude (0 no, 1 yes)?
Using suppressed amplitude.
Exact helicity sum (0 yes, n = number/event)?
Do MC over helicities for the virtuals
Enter Configuration Number:
Running Configuration Number: 1
Enter running mode for MINT:
0 to set-up grids, 1 to integrate, 2 to generate events
MINT running mode: 0
Set the three folding parameters for MINT
xi_i, phi_i, y_ij
1 1 1
'all ', 'born', 'real', 'virt', 'novi' or 'grid'?
Enter 'born0' or 'virt0' to perform
a pure n-body integration (no S functions)
doing the all of this channel
Normal integration (Sfunction != 1)
about to integrate 13 -1 12 1
imode is 0
channel 1 : 1 T 0 0 0.1000E+01 0.0000E+00 0.1000E+01
+----------------------------------------------------------------+
| |
| Ninja - version 1.2.0 |
| |
| Author: <NAME> |
| |
| Based on: |
| |
| <NAME>, <NAME> and <NAME>, |
| "Integrand reduction of one-loop scattering amplitudes |
| through Laurent series expansion," |
| JHEP 1206 (2012) 095 [arXiv:1203.0291 [hep-ph]]. |
| |
| <NAME>, |
| "Ninja: Automated Integrand Reduction via Laurent |
| Expansion for One-Loop Amplitudes," |
| Comput.Phys.Commun. 185 (2014) [arXiv:1403.1229 [hep-ph]] |
| |
+----------------------------------------------------------------+
------- iteration 1
Update # PS points (even): 1040 --> 1040
Using random seed offsets: 1 , 4 , 0
with seed 34
Ranmar initialization seeds 13168 9412
Total number of FKS directories is 4
FKS process map (sum= 3 ) :
1 --> 2 : 1 3
2 --> 2 : 2 4
================================
process combination map (specified per FKS dir):
1 map 1 2 3 4
1 inv. map 1 2 3 4
2 map 1 2 3 4
2 inv. map 1 2 3 4
3 map 1 2 3 4
3 inv. map 1 2 3 4
4 map 1 2 3 4
4 inv. map 1 2 3 4
================================
tau_min 1 1 : 0.18238E+03 -- 0.39119E+03
tau_min 2 1 : 0.18238E+03 -- 0.39119E+03
tau_min 3 1 : 0.18238E+03 -- 0.39119E+03
tau_min 4 1 : 0.18238E+03 -- 0.39119E+03
bpower is 0.0000000000000000
Scale values (may change event by event):
muR, muR_reference: 0.221185D+03 0.221185D+03 1.00
muF1, muF1_reference: 0.221185D+03 0.221185D+03 1.00
muF2, muF2_reference: 0.221185D+03 0.221185D+03 1.00
QES, QES_reference: 0.221185D+03 0.221185D+03 1.00
muR_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF1_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF2_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
QES_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
alpha_s= 0.10489892841367188
alpha_s value used for the virtuals is (for the first PS point): 0.10489892841367188
==========================================================================================
{ }
{ [32m [0m }
{ [32m ,, [0m }
{ [32m`7MMM. ,MMF' `7MM `7MMF' [0m }
{ [32m MMMb dPMM MM MM [0m }
{ [32m M YM ,M MM ,6"Yb. ,M""bMM MM ,pW"Wq. ,pW"Wq.`7MMpdMAo. [0m }
{ [32m M Mb M' MM 8) MM ,AP MM MM 6W' `Wb 6W' `Wb MM `Wb [0m }
{ [32m M YM.P' MM ,pm9MM 8MI MM MM , 8M M8 8M M8 MM M8 [0m }
{ [32m M `YM' MM 8M MM `Mb MM MM ,M YA. ,A9 YA. ,A9 MM ,AP [0m }
{ [32m.JML. `' .JMML.`Moo9^Yo.`Wbmd"MML..JMMmmmmMMM `Ybmd9' `Ybmd9' MMbmmd' [0m }
{ [32m MM [0m }
{ [32m .JMML. [0m }
{ [32m[0mv2.6.6 (2018-06-28), Ref: arXiv:1103.0621v2, arXiv:1405.0301[32m [0m }
{ [32m [0m }
{ }
==========================================================================================
===============================================================
INFO: MadLoop read these parameters from ../MadLoop5_resources/MadLoopParams.dat
===============================================================
> MLReductionLib = 6|7|1
> CTModeRun = -1
> MLStabThres = 1.0000000000000000E-003
> NRotations_DP = 0
> NRotations_QP = 0
> CTStabThres = 1.0000000000000000E-002
> CTLoopLibrary = 2
> CTModeInit = 1
> CheckCycle = 3
> MaxAttempts = 10
> UseLoopFilter = F
> HelicityFilterLevel = 2
> ImprovePSPoint = 2
> DoubleCheckHelicityFilter = T
> LoopInitStartOver = F
> HelInitStartOver = F
> ZeroThres = 1.0000000000000001E-009
> OSThres = 1.0000000000000000E-008
> WriteOutFilters = T
> UseQPIntegrandForNinja = T
> UseQPIntegrandForCutTools = T
> IREGIMODE = 2
> IREGIRECY = T
> COLLIERMode = 1
> COLLIERRequiredAccuracy = 1.0000000000000000E-008
> COLLIERCanOutput = F
> COLLIERComputeUVpoles = T
> COLLIERComputeIRpoles = T
> COLLIERGlobalCache = -1
> COLLIERUseCacheForPoles = F
> COLLIERUseInternalStabilityTest = T
===============================================================
------------------------------------------------------------------------
| You are using CutTools - Version 1.9.3 |
| Authors: <NAME>, <NAME>, <NAME> |
| Published in JHEP 0803:042,2008 |
| http://www.ugr.es/~pittau/CutTools |
| |
| Compiler with 34 significant digits detetected |
----------------------------------------------------------------------
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
---- POLES CANCELLED ----
ABS integral = 0.4788E-03 +/- 0.3545E-04 ( 7.404 %)
Integral = 0.4462E-03 +/- 0.3414E-04 ( 7.652 %)
Virtual = 0.3180E-04 +/- 0.2523E-05 ( 7.932 %)
Virtual ratio = 0.5258E+01 +/- 0.1882E-01 ( 0.358 %)
ABS virtual = 0.3234E-04 +/- 0.2519E-05 ( 7.790 %)
Born*ao2pi = 0.6179E-05 +/- 0.4836E-06 ( 7.827 %)
Chi^2 per d.o.f. 0.0000E+00
accumulated results ABS integral = 0.4788E-03 +/- 0.3545E-04 ( 7.404 %)
accumulated results Integral = 0.4462E-03 +/- 0.3414E-04 ( 7.652 %)
accumulated results Virtual = 0.3180E-04 +/- 0.2523E-05 ( 7.932 %)
accumulated results Virtual ratio = 0.5258E+01 +/- 0.1882E-01 ( 0.358 %)
accumulated results ABS virtual = 0.3234E-04 +/- 0.2519E-05 ( 7.790 %)
accumulated results Born*ao2pi = 0.6179E-05 +/- 0.4836E-06 ( 7.827 %)
accumulated result Chi^2 per DoF = 0.0000E+00
1: 0 1 2
channel 1 : 1 T 2080 0 0.4788E-03 0.4462E-03 0.2500E+00
------- iteration 2
Update # PS points (even): 2080 --> 2080
ABS integral = 0.4227E-03 +/- 0.9341E-05 ( 2.210 %)
Integral = 0.3917E-03 +/- 0.8799E-05 ( 2.246 %)
Virtual = -.4953E-06 +/- 0.2788E-06 ( 56.295 %)
Virtual ratio = 0.5171E+01 +/- 0.2490E-01 ( 0.482 %)
ABS virtual = 0.2728E-05 +/- 0.2757E-06 ( 10.108 %)
Born*ao2pi = 0.6103E-05 +/- 0.3167E-06 ( 5.189 %)
Chi^2= 0.1565E+01
accumulated results ABS integral = 0.4344E-03 +/- 0.9033E-05 ( 2.079 %)
accumulated results Integral = 0.4029E-03 +/- 0.8521E-05 ( 2.115 %)
accumulated results Virtual = 0.2719E-05 +/- 0.2772E-06 ( 10.192 %)
accumulated results Virtual ratio = 0.5221E+01 +/- 0.1502E-01 ( 0.288 %)
accumulated results ABS virtual = 0.5649E-05 +/- 0.2741E-06 ( 4.852 %)
accumulated results Born*ao2pi = 0.6133E-05 +/- 0.2649E-06 ( 4.320 %)
accumulated result Chi^2 per DoF = 0.1565E+01
1: 0 1 2
channel 1 : 1 T 4160 2080 0.4344E-03 0.4029E-03 0.6250E-01
------- iteration 3
Update # PS points (even): 4160 --> 4160
ABS integral = 0.4413E-03 +/- 0.7358E-05 ( 1.667 %)
Integral = 0.4068E-03 +/- 0.7044E-05 ( 1.732 %)
Virtual = -.1967E-06 +/- 0.4628E-06 ( 235.301 %)
Virtual ratio = 0.5105E+01 +/- 0.4944E-01 ( 0.969 %)
ABS virtual = 0.2835E-05 +/- 0.4618E-06 ( 16.290 %)
Born*ao2pi = 0.5963E-05 +/- 0.8128E-06 ( 13.632 %)
Chi^2= 0.1753E+00
accumulated results ABS integral = 0.4382E-03 +/- 0.5705E-05 ( 1.302 %)
accumulated results Integral = 0.4050E-03 +/- 0.5429E-05 ( 1.341 %)
accumulated results Virtual = 0.1627E-05 +/- 0.2378E-06 ( 14.613 %)
accumulated results Virtual ratio = 0.5194E+01 +/- 0.1437E-01 ( 0.277 %)
accumulated results ABS virtual = 0.4601E-05 +/- 0.2357E-06 ( 5.123 %)
accumulated results Born*ao2pi = 0.6091E-05 +/- 0.2519E-06 ( 4.135 %)
accumulated result Chi^2 per DoF = 0.8703E+00
1: 0 1 2
channel 1 : 1 T 8320 4160 0.4382E-03 0.4050E-03 0.1562E-01
------- iteration 4
Update # PS points (even): 8320 --> 8320
ABS integral = 0.4416E-03 +/- 0.4143E-05 ( 0.938 %)
Integral = 0.4091E-03 +/- 0.4061E-05 ( 0.993 %)
Virtual = -.7901E-06 +/- 0.6076E-06 ( 76.910 %)
Virtual ratio = 0.5044E+01 +/- 0.7125E-01 ( 1.413 %)
ABS virtual = 0.2816E-05 +/- 0.6073E-06 ( 21.563 %)
Born*ao2pi = 0.5098E-05 +/- 0.4597E-06 ( 9.017 %)
Chi^2= 0.1202E+00
accumulated results ABS integral = 0.4402E-03 +/- 0.3352E-05 ( 0.762 %)
accumulated results Integral = 0.4073E-03 +/- 0.3252E-05 ( 0.798 %)
accumulated results Virtual = 0.9473E-06 +/- 0.2214E-06 ( 23.374 %)
accumulated results Virtual ratio = 0.5168E+01 +/- 0.1408E-01 ( 0.273 %)
accumulated results ABS virtual = 0.4102E-05 +/- 0.2197E-06 ( 5.357 %)
accumulated results Born*ao2pi = 0.5739E-05 +/- 0.2209E-06 ( 3.849 %)
accumulated result Chi^2 per DoF = 0.6203E+00
accumulated results last 3 iterations ABS integral = 0.4381E-03 +/- 0.3367E-05 ( 0.769 %)
accumulated results last 3 iterations Integral = 0.4053E-03 +/- 0.3267E-05 ( 0.806 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.9844E+00
1: 0 1 2
Found desired accuracy
channel 1 : 1 T 16652 8320 0.4402E-03 0.4073E-03 0.5000E-02
-------
Final result [ABS]: 4.4016655932437233E-004 +/- 3.3523583315517179E-006
Final result: 4.0734216054818915E-004 +/- 3.2519133823694836E-006
chi**2 per D.o.F.: 0.62028447044538371
Satistics from MadLoop:
Total points tried: 3292
Stability unknown: 0
Stable PS point: 3292
Unstable PS point (and rescued): 0
Exceptional PS point (unstable and not rescued): 0
Double precision used: 3292
Quadruple precision used: 0
Initialization phase-space points: 0
Unknown return code (100): 0
Unknown return code (10): 0
Unit return code distribution (1):
#Unit 6 = 3292
Time spent in Born : 3.25972986
Time spent in PS_Generation : 0.00000000
Time spent in Reals_evaluation: 13.9387150
Time spent in MCsubtraction : 9.83717632
Time spent in Counter_terms : 7.31522894
Time spent in Integrated_CT : 0.242120534
Time spent in Virtuals : 0.259355754
Time spent in FxFx_cluster : 0.00000000
Time spent in Nbody_prefactor : 3.37291431
Time spent in N1body_prefactor : 3.41166401
Time spent in Adding_alphas_pdf : 0.650007069
Time spent in Reweight_scale : 0.00000000
Time spent in Reweight_pdf : 0.00000000
Time spent in Filling_plots : 0.00000000
Time spent in Applying_cuts : 0.195986584
Time spent in Sum_ident_contr : 5.89901209E-02
Time spent in Pick_unwgt : 0.00000000
Time spent in Write_events : 0.00000000
Time spent in Other_tasks : 1.62001038
Time spent in Total : 44.1618996
Time in seconds: 45
</PRE><br>
<a name=/P0_dxd_zx0_zepemz_no_a/GF2></a>
<font color="red">
<br>LOG file for integration channel /P0_dxd_zx0_zepemz_no_a/GF2, 0 <br></font>
<PRE>
===============================================================
INFO: MadFKS read these parameters from FKS_params.dat
===============================================================
> IRPoleCheckThreshold = 1.0000000000000001E-005
> PrecisionVirtualAtRunTime = 1.0000000000000000E-003
> NHelForMCoverHels = 4
> VirtualFraction = 1.0000000000000000
> MinVirtualFraction = 5.0000000000000001E-003
===============================================================
A PDF is used, so alpha_s(MZ) is going to be modified
Old value of alpha_s from param_card: 0.11799999999999999
****************************************
NNPDFDriver version 1.0.3
Grid: NNPDF23nlo_as_0119_qed_mem0.grid
****************************************
New value of alpha_s from PDF nn23nlo: 0.11899999999999999
*****************************************************
* MadGraph/MadEvent *
* -------------------------------- *
* http://madgraph.hep.uiuc.edu *
* http://madgraph.phys.ucl.ac.be *
* http://madgraph.roma2.infn.it *
* -------------------------------- *
* *
* PARAMETER AND COUPLING VALUES *
* *
*****************************************************
External Params
---------------------------------
MU_R = 91.188000000000002
aEWM1 = 132.50700000000001
mdl_Gf = 1.1663900000000000E-005
aS = 0.11799999999999999
mdl_ymb = 4.7000000000000002
mdl_ymt = 173.00000000000000
mdl_ymtau = 1.7769999999999999
mdl_MT = 173.00000000000000
mdl_MB = 4.7000000000000002
mdl_MZ = 91.188000000000002
mdl_MTA = 1.7769999999999999
mdl_WT = 1.4915000000000000
mdl_WZ = 2.4414039999999999
mdl_WW = 2.0476000000000001
mdl_MX0 = 300.00000000000000
mdl_WX0 = 1.0604700000000000
mdl_Lambda = 5000.0000000000000
mdl_cosa = 1.0000000000000000
mdl_kSM = 5.0000000000000003E-002
mdl_kHtt = 0.0000000000000000
mdl_kAtt = 0.0000000000000000
mdl_kHbb = 0.0000000000000000
mdl_kAbb = 0.0000000000000000
mdl_kHll = 0.0000000000000000
mdl_kAll = 0.0000000000000000
mdl_kHaa = 0.0000000000000000
mdl_kAaa = 0.0000000000000000
mdl_kHza = 0.0000000000000000
mdl_kAza = 0.0000000000000000
mdl_kHzz = 8.1561199999999996
mdl_kAzz = 0.0000000000000000
mdl_kHww = 10.496200000000000
mdl_kAww = 0.0000000000000000
mdl_kHda = 0.0000000000000000
mdl_kHdz = 0.0000000000000000
mdl_kHdwR = 0.0000000000000000
mdl_kHdwI = 0.0000000000000000
Internal Params
---------------------------------
mdl_CKM11 = 1.0000000000000000
mdl_conjg__CKM3x3 = 1.0000000000000000
mdl_conjg__CKM11 = 1.0000000000000000
mdl_lhv = 1.0000000000000000
mdl_CKM3x3 = 1.0000000000000000
mdl_conjg__CKM33 = 1.0000000000000000
mdl_Ncol = 3.0000000000000000
mdl_CA = 3.0000000000000000
mdl_TF = 0.50000000000000000
mdl_CF = 1.3333333333333333
mdl_complexi = ( 0.0000000000000000 , 1.0000000000000000 )
mdl_MZ__exp__2 = 8315.2513440000002
mdl_MZ__exp__4 = 69143404.913893804
mdl_sqrt__2 = 1.4142135623730951
mdl_MX0__exp__2 = 90000.000000000000
mdl_cosa__exp__2 = 1.0000000000000000
mdl_sina = 0.0000000000000000
mdl_kHdw = ( 0.0000000000000000 , 0.0000000000000000 )
mdl_nb__2__exp__0_75 = 1.6817928305074290
mdl_Ncol__exp__2 = 9.0000000000000000
mdl_MB__exp__2 = 22.090000000000003
mdl_MT__exp__2 = 29929.000000000000
mdl_conjg__kHdw = ( 0.0000000000000000 , -0.0000000000000000 )
mdl_aEW = 7.5467711139788835E-003
mdl_MW = 80.419002445756163
mdl_sqrt__aEW = 8.6872153846781555E-002
mdl_ee = 0.30795376724436879
mdl_MW__exp__2 = 6467.2159543705357
mdl_sw2 = 0.22224648578577766
mdl_cw = 0.88190334743339216
mdl_sqrt__sw2 = 0.47143025548407230
mdl_sw = 0.47143025548407230
mdl_g1 = 0.34919219678733299
mdl_gw = 0.65323293034757990
mdl_vev = 246.21845810181637
mdl_vev__exp__2 = 60623.529110035903
mdl_lam = 0.74228605065735920
mdl_yb = 2.6995554250465490E-002
mdl_yt = 0.99366614581500623
mdl_ytau = 1.0206617000654717E-002
mdl_muH = 212.13203435596427
mdl_AxialZUp = -0.18517701861793787
mdl_AxialZDown = 0.18517701861793787
mdl_VectorZUp = 7.5430507588273299E-002
mdl_VectorZDown = -0.13030376310310560
mdl_VectorAUp = 0.20530251149624587
mdl_VectorADown = -0.10265125574812294
mdl_VectorWmDxU = 0.23095271737156670
mdl_AxialWmDxU = -0.23095271737156670
mdl_VectorWpUxD = 0.23095271737156670
mdl_AxialWpUxD = -0.23095271737156670
mdl_I1x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_I2x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I3x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I4x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_Vector_tbGp = (-0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGp = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_Vector_tbGm = ( 0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGm = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_ee__exp__2 = 9.4835522759998875E-002
mdl_gAaa = 1.3008566310666950E-005
mdl_cw__exp__2 = 0.77775351421422245
mdl_gAza = 4.7794971072590281E-006
mdl_gHaa = 2.5475109025056106E-005
mdl_gHza = 3.9182129211851395E-005
mdl_gw__exp__2 = 0.42671326129048615
mdl_sw__exp__2 = 0.22224648578577769
Internal Params evaluated point by point
----------------------------------------
mdl_sqrt__aS = 0.34351128074635334
mdl_G__exp__2 = 1.4828317324943823
mdl_G__exp__4 = 2.1987899468922913
mdl_R2MixedFactor_FIN_ = -2.5040377713124864E-002
mdl_GWcft_UV_b_1EPS_ = -3.1300472141406080E-003
mdl_GWcft_UV_t_1EPS_ = -3.1300472141406080E-003
mdl_bWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_tWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_G__exp__3 = 1.8056676068262196
mdl_MU_R__exp__2 = 8315.2513440000002
mdl_GWcft_UV_b_FIN_ = -1.8563438626678915E-002
mdl_GWcft_UV_t_FIN_ = 4.0087659331150384E-003
mdl_bWcft_UV_FIN_ = -0.13642100947319838
mdl_tWcft_UV_FIN_ = -9.8778211443463623E-004
mdl_gAgg = 7.6274879753643885E-005
mdl_gHgg = -5.0849919835762592E-005
Couplings of HC_NLO_X0_UFO
---------------------------------
R2_UUZ_V2 = -0.00000E+00 -0.72127E-02
R2_UUZ_V5 = 0.00000E+00 0.68702E-03
GC_5 = 0.00000E+00 0.12177E+01
GC_3007a = -0.00000E+00 -0.00000E+00
GC_3007h2 = -0.00000E+00 -0.16312E-02
GC_3007h3 = -0.00000E+00 -0.00000E+00
GC_22 = 0.00000E+00 0.28804E+00
GC_23 = -0.00000E+00 -0.27437E-01
GC_24 = 0.00000E+00 0.82310E-01
GC_3007h1 = 0.00000E+00 0.33772E+01
Collider parameters:
--------------------
Running at P P machine @ 13000.000000000000 GeV
PDF set = nn23nlo
alpha_s(Mz)= 0.1190 running at 2 loops.
alpha_s(Mz)= 0.1190 running at 2 loops.
Renormalization scale set on event-by-event basis
Factorization scale set on event-by-event basis
Diagram information for clustering has been set-up for nFKSprocess 1
Diagram information for clustering has been set-up for nFKSprocess 2
Diagram information for clustering has been set-up for nFKSprocess 3
Diagram information for clustering has been set-up for nFKSprocess 4
getting user params
Enter number of events and iterations:
Number of events and iterations -1 12
Enter desired fractional accuracy:
Desired fractional accuracy: 2.9999999999999999E-002
Enter alpha, beta for G_soft
Enter alpha<0 to set G_soft=1 (no ME soft)
for G_soft: alpha= 1.0000000000000000 , beta= -0.10000000000000001
Enter alpha, beta for G_azi
Enter alpha>0 to set G_azi=0 (no azi corr)
for G_azi: alpha= -1.0000000000000000 , beta= -0.10000000000000001
Doing the S and H events together
Suppress amplitude (0 no, 1 yes)?
Using suppressed amplitude.
Exact helicity sum (0 yes, n = number/event)?
Do MC over helicities for the virtuals
Enter Configuration Number:
Running Configuration Number: 2
Enter running mode for MINT:
0 to set-up grids, 1 to integrate, 2 to generate events
MINT running mode: 0
Set the three folding parameters for MINT
xi_i, phi_i, y_ij
1 1 1
'all ', 'born', 'real', 'virt', 'novi' or 'grid'?
Enter 'born0' or 'virt0' to perform
a pure n-body integration (no S functions)
doing the all of this channel
Normal integration (Sfunction != 1)
about to integrate 13 -1 12 2
imode is 0
channel 1 : 2 T 0 0 0.1000E+01 0.0000E+00 0.1000E+01
+----------------------------------------------------------------+
| |
| Ninja - version 1.2.0 |
| |
| Author: <NAME> |
| |
| Based on: |
| |
| <NAME>, <NAME> and <NAME>, |
| "Integrand reduction of one-loop scattering amplitudes |
| through Laurent series expansion," |
| JHEP 1206 (2012) 095 [arXiv:1203.0291 [hep-ph]]. |
| |
| <NAME>, |
| "Ninja: Automated Integrand Reduction via Laurent |
| Expansion for One-Loop Amplitudes," |
| Comput.Phys.Commun. 185 (2014) [arXiv:1403.1229 [hep-ph]] |
| |
+----------------------------------------------------------------+
------- iteration 1
Update # PS points (even): 1040 --> 1040
Using random seed offsets: 2 , 4 , 0
with seed 34
Ranmar initialization seeds 13169 9412
Total number of FKS directories is 4
FKS process map (sum= 3 ) :
1 --> 2 : 1 3
2 --> 2 : 2 4
================================
process combination map (specified per FKS dir):
1 map 1 2 3 4
1 inv. map 1 2 3 4
2 map 1 2 3 4
2 inv. map 1 2 3 4
3 map 1 2 3 4
3 inv. map 1 2 3 4
4 map 1 2 3 4
4 inv. map 1 2 3 4
================================
tau_min 1 1 : 0.18238E+03 -- 0.39119E+03
tau_min 2 1 : 0.18238E+03 -- 0.39119E+03
tau_min 3 1 : 0.18238E+03 -- 0.39119E+03
tau_min 4 1 : 0.18238E+03 -- 0.39119E+03
bpower is 0.0000000000000000
Scale values (may change event by event):
muR, muR_reference: 0.151503D+03 0.151503D+03 1.00
muF1, muF1_reference: 0.151503D+03 0.151503D+03 1.00
muF2, muF2_reference: 0.151503D+03 0.151503D+03 1.00
QES, QES_reference: 0.151503D+03 0.151503D+03 1.00
muR_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF1_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF2_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
QES_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
alpha_s= 0.11048097281694155
alpha_s value used for the virtuals is (for the first PS point): 0.11048097281694155
==========================================================================================
{ }
{ [32m [0m }
{ [32m ,, [0m }
{ [32m`7MMM. ,MMF' `7MM `7MMF' [0m }
{ [32m MMMb dPMM MM MM [0m }
{ [32m M YM ,M MM ,6"Yb. ,M""bMM MM ,pW"Wq. ,pW"Wq.`7MMpdMAo. [0m }
{ [32m M Mb M' MM 8) MM ,AP MM MM 6W' `Wb 6W' `Wb MM `Wb [0m }
{ [32m M YM.P' MM ,pm9MM 8MI MM MM , 8M M8 8M M8 MM M8 [0m }
{ [32m M `YM' MM 8M MM `Mb MM MM ,M YA. ,A9 YA. ,A9 MM ,AP [0m }
{ [32m.JML. `' .JMML.`Moo9^Yo.`Wbmd"MML..JMMmmmmMMM `Ybmd9' `Ybmd9' MMbmmd' [0m }
{ [32m MM [0m }
{ [32m .JMML. [0m }
{ [32m[0mv2.6.6 (2018-06-28), Ref: arXiv:1103.0621v2, arXiv:1405.0301[32m [0m }
{ [32m [0m }
{ }
==========================================================================================
===============================================================
INFO: MadLoop read these parameters from ../MadLoop5_resources/MadLoopParams.dat
===============================================================
> MLReductionLib = 6|7|1
> CTModeRun = -1
> MLStabThres = 1.0000000000000000E-003
> NRotations_DP = 0
> NRotations_QP = 0
> CTStabThres = 1.0000000000000000E-002
> CTLoopLibrary = 2
> CTModeInit = 1
> CheckCycle = 3
> MaxAttempts = 10
> UseLoopFilter = F
> HelicityFilterLevel = 2
> ImprovePSPoint = 2
> DoubleCheckHelicityFilter = T
> LoopInitStartOver = F
> HelInitStartOver = F
> ZeroThres = 1.0000000000000001E-009
> OSThres = 1.0000000000000000E-008
> WriteOutFilters = T
> UseQPIntegrandForNinja = T
> UseQPIntegrandForCutTools = T
> IREGIMODE = 2
> IREGIRECY = T
> COLLIERMode = 1
> COLLIERRequiredAccuracy = 1.0000000000000000E-008
> COLLIERCanOutput = F
> COLLIERComputeUVpoles = T
> COLLIERComputeIRpoles = T
> COLLIERGlobalCache = -1
> COLLIERUseCacheForPoles = F
> COLLIERUseInternalStabilityTest = T
===============================================================
------------------------------------------------------------------------
| You are using CutTools - Version 1.9.3 |
| Authors: <NAME>, <NAME>, <NAME> |
| Published in JHEP 0803:042,2008 |
| http://www.ugr.es/~pittau/CutTools |
| |
| Compiler with 34 significant digits detetected |
----------------------------------------------------------------------
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
---- POLES CANCELLED ----
ABS integral = 0.7580E-03 +/- 0.5337E-04 ( 7.041 %)
Integral = 0.6952E-03 +/- 0.5040E-04 ( 7.250 %)
Virtual = 0.4703E-04 +/- 0.3509E-05 ( 7.460 %)
Virtual ratio = 0.5225E+01 +/- 0.1918E-01 ( 0.367 %)
ABS virtual = 0.4790E-04 +/- 0.3503E-05 ( 7.314 %)
Born*ao2pi = 0.9431E-05 +/- 0.6953E-06 ( 7.372 %)
Chi^2 per d.o.f. 0.0000E+00
accumulated results ABS integral = 0.7580E-03 +/- 0.5337E-04 ( 7.041 %)
accumulated results Integral = 0.6952E-03 +/- 0.5040E-04 ( 7.250 %)
accumulated results Virtual = 0.4703E-04 +/- 0.3509E-05 ( 7.460 %)
accumulated results Virtual ratio = 0.5225E+01 +/- 0.1918E-01 ( 0.367 %)
accumulated results ABS virtual = 0.4790E-04 +/- 0.3503E-05 ( 7.314 %)
accumulated results Born*ao2pi = 0.9431E-05 +/- 0.6953E-06 ( 7.372 %)
accumulated result Chi^2 per DoF = 0.0000E+00
1: 0 1 2
channel 1 : 2 T 2080 0 0.7580E-03 0.6952E-03 0.2500E+00
------- iteration 2
Update # PS points (even): 2080 --> 2080
ABS integral = 0.8749E-03 +/- 0.1990E-04 ( 2.274 %)
Integral = 0.8152E-03 +/- 0.1933E-04 ( 2.371 %)
Virtual = 0.4564E-07 +/- 0.8008E-06 ( ******* %)
Virtual ratio = 0.5186E+01 +/- 0.2621E-01 ( 0.505 %)
ABS virtual = 0.6566E-05 +/- 0.7943E-06 ( 12.097 %)
Born*ao2pi = 0.1147E-04 +/- 0.5892E-06 ( 5.138 %)
Chi^2= 0.2546E+01
accumulated results ABS integral = 0.8431E-03 +/- 0.1864E-04 ( 2.211 %)
accumulated results Integral = 0.7819E-03 +/- 0.1805E-04 ( 2.308 %)
accumulated results Virtual = 0.8777E-05 +/- 0.7808E-06 ( 8.895 %)
accumulated results Virtual ratio = 0.5209E+01 +/- 0.1548E-01 ( 0.297 %)
accumulated results ABS virtual = 0.1421E-04 +/- 0.7747E-06 ( 5.453 %)
accumulated results Born*ao2pi = 0.1053E-04 +/- 0.4495E-06 ( 4.267 %)
accumulated result Chi^2 per DoF = 0.2546E+01
1: 0 1 2
channel 1 : 2 T 4160 2080 0.8431E-03 0.7819E-03 0.6250E-01
------- iteration 3
Update # PS points (even): 4160 --> 4160
ABS integral = 0.8440E-03 +/- 0.8427E-05 ( 0.998 %)
Integral = 0.7843E-03 +/- 0.8044E-05 ( 1.026 %)
Virtual = -.1280E-07 +/- 0.6696E-06 ( ******* %)
Virtual ratio = 0.5094E+01 +/- 0.3436E-01 ( 0.674 %)
ABS virtual = 0.6253E-05 +/- 0.6661E-06 ( 10.653 %)
Born*ao2pi = 0.1184E-04 +/- 0.6709E-06 ( 5.666 %)
Chi^2= 0.1037E-02
accumulated results ABS integral = 0.8437E-03 +/- 0.7679E-05 ( 0.910 %)
accumulated results Integral = 0.7835E-03 +/- 0.7347E-05 ( 0.938 %)
accumulated results Virtual = 0.4045E-05 +/- 0.5083E-06 ( 12.564 %)
accumulated results Virtual ratio = 0.5173E+01 +/- 0.1411E-01 ( 0.273 %)
accumulated results ABS virtual = 0.9929E-05 +/- 0.5050E-06 ( 5.086 %)
accumulated results Born*ao2pi = 0.1106E-04 +/- 0.3735E-06 ( 3.377 %)
accumulated result Chi^2 per DoF = 0.1274E+01
1: 0 1 2
channel 1 : 2 T 8320 4160 0.8437E-03 0.7835E-03 0.1562E-01
------- iteration 4
Update # PS points (even): 8320 --> 8320
ABS integral = 0.8437E-03 +/- 0.5619E-05 ( 0.666 %)
Integral = 0.7778E-03 +/- 0.5076E-05 ( 0.653 %)
Virtual = -.1156E-05 +/- 0.1317E-05 ( 113.977 %)
Virtual ratio = 0.4994E+01 +/- 0.9265E-01 ( 1.855 %)
ABS virtual = 0.6735E-05 +/- 0.1316E-05 ( 19.544 %)
Born*ao2pi = 0.1051E-04 +/- 0.8736E-06 ( 8.315 %)
Chi^2= 0.3615E-05
accumulated results ABS integral = 0.8437E-03 +/- 0.4534E-05 ( 0.537 %)
accumulated results Integral = 0.7802E-03 +/- 0.4176E-05 ( 0.535 %)
accumulated results Virtual = 0.2597E-05 +/- 0.4742E-06 ( 18.258 %)
accumulated results Virtual ratio = 0.5149E+01 +/- 0.1395E-01 ( 0.271 %)
accumulated results ABS virtual = 0.9043E-05 +/- 0.4715E-06 ( 5.214 %)
accumulated results Born*ao2pi = 0.1089E-04 +/- 0.3434E-06 ( 3.152 %)
accumulated result Chi^2 per DoF = 0.8490E+00
accumulated results last 3 iterations ABS integral = 0.8477E-03 +/- 0.4551E-05 ( 0.537 %)
accumulated results last 3 iterations Integral = 0.7841E-03 +/- 0.4191E-05 ( 0.534 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.8454E+00
1: 0 1 2
Found desired accuracy
channel 1 : 2 T 16636 8320 0.8437E-03 0.7802E-03 0.7326E-02
-------
Final result [ABS]: 8.4371106353474151E-004 +/- 4.5343347696796044E-006
Final result: 7.8015778037465668E-004 +/- 4.1762698253903520E-006
chi**2 per D.o.F.: 0.84901871103610882
Satistics from MadLoop:
Total points tried: 3361
Stability unknown: 0
Stable PS point: 3361
Unstable PS point (and rescued): 0
Exceptional PS point (unstable and not rescued): 0
Double precision used: 3361
Quadruple precision used: 0
Initialization phase-space points: 0
Unknown return code (100): 0
Unknown return code (10): 0
Unit return code distribution (1):
#Unit 6 = 3361
Time spent in Born : 3.27978659
Time spent in PS_Generation : 0.00000000
Time spent in Reals_evaluation: 14.0180092
Time spent in MCsubtraction : 9.95594692
Time spent in Counter_terms : 7.54694414
Time spent in Integrated_CT : 0.239453882
Time spent in Virtuals : 0.260916620
Time spent in FxFx_cluster : 0.00000000
Time spent in Nbody_prefactor : 3.39937067
Time spent in N1body_prefactor : 3.41732311
Time spent in Adding_alphas_pdf : 0.651198983
Time spent in Reweight_scale : 0.00000000
Time spent in Reweight_pdf : 0.00000000
Time spent in Filling_plots : 0.00000000
Time spent in Applying_cuts : 0.185251296
Time spent in Sum_ident_contr : 5.60155660E-02
Time spent in Pick_unwgt : 0.00000000
Time spent in Write_events : 0.00000000
Time spent in Other_tasks : 1.49882126
Time spent in Total : 44.5090408
Time in seconds: 45
</PRE><br>
</font>
</BODY></HTML>
<file_sep>/TimingMeasurement/B/SubProcesses/P1_bbx_zx0_z_ll_x0_qqqq/maxamps.inc
INTEGER MAXAMPS, MAXFLOW, MAXPROC, MAXSPROC
PARAMETER (MAXAMPS=10, MAXFLOW=2)
PARAMETER (MAXPROC=12, MAXSPROC=2)
<file_sep>/LHC_HH_2lep/Source/MODEL/param_write.inc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c written by the UFO converter
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
WRITE(*,*) ' External Params'
WRITE(*,*) ' ---------------------------------'
WRITE(*,*) ' '
WRITE(*,*) 'mdl_cabi = ', MDL_CABI
WRITE(*,*) 'mdl_rhoH = ', MDL_RHOH
WRITE(*,*) 'mdl_Lambda = ', MDL_LAMBDA
WRITE(*,*) 'mdl_fW = ', MDL_FW
WRITE(*,*) 'mdl_fWW = ', MDL_FWW
WRITE(*,*) 'mdl_fB = ', MDL_FB
WRITE(*,*) 'mdl_fBB = ', MDL_FBB
WRITE(*,*) 'aEWM1 = ', AEWM1
WRITE(*,*) 'mdl_Gf = ', MDL_GF
WRITE(*,*) 'aS = ', AS
WRITE(*,*) 'mdl_ymb = ', MDL_YMB
WRITE(*,*) 'mdl_ymt = ', MDL_YMT
WRITE(*,*) 'mdl_ymtau = ', MDL_YMTAU
WRITE(*,*) 'mdl_MZ = ', MDL_MZ
WRITE(*,*) 'mdl_MTA = ', MDL_MTA
WRITE(*,*) 'mdl_MT = ', MDL_MT
WRITE(*,*) 'mdl_MB = ', MDL_MB
WRITE(*,*) 'mdl_MH = ', MDL_MH
WRITE(*,*) 'mdl_MHH = ', MDL_MHH
WRITE(*,*) 'mdl_WZ = ', MDL_WZ
WRITE(*,*) 'mdl_WW = ', MDL_WW
WRITE(*,*) 'mdl_WT = ', MDL_WT
WRITE(*,*) 'mdl_WH = ', MDL_WH
WRITE(*,*) 'mdl_WHH = ', MDL_WHH
WRITE(*,*) ' Internal Params'
WRITE(*,*) ' ---------------------------------'
WRITE(*,*) ' '
WRITE(*,*) 'mdl_cos__cabi = ', MDL_COS__CABI
WRITE(*,*) 'mdl_CKM1x1 = ', MDL_CKM1X1
WRITE(*,*) 'mdl_sin__cabi = ', MDL_SIN__CABI
WRITE(*,*) 'mdl_CKM1x2 = ', MDL_CKM1X2
WRITE(*,*) 'mdl_CKM2x1 = ', MDL_CKM2X1
WRITE(*,*) 'mdl_CKM2x2 = ', MDL_CKM2X2
WRITE(*,*) 'mdl_MZ__exp__2 = ', MDL_MZ__EXP__2
WRITE(*,*) 'mdl_MZ__exp__4 = ', MDL_MZ__EXP__4
WRITE(*,*) 'mdl_sqrt__2 = ', MDL_SQRT__2
WRITE(*,*) 'mdl_Lambda__exp__2 = ', MDL_LAMBDA__EXP__2
WRITE(*,*) 'mdl_MH__exp__2 = ', MDL_MH__EXP__2
WRITE(*,*) 'mdl_complexi = ', MDL_COMPLEXI
WRITE(*,*) 'mdl_conjg__CKM1x1 = ', MDL_CONJG__CKM1X1
WRITE(*,*) 'mdl_conjg__CKM1x2 = ', MDL_CONJG__CKM1X2
WRITE(*,*) 'mdl_conjg__CKM2x1 = ', MDL_CONJG__CKM2X1
WRITE(*,*) 'mdl_conjg__CKM2x2 = ', MDL_CONJG__CKM2X2
WRITE(*,*) 'mdl_aEW = ', MDL_AEW
WRITE(*,*) 'mdl_MW = ', MDL_MW
WRITE(*,*) 'mdl_sqrt__aEW = ', MDL_SQRT__AEW
WRITE(*,*) 'mdl_ee = ', MDL_EE
WRITE(*,*) 'mdl_MW__exp__2 = ', MDL_MW__EXP__2
WRITE(*,*) 'mdl_sw2 = ', MDL_SW2
WRITE(*,*) 'mdl_cw = ', MDL_CW
WRITE(*,*) 'mdl_sqrt__sw2 = ', MDL_SQRT__SW2
WRITE(*,*) 'mdl_sw = ', MDL_SW
WRITE(*,*) 'mdl_g1 = ', MDL_G1
WRITE(*,*) 'mdl_gw = ', MDL_GW
WRITE(*,*) 'mdl_vev = ', MDL_VEV
WRITE(*,*) 'mdl_gHWW = ', MDL_GHWW
WRITE(*,*) 'mdl_gHWW1 = ', MDL_GHWW1
WRITE(*,*) 'mdl_gHWW2 = ', MDL_GHWW2
WRITE(*,*) 'mdl_cw__exp__2 = ', MDL_CW__EXP__2
WRITE(*,*) 'mdl_gHZZ = ', MDL_GHZZ
WRITE(*,*) 'mdl_sw__exp__2 = ', MDL_SW__EXP__2
WRITE(*,*) 'mdl_gHZZ1 = ', MDL_GHZZ1
WRITE(*,*) 'mdl_cw__exp__4 = ', MDL_CW__EXP__4
WRITE(*,*) 'mdl_sw__exp__4 = ', MDL_SW__EXP__4
WRITE(*,*) 'mdl_gHZZ2 = ', MDL_GHZZ2
WRITE(*,*) 'mdl_vev__exp__2 = ', MDL_VEV__EXP__2
WRITE(*,*) 'mdl_lam = ', MDL_LAM
WRITE(*,*) 'mdl_yb = ', MDL_YB
WRITE(*,*) 'mdl_yt = ', MDL_YT
WRITE(*,*) 'mdl_ytau = ', MDL_YTAU
WRITE(*,*) 'mdl_muH = ', MDL_MUH
WRITE(*,*) 'mdl_I1a33 = ', MDL_I1A33
WRITE(*,*) 'mdl_I2a33 = ', MDL_I2A33
WRITE(*,*) 'mdl_I3a33 = ', MDL_I3A33
WRITE(*,*) 'mdl_I4a33 = ', MDL_I4A33
WRITE(*,*) 'mdl_ee__exp__2 = ', MDL_EE__EXP__2
WRITE(*,*) ' Internal Params evaluated point by point'
WRITE(*,*) ' ----------------------------------------'
WRITE(*,*) ' '
WRITE(*,*) 'mdl_sqrt__aS = ', MDL_SQRT__AS
WRITE(*,*) 'mdl_G__exp__2 = ', MDL_G__EXP__2
<file_sep>/TimingMeasurement/A/SubProcesses/P1_qq_zx0_z_qq_x0_tamtapbbx/coloramps.inc
LOGICAL ICOLAMP(1,50,4)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,49,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,50,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,49,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,50,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,49,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,50,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,49,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,50,4),I=1,1)/.TRUE./
<file_sep>/fit_code/FitOneBin/out1.cc
void out1() {
gROOT->ProcessLine(".L fit_com_1.cc++");
gSystem->Load("fit_com_1_cc.so");
plot();
}
<file_sep>/TimingMeasurement/B/SubProcesses/P2_qq_zx0_z_ll_x0_tamvlqq/coloramps.inc
LOGICAL ICOLAMP(1,4,8)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,8),I=1,1)/.TRUE./
<file_sep>/fit_code/FitSpectrum/create.sh
for((i=2; i<4; i++)); do
let down=($i-1)*5+1
let up=($i-1)*5+7
cp fit_com_1.cc fit_com_$i.cc
sed -i "s/alpha_1/alpha_$i/g" fit_com_$i.cc
sed -i "s/Row>1/Row>$down/g" fit_com_$i.cc
sed -i "s/Row<7/Row<$up/g" fit_com_$i.cc
cp submit_1.sh submit_$i.sh
sed -i "s/out1/out$i/g" submit_$i.sh
cp out1.cc out$i.cc
sed -i "s/out1/out$i/g" out$i.cc
sed -i "s/com_1/com_$i/g" out$i.cc
done
<file_sep>/TimingMeasurement/A/Source/maxamps.inc
../SubProcesses/P1_bbx_zx0_z_bbx_x0_tamtapbbx/maxamps.inc<file_sep>/Processes/reader.h
// Declaration of leaf types
Int_t EventNumber;
Float_t mc_event_weight;
Int_t mu_n;
Float_t mu_E[4]; //[mu_n]
Float_t mu_pt[4]; //[mu_n]
Float_t mu_eta[4]; //[mu_n]
Float_t mu_phi[4]; //[mu_n]
Int_t mu_charge[4]; //[mu_n]
Int_t el_n;
Float_t el_E[4]; //[el_n]
Float_t el_pt[4]; //[el_n]
Float_t el_eta[4]; //[el_n]
Float_t el_phi[4]; //[el_n]
Int_t el_charge[4]; //[el_n]
Int_t jet_n;
Float_t jet_E[10]; //[jet_n]
Float_t jet_m[10]; //[jet_n]
Float_t jet_pt[10]; //[jet_n]
Float_t jet_eta[10]; //[jet_n]
Float_t jet_phi[10]; //[jet_n]
Float_t jet_tau1[10];
Float_t jet_tau2[10];
Float_t jet_tau3[10];
Float_t jet_tau4[10];
Bool_t jet_isBtagged[11];
Int_t fatjet_n;
Float_t fatjet_E[8]; //[fatjet_n]
Float_t fatjet_m[8]; //[fatjet_n]
Float_t fatjet_pt[8]; //[fatjet_n]
Float_t fatjet_eta[8]; //[fatjet_n]
Float_t fatjet_phi[8]; //[fatjet_n]
Float_t fatjet_tau1[8]; //[fatjet_n]
Float_t fatjet_tau2[8]; //[fatjet_n]
Float_t fatjet_tau3[8]; //[fatjet_n]
Float_t fatjet_tau4[8]; //[fatjet_n]
Int_t fatjet_sj_n[8]; //[fatjet_n]
Float_t fatjet_m_sj1[8]; //[fatjet_n]
Float_t fatjet_pt_sj1[8]; //[fatjet_n]
Float_t fatjet_eta_sj1[8]; //[fatjet_n]
Float_t fatjet_phi_sj1[8]; //[fatjet_n]
Float_t fatjet_m_sj2[8]; //[fatjet_n]
Float_t fatjet_pt_sj2[8]; //[fatjet_n]
Float_t fatjet_eta_sj2[8]; //[fatjet_n]
Float_t fatjet_phi_sj2[8]; //[fatjet_n]
Float_t MET_ex;
Float_t MET_ey;
Float_t MET_et;
Float_t MET_phi;
Float_t MET_sumet;
Float_t MET_Truth_NonInt_ex;
Float_t MET_Truth_NonInt_ey;
Float_t MET_Truth_NonInt_et;
Int_t jet_truth_n;
Float_t jet_truth_pt[15]; //[jet_truth_n]
Float_t jet_truth_eta[15]; //[jet_truth_n]
Float_t jet_truth_phi[15]; //[jet_truth_n]
Float_t jet_truth_m[15]; //[jet_truth_n]
Int_t fatjet_truth_n;
Float_t fatjet_truth_pt[10]; //[fatjet_truth_n]
Float_t fatjet_truth_eta[10]; //[fatjet_truth_n]
Float_t fatjet_truth_phi[10]; //[fatjet_truth_n]
Float_t fatjet_truth_m[10]; //[fatjet_truth_n]
Int_t truthV_n;
Int_t truthV_pdgId[3]; //[truthV_n]
Float_t truthV_pt[3]; //[truthV_n]
Float_t truthV_m[3]; //[truthV_n]
Float_t truthV_eta[3]; //[truthV_n]
Float_t truthV_phi[3]; //[truthV_n]
Int_t truthV_charge[3]; //[truthV_n]
Int_t truthV_dau1_pdgId[3]; //[truthV_n]
Float_t truthV_dau1_pt[3]; //[truthV_n]
Float_t truthV_dau1_m[3]; //[truthV_n]
Float_t truthV_dau1_eta[3]; //[truthV_n]
Float_t truthV_dau1_phi[3]; //[truthV_n]
Int_t truthV_dau1_charge[3]; //[truthV_n]
Int_t truthV_dau2_pdgId[3]; //[truthV_n]
Float_t truthV_dau2_pt[3]; //[truthV_n]
Float_t truthV_dau2_m[3]; //[truthV_n]
Float_t truthV_dau2_eta[3]; //[truthV_n]
Float_t truthV_dau2_phi[3]; //[truthV_n]
Int_t truthV_dau2_charge[3]; //[truthV_n]
// List of branches
TBranch *b_EventNumber; //!
TBranch *b_mc_event_weight; //!
TBranch *b_mu_n; //!
TBranch *b_mu_E; //!
TBranch *b_mu_pt; //!
TBranch *b_mu_eta; //!
TBranch *b_mu_phi; //!
TBranch *b_mu_charge; //!
TBranch *b_el_n; //!
TBranch *b_el_E; //!
TBranch *b_el_pt; //!
TBranch *b_el_eta; //!
TBranch *b_el_phi; //!
TBranch *b_el_charge; //!
TBranch *b_jet_n; //!
TBranch *b_jet_E; //!
TBranch *b_jet_m; //!
TBranch *b_jet_pt; //!
TBranch *b_jet_eta; //!
TBranch *b_jet_phi; //!
TBranch *b_jet_tau2; //!
TBranch *b_jet_tau1; //!
TBranch *b_jet_tau3; //!
TBranch *b_jet_tau4; //!
TBranch *b_jet_isBtagged; //!
TBranch *b_fatjet_n; //!
TBranch *b_fatjet_E; //!
TBranch *b_fatjet_m; //!
TBranch *b_fatjet_pt; //!
TBranch *b_fatjet_eta; //!
TBranch *b_fatjet_phi; //!
TBranch *b_fatjet_tau1; //!
TBranch *b_fatjet_tau2; //!
TBranch *b_fatjet_tau3; //!
TBranch *b_fatjet_tau4; //!
TBranch *b_fatjet_sj_n; //!
TBranch *b_fatjet_m_sj1; //!
TBranch *b_fatjet_pt_sj1; //!
TBranch *b_fatjet_eta_sj1; //!
TBranch *b_fatjet_phi_sj1; //!
TBranch *b_fatjet_m_sj2; //!
TBranch *b_fatjet_pt_sj2; //!
TBranch *b_fatjet_eta_sj2; //!
TBranch *b_fatjet_phi_sj2; //!
TBranch *b_MET_ex; //!
TBranch *b_MET_ey; //!
TBranch *b_MET_et; //!
TBranch *b_MET_phi; //!
TBranch *b_MET_sumet; //!
TBranch *b_MET_Truth_NonInt_ex; //!
TBranch *b_MET_Truth_NonInt_ey; //!
TBranch *b_MET_Truth_NonInt_et; //!
TBranch *b_jet_truth_n; //!
TBranch *b_jet_truth_pt; //!
TBranch *b_jet_truth_eta; //!
TBranch *b_jet_truth_phi; //!
TBranch *b_jet_truth_m; //!
TBranch *b_fatjet_truth_n; //!
TBranch *b_fatjet_truth_pt; //!
TBranch *b_fatjet_truth_eta; //!
TBranch *b_fatjet_truth_phi; //!
TBranch *b_fatjet_truth_m; //!
TBranch *b_truthV_n; //!
TBranch *b_truthV_pdgId; //!
TBranch *b_truthV_pt; //!
TBranch *b_truthV_m; //!
TBranch *b_truthV_eta; //!
TBranch *b_truthV_phi; //!
TBranch *b_truthV_charge; //!
TBranch *b_truthV_dau1_pdgId; //!
TBranch *b_truthV_dau1_pt; //!
TBranch *b_truthV_dau1_m; //!
TBranch *b_truthV_dau1_eta; //!
TBranch *b_truthV_dau1_phi; //!
TBranch *b_truthV_dau1_charge; //!
TBranch *b_truthV_dau2_pdgId; //!
TBranch *b_truthV_dau2_pt; //!
TBranch *b_truthV_dau2_m; //!
TBranch *b_truthV_dau2_eta; //!
TBranch *b_truthV_dau2_phi; //!
TBranch *b_truthV_dau2_charge; //!
void Init(TTree *tree)
{
// The Init() function is called when the selector needs to initialize
// a new tree or chain. Typically here the branch addresses and branch
// pointers of the tree will be set.
// It is normally not necessary to make changes to the generated
// code, but the routine can be extended by the user if needed.
// Init() will be called many times when running on PROOF
// (once per file to be processed).
// Set branch addresses and branch pointers
if (!tree) return;
TTree* fChain = tree;
fChain->SetMakeClass(1);
fChain->SetBranchAddress("EventNumber", &EventNumber, &b_EventNumber);
fChain->SetBranchAddress("mc_event_weight", &mc_event_weight, &b_mc_event_weight);
fChain->SetBranchAddress("mu_n", &mu_n, &b_mu_n);
fChain->SetBranchAddress("mu_E", mu_E, &b_mu_E);
fChain->SetBranchAddress("mu_pt", mu_pt, &b_mu_pt);
fChain->SetBranchAddress("mu_eta", mu_eta, &b_mu_eta);
fChain->SetBranchAddress("mu_phi", mu_phi, &b_mu_phi);
fChain->SetBranchAddress("mu_charge", mu_charge, &b_mu_charge);
fChain->SetBranchAddress("el_n", &el_n, &b_el_n);
fChain->SetBranchAddress("el_E", el_E, &b_el_E);
fChain->SetBranchAddress("el_pt", el_pt, &b_el_pt);
fChain->SetBranchAddress("el_eta", el_eta, &b_el_eta);
fChain->SetBranchAddress("el_phi", el_phi, &b_el_phi);
fChain->SetBranchAddress("el_charge", el_charge, &b_el_charge);
fChain->SetBranchAddress("jet_n", &jet_n, &b_jet_n);
fChain->SetBranchAddress("jet_E", jet_E, &b_jet_E);
fChain->SetBranchAddress("jet_m", jet_m, &b_jet_m);
fChain->SetBranchAddress("jet_pt", jet_pt, &b_jet_pt);
fChain->SetBranchAddress("jet_eta", jet_eta, &b_jet_eta);
fChain->SetBranchAddress("jet_phi", jet_phi, &b_jet_phi);
fChain->SetBranchAddress("jet_tau2", jet_tau2, &b_jet_tau2);
fChain->SetBranchAddress("jet_tau1", jet_tau1, &b_jet_tau1);
fChain->SetBranchAddress("jet_tau3", jet_tau3, &b_jet_tau3);
fChain->SetBranchAddress("jet_tau4", jet_tau4, &b_jet_tau4);
fChain->SetBranchAddress("jet_isBtagged", jet_isBtagged, &b_jet_isBtagged);
fChain->SetBranchAddress("fatjet_n", &fatjet_n, &b_fatjet_n);
fChain->SetBranchAddress("fatjet_E", fatjet_E, &b_fatjet_E);
fChain->SetBranchAddress("fatjet_m", fatjet_m, &b_fatjet_m);
fChain->SetBranchAddress("fatjet_pt", fatjet_pt, &b_fatjet_pt);
fChain->SetBranchAddress("fatjet_eta", fatjet_eta, &b_fatjet_eta);
fChain->SetBranchAddress("fatjet_phi", fatjet_phi, &b_fatjet_phi);
fChain->SetBranchAddress("fatjet_tau1", fatjet_tau1, &b_fatjet_tau1);
fChain->SetBranchAddress("fatjet_tau2", fatjet_tau2, &b_fatjet_tau2);
fChain->SetBranchAddress("fatjet_tau3", fatjet_tau3, &b_fatjet_tau3);
fChain->SetBranchAddress("fatjet_tau4", fatjet_tau4, &b_fatjet_tau4);
fChain->SetBranchAddress("fatjet_sj_n", fatjet_sj_n, &b_fatjet_sj_n);
fChain->SetBranchAddress("fatjet_m_sj1", fatjet_m_sj1, &b_fatjet_m_sj1);
fChain->SetBranchAddress("fatjet_pt_sj1", fatjet_pt_sj1, &b_fatjet_pt_sj1);
fChain->SetBranchAddress("fatjet_eta_sj1", fatjet_eta_sj1, &b_fatjet_eta_sj1);
fChain->SetBranchAddress("fatjet_phi_sj1", fatjet_phi_sj1, &b_fatjet_phi_sj1);
fChain->SetBranchAddress("fatjet_m_sj2", fatjet_m_sj2, &b_fatjet_m_sj2);
fChain->SetBranchAddress("fatjet_pt_sj2", fatjet_pt_sj2, &b_fatjet_pt_sj2);
fChain->SetBranchAddress("fatjet_eta_sj2", fatjet_eta_sj2, &b_fatjet_eta_sj2);
fChain->SetBranchAddress("fatjet_phi_sj2", fatjet_phi_sj2, &b_fatjet_phi_sj2);
fChain->SetBranchAddress("MET_ex", &MET_ex, &b_MET_ex);
fChain->SetBranchAddress("MET_ey", &MET_ey, &b_MET_ey);
fChain->SetBranchAddress("MET_et", &MET_et, &b_MET_et);
fChain->SetBranchAddress("MET_phi", &MET_phi, &b_MET_phi);
fChain->SetBranchAddress("MET_sumet", &MET_sumet, &b_MET_sumet);
fChain->SetBranchAddress("MET_Truth_NonInt_ex", &MET_Truth_NonInt_ex, &b_MET_Truth_NonInt_ex);
fChain->SetBranchAddress("MET_Truth_NonInt_ey", &MET_Truth_NonInt_ey, &b_MET_Truth_NonInt_ey);
fChain->SetBranchAddress("MET_Truth_NonInt_et", &MET_Truth_NonInt_et, &b_MET_Truth_NonInt_et);
fChain->SetBranchAddress("jet_truth_n", &jet_truth_n, &b_jet_truth_n);
fChain->SetBranchAddress("jet_truth_pt", jet_truth_pt, &b_jet_truth_pt);
fChain->SetBranchAddress("jet_truth_eta", jet_truth_eta, &b_jet_truth_eta);
fChain->SetBranchAddress("jet_truth_phi", jet_truth_phi, &b_jet_truth_phi);
fChain->SetBranchAddress("jet_truth_m", jet_truth_m, &b_jet_truth_m);
fChain->SetBranchAddress("fatjet_truth_n", &fatjet_truth_n, &b_fatjet_truth_n);
fChain->SetBranchAddress("fatjet_truth_pt", fatjet_truth_pt, &b_fatjet_truth_pt);
fChain->SetBranchAddress("fatjet_truth_eta", fatjet_truth_eta, &b_fatjet_truth_eta);
fChain->SetBranchAddress("fatjet_truth_phi", fatjet_truth_phi, &b_fatjet_truth_phi);
fChain->SetBranchAddress("fatjet_truth_m", fatjet_truth_m, &b_fatjet_truth_m);
fChain->SetBranchAddress("truthV_n", &truthV_n, &b_truthV_n);
fChain->SetBranchAddress("truthV_pdgId", truthV_pdgId, &b_truthV_pdgId);
fChain->SetBranchAddress("truthV_pt", truthV_pt, &b_truthV_pt);
fChain->SetBranchAddress("truthV_m", truthV_m, &b_truthV_m);
fChain->SetBranchAddress("truthV_eta", truthV_eta, &b_truthV_eta);
fChain->SetBranchAddress("truthV_phi", truthV_phi, &b_truthV_phi);
fChain->SetBranchAddress("truthV_charge", truthV_charge, &b_truthV_charge);
fChain->SetBranchAddress("truthV_dau1_pdgId", truthV_dau1_pdgId, &b_truthV_dau1_pdgId);
fChain->SetBranchAddress("truthV_dau1_pt", truthV_dau1_pt, &b_truthV_dau1_pt);
fChain->SetBranchAddress("truthV_dau1_m", truthV_dau1_m, &b_truthV_dau1_m);
fChain->SetBranchAddress("truthV_dau1_eta", truthV_dau1_eta, &b_truthV_dau1_eta);
fChain->SetBranchAddress("truthV_dau1_phi", truthV_dau1_phi, &b_truthV_dau1_phi);
fChain->SetBranchAddress("truthV_dau1_charge", truthV_dau1_charge, &b_truthV_dau1_charge);
fChain->SetBranchAddress("truthV_dau2_pdgId", truthV_dau2_pdgId, &b_truthV_dau2_pdgId);
fChain->SetBranchAddress("truthV_dau2_pt", truthV_dau2_pt, &b_truthV_dau2_pt);
fChain->SetBranchAddress("truthV_dau2_m", truthV_dau2_m, &b_truthV_dau2_m);
fChain->SetBranchAddress("truthV_dau2_eta", truthV_dau2_eta, &b_truthV_dau2_eta);
fChain->SetBranchAddress("truthV_dau2_phi", truthV_dau2_phi, &b_truthV_dau2_phi);
fChain->SetBranchAddress("truthV_dau2_charge", truthV_dau2_charge, &b_truthV_dau2_charge);
}
<file_sep>/fit_code/Elizabeth.h
#include "TROOT.h"
#include "TMath.h"
//#define M_PI 3.14159265359
// individual terms of the Poisson distribution
Double_t SUSYStat_PoissonTerm(Double_t lambda, Int_t i) {
if(lambda<0) {
printf("Error: input lambda can not be negative !\n");
return 0;
}
if(i<0) return 0;
else if(i==0) return exp(-lambda);
else {
Double_t t = exp(-lambda);
for(Int_t k=i;k>=1;k--) t *= lambda/k;
return t;
}
}
// forward declaration
Double_t SUSYStat_PoissonCCDF(Double_t lambda, Double_t n, Double_t precision=1e-6);
// the left tail integral (cdf) of the Poisson distribution
Double_t SUSYStat_PoissonCDF(Double_t lambda, Double_t n, Double_t precision=1e-6) {
if(lambda<0) {
printf("Error: input lambda can not be negative !\n");
return 0;
}
if(n<0) return 0;
else if(n>lambda) return 1-SUSYStat_PoissonCCDF(lambda,n);
Int_t i = Int_t(n);
Double_t t = SUSYStat_PoissonTerm(lambda,i);
Double_t p = t;
while(i>0 && t/p>precision) {
t *= i/lambda;
p += t;
i--;
}
// Int_t lo = Int_t(n);
// Double_t x = n-lo;
// if(x>0.5) p += SUSYStat_PoissonTerm(lambda,lo+1)*(x-0.5);
// else p -= SUSYStat_PoissonTerm(lambda,lo)*(0.5-x);
return p;
}
// the right tail integral (ccdf) of the Poisson distribution
Double_t SUSYStat_PoissonCCDF(Double_t lambda, Double_t n, Double_t precision) {
if(lambda<0) {
printf("Error: input lambda can not be negative !\n");
return 0;
}
if(n<0) return 1;
if(n<=lambda) return 1-SUSYStat_PoissonCDF(lambda,n);
Int_t i = Int_t(n)+1;
Double_t t = SUSYStat_PoissonTerm(lambda,i);
Double_t p = t;
while(t/p>precision) {
i++;
t *= lambda/i;
p += t;
}
// Int_t up = Int_t(n)+1;
// Double_t x = up-n;
// if(x>0.5) p += SUSYStat_PoissonTerm(lambda,up-1)*(x-0.5);
// else p -= SUSYStat_PoissonTerm(lambda,up)*(0.5-x);
return p;
}
// convert p-value to standard deviation (significance)
Double_t SUSYStat_SigFromP(Double_t p) {
if(p<=0 || p>=1) {
printf("Error: input p-value is invalid !\n");
return 0;
}
Double_t pval = (p<0.5?p:1-p);
Double_t sig = 0;
if(pval>6.221*10e-16) sig = sqrt(2.)*TMath::ErfcInverse(2*pval);
else { // asymptotic formula for very small pval
Double_t u = -2*log(sqrt(2*M_PI)*pval);
sig = sqrt(u-log(u));
}
return (p<0.5?sig:-sig);
}
// convert standard deviation to p-value
Double_t SUSYStat_Pval(Double_t Sig) {
// asymptotic formula for very large sig
if(Sig>20) return exp(-Sig*Sig/2)/sqrt(2*M_PI)/Sig;
else if(Sig<-20) return 1+exp(-Sig*Sig/2)/sqrt(2*M_PI)/Sig;
else return 0.5*TMath::Erfc(Sig/sqrt(2));
}
// LLR-based discovery significance with sys. error db on b0
// b0 is the expected background, n is the total observed
Double_t SUSYStat_DiscSig_LLR(Double_t b0, Double_t n, Double_t db) {
if(b0<0) {
printf("Error: input b0 can not be negative !\n");
return 0;
}
if(db<0) {
printf("Error: input db can not be negative !\n");
return 0;
}
if(n<=b0) return 0;
if(db==0) {
Double_t s = n-b0;
return sqrt(2*(s+b0)*log(1+s/b0)-2*s);
}
Double_t tmp = b0-db*db;
Double_t b = 0.5*(tmp+sqrt(pow(tmp,2)+4*db*db*n));
return sqrt(2*n*log(n/b)-n+b-(b-b0)*b0/db/db);
}
// integration-based discovery significance with sys. error db on b0
// b0 is the expected background, n is the total observed
Double_t SUSYStat_DiscSig_Int(Double_t b0, Double_t n, Double_t db, Double_t precision=1e-6) {
if(b0<0) {
printf("Error: input b0 can not be negative !\n");
return 0;
}
if(db<0) {
printf("Error: input db can not be negative !\n");
return 0;
}
if(n<=b0) return 0;
if(db==0) return SUSYStat_SigFromP(SUSYStat_PoissonCCDF(b0,n));
Double_t nsig = SUSYStat_SigFromP(precision);
Double_t p = 0;
Double_t C = 1/sqrt(2*M_PI)/db;
Double_t dx = 0.01;
Double_t x = -nsig;
while(x<nsig) {
Double_t b = b0+db*x;
p += C*exp(-0.5*pow((b-b0)/db,2))*db*dx*SUSYStat_PoissonCCDF(b<0?0:b,n);
x += dx;
}
return SUSYStat_SigFromP(p);
}
// LLR-based exclusion significance with sys. errors db and dmu (relative)
// on the expected background b0 and signal s0, rho is the correlation
// coefficient between db and dmu
Double_t SUSYStat_ExclSig_LLR(Double_t b0, Double_t s0, Double_t n, Double_t db, Double_t dmu, Double_t rho=0) {
if(b0<0 || s0<0) {
printf("Error: input b0 or s0 can not be negative !\n");
return 0;
}
if(db<0) {
printf("Error: input db can not be negative !\n");
return 0;
}
if(dmu<0) {
printf("Error: input dmu can not be negative !\n");
return 0;
}
if(fabs(rho)>1) {
printf("Error: input rho is invalid !\n");
return 0;
}
Double_t sign = (n<=s0+b0?1:-1);
if(db==0 && dmu==0) {
Double_t term = 0;
if(n!=0) term = 2*n*log(n/(s0+b0));
return sign*sqrt(term+2*(s0+b0)-2*n);
}
else {
Double_t d2 = db*db+s0*s0*dmu*dmu+2*rho*db*dmu*s0;
Double_t lambda = -0.5*(d2-s0-b0)+0.5*sqrt(pow(d2-s0-b0,2)+4*d2*n);
Double_t term = 0;
if(n!=0) term = 2*n*log(n/lambda);
return sign*sqrt(term+lambda-n+(s0+b0-lambda)/d2*(s0+b0));
}
}
// integration-based exclusion significance with sys. errors db and dmu (relative)
// on the expected background b0 and signal s0, rho is the correlation
// coefficient between db and dmu
Double_t SUSYStat_ExclSig_Int(Double_t b0, Double_t s0, Double_t n, Double_t db, Double_t dmu, Double_t rho=0, Double_t precision=1e-6) {
if(b0<0 || s0<0) {
printf("Error: input b0 or s0 can not be negative !\n");
return 0;
}
if(db<0) {
printf("Error: input db can not be negative !\n");
return 0;
}
if(dmu<0) {
printf("Error: input dmu can not be negative !\n");
return 0;
}
if(fabs(rho)>1) {
printf("Error: input rho is invalid !\n");
return 0;
}
if(n>=s0+b0) return 0;
Double_t nsig = SUSYStat_SigFromP(precision);
Double_t p = 0;
if(db==0 && dmu==0) {
return SUSYStat_SigFromP(SUSYStat_PoissonCDF(s0+b0,n));
}
else if(dmu==0) {
Double_t C = 1/sqrt(2*M_PI)/db;
Double_t dx = 0.01;
Double_t x = -nsig;
while(x<nsig) {
Double_t b = b0+db*x;
p += C*exp(-0.5*pow((b-b0)/db,2))*db*dx*SUSYStat_PoissonCDF(s0+(b<0?0:b),n);
x += dx;
}
}
else if(db==0) {
Double_t C = 1/sqrt(2*M_PI)/dmu;
Double_t dx = 0.01;
Double_t x = -nsig;
while(x<nsig) {
Double_t mu = 1+dmu*x;
p += C*exp(-0.5*pow((mu-1)/dmu,2))*dmu*dx*SUSYStat_PoissonCDF(s0*(mu<0?0:mu)+b0,n);
x += dx;
}
}
else if(fabs(rho)==1) {
Double_t C = 1/sqrt(2*M_PI)/dmu;
Double_t dx = 0.01;
Double_t x = -nsig;
while(x<nsig) {
Double_t mu = dmu*x;
p += C*exp(-0.5*pow(mu/dmu,2))*dmu*dx*SUSYStat_PoissonCDF((s0+mu*s0<0?0:s0+mu*s0)+(b0+mu*rho*b0*db/dmu<0?0:b0+mu*rho*b0*db/dmu),n);
x += dx;
}
}
else {
Double_t Dmu = dmu*sqrt(1-rho*rho);
Double_t C1 = 1/sqrt(2*M_PI)/db;
Double_t C2 = 1/sqrt(2*M_PI)/Dmu;
Double_t dx1 = 0.01;
Double_t dx2 = 0.01;
Double_t x1 = -nsig;
while(x1<nsig) {
Double_t b = b0+db*x1;
Double_t mean = 1+rho*(b-b0)*dmu/db;
Double_t x2 = -nsig;
while(x2<nsig) {
Double_t mu = mean+Dmu*x2;
p += C1*exp(-0.5*pow((b-b0)/db,2))*C2*exp(-0.5*pow((mu-mean)/Dmu,2))*db*dx1*Dmu*dx2*SUSYStat_PoissonCDF(s0*(mu<0?0:mu)+(b<0?0:b),n);
x2 += dx2;
}
x1 += dx1;
}
}
return SUSYStat_SigFromP(p);
}
<file_sep>/PROCNLO_HC_NLO_X0_UFO_0_3/Events/run_02/alllogs_1.html
<HTML><BODY>
<font face="courier" size=2><a name=/P0_dux_wmx0_wmepemz_no_a/GF1></a>
<font color="red">
<br>LOG file for integration channel /P0_dux_wmx0_wmepemz_no_a/GF1, 1 <br></font>
<PRE>
===============================================================
INFO: MadFKS read these parameters from FKS_params.dat
===============================================================
> IRPoleCheckThreshold = 1.0000000000000001E-005
> PrecisionVirtualAtRunTime = 1.0000000000000000E-003
> NHelForMCoverHels = 4
> VirtualFraction = 1.0000000000000000
> MinVirtualFraction = 5.0000000000000001E-003
===============================================================
A PDF is used, so alpha_s(MZ) is going to be modified
Old value of alpha_s from param_card: 0.11799999999999999
****************************************
NNPDFDriver version 1.0.3
Grid: NNPDF23nlo_as_0119_qed_mem0.grid
****************************************
New value of alpha_s from PDF nn23nlo: 0.11899999999999999
*****************************************************
* MadGraph/MadEvent *
* -------------------------------- *
* http://madgraph.hep.uiuc.edu *
* http://madgraph.phys.ucl.ac.be *
* http://madgraph.roma2.infn.it *
* -------------------------------- *
* *
* PARAMETER AND COUPLING VALUES *
* *
*****************************************************
External Params
---------------------------------
MU_R = 91.188000000000002
aEWM1 = 132.50700000000001
mdl_Gf = 1.1663900000000000E-005
aS = 0.11799999999999999
mdl_ymb = 4.7000000000000002
mdl_ymt = 173.00000000000000
mdl_ymtau = 1.7769999999999999
mdl_MT = 173.00000000000000
mdl_MB = 4.7000000000000002
mdl_MZ = 91.188000000000002
mdl_MTA = 1.7769999999999999
mdl_WT = 1.4915000000000000
mdl_WZ = 2.4414039999999999
mdl_WW = 2.0476000000000001
mdl_MX0 = 300.00000000000000
mdl_WX0 = 1.0604700000000000
mdl_Lambda = 5000.0000000000000
mdl_cosa = 1.0000000000000000
mdl_kSM = 5.0000000000000003E-002
mdl_kHtt = 0.0000000000000000
mdl_kAtt = 0.0000000000000000
mdl_kHbb = 0.0000000000000000
mdl_kAbb = 0.0000000000000000
mdl_kHll = 0.0000000000000000
mdl_kAll = 0.0000000000000000
mdl_kHaa = 0.0000000000000000
mdl_kAaa = 0.0000000000000000
mdl_kHza = 0.0000000000000000
mdl_kAza = 0.0000000000000000
mdl_kHzz = 8.1561199999999996
mdl_kAzz = 0.0000000000000000
mdl_kHww = 10.496200000000000
mdl_kAww = 0.0000000000000000
mdl_kHda = 0.0000000000000000
mdl_kHdz = 0.0000000000000000
mdl_kHdwR = 0.0000000000000000
mdl_kHdwI = 0.0000000000000000
Internal Params
---------------------------------
mdl_CKM11 = 1.0000000000000000
mdl_conjg__CKM3x3 = 1.0000000000000000
mdl_conjg__CKM11 = 1.0000000000000000
mdl_lhv = 1.0000000000000000
mdl_CKM3x3 = 1.0000000000000000
mdl_conjg__CKM33 = 1.0000000000000000
mdl_Ncol = 3.0000000000000000
mdl_CA = 3.0000000000000000
mdl_TF = 0.50000000000000000
mdl_CF = 1.3333333333333333
mdl_complexi = ( 0.0000000000000000 , 1.0000000000000000 )
mdl_MZ__exp__2 = 8315.2513440000002
mdl_MZ__exp__4 = 69143404.913893804
mdl_sqrt__2 = 1.4142135623730951
mdl_MX0__exp__2 = 90000.000000000000
mdl_cosa__exp__2 = 1.0000000000000000
mdl_sina = 0.0000000000000000
mdl_kHdw = ( 0.0000000000000000 , 0.0000000000000000 )
mdl_nb__2__exp__0_75 = 1.6817928305074290
mdl_Ncol__exp__2 = 9.0000000000000000
mdl_MB__exp__2 = 22.090000000000003
mdl_MT__exp__2 = 29929.000000000000
mdl_conjg__kHdw = ( 0.0000000000000000 , -0.0000000000000000 )
mdl_aEW = 7.5467711139788835E-003
mdl_MW = 80.419002445756163
mdl_sqrt__aEW = 8.6872153846781555E-002
mdl_ee = 0.30795376724436879
mdl_MW__exp__2 = 6467.2159543705357
mdl_sw2 = 0.22224648578577766
mdl_cw = 0.88190334743339216
mdl_sqrt__sw2 = 0.47143025548407230
mdl_sw = 0.47143025548407230
mdl_g1 = 0.34919219678733299
mdl_gw = 0.65323293034757990
mdl_vev = 246.21845810181637
mdl_vev__exp__2 = 60623.529110035903
mdl_lam = 0.74228605065735920
mdl_yb = 2.6995554250465490E-002
mdl_yt = 0.99366614581500623
mdl_ytau = 1.0206617000654717E-002
mdl_muH = 212.13203435596427
mdl_AxialZUp = -0.18517701861793787
mdl_AxialZDown = 0.18517701861793787
mdl_VectorZUp = 7.5430507588273299E-002
mdl_VectorZDown = -0.13030376310310560
mdl_VectorAUp = 0.20530251149624587
mdl_VectorADown = -0.10265125574812294
mdl_VectorWmDxU = 0.23095271737156670
mdl_AxialWmDxU = -0.23095271737156670
mdl_VectorWpUxD = 0.23095271737156670
mdl_AxialWpUxD = -0.23095271737156670
mdl_I1x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_I2x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I3x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I4x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_Vector_tbGp = (-0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGp = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_Vector_tbGm = ( 0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGm = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_ee__exp__2 = 9.4835522759998875E-002
mdl_gAaa = 1.3008566310666950E-005
mdl_cw__exp__2 = 0.77775351421422245
mdl_gAza = 4.7794971072590281E-006
mdl_gHaa = 2.5475109025056106E-005
mdl_gHza = 3.9182129211851395E-005
mdl_gw__exp__2 = 0.42671326129048615
mdl_sw__exp__2 = 0.22224648578577769
Internal Params evaluated point by point
----------------------------------------
mdl_sqrt__aS = 0.34351128074635334
mdl_G__exp__2 = 1.4828317324943823
mdl_G__exp__4 = 2.1987899468922913
mdl_R2MixedFactor_FIN_ = -2.5040377713124864E-002
mdl_GWcft_UV_b_1EPS_ = -3.1300472141406080E-003
mdl_GWcft_UV_t_1EPS_ = -3.1300472141406080E-003
mdl_bWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_tWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_G__exp__3 = 1.8056676068262196
mdl_MU_R__exp__2 = 8315.2513440000002
mdl_GWcft_UV_b_FIN_ = -1.8563438626678915E-002
mdl_GWcft_UV_t_FIN_ = 4.0087659331150384E-003
mdl_bWcft_UV_FIN_ = -0.13642100947319838
mdl_tWcft_UV_FIN_ = -9.8778211443463623E-004
mdl_gAgg = 7.6274879753643885E-005
mdl_gHgg = -5.0849919835762592E-005
Couplings of HC_NLO_X0_UFO
---------------------------------
R2_dxuW = -0.00000E+00 -0.11566E-01
GC_5 = 0.00000E+00 0.12177E+01
GC_3005a = -0.00000E+00 -0.00000E+00
GC_3005h2 = -0.00000E+00 -0.00000E+00
GC_3005h3 = -0.00000E+00 -0.20992E-02
GC_3005h4 = -0.00000E+00 -0.00000E+00
GC_3007a = -0.00000E+00 -0.00000E+00
GC_3007h2 = -0.00000E+00 -0.16312E-02
GC_3007h3 = -0.00000E+00 -0.00000E+00
GC_22 = 0.00000E+00 0.28804E+00
GC_24 = 0.00000E+00 0.82310E-01
GC_47 = 0.00000E+00 0.46191E+00
GC_3005h1 = 0.00000E+00 0.26266E+01
GC_3007h1 = 0.00000E+00 0.33772E+01
Collider parameters:
--------------------
Running at P P machine @ 13000.000000000000 GeV
PDF set = nn23nlo
alpha_s(Mz)= 0.1190 running at 2 loops.
alpha_s(Mz)= 0.1190 running at 2 loops.
Renormalization scale set on event-by-event basis
Factorization scale set on event-by-event basis
Diagram information for clustering has been set-up for nFKSprocess 1
Diagram information for clustering has been set-up for nFKSprocess 2
Diagram information for clustering has been set-up for nFKSprocess 3
Diagram information for clustering has been set-up for nFKSprocess 4
getting user params
Enter number of events and iterations:
Number of events and iterations -1 12
Enter desired fractional accuracy:
Desired fractional accuracy: 2.4307304179300000E-002
Enter alpha, beta for G_soft
Enter alpha<0 to set G_soft=1 (no ME soft)
for G_soft: alpha= 1.0000000000000000 , beta= -0.10000000000000001
Enter alpha, beta for G_azi
Enter alpha>0 to set G_azi=0 (no azi corr)
for G_azi: alpha= -1.0000000000000000 , beta= -0.10000000000000001
Doing the S and H events together
Suppress amplitude (0 no, 1 yes)?
Using suppressed amplitude.
Exact helicity sum (0 yes, n = number/event)?
Do MC over helicities for the virtuals
Enter Configuration Number:
Running Configuration Number: 1
Enter running mode for MINT:
0 to set-up grids, 1 to integrate, 2 to generate events
MINT running mode: 1
Set the three folding parameters for MINT
xi_i, phi_i, y_ij
1 1 1
'all ', 'born', 'real', 'virt', 'novi' or 'grid'?
Enter 'born0' or 'virt0' to perform
a pure n-body integration (no S functions)
doing the all of this channel
Normal integration (Sfunction != 1)
about to integrate 13 -1 12 1
imode is 1
channel 1 : 1 F 0 0 0.2561E-02 0.0000E+00 0.7065E-02
+----------------------------------------------------------------+
| |
| Ninja - version 1.2.0 |
| |
| Author: <NAME> |
| |
| Based on: |
| |
| <NAME>, <NAME> and <NAME>, |
| "Integrand reduction of one-loop scattering amplitudes |
| through Laurent series expansion," |
| JHEP 1206 (2012) 095 [arXiv:1203.0291 [hep-ph]]. |
| |
| <NAME>, |
| "Ninja: Automated Integrand Reduction via Laurent |
| Expansion for One-Loop Amplitudes," |
| Comput.Phys.Commun. 185 (2014) [arXiv:1403.1229 [hep-ph]] |
| |
+----------------------------------------------------------------+
------- iteration 1
Update # PS points: 1040 --> 1040
Using random seed offsets: 1 , 1 , 0
with seed 34
Ranmar initialization seeds 13168 9409
Total number of FKS directories is 4
FKS process map (sum= 3 ) :
1 --> 2 : 1 3
2 --> 2 : 2 4
================================
process combination map (specified per FKS dir):
1 map 1 2 3 4
1 inv. map 1 2 3 4
2 map 1 2 3 4
2 inv. map 1 2 3 4
3 map 1 2 3 4
3 inv. map 1 2 3 4
4 map 1 2 3 4
4 inv. map 1 2 3 4
================================
tau_min 1 1 : 0.17161E+03 -- 0.38042E+03
tau_min 2 1 : 0.17161E+03 -- 0.38042E+03
tau_min 3 1 : 0.17161E+03 -- 0.38042E+03
tau_min 4 1 : 0.17161E+03 -- 0.38042E+03
bpower is 0.0000000000000000
Scale values (may change event by event):
muR, muR_reference: 0.241030D+03 0.241030D+03 1.00
muF1, muF1_reference: 0.241030D+03 0.241030D+03 1.00
muF2, muF2_reference: 0.241030D+03 0.241030D+03 1.00
QES, QES_reference: 0.241030D+03 0.241030D+03 1.00
muR_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF1_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF2_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
QES_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
alpha_s= 0.10371061416748721
alpha_s value used for the virtuals is (for the first PS point): 0.10612305078433161
==========================================================================================
{ }
{ [32m [0m }
{ [32m ,, [0m }
{ [32m`7MMM. ,MMF' `7MM `7MMF' [0m }
{ [32m MMMb dPMM MM MM [0m }
{ [32m M YM ,M MM ,6"Yb. ,M""bMM MM ,pW"Wq. ,pW"Wq.`7MMpdMAo. [0m }
{ [32m M Mb M' MM 8) MM ,AP MM MM 6W' `Wb 6W' `Wb MM `Wb [0m }
{ [32m M YM.P' MM ,pm9MM 8MI MM MM , 8M M8 8M M8 MM M8 [0m }
{ [32m M `YM' MM 8M MM `Mb MM MM ,M YA. ,A9 YA. ,A9 MM ,AP [0m }
{ [32m.JML. `' .JMML.`Moo9^Yo.`Wbmd"MML..JMMmmmmMMM `Ybmd9' `Ybmd9' MMbmmd' [0m }
{ [32m MM [0m }
{ [32m .JMML. [0m }
{ [32m[0mv2.6.6 (2018-06-28), Ref: arXiv:1103.0621v2, arXiv:1405.0301[32m [0m }
{ [32m [0m }
{ }
==========================================================================================
===============================================================
INFO: MadLoop read these parameters from ../MadLoop5_resources/MadLoopParams.dat
===============================================================
> MLReductionLib = 6|7|1
> CTModeRun = -1
> MLStabThres = 1.0000000000000000E-003
> NRotations_DP = 0
> NRotations_QP = 0
> CTStabThres = 1.0000000000000000E-002
> CTLoopLibrary = 2
> CTModeInit = 1
> CheckCycle = 3
> MaxAttempts = 10
> UseLoopFilter = F
> HelicityFilterLevel = 2
> ImprovePSPoint = 2
> DoubleCheckHelicityFilter = T
> LoopInitStartOver = F
> HelInitStartOver = F
> ZeroThres = 1.0000000000000001E-009
> OSThres = 1.0000000000000000E-008
> WriteOutFilters = T
> UseQPIntegrandForNinja = T
> UseQPIntegrandForCutTools = T
> IREGIMODE = 2
> IREGIRECY = T
> COLLIERMode = 1
> COLLIERRequiredAccuracy = 1.0000000000000000E-008
> COLLIERCanOutput = F
> COLLIERComputeUVpoles = T
> COLLIERComputeIRpoles = T
> COLLIERGlobalCache = -1
> COLLIERUseCacheForPoles = F
> COLLIERUseInternalStabilityTest = T
===============================================================
------------------------------------------------------------------------
| You are using CutTools - Version 1.9.3 |
| Authors: <NAME>, <NAME>, <NAME> |
| Published in JHEP 0803:042,2008 |
| http://www.ugr.es/~pittau/CutTools |
| |
| Compiler with 34 significant digits detetected |
----------------------------------------------------------------------
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
---- POLES CANCELLED ----
ABS integral = 0.2542E-02 +/- 0.4380E-04 ( 1.723 %)
Integral = 0.2349E-02 +/- 0.3687E-04 ( 1.570 %)
Virtual = 0.5864E-05 +/- 0.2459E-05 ( 41.931 %)
Virtual ratio = 0.5392E+01 +/- 0.5383E-01 ( 0.998 %)
ABS virtual = 0.5864E-05 +/- 0.2459E-05 ( 41.931 %)
Born*ao2pi = 0.1040E-06 +/- 0.4062E-07 ( 39.059 %)
Chi^2 per d.o.f. 0.0000E+00
accumulated results ABS integral = 0.2542E-02 +/- 0.4380E-04 ( 1.723 %)
accumulated results Integral = 0.2349E-02 +/- 0.3687E-04 ( 1.570 %)
accumulated results Virtual = 0.5864E-05 +/- 0.2459E-05 ( 41.931 %)
accumulated results Virtual ratio = 0.5392E+01 +/- 0.5383E-01 ( 0.998 %)
accumulated results ABS virtual = 0.5864E-05 +/- 0.2459E-05 ( 41.931 %)
accumulated results Born*ao2pi = 0.1040E-06 +/- 0.4062E-07 ( 39.059 %)
accumulated result Chi^2 per DoF = 0.0000E+00
channel 1 : 1 F 0 0 0.2542E-02 0.2349E-02 0.7065E-02
------- iteration 2
Update # PS points: 2080 --> 2080
ABS integral = 0.2543E-02 +/- 0.2742E-04 ( 1.078 %)
Integral = 0.2359E-02 +/- 0.2680E-04 ( 1.136 %)
Virtual = -.1496E-06 +/- 0.6041E-05 ( ******* %)
Virtual ratio = 0.5000E+01 +/- 0.2600E+00 ( 5.200 %)
ABS virtual = 0.1544E-04 +/- 0.6036E-05 ( 39.084 %)
Born*ao2pi = 0.1496E-06 +/- 0.3816E-07 ( 25.517 %)
Chi^2= 0.1171E-03
accumulated results ABS integral = 0.2543E-02 +/- 0.2324E-04 ( 0.914 %)
accumulated results Integral = 0.2355E-02 +/- 0.2168E-04 ( 0.920 %)
accumulated results Virtual = 0.4124E-05 +/- 0.2277E-05 ( 55.218 %)
accumulated results Virtual ratio = 0.5325E+01 +/- 0.5271E-01 ( 0.990 %)
accumulated results ABS virtual = 0.8637E-05 +/- 0.2277E-05 ( 26.365 %)
accumulated results Born*ao2pi = 0.1275E-06 +/- 0.2781E-07 ( 21.817 %)
accumulated result Chi^2 per DoF = 0.1171E-03
channel 1 : 1 F 0 0 0.2543E-02 0.2355E-02 0.7065E-02
------- iteration 3
Update # PS points: 4160 --> 4160
ABS integral = 0.2594E-02 +/- 0.2493E-04 ( 0.961 %)
Integral = 0.2409E-02 +/- 0.2410E-04 ( 1.000 %)
Virtual = 0.7609E-05 +/- 0.2146E-05 ( 28.199 %)
Virtual ratio = 0.5272E+01 +/- 0.6038E-01 ( 1.145 %)
ABS virtual = 0.9443E-05 +/- 0.2145E-05 ( 22.712 %)
Born*ao2pi = 0.1670E-06 +/- 0.3414E-07 ( 20.438 %)
Chi^2= 0.1124E+01
accumulated results ABS integral = 0.2568E-02 +/- 0.1700E-04 ( 0.662 %)
accumulated results Integral = 0.2381E-02 +/- 0.1612E-04 ( 0.677 %)
accumulated results Virtual = 0.5918E-05 +/- 0.1562E-05 ( 26.387 %)
accumulated results Virtual ratio = 0.5300E+01 +/- 0.3971E-01 ( 0.749 %)
accumulated results ABS virtual = 0.9052E-05 +/- 0.1561E-05 ( 17.248 %)
accumulated results Born*ao2pi = 0.1452E-06 +/- 0.2156E-07 ( 14.846 %)
accumulated result Chi^2 per DoF = 0.5619E+00
channel 1 : 1 F 0 0 0.2568E-02 0.2381E-02 0.7065E-02
------- iteration 4
Update # PS points: 8320 --> 8320
ABS integral = 0.2531E-02 +/- 0.1337E-04 ( 0.528 %)
Integral = 0.2351E-02 +/- 0.1335E-04 ( 0.568 %)
Virtual = 0.3684E-06 +/- 0.3579E-05 ( 971.702 %)
Virtual ratio = 0.4964E+01 +/- 0.1179E+00 ( 2.375 %)
ABS virtual = 0.1802E-04 +/- 0.3577E-05 ( 19.850 %)
Born*ao2pi = 0.2177E-06 +/- 0.2361E-07 ( 10.842 %)
Chi^2= 0.1443E+01
accumulated results ABS integral = 0.2547E-02 +/- 0.1051E-04 ( 0.413 %)
accumulated results Integral = 0.2364E-02 +/- 0.1028E-04 ( 0.435 %)
accumulated results Virtual = 0.4233E-05 +/- 0.1431E-05 ( 33.818 %)
accumulated results Virtual ratio = 0.5216E+01 +/- 0.3763E-01 ( 0.722 %)
accumulated results ABS virtual = 0.1178E-04 +/- 0.1431E-05 ( 12.150 %)
accumulated results Born*ao2pi = 0.1798E-06 +/- 0.1592E-07 ( 8.853 %)
accumulated result Chi^2 per DoF = 0.8555E+00
accumulated results last 3 iterations ABS integral = 0.2547E-02 +/- 0.1082E-04 ( 0.425 %)
accumulated results last 3 iterations Integral = 0.2365E-02 +/- 0.1071E-04 ( 0.453 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.1211E+01
channel 1 : 1 F 0 0 0.2547E-02 0.2364E-02 0.7065E-02
------- iteration 5
Update # PS points: 16640 --> 16640
ABS integral = 0.2549E-02 +/- 0.1626E-04 ( 0.638 %)
Integral = 0.2358E-02 +/- 0.1636E-04 ( 0.694 %)
Virtual = -.2885E-05 +/- 0.3966E-05 ( 137.497 %)
Virtual ratio = 0.4960E+01 +/- 0.7840E-01 ( 1.581 %)
ABS virtual = 0.2349E-04 +/- 0.3964E-05 ( 16.874 %)
Born*ao2pi = 0.2479E-06 +/- 0.1811E-07 ( 7.304 %)
Chi^2= 0.3130E-02
accumulated results ABS integral = 0.2548E-02 +/- 0.8825E-05 ( 0.346 %)
accumulated results Integral = 0.2362E-02 +/- 0.8704E-05 ( 0.369 %)
accumulated results Virtual = 0.2345E-05 +/- 0.1346E-05 ( 57.411 %)
accumulated results Virtual ratio = 0.5133E+01 +/- 0.3393E-01 ( 0.661 %)
accumulated results ABS virtual = 0.1488E-04 +/- 0.1346E-05 ( 9.042 %)
accumulated results Born*ao2pi = 0.2117E-06 +/- 0.1196E-07 ( 5.648 %)
accumulated result Chi^2 per DoF = 0.6424E+00
accumulated results last 3 iterations ABS integral = 0.2551E-02 +/- 0.9539E-05 ( 0.374 %)
accumulated results last 3 iterations Integral = 0.2366E-02 +/- 0.9504E-05 ( 0.402 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.1361E+01
Found desired accuracy
channel 1 : 1 F 0 0 0.2548E-02 0.2362E-02 0.7065E-02
-------
Final result [ABS]: 2.5626536599710993E-003 +/- 8.9268137500251145E-006
Final result: 2.3615847039148946E-003 +/- 8.7041919124186468E-006
chi**2 per D.o.F.: 0.64240882745673966
Satistics from MadLoop:
Total points tried: 416
Stability unknown: 0
Stable PS point: 416
Unstable PS point (and rescued): 0
Exceptional PS point (unstable and not rescued): 0
Double precision used: 416
Quadruple precision used: 0
Initialization phase-space points: 0
Unknown return code (100): 0
Unknown return code (10): 0
Unit return code distribution (1):
#Unit 6 = 416
Time spent in Born : 1.69362450
Time spent in PS_Generation : 0.00000000
Time spent in Reals_evaluation: 13.0106173
Time spent in MCsubtraction : 5.36766481
Time spent in Counter_terms : 7.14002800
Time spent in Integrated_CT : 0.311251342
Time spent in Virtuals : 4.91211563E-02
Time spent in FxFx_cluster : 0.00000000
Time spent in Nbody_prefactor : 1.77012241
Time spent in N1body_prefactor : 1.89570725
Time spent in Adding_alphas_pdf : 1.23763585
Time spent in Reweight_scale : 0.00000000
Time spent in Reweight_pdf : 0.00000000
Time spent in Filling_plots : 0.00000000
Time spent in Applying_cuts : 0.354371279
Time spent in Sum_ident_contr : 0.106068090
Time spent in Pick_unwgt : 0.00000000
Time spent in Write_events : 0.00000000
Time spent in Other_tasks : 2.84969330
Time spent in Total : 35.7859077
Time in seconds: 36
</PRE><br>
<a name=/P0_uxd_wmx0_wmepemz_no_a/GF1></a>
<font color="red">
<br>LOG file for integration channel /P0_uxd_wmx0_wmepemz_no_a/GF1, 1 <br></font>
<PRE>
===============================================================
INFO: MadFKS read these parameters from FKS_params.dat
===============================================================
> IRPoleCheckThreshold = 1.0000000000000001E-005
> PrecisionVirtualAtRunTime = 1.0000000000000000E-003
> NHelForMCoverHels = 4
> VirtualFraction = 1.0000000000000000
> MinVirtualFraction = 5.0000000000000001E-003
===============================================================
A PDF is used, so alpha_s(MZ) is going to be modified
Old value of alpha_s from param_card: 0.11799999999999999
****************************************
NNPDFDriver version 1.0.3
Grid: NNPDF23nlo_as_0119_qed_mem0.grid
****************************************
New value of alpha_s from PDF nn23nlo: 0.11899999999999999
*****************************************************
* MadGraph/MadEvent *
* -------------------------------- *
* http://madgraph.hep.uiuc.edu *
* http://madgraph.phys.ucl.ac.be *
* http://madgraph.roma2.infn.it *
* -------------------------------- *
* *
* PARAMETER AND COUPLING VALUES *
* *
*****************************************************
External Params
---------------------------------
MU_R = 91.188000000000002
aEWM1 = 132.50700000000001
mdl_Gf = 1.1663900000000000E-005
aS = 0.11799999999999999
mdl_ymb = 4.7000000000000002
mdl_ymt = 173.00000000000000
mdl_ymtau = 1.7769999999999999
mdl_MT = 173.00000000000000
mdl_MB = 4.7000000000000002
mdl_MZ = 91.188000000000002
mdl_MTA = 1.7769999999999999
mdl_WT = 1.4915000000000000
mdl_WZ = 2.4414039999999999
mdl_WW = 2.0476000000000001
mdl_MX0 = 300.00000000000000
mdl_WX0 = 1.0604700000000000
mdl_Lambda = 5000.0000000000000
mdl_cosa = 1.0000000000000000
mdl_kSM = 5.0000000000000003E-002
mdl_kHtt = 0.0000000000000000
mdl_kAtt = 0.0000000000000000
mdl_kHbb = 0.0000000000000000
mdl_kAbb = 0.0000000000000000
mdl_kHll = 0.0000000000000000
mdl_kAll = 0.0000000000000000
mdl_kHaa = 0.0000000000000000
mdl_kAaa = 0.0000000000000000
mdl_kHza = 0.0000000000000000
mdl_kAza = 0.0000000000000000
mdl_kHzz = 8.1561199999999996
mdl_kAzz = 0.0000000000000000
mdl_kHww = 10.496200000000000
mdl_kAww = 0.0000000000000000
mdl_kHda = 0.0000000000000000
mdl_kHdz = 0.0000000000000000
mdl_kHdwR = 0.0000000000000000
mdl_kHdwI = 0.0000000000000000
Internal Params
---------------------------------
mdl_CKM11 = 1.0000000000000000
mdl_conjg__CKM3x3 = 1.0000000000000000
mdl_conjg__CKM11 = 1.0000000000000000
mdl_lhv = 1.0000000000000000
mdl_CKM3x3 = 1.0000000000000000
mdl_conjg__CKM33 = 1.0000000000000000
mdl_Ncol = 3.0000000000000000
mdl_CA = 3.0000000000000000
mdl_TF = 0.50000000000000000
mdl_CF = 1.3333333333333333
mdl_complexi = ( 0.0000000000000000 , 1.0000000000000000 )
mdl_MZ__exp__2 = 8315.2513440000002
mdl_MZ__exp__4 = 69143404.913893804
mdl_sqrt__2 = 1.4142135623730951
mdl_MX0__exp__2 = 90000.000000000000
mdl_cosa__exp__2 = 1.0000000000000000
mdl_sina = 0.0000000000000000
mdl_kHdw = ( 0.0000000000000000 , 0.0000000000000000 )
mdl_nb__2__exp__0_75 = 1.6817928305074290
mdl_Ncol__exp__2 = 9.0000000000000000
mdl_MB__exp__2 = 22.090000000000003
mdl_MT__exp__2 = 29929.000000000000
mdl_conjg__kHdw = ( 0.0000000000000000 , -0.0000000000000000 )
mdl_aEW = 7.5467711139788835E-003
mdl_MW = 80.419002445756163
mdl_sqrt__aEW = 8.6872153846781555E-002
mdl_ee = 0.30795376724436879
mdl_MW__exp__2 = 6467.2159543705357
mdl_sw2 = 0.22224648578577766
mdl_cw = 0.88190334743339216
mdl_sqrt__sw2 = 0.47143025548407230
mdl_sw = 0.47143025548407230
mdl_g1 = 0.34919219678733299
mdl_gw = 0.65323293034757990
mdl_vev = 246.21845810181637
mdl_vev__exp__2 = 60623.529110035903
mdl_lam = 0.74228605065735920
mdl_yb = 2.6995554250465490E-002
mdl_yt = 0.99366614581500623
mdl_ytau = 1.0206617000654717E-002
mdl_muH = 212.13203435596427
mdl_AxialZUp = -0.18517701861793787
mdl_AxialZDown = 0.18517701861793787
mdl_VectorZUp = 7.5430507588273299E-002
mdl_VectorZDown = -0.13030376310310560
mdl_VectorAUp = 0.20530251149624587
mdl_VectorADown = -0.10265125574812294
mdl_VectorWmDxU = 0.23095271737156670
mdl_AxialWmDxU = -0.23095271737156670
mdl_VectorWpUxD = 0.23095271737156670
mdl_AxialWpUxD = -0.23095271737156670
mdl_I1x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_I2x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I3x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I4x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_Vector_tbGp = (-0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGp = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_Vector_tbGm = ( 0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGm = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_ee__exp__2 = 9.4835522759998875E-002
mdl_gAaa = 1.3008566310666950E-005
mdl_cw__exp__2 = 0.77775351421422245
mdl_gAza = 4.7794971072590281E-006
mdl_gHaa = 2.5475109025056106E-005
mdl_gHza = 3.9182129211851395E-005
mdl_gw__exp__2 = 0.42671326129048615
mdl_sw__exp__2 = 0.22224648578577769
Internal Params evaluated point by point
----------------------------------------
mdl_sqrt__aS = 0.34351128074635334
mdl_G__exp__2 = 1.4828317324943823
mdl_G__exp__4 = 2.1987899468922913
mdl_R2MixedFactor_FIN_ = -2.5040377713124864E-002
mdl_GWcft_UV_b_1EPS_ = -3.1300472141406080E-003
mdl_GWcft_UV_t_1EPS_ = -3.1300472141406080E-003
mdl_bWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_tWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_G__exp__3 = 1.8056676068262196
mdl_MU_R__exp__2 = 8315.2513440000002
mdl_GWcft_UV_b_FIN_ = -1.8563438626678915E-002
mdl_GWcft_UV_t_FIN_ = 4.0087659331150384E-003
mdl_bWcft_UV_FIN_ = -0.13642100947319838
mdl_tWcft_UV_FIN_ = -9.8778211443463623E-004
mdl_gAgg = 7.6274879753643885E-005
mdl_gHgg = -5.0849919835762592E-005
Couplings of HC_NLO_X0_UFO
---------------------------------
R2_dxuW = -0.00000E+00 -0.11566E-01
GC_5 = 0.00000E+00 0.12177E+01
GC_3005a = -0.00000E+00 -0.00000E+00
GC_3005h2 = -0.00000E+00 -0.00000E+00
GC_3005h3 = -0.00000E+00 -0.20992E-02
GC_3005h4 = -0.00000E+00 -0.00000E+00
GC_3007a = -0.00000E+00 -0.00000E+00
GC_3007h2 = -0.00000E+00 -0.16312E-02
GC_3007h3 = -0.00000E+00 -0.00000E+00
GC_22 = 0.00000E+00 0.28804E+00
GC_24 = 0.00000E+00 0.82310E-01
GC_47 = 0.00000E+00 0.46191E+00
GC_3005h1 = 0.00000E+00 0.26266E+01
GC_3007h1 = 0.00000E+00 0.33772E+01
Collider parameters:
--------------------
Running at P P machine @ 13000.000000000000 GeV
PDF set = nn23nlo
alpha_s(Mz)= 0.1190 running at 2 loops.
alpha_s(Mz)= 0.1190 running at 2 loops.
Renormalization scale set on event-by-event basis
Factorization scale set on event-by-event basis
Diagram information for clustering has been set-up for nFKSprocess 1
Diagram information for clustering has been set-up for nFKSprocess 2
Diagram information for clustering has been set-up for nFKSprocess 3
Diagram information for clustering has been set-up for nFKSprocess 4
getting user params
Enter number of events and iterations:
Number of events and iterations -1 12
Enter desired fractional accuracy:
Desired fractional accuracy: 2.4378623986800001E-002
Enter alpha, beta for G_soft
Enter alpha<0 to set G_soft=1 (no ME soft)
for G_soft: alpha= 1.0000000000000000 , beta= -0.10000000000000001
Enter alpha, beta for G_azi
Enter alpha>0 to set G_azi=0 (no azi corr)
for G_azi: alpha= -1.0000000000000000 , beta= -0.10000000000000001
Doing the S and H events together
Suppress amplitude (0 no, 1 yes)?
Using suppressed amplitude.
Exact helicity sum (0 yes, n = number/event)?
Do MC over helicities for the virtuals
Enter Configuration Number:
Running Configuration Number: 1
Enter running mode for MINT:
0 to set-up grids, 1 to integrate, 2 to generate events
MINT running mode: 1
Set the three folding parameters for MINT
xi_i, phi_i, y_ij
1 1 1
'all ', 'born', 'real', 'virt', 'novi' or 'grid'?
Enter 'born0' or 'virt0' to perform
a pure n-body integration (no S functions)
doing the all of this channel
Normal integration (Sfunction != 1)
about to integrate 13 -1 12 1
imode is 1
channel 1 : 1 F 0 0 0.2546E-02 0.0000E+00 0.5000E-02
+----------------------------------------------------------------+
| |
| Ninja - version 1.2.0 |
| |
| Author: <NAME> |
| |
| Based on: |
| |
| <NAME>, <NAME> and <NAME>, |
| "Integrand reduction of one-loop scattering amplitudes |
| through Laurent series expansion," |
| JHEP 1206 (2012) 095 [arXiv:1203.0291 [hep-ph]]. |
| |
| <NAME>, |
| "Ninja: Automated Integrand Reduction via Laurent |
| Expansion for One-Loop Amplitudes," |
| Comput.Phys.Commun. 185 (2014) [arXiv:1403.1229 [hep-ph]] |
| |
+----------------------------------------------------------------+
------- iteration 1
Update # PS points: 1040 --> 1040
Using random seed offsets: 1 , 2 , 0
with seed 34
Ranmar initialization seeds 13168 9410
Total number of FKS directories is 4
FKS process map (sum= 3 ) :
1 --> 2 : 1 3
2 --> 2 : 2 4
================================
process combination map (specified per FKS dir):
1 map 1 2 3 4
1 inv. map 1 2 3 4
2 map 1 2 3 4
2 inv. map 1 2 3 4
3 map 1 2 3 4
3 inv. map 1 2 3 4
4 map 1 2 3 4
4 inv. map 1 2 3 4
================================
tau_min 1 1 : 0.17161E+03 -- 0.38042E+03
tau_min 2 1 : 0.17161E+03 -- 0.38042E+03
tau_min 3 1 : 0.17161E+03 -- 0.38042E+03
tau_min 4 1 : 0.17161E+03 -- 0.38042E+03
bpower is 0.0000000000000000
Scale values (may change event by event):
muR, muR_reference: 0.223008D+03 0.223008D+03 1.00
muF1, muF1_reference: 0.223008D+03 0.223008D+03 1.00
muF2, muF2_reference: 0.223008D+03 0.223008D+03 1.00
QES, QES_reference: 0.223008D+03 0.223008D+03 1.00
muR_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF1_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF2_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
QES_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
alpha_s= 0.10478419500866530
alpha_s value used for the virtuals is (for the first PS point): 0.10755233181050759
==========================================================================================
{ }
{ [32m [0m }
{ [32m ,, [0m }
{ [32m`7MMM. ,MMF' `7MM `7MMF' [0m }
{ [32m MMMb dPMM MM MM [0m }
{ [32m M YM ,M MM ,6"Yb. ,M""bMM MM ,pW"Wq. ,pW"Wq.`7MMpdMAo. [0m }
{ [32m M Mb M' MM 8) MM ,AP MM MM 6W' `Wb 6W' `Wb MM `Wb [0m }
{ [32m M YM.P' MM ,pm9MM 8MI MM MM , 8M M8 8M M8 MM M8 [0m }
{ [32m M `YM' MM 8M MM `Mb MM MM ,M YA. ,A9 YA. ,A9 MM ,AP [0m }
{ [32m.JML. `' .JMML.`Moo9^Yo.`Wbmd"MML..JMMmmmmMMM `Ybmd9' `Ybmd9' MMbmmd' [0m }
{ [32m MM [0m }
{ [32m .JMML. [0m }
{ [32m[0mv2.6.6 (2018-06-28), Ref: arXiv:1103.0621v2, arXiv:1405.0301[32m [0m }
{ [32m [0m }
{ }
==========================================================================================
===============================================================
INFO: MadLoop read these parameters from ../MadLoop5_resources/MadLoopParams.dat
===============================================================
> MLReductionLib = 6|7|1
> CTModeRun = -1
> MLStabThres = 1.0000000000000000E-003
> NRotations_DP = 0
> NRotations_QP = 0
> CTStabThres = 1.0000000000000000E-002
> CTLoopLibrary = 2
> CTModeInit = 1
> CheckCycle = 3
> MaxAttempts = 10
> UseLoopFilter = F
> HelicityFilterLevel = 2
> ImprovePSPoint = 2
> DoubleCheckHelicityFilter = T
> LoopInitStartOver = F
> HelInitStartOver = F
> ZeroThres = 1.0000000000000001E-009
> OSThres = 1.0000000000000000E-008
> WriteOutFilters = T
> UseQPIntegrandForNinja = T
> UseQPIntegrandForCutTools = T
> IREGIMODE = 2
> IREGIRECY = T
> COLLIERMode = 1
> COLLIERRequiredAccuracy = 1.0000000000000000E-008
> COLLIERCanOutput = F
> COLLIERComputeUVpoles = T
> COLLIERComputeIRpoles = T
> COLLIERGlobalCache = -1
> COLLIERUseCacheForPoles = F
> COLLIERUseInternalStabilityTest = T
===============================================================
------------------------------------------------------------------------
| You are using CutTools - Version 1.9.3 |
| Authors: <NAME>, <NAME>, <NAME> |
| Published in JHEP 0803:042,2008 |
| http://www.ugr.es/~pittau/CutTools |
| |
| Compiler with 34 significant digits detetected |
----------------------------------------------------------------------
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
---- POLES CANCELLED ----
ABS integral = 0.2572E-02 +/- 0.4144E-04 ( 1.611 %)
Integral = 0.2388E-02 +/- 0.4124E-04 ( 1.726 %)
Virtual = 0.8797E-05 +/- 0.8753E-05 ( 99.503 %)
Virtual ratio = 0.5168E+01 +/- 0.1508E+00 ( 2.919 %)
ABS virtual = 0.2794E-04 +/- 0.8734E-05 ( 31.260 %)
Born*ao2pi = 0.2835E-06 +/- 0.7625E-07 ( 26.893 %)
Chi^2 per d.o.f. 0.0000E+00
accumulated results ABS integral = 0.2572E-02 +/- 0.4144E-04 ( 1.611 %)
accumulated results Integral = 0.2388E-02 +/- 0.4124E-04 ( 1.726 %)
accumulated results Virtual = 0.8797E-05 +/- 0.8753E-05 ( 99.503 %)
accumulated results Virtual ratio = 0.5168E+01 +/- 0.1508E+00 ( 2.919 %)
accumulated results ABS virtual = 0.2794E-04 +/- 0.8734E-05 ( 31.260 %)
accumulated results Born*ao2pi = 0.2835E-06 +/- 0.7625E-07 ( 26.893 %)
accumulated result Chi^2 per DoF = 0.0000E+00
channel 1 : 1 F 0 0 0.2572E-02 0.2388E-02 0.5000E-02
------- iteration 2
Update # PS points: 2080 --> 2080
ABS integral = 0.2544E-02 +/- 0.4348E-04 ( 1.709 %)
Integral = 0.2364E-02 +/- 0.4309E-04 ( 1.823 %)
Virtual = 0.4224E-05 +/- 0.6026E-05 ( 142.666 %)
Virtual ratio = 0.5062E+01 +/- 0.1304E+00 ( 2.575 %)
ABS virtual = 0.1956E-04 +/- 0.6018E-05 ( 30.775 %)
Born*ao2pi = 0.2063E-06 +/- 0.5259E-07 ( 25.498 %)
Chi^2= 0.1066E+00
accumulated results ABS integral = 0.2558E-02 +/- 0.3000E-04 ( 1.173 %)
accumulated results Integral = 0.2377E-02 +/- 0.2979E-04 ( 1.254 %)
accumulated results Virtual = 0.6088E-05 +/- 0.4963E-05 ( 81.523 %)
accumulated results Virtual ratio = 0.5111E+01 +/- 0.9863E-01 ( 1.930 %)
accumulated results ABS virtual = 0.2298E-04 +/- 0.4956E-05 ( 21.569 %)
accumulated results Born*ao2pi = 0.2378E-06 +/- 0.4329E-07 ( 18.206 %)
accumulated result Chi^2 per DoF = 0.1066E+00
channel 1 : 1 F 0 0 0.2558E-02 0.2377E-02 0.5000E-02
------- iteration 3
Update # PS points: 4160 --> 4160
ABS integral = 0.2544E-02 +/- 0.2268E-04 ( 0.892 %)
Integral = 0.2355E-02 +/- 0.2245E-04 ( 0.953 %)
Virtual = 0.3198E-05 +/- 0.4572E-05 ( 142.979 %)
Virtual ratio = 0.5007E+01 +/- 0.1447E+00 ( 2.890 %)
ABS virtual = 0.1856E-04 +/- 0.4567E-05 ( 24.611 %)
Born*ao2pi = 0.1792E-06 +/- 0.2887E-07 ( 16.112 %)
Chi^2= 0.7174E-01
accumulated results ABS integral = 0.2550E-02 +/- 0.1809E-04 ( 0.709 %)
accumulated results Integral = 0.2364E-02 +/- 0.1793E-04 ( 0.758 %)
accumulated results Virtual = 0.4583E-05 +/- 0.3363E-05 ( 73.364 %)
accumulated results Virtual ratio = 0.5069E+01 +/- 0.8150E-01 ( 1.608 %)
accumulated results ABS virtual = 0.2068E-04 +/- 0.3359E-05 ( 16.243 %)
accumulated results Born*ao2pi = 0.2026E-06 +/- 0.2402E-07 ( 11.853 %)
accumulated result Chi^2 per DoF = 0.8919E-01
channel 1 : 1 F 0 0 0.2550E-02 0.2364E-02 0.5000E-02
------- iteration 4
Update # PS points: 8320 --> 8320
ABS integral = 0.2540E-02 +/- 0.1433E-04 ( 0.564 %)
Integral = 0.2359E-02 +/- 0.1402E-04 ( 0.594 %)
Virtual = 0.3119E-05 +/- 0.4284E-05 ( 137.359 %)
Virtual ratio = 0.5160E+01 +/- 0.8546E-01 ( 1.656 %)
ABS virtual = 0.1630E-04 +/- 0.4282E-05 ( 26.272 %)
Born*ao2pi = 0.1522E-06 +/- 0.1945E-07 ( 12.773 %)
Chi^2= 0.9288E-01
accumulated results ABS integral = 0.2545E-02 +/- 0.1123E-04 ( 0.441 %)
accumulated results Integral = 0.2362E-02 +/- 0.1104E-04 ( 0.468 %)
accumulated results Virtual = 0.3939E-05 +/- 0.2645E-05 ( 67.145 %)
accumulated results Virtual ratio = 0.5114E+01 +/- 0.5898E-01 ( 1.153 %)
accumulated results ABS virtual = 0.1875E-04 +/- 0.2643E-05 ( 14.092 %)
accumulated results Born*ao2pi = 0.1748E-06 +/- 0.1511E-07 ( 8.647 %)
accumulated result Chi^2 per DoF = 0.9042E-01
accumulated results last 3 iterations ABS integral = 0.2542E-02 +/- 0.1167E-04 ( 0.459 %)
accumulated results last 3 iterations Integral = 0.2359E-02 +/- 0.1146E-04 ( 0.486 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.6012E-02
channel 1 : 1 F 0 0 0.2545E-02 0.2362E-02 0.5000E-02
------- iteration 5
Update # PS points: 16640 --> 16640
ABS integral = 0.2534E-02 +/- 0.1124E-04 ( 0.444 %)
Integral = 0.2350E-02 +/- 0.1153E-04 ( 0.491 %)
Virtual = -.5718E-05 +/- 0.4173E-05 ( 72.984 %)
Virtual ratio = 0.4865E+01 +/- 0.9852E-01 ( 2.025 %)
ABS virtual = 0.2476E-04 +/- 0.4171E-05 ( 16.844 %)
Born*ao2pi = 0.1734E-06 +/- 0.1473E-07 ( 8.494 %)
Chi^2= 0.2086E+00
accumulated results ABS integral = 0.2540E-02 +/- 0.7947E-05 ( 0.313 %)
accumulated results Integral = 0.2356E-02 +/- 0.7975E-05 ( 0.339 %)
accumulated results Virtual = 0.1929E-06 +/- 0.2234E-05 ( ******* %)
accumulated results Virtual ratio = 0.5021E+01 +/- 0.5060E-01 ( 1.008 %)
accumulated results ABS virtual = 0.2108E-04 +/- 0.2232E-05 ( 10.588 %)
accumulated results Born*ao2pi = 0.1741E-06 +/- 0.1055E-07 ( 6.059 %)
accumulated result Chi^2 per DoF = 0.1200E+00
accumulated results last 3 iterations ABS integral = 0.2538E-02 +/- 0.8241E-05 ( 0.325 %)
accumulated results last 3 iterations Integral = 0.2354E-02 +/- 0.8277E-05 ( 0.352 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.5508E-01
Found desired accuracy
channel 1 : 1 F 0 0 0.2540E-02 0.2356E-02 0.5000E-02
-------
Final result [ABS]: 2.5606792457994300E-003 +/- 8.2543029919871308E-006
Final result: 2.3558039758559044E-003 +/- 7.9746467805362300E-006
chi**2 per D.o.F.: 0.11995976267087909
Satistics from MadLoop:
Total points tried: 351
Stability unknown: 0
Stable PS point: 351
Unstable PS point (and rescued): 0
Exceptional PS point (unstable and not rescued): 0
Double precision used: 351
Quadruple precision used: 0
Initialization phase-space points: 0
Unknown return code (100): 0
Unknown return code (10): 0
Unit return code distribution (1):
#Unit 6 = 351
Time spent in Born : 1.69295776
Time spent in PS_Generation : 0.00000000
Time spent in Reals_evaluation: 13.0007505
Time spent in MCsubtraction : 5.29688501
Time spent in Counter_terms : 7.21122456
Time spent in Integrated_CT : 0.318246126
Time spent in Virtuals : 4.54178154E-02
Time spent in FxFx_cluster : 0.00000000
Time spent in Nbody_prefactor : 1.76472342
Time spent in N1body_prefactor : 1.88039899
Time spent in Adding_alphas_pdf : 1.23606038
Time spent in Reweight_scale : 0.00000000
Time spent in Reweight_pdf : 0.00000000
Time spent in Filling_plots : 0.00000000
Time spent in Applying_cuts : 0.370839715
Time spent in Sum_ident_contr : 0.106384084
Time spent in Pick_unwgt : 0.00000000
Time spent in Write_events : 0.00000000
Time spent in Other_tasks : 2.97308350
Time spent in Total : 35.8969765
Time in seconds: 36
</PRE><br>
<a name=/P0_udx_wpx0_wpepemz_no_a/GF1></a>
<font color="red">
<br>LOG file for integration channel /P0_udx_wpx0_wpepemz_no_a/GF1, 1 <br></font>
<PRE>
===============================================================
INFO: MadFKS read these parameters from FKS_params.dat
===============================================================
> IRPoleCheckThreshold = 1.0000000000000001E-005
> PrecisionVirtualAtRunTime = 1.0000000000000000E-003
> NHelForMCoverHels = 4
> VirtualFraction = 1.0000000000000000
> MinVirtualFraction = 5.0000000000000001E-003
===============================================================
A PDF is used, so alpha_s(MZ) is going to be modified
Old value of alpha_s from param_card: 0.11799999999999999
****************************************
NNPDFDriver version 1.0.3
Grid: NNPDF23nlo_as_0119_qed_mem0.grid
****************************************
New value of alpha_s from PDF nn23nlo: 0.11899999999999999
*****************************************************
* MadGraph/MadEvent *
* -------------------------------- *
* http://madgraph.hep.uiuc.edu *
* http://madgraph.phys.ucl.ac.be *
* http://madgraph.roma2.infn.it *
* -------------------------------- *
* *
* PARAMETER AND COUPLING VALUES *
* *
*****************************************************
External Params
---------------------------------
MU_R = 91.188000000000002
aEWM1 = 132.50700000000001
mdl_Gf = 1.1663900000000000E-005
aS = 0.11799999999999999
mdl_ymb = 4.7000000000000002
mdl_ymt = 173.00000000000000
mdl_ymtau = 1.7769999999999999
mdl_MT = 173.00000000000000
mdl_MB = 4.7000000000000002
mdl_MZ = 91.188000000000002
mdl_MTA = 1.7769999999999999
mdl_WT = 1.4915000000000000
mdl_WZ = 2.4414039999999999
mdl_WW = 2.0476000000000001
mdl_MX0 = 300.00000000000000
mdl_WX0 = 1.0604700000000000
mdl_Lambda = 5000.0000000000000
mdl_cosa = 1.0000000000000000
mdl_kSM = 5.0000000000000003E-002
mdl_kHtt = 0.0000000000000000
mdl_kAtt = 0.0000000000000000
mdl_kHbb = 0.0000000000000000
mdl_kAbb = 0.0000000000000000
mdl_kHll = 0.0000000000000000
mdl_kAll = 0.0000000000000000
mdl_kHaa = 0.0000000000000000
mdl_kAaa = 0.0000000000000000
mdl_kHza = 0.0000000000000000
mdl_kAza = 0.0000000000000000
mdl_kHzz = 8.1561199999999996
mdl_kAzz = 0.0000000000000000
mdl_kHww = 10.496200000000000
mdl_kAww = 0.0000000000000000
mdl_kHda = 0.0000000000000000
mdl_kHdz = 0.0000000000000000
mdl_kHdwR = 0.0000000000000000
mdl_kHdwI = 0.0000000000000000
Internal Params
---------------------------------
mdl_CKM11 = 1.0000000000000000
mdl_conjg__CKM3x3 = 1.0000000000000000
mdl_conjg__CKM11 = 1.0000000000000000
mdl_lhv = 1.0000000000000000
mdl_CKM3x3 = 1.0000000000000000
mdl_conjg__CKM33 = 1.0000000000000000
mdl_Ncol = 3.0000000000000000
mdl_CA = 3.0000000000000000
mdl_TF = 0.50000000000000000
mdl_CF = 1.3333333333333333
mdl_complexi = ( 0.0000000000000000 , 1.0000000000000000 )
mdl_MZ__exp__2 = 8315.2513440000002
mdl_MZ__exp__4 = 69143404.913893804
mdl_sqrt__2 = 1.4142135623730951
mdl_MX0__exp__2 = 90000.000000000000
mdl_cosa__exp__2 = 1.0000000000000000
mdl_sina = 0.0000000000000000
mdl_kHdw = ( 0.0000000000000000 , 0.0000000000000000 )
mdl_nb__2__exp__0_75 = 1.6817928305074290
mdl_Ncol__exp__2 = 9.0000000000000000
mdl_MB__exp__2 = 22.090000000000003
mdl_MT__exp__2 = 29929.000000000000
mdl_conjg__kHdw = ( 0.0000000000000000 , -0.0000000000000000 )
mdl_aEW = 7.5467711139788835E-003
mdl_MW = 80.419002445756163
mdl_sqrt__aEW = 8.6872153846781555E-002
mdl_ee = 0.30795376724436879
mdl_MW__exp__2 = 6467.2159543705357
mdl_sw2 = 0.22224648578577766
mdl_cw = 0.88190334743339216
mdl_sqrt__sw2 = 0.47143025548407230
mdl_sw = 0.47143025548407230
mdl_g1 = 0.34919219678733299
mdl_gw = 0.65323293034757990
mdl_vev = 246.21845810181637
mdl_vev__exp__2 = 60623.529110035903
mdl_lam = 0.74228605065735920
mdl_yb = 2.6995554250465490E-002
mdl_yt = 0.99366614581500623
mdl_ytau = 1.0206617000654717E-002
mdl_muH = 212.13203435596427
mdl_AxialZUp = -0.18517701861793787
mdl_AxialZDown = 0.18517701861793787
mdl_VectorZUp = 7.5430507588273299E-002
mdl_VectorZDown = -0.13030376310310560
mdl_VectorAUp = 0.20530251149624587
mdl_VectorADown = -0.10265125574812294
mdl_VectorWmDxU = 0.23095271737156670
mdl_AxialWmDxU = -0.23095271737156670
mdl_VectorWpUxD = 0.23095271737156670
mdl_AxialWpUxD = -0.23095271737156670
mdl_I1x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_I2x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I3x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I4x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_Vector_tbGp = (-0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGp = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_Vector_tbGm = ( 0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGm = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_ee__exp__2 = 9.4835522759998875E-002
mdl_gAaa = 1.3008566310666950E-005
mdl_cw__exp__2 = 0.77775351421422245
mdl_gAza = 4.7794971072590281E-006
mdl_gHaa = 2.5475109025056106E-005
mdl_gHza = 3.9182129211851395E-005
mdl_gw__exp__2 = 0.42671326129048615
mdl_sw__exp__2 = 0.22224648578577769
Internal Params evaluated point by point
----------------------------------------
mdl_sqrt__aS = 0.34351128074635334
mdl_G__exp__2 = 1.4828317324943823
mdl_G__exp__4 = 2.1987899468922913
mdl_R2MixedFactor_FIN_ = -2.5040377713124864E-002
mdl_GWcft_UV_b_1EPS_ = -3.1300472141406080E-003
mdl_GWcft_UV_t_1EPS_ = -3.1300472141406080E-003
mdl_bWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_tWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_G__exp__3 = 1.8056676068262196
mdl_MU_R__exp__2 = 8315.2513440000002
mdl_GWcft_UV_b_FIN_ = -1.8563438626678915E-002
mdl_GWcft_UV_t_FIN_ = 4.0087659331150384E-003
mdl_bWcft_UV_FIN_ = -0.13642100947319838
mdl_tWcft_UV_FIN_ = -9.8778211443463623E-004
mdl_gAgg = 7.6274879753643885E-005
mdl_gHgg = -5.0849919835762592E-005
Couplings of HC_NLO_X0_UFO
---------------------------------
R2_dxuW = -0.00000E+00 -0.11566E-01
GC_5 = 0.00000E+00 0.12177E+01
GC_3005a = -0.00000E+00 -0.00000E+00
GC_3005h2 = -0.00000E+00 -0.00000E+00
GC_3005h3 = -0.00000E+00 -0.20992E-02
GC_3005h4 = -0.00000E+00 -0.00000E+00
GC_3007a = -0.00000E+00 -0.00000E+00
GC_3007h2 = -0.00000E+00 -0.16312E-02
GC_3007h3 = -0.00000E+00 -0.00000E+00
GC_22 = 0.00000E+00 0.28804E+00
GC_24 = 0.00000E+00 0.82310E-01
GC_47 = 0.00000E+00 0.46191E+00
GC_3005h1 = 0.00000E+00 0.26266E+01
GC_3007h1 = 0.00000E+00 0.33772E+01
Collider parameters:
--------------------
Running at P P machine @ 13000.000000000000 GeV
PDF set = nn23nlo
alpha_s(Mz)= 0.1190 running at 2 loops.
alpha_s(Mz)= 0.1190 running at 2 loops.
Renormalization scale set on event-by-event basis
Factorization scale set on event-by-event basis
Diagram information for clustering has been set-up for nFKSprocess 1
Diagram information for clustering has been set-up for nFKSprocess 2
Diagram information for clustering has been set-up for nFKSprocess 3
Diagram information for clustering has been set-up for nFKSprocess 4
getting user params
Enter number of events and iterations:
Number of events and iterations -1 12
Enter desired fractional accuracy:
Desired fractional accuracy: 1.7376435669300000E-002
Enter alpha, beta for G_soft
Enter alpha<0 to set G_soft=1 (no ME soft)
for G_soft: alpha= 1.0000000000000000 , beta= -0.10000000000000001
Enter alpha, beta for G_azi
Enter alpha>0 to set G_azi=0 (no azi corr)
for G_azi: alpha= -1.0000000000000000 , beta= -0.10000000000000001
Doing the S and H events together
Suppress amplitude (0 no, 1 yes)?
Using suppressed amplitude.
Exact helicity sum (0 yes, n = number/event)?
Do MC over helicities for the virtuals
Enter Configuration Number:
Running Configuration Number: 1
Enter running mode for MINT:
0 to set-up grids, 1 to integrate, 2 to generate events
MINT running mode: 1
Set the three folding parameters for MINT
xi_i, phi_i, y_ij
1 1 1
'all ', 'born', 'real', 'virt', 'novi' or 'grid'?
Enter 'born0' or 'virt0' to perform
a pure n-body integration (no S functions)
doing the all of this channel
Normal integration (Sfunction != 1)
about to integrate 13 -1 12 1
imode is 1
channel 1 : 1 F 0 0 0.5011E-02 0.0000E+00 0.5201E-02
+----------------------------------------------------------------+
| |
| Ninja - version 1.2.0 |
| |
| Author: <NAME> |
| |
| Based on: |
| |
| <NAME>, <NAME> and <NAME>, |
| "Integrand reduction of one-loop scattering amplitudes |
| through Laurent series expansion," |
| JHEP 1206 (2012) 095 [arXiv:1203.0291 [hep-ph]]. |
| |
| <NAME>, |
| "Ninja: Automated Integrand Reduction via Laurent |
| Expansion for One-Loop Amplitudes," |
| Comput.Phys.Commun. 185 (2014) [arXiv:1403.1229 [hep-ph]] |
| |
+----------------------------------------------------------------+
------- iteration 1
Update # PS points: 1040 --> 1040
Using random seed offsets: 1 , 3 , 0
with seed 34
Ranmar initialization seeds 13168 9411
Total number of FKS directories is 4
FKS process map (sum= 3 ) :
1 --> 2 : 1 3
2 --> 2 : 2 4
================================
process combination map (specified per FKS dir):
1 map 1 2 3 4
1 inv. map 1 2 3 4
2 map 1 2 3 4
2 inv. map 1 2 3 4
3 map 1 2 3 4
3 inv. map 1 2 3 4
4 map 1 2 3 4
4 inv. map 1 2 3 4
================================
tau_min 1 1 : 0.17161E+03 -- 0.38042E+03
tau_min 2 1 : 0.17161E+03 -- 0.38042E+03
tau_min 3 1 : 0.17161E+03 -- 0.38042E+03
tau_min 4 1 : 0.17161E+03 -- 0.38042E+03
bpower is 0.0000000000000000
Scale values (may change event by event):
muR, muR_reference: 0.198690D+03 0.198690D+03 1.00
muF1, muF1_reference: 0.198690D+03 0.198690D+03 1.00
muF2, muF2_reference: 0.198690D+03 0.198690D+03 1.00
QES, QES_reference: 0.198690D+03 0.198690D+03 1.00
muR_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF1_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF2_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
QES_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
alpha_s= 0.10642184187496337
alpha_s value used for the virtuals is (for the first PS point): 0.10645126743219245
==========================================================================================
{ }
{ [32m [0m }
{ [32m ,, [0m }
{ [32m`7MMM. ,MMF' `7MM `7MMF' [0m }
{ [32m MMMb dPMM MM MM [0m }
{ [32m M YM ,M MM ,6"Yb. ,M""bMM MM ,pW"Wq. ,pW"Wq.`7MMpdMAo. [0m }
{ [32m M Mb M' MM 8) MM ,AP MM MM 6W' `Wb 6W' `Wb MM `Wb [0m }
{ [32m M YM.P' MM ,pm9MM 8MI MM MM , 8M M8 8M M8 MM M8 [0m }
{ [32m M `YM' MM 8M MM `Mb MM MM ,M YA. ,A9 YA. ,A9 MM ,AP [0m }
{ [32m.JML. `' .JMML.`Moo9^Yo.`Wbmd"MML..JMMmmmmMMM `Ybmd9' `Ybmd9' MMbmmd' [0m }
{ [32m MM [0m }
{ [32m .JMML. [0m }
{ [32m[0mv2.6.6 (2018-06-28), Ref: arXiv:1103.0621v2, arXiv:1405.0301[32m [0m }
{ [32m [0m }
{ }
==========================================================================================
===============================================================
INFO: MadLoop read these parameters from ../MadLoop5_resources/MadLoopParams.dat
===============================================================
> MLReductionLib = 6|7|1
> CTModeRun = -1
> MLStabThres = 1.0000000000000000E-003
> NRotations_DP = 0
> NRotations_QP = 0
> CTStabThres = 1.0000000000000000E-002
> CTLoopLibrary = 2
> CTModeInit = 1
> CheckCycle = 3
> MaxAttempts = 10
> UseLoopFilter = F
> HelicityFilterLevel = 2
> ImprovePSPoint = 2
> DoubleCheckHelicityFilter = T
> LoopInitStartOver = F
> HelInitStartOver = F
> ZeroThres = 1.0000000000000001E-009
> OSThres = 1.0000000000000000E-008
> WriteOutFilters = T
> UseQPIntegrandForNinja = T
> UseQPIntegrandForCutTools = T
> IREGIMODE = 2
> IREGIRECY = T
> COLLIERMode = 1
> COLLIERRequiredAccuracy = 1.0000000000000000E-008
> COLLIERCanOutput = F
> COLLIERComputeUVpoles = T
> COLLIERComputeIRpoles = T
> COLLIERGlobalCache = -1
> COLLIERUseCacheForPoles = F
> COLLIERUseInternalStabilityTest = T
===============================================================
------------------------------------------------------------------------
| You are using CutTools - Version 1.9.3 |
| Authors: <NAME>, <NAME>, <NAME> |
| Published in JHEP 0803:042,2008 |
| http://www.ugr.es/~pittau/CutTools |
| |
| Compiler with 34 significant digits detetected |
----------------------------------------------------------------------
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
---- POLES CANCELLED ----
ABS integral = 0.5015E-02 +/- 0.7010E-04 ( 1.398 %)
Integral = 0.4688E-02 +/- 0.6736E-04 ( 1.437 %)
Virtual = 0.9014E-05 +/- 0.5724E-05 ( 63.501 %)
Virtual ratio = 0.5270E+01 +/- 0.9916E-01 ( 1.882 %)
ABS virtual = 0.1335E-04 +/- 0.5720E-05 ( 42.842 %)
Born*ao2pi = 0.2246E-06 +/- 0.9274E-07 ( 41.290 %)
Chi^2 per d.o.f. 0.0000E+00
accumulated results ABS integral = 0.5015E-02 +/- 0.7010E-04 ( 1.398 %)
accumulated results Integral = 0.4688E-02 +/- 0.6736E-04 ( 1.437 %)
accumulated results Virtual = 0.9014E-05 +/- 0.5724E-05 ( 63.501 %)
accumulated results Virtual ratio = 0.5270E+01 +/- 0.9916E-01 ( 1.882 %)
accumulated results ABS virtual = 0.1335E-04 +/- 0.5720E-05 ( 42.842 %)
accumulated results Born*ao2pi = 0.2246E-06 +/- 0.9274E-07 ( 41.290 %)
accumulated result Chi^2 per DoF = 0.0000E+00
channel 1 : 1 F 0 0 0.5015E-02 0.4688E-02 0.5201E-02
------- iteration 2
Update # PS points: 2080 --> 2080
ABS integral = 0.5471E-02 +/- 0.2527E-03 ( 4.619 %)
Integral = 0.5120E-02 +/- 0.2524E-03 ( 4.929 %)
Virtual = 0.8920E-05 +/- 0.7387E-05 ( 82.818 %)
Virtual ratio = 0.5040E+01 +/- 0.1864E+00 ( 3.699 %)
ABS virtual = 0.2702E-04 +/- 0.7377E-05 ( 27.307 %)
Born*ao2pi = 0.3231E-06 +/- 0.7604E-07 ( 23.530 %)
Chi^2= 0.1994E+01
accumulated results ABS integral = 0.5114E-02 +/- 0.6755E-04 ( 1.321 %)
accumulated results Integral = 0.4779E-02 +/- 0.6508E-04 ( 1.362 %)
accumulated results Virtual = 0.8973E-05 +/- 0.4525E-05 ( 50.426 %)
accumulated results Virtual ratio = 0.5190E+01 +/- 0.8755E-01 ( 1.687 %)
accumulated results ABS virtual = 0.1932E-04 +/- 0.4520E-05 ( 23.398 %)
accumulated results Born*ao2pi = 0.2787E-06 +/- 0.5880E-07 ( 21.094 %)
accumulated result Chi^2 per DoF = 0.1994E+01
channel 1 : 1 F 0 0 0.5114E-02 0.4779E-02 0.5201E-02
------- iteration 3
Update # PS points: 4160 --> 4160
ABS integral = 0.5001E-02 +/- 0.3586E-04 ( 0.717 %)
Integral = 0.4630E-02 +/- 0.3640E-04 ( 0.786 %)
Virtual = -.7523E-05 +/- 0.1256E-04 ( 166.939 %)
Virtual ratio = 0.4898E+01 +/- 0.1884E+00 ( 3.847 %)
ABS virtual = 0.3576E-04 +/- 0.1255E-04 ( 35.102 %)
Born*ao2pi = 0.3123E-06 +/- 0.6107E-07 ( 19.557 %)
Chi^2= 0.1192E+01
accumulated results ABS integral = 0.5040E-02 +/- 0.3168E-04 ( 0.628 %)
accumulated results Integral = 0.4683E-02 +/- 0.3177E-04 ( 0.678 %)
accumulated results Virtual = 0.4604E-05 +/- 0.4257E-05 ( 92.462 %)
accumulated results Virtual ratio = 0.5097E+01 +/- 0.7939E-01 ( 1.558 %)
accumulated results ABS virtual = 0.2367E-04 +/- 0.4253E-05 ( 17.966 %)
accumulated results Born*ao2pi = 0.2952E-06 +/- 0.4236E-07 ( 14.349 %)
accumulated result Chi^2 per DoF = 0.1593E+01
channel 1 : 1 F 0 0 0.5040E-02 0.4683E-02 0.5201E-02
------- iteration 4
Update # PS points: 8320 --> 8320
ABS integral = 0.5126E-02 +/- 0.9000E-04 ( 1.756 %)
Integral = 0.4756E-02 +/- 0.9394E-04 ( 1.975 %)
Virtual = -.2463E-04 +/- 0.2859E-04 ( 116.056 %)
Virtual ratio = 0.4959E+01 +/- 0.1067E+00 ( 2.152 %)
ABS virtual = 0.5489E-04 +/- 0.2859E-04 ( 52.080 %)
Born*ao2pi = 0.3466E-06 +/- 0.6795E-07 ( 19.607 %)
Chi^2= 0.5010E+00
accumulated results ABS integral = 0.5063E-02 +/- 0.2988E-04 ( 0.590 %)
accumulated results Integral = 0.4702E-02 +/- 0.3009E-04 ( 0.640 %)
accumulated results Virtual = 0.8147E-06 +/- 0.4211E-05 ( 516.837 %)
accumulated results Virtual ratio = 0.5038E+01 +/- 0.6369E-01 ( 1.264 %)
accumulated results ABS virtual = 0.2772E-04 +/- 0.4207E-05 ( 15.178 %)
accumulated results Born*ao2pi = 0.3149E-06 +/- 0.3595E-07 ( 11.414 %)
accumulated result Chi^2 per DoF = 0.1229E+01
accumulated results last 3 iterations ABS integral = 0.5078E-02 +/- 0.3303E-04 ( 0.650 %)
accumulated results last 3 iterations Integral = 0.4710E-02 +/- 0.3364E-04 ( 0.714 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.1467E+01
channel 1 : 1 F 0 0 0.5063E-02 0.4702E-02 0.5201E-02
------- iteration 5
Update # PS points: 16640 --> 16640
ABS integral = 0.5035E-02 +/- 0.1865E-04 ( 0.370 %)
Integral = 0.4637E-02 +/- 0.2307E-04 ( 0.498 %)
Virtual = -.3996E-04 +/- 0.1569E-04 ( 39.267 %)
Virtual ratio = 0.4696E+01 +/- 0.1319E+00 ( 2.808 %)
ABS virtual = 0.6846E-04 +/- 0.1569E-04 ( 22.919 %)
Born*ao2pi = 0.3395E-06 +/- 0.3369E-07 ( 9.924 %)
Chi^2= 0.3292E+00
accumulated results ABS integral = 0.5045E-02 +/- 0.1582E-04 ( 0.314 %)
accumulated results Integral = 0.4665E-02 +/- 0.1831E-04 ( 0.392 %)
accumulated results Virtual = -.7812E-05 +/- 0.4067E-05 ( 52.056 %)
accumulated results Virtual ratio = 0.4927E+01 +/- 0.5736E-01 ( 1.164 %)
accumulated results ABS virtual = 0.3633E-04 +/- 0.4063E-05 ( 11.184 %)
accumulated results Born*ao2pi = 0.3276E-06 +/- 0.2458E-07 ( 7.504 %)
accumulated result Chi^2 per DoF = 0.1004E+01
accumulated results last 3 iterations ABS integral = 0.5035E-02 +/- 0.1627E-04 ( 0.323 %)
accumulated results last 3 iterations Integral = 0.4648E-02 +/- 0.1908E-04 ( 0.410 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.4960E+00
Found desired accuracy
channel 1 : 1 F 0 0 0.5045E-02 0.4665E-02 0.5201E-02
-------
Final result [ABS]: 5.0817280926138695E-003 +/- 1.6331987462887168E-005
Final result: 4.6648111626082234E-003 +/- 1.8307129381636328E-005
chi**2 per D.o.F.: 1.0040822850606084
Satistics from MadLoop:
Total points tried: 302
Stability unknown: 0
Stable PS point: 302
Unstable PS point (and rescued): 0
Exceptional PS point (unstable and not rescued): 0
Double precision used: 302
Quadruple precision used: 0
Initialization phase-space points: 0
Unknown return code (100): 0
Unknown return code (10): 0
Unit return code distribution (1):
#Unit 6 = 302
Time spent in Born : 1.74591887
Time spent in PS_Generation : 0.00000000
Time spent in Reals_evaluation: 13.4951077
Time spent in MCsubtraction : 5.54358196
Time spent in Counter_terms : 7.52073956
Time spent in Integrated_CT : 0.319058955
Time spent in Virtuals : 4.19065803E-02
Time spent in FxFx_cluster : 0.00000000
Time spent in Nbody_prefactor : 1.81274259
Time spent in N1body_prefactor : 1.93571591
Time spent in Adding_alphas_pdf : 1.24926901
Time spent in Reweight_scale : 0.00000000
Time spent in Reweight_pdf : 0.00000000
Time spent in Filling_plots : 0.00000000
Time spent in Applying_cuts : 0.376293540
Time spent in Sum_ident_contr : 0.111064397
Time spent in Pick_unwgt : 0.00000000
Time spent in Write_events : 0.00000000
Time spent in Other_tasks : 2.91578293
Time spent in Total : 37.0671844
Time in seconds: 37
</PRE><br>
<a name=/P0_dxu_wpx0_wpepemz_no_a/GF1></a>
<font color="red">
<br>LOG file for integration channel /P0_dxu_wpx0_wpepemz_no_a/GF1, 1 <br></font>
<PRE>
===============================================================
INFO: MadFKS read these parameters from FKS_params.dat
===============================================================
> IRPoleCheckThreshold = 1.0000000000000001E-005
> PrecisionVirtualAtRunTime = 1.0000000000000000E-003
> NHelForMCoverHels = 4
> VirtualFraction = 1.0000000000000000
> MinVirtualFraction = 5.0000000000000001E-003
===============================================================
A PDF is used, so alpha_s(MZ) is going to be modified
Old value of alpha_s from param_card: 0.11799999999999999
****************************************
NNPDFDriver version 1.0.3
Grid: NNPDF23nlo_as_0119_qed_mem0.grid
****************************************
New value of alpha_s from PDF nn23nlo: 0.11899999999999999
*****************************************************
* MadGraph/MadEvent *
* -------------------------------- *
* http://madgraph.hep.uiuc.edu *
* http://madgraph.phys.ucl.ac.be *
* http://madgraph.roma2.infn.it *
* -------------------------------- *
* *
* PARAMETER AND COUPLING VALUES *
* *
*****************************************************
External Params
---------------------------------
MU_R = 91.188000000000002
aEWM1 = 132.50700000000001
mdl_Gf = 1.1663900000000000E-005
aS = 0.11799999999999999
mdl_ymb = 4.7000000000000002
mdl_ymt = 173.00000000000000
mdl_ymtau = 1.7769999999999999
mdl_MT = 173.00000000000000
mdl_MB = 4.7000000000000002
mdl_MZ = 91.188000000000002
mdl_MTA = 1.7769999999999999
mdl_WT = 1.4915000000000000
mdl_WZ = 2.4414039999999999
mdl_WW = 2.0476000000000001
mdl_MX0 = 300.00000000000000
mdl_WX0 = 1.0604700000000000
mdl_Lambda = 5000.0000000000000
mdl_cosa = 1.0000000000000000
mdl_kSM = 5.0000000000000003E-002
mdl_kHtt = 0.0000000000000000
mdl_kAtt = 0.0000000000000000
mdl_kHbb = 0.0000000000000000
mdl_kAbb = 0.0000000000000000
mdl_kHll = 0.0000000000000000
mdl_kAll = 0.0000000000000000
mdl_kHaa = 0.0000000000000000
mdl_kAaa = 0.0000000000000000
mdl_kHza = 0.0000000000000000
mdl_kAza = 0.0000000000000000
mdl_kHzz = 8.1561199999999996
mdl_kAzz = 0.0000000000000000
mdl_kHww = 10.496200000000000
mdl_kAww = 0.0000000000000000
mdl_kHda = 0.0000000000000000
mdl_kHdz = 0.0000000000000000
mdl_kHdwR = 0.0000000000000000
mdl_kHdwI = 0.0000000000000000
Internal Params
---------------------------------
mdl_CKM11 = 1.0000000000000000
mdl_conjg__CKM3x3 = 1.0000000000000000
mdl_conjg__CKM11 = 1.0000000000000000
mdl_lhv = 1.0000000000000000
mdl_CKM3x3 = 1.0000000000000000
mdl_conjg__CKM33 = 1.0000000000000000
mdl_Ncol = 3.0000000000000000
mdl_CA = 3.0000000000000000
mdl_TF = 0.50000000000000000
mdl_CF = 1.3333333333333333
mdl_complexi = ( 0.0000000000000000 , 1.0000000000000000 )
mdl_MZ__exp__2 = 8315.2513440000002
mdl_MZ__exp__4 = 69143404.913893804
mdl_sqrt__2 = 1.4142135623730951
mdl_MX0__exp__2 = 90000.000000000000
mdl_cosa__exp__2 = 1.0000000000000000
mdl_sina = 0.0000000000000000
mdl_kHdw = ( 0.0000000000000000 , 0.0000000000000000 )
mdl_nb__2__exp__0_75 = 1.6817928305074290
mdl_Ncol__exp__2 = 9.0000000000000000
mdl_MB__exp__2 = 22.090000000000003
mdl_MT__exp__2 = 29929.000000000000
mdl_conjg__kHdw = ( 0.0000000000000000 , -0.0000000000000000 )
mdl_aEW = 7.5467711139788835E-003
mdl_MW = 80.419002445756163
mdl_sqrt__aEW = 8.6872153846781555E-002
mdl_ee = 0.30795376724436879
mdl_MW__exp__2 = 6467.2159543705357
mdl_sw2 = 0.22224648578577766
mdl_cw = 0.88190334743339216
mdl_sqrt__sw2 = 0.47143025548407230
mdl_sw = 0.47143025548407230
mdl_g1 = 0.34919219678733299
mdl_gw = 0.65323293034757990
mdl_vev = 246.21845810181637
mdl_vev__exp__2 = 60623.529110035903
mdl_lam = 0.74228605065735920
mdl_yb = 2.6995554250465490E-002
mdl_yt = 0.99366614581500623
mdl_ytau = 1.0206617000654717E-002
mdl_muH = 212.13203435596427
mdl_AxialZUp = -0.18517701861793787
mdl_AxialZDown = 0.18517701861793787
mdl_VectorZUp = 7.5430507588273299E-002
mdl_VectorZDown = -0.13030376310310560
mdl_VectorAUp = 0.20530251149624587
mdl_VectorADown = -0.10265125574812294
mdl_VectorWmDxU = 0.23095271737156670
mdl_AxialWmDxU = -0.23095271737156670
mdl_VectorWpUxD = 0.23095271737156670
mdl_AxialWpUxD = -0.23095271737156670
mdl_I1x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_I2x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I3x33 = ( 0.99366614581500623 , 0.0000000000000000 )
mdl_I4x33 = ( 2.6995554250465490E-002, 0.0000000000000000 )
mdl_Vector_tbGp = (-0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGp = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_Vector_tbGm = ( 0.96667059156454072 , 0.0000000000000000 )
mdl_Axial_tbGm = ( -1.0206617000654716 , -0.0000000000000000 )
mdl_ee__exp__2 = 9.4835522759998875E-002
mdl_gAaa = 1.3008566310666950E-005
mdl_cw__exp__2 = 0.77775351421422245
mdl_gAza = 4.7794971072590281E-006
mdl_gHaa = 2.5475109025056106E-005
mdl_gHza = 3.9182129211851395E-005
mdl_gw__exp__2 = 0.42671326129048615
mdl_sw__exp__2 = 0.22224648578577769
Internal Params evaluated point by point
----------------------------------------
mdl_sqrt__aS = 0.34351128074635334
mdl_G__exp__2 = 1.4828317324943823
mdl_G__exp__4 = 2.1987899468922913
mdl_R2MixedFactor_FIN_ = -2.5040377713124864E-002
mdl_GWcft_UV_b_1EPS_ = -3.1300472141406080E-003
mdl_GWcft_UV_t_1EPS_ = -3.1300472141406080E-003
mdl_bWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_tWcft_UV_1EPS_ = -1.8780283284843650E-002
mdl_G__exp__3 = 1.8056676068262196
mdl_MU_R__exp__2 = 8315.2513440000002
mdl_GWcft_UV_b_FIN_ = -1.8563438626678915E-002
mdl_GWcft_UV_t_FIN_ = 4.0087659331150384E-003
mdl_bWcft_UV_FIN_ = -0.13642100947319838
mdl_tWcft_UV_FIN_ = -9.8778211443463623E-004
mdl_gAgg = 7.6274879753643885E-005
mdl_gHgg = -5.0849919835762592E-005
Couplings of HC_NLO_X0_UFO
---------------------------------
R2_dxuW = -0.00000E+00 -0.11566E-01
GC_5 = 0.00000E+00 0.12177E+01
GC_3005a = -0.00000E+00 -0.00000E+00
GC_3005h2 = -0.00000E+00 -0.00000E+00
GC_3005h3 = -0.00000E+00 -0.20992E-02
GC_3005h4 = -0.00000E+00 -0.00000E+00
GC_3007a = -0.00000E+00 -0.00000E+00
GC_3007h2 = -0.00000E+00 -0.16312E-02
GC_3007h3 = -0.00000E+00 -0.00000E+00
GC_22 = 0.00000E+00 0.28804E+00
GC_24 = 0.00000E+00 0.82310E-01
GC_47 = 0.00000E+00 0.46191E+00
GC_3005h1 = 0.00000E+00 0.26266E+01
GC_3007h1 = 0.00000E+00 0.33772E+01
Collider parameters:
--------------------
Running at P P machine @ 13000.000000000000 GeV
PDF set = nn23nlo
alpha_s(Mz)= 0.1190 running at 2 loops.
alpha_s(Mz)= 0.1190 running at 2 loops.
Renormalization scale set on event-by-event basis
Factorization scale set on event-by-event basis
Diagram information for clustering has been set-up for nFKSprocess 1
Diagram information for clustering has been set-up for nFKSprocess 2
Diagram information for clustering has been set-up for nFKSprocess 3
Diagram information for clustering has been set-up for nFKSprocess 4
getting user params
Enter number of events and iterations:
Number of events and iterations -1 12
Enter desired fractional accuracy:
Desired fractional accuracy: 1.7373590671899999E-002
Enter alpha, beta for G_soft
Enter alpha<0 to set G_soft=1 (no ME soft)
for G_soft: alpha= 1.0000000000000000 , beta= -0.10000000000000001
Enter alpha, beta for G_azi
Enter alpha>0 to set G_azi=0 (no azi corr)
for G_azi: alpha= -1.0000000000000000 , beta= -0.10000000000000001
Doing the S and H events together
Suppress amplitude (0 no, 1 yes)?
Using suppressed amplitude.
Exact helicity sum (0 yes, n = number/event)?
Do MC over helicities for the virtuals
Enter Configuration Number:
Running Configuration Number: 1
Enter running mode for MINT:
0 to set-up grids, 1 to integrate, 2 to generate events
MINT running mode: 1
Set the three folding parameters for MINT
xi_i, phi_i, y_ij
1 1 1
'all ', 'born', 'real', 'virt', 'novi' or 'grid'?
Enter 'born0' or 'virt0' to perform
a pure n-body integration (no S functions)
doing the all of this channel
Normal integration (Sfunction != 1)
about to integrate 13 -1 12 1
imode is 1
channel 1 : 1 F 0 0 0.5013E-02 0.0000E+00 0.5000E-02
+----------------------------------------------------------------+
| |
| Ninja - version 1.2.0 |
| |
| Author: <NAME> |
| |
| Based on: |
| |
| <NAME>, <NAME> and <NAME>, |
| "Integrand reduction of one-loop scattering amplitudes |
| through Laurent series expansion," |
| JHEP 1206 (2012) 095 [arXiv:1203.0291 [hep-ph]]. |
| |
| <NAME>, |
| "Ninja: Automated Integrand Reduction via Laurent |
| Expansion for One-Loop Amplitudes," |
| Comput.Phys.Commun. 185 (2014) [arXiv:1403.1229 [hep-ph]] |
| |
+----------------------------------------------------------------+
------- iteration 1
Update # PS points: 1040 --> 1040
Using random seed offsets: 1 , 4 , 0
with seed 34
Ranmar initialization seeds 13168 9412
Total number of FKS directories is 4
FKS process map (sum= 3 ) :
1 --> 2 : 1 3
2 --> 2 : 2 4
================================
process combination map (specified per FKS dir):
1 map 1 2 3 4
1 inv. map 1 2 3 4
2 map 1 2 3 4
2 inv. map 1 2 3 4
3 map 1 2 3 4
3 inv. map 1 2 3 4
4 map 1 2 3 4
4 inv. map 1 2 3 4
================================
tau_min 1 1 : 0.17161E+03 -- 0.38042E+03
tau_min 2 1 : 0.17161E+03 -- 0.38042E+03
tau_min 3 1 : 0.17161E+03 -- 0.38042E+03
tau_min 4 1 : 0.17161E+03 -- 0.38042E+03
bpower is 0.0000000000000000
Scale values (may change event by event):
muR, muR_reference: 0.207827D+03 0.207827D+03 1.00
muF1, muF1_reference: 0.207827D+03 0.207827D+03 1.00
muF2, muF2_reference: 0.207827D+03 0.207827D+03 1.00
QES, QES_reference: 0.207827D+03 0.207827D+03 1.00
muR_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF1_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
muF2_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
QES_reference [functional form]:
H_T/2 := sum_i mT(i)/2, i=final state
alpha_s= 0.10577794065677032
alpha_s value used for the virtuals is (for the first PS point): 0.10594314538627060
==========================================================================================
{ }
{ [32m [0m }
{ [32m ,, [0m }
{ [32m`7MMM. ,MMF' `7MM `7MMF' [0m }
{ [32m MMMb dPMM MM MM [0m }
{ [32m M YM ,M MM ,6"Yb. ,M""bMM MM ,pW"Wq. ,pW"Wq.`7MMpdMAo. [0m }
{ [32m M Mb M' MM 8) MM ,AP MM MM 6W' `Wb 6W' `Wb MM `Wb [0m }
{ [32m M YM.P' MM ,pm9MM 8MI MM MM , 8M M8 8M M8 MM M8 [0m }
{ [32m M `YM' MM 8M MM `Mb MM MM ,M YA. ,A9 YA. ,A9 MM ,AP [0m }
{ [32m.JML. `' .JMML.`Moo9^Yo.`Wbmd"MML..JMMmmmmMMM `Ybmd9' `Ybmd9' MMbmmd' [0m }
{ [32m MM [0m }
{ [32m .JMML. [0m }
{ [32m[0mv2.6.6 (2018-06-28), Ref: arXiv:1103.0621v2, arXiv:1405.0301[32m [0m }
{ [32m [0m }
{ }
==========================================================================================
===============================================================
INFO: MadLoop read these parameters from ../MadLoop5_resources/MadLoopParams.dat
===============================================================
> MLReductionLib = 6|7|1
> CTModeRun = -1
> MLStabThres = 1.0000000000000000E-003
> NRotations_DP = 0
> NRotations_QP = 0
> CTStabThres = 1.0000000000000000E-002
> CTLoopLibrary = 2
> CTModeInit = 1
> CheckCycle = 3
> MaxAttempts = 10
> UseLoopFilter = F
> HelicityFilterLevel = 2
> ImprovePSPoint = 2
> DoubleCheckHelicityFilter = T
> LoopInitStartOver = F
> HelInitStartOver = F
> ZeroThres = 1.0000000000000001E-009
> OSThres = 1.0000000000000000E-008
> WriteOutFilters = T
> UseQPIntegrandForNinja = T
> UseQPIntegrandForCutTools = T
> IREGIMODE = 2
> IREGIRECY = T
> COLLIERMode = 1
> COLLIERRequiredAccuracy = 1.0000000000000000E-008
> COLLIERCanOutput = F
> COLLIERComputeUVpoles = T
> COLLIERComputeIRpoles = T
> COLLIERGlobalCache = -1
> COLLIERUseCacheForPoles = F
> COLLIERUseInternalStabilityTest = T
===============================================================
------------------------------------------------------------------------
| You are using CutTools - Version 1.9.3 |
| Authors: <NAME>, <NAME>, <NAME> |
| Published in JHEP 0803:042,2008 |
| http://www.ugr.es/~pittau/CutTools |
| |
| Compiler with 34 significant digits detetected |
----------------------------------------------------------------------
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
########################################################################
# #
# You are using OneLOop-3.6 #
# #
# for the evaluation of 1-loop scalar 1-, 2-, 3- and 4-point functions #
# #
# author: <NAME> <<EMAIL>> #
# date: 18-02-2015 #
# #
# Please cite #
# <NAME>, #
# Comput.Phys.Commun. 182 (2011) 2427-2438, arXiv:1007.4716 #
# <NAME>, <NAME> and <NAME>, #
# JHEP 0909:106,2009, arXiv:0903.4665 #
# in publications with results obtained with the help of this program. #
# #
########################################################################
---- POLES CANCELLED ----
ABS integral = 0.5022E-02 +/- 0.7655E-04 ( 1.524 %)
Integral = 0.4669E-02 +/- 0.8208E-04 ( 1.758 %)
Virtual = -.8363E-05 +/- 0.3534E-04 ( 422.531 %)
Virtual ratio = 0.5010E+01 +/- 0.3407E+00 ( 6.802 %)
ABS virtual = 0.5940E-04 +/- 0.3531E-04 ( 59.453 %)
Born*ao2pi = 0.3523E-06 +/- 0.1253E-06 ( 35.577 %)
Chi^2 per d.o.f. 0.0000E+00
accumulated results ABS integral = 0.5022E-02 +/- 0.7655E-04 ( 1.524 %)
accumulated results Integral = 0.4669E-02 +/- 0.8208E-04 ( 1.758 %)
accumulated results Virtual = -.8363E-05 +/- 0.3534E-04 ( 422.531 %)
accumulated results Virtual ratio = 0.5010E+01 +/- 0.3407E+00 ( 6.802 %)
accumulated results ABS virtual = 0.5940E-04 +/- 0.3531E-04 ( 59.453 %)
accumulated results Born*ao2pi = 0.3523E-06 +/- 0.1253E-06 ( 35.577 %)
accumulated result Chi^2 per DoF = 0.0000E+00
channel 1 : 1 F 0 0 0.5022E-02 0.4669E-02 0.5000E-02
------- iteration 2
Update # PS points: 2080 --> 2080
ABS integral = 0.5159E-02 +/- 0.1094E-03 ( 2.121 %)
Integral = 0.4817E-02 +/- 0.1086E-03 ( 2.255 %)
Virtual = 0.1765E-04 +/- 0.7081E-05 ( 40.132 %)
Virtual ratio = 0.5280E+01 +/- 0.6902E-01 ( 1.307 %)
ABS virtual = 0.2243E-04 +/- 0.7078E-05 ( 31.554 %)
Born*ao2pi = 0.2628E-06 +/- 0.7293E-07 ( 27.751 %)
Chi^2= 0.5426E+00
accumulated results ABS integral = 0.5078E-02 +/- 0.6273E-04 ( 1.235 %)
accumulated results Integral = 0.4733E-02 +/- 0.6549E-04 ( 1.384 %)
accumulated results Virtual = 0.1330E-04 +/- 0.6943E-05 ( 52.192 %)
accumulated results Virtual ratio = 0.5234E+01 +/- 0.6765E-01 ( 1.292 %)
accumulated results ABS virtual = 0.2860E-04 +/- 0.6940E-05 ( 24.263 %)
accumulated results Born*ao2pi = 0.2957E-06 +/- 0.6303E-07 ( 21.316 %)
accumulated result Chi^2 per DoF = 0.5426E+00
channel 1 : 1 F 0 0 0.5078E-02 0.4733E-02 0.5000E-02
------- iteration 3
Update # PS points: 4160 --> 4160
ABS integral = 0.5053E-02 +/- 0.4684E-04 ( 0.927 %)
Integral = 0.4708E-02 +/- 0.4519E-04 ( 0.960 %)
Virtual = 0.1645E-04 +/- 0.6005E-05 ( 36.504 %)
Virtual ratio = 0.5117E+01 +/- 0.1080E+00 ( 2.111 %)
ABS virtual = 0.3052E-04 +/- 0.5998E-05 ( 19.654 %)
Born*ao2pi = 0.3231E-06 +/- 0.5630E-07 ( 17.428 %)
Chi^2= 0.5565E-01
accumulated results ABS integral = 0.5064E-02 +/- 0.3753E-04 ( 0.741 %)
accumulated results Integral = 0.4718E-02 +/- 0.3719E-04 ( 0.788 %)
accumulated results Virtual = 0.1499E-04 +/- 0.4542E-05 ( 30.298 %)
accumulated results Virtual ratio = 0.5189E+01 +/- 0.5733E-01 ( 1.105 %)
accumulated results ABS virtual = 0.2963E-04 +/- 0.4538E-05 ( 15.316 %)
accumulated results Born*ao2pi = 0.3102E-06 +/- 0.4199E-07 ( 13.538 %)
accumulated result Chi^2 per DoF = 0.2991E+00
channel 1 : 1 F 0 0 0.5064E-02 0.4718E-02 0.5000E-02
------- iteration 4
Update # PS points: 8320 --> 8320
ABS integral = 0.5106E-02 +/- 0.2658E-04 ( 0.521 %)
Integral = 0.4735E-02 +/- 0.2617E-04 ( 0.553 %)
Virtual = 0.5102E-05 +/- 0.7314E-05 ( 143.348 %)
Virtual ratio = 0.5100E+01 +/- 0.1045E+00 ( 2.049 %)
ABS virtual = 0.3184E-04 +/- 0.7310E-05 ( 22.957 %)
Born*ao2pi = 0.2635E-06 +/- 0.3993E-07 ( 15.150 %)
Chi^2= 0.4340E+00
accumulated results ABS integral = 0.5088E-02 +/- 0.2169E-04 ( 0.426 %)
accumulated results Integral = 0.4728E-02 +/- 0.2140E-04 ( 0.453 %)
accumulated results Virtual = 0.1120E-04 +/- 0.3858E-05 ( 34.443 %)
accumulated results Virtual ratio = 0.5158E+01 +/- 0.5026E-01 ( 0.975 %)
accumulated results ABS virtual = 0.3048E-04 +/- 0.3856E-05 ( 12.651 %)
accumulated results Born*ao2pi = 0.2863E-06 +/- 0.2894E-07 ( 10.108 %)
accumulated result Chi^2 per DoF = 0.3441E+00
accumulated results last 3 iterations ABS integral = 0.5098E-02 +/- 0.2262E-04 ( 0.444 %)
accumulated results last 3 iterations Integral = 0.4737E-02 +/- 0.2217E-04 ( 0.468 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.2792E+00
channel 1 : 1 F 0 0 0.5088E-02 0.4728E-02 0.5000E-02
------- iteration 5
Update # PS points: 16640 --> 16640
ABS integral = 0.5033E-02 +/- 0.2146E-04 ( 0.426 %)
Integral = 0.4676E-02 +/- 0.2123E-04 ( 0.454 %)
Virtual = 0.8531E-05 +/- 0.5056E-05 ( 59.264 %)
Virtual ratio = 0.5073E+01 +/- 0.6687E-01 ( 1.318 %)
ABS virtual = 0.4173E-04 +/- 0.5051E-05 ( 12.102 %)
Born*ao2pi = 0.3614E-06 +/- 0.3218E-07 ( 8.903 %)
Chi^2= 0.1618E+01
accumulated results ABS integral = 0.5061E-02 +/- 0.1526E-04 ( 0.301 %)
accumulated results Integral = 0.4702E-02 +/- 0.1507E-04 ( 0.321 %)
accumulated results Virtual = 0.1005E-04 +/- 0.3067E-05 ( 30.532 %)
accumulated results Virtual ratio = 0.5121E+01 +/- 0.4018E-01 ( 0.785 %)
accumulated results ABS virtual = 0.3535E-04 +/- 0.3065E-05 ( 8.669 %)
accumulated results Born*ao2pi = 0.3219E-06 +/- 0.2152E-07 ( 6.685 %)
accumulated result Chi^2 per DoF = 0.6627E+00
accumulated results last 3 iterations ABS integral = 0.5059E-02 +/- 0.1573E-04 ( 0.311 %)
accumulated results last 3 iterations Integral = 0.4700E-02 +/- 0.1549E-04 ( 0.330 %)
accumulated result last 3 iterrations Chi^2 per DoF = 0.9732E+00
Found desired accuracy
channel 1 : 1 F 0 0 0.5061E-02 0.4702E-02 0.5000E-02
-------
Final result [ABS]: 5.0960317548845949E-003 +/- 1.5561658567171803E-005
Final result: 4.7020256725820858E-003 +/- 1.5073086934846550E-005
chi**2 per D.o.F.: 0.66266975257504601
Satistics from MadLoop:
Total points tried: 306
Stability unknown: 0
Stable PS point: 306
Unstable PS point (and rescued): 0
Exceptional PS point (unstable and not rescued): 0
Double precision used: 306
Quadruple precision used: 0
Initialization phase-space points: 0
Unknown return code (100): 0
Unknown return code (10): 0
Unit return code distribution (1):
#Unit 6 = 306
Time spent in Born : 1.74970555
Time spent in PS_Generation : 0.00000000
Time spent in Reals_evaluation: 13.4048061
Time spent in MCsubtraction : 5.44208813
Time spent in Counter_terms : 7.45823097
Time spent in Integrated_CT : 0.325882077
Time spent in Virtuals : 4.19625640E-02
Time spent in FxFx_cluster : 0.00000000
Time spent in Nbody_prefactor : 1.82867861
Time spent in N1body_prefactor : 1.94642377
Time spent in Adding_alphas_pdf : 1.26627827
Time spent in Reweight_scale : 0.00000000
Time spent in Reweight_pdf : 0.00000000
Time spent in Filling_plots : 0.00000000
Time spent in Applying_cuts : 0.389467418
Time spent in Sum_ident_contr : 0.112408705
Time spent in Pick_unwgt : 0.00000000
Time spent in Write_events : 0.00000000
Time spent in Other_tasks : 2.98524094
Time spent in Total : 36.9511719
Time in seconds: 37
</PRE><br>
</font>
</BODY></HTML>
<file_sep>/TimingMeasurement/B/SubProcesses/P3_bbx_zx0_z_ll_x0_tapvlqq/coloramps.inc
LOGICAL ICOLAMP(1,8,4)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,4),I=1,1)/.TRUE./
<file_sep>/LHC_HH_2lep/Source/nexternal.inc
../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/nexternal.inc<file_sep>/PROCNLO_HC_NLO_X0_UFO_0/SubProcesses/P0_uxd_wmx0_wmepemz_no_a/leshouche_decl.inc
INTEGER MAXPROC_USED, MAXFLOW_USED
PARAMETER (MAXPROC_USED = 4)
PARAMETER (MAXFLOW_USED = 1)
INTEGER IDUP_D(4,7,MAXPROC_USED)
INTEGER MOTHUP_D(4,2,7,MAXPROC_USED)
INTEGER ICOLUP_D(4,2,7,MAXFLOW_USED)
INTEGER NIPROCS_D(4)
<file_sep>/LHC_HH_2lep/SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/mirrorprocs.inc
DATA (MIRRORPROCS(I),I=1,40)/.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE./
<file_sep>/TimingMeasurement/D/SubProcesses/P2_qq_wmx0_wm_tamvl_x0_llbbx/coloramps.inc
LOGICAL ICOLAMP(1,12,4)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,4),I=1,1)/.TRUE./
<file_sep>/Processes/job_2lep_9_360.sh
#!/bin/bash
date
pwd
hostname
rundir=/home/disk-13/xuyue
rm -fr $rundir/tmp_2lep_360
mkdir -p $rundir/tmp_2lep_360
pushd $rundir/tmp_2lep_360
cp /home/storage/Users/chenx/atlas/Htautau/MG5_aMC_v2_5_4/plot_heavy/MG5/LHC_HH_2lep.tgz .
tar xf LHC_HH_2lep.tgz
pushd $rundir/tmp_2lep_360/LHC_HH_2lep
cat Cards/run_card.dat | sed 's/ 0 = iseed/ 360 = iseed/' > tmp.txt
mv tmp.txt Cards/run_card.dat
rm -f tmp.txt
cat Cards/param_card.dat | sed 's/1 1.000000e+00 # rhoH/1 0.05 # rhoH/'|sed 's/254 5.000000e+02 # MHH/254 300 # MHH/'|sed 's/3 1.300000e+00 # fW/3 160 # fW/'|sed 's/4 1.400000e+00 # fWW/4 960 # fWW/' > tmp.txt
mv tmp.txt Cards/param_card.dat
rm -f tmp.txt
./bin/generate_events -f run1
popd
mv $rundir/tmp_2lep_360/LHC_HH_2lep/Events/run1/unweighted_events.lhe.gz .
gunzip unweighted_events.lhe.gz
mv LHC_HH_2lep/Events/run1/run1_tag_1_banner.txt /home/storage/Users/xuyue/HeavyHiggs/plot_heavy/rootfiles/300GeV/ntuple_2lep/S2_red_360.txt
rm -fr LHC_HH_2lep*
export LD_LIBRARY_PATH=/home/storage/Users/chenx/atlas/Htautau/pythia8219/lib:/usr/local/root/lib:$LD_LIBRARY_PATH
/home/storage/Users/chenx/atlas/Htautau/pythia8219/examples/main_EWZjj /home/storage/Users/chenx/atlas/Htautau/pythia8219/examples/main_EWZjj.cmnd unweighted_events.lhe S2_360.hepmc 360
rm -f S2_360.root
/home/storage/Users/chenx/atlas/Htautau/delphes/DelphesHepMC /home/storage/Users/chenx/atlas/Htautau/delphes/cards/delphes_card_ATLAS_HLVVV.tcl S2_360.root S2_360.hepmc
rm -f S2_360.hepmc
root -l -b -q /home/storage/Users/xuyue/HeavyHiggs/plot_heavy/slurm/run_reduce.cc"(\"S2_360.root\",\"S2_red_360.root\")"
rm -f S2_360.root
mv S2_red_360.root /home/storage/Users/xuyue/HeavyHiggs/plot_heavy/rootfiles/300GeV/ntuple_2lep
popd
rm -fr $rundir/tmp_2lep_360
date
<file_sep>/TimingMeasurement/B/Source/nexternal.inc
../SubProcesses/P3_bbx_zx0_z_tamtap_x0_tapvlqq/nexternal.inc<file_sep>/TimingMeasurement/C/SubProcesses/P2_qq_wpx0_wp_tapvl_x0_llqq/mirrorprocs.inc
DATA (MIRRORPROCS(I),I=1,8)/.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE./
<file_sep>/TimingMeasurement/C/SubProcesses/P2_qq_wpx0_wp_lvl_x0_llbbx/coloramps.inc
LOGICAL ICOLAMP(1,12,8)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,8),I=1,1)/.TRUE./
<file_sep>/TimingMeasurement/D/Source/MODEL/input.inc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c written by the UFO converter
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
DOUBLE PRECISION MDL_SQRT__AS,MDL_G__EXP__2,MDL_GAAGG,MDL_GAGG
$ ,MDL_GHGG,MDL_GHHGG,MDL_COS__CABI,MDL_SIN__CABI,MDL_CA__EXP__2
$ ,MDL_SA,MDL_MZ__EXP__2,MDL_MZ__EXP__4,MDL_SQRT__2
$ ,MDL_NB__2__EXP__0_75,MDL_MX0__EXP__2,MDL_CA__EXP__4
$ ,MDL_CA__EXP__3,MDL_AEW,MDL_SQRT__AEW,MDL_EE,MDL_MW__EXP__2
$ ,MDL_SW2,MDL_CW,MDL_SQRT__SW2,MDL_SW,MDL_AD,MDL_AL,MDL_AN
$ ,MDL_AU,MDL_BD,MDL_BL,MDL_BN,MDL_BU,MDL_GWWZ,MDL_G1,MDL_GW
$ ,MDL_VEV,MDL_EE__EXP__2,MDL_GAAA,MDL_VEV__EXP__2,MDL_CW__EXP__2
$ ,MDL_GAZA,MDL_GHAA,MDL_GHZA,MDL_LAM,MDL_YB,MDL_YT,MDL_YTAU
$ ,MDL_MUH,MDL_SW__EXP__2,MDL_CABI,AEWM1,MDL_GF,AS,MDL_YMB
$ ,MDL_YMT,MDL_YMTAU,MDL_LAMBDA,MDL_CA,MDL_KSM,MDL_KHTT,MDL_KATT
$ ,MDL_KHBB,MDL_KABB,MDL_KHLL,MDL_KALL,MDL_KHAA,MDL_KAAA,MDL_KHZA
$ ,MDL_KAZA,MDL_KHGG,MDL_KAGG,MDL_KHZZ,MDL_KAZZ,MDL_KHWW,MDL_KAWW
$ ,MDL_KHDA,MDL_KHDZ,MDL_KHDWR,MDL_KHDWI,MDL_KHHGG,MDL_KAAGG
$ ,MDL_KQA,MDL_KQB,MDL_KLA,MDL_KLB,MDL_KW1,MDL_KW2,MDL_KW3
$ ,MDL_KW4,MDL_KW5,MDL_KZ1,MDL_KZ3,MDL_KZ5,MDL_KQ,MDL_KQ3,MDL_KL
$ ,MDL_KG,MDL_KA,MDL_KZ,MDL_KW,MDL_KZA
COMMON/PARAMS_R/ MDL_SQRT__AS,MDL_G__EXP__2,MDL_GAAGG,MDL_GAGG
$ ,MDL_GHGG,MDL_GHHGG,MDL_COS__CABI,MDL_SIN__CABI,MDL_CA__EXP__2
$ ,MDL_SA,MDL_MZ__EXP__2,MDL_MZ__EXP__4,MDL_SQRT__2
$ ,MDL_NB__2__EXP__0_75,MDL_MX0__EXP__2,MDL_CA__EXP__4
$ ,MDL_CA__EXP__3,MDL_AEW,MDL_SQRT__AEW,MDL_EE,MDL_MW__EXP__2
$ ,MDL_SW2,MDL_CW,MDL_SQRT__SW2,MDL_SW,MDL_AD,MDL_AL,MDL_AN
$ ,MDL_AU,MDL_BD,MDL_BL,MDL_BN,MDL_BU,MDL_GWWZ,MDL_G1,MDL_GW
$ ,MDL_VEV,MDL_EE__EXP__2,MDL_GAAA,MDL_VEV__EXP__2,MDL_CW__EXP__2
$ ,MDL_GAZA,MDL_GHAA,MDL_GHZA,MDL_LAM,MDL_YB,MDL_YT,MDL_YTAU
$ ,MDL_MUH,MDL_SW__EXP__2,MDL_CABI,AEWM1,MDL_GF,AS,MDL_YMB
$ ,MDL_YMT,MDL_YMTAU,MDL_LAMBDA,MDL_CA,MDL_KSM,MDL_KHTT,MDL_KATT
$ ,MDL_KHBB,MDL_KABB,MDL_KHLL,MDL_KALL,MDL_KHAA,MDL_KAAA,MDL_KHZA
$ ,MDL_KAZA,MDL_KHGG,MDL_KAGG,MDL_KHZZ,MDL_KAZZ,MDL_KHWW,MDL_KAWW
$ ,MDL_KHDA,MDL_KHDZ,MDL_KHDWR,MDL_KHDWI,MDL_KHHGG,MDL_KAAGG
$ ,MDL_KQA,MDL_KQB,MDL_KLA,MDL_KLB,MDL_KW1,MDL_KW2,MDL_KW3
$ ,MDL_KW4,MDL_KW5,MDL_KZ1,MDL_KZ3,MDL_KZ5,MDL_KQ,MDL_KQ3,MDL_KL
$ ,MDL_KG,MDL_KA,MDL_KZ,MDL_KW,MDL_KZA
DOUBLE COMPLEX MDL_CKM1X1,MDL_CKM1X2,MDL_CKM2X1,MDL_CKM2X2
$ ,MDL_COMPLEXI,MDL_KHDW,MDL_CONJG__CKM1X1,MDL_CONJG__CKM1X2
$ ,MDL_CONJG__CKM2X1,MDL_CONJG__CKM2X2,MDL_CONJG__KHDW
COMMON/PARAMS_C/ MDL_CKM1X1,MDL_CKM1X2,MDL_CKM2X1,MDL_CKM2X2
$ ,MDL_COMPLEXI,MDL_KHDW,MDL_CONJG__CKM1X1,MDL_CONJG__CKM1X2
$ ,MDL_CONJG__CKM2X1,MDL_CONJG__CKM2X2,MDL_CONJG__KHDW
<file_sep>/TimingMeasurement/B/SubProcesses/P1_bbx_zx0_z_ll_x0_qqbbx/coloramps.inc
LOGICAL ICOLAMP(2,12,1)
DATA(ICOLAMP(I,1,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,2,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,3,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,4,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,5,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,6,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,7,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,8,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,9,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,10,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,11,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,12,1),I=1,2)/.FALSE.,.TRUE./
<file_sep>/Processes/run_reduce.cc
void run_reduce(const char* infile, const char* outfile) {
gSystem->Load("/home/storage/Users/chenx/atlas/Htautau/delphes/libDelphes.so");
gSystem->Load("/home/storage/Users/chenx/atlas/Htautau/delphes/reduce_VVV_cc.so");
reduce(infile,outfile);
}
<file_sep>/TimingMeasurement/A/Source/MODEL/coupl.inc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c written by the UFO converter
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
DOUBLE PRECISION G
COMMON/STRONG/ G
DOUBLE COMPLEX GAL(2)
COMMON/WEAK/ GAL
DOUBLE PRECISION MU_R
COMMON/RSCALE/ MU_R
DOUBLE PRECISION NF
PARAMETER(NF=4)
DOUBLE PRECISION MDL_MT,MDL_MW,MDL_MZ,MDL_MTA,MDL_MB,MDL_MX2
$ ,MDL_MX0,MDL_MX1
COMMON/MASSES/ MDL_MT,MDL_MW,MDL_MZ,MDL_MTA,MDL_MB,MDL_MX2
$ ,MDL_MX0,MDL_MX1
DOUBLE PRECISION MDL_WW,MDL_WT,MDL_WZ,MDL_WX0,MDL_WX1,MDL_WX2
COMMON/WIDTHS/ MDL_WW,MDL_WT,MDL_WZ,MDL_WX0,MDL_WX1,MDL_WX2
DOUBLE COMPLEX GC_10, GC_13, GC_62, GC_64, GC_1, GC_2, GC_3,
$ GC_9, GC_16, GC_17, GC_19, GC_21, GC_22, GC_23, GC_24, GC_61,
$ GC_66, GC_77, GC_78, GC_89, GC_90, GC_98, GC_100, GC_101,
$ GC_102, GC_105, GC_106, GC_35, GC_38, GC_40, GC_42, GC_43,
$ GC_45, GC_49, GC_56, GC_58, GC_68
COMMON/COUPLINGS/ GC_10, GC_13, GC_62, GC_64, GC_1, GC_2, GC_3,
$ GC_9, GC_16, GC_17, GC_19, GC_21, GC_22, GC_23, GC_24, GC_61,
$ GC_66, GC_77, GC_78, GC_89, GC_90, GC_98, GC_100, GC_101,
$ GC_102, GC_105, GC_106, GC_35, GC_38, GC_40, GC_42, GC_43,
$ GC_45, GC_49, GC_56, GC_58, GC_68
<file_sep>/LHC_HH_2lep_rw/HTML/info.html
<HTML>
<HEAD>
<TITLE>Detail on the Generation</TITLE>
<META HTTP-EQUIV="REFRESH" CONTENT="30" ></HEAD>
<style type="text/css">
table.processes { border-collapse: collapse;
border: solid}
.processes td {
padding: 2 5 2 5;
border: solid thin;
}
th{
border-top: solid;
border-bottom: solid;
}
.first td{
border-top: solid;
}
</style>
<BODY>
<P> <H2 ALIGN=CENTER> SubProcesses and Feynman diagrams </H2>
<TABLE BORDER=2 ALIGN=CENTER class=processes>
<TR>
<TH>Directory</TH>
<TH NOWRAP># Diagrams </TH>
<TH NOWRAP># Subprocesses </TH>
<TH>FEYNMAN DIAGRAMS</TH>
<TH> SUBPROCESS </TH>
</TR>
<TR class=first> <TD class=$class rowspan=40> P1_qq_zhh_z_ll_hh_qqqq </TD>
<TD> 8 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#1" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix1.ps" >postscript </A>
</TD><TD class=first>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c c c~ c~
, <br>u~ u > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c c c~ c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#2" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix2.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u c u~ c~
, <br>u~ u > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u c u~ c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#3" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix3.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u d u~ d~
, <br>u~ u > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u d u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#4" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix4.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u d u~ s~
, <br>u~ u > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u d u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#5" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix5.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u d c~ d~
, <br>u~ u > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u d c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#6" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix6.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u d c~ s~
, <br>u~ u > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u d c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#7" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix7.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u s u~ d~
, <br>u~ u > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u s u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#8" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix8.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u s u~ s~
, <br>u~ u > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u s u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#9" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix9.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u s c~ d~
, <br>u~ u > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u s c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#10" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix10.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u s c~ s~
, <br>u~ u > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u s c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#11" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix11.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c d u~ d~
, <br>u~ u > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c d u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#12" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix12.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c d u~ s~
, <br>u~ u > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c d u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#13" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix13.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c d c~ d~
, <br>u~ u > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c d c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#14" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix14.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c d c~ s~
, <br>u~ u > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c d c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#15" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix15.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c s u~ d~
, <br>u~ u > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c s u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#16" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix16.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c s u~ s~
, <br>u~ u > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c s u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#17" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix17.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c s c~ d~
, <br>u~ u > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c s c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#18" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix18.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c s c~ s~
, <br>u~ u > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c s c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#19" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix19.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ s s s~ s~
, <br>u~ u > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ s s s~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#20" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix20.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ d s d~ s~
, <br>u~ u > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ d s d~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#21" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix21.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c c c~ c~
, <br>d~ d > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c c c~ c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#22" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix22.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u c u~ c~
, <br>d~ d > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u c u~ c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#23" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix23.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u d u~ d~
, <br>d~ d > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u d u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#24" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix24.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u d u~ s~
, <br>d~ d > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u d u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#25" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix25.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u d c~ d~
, <br>d~ d > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u d c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#26" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix26.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u d c~ s~
, <br>d~ d > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u d c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#27" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix27.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u s u~ d~
, <br>d~ d > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u s u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#28" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix28.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u s u~ s~
, <br>d~ d > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u s u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#29" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix29.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u s c~ d~
, <br>d~ d > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u s c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#30" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix30.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u s c~ s~
, <br>d~ d > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u s c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#31" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix31.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c d u~ d~
, <br>d~ d > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c d u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#32" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix32.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c d u~ s~
, <br>d~ d > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c d u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#33" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix33.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c d c~ d~
, <br>d~ d > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c d c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#34" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix34.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c d c~ s~
, <br>d~ d > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c d c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#35" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix35.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c s u~ d~
, <br>d~ d > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c s u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#36" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix36.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c s u~ s~
, <br>d~ d > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c s u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#37" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix37.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c s c~ d~
, <br>d~ d > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c s c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#38" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix38.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c s c~ s~
, <br>d~ d > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c s c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#39" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix39.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ s s s~ s~
, <br>d~ d > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ s s s~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#40" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix40.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ d s d~ s~
, <br>d~ d > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ d s d~ s~</SPAN>
</TD></TR>
<TR class=first> <TD class=$class rowspan=12> P2_qq_zhh_z_qq_hh_llqq </TD>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/diagrams.html#1" >html</A> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/matrix1.ps" >postscript </A>
</TD><TD class=first>
<SPAN style="white-space: nowrap;"> u u~ > u u~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > u u~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > c c~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > c c~ e- e+ c c~
, <br>u~ u > u u~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > u u~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > c c~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > c c~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/diagrams.html#2" >html</A> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/matrix2.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > c c~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > c c~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > u u~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > u u~ e- e+ c c~
, <br>u~ u > c c~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > c c~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > u u~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > u u~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/diagrams.html#3" >html</A> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/matrix3.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > d d~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > d d~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > s s~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > s s~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > d d~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > d d~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > s s~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > s s~ e- e+ c c~
, <br>u~ u > d d~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > d d~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > s s~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > s s~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > d d~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > d d~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > s s~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > s s~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/diagrams.html#4" >html</A> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/matrix4.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > u u~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > u u~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > c c~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > c c~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > u u~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > u u~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > c c~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > c c~ e- e+ s s~
, <br>u~ u > u u~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > u u~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > c c~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > c c~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > u u~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > u u~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > c c~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > c c~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/diagrams.html#5" >html</A> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/matrix5.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > d d~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > d d~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > s s~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > s s~ e- e+ s s~
, <br>u~ u > d d~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > d d~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > s s~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > s s~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/diagrams.html#6" >html</A> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/matrix6.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > s s~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > s s~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > d d~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > d d~ e- e+ s s~
, <br>u~ u > s s~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > s s~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > d d~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > d d~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/diagrams.html#7" >html</A> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/matrix7.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > u u~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > u u~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > c c~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > c c~ e- e+ c c~
, <br>d~ d > u u~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > u u~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > c c~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > c c~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/diagrams.html#8" >html</A> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/matrix8.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > c c~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > c c~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > u u~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > u u~ e- e+ c c~
, <br>d~ d > c c~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > c c~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > u u~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > u u~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/diagrams.html#9" >html</A> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/matrix9.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > d d~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > d d~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > s s~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > s s~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > d d~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > d d~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > s s~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > s s~ e- e+ c c~
, <br>d~ d > d d~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > d d~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > s s~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > s s~ e- e+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > d d~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > d d~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > s s~ e- e+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > s s~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/diagrams.html#10" >html</A> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/matrix10.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > u u~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > u u~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > c c~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > c c~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > u u~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > u u~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > c c~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > c c~ e- e+ s s~
, <br>d~ d > u u~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > u u~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > c c~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > c c~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > u u~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > u u~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > c c~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > c c~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/diagrams.html#11" >html</A> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/matrix11.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > d d~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > d d~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > s s~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > s s~ e- e+ s s~
, <br>d~ d > d d~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > d d~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > s s~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > s s~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/diagrams.html#12" >html</A> <A HREF="../SubProcesses/P2_qq_zhh_z_qq_hh_llqq/matrix12.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > s s~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > s s~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > d d~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > d d~ e- e+ s s~
, <br>d~ d > s s~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > s s~ e- e+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > d d~ e- e+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > d d~ e- e+ s s~</SPAN>
</TD></TR>
<TR class=first> <TD class=$class rowspan=12> P3_qq_zhh_z_qq_hh_llqq </TD>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/diagrams.html#1" >html</A> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/matrix1.ps" >postscript </A>
</TD><TD class=first>
<SPAN style="white-space: nowrap;"> u u~ > u u~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > u u~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > c c~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > c c~ mu- mu+ c c~
, <br>u~ u > u u~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > u u~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > c c~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > c c~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/diagrams.html#2" >html</A> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/matrix2.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > c c~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > c c~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > u u~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > u u~ mu- mu+ c c~
, <br>u~ u > c c~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > c c~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > u u~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > u u~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/diagrams.html#3" >html</A> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/matrix3.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > d d~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > d d~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > s s~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > s s~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > d d~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > d d~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > s s~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > s s~ mu- mu+ c c~
, <br>u~ u > d d~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > d d~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > s s~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > s s~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > d d~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > d d~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > s s~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > s s~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/diagrams.html#4" >html</A> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/matrix4.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > u u~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > u u~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > c c~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > c c~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > u u~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > u u~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > c c~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > c c~ mu- mu+ s s~
, <br>u~ u > u u~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > u u~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > c c~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > c c~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > u u~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > u u~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > c c~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > c c~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/diagrams.html#5" >html</A> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/matrix5.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > d d~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > d d~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > s s~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > s s~ mu- mu+ s s~
, <br>u~ u > d d~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > d d~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > s s~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > s s~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/diagrams.html#6" >html</A> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/matrix6.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > s s~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > s s~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > d d~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > d d~ mu- mu+ s s~
, <br>u~ u > s s~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > s s~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > d d~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > d d~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/diagrams.html#7" >html</A> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/matrix7.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > u u~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > u u~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > c c~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > c c~ mu- mu+ c c~
, <br>d~ d > u u~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > u u~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > c c~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > c c~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/diagrams.html#8" >html</A> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/matrix8.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > c c~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > c c~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > u u~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > u u~ mu- mu+ c c~
, <br>d~ d > c c~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > c c~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > u u~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > u u~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/diagrams.html#9" >html</A> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/matrix9.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > d d~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > d d~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > s s~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > s s~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > d d~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > d d~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > s s~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > s s~ mu- mu+ c c~
, <br>d~ d > d d~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > d d~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > s s~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > s s~ mu- mu+ u u~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > d d~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > d d~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > s s~ mu- mu+ c c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > s s~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/diagrams.html#10" >html</A> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/matrix10.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > u u~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > u u~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > c c~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > c c~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > u u~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > u u~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > c c~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > c c~ mu- mu+ s s~
, <br>d~ d > u u~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > u u~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > c c~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > c c~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > u u~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > u u~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > c c~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > c c~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/diagrams.html#11" >html</A> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/matrix11.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > d d~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > d d~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > s s~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > s s~ mu- mu+ s s~
, <br>d~ d > d d~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > d d~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > s s~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > s s~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/diagrams.html#12" >html</A> <A HREF="../SubProcesses/P3_qq_zhh_z_qq_hh_llqq/matrix12.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > s s~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > s s~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > d d~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > d d~ mu- mu+ s s~
, <br>d~ d > s s~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > s s~ mu- mu+ d d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > d d~ mu- mu+ s s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > d d~ mu- mu+ s s~</SPAN>
</TD></TR>
<TR class=first> <TD class=$class rowspan=64> P4_qq_wmhh_wm_qq_hh_llqq </TD>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#1" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix1.ps" >postscript </A>
</TD><TD class=first>
<SPAN style="white-space: nowrap;"> d u~ > d u~ e- e+ u u~
, <br>u~ d > d u~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#2" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix2.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d u~ e- e+ c c~
, <br>u~ d > d u~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#3" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix3.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d u~ e- e+ d d~
, <br>u~ d > d u~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#4" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix4.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d u~ e- e+ s s~
, <br>u~ d > d u~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#5" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix5.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d c~ e- e+ u u~
, <br>u~ d > d c~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#6" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix6.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d c~ e- e+ c c~
, <br>u~ d > d c~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#7" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix7.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d c~ e- e+ d d~
, <br>u~ d > d c~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#8" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix8.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d c~ e- e+ s s~
, <br>u~ d > d c~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#9" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix9.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s u~ e- e+ u u~
, <br>u~ d > s u~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#10" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix10.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s u~ e- e+ c c~
, <br>u~ d > s u~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#11" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix11.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s u~ e- e+ d d~
, <br>u~ d > s u~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#12" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix12.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s u~ e- e+ s s~
, <br>u~ d > s u~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#13" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix13.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s c~ e- e+ u u~
, <br>u~ d > s c~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#14" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix14.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s c~ e- e+ c c~
, <br>u~ d > s c~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#15" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix15.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s c~ e- e+ d d~
, <br>u~ d > s c~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#16" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix16.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s c~ e- e+ s s~
, <br>u~ d > s c~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#17" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix17.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d u~ e- e+ u u~
, <br>c~ d > d u~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#18" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix18.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d u~ e- e+ c c~
, <br>c~ d > d u~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#19" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix19.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d u~ e- e+ d d~
, <br>c~ d > d u~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#20" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix20.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d u~ e- e+ s s~
, <br>c~ d > d u~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#21" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix21.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d c~ e- e+ u u~
, <br>c~ d > d c~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#22" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix22.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d c~ e- e+ c c~
, <br>c~ d > d c~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#23" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix23.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d c~ e- e+ d d~
, <br>c~ d > d c~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#24" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix24.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d c~ e- e+ s s~
, <br>c~ d > d c~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#25" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix25.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s u~ e- e+ u u~
, <br>c~ d > s u~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#26" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix26.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s u~ e- e+ c c~
, <br>c~ d > s u~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#27" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix27.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s u~ e- e+ d d~
, <br>c~ d > s u~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#28" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix28.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s u~ e- e+ s s~
, <br>c~ d > s u~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#29" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix29.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s c~ e- e+ u u~
, <br>c~ d > s c~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#30" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix30.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s c~ e- e+ c c~
, <br>c~ d > s c~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#31" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix31.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s c~ e- e+ d d~
, <br>c~ d > s c~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#32" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix32.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s c~ e- e+ s s~
, <br>c~ d > s c~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#33" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix33.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d u~ e- e+ u u~
, <br>u~ s > d u~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#34" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix34.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d u~ e- e+ c c~
, <br>u~ s > d u~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#35" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix35.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d u~ e- e+ d d~
, <br>u~ s > d u~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#36" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix36.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d u~ e- e+ s s~
, <br>u~ s > d u~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#37" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix37.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d c~ e- e+ u u~
, <br>u~ s > d c~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#38" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix38.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d c~ e- e+ c c~
, <br>u~ s > d c~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#39" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix39.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d c~ e- e+ d d~
, <br>u~ s > d c~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#40" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix40.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d c~ e- e+ s s~
, <br>u~ s > d c~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#41" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix41.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s u~ e- e+ u u~
, <br>u~ s > s u~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#42" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix42.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s u~ e- e+ c c~
, <br>u~ s > s u~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#43" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix43.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s u~ e- e+ d d~
, <br>u~ s > s u~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#44" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix44.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s u~ e- e+ s s~
, <br>u~ s > s u~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#45" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix45.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s c~ e- e+ u u~
, <br>u~ s > s c~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#46" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix46.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s c~ e- e+ c c~
, <br>u~ s > s c~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#47" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix47.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s c~ e- e+ d d~
, <br>u~ s > s c~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#48" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix48.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s c~ e- e+ s s~
, <br>u~ s > s c~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#49" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix49.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d u~ e- e+ u u~
, <br>c~ s > d u~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#50" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix50.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d u~ e- e+ c c~
, <br>c~ s > d u~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#51" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix51.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d u~ e- e+ d d~
, <br>c~ s > d u~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#52" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix52.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d u~ e- e+ s s~
, <br>c~ s > d u~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#53" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix53.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d c~ e- e+ u u~
, <br>c~ s > d c~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#54" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix54.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d c~ e- e+ c c~
, <br>c~ s > d c~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#55" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix55.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d c~ e- e+ d d~
, <br>c~ s > d c~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#56" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix56.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d c~ e- e+ s s~
, <br>c~ s > d c~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#57" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix57.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s u~ e- e+ u u~
, <br>c~ s > s u~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#58" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix58.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s u~ e- e+ c c~
, <br>c~ s > s u~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#59" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix59.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s u~ e- e+ d d~
, <br>c~ s > s u~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#60" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix60.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s u~ e- e+ s s~
, <br>c~ s > s u~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#61" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix61.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s c~ e- e+ u u~
, <br>c~ s > s c~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#62" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix62.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s c~ e- e+ c c~
, <br>c~ s > s c~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#63" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix63.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s c~ e- e+ d d~
, <br>c~ s > s c~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/diagrams.html#64" >html</A> <A HREF="../SubProcesses/P4_qq_wmhh_wm_qq_hh_llqq/matrix64.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s c~ e- e+ s s~
, <br>c~ s > s c~ e- e+ s s~</SPAN>
</TD></TR>
<TR class=first> <TD class=$class rowspan=64> P5_qq_wmhh_wm_qq_hh_llqq </TD>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#1" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix1.ps" >postscript </A>
</TD><TD class=first>
<SPAN style="white-space: nowrap;"> d u~ > d u~ mu- mu+ u u~
, <br>u~ d > d u~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#2" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix2.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d u~ mu- mu+ c c~
, <br>u~ d > d u~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#3" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix3.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d u~ mu- mu+ d d~
, <br>u~ d > d u~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#4" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix4.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d u~ mu- mu+ s s~
, <br>u~ d > d u~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#5" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix5.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d c~ mu- mu+ u u~
, <br>u~ d > d c~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#6" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix6.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d c~ mu- mu+ c c~
, <br>u~ d > d c~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#7" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix7.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d c~ mu- mu+ d d~
, <br>u~ d > d c~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#8" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix8.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > d c~ mu- mu+ s s~
, <br>u~ d > d c~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#9" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix9.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s u~ mu- mu+ u u~
, <br>u~ d > s u~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#10" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix10.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s u~ mu- mu+ c c~
, <br>u~ d > s u~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#11" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix11.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s u~ mu- mu+ d d~
, <br>u~ d > s u~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#12" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix12.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s u~ mu- mu+ s s~
, <br>u~ d > s u~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#13" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix13.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s c~ mu- mu+ u u~
, <br>u~ d > s c~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#14" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix14.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s c~ mu- mu+ c c~
, <br>u~ d > s c~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#15" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix15.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s c~ mu- mu+ d d~
, <br>u~ d > s c~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#16" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix16.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d u~ > s c~ mu- mu+ s s~
, <br>u~ d > s c~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#17" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix17.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d u~ mu- mu+ u u~
, <br>c~ d > d u~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#18" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix18.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d u~ mu- mu+ c c~
, <br>c~ d > d u~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#19" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix19.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d u~ mu- mu+ d d~
, <br>c~ d > d u~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#20" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix20.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d u~ mu- mu+ s s~
, <br>c~ d > d u~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#21" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix21.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d c~ mu- mu+ u u~
, <br>c~ d > d c~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#22" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix22.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d c~ mu- mu+ c c~
, <br>c~ d > d c~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#23" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix23.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d c~ mu- mu+ d d~
, <br>c~ d > d c~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#24" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix24.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > d c~ mu- mu+ s s~
, <br>c~ d > d c~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#25" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix25.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s u~ mu- mu+ u u~
, <br>c~ d > s u~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#26" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix26.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s u~ mu- mu+ c c~
, <br>c~ d > s u~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#27" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix27.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s u~ mu- mu+ d d~
, <br>c~ d > s u~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#28" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix28.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s u~ mu- mu+ s s~
, <br>c~ d > s u~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#29" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix29.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s c~ mu- mu+ u u~
, <br>c~ d > s c~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#30" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix30.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s c~ mu- mu+ c c~
, <br>c~ d > s c~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#31" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix31.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s c~ mu- mu+ d d~
, <br>c~ d > s c~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#32" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix32.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d c~ > s c~ mu- mu+ s s~
, <br>c~ d > s c~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#33" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix33.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d u~ mu- mu+ u u~
, <br>u~ s > d u~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#34" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix34.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d u~ mu- mu+ c c~
, <br>u~ s > d u~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#35" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix35.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d u~ mu- mu+ d d~
, <br>u~ s > d u~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#36" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix36.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d u~ mu- mu+ s s~
, <br>u~ s > d u~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#37" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix37.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d c~ mu- mu+ u u~
, <br>u~ s > d c~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#38" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix38.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d c~ mu- mu+ c c~
, <br>u~ s > d c~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#39" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix39.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d c~ mu- mu+ d d~
, <br>u~ s > d c~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#40" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix40.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > d c~ mu- mu+ s s~
, <br>u~ s > d c~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#41" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix41.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s u~ mu- mu+ u u~
, <br>u~ s > s u~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#42" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix42.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s u~ mu- mu+ c c~
, <br>u~ s > s u~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#43" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix43.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s u~ mu- mu+ d d~
, <br>u~ s > s u~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#44" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix44.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s u~ mu- mu+ s s~
, <br>u~ s > s u~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#45" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix45.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s c~ mu- mu+ u u~
, <br>u~ s > s c~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#46" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix46.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s c~ mu- mu+ c c~
, <br>u~ s > s c~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#47" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix47.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s c~ mu- mu+ d d~
, <br>u~ s > s c~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#48" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix48.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s u~ > s c~ mu- mu+ s s~
, <br>u~ s > s c~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#49" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix49.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d u~ mu- mu+ u u~
, <br>c~ s > d u~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#50" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix50.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d u~ mu- mu+ c c~
, <br>c~ s > d u~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#51" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix51.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d u~ mu- mu+ d d~
, <br>c~ s > d u~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#52" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix52.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d u~ mu- mu+ s s~
, <br>c~ s > d u~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#53" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix53.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d c~ mu- mu+ u u~
, <br>c~ s > d c~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#54" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix54.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d c~ mu- mu+ c c~
, <br>c~ s > d c~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#55" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix55.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d c~ mu- mu+ d d~
, <br>c~ s > d c~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#56" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix56.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > d c~ mu- mu+ s s~
, <br>c~ s > d c~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#57" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix57.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s u~ mu- mu+ u u~
, <br>c~ s > s u~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#58" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix58.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s u~ mu- mu+ c c~
, <br>c~ s > s u~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#59" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix59.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s u~ mu- mu+ d d~
, <br>c~ s > s u~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#60" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix60.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s u~ mu- mu+ s s~
, <br>c~ s > s u~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#61" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix61.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s c~ mu- mu+ u u~
, <br>c~ s > s c~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#62" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix62.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s c~ mu- mu+ c c~
, <br>c~ s > s c~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#63" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix63.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s c~ mu- mu+ d d~
, <br>c~ s > s c~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/diagrams.html#64" >html</A> <A HREF="../SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/matrix64.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> s c~ > s c~ mu- mu+ s s~
, <br>c~ s > s c~ mu- mu+ s s~</SPAN>
</TD></TR>
<TR class=first> <TD class=$class rowspan=64> P6_qq_wphh_wp_qq_hh_llqq </TD>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#1" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix1.ps" >postscript </A>
</TD><TD class=first>
<SPAN style="white-space: nowrap;"> u d~ > u d~ e- e+ u u~
, <br>d~ u > u d~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#2" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix2.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u d~ e- e+ c c~
, <br>d~ u > u d~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#3" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix3.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u d~ e- e+ d d~
, <br>d~ u > u d~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#4" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix4.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u d~ e- e+ s s~
, <br>d~ u > u d~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#5" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix5.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u s~ e- e+ u u~
, <br>d~ u > u s~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#6" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix6.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u s~ e- e+ c c~
, <br>d~ u > u s~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#7" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix7.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u s~ e- e+ d d~
, <br>d~ u > u s~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#8" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix8.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u s~ e- e+ s s~
, <br>d~ u > u s~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#9" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix9.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c d~ e- e+ u u~
, <br>d~ u > c d~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#10" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix10.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c d~ e- e+ c c~
, <br>d~ u > c d~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#11" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix11.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c d~ e- e+ d d~
, <br>d~ u > c d~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#12" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix12.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c d~ e- e+ s s~
, <br>d~ u > c d~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#13" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix13.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c s~ e- e+ u u~
, <br>d~ u > c s~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#14" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix14.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c s~ e- e+ c c~
, <br>d~ u > c s~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#15" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix15.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c s~ e- e+ d d~
, <br>d~ u > c s~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#16" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix16.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c s~ e- e+ s s~
, <br>d~ u > c s~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#17" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix17.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u d~ e- e+ u u~
, <br>s~ u > u d~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#18" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix18.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u d~ e- e+ c c~
, <br>s~ u > u d~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#19" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix19.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u d~ e- e+ d d~
, <br>s~ u > u d~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#20" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix20.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u d~ e- e+ s s~
, <br>s~ u > u d~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#21" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix21.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u s~ e- e+ u u~
, <br>s~ u > u s~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#22" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix22.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u s~ e- e+ c c~
, <br>s~ u > u s~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#23" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix23.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u s~ e- e+ d d~
, <br>s~ u > u s~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#24" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix24.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u s~ e- e+ s s~
, <br>s~ u > u s~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#25" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix25.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c d~ e- e+ u u~
, <br>s~ u > c d~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#26" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix26.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c d~ e- e+ c c~
, <br>s~ u > c d~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#27" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix27.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c d~ e- e+ d d~
, <br>s~ u > c d~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#28" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix28.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c d~ e- e+ s s~
, <br>s~ u > c d~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#29" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix29.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c s~ e- e+ u u~
, <br>s~ u > c s~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#30" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix30.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c s~ e- e+ c c~
, <br>s~ u > c s~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#31" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix31.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c s~ e- e+ d d~
, <br>s~ u > c s~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#32" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix32.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c s~ e- e+ s s~
, <br>s~ u > c s~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#33" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix33.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u d~ e- e+ u u~
, <br>d~ c > u d~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#34" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix34.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u d~ e- e+ c c~
, <br>d~ c > u d~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#35" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix35.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u d~ e- e+ d d~
, <br>d~ c > u d~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#36" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix36.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u d~ e- e+ s s~
, <br>d~ c > u d~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#37" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix37.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u s~ e- e+ u u~
, <br>d~ c > u s~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#38" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix38.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u s~ e- e+ c c~
, <br>d~ c > u s~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#39" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix39.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u s~ e- e+ d d~
, <br>d~ c > u s~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#40" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix40.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u s~ e- e+ s s~
, <br>d~ c > u s~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#41" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix41.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c d~ e- e+ u u~
, <br>d~ c > c d~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#42" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix42.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c d~ e- e+ c c~
, <br>d~ c > c d~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#43" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix43.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c d~ e- e+ d d~
, <br>d~ c > c d~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#44" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix44.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c d~ e- e+ s s~
, <br>d~ c > c d~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#45" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix45.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c s~ e- e+ u u~
, <br>d~ c > c s~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#46" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix46.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c s~ e- e+ c c~
, <br>d~ c > c s~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#47" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix47.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c s~ e- e+ d d~
, <br>d~ c > c s~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#48" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix48.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c s~ e- e+ s s~
, <br>d~ c > c s~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#49" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix49.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u d~ e- e+ u u~
, <br>s~ c > u d~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#50" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix50.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u d~ e- e+ c c~
, <br>s~ c > u d~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#51" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix51.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u d~ e- e+ d d~
, <br>s~ c > u d~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#52" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix52.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u d~ e- e+ s s~
, <br>s~ c > u d~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#53" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix53.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u s~ e- e+ u u~
, <br>s~ c > u s~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#54" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix54.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u s~ e- e+ c c~
, <br>s~ c > u s~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#55" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix55.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u s~ e- e+ d d~
, <br>s~ c > u s~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#56" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix56.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u s~ e- e+ s s~
, <br>s~ c > u s~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#57" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix57.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c d~ e- e+ u u~
, <br>s~ c > c d~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#58" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix58.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c d~ e- e+ c c~
, <br>s~ c > c d~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#59" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix59.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c d~ e- e+ d d~
, <br>s~ c > c d~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#60" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix60.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c d~ e- e+ s s~
, <br>s~ c > c d~ e- e+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#61" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix61.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c s~ e- e+ u u~
, <br>s~ c > c s~ e- e+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#62" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix62.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c s~ e- e+ c c~
, <br>s~ c > c s~ e- e+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#63" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix63.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c s~ e- e+ d d~
, <br>s~ c > c s~ e- e+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/diagrams.html#64" >html</A> <A HREF="../SubProcesses/P6_qq_wphh_wp_qq_hh_llqq/matrix64.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c s~ e- e+ s s~
, <br>s~ c > c s~ e- e+ s s~</SPAN>
</TD></TR>
<TR class=first> <TD class=$class rowspan=64> P7_qq_wphh_wp_qq_hh_llqq </TD>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#1" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix1.ps" >postscript </A>
</TD><TD class=first>
<SPAN style="white-space: nowrap;"> u d~ > u d~ mu- mu+ u u~
, <br>d~ u > u d~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#2" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix2.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u d~ mu- mu+ c c~
, <br>d~ u > u d~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#3" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix3.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u d~ mu- mu+ d d~
, <br>d~ u > u d~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#4" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix4.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u d~ mu- mu+ s s~
, <br>d~ u > u d~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#5" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix5.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u s~ mu- mu+ u u~
, <br>d~ u > u s~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#6" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix6.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u s~ mu- mu+ c c~
, <br>d~ u > u s~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#7" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix7.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u s~ mu- mu+ d d~
, <br>d~ u > u s~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#8" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix8.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > u s~ mu- mu+ s s~
, <br>d~ u > u s~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#9" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix9.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c d~ mu- mu+ u u~
, <br>d~ u > c d~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#10" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix10.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c d~ mu- mu+ c c~
, <br>d~ u > c d~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#11" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix11.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c d~ mu- mu+ d d~
, <br>d~ u > c d~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#12" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix12.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c d~ mu- mu+ s s~
, <br>d~ u > c d~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#13" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix13.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c s~ mu- mu+ u u~
, <br>d~ u > c s~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#14" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix14.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c s~ mu- mu+ c c~
, <br>d~ u > c s~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#15" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix15.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c s~ mu- mu+ d d~
, <br>d~ u > c s~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#16" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix16.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u d~ > c s~ mu- mu+ s s~
, <br>d~ u > c s~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#17" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix17.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u d~ mu- mu+ u u~
, <br>s~ u > u d~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#18" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix18.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u d~ mu- mu+ c c~
, <br>s~ u > u d~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#19" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix19.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u d~ mu- mu+ d d~
, <br>s~ u > u d~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#20" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix20.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u d~ mu- mu+ s s~
, <br>s~ u > u d~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#21" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix21.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u s~ mu- mu+ u u~
, <br>s~ u > u s~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#22" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix22.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u s~ mu- mu+ c c~
, <br>s~ u > u s~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#23" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix23.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u s~ mu- mu+ d d~
, <br>s~ u > u s~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#24" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix24.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > u s~ mu- mu+ s s~
, <br>s~ u > u s~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#25" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix25.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c d~ mu- mu+ u u~
, <br>s~ u > c d~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#26" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix26.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c d~ mu- mu+ c c~
, <br>s~ u > c d~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#27" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix27.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c d~ mu- mu+ d d~
, <br>s~ u > c d~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#28" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix28.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c d~ mu- mu+ s s~
, <br>s~ u > c d~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#29" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix29.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c s~ mu- mu+ u u~
, <br>s~ u > c s~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#30" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix30.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c s~ mu- mu+ c c~
, <br>s~ u > c s~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#31" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix31.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c s~ mu- mu+ d d~
, <br>s~ u > c s~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#32" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix32.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u s~ > c s~ mu- mu+ s s~
, <br>s~ u > c s~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#33" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix33.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u d~ mu- mu+ u u~
, <br>d~ c > u d~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#34" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix34.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u d~ mu- mu+ c c~
, <br>d~ c > u d~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#35" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix35.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u d~ mu- mu+ d d~
, <br>d~ c > u d~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#36" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix36.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u d~ mu- mu+ s s~
, <br>d~ c > u d~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#37" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix37.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u s~ mu- mu+ u u~
, <br>d~ c > u s~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#38" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix38.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u s~ mu- mu+ c c~
, <br>d~ c > u s~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#39" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix39.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u s~ mu- mu+ d d~
, <br>d~ c > u s~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#40" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix40.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > u s~ mu- mu+ s s~
, <br>d~ c > u s~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#41" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix41.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c d~ mu- mu+ u u~
, <br>d~ c > c d~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#42" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix42.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c d~ mu- mu+ c c~
, <br>d~ c > c d~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#43" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix43.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c d~ mu- mu+ d d~
, <br>d~ c > c d~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#44" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix44.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c d~ mu- mu+ s s~
, <br>d~ c > c d~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#45" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix45.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c s~ mu- mu+ u u~
, <br>d~ c > c s~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#46" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix46.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c s~ mu- mu+ c c~
, <br>d~ c > c s~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#47" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix47.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c s~ mu- mu+ d d~
, <br>d~ c > c s~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#48" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix48.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c d~ > c s~ mu- mu+ s s~
, <br>d~ c > c s~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#49" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix49.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u d~ mu- mu+ u u~
, <br>s~ c > u d~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#50" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix50.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u d~ mu- mu+ c c~
, <br>s~ c > u d~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#51" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix51.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u d~ mu- mu+ d d~
, <br>s~ c > u d~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#52" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix52.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u d~ mu- mu+ s s~
, <br>s~ c > u d~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#53" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix53.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u s~ mu- mu+ u u~
, <br>s~ c > u s~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#54" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix54.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u s~ mu- mu+ c c~
, <br>s~ c > u s~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#55" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix55.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u s~ mu- mu+ d d~
, <br>s~ c > u s~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#56" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix56.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > u s~ mu- mu+ s s~
, <br>s~ c > u s~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#57" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix57.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c d~ mu- mu+ u u~
, <br>s~ c > c d~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#58" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix58.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c d~ mu- mu+ c c~
, <br>s~ c > c d~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#59" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix59.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c d~ mu- mu+ d d~
, <br>s~ c > c d~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#60" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix60.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c d~ mu- mu+ s s~
, <br>s~ c > c d~ mu- mu+ s s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#61" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix61.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c s~ mu- mu+ u u~
, <br>s~ c > c s~ mu- mu+ u u~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#62" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix62.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c s~ mu- mu+ c c~
, <br>s~ c > c s~ mu- mu+ c c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#63" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix63.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c s~ mu- mu+ d d~
, <br>s~ c > c s~ mu- mu+ d d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 2 </TD>
<TD> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/diagrams.html#64" >html</A> <A HREF="../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/matrix64.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> c s~ > c s~ mu- mu+ s s~
, <br>s~ c > c s~ mu- mu+ s s~</SPAN>
</TD></TR>
</TABLE><BR>
<CENTER> 4992 diagrams (1328 independent).</CENTER>
<br><br><br>
<TABLE ALIGN=CENTER>
<TR>
<TD ALIGN=CENTER> <A HREF="../Cards/proc_card_mg5.dat">proc_card_mg5.dat</A> </TD>
<TD> Input file used for code generation.
</TABLE><br>
<center>
<H3>Back to <A HREF="../index.html">Process main page</A></H3>
</center>
</BODY>
</HTML><file_sep>/TimingMeasurement/A/SubProcesses/P1_bbx_zx0_z_qq_x0_tamtapbbx/coloramps.inc
LOGICAL ICOLAMP(1,100,2)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,49,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,50,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,51,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,52,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,53,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,54,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,55,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,56,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,57,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,58,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,59,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,60,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,61,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,62,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,63,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,64,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,65,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,66,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,67,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,68,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,69,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,70,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,71,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,72,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,73,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,74,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,75,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,76,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,77,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,78,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,79,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,80,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,81,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,82,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,83,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,84,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,85,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,86,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,87,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,88,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,89,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,90,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,91,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,92,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,93,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,94,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,95,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,96,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,97,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,98,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,99,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,100,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,49,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,50,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,51,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,52,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,53,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,54,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,55,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,56,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,57,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,58,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,59,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,60,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,61,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,62,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,63,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,64,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,65,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,66,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,67,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,68,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,69,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,70,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,71,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,72,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,73,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,74,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,75,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,76,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,77,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,78,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,79,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,80,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,81,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,82,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,83,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,84,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,85,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,86,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,87,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,88,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,89,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,90,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,91,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,92,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,93,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,94,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,95,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,96,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,97,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,98,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,99,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,100,2),I=1,1)/.TRUE./
<file_sep>/HC_lljjjj/Source/leshouche.inc
../SubProcesses/P1_qq_zx0_z_ll_x0_qqqq/leshouche.inc<file_sep>/TimingMeasurement/C/Source/leshouche.inc
../SubProcesses/P3_qq_wpwpwm_wp_tapvl_wp_tapvl_wm_qq/leshouche.inc<file_sep>/rw_lljjjj/HTML/info.html
<HTML>
<HEAD>
<TITLE>Detail on the Generation</TITLE>
<META HTTP-EQUIV="REFRESH" CONTENT="30" ></HEAD>
<style type="text/css">
table.processes { border-collapse: collapse;
border: solid}
.processes td {
padding: 2 5 2 5;
border: solid thin;
}
th{
border-top: solid;
border-bottom: solid;
}
.first td{
border-top: solid;
}
</style>
<BODY>
<P> <H2 ALIGN=CENTER> SubProcesses and Feynman diagrams </H2>
<TABLE BORDER=2 ALIGN=CENTER class=processes>
<TR>
<TH>Directory</TH>
<TH NOWRAP># Diagrams </TH>
<TH NOWRAP># Subprocesses </TH>
<TH>FEYNMAN DIAGRAMS</TH>
<TH> SUBPROCESS </TH>
</TR>
<TR class=first> <TD class=$class rowspan=40> P1_qq_zhh_z_ll_hh_qqqq </TD>
<TD> 8 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#1" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix1.ps" >postscript </A>
</TD><TD class=first>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c c c~ c~
, <br>u~ u > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c c c~ c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#2" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix2.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u c u~ c~
, <br>u~ u > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u c u~ c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#3" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix3.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u d u~ d~
, <br>u~ u > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u d u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#4" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix4.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u d u~ s~
, <br>u~ u > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u d u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#5" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix5.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u d c~ d~
, <br>u~ u > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u d c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#6" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix6.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u d c~ s~
, <br>u~ u > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u d c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#7" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix7.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u s u~ d~
, <br>u~ u > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u s u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#8" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix8.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u s u~ s~
, <br>u~ u > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u s u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#9" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix9.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u s c~ d~
, <br>u~ u > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u s c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#10" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix10.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ u s c~ s~
, <br>u~ u > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ u s c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#11" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix11.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c d u~ d~
, <br>u~ u > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c d u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#12" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix12.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c d u~ s~
, <br>u~ u > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c d u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#13" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix13.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c d c~ d~
, <br>u~ u > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c d c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#14" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix14.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c d c~ s~
, <br>u~ u > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c d c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#15" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix15.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c s u~ d~
, <br>u~ u > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c s u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#16" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix16.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c s u~ s~
, <br>u~ u > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c s u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#17" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix17.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c s c~ d~
, <br>u~ u > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c s c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#18" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix18.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ c s c~ s~
, <br>u~ u > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ c s c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#19" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix19.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ s s s~ s~
, <br>u~ u > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ s s s~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#20" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix20.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> u u~ > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u u~ > mu- mu+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c c~ > mu- mu+ d s d~ s~
, <br>u~ u > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> u~ u > mu- mu+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> c~ c > mu- mu+ d s d~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#21" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix21.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c c c~ c~
, <br>d~ d > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u u u~ u~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c c c~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c c c~ c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#22" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix22.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u c u~ c~
, <br>d~ d > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u c u~ c~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u c u~ c~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#23" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix23.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u d u~ d~
, <br>d~ d > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u d u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#24" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix24.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u d u~ s~
, <br>d~ d > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u d u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#25" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix25.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u d c~ d~
, <br>d~ d > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u d c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#26" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix26.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u d c~ s~
, <br>d~ d > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u d c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#27" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix27.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u s u~ d~
, <br>d~ d > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u s u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#28" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix28.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u s u~ s~
, <br>d~ d > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u s u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#29" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix29.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u s c~ d~
, <br>d~ d > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u s c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#30" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix30.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ u s c~ s~
, <br>d~ d > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ u s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ u s c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#31" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix31.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c d u~ d~
, <br>d~ d > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c d u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c d u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#32" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix32.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c d u~ s~
, <br>d~ d > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c d u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c d u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#33" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix33.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c d c~ d~
, <br>d~ d > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c d c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c d c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#34" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix34.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c d c~ s~
, <br>d~ d > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c d c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c d c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#35" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix35.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c s u~ d~
, <br>d~ d > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c s u~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c s u~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#36" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix36.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c s u~ s~
, <br>d~ d > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c s u~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c s u~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#37" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix37.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c s c~ d~
, <br>d~ d > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c s c~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c s c~ d~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#38" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix38.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ c s c~ s~
, <br>d~ d > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ c s c~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ c s c~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 8 </TD>
<TD> 16 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#39" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix39.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ s s s~ s~
, <br>d~ d > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ d d d~ d~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ s s s~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ s s s~ s~
</SPAN>
</TD></TR>
<TR class=second>
<TD> 4 </TD>
<TD> 8 </TD>
<TD> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/diagrams.html#40" >html</A> <A HREF="../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/matrix40.ps" >postscript </A>
</TD><TD class=second>
<SPAN style="white-space: nowrap;"> d d~ > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d d~ > mu- mu+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s s~ > mu- mu+ d s d~ s~
, <br>d~ d > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > e- e+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> d~ d > mu- mu+ d s d~ s~ </SPAN> , <SPAN style="white-space: nowrap;"> s~ s > mu- mu+ d s d~ s~</SPAN>
</TD></TR>
</TABLE><BR>
<CENTER> 1920 diagrams (208 independent).</CENTER>
<br><br><br>
<TABLE ALIGN=CENTER>
<TR>
<TD ALIGN=CENTER> <A HREF="../Cards/proc_card_mg5.dat">proc_card_mg5.dat</A> </TD>
<TD> Input file used for code generation.
</TABLE><br>
<center>
<H3>Back to <A HREF="../index.html">Process main page</A></H3>
</center>
</BODY>
</HTML><file_sep>/TimingMeasurement/A/Source/MODEL/coupl_write.inc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c written by the UFO converter
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
WRITE(*,*) ' Couplings of HC_UFO'
WRITE(*,*) ' ---------------------------------'
WRITE(*,*) ' '
WRITE(*,2) 'GC_10 = ', GC_10
WRITE(*,2) 'GC_13 = ', GC_13
WRITE(*,2) 'GC_62 = ', GC_62
WRITE(*,2) 'GC_64 = ', GC_64
WRITE(*,2) 'GC_1 = ', GC_1
WRITE(*,2) 'GC_2 = ', GC_2
WRITE(*,2) 'GC_3 = ', GC_3
WRITE(*,2) 'GC_9 = ', GC_9
WRITE(*,2) 'GC_16 = ', GC_16
WRITE(*,2) 'GC_17 = ', GC_17
WRITE(*,2) 'GC_19 = ', GC_19
WRITE(*,2) 'GC_21 = ', GC_21
WRITE(*,2) 'GC_22 = ', GC_22
WRITE(*,2) 'GC_23 = ', GC_23
WRITE(*,2) 'GC_24 = ', GC_24
WRITE(*,2) 'GC_61 = ', GC_61
WRITE(*,2) 'GC_66 = ', GC_66
WRITE(*,2) 'GC_77 = ', GC_77
WRITE(*,2) 'GC_78 = ', GC_78
WRITE(*,2) 'GC_89 = ', GC_89
WRITE(*,2) 'GC_90 = ', GC_90
WRITE(*,2) 'GC_98 = ', GC_98
WRITE(*,2) 'GC_100 = ', GC_100
WRITE(*,2) 'GC_101 = ', GC_101
WRITE(*,2) 'GC_102 = ', GC_102
WRITE(*,2) 'GC_105 = ', GC_105
WRITE(*,2) 'GC_106 = ', GC_106
WRITE(*,2) 'GC_35 = ', GC_35
WRITE(*,2) 'GC_38 = ', GC_38
WRITE(*,2) 'GC_40 = ', GC_40
WRITE(*,2) 'GC_42 = ', GC_42
WRITE(*,2) 'GC_43 = ', GC_43
WRITE(*,2) 'GC_45 = ', GC_45
WRITE(*,2) 'GC_49 = ', GC_49
WRITE(*,2) 'GC_56 = ', GC_56
WRITE(*,2) 'GC_58 = ', GC_58
WRITE(*,2) 'GC_68 = ', GC_68
<file_sep>/TimingMeasurement/D/SubProcesses/P1_qq_wmx0_wm_qq_x0_llbbx/coloramps.inc
LOGICAL ICOLAMP(1,12,16)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,16),I=1,1)/.TRUE./
<file_sep>/TimingMeasurement/D/Source/nexternal.inc
../SubProcesses/P3_qq_wmwmwp_wm_tamvl_wm_tamvl_wp_qq/nexternal.inc<file_sep>/README.md
# MG5-heavy-Higgs
<file_sep>/Processes/plot_2lep_www_600.cc
#include "TROOT.h"
#include "TLorentzVector.h"
#include "TChain.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TMath.h"
#include "THStack.h"
#include "TLegend.h"
#include "TCanvas.h"
#include "TStyle.h"
#include "../reader.h"
#define GeV 1000
#define lumi 300 //fb-1
void calibrate_jet() {
Double_t thr[7] = {30,50,80,120,200,400,800};
Double_t sf[3][7] = {
{1.00113, 1.0039, 1.00243, 1.00129, 1.00032, 1.00126, 1.00133},
{1.05701, 1.03567, 1.02281, 1.01503, 1.00959, 1.00691, 1.00511},
{1.04688, 1.02907, 1.021 , 1.01858, 1.02032, 1. , 1. }
};
for(Int_t i=0; i<jet_n; i++) {
Double_t SF = 1.0;
if(fabs(jet_eta[i])<1.7) {
for(Int_t j=6; j>=0; j--) {
if(jet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[0][j]; break;
}
}
}
else if(fabs(jet_eta[i])<3.2) {
for(Int_t j=6; j>=0; j--) {
if(jet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[1][j]; break;
}
}
}
else {
for(Int_t j=6; j>=0; j--) {
if(jet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[2][j]; break;
}
}
}
jet_E[i] *= SF;
jet_m[i] *= SF;
jet_pt[i] *= SF;
}
}
void calibrate_fatjet() {
Double_t thr[7] = {40,50,80,120,200,400,800};
Double_t sf[3][7] = {
{0.835528, 0.876777, 0.914269, 0.940094, 0.962477, 0.981316, 0.990554},
{0.959362, 0.968022, 0.976831, 0.983729, 0.989864, 0.995393, 0.997024},
{0.979653, 0.984607, 0.990887, 0.99717, 1.00537 , 1. , 1. }
};
for(Int_t i=0; i<fatjet_n; i++) {
Double_t SF = 1.0;
if(fabs(fatjet_eta[i])<1.7) {
for(Int_t j=6; j>=0; j--) {
if(fatjet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[0][j]; break;
}
}
}
else if(fabs(fatjet_eta[i])<3.2) {
for(Int_t j=6; j>=0; j--) {
if(fatjet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[1][j]; break;
}
}
}
else {
for(Int_t j=6; j>=0; j--) {
if(fatjet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[2][j]; break;
}
}
}
fatjet_E[i] *= SF;
fatjet_m[i] *= SF;
fatjet_pt[i] *= SF;
fatjet_m_sj1[i] *= SF;
fatjet_pt_sj1[i] *= SF;
fatjet_m_sj2[i] *= SF;
fatjet_pt_sj2[i] *= SF;
}
}
void SetMax(TH1* h1, TH1* h2, Double_t scale=1.0) {
h1->SetMaximum(scale*TMath::Max(h1->GetMaximum(),h2->GetMaximum()));
h2->SetMaximum(scale*TMath::Max(h1->GetMaximum(),h2->GetMaximum()));
}
Float_t DR(Float_t eta1, Float_t phi1, Float_t eta2, Float_t phi2) {
Float_t dphi = fabs(phi1-phi2);
if(dphi>M_PI) dphi = 2*M_PI-dphi;
Float_t deta = fabs(eta1-eta2);
return sqrt(dphi*dphi+deta*deta);
}
Double_t NormPhi(Double_t phi) {
if(phi>=M_PI) return phi - 2*M_PI;
else if(phi<-M_PI) return phi + 2*M_PI;
else return phi;
}
Double_t significance(Double_t b0, Double_t s0, Double_t db) {
if(db==0) return sqrt(2*(s0+b0)*log(1+s0/b0)-2*s0);
else {
Double_t tmp = b0-db*db;
Double_t b = 0.5*(tmp+sqrt(pow(tmp,2)+4*db*db*(b0+s0)));
return sqrt(2*(b0+s0)*log((b0+s0)/b)-(b0+s0)+b-(b-b0)*b0/db/db);
}
}
class binning {
public:
Int_t nbin[50];
Float_t xlo[50];
Float_t xhi[50];
std::string titleX[50];
Float_t* var1[50];
Int_t* var2[50];
Bool_t MeVtoGeV[50];
Int_t nvar;
binning();
virtual ~binning();
void add(Int_t nbin_, Float_t xlo_, Float_t xhi_, const char* titleX_, Int_t* var_);
void add(Int_t nbin_, Float_t xlo_, Float_t xhi_, const char* titleX_, Float_t* var_, Bool_t MeVtoGeV_);
Float_t getVal(Int_t i);
};
binning::binning() {
nvar = 0;
for(Int_t i=0; i<50; i++) {
nbin[i] = 1; xlo[i] = 0; xhi[i] = 1; var1[i] = 0; var2[i] = 0; MeVtoGeV[i] = 0;
}
}
binning::~binning() {}
void binning::add(Int_t nbin_, Float_t xlo_, Float_t xhi_, const char* titleX_, Int_t* var_) {
if(nvar>=0 && nvar<50) {
nbin[nvar] = nbin_; xlo[nvar] = xlo_; xhi[nvar] = xhi_;
titleX[nvar] = titleX_; var2[nvar] = var_;
nvar++;
}
}
void binning::add(Int_t nbin_, Float_t xlo_, Float_t xhi_, const char* titleX_, Float_t* var_, Bool_t MeVtoGeV_) {
if(nvar>=0 && nvar<50) {
nbin[nvar] = nbin_; xlo[nvar] = xlo_; xhi[nvar] = xhi_;
titleX[nvar] = titleX_; var1[nvar] = var_; MeVtoGeV[nvar] = MeVtoGeV_;
nvar++;
}
}
Float_t binning::getVal(Int_t i) {
Float_t tmp = -999999;
if(i>=0 && i<nvar) {
if(var1[i]) tmp = MeVtoGeV[i] ? *var1[i]/GeV : *var1[i];
else if(var2[i]) tmp = *var2[i];
}
if(tmp >= xhi[i]) tmp = xhi[i]*0.999999;
if(tmp < xlo[i]) tmp = xlo[i];
return tmp;
}
binning* bn(0);
// new vars:
TLorentzVector v1, v3;
Bool_t isFatJet_v3;
Float_t tau21_v3;
Int_t reg;
Float_t mLL;
Float_t ptLL;
Float_t ptL1;
Float_t ptL2;
Float_t dphiLL;
Float_t mV3;
Float_t pV3;
Float_t ptV3;
Float_t d_eta_jj;
Bool_t hasBjet;
void initialize() {
bn = new binning();
bn->add(100,0,1000,"m_{LL} [GeV]",&mLL,true);
bn->add(50,0,1500,"p_{T,LL} [GeV]",&ptLL,true);
bn->add(50,0,1500,"p_{T,L1} [GeV]",&ptL1,true);
bn->add(50,0,500,"p_{T,L2} [GeV]",&ptL2,true);
bn->add(20,0,acos(-1),"#Delta#phi_{LL}",&dphiLL,false);
//bn->add(50,0,500,"m_{V(jj)} [GeV]",&mV3,true);
bn->add(20,0,250,"m_{V(jj)} [GeV]",&mV3,true);
bn->add(100,0,2000,"m_{LL} [GeV]",&mLL,true);
bn->add(50,0,2500,"p_{T,V(jj)} [GeV]",&ptV3,true);
bn->add(50,0,1500,"MET [GeV]",&MET_et,true);
bn->add(20,0,5,"#Delta#eta_{jj}",&d_eta_jj,true);
}
Float_t figSigSF = 1; //sig
Float_t figMax = 1.2;
Bool_t Pass(Int_t ich) { //cut1 ptL1>300 ,, previous ptL1>200 1,2
// change ptL1>400 to ptL2>450 2
// cut on mLL performed well in reg 1
Bool_t cut1 = mLL/GeV>300 && ptV3/GeV>0 && MET_et/GeV>100 && ptLL/GeV>100 && ptL1/GeV>300 && ptL2/GeV>50 && dphiLL>2.0 && !hasBjet && (reg==1 || reg==2); // without mass window cut
// Bool_t cut1 = mV3/GeV>60 && mV3/GeV<150 && mLL/GeV>300 && ptV3/GeV>0 && MET_et/GeV>100 && ptLL/GeV>100 && ptL1/GeV>300 && ptL2/GeV>50 && dphiLL>2.0 && !hasBjet && (reg==1 || reg==2); // add cut on mLL
Bool_t cut3 = mLL/GeV>400 && ptV3/GeV>0 && MET_et/GeV>100 && ptLL/GeV>100 && ptL1/GeV>450 && ptL2/GeV>50 && dphiLL>1.6 && (reg==3);
return (cut1 || cut3);
// return (cut1);
}
void GetVars(Int_t ich) {
TLorentzVector vec_l1;
TLorentzVector vec_l2;
//// two electrons ???
if(el_n==1 && mu_n==1 && el_charge[0]*mu_charge[0]>0) {
vec_l1.SetPtEtaPhiE(el_pt[0],el_eta[0],el_phi[0],el_E[0]);
vec_l2.SetPtEtaPhiE(mu_pt[0],mu_eta[0],mu_phi[0],mu_E[0]);
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
dphiLL = vec_l1.DeltaR(vec_l2);
}
else if(mu_n==2 && mu_charge[0]*mu_charge[1]>0 && el_n==0) {
vec_l1.SetPtEtaPhiE(mu_pt[0],mu_eta[0],mu_phi[0],mu_E[0]);
vec_l2.SetPtEtaPhiE(mu_pt[1],mu_eta[1],mu_phi[1],mu_E[1]);
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
dphiLL = vec_l1.DeltaR(vec_l2);
}
else if(el_n==2 && el_charge[0]*el_charge[1]>0 && mu_n==0) {
vec_l1.SetPtEtaPhiE(el_pt[0],el_eta[0],el_phi[0],el_E[0]);
vec_l2.SetPtEtaPhiE(el_pt[1],el_eta[1],el_phi[1],el_E[1]);
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
dphiLL = vec_l1.DeltaR(vec_l2);
}
else {
mLL = 0;
ptLL = 0;
dphiLL = 0;
}
ptL1 = ptL2 = 0;
if(vec_l1.Pt()>vec_l2.Pt()) {
ptL1 = vec_l1.Pt(); ptL2 = vec_l2.Pt();
}
else {
ptL1 = vec_l2.Pt(); ptL2 = vec_l1.Pt();
}
v1 = vec_l1+vec_l2;
Int_t ifj1(-1);
Float_t maxPt = -999;
for(Int_t i=0; i<fatjet_n; i++) {
if(fatjet_pt[i]/GeV<50) continue;
if(fatjet_pt[i]>maxPt) {
maxPt = fatjet_pt[i];
ifj1 = i;
}
}
Int_t ij[2] = {-1,-1};
maxPt = -999;
for(Int_t i=0; i<jet_n; i++) {
if(jet_pt[i]/GeV<30) continue;
if(jet_pt[i]>maxPt) {
maxPt = jet_pt[i];
ij[0] = i;
}
}
maxPt = -999;
for(Int_t i=0; i<jet_n; i++) {
if(jet_pt[i]/GeV<30) continue;
if(i==ij[0]) continue;
if(jet_pt[i]>maxPt) {
maxPt = jet_pt[i];
ij[1] = i;
}
}
hasBjet = false;
for(Int_t i=0; i<jet_n; i++) {
if(jet_pt[i]/GeV>30 && fabs(jet_eta[i])<2.5 && jet_isBtagged[i]) {
hasBjet = true;
break;
}
}
isFatJet_v3 = false;
tau21_v3 = -999;
v3.SetXYZT(0,0,0,0);
reg = 0;
if(v1.Pt()>0) {
if(v3.Pt()==0) {
//if(ij[0]>=0 && jet_tau2[ij[0]]/jet_tau1[ij[0]]<0.7) { // zll_wlv_red.root has no tauXX
if(ij[0]>=0) {
TLorentzVector tmp;
tmp.SetPtEtaPhiM(jet_pt[ij[0]],jet_eta[ij[0]],jet_phi[ij[0]],jet_m[ij[0]]); //main
if(tmp.Pt()/GeV>400) {
v3 = tmp;
isFatJet_v3 = false;
reg = 1;
}
}
}
if(v3.Pt()==0) {
if(ifj1>=0 && fatjet_tau2[ifj1]/fatjet_tau1[ifj1]<0.6) {
TLorentzVector tmp;
tmp.SetPtEtaPhiM(fatjet_pt[ifj1],fatjet_eta[ifj1],fatjet_phi[ifj1],fatjet_m[ifj1]);
if(tmp.Pt()/GeV>100) {
v3 = tmp;
isFatJet_v3 = true;
tau21_v3 = fatjet_tau2[ifj1]/fatjet_tau1[ifj1];
reg = 2;
}
}
}
if(v3.Pt()==0) {
if(ij[0]>=0 && ij[1]>=0) {
TLorentzVector tmp1; TLorentzVector tmp2;
tmp1.SetPtEtaPhiM(jet_pt[ij[0]],jet_eta[ij[0]],jet_phi[ij[0]],jet_m[ij[0]]);
tmp2.SetPtEtaPhiM(jet_pt[ij[1]],jet_eta[ij[1]],jet_phi[ij[1]],jet_m[ij[1]]);
TLorentzVector tmp = tmp1+tmp2;
d_eta_jj = fabs(jet_eta[ij[0]]-jet_eta[ij[1]])*1000.;
// if((tmp1+tmp2).Pt()/GeV>250 && d_eta_jj<1.5*1000.) {
if((tmp1+tmp2).Pt()/GeV>0) {
v3 = tmp;
isFatJet_v3 = false;
reg = 3;
}
}
}
}
mV3 = v3.M();
pV3 = v3.P();
ptV3 = v3.Pt();
if(ich==0) mc_event_weight *= lumi*0.1638887/8.19444; // 600
else if(ich==1) mc_event_weight *= lumi*3.134693e02/1.55753e-07; //zll_wlv
else if(ich==2) mc_event_weight *= lumi*0.014e03/24624.98383; //ttV_3lep
else if(ich==3) mc_event_weight *= lumi*0.010286e03/2057.61; //ttV_2l_ss
else if(ich==4) mc_event_weight *= lumi*0.004726e03/467.61446;//zll_wlv_vjj
else if(ich==5) mc_event_weight *= lumi*3.5841227/358.384; //www_2l_ss
}
void plot() {
char str[200];
initialize();
TChain* ch[6] = {0,0,0,0,0,0};
ch[0] = new TChain("tau");
ch[0]->Add("../../../rootfiles/ntupleForWWW/sig_2lepWW_red_001.root"); // 1000๏ผ1000
// ch[0]->Add("../../../rootfiles/rhoH_005/ntuple_www/S2_red_265.root");// 700๏ผ700
Init(ch[0]);
ch[1] = new TChain("tau");
ch[1]->Add("../../../rootfiles/ntuple_merged/zll_wlv_red.root"); // no filter
Init(ch[1]);
ch[2] = new TChain("tau");
ch[2]->Add("../../../rootfiles/ntuple_merged2/ttV_3lep_red.root");
Init(ch[2]);
ch[3] = new TChain("tau");
ch[3]->Add("../../../rootfiles/ntuple_merged2/ttV_2l_ss_red.root");
Init(ch[3]);
ch[4] = new TChain("tau");
ch[4]->Add("../../../rootfiles/ntuple_merged2/zll_wlv_vjj_red.root");
Init(ch[4]);
ch[5] = new TChain("tau");
ch[5]->Add("../../../rootfiles/ntuple_merged2/www_2l_ss_red.root");
Init(ch[5]);
// sig,bkg
TH1F* h1[50]; TH1F* h2[50]; TH1F* h3[50]; TH1F* h4[50];
for(Int_t i=0; i<bn->nvar; i++) {
sprintf(str,"h1_var%d",i+1);
h1[i] = new TH1F(str,"",bn->nbin[i],bn->xlo[i],bn->xhi[i]);
sprintf(str,"h2_var%d",i+1);
h2[i] = new TH1F(str,"",bn->nbin[i],bn->xlo[i],bn->xhi[i]);
sprintf(str,"h3_var%d",i+1);
h3[i] = new TH1F(str,"",bn->nbin[i],bn->xlo[i],bn->xhi[i]);
sprintf(str,"h4_var%d",i+1);
h4[i] = new TH1F(str,"",bn->nbin[i],bn->xlo[i],bn->xhi[i]);
}
TH1F* hh1 = new TH1F("hh1","",20,0,1);
TH1F* hh2 = new TH1F("hh2","",20,0,1);
TH1F* hsig = new TH1F("sig","",40,0,2000);
TH1F* hbkg1 = new TH1F("hbkg1","",40,0,2000);
TH1F* hbkg2 = new TH1F("hbkg2","",40,0,2000);
TH1F* hbkg3 = new TH1F("hbkg3","",40,0,2000);
Double_t n_eve[6][5] = {
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0}
};
for(Int_t ich=0; ich<6; ich++) {
if(!ch[ich]) continue;
Int_t numberOfEntries = (Int_t)ch[ich]->GetEntries();
// Loop over all events
printf(" %d entries to be processed\n",numberOfEntries);
for(Int_t entry = 0; entry < numberOfEntries; entry++) {
// Load selected branches with data from specified event
ch[ich]->GetEntry(entry);
if((entry+1)%10000000==0) printf(" %d entries processed\n",entry+1);
calibrate_jet();
calibrate_fatjet();
GetVars(ich);
Double_t wt = mc_event_weight;
n_eve[ich][0] += wt;
if(Pass(ich)) {
n_eve[ich][1] += wt;
if(ich==0) hsig->Fill(mV3/GeV,wt);
else if(ich==1) hbkg1->Fill(mV3/GeV,wt);
else if(ich==2||ich==3) hbkg1->Fill(mV3/GeV,wt);
else if(ich==4||ich==5) hbkg2->Fill(mV3/GeV,wt);
for(Int_t i=0; i<bn->nvar; i++) {
if(ich==0) h1[i]->Fill(bn->getVal(i),wt);
else if(ich==1) h2[i]->Fill(bn->getVal(i),wt);
else if(ich==4||ich==5||ich==2||ich==3) h3[i]->Fill(bn->getVal(i),wt);
// else if(ich==4||ich==5) h4[i]->Fill(bn->getVal(i),wt);
}
if(ich==0) {
if(isFatJet_v3) hh1->Fill(tau21_v3,wt);
if(isFatJet_v3) n_eve[0][2] += wt;
}
else {
if(isFatJet_v3) hh2->Fill(tau21_v3,wt);
if(isFatJet_v3) n_eve[1][2] += wt;
}
}
}
}
printf("Sig: %.5f %.3f\n",n_eve[0][0],n_eve[0][1]);
printf("Bkg1: %.5f %.3f\n",n_eve[1][0],n_eve[1][1]);
printf("Bkg2: %.5f %.3f\n",n_eve[2][0],n_eve[2][1]);
printf("Bkg3: %.5f %.3f\n",n_eve[3][0],n_eve[3][1]);
printf("Bkg4: %.5f %.3f\n",n_eve[4][0],n_eve[4][1]);
printf("Bkg4: %.5f %.3f\n",n_eve[5][0],n_eve[5][1]);
printf("HasFatJet: %.1f(sig) %.1f(bkg)\n",n_eve[0][2],n_eve[1][2]);
printf("significance: %0.3f\n", significance(n_eve[1][1]+n_eve[2][1]+n_eve[3][1]+n_eve[4][1]+n_eve[5][1], n_eve[0][1], 0) );
gStyle->SetLegendFont(62);
TLegend* lg = new TLegend(0.6,0.65,0.88,0.87,"");
if(figSigSF==1) sprintf(str,"Signal");
else sprintf(str,"Sig.#times%.1f",figSigSF);
lg->AddEntry(h1[0],"Signal","F");
lg->AddEntry(h2[0],"WZ+jets","F");
lg->AddEntry(h3[0],"Other","F");
// lg->AddEntry(h3[0],"t#bar{t}V","F");
// lg->AddEntry(h4[0],"VVV","F");
lg->SetBorderSize(0);
lg->SetMargin(0.25);
lg->SetFillColor(kWhite);
TCanvas* c01 = new TCanvas("c01","c01",600,600);
hh1->SetLineColor(kRed);
hh2->SetLineColor(kBlue);
hh1->SetMarkerColor(kRed);
hh2->SetMarkerColor(kBlue);
hh1->SetMarkerSize(0.8);
hh2->SetMarkerSize(0.8);
hh1->Scale(hh2->Integral()/hh1->Integral());
SetMax(hh1,hh2,1.1);
hh1->Draw();
hh2->Draw("same");
//////////////////////////////////////////////
TStyle *atlasStyle= new TStyle("ATLAS","Atlas style");
// use plain black on white colors
Int_t icol=0;
atlasStyle->SetFrameBorderMode(icol);
atlasStyle->SetCanvasBorderMode(icol);
atlasStyle->SetPadBorderMode(icol);
atlasStyle->SetPadColor(icol);
atlasStyle->SetCanvasColor(icol);
atlasStyle->SetStatColor(icol);
//atlasStyle->SetFillColor(icol);
// set the paper & margin sizes
atlasStyle->SetPaperSize(20,26);
atlasStyle->SetPadTopMargin(0.07);
atlasStyle->SetPadRightMargin(0.07);
atlasStyle->SetPadBottomMargin(0.13);
atlasStyle->SetPadLeftMargin(0.13);
// use large fonts
//Int_t font=72;
Int_t font=42;
Double_t tsize=0.05;
atlasStyle->SetTextFont(font);
atlasStyle->SetTextSize(tsize);
atlasStyle->SetLabelFont(font,"x");
atlasStyle->SetTitleFont(font,"x");
atlasStyle->SetLabelFont(font,"y");
atlasStyle->SetTitleFont(font,"y");
atlasStyle->SetLabelFont(font,"z");
atlasStyle->SetTitleFont(font,"z");
atlasStyle->SetLabelSize(tsize,"x");
atlasStyle->SetTitleSize(tsize,"x");
atlasStyle->SetLabelSize(tsize,"y");
atlasStyle->SetTitleSize(tsize,"y");
atlasStyle->SetLabelSize(tsize,"z");
atlasStyle->SetTitleSize(tsize,"z");
// Xin:
atlasStyle->SetTitleOffset(1.1,"X");
atlasStyle->SetTitleOffset(1.2,"Y");
//use bold lines and markers
atlasStyle->SetMarkerStyle(20);
atlasStyle->SetMarkerSize(1.2);
atlasStyle->SetHistLineWidth(2.);
atlasStyle->SetLineStyleString(2,"[12 12]"); // postscript dashes
//get rid of X error bars and y error bar caps
//atlasStyle->SetErrorX(0.001);
//do not display any of the standard histogram decorations
atlasStyle->SetOptTitle(0);
//atlasStyle->SetOptStat(1111);
atlasStyle->SetOptStat(0);
//atlasStyle->SetOptFit(1111);
atlasStyle->SetOptFit(0);
// put tick marks on top and RHS of plots
atlasStyle->SetPadTickX(1);
atlasStyle->SetPadTickY(1);
//gROOT->SetStyle("Plain");
gROOT->SetStyle("ATLAS");
gROOT->ForceStyle();
//////////////////////////////////////////////
THStack* hsk[50];
TCanvas* cv[50];
for(Int_t i=0; i<bn->nvar; i++) {
h1[i]->Scale(figSigSF);
h1[i]->SetLineColor(kRed);
h1[i]->SetFillColor(kRed);
h2[i]->SetLineColor(kBlue);
h2[i]->SetFillColor(kBlue);
h3[i]->SetLineColor(kGreen-3);
h3[i]->SetFillColor(kGreen-3);
// h4[i]->SetLineColor(kBlue-5);
// h4[i]->SetFillColor(kBlue-5);
sprintf(str,"hsk_var%d",i+1);
hsk[i] = new THStack(str,"");
if(bn->titleX[i]=="m_{V(jj)} [GeV]" || bn->titleX[i]=="#Delta#phi_{LL}") {
hsk[i]->Add(h4[i]);
hsk[i]->Add(h3[i]);
hsk[i]->Add(h2[i]);
hsk[i]->Add(h1[i]);
}
else {
hsk[i]->Add(h1[i]);
hsk[i]->Add(h4[i]);
hsk[i]->Add(h3[i]);
hsk[i]->Add(h2[i]);
}
sprintf(str,"c%d",i+1);
cv[i] = new TCanvas(str,str,912,600);
hsk[i]->Draw("hist");
hsk[i]->GetXaxis()->SetTitle(bn->titleX[i].c_str());
sprintf(str,"Events/( %4.2f )",h1[i]->GetBinWidth(1));
hsk[i]->GetYaxis()->SetTitle(str);
lg->Draw("same");
// sprintf(str,"c%d.eps",i+1);
// cv[i]->SaveAs(str);
}
}
<file_sep>/LHC_HH_2lep/rw_me/Source/MODEL/coupl_write.inc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c written by the UFO converter
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
WRITE(*,*) ' Couplings of SMwithHeavyScalarDim4Dim6_NoDecay_UFO'
WRITE(*,*) ' ---------------------------------'
WRITE(*,*) ' '
WRITE(*,2) 'GC_13 = ', GC_13
WRITE(*,2) 'GC_14 = ', GC_14
WRITE(*,2) 'GC_15 = ', GC_15
WRITE(*,2) 'GC_16 = ', GC_16
WRITE(*,2) 'GC_17 = ', GC_17
WRITE(*,2) 'GC_18 = ', GC_18
WRITE(*,2) 'GC_33 = ', GC_33
WRITE(*,2) 'GC_34 = ', GC_34
WRITE(*,2) 'GC_35 = ', GC_35
WRITE(*,2) 'GC_36 = ', GC_36
WRITE(*,2) 'GC_37 = ', GC_37
WRITE(*,2) 'GC_38 = ', GC_38
WRITE(*,2) 'GC_45 = ', GC_45
WRITE(*,2) 'GC_46 = ', GC_46
WRITE(*,2) 'GC_77 = ', GC_77
WRITE(*,2) 'GC_78 = ', GC_78
WRITE(*,2) 'GC_79 = ', GC_79
WRITE(*,2) 'GC_80 = ', GC_80
<file_sep>/TimingMeasurement/A/Source/nexternal.inc
../SubProcesses/P1_bbx_zx0_z_bbx_x0_tamtapbbx/nexternal.inc<file_sep>/TimingMeasurement/A/Source/leshouche.inc
../SubProcesses/P1_bbx_zx0_z_bbx_x0_tamtapbbx/leshouche.inc<file_sep>/PROCNLO_HC_NLO_X0_UFO_0_1/SubProcesses/P0_uux_zx0_zepemz_no_a/coloramps.inc
LOGICAL ICOLAMP(1,3,1)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
<file_sep>/Processes/exclusion/fit_com_1.cc
#include "TFile.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TCanvas.h"
#include "TMath.h"
#include "TH1F.h"
#include "TCanvas.h"
#include "TLine.h"
#include "TRandom1.h"
#include "TLegend.h"
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <vector>
#include <sstream> //istringstream
#include "../Elizabeth.h"
using namespace std;
Double_t f(Double_t x, Double_t* s, Double_t* b, Double_t* n) {
return n[0]*s[0]/(s[0]*x+b[0]) + n[1]*s[1]/(s[1]*x+b[1]) + n[2]*s[2]/(s[2]*x+b[2]) - (s[0]+s[1]+s[2]);
}
Double_t fprime(Double_t x, Double_t* s, Double_t* b, Double_t* n) {
return -n[0]*pow(s[0]/(s[0]*x+b[0]),2)-n[1]*pow(s[1]/(s[1]*x+b[1]),2)-n[2]*pow(s[2]/(s[2]*x+b[2]),2);
}
// get the solution using Newton's method
Double_t getMuBest(Double_t* s, Double_t* b, Double_t* n) {
Double_t lo = TMath::Min(-b[0]/s[0],-b[1]/s[1]);
lo = TMath::Min(lo,-b[2]/s[2])+1e-4;
Double_t x1 = 1;
Double_t x2 = 0;
while(fabs(x2-x1)>1e-4) {
x1 = x2;
x2 = x1 - f(x1,s,b,n)/fprime(x1,s,b,n);
//if(x2<lo) printf("Error: solution out of range in Newton's iteration\n");
}
return x2;
}
Double_t getSigmaExcl(Double_t* s, Double_t* b, Double_t* n) {
Double_t mu_best = getMuBest(s,b,n);
Double_t lnL_best = n[0]*log(s[0]*mu_best+b[0])-(s[0]*mu_best+b[0]) +
n[1]*log(s[1]*mu_best+b[1])-(s[1]*mu_best+b[1]) +
n[2]*log(s[2]*mu_best+b[2])-(s[2]*mu_best+b[2]);
Double_t lnL_1 = n[0]*log(s[0]+b[0])-(s[0]+b[0]) +
n[1]*log(s[1]+b[1])-(s[1]+b[1]) +
n[2]*log(s[2]+b[2])-(s[2]+b[2]);
return sqrt(2*(lnL_best-lnL_1))*(mu_best>1. ? -1. : 1.);
}
void Fill(TH1F* h, Double_t x) {
Double_t tmp = x;
if(x<h->GetXaxis()->GetXmin()) tmp = h->GetXaxis()->GetXmin();
if(x>=h->GetXaxis()->GetXmax()) tmp = h->GetXaxis()->GetXmax()*0.999999;
h->Fill(tmp);
}
string to_string(int val) {
char buf[200];
sprintf(buf, "%d", val);
return string(buf);
}
void plot() {
ofstream fout("alpha_1.txt");
fout<<"file"<<" "<<""<<"mass"<<" "<<"fw"<<" "<<"fww"<<" "<<"alpha"<<" "<<"sigma1"<<" "<<"sigma2"<<endl;
ifstream fr("../../../param_2lep600.txt");
if(!fr.is_open()){
cout<<"unable to open file"<<endl;
}
vector<string> vec;
Double_t cs;
Double_t fw;
Double_t fww;
Double_t mass;
Int_t num;
Int_t i=0;
while(!fr.eof()) //while ๅพช็ฏ
{
string temp;
getline(fr, temp, '\n');
vec.push_back(temp);
i ++;
}
int Row=0; //่ก
// //for(auto it=vec.begin(); it != vec.end(); it++)
for(std::vector<string>::iterator it=vec.begin(); it != vec.end(); it++)
{
// cout << *it << endl;
istringstream is(*it);
string s;
Row++;
num=0;
int column=0; //ๅ
//if( (Row>1 && Row<46) ){
if( (Row>1 && Row<212) ){
while(is>>s)
{
if(column == 0 )
{
num=atof(s.c_str());
}
if(column == 1 )
{
mass=atof(s.c_str());
}
if(column == 2 )
{
fw=atof(s.c_str());
}
if(column == 3 )
{
fww=atof(s.c_str());
}
if(column == 4 )
{
cs=atof(s.c_str());
}
column++;
}
string s_fw = to_string(int(fabs(fw)));
string s_fww = to_string(int(fabs(fww)));
string in_fw = "";
string in_fww = "";
if(fw<0.) in_fw = "m";
if(fww<0.) in_fww = "m";
TString hist_sig_name = "hsig_fw_"+in_fw+s_fw+"_fww_"+in_fww+s_fww;
cout<<"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<:"<<hist_sig_name<<endl;
char str[200];
TFile *file_2_bkg = TFile::Open("../../ntuple/mHH_600_hist_bkg_2lep.root");
if (!file_2_bkg) return;
TFile *file_2_sig = TFile::Open("../../ntuple/mHH_600_sig_2lep_005.root");//30,40,50,60,70
if (!file_2_sig) return;
TH1F* hsig_1 = (TH1F*) file_2_sig->Get(hist_sig_name);
TH1F* hbkg_1 = (TH1F*) file_2_bkg->Get("hbkg1");
hsig_1->SetName("hsig_1");
hbkg_1->SetName("hbkg_1");
hsig_1->Scale(140./300.);
hbkg_1->Scale(140./300.);
hsig_1->SetDirectory(0);
hbkg_1->SetDirectory(0);
Double_t nsig_exp_1 = hsig_1->Integral();
Double_t nbkg_exp_1 = hbkg_1->Integral();
TFile *file_3_bkg = TFile::Open("../../ntuple/mHH_600_hist_bkg_3lep.root");
if (!file_3_bkg) return;
TFile *file_3_sig = TFile::Open("../../ntuple/mHH_600_sig_3lep_005.root");//30,40,50,60
if (!file_3_sig) return;
TH1F* hsig_2 = (TH1F*) file_3_sig->Get(hist_sig_name);
TH1F* hbkg_2 = (TH1F*) file_3_bkg->Get("hbkg1");
TH1F* hbkg2_2 = (TH1F*) file_3_bkg->Get("hbkg2");
hsig_2->SetName("hsig_2");
hbkg_2->SetName("hbkg_2");
hbkg2_2->SetName("hbkg2_2");
hsig_2->Scale(140./300.);
hbkg_2->Scale(140./300.);
hbkg2_2->Scale(140./300.);
hsig_2->SetDirectory(0);
hbkg_2->SetDirectory(0);
hbkg2_2->SetDirectory(0);
hbkg_2->Add(hbkg2_2);
Double_t nsig_exp_2 = hsig_2->Integral();
Double_t nbkg_exp_2 = hbkg_2->Integral();
////////////////////////// www ////////////
TFile *file_4_bkg = TFile::Open("../../ntuple/mHH_600_hist_bkg_www.root");
if (!file_4_bkg) return;
TFile *file_4_sig = TFile::Open("../../ntuple/mHH_600_sig_www_005.root");//30,40,50,60
if (!file_4_sig) return;
TH1F* hsig_3 = (TH1F*) file_4_sig->Get(hist_sig_name);
TH1F* hbkg_3 = (TH1F*) file_4_bkg->Get("hbkg1");
TH1F* hbkg2_3 = (TH1F*) file_4_bkg->Get("hbkg2");
TH1F* hbkg3_3 = (TH1F*) file_4_bkg->Get("hbkg3");
hsig_3->SetName("hsig_3");
hbkg_3->SetName("hbkg_3");
hbkg2_3->SetName("hbkg2_3");
hbkg3_3->SetName("hbkg3_3");
hsig_3->Scale(140./300.);
hbkg_3->Scale(140./300.);
hbkg2_3->Scale(140./300.);
hbkg3_3->Scale(140./300.);
hsig_3->SetDirectory(0);
hbkg_3->SetDirectory(0);
hbkg2_3->SetDirectory(0);
hbkg3_3->SetDirectory(0);
hbkg_3->Add(hbkg2_3);
hbkg_3->Add(hbkg3_3);
Double_t nsig_exp_3 = hsig_3->Integral();
Double_t nbkg_exp_3 = hbkg_3->Integral();
//////////////////////////////////////////
Double_t s[3] = {nsig_exp_1, nsig_exp_2, nsig_exp_3};
Double_t b[3] = {nbkg_exp_1, nbkg_exp_2, nbkg_exp_3};
Double_t n[3];
TH1F* h1 = new TH1F("h1","",1000,-3,5); // b-only
TH1F* h2 = new TH1F("h2","",1000,-3,5); // s+b
TRandom1 rdm;
for(Int_t i=0; i<10000; i++) {
n[0] = rdm.Poisson(b[0]);
n[1] = rdm.Poisson(b[1]);
n[2] = rdm.Poisson(b[2]);
Fill(h1,getSigmaExcl(s,b,n));
}
for(Int_t i=0; i<10000; i++) {
n[0] = rdm.Poisson(b[0]+s[0]);
n[1] = rdm.Poisson(b[1]+s[1]);
n[2] = rdm.Poisson(b[2]+s[2]);
Fill(h2,getSigmaExcl(s,b,n));
}
h2->SetLineColor(kBlue);
TLegend* lg = new TLegend(0.77,0.74,0.90,0.89,"");
lg->AddEntry(h1,"B-only","L");
lg->AddEntry(h2,"S+B","L");
lg->SetBorderSize(0);
lg->SetMargin(0.25);
lg->SetFillColor(kWhite);
TCanvas* c1 = new TCanvas("c1","c1",1000,500);
h1->Draw("hist");
h2->Draw("hist same");
lg->Draw("same");
// Double_t F[1] = {0.5};
// // Double_t q[1];
// // h1->GetQuantiles(1,q,F);
Int_t iqS1=0;
Int_t iqS2=0;
Int_t iq=0;
Double_t minS1 = 999;
Double_t minS2 = 999;
Double_t min = 999;
Double_t ptmp = SUSYStat_Pval(1);
Double_t xq[3] = {ptmp,0.5,1-ptmp};
for(Int_t i=1; i<h1->GetNbinsX(); i++) {
if(fabs(h1->Integral(1,i)/h1->Integral()-xq[0])<minS1) {
minS1 = fabs(h1->Integral(1,i)/h1->Integral()-xq[0]);
iqS1 = i;
}
}
for(Int_t i=1; i<h1->GetNbinsX(); i++) {
if(fabs(h1->Integral(1,i)/h1->Integral()-xq[2])<minS2) {
minS2 = fabs(h1->Integral(1,i)/h1->Integral()-xq[2]);
iqS2 = i;
}
}
for(Int_t i=1; i<h1->GetNbinsX(); i++) {
if(fabs(h1->Integral(1,i)/h1->Integral()-0.5)<min) {
min = fabs(h1->Integral(1,i)/h1->Integral()-0.5);
iq = i;
}
}
Double_t q[3] = {h1->GetBinCenter(iqS1),h1->GetBinCenter(iq),h1->GetBinCenter(iqS2)};
printf("q = %f\n",q[1]);
TLine* line2lo = new TLine(q[0],0,q[0],h2->GetMaximum());
line2lo->SetLineWidth(1);
line2lo->SetLineColor(kRed);
line2lo->SetLineStyle(2);
line2lo->Draw();
TLine* line2 = new TLine(q[1],0,q[1],h2->GetMaximum());
line2->SetLineWidth(2);
line2->SetLineColor(kRed);
line2->Draw();
TLine* line2hi = new TLine(q[2],0,q[2],h2->GetMaximum());
line2hi->SetLineWidth(1);
line2hi->SetLineColor(kRed);
line2hi->SetLineStyle(2);
line2hi->Draw();
printf("Excl. CL = %%%.1f\n",h2->Integral(1,h2->FindBin(q[1]))/h2->Integral()*100);
Double_t alpha = 1.-h2->Integral(1,h2->FindBin(q[1]))/h2->Integral();
Double_t sigma1 = 1.-h2->Integral(1,h2->FindBin(q[0]))/h2->Integral();
Double_t sigma2 = 1.-h2->Integral(1,h2->FindBin(q[2]))/h2->Integral();
fout<<num<<" "<<mass<<" "<<fw<<" "<<fww<<" "<<alpha<<" "<<sigma1<<" "<<sigma2<<endl;
c1->SaveAs(hist_sig_name+"_h12.eps");
}
}
}
<file_sep>/TimingMeasurement/D/Source/leshouche.inc
../SubProcesses/P3_qq_wmwmwp_wm_tamvl_wm_tamvl_wp_qq/leshouche.inc<file_sep>/TimingMeasurement/D/Source/maxamps.inc
../SubProcesses/P3_qq_wmwmwp_wm_tamvl_wm_tamvl_wp_qq/maxamps.inc<file_sep>/fit_code/FitOneBin/submit_1.sh
root -l -b -q out1.cc
<file_sep>/TimingMeasurement/D/SubProcesses/P3_qq_wmwmwp_wm_lvl_wm_lvl_wp_qq/coloramps.inc
LOGICAL ICOLAMP(1,2,32)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,32),I=1,1)/.TRUE./
<file_sep>/LHC_HH_2lep_rw/Source/leshouche.inc
../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/leshouche.inc<file_sep>/LHC_HH_2lep/Source/maxamps.inc
../SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/maxamps.inc<file_sep>/LHC_HH_2lep/Source/MODEL/coupl.inc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c written by the UFO converter
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
DOUBLE PRECISION G
COMMON/STRONG/ G
DOUBLE COMPLEX GAL(2)
COMMON/WEAK/ GAL
DOUBLE PRECISION MU_R
COMMON/RSCALE/ MU_R
DOUBLE PRECISION NF
PARAMETER(NF=4)
DOUBLE PRECISION MDL_MT,MDL_MW,MDL_MZ,MDL_MTA,MDL_MHH,MDL_MB
$ ,MDL_MH
COMMON/MASSES/ MDL_MT,MDL_MW,MDL_MZ,MDL_MTA,MDL_MHH,MDL_MB,MDL_MH
DOUBLE PRECISION MDL_WHH,MDL_WZ,MDL_WH,MDL_WW,MDL_WT
COMMON/WIDTHS/ MDL_WHH,MDL_WZ,MDL_WH,MDL_WW,MDL_WT
DOUBLE COMPLEX GC_13, GC_14, GC_15, GC_16, GC_17, GC_18, GC_33,
$ GC_34, GC_35, GC_36, GC_37, GC_38, GC_45, GC_46, GC_77, GC_78,
$ GC_79, GC_80
COMMON/COUPLINGS/ GC_13, GC_14, GC_15, GC_16, GC_17, GC_18,
$ GC_33, GC_34, GC_35, GC_36, GC_37, GC_38, GC_45, GC_46, GC_77,
$ GC_78, GC_79, GC_80
<file_sep>/PROCNLO_HC_NLO_X0_UFO_0/Source/MODEL/param_write.inc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c written by the UFO converter
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
WRITE(*,*) ' External Params'
WRITE(*,*) ' ---------------------------------'
WRITE(*,*) ' '
WRITE(*,*) 'MU_R = ', MU_R
WRITE(*,*) 'aEWM1 = ', AEWM1
WRITE(*,*) 'mdl_Gf = ', MDL_GF
WRITE(*,*) 'aS = ', AS
WRITE(*,*) 'mdl_ymb = ', MDL_YMB
WRITE(*,*) 'mdl_ymt = ', MDL_YMT
WRITE(*,*) 'mdl_ymtau = ', MDL_YMTAU
WRITE(*,*) 'mdl_MT = ', MDL_MT
WRITE(*,*) 'mdl_MB = ', MDL_MB
WRITE(*,*) 'mdl_MZ = ', MDL_MZ
WRITE(*,*) 'mdl_MTA = ', MDL_MTA
WRITE(*,*) 'mdl_WT = ', MDL_WT
WRITE(*,*) 'mdl_WZ = ', MDL_WZ
WRITE(*,*) 'mdl_WW = ', MDL_WW
WRITE(*,*) 'mdl_MX0 = ', MDL_MX0
WRITE(*,*) 'mdl_WX0 = ', MDL_WX0
WRITE(*,*) 'mdl_Lambda = ', MDL_LAMBDA
WRITE(*,*) 'mdl_cosa = ', MDL_COSA
WRITE(*,*) 'mdl_kSM = ', MDL_KSM
WRITE(*,*) 'mdl_kHtt = ', MDL_KHTT
WRITE(*,*) 'mdl_kAtt = ', MDL_KATT
WRITE(*,*) 'mdl_kHbb = ', MDL_KHBB
WRITE(*,*) 'mdl_kAbb = ', MDL_KABB
WRITE(*,*) 'mdl_kHll = ', MDL_KHLL
WRITE(*,*) 'mdl_kAll = ', MDL_KALL
WRITE(*,*) 'mdl_kHaa = ', MDL_KHAA
WRITE(*,*) 'mdl_kAaa = ', MDL_KAAA
WRITE(*,*) 'mdl_kHza = ', MDL_KHZA
WRITE(*,*) 'mdl_kAza = ', MDL_KAZA
WRITE(*,*) 'mdl_kHzz = ', MDL_KHZZ
WRITE(*,*) 'mdl_kAzz = ', MDL_KAZZ
WRITE(*,*) 'mdl_kHww = ', MDL_KHWW
WRITE(*,*) 'mdl_kAww = ', MDL_KAWW
WRITE(*,*) 'mdl_kHda = ', MDL_KHDA
WRITE(*,*) 'mdl_kHdz = ', MDL_KHDZ
WRITE(*,*) 'mdl_kHdwR = ', MDL_KHDWR
WRITE(*,*) 'mdl_kHdwI = ', MDL_KHDWI
WRITE(*,*) ' Internal Params'
WRITE(*,*) ' ---------------------------------'
WRITE(*,*) ' '
WRITE(*,*) 'mdl_CKM11 = ', MDL_CKM11
WRITE(*,*) 'mdl_conjg__CKM3x3 = ', MDL_CONJG__CKM3X3
WRITE(*,*) 'mdl_conjg__CKM11 = ', MDL_CONJG__CKM11
WRITE(*,*) 'mdl_lhv = ', MDL_LHV
WRITE(*,*) 'mdl_CKM3x3 = ', MDL_CKM3X3
WRITE(*,*) 'mdl_conjg__CKM33 = ', MDL_CONJG__CKM33
WRITE(*,*) 'mdl_Ncol = ', MDL_NCOL
WRITE(*,*) 'mdl_CA = ', MDL_CA
WRITE(*,*) 'mdl_TF = ', MDL_TF
WRITE(*,*) 'mdl_CF = ', MDL_CF
WRITE(*,*) 'mdl_complexi = ', MDL_COMPLEXI
WRITE(*,*) 'mdl_MZ__exp__2 = ', MDL_MZ__EXP__2
WRITE(*,*) 'mdl_MZ__exp__4 = ', MDL_MZ__EXP__4
WRITE(*,*) 'mdl_sqrt__2 = ', MDL_SQRT__2
WRITE(*,*) 'mdl_MX0__exp__2 = ', MDL_MX0__EXP__2
WRITE(*,*) 'mdl_cosa__exp__2 = ', MDL_COSA__EXP__2
WRITE(*,*) 'mdl_sina = ', MDL_SINA
WRITE(*,*) 'mdl_kHdw = ', MDL_KHDW
WRITE(*,*) 'mdl_nb__2__exp__0_75 = ', MDL_NB__2__EXP__0_75
WRITE(*,*) 'mdl_Ncol__exp__2 = ', MDL_NCOL__EXP__2
WRITE(*,*) 'mdl_MB__exp__2 = ', MDL_MB__EXP__2
WRITE(*,*) 'mdl_MT__exp__2 = ', MDL_MT__EXP__2
WRITE(*,*) 'mdl_conjg__kHdw = ', MDL_CONJG__KHDW
WRITE(*,*) 'mdl_aEW = ', MDL_AEW
WRITE(*,*) 'mdl_MW = ', MDL_MW
WRITE(*,*) 'mdl_sqrt__aEW = ', MDL_SQRT__AEW
WRITE(*,*) 'mdl_ee = ', MDL_EE
WRITE(*,*) 'mdl_MW__exp__2 = ', MDL_MW__EXP__2
WRITE(*,*) 'mdl_sw2 = ', MDL_SW2
WRITE(*,*) 'mdl_cw = ', MDL_CW
WRITE(*,*) 'mdl_sqrt__sw2 = ', MDL_SQRT__SW2
WRITE(*,*) 'mdl_sw = ', MDL_SW
WRITE(*,*) 'mdl_g1 = ', MDL_G1
WRITE(*,*) 'mdl_gw = ', MDL_GW
WRITE(*,*) 'mdl_vev = ', MDL_VEV
WRITE(*,*) 'mdl_vev__exp__2 = ', MDL_VEV__EXP__2
WRITE(*,*) 'mdl_lam = ', MDL_LAM
WRITE(*,*) 'mdl_yb = ', MDL_YB
WRITE(*,*) 'mdl_yt = ', MDL_YT
WRITE(*,*) 'mdl_ytau = ', MDL_YTAU
WRITE(*,*) 'mdl_muH = ', MDL_MUH
WRITE(*,*) 'mdl_AxialZUp = ', MDL_AXIALZUP
WRITE(*,*) 'mdl_AxialZDown = ', MDL_AXIALZDOWN
WRITE(*,*) 'mdl_VectorZUp = ', MDL_VECTORZUP
WRITE(*,*) 'mdl_VectorZDown = ', MDL_VECTORZDOWN
WRITE(*,*) 'mdl_VectorAUp = ', MDL_VECTORAUP
WRITE(*,*) 'mdl_VectorADown = ', MDL_VECTORADOWN
WRITE(*,*) 'mdl_VectorWmDxU = ', MDL_VECTORWMDXU
WRITE(*,*) 'mdl_AxialWmDxU = ', MDL_AXIALWMDXU
WRITE(*,*) 'mdl_VectorWpUxD = ', MDL_VECTORWPUXD
WRITE(*,*) 'mdl_AxialWpUxD = ', MDL_AXIALWPUXD
WRITE(*,*) 'mdl_I1x33 = ', MDL_I1X33
WRITE(*,*) 'mdl_I2x33 = ', MDL_I2X33
WRITE(*,*) 'mdl_I3x33 = ', MDL_I3X33
WRITE(*,*) 'mdl_I4x33 = ', MDL_I4X33
WRITE(*,*) 'mdl_Vector_tbGp = ', MDL_VECTOR_TBGP
WRITE(*,*) 'mdl_Axial_tbGp = ', MDL_AXIAL_TBGP
WRITE(*,*) 'mdl_Vector_tbGm = ', MDL_VECTOR_TBGM
WRITE(*,*) 'mdl_Axial_tbGm = ', MDL_AXIAL_TBGM
WRITE(*,*) 'mdl_ee__exp__2 = ', MDL_EE__EXP__2
WRITE(*,*) 'mdl_gAaa = ', MDL_GAAA
WRITE(*,*) 'mdl_cw__exp__2 = ', MDL_CW__EXP__2
WRITE(*,*) 'mdl_gAza = ', MDL_GAZA
WRITE(*,*) 'mdl_gHaa = ', MDL_GHAA
WRITE(*,*) 'mdl_gHza = ', MDL_GHZA
WRITE(*,*) 'mdl_gw__exp__2 = ', MDL_GW__EXP__2
WRITE(*,*) 'mdl_sw__exp__2 = ', MDL_SW__EXP__2
WRITE(*,*) ' Internal Params evaluated point by point'
WRITE(*,*) ' ----------------------------------------'
WRITE(*,*) ' '
WRITE(*,*) 'mdl_sqrt__aS = ', MDL_SQRT__AS
WRITE(*,*) 'mdl_G__exp__2 = ', MDL_G__EXP__2
WRITE(*,*) 'mdl_G__exp__4 = ', MDL_G__EXP__4
WRITE(*,*) 'mdl_R2MixedFactor_FIN_ = ', MDL_R2MIXEDFACTOR_FIN_
WRITE(*,*) 'mdl_GWcft_UV_b_1EPS_ = ', MDL_GWCFT_UV_B_1EPS_
WRITE(*,*) 'mdl_GWcft_UV_t_1EPS_ = ', MDL_GWCFT_UV_T_1EPS_
WRITE(*,*) 'mdl_bWcft_UV_1EPS_ = ', MDL_BWCFT_UV_1EPS_
WRITE(*,*) 'mdl_tWcft_UV_1EPS_ = ', MDL_TWCFT_UV_1EPS_
WRITE(*,*) 'mdl_G__exp__3 = ', MDL_G__EXP__3
WRITE(*,*) 'mdl_MU_R__exp__2 = ', MDL_MU_R__EXP__2
WRITE(*,*) 'mdl_GWcft_UV_b_FIN_ = ', MDL_GWCFT_UV_B_FIN_
WRITE(*,*) 'mdl_GWcft_UV_t_FIN_ = ', MDL_GWCFT_UV_T_FIN_
WRITE(*,*) 'mdl_bWcft_UV_FIN_ = ', MDL_BWCFT_UV_FIN_
WRITE(*,*) 'mdl_tWcft_UV_FIN_ = ', MDL_TWCFT_UV_FIN_
WRITE(*,*) 'mdl_gAgg = ', MDL_GAGG
WRITE(*,*) 'mdl_gHgg = ', MDL_GHGG
<file_sep>/TimingMeasurement/C/SubProcesses/P2_qq_wpx0_wp_lvl_x0_llqq/coloramps.inc
LOGICAL ICOLAMP(1,4,16)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,16),I=1,1)/.TRUE./
<file_sep>/TimingMeasurement/C/Source/maxamps.inc
../SubProcesses/P3_qq_wpwpwm_wp_tapvl_wp_tapvl_wm_qq/maxamps.inc<file_sep>/rw_lljjjj/Source/maxamps.inc
../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/maxamps.inc<file_sep>/TimingMeasurement/B/Source/MODEL/coupl.inc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c written by the UFO converter
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
DOUBLE PRECISION G
COMMON/STRONG/ G
DOUBLE COMPLEX GAL(2)
COMMON/WEAK/ GAL
DOUBLE PRECISION MU_R
COMMON/RSCALE/ MU_R
DOUBLE PRECISION NF
PARAMETER(NF=4)
DOUBLE PRECISION MDL_MT,MDL_MW,MDL_MZ,MDL_MTA,MDL_MB,MDL_MX2
$ ,MDL_MX0,MDL_MX1
COMMON/MASSES/ MDL_MT,MDL_MW,MDL_MZ,MDL_MTA,MDL_MB,MDL_MX2
$ ,MDL_MX0,MDL_MX1
DOUBLE PRECISION MDL_WW,MDL_WT,MDL_WZ,MDL_WX0,MDL_WX1,MDL_WX2
COMMON/WIDTHS/ MDL_WW,MDL_WT,MDL_WZ,MDL_WX0,MDL_WX1,MDL_WX2
DOUBLE COMPLEX GC_6, GC_7, GC_8, GC_10, GC_11, GC_12, GC_13,
$ GC_62, GC_64, GC_65, GC_1, GC_2, GC_16, GC_66, GC_72, GC_73,
$ GC_74, GC_75, GC_76, GC_77, GC_78, GC_89, GC_90, GC_99, GC_100
$ , GC_101, GC_102, GC_105, GC_106, GC_107, GC_108, GC_109,
$ GC_110, GC_38, GC_39, GC_40, GC_41, GC_42, GC_67, GC_68, GC_111
COMMON/COUPLINGS/ GC_6, GC_7, GC_8, GC_10, GC_11, GC_12, GC_13,
$ GC_62, GC_64, GC_65, GC_1, GC_2, GC_16, GC_66, GC_72, GC_73,
$ GC_74, GC_75, GC_76, GC_77, GC_78, GC_89, GC_90, GC_99, GC_100
$ , GC_101, GC_102, GC_105, GC_106, GC_107, GC_108, GC_109,
$ GC_110, GC_38, GC_39, GC_40, GC_41, GC_42, GC_67, GC_68, GC_111
<file_sep>/TimingMeasurement/B/SubProcesses/P1_qq_zx0_z_ll_x0_qqqq/coloramps.inc
LOGICAL ICOLAMP(2,4,4)
DATA(ICOLAMP(I,1,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,2,1),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,3,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,4,1),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,1,2),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,3,2),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,1,3),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,2,3),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,3,3),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,4,3),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,1,4),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,3,4),I=1,2)/.FALSE.,.TRUE./
<file_sep>/Processes/plot_2lep_600.cc
#include "TROOT.h"
#include "TLorentzVector.h"
#include "TChain.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TMath.h"
#include "THStack.h"
#include "TLegend.h"
#include "TCanvas.h"
#include "TStyle.h"
#include "../reader.h"
#define GeV 1000
#define MASSLO 75
#define MASSHI 110
#define MASSLO2 70
#define MASSHI2 150
#define lumi 300 //fb-1
void calibrate_jet() {
Double_t thr[7] = {30,50,80,120,200,400,800};
Double_t sf[3][7] = {
{1.00113, 1.0039, 1.00243, 1.00129, 1.00032, 1.00126, 1.00133},
{1.05701, 1.03567, 1.02281, 1.01503, 1.00959, 1.00691, 1.00511},
{1.04688, 1.02907, 1.021 , 1.01858, 1.02032, 1. , 1. }
};
for(Int_t i=0; i<jet_n; i++) {
Double_t SF = 1.0;
if(fabs(jet_eta[i])<1.7) {
for(Int_t j=6; j>=0; j--) {
if(jet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[0][j]; break;
}
}
}
else if(fabs(jet_eta[i])<3.2) {
for(Int_t j=6; j>=0; j--) {
if(jet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[1][j]; break;
}
}
}
else {
for(Int_t j=6; j>=0; j--) {
if(jet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[2][j]; break;
}
}
}
jet_E[i] *= SF;
jet_m[i] *= SF;
jet_pt[i] *= SF;
}
}
void calibrate_fatjet() {
Double_t thr[7] = {40,50,80,120,200,400,800};
Double_t sf[3][7] = {
{0.835528, 0.876777, 0.914269, 0.940094, 0.962477, 0.981316, 0.990554},
{0.959362, 0.968022, 0.976831, 0.983729, 0.989864, 0.995393, 0.997024},
{0.979653, 0.984607, 0.990887, 0.99717, 1.00537 , 1. , 1. }
};
for(Int_t i=0; i<fatjet_n; i++) {
Double_t SF = 1.0;
if(fabs(fatjet_eta[i])<1.7) {
for(Int_t j=6; j>=0; j--) {
if(fatjet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[0][j]; break;
}
}
}
else if(fabs(fatjet_eta[i])<3.2) {
for(Int_t j=6; j>=0; j--) {
if(fatjet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[1][j]; break;
}
}
}
else {
for(Int_t j=6; j>=0; j--) {
if(fatjet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[2][j]; break;
}
}
}
fatjet_E[i] *= SF;
fatjet_m[i] *= SF;
fatjet_pt[i] *= SF;
fatjet_m_sj1[i] *= SF;
fatjet_pt_sj1[i] *= SF;
fatjet_m_sj2[i] *= SF;
fatjet_pt_sj2[i] *= SF;
}
}
void SetMax(TH1* h1, TH1* h2, Double_t scale=1.0) {
h1->SetMaximum(scale*TMath::Max(h1->GetMaximum(),h2->GetMaximum()));
h2->SetMaximum(scale*TMath::Max(h1->GetMaximum(),h2->GetMaximum()));
}
Float_t DR(Float_t eta1, Float_t phi1, Float_t eta2, Float_t phi2) {
Float_t dphi = fabs(phi1-phi2);
if(dphi>M_PI) dphi = 2*M_PI-dphi;
Float_t deta = fabs(eta1-eta2);
return sqrt(dphi*dphi+deta*deta);
}
Double_t NormPhi(Double_t phi) {
if(phi>=M_PI) return phi - 2*M_PI;
else if(phi<-M_PI) return phi + 2*M_PI;
else return phi;
}
Double_t significance(Double_t b0, Double_t s0, Double_t db) {
if(db==0) return sqrt(2*(s0+b0)*log(1+s0/b0)-2*s0);
else {
Double_t tmp = b0-db*db;
Double_t b = 0.5*(tmp+sqrt(pow(tmp,2)+4*db*db*(b0+s0)));
return sqrt(2*(b0+s0)*log((b0+s0)/b)-(b0+s0)+b-(b-b0)*b0/db/db);
}
}
class binning {
public:
Int_t nbin[50];
Float_t xlo[50];
Float_t xhi[50];
std::string titleX[50];
Float_t* var1[50];
Int_t* var2[50];
Bool_t MeVtoGeV[50];
Int_t nvar;
binning();
virtual ~binning();
void add(Int_t nbin_, Float_t xlo_, Float_t xhi_, const char* titleX_, Int_t* var_);
void add(Int_t nbin_, Float_t xlo_, Float_t xhi_, const char* titleX_, Float_t* var_, Bool_t MeVtoGeV_);
Float_t getVal(Int_t i);
};
binning::binning() {
nvar = 0;
for(Int_t i=0; i<50; i++) {
nbin[i] = 1; xlo[i] = 0; xhi[i] = 1; var1[i] = 0; var2[i] = 0; MeVtoGeV[i] = 0;
}
}
binning::~binning() {}
void binning::add(Int_t nbin_, Float_t xlo_, Float_t xhi_, const char* titleX_, Int_t* var_) {
if(nvar>=0 && nvar<50) {
nbin[nvar] = nbin_; xlo[nvar] = xlo_; xhi[nvar] = xhi_;
titleX[nvar] = titleX_; var2[nvar] = var_;
nvar++;
}
}
void binning::add(Int_t nbin_, Float_t xlo_, Float_t xhi_, const char* titleX_, Float_t* var_, Bool_t MeVtoGeV_) {
if(nvar>=0 && nvar<50) {
nbin[nvar] = nbin_; xlo[nvar] = xlo_; xhi[nvar] = xhi_;
titleX[nvar] = titleX_; var1[nvar] = var_; MeVtoGeV[nvar] = MeVtoGeV_;
nvar++;
}
}
Float_t binning::getVal(Int_t i) {
Float_t tmp = -999999;
if(i>=0 && i<nvar) {
if(var1[i]) tmp = MeVtoGeV[i] ? *var1[i]/GeV : *var1[i];
else if(var2[i]) tmp = *var2[i];
}
if(tmp >= xhi[i]) tmp = xhi[i]*0.999999;
if(tmp < xlo[i]) tmp = xlo[i];
return tmp;
}
binning* bn(0);
// new vars:
TLorentzVector v1, v2, v3;
Int_t reg;
Float_t mLL;
Float_t ptLL;
TLorentzVector V0, V1, V2;
Bool_t isLL[3];
Float_t tauXX;
Float_t mV[3];
Float_t pV[3];
Float_t ptV[3];
Float_t mHH;
Float_t pHH;
Float_t ptHH;
Float_t EVVV;
void initialize() {
bn = new binning();
//bn->add(40,0,2000,"m_{WW}^{truth} [GeV]",&mvv_truth,true);
//bn->add(150,0,150,"m_{LL} [GeV]",&mLL,true);
bn->add(50,0,500,"m_{V0} [GeV]",&mV[0],true);
bn->add(50,0,2000,"p_{T,V0} [GeV]",&ptV[0],true);
bn->add(50,0,500,"m_{V1} [GeV]",&mV[1],true);
bn->add(50,0,2000,"p_{T,V1} [GeV]",&ptV[1],true);
bn->add(50,0,500,"m_{V2} [GeV]",&mV[2],true);
bn->add(50,0,2000,"p_{T,V2} [GeV]",&ptV[2],true);
bn->add(40,0,2000,"m_{VV} [GeV]",&mHH,true);
bn->add(50,0,2000,"p_{T,VV} [GeV]",&ptHH,true);
}
Float_t figSigSF = 1; //sig
Float_t figMax = 1.2;
Bool_t Pass(Int_t ich) {
//Bool_t cut = mLL>0;
// Bool_t cut = mLL/GeV>80 && mLL/GeV<100 && mHH>0 && reg==4;
// Bool_t cut = mLL/GeV>80 && mLL/GeV<100 && mHH>0 && (reg==3 || reg==4);
Bool_t cut = mLL/GeV>80 && mLL/GeV<100 && mHH>0;
return cut;
}
void GetVars(Int_t ich) {
TLorentzVector temp_V;
TLorentzVector temp_VVV;
temp_VVV.SetPtEtaPhiM(0,0,0,0);
for(int i=0; i<truthV_n; i++){
temp_V.SetPtEtaPhiM(0,0,0,0);
temp_V.SetPtEtaPhiM(truthV_pt[i],truthV_eta[i],truthV_phi[i],truthV_m[i]);
temp_VVV += temp_V;
}
if(truthV_n==3) EVVV = temp_VVV.E()/GeV;
TLorentzVector vec_l1;
TLorentzVector vec_l2;
if(el_n==2 && el_charge[0]*el_charge[1]<0 && mu_n==0) {
vec_l1.SetPtEtaPhiE(el_pt[0],el_eta[0],el_phi[0],el_E[0]);
vec_l2.SetPtEtaPhiE(el_pt[1],el_eta[1],el_phi[1],el_E[1]);
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
}
else if(mu_n==2 && mu_charge[0]*mu_charge[1]<0 && el_n==0) {
vec_l1.SetPtEtaPhiE(mu_pt[0],mu_eta[0],mu_phi[0],mu_E[0]);
vec_l2.SetPtEtaPhiE(mu_pt[1],mu_eta[1],mu_phi[1],mu_E[1]);
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
}
else {
mLL = 0;
ptLL = 0;
}
v1 = vec_l1+vec_l2;
Int_t ifj1(-1);
Float_t maxPt = -999;
for(Int_t i=0; i<fatjet_n; i++) {
if(fatjet_pt[i]/GeV<50) continue;
if(fatjet_pt[i]>maxPt) {
maxPt = fatjet_pt[i];
ifj1 = i;
}
}
Int_t ifj2(-1);
maxPt = -999;
for(Int_t i=0; i<fatjet_n; i++) {
if(fatjet_pt[i]/GeV<50) continue;
if(i==ifj1) continue;
if(fatjet_pt[i]>maxPt) {
maxPt = fatjet_pt[i];
ifj2 = i;
}
}
Int_t ij[4] = {-1,-1,-1,-1};
maxPt = -999;
for(Int_t i=0; i<jet_n; i++) {
if(jet_pt[i]/GeV<30) continue;
if(jet_pt[i]>maxPt) {
maxPt = jet_pt[i];
ij[0] = i;
}
}
maxPt = -999;
for(Int_t i=0; i<jet_n; i++) {
if(jet_pt[i]/GeV<30) continue;
if(i==ij[0]) continue;
if(jet_pt[i]>maxPt) {
maxPt = jet_pt[i];
ij[1] = i;
}
}
maxPt = -999;
for(Int_t i=0; i<jet_n; i++) {
if(jet_pt[i]/GeV<30) continue;
if(i==ij[0] || i==ij[1]) continue;
if(jet_pt[i]>maxPt) {
maxPt = jet_pt[i];
ij[2] = i;
}
}
maxPt = -999;
for(Int_t i=0; i<jet_n; i++) {
if(jet_pt[i]/GeV<30) continue;
if(i==ij[0] || i==ij[1] || i==ij[2]) continue;
if(jet_pt[i]>maxPt) {
maxPt = jet_pt[i];
ij[3] = i;
}
}
v2.SetPxPyPzE(0,0,0,0);
v3.SetPxPyPzE(0,0,0,0);
reg = 0;
if(v2.Pt()==0) {
if(ptLL/GeV>950 && ifj1>=0 && fatjet_pt[ifj1]/GeV>750 && fatjet_sj_n[ifj1]==2 && fatjet_m_sj1[ifj1]/GeV>70 && fatjet_m_sj1[ifj1]/GeV<150 && fatjet_m_sj2[ifj1]/GeV>70 && fatjet_m_sj2[ifj1]/GeV<150 && fatjet_tau2[ifj1]/fatjet_tau1[ifj1]<0.45) {
v2.SetPtEtaPhiM(fatjet_pt_sj1[ifj1],fatjet_eta_sj1[ifj1],fatjet_phi_sj1[ifj1],fatjet_m_sj1[ifj1]);
v3.SetPtEtaPhiM(fatjet_pt_sj2[ifj1],fatjet_eta_sj2[ifj1],fatjet_phi_sj2[ifj1],fatjet_m_sj2[ifj1]);
tauXX = fatjet_tau2[ifj1]/fatjet_tau1[ifj1];
reg = 1;
}
}
if(v2.Pt()==0) {
if(ptLL/GeV>550 && ij[0]>=0 && jet_pt[ij[0]]/GeV>300 && jet_m[ij[0]]/GeV>70 && jet_m[ij[0]]/GeV<150 && ij[1]>=0 && ij[2]>=0 && jet_tau2[ij[0]]/jet_tau1[ij[0]]<0.4) {
TLorentzVector tmp1; TLorentzVector tmp2; TLorentzVector tmp3;
tmp1.SetPtEtaPhiM(jet_pt[ij[0]],jet_eta[ij[0]],jet_phi[ij[0]],jet_m[ij[0]]);
tmp2.SetPtEtaPhiM(jet_pt[ij[1]],jet_eta[ij[1]],jet_phi[ij[1]],jet_m[ij[1]]);
tmp3.SetPtEtaPhiM(jet_pt[ij[2]],jet_eta[ij[2]],jet_phi[ij[2]],jet_m[ij[2]]);
TLorentzVector tmp23 = tmp2+tmp3;
if(tmp23.M()/GeV>70 && tmp23.M()/GeV<110 && tmp23.Pt()/GeV>150 && tmp23.DeltaR(tmp1)<tmp23.DeltaR(v1) && tmp23.DeltaR(tmp1)<tmp1.DeltaR(v1) && (tmp1+tmp23).Pt()/GeV>550) {
v2 = tmp1;
v3 = tmp23;
tauXX = jet_tau2[ij[0]]/jet_tau1[ij[0]];
reg = 2;
}
}
}
if(v2.Pt()==0) {
if(ij[0]>=0 && jet_pt[ij[0]]/GeV>700 && jet_m[ij[0]]/GeV>70 && jet_m[ij[0]]/GeV<150 && jet_tau2[ij[0]]/jet_tau1[ij[0]]<0.60 && ij[1]>=0 && ij[2]>=0 && ptLL/GeV>300) {
TLorentzVector tmp1; TLorentzVector tmp2; TLorentzVector tmp3;
tmp1.SetPtEtaPhiM(jet_pt[ij[0]],jet_eta[ij[0]],jet_phi[ij[0]],jet_m[ij[0]]);
tmp2.SetPtEtaPhiM(jet_pt[ij[1]],jet_eta[ij[1]],jet_phi[ij[1]],jet_m[ij[1]]);
tmp3.SetPtEtaPhiM(jet_pt[ij[2]],jet_eta[ij[2]],jet_phi[ij[2]],jet_m[ij[2]]);
TLorentzVector tmp23 = tmp2+tmp3;
if(tmp23.M()/GeV>75 && tmp23.M()/GeV<115 && tmp23.Pt()/GeV>50 && tmp23.DeltaR(v1)<tmp23.DeltaR(tmp1) && tmp23.DeltaR(v1)<tmp1.DeltaR(v1) && (tmp23+v1).Pt()/GeV>700) {
v2 = tmp1;
v3 = tmp23;
tauXX = jet_tau2[ij[0]]/jet_tau1[ij[0]];
reg = 3;
}
}
}
if(v2.Pt()==0) {
if(ij[0]>=0 && jet_pt[ij[0]]/GeV>700 && jet_m[ij[0]]/GeV>70 && jet_m[ij[0]]/GeV<150 && ij[1]>=0 && jet_pt[ij[1]]/GeV>250 && jet_m[ij[1]]/GeV>70 && jet_m[ij[1]]/GeV<150 && jet_tau2[ij[0]]/jet_tau1[ij[0]]<0.52 && jet_tau2[ij[1]]/jet_tau1[ij[1]]<0.52 && ptLL/GeV>300) {
TLorentzVector tmp1; TLorentzVector tmp2;
tmp1.SetPtEtaPhiM(jet_pt[ij[0]],jet_eta[ij[0]],jet_phi[ij[0]],jet_m[ij[0]]);
tmp2.SetPtEtaPhiM(jet_pt[ij[1]],jet_eta[ij[1]],jet_phi[ij[1]],jet_m[ij[1]]);
if(tmp2.DeltaR(v1)<tmp2.DeltaR(tmp1) && tmp2.DeltaR(v1)<v1.DeltaR(tmp1) && (v1+tmp2).Pt()/GeV>700) {
v2 = tmp1;
v3 = tmp2;
tauXX = jet_tau2[ij[0]]/jet_tau1[ij[0]];
reg = 4;
}
}
}
V0.SetPxPyPzE(0,0,0,0); V1.SetPxPyPzE(0,0,0,0); V2.SetPxPyPzE(0,0,0,0);
isLL[0] = isLL[1] = isLL[2] = false;
mV[0] = mV[1] = mV[2] = 0;
pV[0] = pV[1] = pV[2] = 0;
ptV[0] = ptV[1] = ptV[2] = 0;
mHH = pHH = ptHH = 0;
if(reg==1 || reg==2) {
V0 = v1; V1 = v2; V2 = v3;
isLL[0] = true;
mV[0] = V0.M(); mV[1] = V1.M(); mV[2] = V2.M();
pV[0] = V0.P(); pV[1] = V1.P(); pV[2] = V2.P();
ptV[0] = V0.Pt(); ptV[1] = V1.Pt(); ptV[2] = V2.Pt();
mHH = (V1+V2).M();
pHH = (V1+V2).P();
ptHH = (V1+V2).Pt();
}
else if(reg==3 || reg==4) {
V0 = v2; V1 = v1; V2 = v3;
isLL[1] = true;
mV[0] = V0.M(); mV[1] = V1.M(); mV[2] = V2.M();
pV[0] = V0.P(); pV[1] = V1.P(); pV[2] = V2.P();
ptV[0] = V0.Pt(); ptV[1] = V1.Pt(); ptV[2] = V2.Pt();
mHH = (V1+V2).M();
pHH = (V1+V2).P();
ptHH = (V1+V2).Pt();
}
else if(reg==6){
V0 = v1;
mV[0] = V0.M(); pV[0] = V0.P(); ptV[0] = V0.Pt();
isLL[0] = true;
mHH = v2.M();
pHH = v2.P();
ptHH = v2.Pt();
}
if(ich==0) mc_event_weight *= lumi*0.00062418374e03/0.00062418374e04; //600,1000,6000
/////////////////////////////quadrant_1 //mass,fw,fww
// if(ich==0) mc_event_weight *= lumi*3.95981917e-02/3.95981917e-01; // 600,30,30
else if(ich==1) mc_event_weight *= lumi*6.83279757e01/68.72184;
else if(ich==2) mc_event_weight *= lumi*6.87452922e01/68.70894;
else if(ich==3) mc_event_weight *= lumi*6.154065e02/3.03691e-07;
else if(ich==4) mc_event_weight *= lumi*6.150717e02/3.03093e-07;
else if(ich==5) mc_event_weight *= lumi*0.01454e03/1470.53;
}
void plot() {
char str[200];
initialize();
TString title_sig = "hsig_fw_70_fww_m70";
TChain* ch[6] = {0,0,0,0,0,0};
ch[0] = new TChain("tau");
// ch[0]->Add("../../../rootfiles/test600/ntuple_2lep/S2_red_15.root"); //600,1000,6000
// ch[0]->Add("../../../rootfiles/test600/ntuple_2lep/S2_red_380.root"); //600,1000,6000
ch[0]->Add("../../../rootfiles/rhoH_005/ntuple_2lep/S2_red_1.root"); //600,1500,0
////////////////////////quadrant_1 //mass,fw,fww
// ch[0]->Add("../../rootfiles/ntuple_2lep/S2_red_68.root"); //600,30,30
Init(ch[0]);
ch[1] = new TChain("tau");
ch[1]->Add("../../../rootfiles/ntuple_merged2/zee_red.root");
Init(ch[1]);
ch[2] = new TChain("tau");
ch[2]->Add("../../../rootfiles/ntuple_merged2/zmm_red.root");
Init(ch[2]);
ch[3] = new TChain("tau");
ch[3]->Add("../../../rootfiles/ntuple_merged2/zee_vjj_red.root");
Init(ch[3]);
ch[4] = new TChain("tau");
ch[4]->Add("../../../rootfiles/ntuple_merged2/zmm_vjj_red.root");
Init(ch[4]);
ch[5] = new TChain("tau");
ch[5]->Add("../../../rootfiles/ntuple_merged2/zll_vv4j_red.root");
Init(ch[5]);
//////////////////////////////////
///////////////////////////////////////
TH1F* ht1 = new TH1F("ht1","",100,0,1);
TH1F* ht2 = new TH1F("ht2","",100,0,1);
TH1F* hsig = new TH1F(title_sig,"",40,0,2000);
TH1F* hbkg1 = new TH1F("hbkg1","zll",40,0,2000);
// sig,bkg
TH1F* h1[50]; TH1F* h2[50];
for(Int_t i=0; i<bn->nvar; i++) {
sprintf(str,"h1_var%d",i+1);
h1[i] = new TH1F(str,"",bn->nbin[i],bn->xlo[i],bn->xhi[i]);
sprintf(str,"h2_var%d",i+1);
h2[i] = new TH1F(str,"",bn->nbin[i],bn->xlo[i],bn->xhi[i]);
}
TH1F* hh1 = new TH1F("hh1","",200,0,1);
TH1F* hh2 = new TH1F("hh2","",200,0,1);
TH1F* hz = new TH1F("hz","",1000,0,10);
TH1F* h_EVVV = new TH1F("hz","",100,0,7000);
TH1F* hdr1 = new TH1F("hdr1","",200,-5,5);
TH1F* hdr2 = new TH1F("hdr2","",200,-5,5);
Double_t n_eve[6][5] = {
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0}
};
for(Int_t ich=0; ich<6; ich++) {
if(!ch[ich]) continue;
Int_t numberOfEntries = (Int_t)ch[ich]->GetEntries();
// Loop over all events
printf(" %d entries to be processed\n",numberOfEntries);
for(Int_t entry = 0; entry < numberOfEntries; entry++) {
// Load selected branches with data from specified event
ch[ich]->GetEntry(entry);
if((entry+1)%10000000==0) printf(" %d entries processed\n",entry+1);
calibrate_jet();
calibrate_fatjet();
GetVars(ich);
Double_t wt = mc_event_weight;
n_eve[ich][0] += wt;
if(truthV_n==3) h_EVVV->Fill(EVVV);
if(Pass(ich)) {
n_eve[ich][1] += wt;
if(ich==0) hsig->Fill(mHH/GeV,wt);
else hbkg1->Fill(mHH/GeV,wt);
for(Int_t i=0; i<bn->nvar; i++) {
if(ich==0) h1[i]->Fill(bn->getVal(i),wt);
else h2[i]->Fill(bn->getVal(i),wt);
}
if(ich==0) ht1->Fill(tauXX);
else ht2->Fill(tauXX);
}
}
}
printf("Sig: %.1f %.3f\n",n_eve[0][0],n_eve[0][1]);
printf("Bkg1: %.1f %.3f\n",n_eve[1][0],n_eve[1][1]);
printf("Bkg2: %.1f %.3f\n",n_eve[2][0],n_eve[2][1]);
printf("Bkg3: %.1f %.3f\n",n_eve[3][0],n_eve[3][1]);
printf("Bkg4: %.1f %.3f\n",n_eve[4][0],n_eve[4][1]);
printf("Bkg5: %.1f %.3f\n",n_eve[5][0],n_eve[5][1]);
printf("significance: %0.3f\n", significance(n_eve[1][1]+n_eve[2][1]+n_eve[3][1]+n_eve[4][1]+n_eve[5][1], n_eve[0][1], 0) );
TCanvas* c01 = new TCanvas("c01","c01",600,600);
ht1->SetLineColor(kRed);
ht2->SetLineColor(kBlue);
ht1->Scale(ht2->Integral()/ht1->Integral());
SetMax(ht1,ht2,1.1);
ht1->Draw();
ht2->Draw("same");
TLegend* lg = new TLegend(0.62,0.74,0.90,0.89,"");
if(figSigSF==1) sprintf(str,"Signal");
else sprintf(str,"Signal#times%1.0f",figSigSF);
lg->AddEntry(h1[0],str,"F");
lg->AddEntry(h2[0],"Background","F");
lg->SetBorderSize(0);
lg->SetMargin(0.25);
lg->SetFillColor(kWhite);
THStack* hsk[50];
TCanvas* cv[50];
for(Int_t i=0; i<bn->nvar; i++) {
h1[i]->Scale(figSigSF);
h1[i]->SetLineColor(kRed);
h1[i]->SetFillColor(kRed);
h2[i]->SetLineColor(kBlue);
h2[i]->SetFillColor(kBlue);
sprintf(str,"hsk_var%d",i+1);
hsk[i] = new THStack(str,"");
if(bn->titleX[i]=="m_{VV} [GeV]") {
hsk[i]->Add(h2[i]);
hsk[i]->Add(h1[i]);
}
else {
hsk[i]->Add(h1[i]);
hsk[i]->Add(h2[i]);
}
sprintf(str,"c%d",i+1);
cv[i] = new TCanvas(str,str,600,600);
hsk[i]->Draw("hist");
hsk[i]->GetXaxis()->SetTitle(bn->titleX[i].c_str());
sprintf(str,"Events/( %4.2f )",h1[i]->GetBinWidth(1));
hsk[i]->GetYaxis()->SetTitle(str);
lg->Draw("same");
// sprintf(str,"c%d.eps",i+1);
// cv[i]->SaveAs(str);
}
TCanvas* cvvv = new TCanvas();
h_EVVV->Draw();
// TFile f1("mHH_600_hist_bkg_2lep_lumi3000.root","recreate");
// TFile f1("mHH_600_hist_sig_2lep.root","recreate");
// TFile f1("mHH_600_hist_sig_2lep.root","update");
// f1.cd();
// hsig->Write();
// hbkg1->Write();
// f1.Close();
}
<file_sep>/TimingMeasurement/D/SubProcesses/P1_qq_wmx0_wm_qq_x0_llqq/coloramps.inc
LOGICAL ICOLAMP(1,4,64)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,64),I=1,1)/.TRUE./
<file_sep>/TimingMeasurement/C/SubProcesses/P1_qq_wpx0_wp_qq_x0_tamtapgg/coloramps.inc
LOGICAL ICOLAMP(1,7,16)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,16),I=1,1)/.TRUE./
<file_sep>/HC_lljjjj/Source/maxamps.inc
../SubProcesses/P1_qq_zx0_z_ll_x0_qqqq/maxamps.inc<file_sep>/LHC_HH_2lep/SubProcesses/P5_qq_wmhh_wm_qq_hh_llqq/mirrorprocs.inc
DATA (MIRRORPROCS(I),I=1,64)/.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE./
<file_sep>/HC_lljjjj/SubProcesses/P1_qq_zx0_z_ll_x0_qqqq/config_nqcd.inc
DATA NQCD(1)/2/
DATA NQCD(2)/2/
DATA NQCD(3)/2/
DATA NQCD(4)/2/
<file_sep>/TimingMeasurement/A/SubProcesses/P1_qq_zx0_z_qq_x0_tamtapqq/coloramps.inc
LOGICAL ICOLAMP(1,24,12)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,12),I=1,1)/.TRUE./
<file_sep>/TimingMeasurement/C/Source/MODEL/coupl.inc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c written by the UFO converter
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
DOUBLE PRECISION G
COMMON/STRONG/ G
DOUBLE COMPLEX GAL(2)
COMMON/WEAK/ GAL
DOUBLE PRECISION MU_R
COMMON/RSCALE/ MU_R
DOUBLE PRECISION NF
PARAMETER(NF=4)
DOUBLE PRECISION MDL_MT,MDL_MW,MDL_MZ,MDL_MTA,MDL_MB,MDL_MX2
$ ,MDL_MX0,MDL_MX1
COMMON/MASSES/ MDL_MT,MDL_MW,MDL_MZ,MDL_MTA,MDL_MB,MDL_MX2
$ ,MDL_MX0,MDL_MX1
DOUBLE PRECISION MDL_WW,MDL_WT,MDL_WZ,MDL_WX0,MDL_WX1,MDL_WX2
COMMON/WIDTHS/ MDL_WW,MDL_WT,MDL_WZ,MDL_WX0,MDL_WX1,MDL_WX2
DOUBLE COMPLEX GC_10, GC_13, GC_62, GC_64, GC_1, GC_2, GC_3,
$ GC_9, GC_16, GC_17, GC_19, GC_21, GC_22, GC_23, GC_24, GC_61,
$ GC_66, GC_72, GC_73, GC_74, GC_75, GC_76, GC_77, GC_78, GC_89,
$ GC_90, GC_98, GC_99, GC_100, GC_101, GC_102, GC_105, GC_106,
$ GC_107, GC_108, GC_109, GC_110, GC_35, GC_38, GC_39, GC_40,
$ GC_41, GC_42, GC_43, GC_45, GC_49, GC_56, GC_58, GC_67, GC_68,
$ GC_111
COMMON/COUPLINGS/ GC_10, GC_13, GC_62, GC_64, GC_1, GC_2, GC_3,
$ GC_9, GC_16, GC_17, GC_19, GC_21, GC_22, GC_23, GC_24, GC_61,
$ GC_66, GC_72, GC_73, GC_74, GC_75, GC_76, GC_77, GC_78, GC_89,
$ GC_90, GC_98, GC_99, GC_100, GC_101, GC_102, GC_105, GC_106,
$ GC_107, GC_108, GC_109, GC_110, GC_35, GC_38, GC_39, GC_40,
$ GC_41, GC_42, GC_43, GC_45, GC_49, GC_56, GC_58, GC_67, GC_68,
$ GC_111
<file_sep>/TimingMeasurement/D/SubProcesses/P2_qq_wmx0_wm_lvl_x0_llqq/mirrorprocs.inc
DATA (MIRRORPROCS(I),I=1,16)/.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.,.TRUE.
$ ,.TRUE.,.TRUE./
<file_sep>/TimingMeasurement/B/SubProcesses/P3_qq_zx0_z_tamtap_x0_lvlqq/coloramps.inc
LOGICAL ICOLAMP(1,2,8)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,8),I=1,1)/.TRUE./
<file_sep>/TimingMeasurement/B/SubProcesses/P1_qq_zx0_z_ll_x0_ggbbx/ngraphs.inc
INTEGER N_MAX_CG
PARAMETER (N_MAX_CG=30)
<file_sep>/TimingMeasurement/C/SubProcesses/P3_qq_wpwpwm_wp_tapvl_wp_tapvl_wm_qq/coloramps.inc
LOGICAL ICOLAMP(1,2,16)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,16),I=1,1)/.TRUE./
<file_sep>/TimingMeasurement/B/Source/leshouche.inc
../SubProcesses/P3_bbx_zx0_z_tamtap_x0_tapvlqq/leshouche.inc<file_sep>/TimingMeasurement/A/SubProcesses/P1_bbx_zx0_z_qq_x0_llqq/coloramps.inc
LOGICAL ICOLAMP(1,16,6)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,6),I=1,1)/.TRUE./
<file_sep>/HC_lljjjj/Source/MODEL/param_write.inc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c written by the UFO converter
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
WRITE(*,*) ' External Params'
WRITE(*,*) ' ---------------------------------'
WRITE(*,*) ' '
WRITE(*,*) 'mdl_cabi = ', MDL_CABI
WRITE(*,*) 'aEWM1 = ', AEWM1
WRITE(*,*) 'mdl_Gf = ', MDL_GF
WRITE(*,*) 'aS = ', AS
WRITE(*,*) 'mdl_ymb = ', MDL_YMB
WRITE(*,*) 'mdl_ymt = ', MDL_YMT
WRITE(*,*) 'mdl_ymtau = ', MDL_YMTAU
WRITE(*,*) 'mdl_Lambda = ', MDL_LAMBDA
WRITE(*,*) 'mdl_ca = ', MDL_CA
WRITE(*,*) 'mdl_kSM = ', MDL_KSM
WRITE(*,*) 'mdl_kHtt = ', MDL_KHTT
WRITE(*,*) 'mdl_kAtt = ', MDL_KATT
WRITE(*,*) 'mdl_kHbb = ', MDL_KHBB
WRITE(*,*) 'mdl_kAbb = ', MDL_KABB
WRITE(*,*) 'mdl_kHll = ', MDL_KHLL
WRITE(*,*) 'mdl_kAll = ', MDL_KALL
WRITE(*,*) 'mdl_kHaa = ', MDL_KHAA
WRITE(*,*) 'mdl_kAaa = ', MDL_KAAA
WRITE(*,*) 'mdl_kHza = ', MDL_KHZA
WRITE(*,*) 'mdl_kAza = ', MDL_KAZA
WRITE(*,*) 'mdl_kHgg = ', MDL_KHGG
WRITE(*,*) 'mdl_kAgg = ', MDL_KAGG
WRITE(*,*) 'mdl_kHzz = ', MDL_KHZZ
WRITE(*,*) 'mdl_kAzz = ', MDL_KAZZ
WRITE(*,*) 'mdl_kHww = ', MDL_KHWW
WRITE(*,*) 'mdl_kAww = ', MDL_KAWW
WRITE(*,*) 'mdl_kHda = ', MDL_KHDA
WRITE(*,*) 'mdl_kHdz = ', MDL_KHDZ
WRITE(*,*) 'mdl_kHdwR = ', MDL_KHDWR
WRITE(*,*) 'mdl_kHdwI = ', MDL_KHDWI
WRITE(*,*) 'mdl_kHHgg = ', MDL_KHHGG
WRITE(*,*) 'mdl_kAAgg = ', MDL_KAAGG
WRITE(*,*) 'mdl_kqa = ', MDL_KQA
WRITE(*,*) 'mdl_kqb = ', MDL_KQB
WRITE(*,*) 'mdl_kla = ', MDL_KLA
WRITE(*,*) 'mdl_klb = ', MDL_KLB
WRITE(*,*) 'mdl_kw1 = ', MDL_KW1
WRITE(*,*) 'mdl_kw2 = ', MDL_KW2
WRITE(*,*) 'mdl_kw3 = ', MDL_KW3
WRITE(*,*) 'mdl_kw4 = ', MDL_KW4
WRITE(*,*) 'mdl_kw5 = ', MDL_KW5
WRITE(*,*) 'mdl_kz1 = ', MDL_KZ1
WRITE(*,*) 'mdl_kz3 = ', MDL_KZ3
WRITE(*,*) 'mdl_kz5 = ', MDL_KZ5
WRITE(*,*) 'mdl_kq = ', MDL_KQ
WRITE(*,*) 'mdl_kq3 = ', MDL_KQ3
WRITE(*,*) 'mdl_kl = ', MDL_KL
WRITE(*,*) 'mdl_kg = ', MDL_KG
WRITE(*,*) 'mdl_ka = ', MDL_KA
WRITE(*,*) 'mdl_kz = ', MDL_KZ
WRITE(*,*) 'mdl_kw = ', MDL_KW
WRITE(*,*) 'mdl_kza = ', MDL_KZA
WRITE(*,*) 'mdl_MZ = ', MDL_MZ
WRITE(*,*) 'mdl_MTA = ', MDL_MTA
WRITE(*,*) 'mdl_MT = ', MDL_MT
WRITE(*,*) 'mdl_MB = ', MDL_MB
WRITE(*,*) 'mdl_MX0 = ', MDL_MX0
WRITE(*,*) 'mdl_MX1 = ', MDL_MX1
WRITE(*,*) 'mdl_MX2 = ', MDL_MX2
WRITE(*,*) 'mdl_WZ = ', MDL_WZ
WRITE(*,*) 'mdl_WW = ', MDL_WW
WRITE(*,*) 'mdl_WT = ', MDL_WT
WRITE(*,*) 'mdl_WX0 = ', MDL_WX0
WRITE(*,*) 'mdl_WX1 = ', MDL_WX1
WRITE(*,*) 'mdl_WX2 = ', MDL_WX2
WRITE(*,*) ' Internal Params'
WRITE(*,*) ' ---------------------------------'
WRITE(*,*) ' '
WRITE(*,*) 'mdl_cos__cabi = ', MDL_COS__CABI
WRITE(*,*) 'mdl_CKM1x1 = ', MDL_CKM1X1
WRITE(*,*) 'mdl_sin__cabi = ', MDL_SIN__CABI
WRITE(*,*) 'mdl_CKM1x2 = ', MDL_CKM1X2
WRITE(*,*) 'mdl_CKM2x1 = ', MDL_CKM2X1
WRITE(*,*) 'mdl_CKM2x2 = ', MDL_CKM2X2
WRITE(*,*) 'mdl_ca__exp__2 = ', MDL_CA__EXP__2
WRITE(*,*) 'mdl_sa = ', MDL_SA
WRITE(*,*) 'mdl_complexi = ', MDL_COMPLEXI
WRITE(*,*) 'mdl_kHdw = ', MDL_KHDW
WRITE(*,*) 'mdl_MZ__exp__2 = ', MDL_MZ__EXP__2
WRITE(*,*) 'mdl_MZ__exp__4 = ', MDL_MZ__EXP__4
WRITE(*,*) 'mdl_sqrt__2 = ', MDL_SQRT__2
WRITE(*,*) 'mdl_nb__2__exp__0_75 = ', MDL_NB__2__EXP__0_75
WRITE(*,*) 'mdl_MX0__exp__2 = ', MDL_MX0__EXP__2
WRITE(*,*) 'mdl_ca__exp__4 = ', MDL_CA__EXP__4
WRITE(*,*) 'mdl_ca__exp__3 = ', MDL_CA__EXP__3
WRITE(*,*) 'mdl_conjg__CKM1x1 = ', MDL_CONJG__CKM1X1
WRITE(*,*) 'mdl_conjg__CKM1x2 = ', MDL_CONJG__CKM1X2
WRITE(*,*) 'mdl_conjg__CKM2x1 = ', MDL_CONJG__CKM2X1
WRITE(*,*) 'mdl_conjg__CKM2x2 = ', MDL_CONJG__CKM2X2
WRITE(*,*) 'mdl_conjg__kHdw = ', MDL_CONJG__KHDW
WRITE(*,*) 'mdl_aEW = ', MDL_AEW
WRITE(*,*) 'mdl_MW = ', MDL_MW
WRITE(*,*) 'mdl_sqrt__aEW = ', MDL_SQRT__AEW
WRITE(*,*) 'mdl_ee = ', MDL_EE
WRITE(*,*) 'mdl_MW__exp__2 = ', MDL_MW__EXP__2
WRITE(*,*) 'mdl_sw2 = ', MDL_SW2
WRITE(*,*) 'mdl_cw = ', MDL_CW
WRITE(*,*) 'mdl_sqrt__sw2 = ', MDL_SQRT__SW2
WRITE(*,*) 'mdl_sw = ', MDL_SW
WRITE(*,*) 'mdl_ad = ', MDL_AD
WRITE(*,*) 'mdl_al = ', MDL_AL
WRITE(*,*) 'mdl_an = ', MDL_AN
WRITE(*,*) 'mdl_au = ', MDL_AU
WRITE(*,*) 'mdl_bd = ', MDL_BD
WRITE(*,*) 'mdl_bl = ', MDL_BL
WRITE(*,*) 'mdl_bn = ', MDL_BN
WRITE(*,*) 'mdl_bu = ', MDL_BU
WRITE(*,*) 'mdl_gwwz = ', MDL_GWWZ
WRITE(*,*) 'mdl_g1 = ', MDL_G1
WRITE(*,*) 'mdl_gw = ', MDL_GW
WRITE(*,*) 'mdl_vev = ', MDL_VEV
WRITE(*,*) 'mdl_ee__exp__2 = ', MDL_EE__EXP__2
WRITE(*,*) 'mdl_gAaa = ', MDL_GAAA
WRITE(*,*) 'mdl_vev__exp__2 = ', MDL_VEV__EXP__2
WRITE(*,*) 'mdl_cw__exp__2 = ', MDL_CW__EXP__2
WRITE(*,*) 'mdl_gAza = ', MDL_GAZA
WRITE(*,*) 'mdl_gHaa = ', MDL_GHAA
WRITE(*,*) 'mdl_gHza = ', MDL_GHZA
WRITE(*,*) 'mdl_lam = ', MDL_LAM
WRITE(*,*) 'mdl_yb = ', MDL_YB
WRITE(*,*) 'mdl_yt = ', MDL_YT
WRITE(*,*) 'mdl_ytau = ', MDL_YTAU
WRITE(*,*) 'mdl_muH = ', MDL_MUH
WRITE(*,*) 'mdl_sw__exp__2 = ', MDL_SW__EXP__2
WRITE(*,*) ' Internal Params evaluated point by point'
WRITE(*,*) ' ----------------------------------------'
WRITE(*,*) ' '
WRITE(*,*) 'mdl_sqrt__aS = ', MDL_SQRT__AS
WRITE(*,*) 'mdl_G__exp__2 = ', MDL_G__EXP__2
WRITE(*,*) 'mdl_gAAgg = ', MDL_GAAGG
WRITE(*,*) 'mdl_gAgg = ', MDL_GAGG
WRITE(*,*) 'mdl_gHgg = ', MDL_GHGG
WRITE(*,*) 'mdl_gHHgg = ', MDL_GHHGG
<file_sep>/Processes/plot_3lep_600.cc
#include "TROOT.h"
#include "TLorentzVector.h"
#include "TChain.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TMath.h"
#include "THStack.h"
#include "TLegend.h"
#include "TCanvas.h"
#include "TStyle.h"
#include "../reader.h"
#define GeV 1000
#define MASSLO 70
#define MASSHI 110
#define lumi 300 //fb-1
void calibrate_jet() {
Double_t thr[7] = {30,50,80,120,200,400,800};
Double_t sf[3][7] = {
{1.00113, 1.0039, 1.00243, 1.00129, 1.00032, 1.00126, 1.00133},
{1.05701, 1.03567, 1.02281, 1.01503, 1.00959, 1.00691, 1.00511},
{1.04688, 1.02907, 1.021 , 1.01858, 1.02032, 1. , 1. }
};
for(Int_t i=0; i<jet_n; i++) {
Double_t SF = 1.0;
if(fabs(jet_eta[i])<1.7) {
for(Int_t j=6; j>=0; j--) {
if(jet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[0][j]; break;
}
}
}
else if(fabs(jet_eta[i])<3.2) {
for(Int_t j=6; j>=0; j--) {
if(jet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[1][j]; break;
}
}
}
else {
for(Int_t j=6; j>=0; j--) {
if(jet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[2][j]; break;
}
}
}
jet_E[i] *= SF;
jet_m[i] *= SF;
jet_pt[i] *= SF;
}
}
void calibrate_fatjet() {
Double_t thr[7] = {40,50,80,120,200,400,800};
Double_t sf[3][7] = {
{0.835528, 0.876777, 0.914269, 0.940094, 0.962477, 0.981316, 0.990554},
{0.959362, 0.968022, 0.976831, 0.983729, 0.989864, 0.995393, 0.997024},
{0.979653, 0.984607, 0.990887, 0.99717, 1.00537 , 1. , 1. }
};
for(Int_t i=0; i<fatjet_n; i++) {
Double_t SF = 1.0;
if(fabs(fatjet_eta[i])<1.7) {
for(Int_t j=6; j>=0; j--) {
if(fatjet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[0][j]; break;
}
}
}
else if(fabs(fatjet_eta[i])<3.2) {
for(Int_t j=6; j>=0; j--) {
if(fatjet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[1][j]; break;
}
}
}
else {
for(Int_t j=6; j>=0; j--) {
if(fatjet_pt[i]/GeV>=thr[j]) {
SF = 1/sf[2][j]; break;
}
}
}
fatjet_E[i] *= SF;
fatjet_m[i] *= SF;
fatjet_pt[i] *= SF;
fatjet_m_sj1[i] *= SF;
fatjet_pt_sj1[i] *= SF;
fatjet_m_sj2[i] *= SF;
fatjet_pt_sj2[i] *= SF;
}
}
void SetMax(TH1* h1, TH1* h2, Double_t scale=1.0) {
h1->SetMaximum(scale*TMath::Max(h1->GetMaximum(),h2->GetMaximum()));
h2->SetMaximum(scale*TMath::Max(h1->GetMaximum(),h2->GetMaximum()));
}
Float_t DR(Float_t eta1, Float_t phi1, Float_t eta2, Float_t phi2) {
Float_t dphi = fabs(phi1-phi2);
if(dphi>M_PI) dphi = 2*M_PI-dphi;
Float_t deta = fabs(eta1-eta2);
return sqrt(dphi*dphi+deta*deta);
}
Double_t NormPhi(Double_t phi) {
if(phi>=M_PI) return phi - 2*M_PI;
else if(phi<-M_PI) return phi + 2*M_PI;
else return phi;
}
Double_t significance(Double_t b0, Double_t s0, Double_t db) {
if(db==0) return sqrt(2*(s0+b0)*log(1+s0/b0)-2*s0);
else {
Double_t tmp = b0-db*db;
Double_t b = 0.5*(tmp+sqrt(pow(tmp,2)+4*db*db*(b0+s0)));
return sqrt(2*(b0+s0)*log((b0+s0)/b)-(b0+s0)+b-(b-b0)*b0/db/db);
}
}
class binning {
public:
Int_t nbin[50];
Float_t xlo[50];
Float_t xhi[50];
std::string titleX[50];
Float_t* var1[50];
Int_t* var2[50];
Bool_t MeVtoGeV[50];
Int_t nvar;
binning();
virtual ~binning();
void add(Int_t nbin_, Float_t xlo_, Float_t xhi_, const char* titleX_, Int_t* var_);
void add(Int_t nbin_, Float_t xlo_, Float_t xhi_, const char* titleX_, Float_t* var_, Bool_t MeVtoGeV_);
Float_t getVal(Int_t i);
};
binning::binning() {
nvar = 0;
for(Int_t i=0; i<50; i++) {
nbin[i] = 1; xlo[i] = 0; xhi[i] = 1; var1[i] = 0; var2[i] = 0; MeVtoGeV[i] = 0;
}
}
binning::~binning() {}
void binning::add(Int_t nbin_, Float_t xlo_, Float_t xhi_, const char* titleX_, Int_t* var_) {
if(nvar>=0 && nvar<50) {
nbin[nvar] = nbin_; xlo[nvar] = xlo_; xhi[nvar] = xhi_;
titleX[nvar] = titleX_; var2[nvar] = var_;
nvar++;
}
}
void binning::add(Int_t nbin_, Float_t xlo_, Float_t xhi_, const char* titleX_, Float_t* var_, Bool_t MeVtoGeV_) {
if(nvar>=0 && nvar<50) {
nbin[nvar] = nbin_; xlo[nvar] = xlo_; xhi[nvar] = xhi_;
titleX[nvar] = titleX_; var1[nvar] = var_; MeVtoGeV[nvar] = MeVtoGeV_;
nvar++;
}
}
Float_t binning::getVal(Int_t i) {
Float_t tmp = -999999;
if(i>=0 && i<nvar) {
if(var1[i]) tmp = MeVtoGeV[i] ? *var1[i]/GeV : *var1[i];
else if(var2[i]) tmp = *var2[i];
}
if(tmp >= xhi[i]) tmp = xhi[i]*0.999999;
if(tmp < xlo[i]) tmp = xlo[i];
return tmp;
}
binning* bn(0);
// new vars:
TLorentzVector v1, v2, v3;
TLorentzVector vec_nu;
Bool_t isFatJet_v3;
Float_t tau21_v3;
Int_t reg;
Float_t mLL;
Float_t ptLL;
Float_t ptL3;
TLorentzVector V0, V1, V2;
Bool_t isLL[3];
Float_t mV[3];
Float_t pV[3];
Float_t ptV[3];
Float_t mHH;
Float_t pHH;
Float_t ptHH;
Float_t mT;
void initialize() {
bn = new binning();
//bn->add(40,0,2000,"m_{WW}^{truth} [GeV]",&mvv_truth,true);
bn->add(100,50,150,"m_{LL} [GeV]",&mLL,true);
bn->add(50,0,1500,"p_{T,V0} [GeV]",&ptV[0],true);
bn->add(50,0,500,"m_{V2} [GeV]",&mV[2],true);
bn->add(25,0,1000,"p_{T,V2} [GeV]",&ptV[2],true);
bn->add(36,200,2000,"m_{VV} [GeV]",&mHH,true);
bn->add(50,0,2000,"p_{T,VV} [GeV]",&ptHH,true);
bn->add(50,0,1500,"MET [GeV]",&MET_et,true);
bn->add(25,0,250,"m_{T} [GeV]",&mT,true);
bn->add(30,0,1500,"p_{T,l3} [GeV]",&ptL3,true);
}
Float_t figSigSF = 1; //sig
Float_t figMax = 1.2;
Bool_t Pass(Int_t ich) {
//Bool_t cut = mLL>0;
//Bool_t cut = mLL/GeV>80 && mLL/GeV<100 && mHH>0 && ptL3/GeV>50 && (reg==3 || reg==4 || reg==7);
//Bool_t cut = mLL/GeV>80 && mLL/GeV<100 && mHH>0 && ptL3/GeV>50 && (reg==1 || reg==2 || reg==6);
Bool_t cut = mLL/GeV>80 && mLL/GeV<100 && mHH>0 && ptL3/GeV>50;
return cut;
}
void GetVars(Int_t ich) {
TLorentzVector vec_l1;
TLorentzVector vec_l2;
TLorentzVector vec_l3;
if(el_n==3 && mu_n==0) {
vec_l1.SetPtEtaPhiE(el_pt[0],el_eta[0],el_phi[0],el_E[0]);
vec_l2.SetPtEtaPhiE(el_pt[1],el_eta[1],el_phi[1],el_E[1]);
vec_l3.SetPtEtaPhiE(el_pt[2],el_eta[2],el_phi[2],el_E[2]);
if(el_charge[0]*el_charge[1]<0 && el_charge[0]*el_charge[2]<0) {
if(vec_l1.DeltaR(vec_l3)<vec_l1.DeltaR(vec_l2)) {
TLorentzVector tmp = vec_l2; vec_l2 = vec_l3; vec_l3 = tmp;
}
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
}
else if(el_charge[0]*el_charge[1]<0 && el_charge[1]*el_charge[2]<0) {
if(vec_l2.DeltaR(vec_l3)<vec_l1.DeltaR(vec_l2)) {
TLorentzVector tmp = vec_l1; vec_l1 = vec_l3; vec_l3 = tmp;
}
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
}
else if(el_charge[0]*el_charge[2]<0 && el_charge[1]*el_charge[2]<0) {
if(vec_l1.DeltaR(vec_l3)<vec_l2.DeltaR(vec_l3)) {
TLorentzVector tmp = vec_l2; vec_l2 = vec_l3; vec_l3 = tmp;
}
else {
TLorentzVector tmp = vec_l1; vec_l1 = vec_l3; vec_l3 = tmp;
}
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
}
else {
mLL = 0;
ptLL = 0;
}
}
else if(mu_n==3 && el_n==0) {
vec_l1.SetPtEtaPhiE(mu_pt[0],mu_eta[0],mu_phi[0],mu_E[0]);
vec_l2.SetPtEtaPhiE(mu_pt[1],mu_eta[1],mu_phi[1],mu_E[1]);
vec_l3.SetPtEtaPhiE(mu_pt[2],mu_eta[2],mu_phi[2],mu_E[2]);
if(mu_charge[0]*mu_charge[1]<0 && mu_charge[0]*mu_charge[2]<0) {
if(vec_l1.DeltaR(vec_l3)<vec_l1.DeltaR(vec_l2)) {
TLorentzVector tmp = vec_l2; vec_l2 = vec_l3; vec_l3 = tmp;
}
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
}
else if(mu_charge[0]*mu_charge[1]<0 && mu_charge[1]*mu_charge[2]<0) {
if(vec_l2.DeltaR(vec_l3)<vec_l1.DeltaR(vec_l2)) {
TLorentzVector tmp = vec_l1; vec_l1 = vec_l3; vec_l3 = tmp;
}
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
}
else if(mu_charge[0]*mu_charge[2]<0 && mu_charge[1]*mu_charge[2]<0) {
if(vec_l1.DeltaR(vec_l3)<vec_l2.DeltaR(vec_l3)) {
TLorentzVector tmp = vec_l2; vec_l2 = vec_l3; vec_l3 = tmp;
}
else {
TLorentzVector tmp = vec_l1; vec_l1 = vec_l3; vec_l3 = tmp;
}
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
}
else {
mLL = 0;
ptLL = 0;
}
}
else if(el_n==2 && el_charge[0]*el_charge[1]<0 && mu_n==1) {
vec_l1.SetPtEtaPhiE(el_pt[0],el_eta[0],el_phi[0],el_E[0]);
vec_l2.SetPtEtaPhiE(el_pt[1],el_eta[1],el_phi[1],el_E[1]);
vec_l3.SetPtEtaPhiE(mu_pt[0],mu_eta[0],mu_phi[0],mu_E[0]);
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
}
else if(mu_n==2 && mu_charge[0]*mu_charge[1]<0 && el_n==1) {
vec_l1.SetPtEtaPhiE(mu_pt[0],mu_eta[0],mu_phi[0],mu_E[0]);
vec_l2.SetPtEtaPhiE(mu_pt[1],mu_eta[1],mu_phi[1],mu_E[1]);
vec_l3.SetPtEtaPhiE(el_pt[0],el_eta[0],el_phi[0],el_E[0]);
mLL = (vec_l1+vec_l2).M();
ptLL = (vec_l1+vec_l2).Pt();
}
else {
mLL = 0;
ptLL = 0;
}
v1 = vec_l1+vec_l2;
ptL3 = vec_l3.Pt();
vec_nu.SetXYZT(0,0,0,0);
if(vec_l3.Pt()>0) {
Float_t phiX = atan2(MET_ey,MET_ex);
Float_t dphi = fabs(vec_l3.Phi() - phiX);
if(dphi>M_PI) dphi = 2*M_PI-dphi;
mT = sqrt(2*vec_l3.Pt()*MET_et*(1-cos(dphi)));
Float_t pzMiss = 0;
if(mT/GeV<80.4) {
Float_t ptX = vec_l3.Px()*MET_ex+vec_l3.Py()*MET_ey;
Float_t tmp = pow(80.4*GeV,2)+2*ptX;
Float_t pzMiss1 = (vec_l3.Pz()*tmp-vec_l3.E()*sqrt(pow(tmp,2)-pow(2*vec_l3.Pt()*MET_et,2)))/2/vec_l3.Pt()/vec_l3.Pt();
Float_t pzMiss2 = (vec_l3.Pz()*tmp+vec_l3.E()*sqrt(pow(tmp,2)-pow(2*vec_l3.Pt()*MET_et,2)))/2/vec_l3.Pt()/vec_l3.Pt();
// TLorentzVector tmp1;
// TLorentzVector tmp2;
// tmp1.SetXYZM(MET_ex,MET_ey,pzMiss1,0);
// tmp2.SetXYZM(MET_ex,MET_ey,pzMiss2,0);
// if(vec_l3.DeltaR(tmp1)<vec_l3.DeltaR(tmp2)) pzMiss = pzMiss2;
// else pzMiss = pzMiss1;
// if(ich==0) {
// Float_t pzMiss_truth(0);
// for(Int_t i=0; i<truthV_n; i++) {
// if(abs(truthV_pdgId[i])==24) {
// if(abs(truthV_dau1_pdgId[i])==12 || abs(truthV_dau1_pdgId[i])==14 || abs(truthV_dau1_pdgId[i])==16) {
// pzMiss_truth = truthV_dau1_pt[i]*sinh(truthV_dau1_eta[i]);
// break;
// }
// if(abs(truthV_dau2_pdgId[i])==12 || abs(truthV_dau2_pdgId[i])==14 || abs(truthV_dau2_pdgId[i])==16) {
// pzMiss_truth = truthV_dau2_pt[i]*sinh(truthV_dau2_eta[i]);
// break;
// }
// }
// }
// pzMiss = fabs(pzMiss1-pzMiss_truth)<fabs(pzMiss2-pzMiss_truth) ? pzMiss1 : pzMiss2;
// }
// else pzMiss = fabs(pzMiss1)<fabs(pzMiss2) ? pzMiss1 : pzMiss2;
pzMiss = fabs(pzMiss1)<fabs(pzMiss2) ? pzMiss1 : pzMiss2;
}
else {
pzMiss = vec_l3.Pz()*MET_et/vec_l3.Pt();
}
vec_nu.SetXYZM(MET_ex,MET_ey,pzMiss,0);
}
v2 = vec_l3+vec_nu;
Int_t ifj1(-1);
Float_t maxPt = -999;
for(Int_t i=0; i<fatjet_n; i++) {
if(fatjet_pt[i]/GeV<50) continue;
if(fatjet_pt[i]>maxPt) {
maxPt = fatjet_pt[i];
ifj1 = i;
}
}
Int_t ij[2] = {-1,-1};
maxPt = -999;
for(Int_t i=0; i<jet_n; i++) {
if(jet_pt[i]/GeV<30) continue;
if(jet_pt[i]>maxPt) {
maxPt = jet_pt[i];
ij[0] = i;
}
}
maxPt = -999;
for(Int_t i=0; i<jet_n; i++) {
if(jet_pt[i]/GeV<30) continue;
if(i==ij[0]) continue;
if(jet_pt[i]>maxPt) {
maxPt = jet_pt[i];
ij[1] = i;
}
}
isFatJet_v3 = false;
tau21_v3 = -999;
v3.SetXYZT(0,0,0,0);
reg = 0;
if(v1.Pt()>0 && v2.Pt()>0) {
if(v3.Pt()==0) {
if(v2.Pt()/GeV>600 && ij[0]>=0 && jet_m[ij[0]]/GeV>60 && jet_m[ij[0]]/GeV<160 && jet_tau2[ij[0]]/jet_tau1[ij[0]]<0.6) {
TLorentzVector tmp;
tmp.SetPtEtaPhiM(jet_pt[ij[0]],jet_eta[ij[0]],jet_phi[ij[0]],jet_m[ij[0]]);
if(v1.DeltaR(tmp)<v1.DeltaR(v2) && v1.DeltaR(tmp)<tmp.DeltaR(v2) && (v1+tmp).Pt()/GeV>600) {
v3 = tmp;
isFatJet_v3 = true;
tau21_v3 = jet_tau2[ij[0]]/jet_tau1[ij[0]];
reg = 3;
}
}
}
if(v3.Pt()==0) {
if(v2.Pt()/GeV>600 && ifj1>=0 && fatjet_m[ifj1]/GeV>70 && fatjet_m[ifj1]/GeV<140 && fatjet_tau2[ifj1]/fatjet_tau1[ifj1]<0.5) {
TLorentzVector tmp;
tmp.SetPtEtaPhiM(fatjet_pt[ifj1],fatjet_eta[ifj1],fatjet_phi[ifj1],fatjet_m[ifj1]);
if(v1.DeltaR(tmp)<v1.DeltaR(v2) && v1.DeltaR(tmp)<tmp.DeltaR(v2) && (v1+tmp).Pt()/GeV>600) {
v3 = tmp;
isFatJet_v3 = true;
tau21_v3 = fatjet_tau2[ifj1]/fatjet_tau1[ifj1];
reg = 4;
}
}
}
if(v3.Pt()==0) {
if(v2.Pt()/GeV>600 && ij[0]>=0 && ij[1]>=0) {
TLorentzVector tmp1; TLorentzVector tmp2;
tmp1.SetPtEtaPhiM(jet_pt[ij[0]],jet_eta[ij[0]],jet_phi[ij[0]],jet_m[ij[0]]);
tmp2.SetPtEtaPhiM(jet_pt[ij[1]],jet_eta[ij[1]],jet_phi[ij[1]],jet_m[ij[1]]);
TLorentzVector tmp = tmp1+tmp2;
if(tmp.M()/GeV>60 && tmp.M()/GeV<120 && v1.DeltaR(tmp)<v1.DeltaR(v2) && v1.DeltaR(tmp)<tmp.DeltaR(v2) && (v1+tmp).Pt()/GeV>600) {
v3 = tmp;
isFatJet_v3 = false;
reg = 7;
}
}
}
if(v3.Pt()==0) {
if(v1.Pt()/GeV>600 && ij[0]>=0 && jet_m[ij[0]]/GeV>60 && jet_m[ij[0]]/GeV<160 && jet_tau2[ij[0]]/jet_tau1[ij[0]]<0.6) {
TLorentzVector tmp;
tmp.SetPtEtaPhiM(jet_pt[ij[0]],jet_eta[ij[0]],jet_phi[ij[0]],jet_m[ij[0]]);
if(v2.DeltaR(tmp)<v1.DeltaR(v2) && v2.DeltaR(tmp)<tmp.DeltaR(v1) && (v2+tmp).Pt()/GeV>600) {
v3 = tmp;
isFatJet_v3 = true;
tau21_v3 = jet_tau2[ij[0]]/jet_tau1[ij[0]];
reg = 1;
}
}
}
if(v3.Pt()==0) {
if(v1.Pt()/GeV>600 && ifj1>=0 && fatjet_m[ifj1]/GeV>70 && fatjet_m[ifj1]/GeV<140 && fatjet_tau2[ifj1]/fatjet_tau1[ifj1]<0.5) {
TLorentzVector tmp;
tmp.SetPtEtaPhiM(fatjet_pt[ifj1],fatjet_eta[ifj1],fatjet_phi[ifj1],fatjet_m[ifj1]);
if(v2.DeltaR(tmp)<v1.DeltaR(v2) && v2.DeltaR(tmp)<tmp.DeltaR(v1) && (v2+tmp).Pt()/GeV>600) {
v3 = tmp;
isFatJet_v3 = true;
tau21_v3 = fatjet_tau2[ifj1]/fatjet_tau1[ifj1];
reg = 2;
}
}
}
if(v3.Pt()==0) {
if(v1.Pt()/GeV>600 && ij[0]>=0 && ij[1]>=0) {
TLorentzVector tmp1; TLorentzVector tmp2;
tmp1.SetPtEtaPhiM(jet_pt[ij[0]],jet_eta[ij[0]],jet_phi[ij[0]],jet_m[ij[0]]);
tmp2.SetPtEtaPhiM(jet_pt[ij[1]],jet_eta[ij[1]],jet_phi[ij[1]],jet_m[ij[1]]);
TLorentzVector tmp = tmp1+tmp2;
if(tmp.M()/GeV>60 && tmp.M()/GeV<120 && v2.DeltaR(tmp)<v1.DeltaR(v2) && v2.DeltaR(tmp)<tmp.DeltaR(v1) && (v2+tmp).Pt()/GeV>600) {
v3 = tmp;
isFatJet_v3 = false;
reg = 6;
}
}
}
}
V0.SetPxPyPzE(0,0,0,0); V1.SetPxPyPzE(0,0,0,0); V2.SetPxPyPzE(0,0,0,0);
isLL[0] = isLL[1] = isLL[2] = false;
mV[0] = mV[1] = mV[2] = 0;
pV[0] = pV[1] = pV[2] = 0;
ptV[0] = ptV[1] = ptV[2] = 0;
mHH = pHH = ptHH = 0;
if(reg==3 || reg==4 || reg==7) {
V0 = v2; V1 = v1; V2 = v3;
isLL[1] = true;
mV[0] = V0.M(); mV[1] = V1.M(); mV[2] = V2.M();
pV[0] = V0.P(); pV[1] = V1.P(); pV[2] = V2.P();
ptV[0] = V0.Pt(); ptV[1] = V1.Pt(); ptV[2] = V2.Pt();
mHH = (V1+V2).M();
pHH = (V1+V2).P();
ptHH = (V1+V2).Pt();
}
else if(reg==1 || reg==2 || reg==6) {
V0 = v1; V1 = v2; V2 = v3;
isLL[0] = true;
mV[0] = V0.M(); mV[1] = V1.M(); mV[2] = V2.M();
pV[0] = V0.P(); pV[1] = V1.P(); pV[2] = V2.P();
ptV[0] = V0.Pt(); ptV[1] = V1.Pt(); ptV[2] = V2.Pt();
mHH = (V1+V2).M();
pHH = (V1+V2).P();
ptHH = (V1+V2).Pt();
}
else if(v1.Pt()>0 && v2.Pt()>0 && v3.Pt()>0) {
if(v1.DeltaR(v3)<v2.DeltaR(v3)) {
V0 = v2; V1 = v1; V2 = v3;
isLL[1] = true;
}
else {
V0 = v1; V1 = v2; V2 = v3;
isLL[0] = true;
}
mV[0] = V0.M(); mV[1] = V1.M(); mV[2] = V2.M();
pV[0] = V0.P(); pV[1] = V1.P(); pV[2] = V2.P();
ptV[0] = V0.Pt(); ptV[1] = V1.Pt(); ptV[2] = V2.Pt();
mHH = (V1+V2).M();
pHH = (V1+V2).P();
ptHH = (V1+V2).Pt();
}
if(ich==0) mc_event_weight *= lumi*0.000234555557e03/0.000234555557e04; // 600, 800, 800
// if(ich==0) mc_event_weight *= lumi*4.09409661e-02/4.09409661e-01; // 600, 800, 800
else if(ich==1) mc_event_weight *= lumi*0.701193227/0.34599; //zll_wmlv
else if(ich==2) mc_event_weight *= lumi*1.41261797/0.67463; //zll_wplv
else if(ich==3) mc_event_weight *= lumi*0.004726e03/467.61446;//zll_wlv_vjj
else if(ich==4) mc_event_weight *= lumi*0.014e03/24624.98383; //ttV_3lep
}
void plot() {
char str[200];
initialize();
TString title_sig = "hsig_fw_30_fww_m30";
TChain* ch[6] = {0,0,0,0,0,0};
ch[0] = new TChain("tau");
// ch[0]->Add("../../../rootfiles/test600/ntuple_3lep/S2_red_380.root");
// ch[0]->Add("../../../rootfiles/rhoH_005/ntuple_3lep/S2_red_265.root");
ch[0]->Add("../../../rootfiles/rhoH_005/ntuple_3lep/S2_red_1.root");
Init(ch[0]);
ch[1] = new TChain("tau");
ch[1]->Add("../../../rootfiles/ntuple_merged2/zll_wmlv_red.root");
Init(ch[1]);
ch[2] = new TChain("tau");
ch[2]->Add("../../../rootfiles/ntuple_merged2/zll_wplv_red.root");
Init(ch[2]);
ch[3] = new TChain("tau");
ch[3]->Add("../../../rootfiles/ntuple_merged2/zll_wlv_vjj_red.root");
Init(ch[3]);
ch[4] = new TChain("tau");
ch[4]->Add("../../../rootfiles/ntuple_merged2/ttV_3lep_red.root");
Init(ch[4]);
// sig,bkg
TH1F* h1[50]; TH1F* h2[50]; TH1F* h3[50];
for(Int_t i=0; i<bn->nvar; i++) {
sprintf(str,"h1_var%d",i+1);
h1[i] = new TH1F(str,"",bn->nbin[i],bn->xlo[i],bn->xhi[i]);
sprintf(str,"h2_var%d",i+1);
h2[i] = new TH1F(str,"",bn->nbin[i],bn->xlo[i],bn->xhi[i]);
sprintf(str,"h3_var%d",i+1);
h3[i] = new TH1F(str,"",bn->nbin[i],bn->xlo[i],bn->xhi[i]);
}
TH1F* hh1 = new TH1F("hh1","",100,0,1);
TH1F* hh2 = new TH1F("hh2","",100,0,1);
TH1F* hsig = new TH1F(title_sig,"",40,0,2000);
TH1F* hbkg1 = new TH1F("hbkg1","zll",40,0,2000);
TH1F* hbkg2 = new TH1F("hbkg2","ttV",40,0,2000);
TH1F* hz = new TH1F("hz","",1000,0,10);
TH1F* hmis = new TH1F("hmis","",200,-400,400);
Double_t n_eve[6][5] = {
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0}
};
for(Int_t ich=0; ich<6; ich++) {
if(!ch[ich]) continue;
Int_t numberOfEntries = (Int_t)ch[ich]->GetEntries();
// Loop over all events
printf(" %d entries to be processed\n",numberOfEntries);
for(Int_t entry = 0; entry < numberOfEntries; entry++) {
// Load selected branches with data from specified event
ch[ich]->GetEntry(entry);
if((entry+1)%10000000==0) printf(" %d entries processed\n",entry+1);
calibrate_jet();
calibrate_fatjet();
GetVars(ich);
Float_t pxMiss_truth(0);
Float_t pzMiss_truth(0);
Double_t wt = mc_event_weight;
n_eve[ich][0] += wt;
if(Pass(ich)) {
n_eve[ich][1] += wt;
if(ich==0) hsig->Fill(mHH/GeV,wt);
else if(ich==1||ich==2||ich==3) hbkg1->Fill(mHH/GeV,wt);
else if(ich==4) hbkg2->Fill(mHH/GeV,wt);
for(Int_t i=0; i<bn->nvar; i++) {
if(ich==0) h1[i]->Fill(bn->getVal(i),wt);
else if(ich==1 || ich==2) h2[i]->Fill(bn->getVal(i),wt);
else if(ich==3||ich==4) h3[i]->Fill(bn->getVal(i),wt);
}
if(ich==0) {
if(isFatJet_v3) hh1->Fill(tau21_v3,wt);
if(isFatJet_v3) n_eve[0][2] += wt;
}
else {
if(isFatJet_v3) hh2->Fill(tau21_v3,wt);
if(isFatJet_v3) n_eve[1][2] += wt;
hz->Fill(wt);
}
if(ich==0 && pzMiss_truth!=0) {
hmis->Fill(vec_nu.Pz()/GeV-pzMiss_truth/GeV);
//hmis->Fill(vec_nu.Px()/GeV-pxMiss_truth/GeV);
}
}
}
}
printf("Sig: %.5f %.1f\n",n_eve[0][0],n_eve[0][1]);
printf("Bkg1: %.5f %.1f\n",n_eve[1][0],n_eve[1][1]);
printf("Bkg2: %.5f %.1f\n",n_eve[2][0],n_eve[2][1]);
printf("Bkg3: %.5f %.1f\n",n_eve[3][0],n_eve[3][1]);
printf("Bkg4: %.5f %.1f\n",n_eve[4][0],n_eve[4][1]);
printf("HasFatJet: %.1f(sig) %.1f(bkg)\n",n_eve[0][2],n_eve[1][2]);
printf("significance: %0.3f\n", significance(n_eve[1][1]+n_eve[2][1]+n_eve[3][1]+n_eve[4][1]+n_eve[5][1], n_eve[0][1], 0) );
TLegend* lg = new TLegend(0.62,0.70,0.90,0.89,"");
if(figSigSF==1) sprintf(str,"Signal");
else sprintf(str,"Sig.#times%.1f",figSigSF);
lg->AddEntry(h1[0],"Signal","F");
lg->AddEntry(h2[0],"WZ+jets","F");
lg->AddEntry(h3[0],"other","F");
lg->SetBorderSize(0);
lg->SetMargin(0.25);
lg->SetFillColor(kWhite);
TCanvas* c01 = new TCanvas("c01","c01",600,600);
hh1->SetLineColor(kRed);
hh2->SetLineColor(kBlue);
hh1->Scale(hh2->Integral()/hh1->Integral());
SetMax(hh1,hh2,1.1);
hh1->Draw();
hh2->Draw("same");
TCanvas* c02 = new TCanvas("c02","c02",600,600);
hz->Draw();
TCanvas* c03 = new TCanvas("c03","c03",600,600);
hmis->Draw();
THStack* hsk[50];
TCanvas* cv[50];
for(Int_t i=0; i<bn->nvar; i++) {
h1[i]->Scale(figSigSF);
h1[i]->SetLineColor(kRed);
h1[i]->SetFillColor(kRed);
h2[i]->SetLineColor(kBlue);
h2[i]->SetFillColor(kBlue);
h3[i]->SetLineColor(kGreen);
h3[i]->SetFillColor(kGreen);
sprintf(str,"hsk_var%d",i+1);
hsk[i] = new THStack(str,"");
if(bn->titleX[i]=="m_{VV} [GeV]") {
hsk[i]->Add(h3[i]);
hsk[i]->Add(h2[i]);
hsk[i]->Add(h1[i]);
// hsk[i]->Add(h1[i]);
// hsk[i]->Add(h3[i]);
// hsk[i]->Add(h2[i]);
}
else {
hsk[i]->Add(h1[i]);
hsk[i]->Add(h3[i]);
hsk[i]->Add(h2[i]);
}
sprintf(str,"c%d",i+1);
cv[i] = new TCanvas(str,str,800,600);
hsk[i]->Draw("hist");
hsk[i]->GetXaxis()->SetTitle(bn->titleX[i].c_str());
sprintf(str,"Events/( %4.2f )",h1[i]->GetBinWidth(1));
hsk[i]->GetYaxis()->SetTitle(str);
lg->Draw("same");
// sprintf(str,"c%d.eps",i+1);
// cv[i]->SaveAs(str);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Float_t num_s = 0.5;
Double_t num_s = n_eve[0][1];
Double_t num_bkg = n_eve[1][1]+n_eve[2][1]+n_eve[3][1];
Double_t num_sig_bkg = num_s+n_eve[1][1]+n_eve[2][1]+n_eve[3][1];
TH1F* p_sig = new TH1F("p_sig","",50, 0,50);
TH1F* p_bkg = new TH1F("p_bkg","",50, 0,50);
TH1F* p_sig_bkg = new TH1F("p_sig_bkg","",60,0,60);
for(int i=0; i<30000; i++){
p_sig->Fill(gRandom->PoissonD(num_s));
p_bkg->Fill(gRandom->PoissonD(num_bkg));
p_sig_bkg->Fill(gRandom->PoissonD(num_sig_bkg));
}
Double_t med_sig_bkg, med_bkg, q;
q=0.5;
p_sig_bkg->GetQuantiles(1, &med_sig_bkg, &q);
p_bkg->GetQuantiles(1, &med_bkg, &q);
cout<<"med sig+bkg:"<<med_sig_bkg<<endl;
cout<<"med bkg:"<<med_bkg<<endl;
TCanvas *c1 = new TCanvas("c1","demo quantiles",600,600);
// p_sig_bkg->Draw();
p_bkg->Draw();
// show the quantiles in the bottom pad
///////////p value and significance: med_sig_bkg in bkg poisson
TAxis* axis_bkg = p_bkg->GetXaxis();
int bin_bkg = axis_bkg->FindBin(med_sig_bkg+1);
Double_t inte_bkg = p_bkg->Integral(bin_bkg, 50);
// inte_bkg -= p_bkg->GetBinContent(bin_bkg)*(med_sig_bkg-axis_bkg->GetBinLowEdge(bin_bkg))/axis_bkg->GetBinWidth(bin_bkg);
// Double_t p_value = inte_bkg/p_bkg->Integral();
cout<<"bin:"<<bin_bkg<<";low edge:"<<axis_bkg->GetBinLowEdge(bin_bkg)<<";content:"<<p_bkg->GetBinContent(bin_bkg)<<endl;
//////// CL:1-alpha med_bkg in sig+bkg poisson
TAxis* axis_sig_bkg = p_sig_bkg->GetXaxis();
int bin_sig_bkg = axis_sig_bkg->FindBin(med_bkg);
Double_t inte_sig_bkg = p_sig_bkg->Integral(1, bin_sig_bkg);
// inte_sig_bkg -= p_sig_bkg->GetBinContent(bin_sig_bkg)*(axis_sig_bkg->GetBinUpEdge(bin_sig_bkg)-med_bkg)/axis_sig_bkg->GetBinWidth(bin_sig_bkg);
// Double_t alpha = inte_sig_bkg/p_sig_bkg->Integral();
Double_t alpha = inte_sig_bkg/30000.;
Double_t CL = 1-alpha;
cout<<"CL:"<<CL<<endl;
/////////็ดๆฅ็จๅ
ฌๅผ็ฎsignificanceๅCL////// CL=1-p-value
Double_t pval = ROOT::Math::chisquared_cdf_c(2.*(num_bkg+num_s), 2*(int(med_bkg)+1));
// p-value = ROOT::Math::normal_cdf_c(d_signifi, 1);
Double_t d_signifi = ROOT::Math::normal_quantile_c(pval,1);
Double_t d_CL = ROOT::Math::chisquared_cdf(2.*(num_bkg+num_s), 2*(int(med_bkg)+1));
cout<<"p value:"<<pval<<endl;
cout<<"fomual signi:"<<d_signifi<<endl;
cout<<"fo CL:"<<d_CL<<endl;
cout<<hsig->Integral()<<endl;
cout<<hbkg1->Integral()<<endl;
cout<<hbkg2->Integral()<<endl;
// TFile f1("mHH_600_hist_bkg_3lep_lumi3000.root","recreate");
// // TFile f1("mHH_600_hist_sig.root","recreate");
// // TFile f1("mHH_600_hist_sig.root","update");
// f1.cd();
// // hsig->Write();
// hbkg1->Write();
// hbkg2->Write();
// f1.Close();
}
<file_sep>/TimingMeasurement/A/SubProcesses/P1_qq_zx0_z_bbx_x0_llbbx/coloramps.inc
LOGICAL ICOLAMP(1,24,2)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,2),I=1,1)/.TRUE./
<file_sep>/HC_lljjjj/Source/MODEL/coupl_write.inc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c written by the UFO converter
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
WRITE(*,*) ' Couplings of HC_UFO'
WRITE(*,*) ' ---------------------------------'
WRITE(*,*) ' '
WRITE(*,2) 'GC_6 = ', GC_6
WRITE(*,2) 'GC_7 = ', GC_7
WRITE(*,2) 'GC_8 = ', GC_8
WRITE(*,2) 'GC_10 = ', GC_10
WRITE(*,2) 'GC_11 = ', GC_11
WRITE(*,2) 'GC_12 = ', GC_12
WRITE(*,2) 'GC_13 = ', GC_13
WRITE(*,2) 'GC_62 = ', GC_62
WRITE(*,2) 'GC_64 = ', GC_64
WRITE(*,2) 'GC_65 = ', GC_65
WRITE(*,2) 'GC_1 = ', GC_1
WRITE(*,2) 'GC_2 = ', GC_2
WRITE(*,2) 'GC_16 = ', GC_16
WRITE(*,2) 'GC_66 = ', GC_66
WRITE(*,2) 'GC_77 = ', GC_77
WRITE(*,2) 'GC_78 = ', GC_78
WRITE(*,2) 'GC_89 = ', GC_89
WRITE(*,2) 'GC_90 = ', GC_90
WRITE(*,2) 'GC_100 = ', GC_100
WRITE(*,2) 'GC_38 = ', GC_38
WRITE(*,2) 'GC_40 = ', GC_40
WRITE(*,2) 'GC_42 = ', GC_42
WRITE(*,2) 'GC_68 = ', GC_68
<file_sep>/TimingMeasurement/B/SubProcesses/P1_bbx_zx0_z_tamtap_x0_qqqq/maxamps.inc
INTEGER MAXAMPS, MAXFLOW, MAXPROC, MAXSPROC
PARAMETER (MAXAMPS=10, MAXFLOW=2)
PARAMETER (MAXPROC=6, MAXSPROC=2)
<file_sep>/rw_lljjjj/SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/coloramps.inc
LOGICAL ICOLAMP(2,3,40)
DATA(ICOLAMP(I,1,1),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,2,1),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,3,3),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,3,8),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,3,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,13),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,3,13),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,3,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,18),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,3,18),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,1,19),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,2,19),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,1,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,21),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,2,21),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,1,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,23),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,3,23),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,3,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,28),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,3,28),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,3,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,33),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,3,33),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,3,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,38),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,3,38),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,1,39),I=1,2)/.TRUE.,.FALSE./
DATA(ICOLAMP(I,2,39),I=1,2)/.FALSE.,.TRUE./
DATA(ICOLAMP(I,1,40),I=1,1)/.TRUE./
<file_sep>/TimingMeasurement/A/SubProcesses/P1_bbx_zx0_z_qq_x0_tamtapqq/coloramps.inc
LOGICAL ICOLAMP(1,48,6)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,6),I=1,1)/.TRUE./
<file_sep>/LHC_HH_2lep_rw/SubProcesses/P7_qq_wphh_wp_qq_hh_llqq/coloramps.inc
LOGICAL ICOLAMP(1,1,64)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,64),I=1,1)/.TRUE./
<file_sep>/TimingMeasurement/B/Source/maxamps.inc
../SubProcesses/P3_bbx_zx0_z_tamtap_x0_tapvlqq/maxamps.inc<file_sep>/TimingMeasurement/D/Source/maxconfigs.inc
INTEGER LMAXCONFIGS
PARAMETER(LMAXCONFIGS=392)
<file_sep>/TimingMeasurement/C/Source/nexternal.inc
../SubProcesses/P3_qq_wpwpwm_wp_tapvl_wp_tapvl_wm_qq/nexternal.inc<file_sep>/fit_code/FitOneBin/fit_com_1.cc
#include "TFile.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TCanvas.h"
#include "TMath.h"
#include "TH1F.h"
#include "TCanvas.h"
#include "TLine.h"
#include "RooArgSet.h"
#include "RooArgList.h"
#include "RooProduct.h"
#include "RooDataSet.h"
#include "RooDataHist.h"
#include "RooRealVar.h"
#include "RooCategory.h"
#include "RooAddPdf.h"
#include "RooHistPdf.h"
#include "RooCategory.h"
#include "RooSimultaneous.h"
#include "RooPlot.h"
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <vector>
#include <sstream> //istringstream
#include "../Elizabeth.h"
using namespace std;
using namespace RooFit;
string to_string(int val) {
char buf[200];
sprintf(buf, "%d", val);
return string(buf);
}
void plot() {
ofstream fout("alpha_1.txt");
fout<<"file"<<" "<<""<<"mass"<<" "<<"fw"<<" "<<"fww"<<" "<<"alpha"<<" "<<"sigma1"<<" "<<"sigma2"<<endl;
ifstream fr("../../parameter/param_2lep900.txt");
if(!fr.is_open()){
cout<<"unable to open file"<<endl;
}
vector<string> vec;
Double_t cs;
Double_t fw;
Double_t fww;
Double_t mass;
Int_t num;
Int_t i=0;
while(!fr.eof()) //while ๅพช็ฏ
{
string temp;
getline(fr, temp, '\n');
vec.push_back(temp);
i ++;
}
int Row=0; //่ก
// //for(auto it=vec.begin(); it != vec.end(); it++)
for(std::vector<string>::iterator it=vec.begin(); it != vec.end(); it++)
{
// cout << *it << endl;
istringstream is(*it);
string s;
Row++;
num=0;
int column=0; //ๅ
//if( (Row>1 && Row<46) ){
if( (Row>1 && Row<7) ){
while(is>>s)
{
if(column == 0 )
{
num=atof(s.c_str());
}
if(column == 1 )
{
mass=atof(s.c_str());
}
if(column == 2 )
{
fw=atof(s.c_str());
}
if(column == 3 )
{
fww=atof(s.c_str());
}
if(column == 4 )
{
cs=atof(s.c_str());
}
column++;
}
string s_fw = to_string(int(fabs(fw)));
string s_fww = to_string(int(fabs(fww)));
string in_fw = "";
string in_fww = "";
if(fw<0.) in_fw = "m";
if(fww<0.) in_fww = "m";
TString hist_sig_name = "hsig_fw_"+in_fw+s_fw+"_fww_"+in_fww+s_fww;
cout<<"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<:"<<hist_sig_name<<endl;
char str[200];
TFile *file_2_bkg = TFile::Open("../../ntuple/mHH_900_hist_bkg_2lep_up.root");
if (!file_2_bkg) return;
TFile *file_2_sig = TFile::Open("../../ntuple/mHH_900_sig_2lep_005.root");//30,40,50,60,70
if (!file_2_sig) return;
TH1F* hsig_1 = (TH1F*) file_2_sig->Get(hist_sig_name);
TH1F* hbkg_1 = (TH1F*) file_2_bkg->Get("hbkg1");
hsig_1->Scale(140./300.);
hbkg_1->Scale(140./300.);
hsig_1->SetName("hsig_1");
hbkg_1->SetName("hbkg_1");
hsig_1->SetDirectory(0);
hbkg_1->SetDirectory(0);
Double_t nsig_exp_1 = hsig_1->Integral();
Double_t nbkg_exp_1 = hbkg_1->Integral();
//TH1F* hOneBin_sig_1 = new TH1F("hOneBin_sig_1","",1,0,1);
// hOneBin_sig_1->SetBinContent(1,nsig_exp_1);
//TH1F* hOneBin_bkg_1 = new TH1F("hOneBin_bkg_1","",1,0,1);
// hOneBin_bkg_1->SetBinContent(1,nbkg_exp_1);
TFile *file_3_bkg = TFile::Open("../../ntuple/mHH_900_hist_bkg_3lep.root");
if (!file_3_bkg) return;
TFile *file_3_sig = TFile::Open("../../ntuple/mHH_900_sig_3lep_005.root");//30,40,50,60
if (!file_3_sig) return;
TH1F* hsig_2 = (TH1F*) file_3_sig->Get(hist_sig_name);
TH1F* hbkg_2 = (TH1F*) file_3_bkg->Get("hbkg1");
TH1F* hbkg2_2 = (TH1F*) file_3_bkg->Get("hbkg2");
hsig_2->Scale(140./300.);
hbkg_2->Scale(140./300.);
hbkg2_2->Scale(140./300.);
hsig_2->SetName("hsig_2");
hbkg_2->SetName("hbkg_2");
hbkg2_2->SetName("hbkg2_2");
hsig_2->SetDirectory(0);
hbkg_2->SetDirectory(0);
hbkg2_2->SetDirectory(0);
hbkg_2->Add(hbkg2_2);
Double_t nsig_exp_2 = hsig_2->Integral();
Double_t nbkg_exp_2 = hbkg_2->Integral();
////////////////////////// www ////////////
TFile *file_4_bkg = TFile::Open("../../ntuple/mHH_900_hist_bkg_www.root");
if (!file_4_bkg) return;
TFile *file_4_sig = TFile::Open("../../ntuple/mHH_900_sig_www_005.root");//30,40,50,60
if (!file_4_sig) return;
TH1F* hsig_3 = (TH1F*) file_4_sig->Get(hist_sig_name);
TH1F* hbkg_3 = (TH1F*) file_4_bkg->Get("hbkg1");
TH1F* hbkg2_3 = (TH1F*) file_4_bkg->Get("hbkg2");
TH1F* hbkg3_3 = (TH1F*) file_4_bkg->Get("hbkg3");
hsig_3->Scale(140./300.);
hbkg_3->Scale(140./300.);
hbkg2_3->Scale(140./300.);
hbkg3_3->Scale(140./300.);
hsig_3->SetName("hsig_3");
hbkg_3->SetName("hbkg_3");
hbkg2_3->SetName("hbkg2_3");
hbkg3_3->SetName("hbkg3_3");
hsig_3->SetDirectory(0);
hbkg_3->SetDirectory(0);
hbkg2_3->SetDirectory(0);
hbkg3_3->SetDirectory(0);
hbkg_3->Add(hbkg2_3);
hbkg_3->Add(hbkg3_3);
Double_t nsig_exp_3 = hsig_3->Integral();
Double_t nbkg_exp_3 = hbkg_3->Integral();
Double_t nsig_exp = nsig_exp_1 + nsig_exp_2 + nsig_exp_3;
Double_t nbkg_exp = nbkg_exp_1 + nbkg_exp_2 + nbkg_exp_3;
TH1F* hOneBin_sig = new TH1F("hOneBin_sig","",1,0,1);
hOneBin_sig->SetBinContent(1,nsig_exp);
TH1F* hOneBin_bkg = new TH1F("hOneBin_bkg","",1,0,1);
hOneBin_bkg->SetBinContent(1,nbkg_exp);
//////////////////////////////////////////
RooRealVar mVV("mVV","m_{VV} [GeV]",0,1);
mVV.setBins(hOneBin_sig->GetNbinsX());
RooRealVar weight("weight","",0,200);
RooCategory cat("cat","");;
cat.defineType("total");
RooDataHist dsig_1("dsig_1","",RooArgList(mVV),hOneBin_sig);
RooDataHist dbkg_1("dbkg_1","",RooArgList(mVV),hOneBin_bkg);
RooHistPdf psig_1("psig_1","",RooArgSet(mVV),dsig_1);
RooHistPdf pbkg_1("pbkg_1","",RooArgSet(mVV),dbkg_1);
RooRealVar nsig_1_("nsig_1_","",nsig_exp);
RooRealVar nbkg_1("nbkg_1","",nbkg_exp);
RooRealVar mu("mu","",-3,3);
RooProduct nsig_1("nsig_1","",RooArgList(nsig_1_,mu));
RooAddPdf* p1 = new RooAddPdf("p1","",RooArgList(pbkg_1,psig_1),RooArgList(nbkg_1,nsig_1));
RooSimultaneous pall("pall","",cat) ;//facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
pall.addPdf(*p1,"total") ;
TH1F* h1 = new TH1F("h1","",600,-3,3);
TH1F* h2 = new TH1F("h2","",600,-3,3);
mu.setVal(1);
nbkg_1.setVal(nbkg_exp);
RooDataSet* d1;
RooDataSet* dall;
RooArgSet* pars1 = (RooArgSet*) p1->getParameters(RooArgSet(mVV))->snapshot();
///ๅฏน2lepๅ3lepไฝไธบไธคไธชsubset๏ผ็จRooCategoryๅบๅไธคไธชๅญ้๏ผfit็ๆถๅๆฏไธคไธชๅญ้ๅๅซfit
Int_t ntoy = 10000;
for(Int_t i=0; i<ntoy; i++) {
(*p1->getParameters(RooArgSet(mVV))) = (*pars1);
mu.setVal(0);
d1 = p1->generate(RooArgSet(mVV),AutoBinned(true),Extended());
dall = new RooDataSet("dall","",RooArgSet(mVV,cat,weight),WeightVar("weight"));
for(Int_t i=0; i<d1->numEntries(); i++) {
const RooArgSet* row = d1->get(i);
cat.setLabel("total");
RooRealVar* var = (RooRealVar*) row->find("mVV");
mVV.setVal(var->getVal());
dall->add(RooArgSet(mVV,cat),d1->weight());
}
pall.fitTo(*dall,Extended(true),SumW2Error(true));
if(mu.getVal()<h1->GetXaxis()->GetXmin()) h1->Fill(h1->GetXaxis()->GetXmin());
else if(mu.getVal()>=h1->GetXaxis()->GetXmax()) h1->Fill(h1->GetXaxis()->GetXmax()*0.999);
else h1->Fill(mu.getVal());
delete d1;
delete dall;
(*p1->getParameters(RooArgSet(mVV))) = (*pars1);
mu.setVal(1);
d1 = p1->generate(RooArgSet(mVV),AutoBinned(true),Extended());
dall = new RooDataSet("dall","",RooArgSet(mVV,cat,weight),WeightVar("weight"));
for(Int_t i=0; i<d1->numEntries(); i++) {
const RooArgSet* row = d1->get(i);
cat.setLabel("total");
RooRealVar* var = (RooRealVar*) row->find("mVV");
mVV.setVal(var->getVal());
dall->add(RooArgSet(mVV,cat),d1->weight());
}
pall.fitTo(*dall,Extended(true),SumW2Error(true));
if(mu.getVal()<h2->GetXaxis()->GetXmin()) h2->Fill(h2->GetXaxis()->GetXmin());
else if(mu.getVal()>=h2->GetXaxis()->GetXmax()) h2->Fill(h2->GetXaxis()->GetXmax()*0.999);
else h2->Fill(mu.getVal());
delete d1;
delete dall;
}
Double_t ptmp = SUSYStat_Pval(1);
Double_t xq[3] = {ptmp,0.5,1-ptmp};
Double_t yq[3];
h1->GetQuantiles(3,yq,xq);
printf("yq[1] = %f\n",yq[1]);
TCanvas* c1 = new TCanvas("c1","c1",600,600);
c1->SetLogy();
h1->Draw();
TLine* line1lo = new TLine(yq[0],0,yq[0],h1->GetMaximum());
line1lo->SetLineWidth(1);
line1lo->SetLineColor(kRed);
line1lo->SetLineStyle(2);
line1lo->Draw();
TLine* line1 = new TLine(yq[1],0,yq[1],h1->GetMaximum());
line1->SetLineWidth(2);
line1->SetLineColor(kRed);
line1->Draw();
TLine* line1hi = new TLine(yq[2],0,yq[2],h1->GetMaximum());
line1hi->SetLineWidth(1);
line1hi->SetLineColor(kRed);
line1hi->SetLineStyle(2);
line1hi->Draw();
// c1->SaveAs(hist_sig_name+"_h1_.eps");
TCanvas* c2 = new TCanvas("c2","c2",600,600);
c2->SetLogy();
h2->Draw();
TLine* line2lo = new TLine(yq[0],0,yq[0],h2->GetMaximum());
line2lo->SetLineWidth(1);
line2lo->SetLineColor(kRed);
line2lo->SetLineStyle(2);
line2lo->Draw();
TLine* line2 = new TLine(yq[1],0,yq[1],h2->GetMaximum());
line2->SetLineWidth(2);
line2->SetLineColor(kRed);
line2->Draw();
TLine* line2hi = new TLine(yq[2],0,yq[2],h2->GetMaximum());
line2hi->SetLineWidth(1);
line2hi->SetLineColor(kRed);
line2hi->SetLineStyle(2);
line2hi->Draw();
// c2->SaveAs(hist_sig_name+"_h2_.eps");
printf("%f %f %f\n",h2->Integral(1,h2->FindBin(yq[0]))/ntoy,h2->Integral(1,h2->FindBin(yq[1]))/ntoy,h2->Integral(1,h2->FindBin(yq[2]))/ntoy);
Double_t alpha = h2->Integral(1,h2->FindBin(yq[1]))/ntoy;
Double_t sigma1 = h2->Integral(1,h2->FindBin(yq[0]))/ntoy;
Double_t sigma2 = h2->Integral(1,h2->FindBin(yq[2]))/ntoy;
fout<<num<<" "<<mass<<" "<<fw<<" "<<fww<<" "<<alpha<<" "<<sigma1<<" "<<sigma2<<endl;
}
}
}
<file_sep>/TimingMeasurement/C/SubProcesses/P2_qq_wpx0_wp_tapvl_x0_tamtapbbx/coloramps.inc
LOGICAL ICOLAMP(1,25,4)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,4),I=1,1)/.TRUE./
<file_sep>/PROCNLO_HC_NLO_X0_UFO_0_3/Source/MODEL/input.inc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c written by the UFO converter
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
DOUBLE PRECISION MDL_SQRT__AS,MDL_G__EXP__2,MDL_G__EXP__4
$ ,MDL_R2MIXEDFACTOR_FIN_,MDL_GWCFT_UV_B_1EPS_
$ ,MDL_GWCFT_UV_T_1EPS_,MDL_BWCFT_UV_1EPS_,MDL_TWCFT_UV_1EPS_
$ ,MDL_G__EXP__3,MDL_MU_R__EXP__2,MDL_GWCFT_UV_B_FIN_
$ ,MDL_GWCFT_UV_T_FIN_,MDL_BWCFT_UV_FIN_,MDL_TWCFT_UV_FIN_
$ ,MDL_GAGG,MDL_GHGG,MDL_CKM11,MDL_CONJG__CKM3X3,MDL_CONJG__CKM11
$ ,MDL_LHV,MDL_CKM3X3,MDL_CONJG__CKM33,MDL_NCOL,MDL_CA,MDL_TF
$ ,MDL_CF,MDL_MZ__EXP__2,MDL_MZ__EXP__4,MDL_SQRT__2
$ ,MDL_MX0__EXP__2,MDL_COSA__EXP__2,MDL_SINA,MDL_NB__2__EXP__0_75
$ ,MDL_NCOL__EXP__2,MDL_MB__EXP__2,MDL_MT__EXP__2,MDL_AEW
$ ,MDL_SQRT__AEW,MDL_EE,MDL_MW__EXP__2,MDL_SW2,MDL_CW
$ ,MDL_SQRT__SW2,MDL_SW,MDL_G1,MDL_GW,MDL_VEV,MDL_VEV__EXP__2
$ ,MDL_LAM,MDL_YB,MDL_YT,MDL_YTAU,MDL_MUH,MDL_AXIALZUP
$ ,MDL_AXIALZDOWN,MDL_VECTORZUP,MDL_VECTORZDOWN,MDL_VECTORAUP
$ ,MDL_VECTORADOWN,MDL_VECTORWMDXU,MDL_AXIALWMDXU,MDL_VECTORWPUXD
$ ,MDL_AXIALWPUXD,MDL_EE__EXP__2,MDL_GAAA,MDL_CW__EXP__2,MDL_GAZA
$ ,MDL_GHAA,MDL_GHZA,MDL_GW__EXP__2,MDL_SW__EXP__2,AEWM1,MDL_GF
$ ,AS,MDL_YMB,MDL_YMT,MDL_YMTAU,MDL_LAMBDA,MDL_COSA,MDL_KSM
$ ,MDL_KHTT,MDL_KATT,MDL_KHBB,MDL_KABB,MDL_KHLL,MDL_KALL,MDL_KHAA
$ ,MDL_KAAA,MDL_KHZA,MDL_KAZA,MDL_KHZZ,MDL_KAZZ,MDL_KHWW,MDL_KAWW
$ ,MDL_KHDA,MDL_KHDZ,MDL_KHDWR,MDL_KHDWI
COMMON/PARAMS_R/ MDL_SQRT__AS,MDL_G__EXP__2,MDL_G__EXP__4
$ ,MDL_R2MIXEDFACTOR_FIN_,MDL_GWCFT_UV_B_1EPS_
$ ,MDL_GWCFT_UV_T_1EPS_,MDL_BWCFT_UV_1EPS_,MDL_TWCFT_UV_1EPS_
$ ,MDL_G__EXP__3,MDL_MU_R__EXP__2,MDL_GWCFT_UV_B_FIN_
$ ,MDL_GWCFT_UV_T_FIN_,MDL_BWCFT_UV_FIN_,MDL_TWCFT_UV_FIN_
$ ,MDL_GAGG,MDL_GHGG,MDL_CKM11,MDL_CONJG__CKM3X3,MDL_CONJG__CKM11
$ ,MDL_LHV,MDL_CKM3X3,MDL_CONJG__CKM33,MDL_NCOL,MDL_CA,MDL_TF
$ ,MDL_CF,MDL_MZ__EXP__2,MDL_MZ__EXP__4,MDL_SQRT__2
$ ,MDL_MX0__EXP__2,MDL_COSA__EXP__2,MDL_SINA,MDL_NB__2__EXP__0_75
$ ,MDL_NCOL__EXP__2,MDL_MB__EXP__2,MDL_MT__EXP__2,MDL_AEW
$ ,MDL_SQRT__AEW,MDL_EE,MDL_MW__EXP__2,MDL_SW2,MDL_CW
$ ,MDL_SQRT__SW2,MDL_SW,MDL_G1,MDL_GW,MDL_VEV,MDL_VEV__EXP__2
$ ,MDL_LAM,MDL_YB,MDL_YT,MDL_YTAU,MDL_MUH,MDL_AXIALZUP
$ ,MDL_AXIALZDOWN,MDL_VECTORZUP,MDL_VECTORZDOWN,MDL_VECTORAUP
$ ,MDL_VECTORADOWN,MDL_VECTORWMDXU,MDL_AXIALWMDXU,MDL_VECTORWPUXD
$ ,MDL_AXIALWPUXD,MDL_EE__EXP__2,MDL_GAAA,MDL_CW__EXP__2,MDL_GAZA
$ ,MDL_GHAA,MDL_GHZA,MDL_GW__EXP__2,MDL_SW__EXP__2,AEWM1,MDL_GF
$ ,AS,MDL_YMB,MDL_YMT,MDL_YMTAU,MDL_LAMBDA,MDL_COSA,MDL_KSM
$ ,MDL_KHTT,MDL_KATT,MDL_KHBB,MDL_KABB,MDL_KHLL,MDL_KALL,MDL_KHAA
$ ,MDL_KAAA,MDL_KHZA,MDL_KAZA,MDL_KHZZ,MDL_KAZZ,MDL_KHWW,MDL_KAWW
$ ,MDL_KHDA,MDL_KHDZ,MDL_KHDWR,MDL_KHDWI
DOUBLE COMPLEX MDL_COMPLEXI,MDL_KHDW,MDL_CONJG__KHDW,MDL_I1X33
$ ,MDL_I2X33,MDL_I3X33,MDL_I4X33,MDL_VECTOR_TBGP,MDL_AXIAL_TBGP
$ ,MDL_VECTOR_TBGM,MDL_AXIAL_TBGM
COMMON/PARAMS_C/ MDL_COMPLEXI,MDL_KHDW,MDL_CONJG__KHDW,MDL_I1X33
$ ,MDL_I2X33,MDL_I3X33,MDL_I4X33,MDL_VECTOR_TBGP,MDL_AXIAL_TBGP
$ ,MDL_VECTOR_TBGM,MDL_AXIAL_TBGM
<file_sep>/rw_lljjjj/Source/nexternal.inc
../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/nexternal.inc<file_sep>/HC_lljjjj/Source/nexternal.inc
../SubProcesses/P1_qq_zx0_z_ll_x0_qqqq/nexternal.inc<file_sep>/TimingMeasurement/D/SubProcesses/P1_qq_wmx0_wm_qq_x0_tamtapqq/coloramps.inc
LOGICAL ICOLAMP(1,12,64)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,17),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,18),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,19),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,20),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,21),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,22),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,23),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,24),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,25),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,26),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,27),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,28),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,29),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,30),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,31),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,32),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,33),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,34),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,35),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,36),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,37),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,38),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,39),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,40),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,41),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,42),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,43),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,44),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,45),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,46),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,47),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,48),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,49),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,50),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,51),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,52),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,53),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,54),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,55),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,56),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,57),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,58),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,59),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,60),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,61),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,62),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,63),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,64),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,64),I=1,1)/.TRUE./
<file_sep>/TimingMeasurement/D/SubProcesses/P2_qq_wmx0_wm_tamvl_x0_llbbx/mirrorprocs.inc
DATA (MIRRORPROCS(I),I=1,4)/.TRUE.,.TRUE.,.TRUE.,.TRUE./
<file_sep>/TimingMeasurement/D/SubProcesses/P1_qq_wmx0_wm_qq_x0_tamtapbbx/coloramps.inc
LOGICAL ICOLAMP(1,25,16)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,5),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,6),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,7),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,8),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,9),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,10),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,11),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,12),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,13),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,14),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,15),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,16),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,16),I=1,1)/.TRUE./
<file_sep>/TimingMeasurement/B/SubProcesses/P2_bbx_zx0_z_tamtap_x0_lvlqq/coloramps.inc
LOGICAL ICOLAMP(1,4,4)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,3),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,4),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,4),I=1,1)/.TRUE./
<file_sep>/rw_lljjjj/Source/leshouche.inc
../SubProcesses/P1_qq_zhh_z_ll_hh_qqqq/leshouche.inc<file_sep>/TimingMeasurement/A/SubProcesses/P1_qq_zx0_z_bbx_x0_tamtapbbx/coloramps.inc
LOGICAL ICOLAMP(1,50,2)
DATA(ICOLAMP(I,1,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,49,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,50,1),I=1,1)/.TRUE./
DATA(ICOLAMP(I,1,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,2,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,3,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,4,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,5,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,6,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,7,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,8,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,9,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,10,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,11,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,12,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,13,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,14,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,15,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,16,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,17,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,18,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,19,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,20,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,21,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,22,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,23,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,24,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,25,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,26,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,27,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,28,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,29,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,30,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,31,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,32,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,33,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,34,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,35,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,36,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,37,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,38,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,39,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,40,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,41,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,42,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,43,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,44,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,45,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,46,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,47,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,48,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,49,2),I=1,1)/.TRUE./
DATA(ICOLAMP(I,50,2),I=1,1)/.TRUE./
| d7a3e57e211cdec1f5b9493c86d2ee70c2af2f0f | [
"SQL",
"HTML",
"Markdown",
"C",
"C++",
"Shell"
] | 89 | SQL | xuyue1231/MG5-heavy-Higgs | 8c1b8b0dd3ec79a297130ac2dc2ae38df7c08b07 | a3752e7da5d4e37a85bea3c0e26a468103d71d02 |
refs/heads/main | <file_sep>// task : create singly linked list
// language : c++
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
class linkedList {
public:
Node* head, *temp;
linkedList() {
head = NULL;
}
void addNode(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = NULL;
if(head == NULL) {
head = newNode;
temp = newNode;
}
else {
temp->next = newNode;
temp = newNode;
}
}
void displayList() {
Node* ptr = head;
while(ptr != NULL) {
cout << ptr->data << " ";
ptr = ptr->next;
}
}
};
int main() {
linkedList List;
int size;
cout << "enter size of list: ";
cin >> size;
int data;
while(size--) {
cout << "enter data: ";
cin >> data;
List.addNode(data);
}
List.displayList();
return 0;
}
<file_sep>// task : check weather given number is prime or not.
#include <iostream>
using namespace std;
bool isPrime(int num) {
bool isPrime = true;
if( num == 0 || num == 1)
isPrime = false;
for(int i = 2; i <= num/2; i++) {
if(num % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
int main() {
int num;
cout << "enter a number: ";
cin >> num;
if(isPrime(num))
cout << num << " is a prime number." << endl;
else
cout << num << " is not a prime number." << endl;
return 0;
}
| 24d9303cea326d4049fd69417244f8e8bb0bb396 | [
"C++"
] | 2 | C++ | Shree-2301/cpp_projects | 4ba17acce3498c678620aaee15232ddc2b70915e | 3a2b286c7862f3cfcd38407bab71a20224364eb4 |
refs/heads/main | <repo_name>alfreddo98/Network-Projects<file_sep>/mp3/receiver_main.c
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <pthread.h>
#include "buffers.c"
int create_socket();
void *get_in_addr(struct sockaddr *sa);
void reliablyReceive(unsigned short int myUDPport, char* destinationFile);
void * write_to_file(void * params);
void * send_acks(void * unusedParam);
pthread_mutex_t buf_lock = PTHREAD_MUTEX_INITIALIZER; // This locks the buffer across threads. Prevents data collisions.
pthread_mutex_t soc_lock = PTHREAD_MUTEX_INITIALIZER; // This locks the buffer across threads. Prevents data collisions.
int sock;
char done = NO;
payload_t ack;
struct sockaddr_in senderaddr;
int senderaddr_len;
unsigned short int udpPort;
int main(int argc, char** argv)
{
if(argc != 3)
{
fprintf(stderr, "usage: %s UDP_port filename_to_write\n\n", argv[0]);
exit(1);
}
udpPort = (unsigned short int)atoi(argv[1]);
create_socket();
reliablyReceive(udpPort, argv[2]);
close(sock);
}
int create_socket(){
struct sockaddr_in bindAddr;
memset(&bindAddr, 0, sizeof(bindAddr));
sock = socket(AF_INET, SOCK_DGRAM, 0);
// struct timeval read_timeout;
// read_timeout.tv_sec = 0;
// read_timeout.tv_usec = 10;
// setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &read_timeout, sizeof read_timeout);
bindAddr.sin_family = AF_INET;
bindAddr.sin_port = htons(udpPort);
bindAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sock, (struct sockaddr*)&bindAddr, sizeof(struct sockaddr_in)) < 0)
{
perror("bind");
close(sock);
exit(1);
}
}
void *get_in_addr(struct sockaddr *sa){
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
payload_t * recv_payload(){
payload_t * buffer;
int count = 0;
buffer = (payload_t *) malloc(sizeof(payload_t)); // alocate a buffer to read file data into
// receive something
recvfrom(sock, buffer, sizeof(*buffer), 0, (struct sockaddr *) &senderaddr, &senderaddr_len);
pthread_mutex_lock(&buf_lock);
return buffer;
}
void reliablyReceive(unsigned short int myUDPport, char* destinationFile) {
payload_t * buffer;
int result;
int ret;
unsigned short recv_len;
senderaddr_len = sizeof(senderaddr);
// Start file write thread
pthread_t fileThread;
pthread_create(&fileThread, 0, write_to_file, (void*)destinationFile);
while(1){
// insert received packet:
buffer = recv_payload();
result = buffer_insert(buffer);
recv_len = buffer->length;
buffer->length = 0;
sendto(sock, buffer, 4, 0, (struct sockaddr *) &senderaddr, senderaddr_len);
buffer->length = recv_len;
pthread_mutex_unlock(&buf_lock);
}
}
void * write_to_file(void * params){
payload_t * buffer;
int total_packets;
FILE * fhandle = fopen((char *)params, "w");
if (!fhandle)
perror("File open failed.");
while (1){
pthread_mutex_lock(&buf_lock);
buffer = buffer_to_be_written();
pthread_mutex_unlock(&buf_lock);
if (buffer){
if (buffer->length == 0){
done = YES;
total_packets = buffer->seqNum;
break;
}
fwrite(&(buffer->data), 1, buffer->length, fhandle);
pthread_mutex_lock(&buf_lock);
buffer_mark_written(buffer->seqNum);
pthread_mutex_unlock(&buf_lock);
}
if (done){
break;
}
}
fflush(fhandle);
fclose(fhandle);
printf("Total Packets: %d\n", total_packets);
printf("Duplicate Packets: %u\n", duplicates);
exit(0);
}<file_sep>/OneDrive/Documentos/group5-master/mp2/helper_fns.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define recvBufSize (8 * 256 * 2) + 30 // extra 30 is for the ttl and just some padding in case.
#define YES 1
#define NO 0
// Define the log events --CdG
#define EVT_FWD 1
#define EVT_SND 2
#define EVT_REC 3
#define EVT_UNR 4
// define min macro
#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
int globalMyID;
//last time you heard from each node.
struct timeval globalLastHeartbeat[256];
int newly_down[256];
int network_size = 1;
//our all-purpose UDP socket, to be bound to 10.1.1.globalMyID, port 7777
int globalSocketUDP;
//pre-filled for sending to 10.1.1.0 - 255, port 7777
struct sockaddr_in globalNodeAddrs[256];
// Keeps track of costs and up hosts that are connected to it: --CdG
struct neighboor_cost {
unsigned int cost;
unsigned short up;
};
struct neighboor_cost neighboors[256];
// Routing Table: If I want to route to some host, the next host to forward to is at the index of the destination host.
// -1 if there is no route to that host. -- CdG
short routing_table[256];
// File descriptor for the logfile:
FILE * log_fd;
// Function Declarations:
extern void init_router(char ** argv);
extern int fetchPacket(char * recvBuf);
extern int handleNonTopoPackets(char * recvBuf);
extern void* announceToNeighbors(void* unusedParam);
extern int updateCost(char recvBuf[recvBufSize]);
extern int checkDownNeighboors();
extern int markNeighboorUp(unsigned short ID);
extern int markNeighboorDown(unsigned short ID);
extern void logEvent(short type, short dest, short next, char* msg);
extern void routeMessage(char * recvBuf, short send);
extern void sendPacket(char * buf, unsigned int len, short destID);
// Initializes and sets up connections for router
void init_router(char ** argv){
//initialization: get this process's node ID, record what time it is,
//and set up our sockaddr_in's for sending to the other nodes.
globalMyID = 0; // just in case
globalMyID = atoi(argv[1]);
int i;
for(i=0;i<256;i++)
{
gettimeofday(&globalLastHeartbeat[i], 0);
char tempaddr[100];
sprintf(tempaddr, "10.1.1.%d", i);
memset(&globalNodeAddrs[i], 0, sizeof(globalNodeAddrs[i]));
globalNodeAddrs[i].sin_family = AF_INET;
globalNodeAddrs[i].sin_port = htons(7777);
inet_pton(AF_INET, tempaddr, &globalNodeAddrs[i].sin_addr);
// init the neighboors struct: -- CdG
neighboors[i].cost = 1;
neighboors[i].up = NO;
// init the routing table to have no valid routes: -- CdG
routing_table[i] = -1;
}
// Set up log file descriptor:
log_fd = fopen(argv[3], "w");
// Read and parse initial costs file. default to cost 1 if no entry for a node. file may be empty. --CdG
// Credit: https://www.programiz.com/c-programming/examples/read-file
FILE * costs_fd;
unsigned int host;
unsigned int cost;
costs_fd = fopen(argv[2], "r");
if (costs_fd == NULL){
perror("Invalid costs file.");
exit(1);
}
while (fscanf(costs_fd, "%u %u [^\n]", &host, &cost) != EOF){ // read a line from the file
neighboors[host].cost = cost; // update the cost
}
neighboors[globalMyID].cost = 0; // costs 0 to send to myself
fclose(costs_fd);
//socket() and bind() our socket. We will do all sendto()ing and recvfrom()ing on this one.
if((globalSocketUDP=socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
exit(1);
}
char myAddr[100];
struct sockaddr_in bindAddr;
sprintf(myAddr, "10.1.1.%d", globalMyID);
memset(&bindAddr, 0, sizeof(bindAddr));
bindAddr.sin_family = AF_INET;
bindAddr.sin_port = htons(7777);
inet_pton(AF_INET, myAddr, &bindAddr.sin_addr);
if(bind(globalSocketUDP, (struct sockaddr*)&bindAddr, sizeof(struct sockaddr_in)) < 0)
{
perror("bind");
close(globalSocketUDP);
exit(1);
}
}
// Fetches a packet. --CdG
int fetchPacket(char * recvBuf){
int bytesRecvd;
int retval = 0;
char fromAddr[100];
struct sockaddr_in theirAddr;
socklen_t theirAddrLen;
theirAddrLen = sizeof(theirAddr);
if ((bytesRecvd = recvfrom(globalSocketUDP, recvBuf, 10000 , 0,
(struct sockaddr*)&theirAddr, &theirAddrLen)) == -1)
{
perror("connectivity listener: recvfrom failed");
exit(1);
}
// String delimeter:
recvBuf[bytesRecvd] = '\0';
inet_ntop(AF_INET, &theirAddr.sin_addr, fromAddr, 100);
short int heardFrom = -1;
if(strstr(fromAddr, "10.1.1."))
{
heardFrom = atoi(
strchr(strchr(strchr(fromAddr,'.')+1,'.')+1,'.')+1);
// Mark the neighboor as connected: --CdG
if (!neighboors[heardFrom].up){
markNeighboorUp(heardFrom);
retval = 1;
}
//record that we heard from heardFrom just now.
gettimeofday(&globalLastHeartbeat[heardFrom], 0);
}
return retval;
}
// Handles non topography related packets
// Ie send, recieve, forward, cost
// Returns 0 if no costs changed.
// Returns 1 if a cost was changed. --CdG
int handleNonTopoPackets(char * recvBuf){
int retval = 0;
//Is it a packet from the manager? (see mp2 specification for more details)
//send format: 'send'<4 ASCII bytes>, destID<net order 2 byte signed>, <some ASCII message>
if(!strncmp(recvBuf, "send", 4))
{
// send the requested message to the requested destination node --CdG
routeMessage(recvBuf, YES);
}
//'cost'<4 ASCII bytes>, destID<net order 2 byte signed> newCost<net order 4 byte signed>
else if(!strncmp(recvBuf, "cos", 3))
{
updateCost(recvBuf);
retval = 1;
}
//forward format: 'fwrd'<4 ASCII bytes>, destID<net order 2 byte signed>, <some ASCII message>
else if(!strncmp(recvBuf, "fwrd", 4))
{
// Forward packets via the table, or receive it if it is addressed to you -- CdG
routeMessage(recvBuf, NO);
}
return retval;
}
//Yes, this is terrible. It's also terrible that, in Linux, a socket
//can't receive broadcast packets unless it's bound to INADDR_ANY,
//which we can't do in this assignment.
void hackyBroadcast(const char* buf, int length)
{
int i;
for(i=0;i<256;i++)
if(i != globalMyID) //(although with a real broadcast you would also get the packet yourself)
sendto(globalSocketUDP, buf, length, 0,
(struct sockaddr*)&globalNodeAddrs[i], sizeof(globalNodeAddrs[i]));
}
void* announceToNeighbors(void* unusedParam)
{
struct timespec sleepFor;
sleepFor.tv_sec = 0;
sleepFor.tv_nsec = 700 * 1000 * 1000; //900 ms
// Make this thread max priority
struct sched_param params;
pthread_t this_thread = pthread_self();
params.sched_priority = sched_get_priority_max(SCHED_FIFO);
pthread_setschedparam(this_thread, SCHED_FIFO, ¶ms);
while(1)
{
hackyBroadcast("H", 1);
nanosleep(&sleepFor, 0);
}
}
// UPdates the cost of a link given the message from the manager --CdG
int updateCost(char recvBuf[recvBufSize]){
// record the cost change (remember, the link might currently be down! in that case,
// this is the new cost you should treat it as having once it comes back up.)
// Yeah, this is nasty I know: --CdG
signed short destID = ntohs(*(short*)(&recvBuf[4]));
signed int newCost = ntohl(*(int*)(&recvBuf[6]));
if (destID > 255) // out of bounds
return -1; // failure
neighboors[destID].cost = newCost;
if (recvBuf[3] == 't'){
// Tell the neighboor that my cost has changed too: (make it bidirectional)
recvBuf[3] = 's'; // so that the neighboor knows not to send this back.
(*(short*)(&recvBuf[4])) = htons(globalMyID); // make me the node.
sendPacket(recvBuf, recvBufSize, destID);
}
return 0; // success
}
// Checks to see if any neighboors have become down.
// Returns 0 for no change in topography.
// Returns the number of neighboors that went down otherwise. --CdG
int checkDownNeighboors(int network_size){
int i, j = 0;
struct timeval now;
struct timeval then;
long delta;
gettimeofday(&now, 0);
for (i = 0; i < 256; i++){
then = globalLastHeartbeat[i];
// If last heartbeat was more than a second ago, mark as down:
delta = ((now.tv_sec - then.tv_sec) * 1000000) + (now.tv_usec - then.tv_usec);
if ((network_size < 50 && delta >= 950000) || (network_size >= 50 && delta >= 1250000) || (network_size >= 150 && delta >= 1750000)){
if (neighboors[i].up){
markNeighboorDown(i);
newly_down[j] = i;
j++;
}
}
}
return j;
}
// Mark a neighboor as up. --CdG
// Returns 0 if neighboor was already up.
// Returns 1 if the neighboor is newly up.
int markNeighboorUp(unsigned short ID){
int retval = 0;
if (ID > 255) // make sure it's valid.
return 0;
if (neighboors[ID].up == NO)
retval = 1;
neighboors[ID].up = YES;
// routing_table[ID] = ID; // Route directly to this node.
return retval;
}
// Mark a neighboor as down. --CdG
// Returns 0 if neighboor was already down.
// Returns 1 if the neighboor is newly down.
int markNeighboorDown(unsigned short ID){
int retval = 0;
if (ID > 255) // make sure it's valid.
return 0;
if (neighboors[ID].up == YES)
retval = 1;
neighboors[ID].up = NO;
return retval;
}
// Logs event to file:
// General purpose, the args that aren't used for a given log entry can be anything, probably easiest to just make them 0.
// type {EVT_FWD, EVT_SND, EVT_REC, EVT_UNR}: Type of event to log
// dest : destination node
// next: next node to forward to
// msg: string message to log --CdG
void logEvent(short type, short dest, short next, char* msg){
char log_buf[256]; // Bigger than it needs to be but just in case.
switch(type){
case EVT_FWD: // Forward Event
sprintf(log_buf, "forward packet dest %d nexthop %d message %s\n", dest, next, msg);
break;
case EVT_REC: // Receive Event
sprintf(log_buf, "receive packet message %s\n", msg);
break;
case EVT_SND: // Send Event
sprintf(log_buf, "sending packet dest %d nexthop %d message %s\n", dest, next, msg);
break;
case EVT_UNR: // Dest Unreachable Event
sprintf(log_buf, "unreachable dest %d\n", dest);
break;
default: return; // type was invalid return now.
}
fputs(log_buf, log_fd);
fflush(log_fd); //Immediately write this to the file.
}
// Routes a given Message
// Inputs: Send: Yes if a send NO if a forward.
// Cases: Destination is itself - logs that it recieved.
// Destination is in the routing table and it forwards it.
// Destination is unreachable. --CdG
void routeMessage(char * recvBuf, short send){
signed short destID = ntohs(*(short*)(&recvBuf[4]));
char * msg = &recvBuf[6];
if (destID == globalMyID){ // I am the destination
logEvent(EVT_REC, destID, 0, msg);
return;
}
signed short next_node = routing_table[destID];
if (next_node == -1){ // Destination is unreachable
logEvent(EVT_UNR, destID, 0, NULL);
return;
}
// Forward the packet:
if (send == YES) {
recvBuf[0] = 'f';recvBuf[1] = 'w';recvBuf[2] = 'r';recvBuf[3] = 'd'; // convert this to a forward packet if it is a send.
logEvent(EVT_SND, destID, next_node, msg);
}
else {
logEvent(EVT_FWD, destID, next_node, msg);
}
// Actual packet send here:
sendPacket(recvBuf, recvBufSize, next_node);
}
// Sends a packet in buf to the host with the dest ID. --CdG
// len = max length of buffer to send
void sendPacket(char * buf, unsigned int len, short destID){
// From manager_send.c:
struct sockaddr_in destAddr;
char tempaddr[100];
sprintf(tempaddr, "10.1.1.%d", destID);
memset(&destAddr, 0, sizeof(destAddr));
destAddr.sin_family = AF_INET;
destAddr.sin_port = htons(7777);
inet_pton(AF_INET, tempaddr, &destAddr.sin_addr);
sendto(globalSocketUDP, buf, len, 0, (struct sockaddr*)&destAddr, sizeof(destAddr));
}
<file_sep>/OneDrive/Documentos/group5-master/mp2/ls_router.c
// Router that Implements LS Routing
// alfredo7 | cdgerth2
#include <pthread.h>
#include <time.h>
#include <inttypes.h>
#include <math.h>
#include "helper_fns.c"
// Declaration of locks and condition for advertisement
pthread_cond_t advr_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t advr_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t neighboor_lock = PTHREAD_MUTEX_INITIALIZER;
int advr_reasess = YES; // locked by advr_lock
int topo_reasses = NO;
int mySeqNum = 0;
int recent_up = YES;
// Declaration of locks and condition for dijk
pthread_cond_t dijk_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t dijkcond_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t dijk_lock = PTHREAD_MUTEX_INITIALIZER;
struct topology {
int seqNum;
int connectedTo[256];
int cost[256];
char in_topo;
};
// struct holding the current topology:
struct topology currentTopo[256];
// DIJK Vars:
char visited[256];
unsigned int dists[256];
unsigned int nearest[256];
// Function Declarations
void handleTopoPackets(char * recvBuf);
void * advertiseLS(void* unusedParam);
void * reasessTopo(void* unusedParam);
void dijk();
int main(int argcount, char ** args){
int i, j;
if(argcount != 4)
{
fprintf(stderr, "Usage: %s mynodeid initialcostsfile logfile\n\n", args[0]);
exit(1);
}
// Perform all the initialization steps.
init_router(args);
// Start announce pthread
pthread_t announcerThread;
pthread_create(&announcerThread, 0, announceToNeighbors, (void*)0);
// Start link state advertisment thread
pthread_t advertismentThread;
pthread_create(&advertismentThread, 0, advertiseLS, (void*)0);
// Start dijk background worker
pthread_t dijkThread;
pthread_create(&dijkThread, 0, reasessTopo, (void*)0);
// Init topology
for (i=0; i<256; i++){
currentTopo[i].seqNum = -1;
for (j=0; j<256; j++){
currentTopo[i].connectedTo[j] = -1;
currentTopo[i].cost[j] = 1;
currentTopo[i].in_topo = NO;
}
}
// put myself in the topology
currentTopo[globalMyID].in_topo = YES;
// Handle packets here ...
unsigned char recvBuf[recvBufSize];
int retval;
while(1)
{
// pthread_mutex_lock(&neighboor_lock); // don't advertise while we update neighboors
retval = fetchPacket(recvBuf); // get the packet.
// pthread_mutex_unlock(&neighboor_lock);
if (retval){ // wake the advertisement thread if needed.
pthread_mutex_lock(&advr_lock);
advr_reasess = YES;
pthread_mutex_unlock(&advr_lock);
printf("N");
if (mySeqNum > 2)
recent_up = YES;
}
pthread_mutex_lock(&neighboor_lock); // don't advertise while we update neighboors
retval = checkDownNeighboors(network_size); // will have to do something with this retval eventually
pthread_mutex_unlock(&neighboor_lock);
if (retval){ // wake the advertisement thread if needed.
pthread_mutex_lock(&advr_lock);
advr_reasess = YES;
pthread_mutex_unlock(&advr_lock);
printf("D");
}
pthread_mutex_lock(&neighboor_lock); // don't advertise while we update neighboors
pthread_mutex_lock(&dijk_lock); // Don't forward a packet while we are updating the routing table.
retval = handleNonTopoPackets(recvBuf);
pthread_mutex_unlock(&dijk_lock);
pthread_mutex_unlock(&neighboor_lock); // don't advertise while we update neighboors
if (retval){ // wake the advertisement thread if needed.
pthread_mutex_lock(&advr_lock);
advr_reasess = YES;
pthread_mutex_unlock(&advr_lock);
}
pthread_mutex_lock(&advr_lock);
if (advr_reasess)
pthread_cond_signal(&advr_cond);
pthread_mutex_unlock(&advr_lock);
handleTopoPackets(recvBuf);
}
//(should never reach here)
fclose(log_fd);
close(globalSocketUDP);
return 0;
}
void handleTopoPackets(char * recvBuf){
// TODO: Handle packets that signal a change in topography.
if(!strncmp(recvBuf, "advr", 4))
{
int i, h;
char changed = NO;
int j = 4 + sizeof(int);
int hostID = *(int*)(&recvBuf[4]);
int seqNum = *((int*)&recvBuf[j]);
j += sizeof(unsigned int);
// we had a loop so drop and don't do any more flooding
if (seqNum <= currentTopo[hostID].seqNum)
return;
// set the sequence number:
currentTopo[hostID].seqNum = seqNum;
//if we have a packet, the node is in the topo.
currentTopo[hostID].in_topo = YES;
pthread_mutex_lock(&dijk_lock); // do not update table WHILE we are rerunning dijkstra's
i = 0;
// pull out the connected hosts:
while (j < recvBufSize){
if (*((unsigned int *)&recvBuf[j]) == 0)
break;
if (currentTopo[hostID].cost[i] != *((unsigned int *)&recvBuf[j])){
changed = YES;
currentTopo[hostID].cost[i] = *((unsigned int *)&recvBuf[j]);
}
j += sizeof(unsigned int);
if (currentTopo[hostID].connectedTo[i] != (unsigned char)recvBuf[j]){
currentTopo[currentTopo[hostID].connectedTo[i]].seqNum = -1;
currentTopo[hostID].seqNum = -1;
changed = YES;
currentTopo[hostID].connectedTo[i] = (unsigned char)recvBuf[j];
}
i++;
j++;
}
if (currentTopo[hostID].connectedTo[i] != -1){
changed = YES;
currentTopo[hostID].seqNum = -1;
}
j += sizeof(int);
// Finish out the rest of it.
for (; i<256; i++)
if (currentTopo[hostID].connectedTo[i] != -1){
currentTopo[currentTopo[hostID].connectedTo[i]].seqNum = -1;
currentTopo[hostID].connectedTo[i] = -1;
}
else break;
pthread_mutex_unlock(&dijk_lock);
if (changed || recent_up){
usleep((globalMyID * 4) % 777);
// Forward this packet:
for (i=0; i<256; i++){
if (neighboors[i].up)
sendPacket(recvBuf, j, i);
}
}
// recompute the routing table.
if (changed){
pthread_mutex_lock(&dijkcond_lock);
pthread_cond_signal(&dijk_cond);
topo_reasses = YES;
pthread_mutex_unlock(&dijkcond_lock);
}
}
}
void * advertiseLS(void* unusedParam){
unsigned short i;
int j;
int offset;
char packetBuf[recvBufSize];
packetBuf[0] = 'a'; packetBuf[1] = 'd'; packetBuf[2] = 'v'; packetBuf[3] = 'r';
*((int*)&packetBuf[4]) = globalMyID;
struct timespec relTime;
struct timespec now;
pthread_mutex_lock(&advr_lock);
advr_reasess = YES;
pthread_mutex_unlock(&advr_lock);
// sleep for random amount of time to avoid flooding the network on startup:
// sleep(1);
while(1)
{
// Advertise the current link state to the neighboors
*((int*)&packetBuf[8]) = mySeqNum;
if (advr_reasess){
pthread_mutex_lock(&neighboor_lock); // don't read an incomplete neighboors block.
pthread_mutex_lock(&advr_lock);
advr_reasess = NO;
pthread_mutex_unlock(&advr_lock);
j = 4 + sizeof(globalMyID) + sizeof(mySeqNum);
for (i=0; i<256; i++){
if (neighboors[i].up){
*((unsigned int *)&packetBuf[j]) = neighboors[i].cost;
j += sizeof(unsigned int);
*((unsigned short *)&packetBuf[j]) = i;
j++;
}
}
pthread_mutex_unlock(&neighboor_lock);
*((unsigned int *)&packetBuf[j]) = 0; // End Sentinel
j += sizeof(unsigned int);
printf("x");
fflush(stdout);
}
for (i=0; i<256; i++){
if (neighboors[i].up)
sendPacket(packetBuf, j, i);
}
// increment the sequence number
mySeqNum++;
clock_gettime(CLOCK_REALTIME, &now);
relTime.tv_nsec = now.tv_nsec;
relTime.tv_sec = now.tv_sec + 2;
// Block until either: change in topology or 1 seconds is up.
pthread_mutex_lock(&advr_lock);
if (!advr_reasess)
pthread_cond_timedwait(&advr_cond, &advr_lock, &relTime);
pthread_mutex_unlock(&advr_lock);
// Rest for a bit to not just attack the network all at once:
sleep(1);
// if (network_size > 100){
// sleep(1);
// }
// if (network_size > 70){
// sleep(1.5);
// }
}
}
// Recomputes the routing table given the current Link states
void * reasessTopo(void * unusedParam){
int i;
struct timespec relTime;
struct timespec now;
while (1){
pthread_mutex_lock(&dijkcond_lock);
// Wait on the condition var:
pthread_cond_wait(&dijk_cond, &dijkcond_lock);
topo_reasses = NO;
pthread_mutex_unlock(&dijkcond_lock);
// Now wait a second in case a bunch of things just changed to avoid redoing this algorithm an obscene numer of times:
while (1){
clock_gettime(CLOCK_REALTIME, &now);
relTime.tv_nsec = now.tv_nsec;
relTime.tv_sec = now.tv_sec + 1;
pthread_mutex_lock(&dijkcond_lock);
pthread_cond_timedwait(&dijk_cond, &dijkcond_lock, &relTime);
if (!topo_reasses){
pthread_mutex_unlock(&dijkcond_lock);
break;
} else {
recent_up = NO;
topo_reasses = NO;
pthread_mutex_unlock(&dijkcond_lock);
}
}
pthread_mutex_lock(&dijk_lock);
printf(".");
fflush(stdout);
// None visited
memset(visited, NO, 256);
// Max dists
memset(dists, 0x77, 256 * sizeof(unsigned int));
dists[globalMyID] = 0;
// Reset Routing table
memset(routing_table, 0xFF, 256 * sizeof(short));
// Reset Nearest:
memset(nearest, 0x77, 256 * sizeof(int));
nearest[globalMyID] = globalMyID;
// Distance to self is 0.
dists[globalMyID] = 0;
network_size = 0;
// Run Dijkstra's
dijk(globalMyID);
pthread_mutex_unlock(&dijk_lock);
}
// Never gets here.
}
// Runs dijkstra's algorithm and returns the best next path to some node
// returns the next node that should be used to get to the given dest.
void dijk(int node){
int i, j, minNeighbor;
int neighboor;
network_size++;
// Mark the tentative distance so far:
for (i=0; i<256; i++){
neighboor = (int)currentTopo[node].connectedTo[i];
if (neighboor == -1){
if (i==0)
network_size--;
break;
}
// base case of if we are processing the root node.
if (node == globalMyID){
routing_table[neighboor] = neighboor;
dists[neighboor] = neighboors[neighboor].cost;
nearest[neighboor] = globalMyID;
continue;
}
// Update tentative costs:
if ((unsigned int)(dists[node] + currentTopo[node].cost[i]) < dists[neighboor]){
dists[neighboor] = dists[node] + currentTopo[node].cost[i];
routing_table[neighboor] = routing_table[node];
nearest[neighboor] = node;
}
else if ((unsigned int)(dists[node] + currentTopo[node].cost[i]) == dists[neighboor]){ // check for if smaller ID
if (node != globalMyID && (node < nearest[neighboor])){
routing_table[neighboor] = routing_table[node];
nearest[neighboor] = node;
}
}
}
// Mark the node as visited
visited[node] = YES;
for (j=0; j<256; j++){
minNeighbor = -1;
// Find the minimum neighboor that has not been visited:
for (neighboor=0; neighboor<256; neighboor++){
if (visited[neighboor] == NO && currentTopo[neighboor].in_topo){
if (minNeighbor == -1)
minNeighbor = neighboor;
else if (dists[neighboor] < dists[minNeighbor])
minNeighbor = neighboor;
else if ((dists[neighboor] == dists[minNeighbor]) && (neighboor < minNeighbor))
minNeighbor = neighboor;
}
}
// we have visited all the neighboors
if (minNeighbor == -1)
return;
// Recurse down on the neighboor:
dijk(minNeighbor);
}
// Never Gets here
return;
}<file_sep>/mp3/Makefile
all: reliable_sender reliable_receiver
reliable_sender:
gcc -g3 -pthread -o reliable_sender sender_main.c -Dsender
reliable_receiver:
gcc -g3 -pthread -o reliable_receiver receiver_main.c -Dreceiver
clean:
@rm -f reliable_sender reliable_receiver *.o
<file_sep>/mp3/buffers.c
// Holds the data structures and functions for the send and receive buffers.
// cdgerth2 alfredo7
// Comment out this next line to turn off verbosity of the buffer system:
// #define verbose
// #define sender
// Includes:
#include <time.h>
// Compiler Macros:
#if defined sender
#define BUF_SIZE 80000
#define BURST_SIZE 5
#define MAX_DELAY (700000 * BURST_SIZE)
#define HIGHER_DELAY (650000 * BURST_SIZE)
#define HIGH_DELAY (600000 * BURST_SIZE)
#define MED_DELAY (400000 * BURST_SIZE)
#define LOW_DELAY (200000 * BURST_SIZE)
#define LOWER_DELAY (150000 * BURST_SIZE)
#define MIN_DELAY (100000 * BURST_SIZE)
#endif
#if defined receiver
#define BUF_SIZE 100000
#endif
// #define MAX_SIZE 1468
#define MAX_SIZE 1468
#define YES 1
#define NO 0
#define TRUE 1
#define FALSE 0
#define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
// Data Structures:
typedef struct payload_t{
unsigned short length;
unsigned short seqNum;
char data[MAX_SIZE];
}payload_t;
typedef struct buffer_node {
struct timespec expires; // time the packet was sent -- unused for the receive buffer
struct timespec time_sent; // time the packet was sent -- unused for the receive buffer
unsigned short seqNum; // Sequence number of the given packet
unsigned short len; // Length of the data in the payload
unsigned char processed; // boolean for if the packet has been acked or written to file, depending on which implementation
payload_t * payload; // Pointer to the dynamically allocated payload
} buffer_node;
static struct buffer_node ring_buffer[BUF_SIZE]; // Define the buffer itself
#if defined sender
static unsigned short oldest_seq_not_acked;
static int newest_seq_sent;
static unsigned long send_delay; // Amount of useconds to wait in between each packet with the aim of keeping the buffer half full
static unsigned long average_rtt; // Holds the average RTT of packets
static unsigned long average_throughput; // Holds the throughput in packets / sec that can be handled by the link
unsigned int fail_count;
static int gain_count;
static unsigned int no_drops;
static char current_speed;
static float average_fail_count;
unsigned int resent;
static struct timespec last_speed_change;
#endif
#if defined receiver
static unsigned short oldest_seq_not_written;
static unsigned short newest_seq_received;
unsigned int duplicates;
#endif
// Function Declarations:
// Call this at the beginning of the program -- resets the buffers.
extern void init_buffers();
// Buffer Access
// Returns a pointer to the buffer node associated with the given sequence number.
// Inputs: sequence number to query
// Output: Pointer to the buffer node
extern buffer_node * buffer_access(unsigned short seqNum);
// Sender only Functions:
#if defined sender
// Buffer Insert
// Inserts data to the buffer (data meaning raw data from the file). Assumes data will be immediately sent.
// Inputs: pointer to the payload with everything filled in except for the sequence number.
// BIG NOTE: Leave the header space at the beginning of raw data -> ie file data shoould start 4B into the buffer. This way we can reuse it as the payload.
// Outputs: The sequence number of the newly created node.
extern int buffer_insert(payload_t * payload);
// Buffer Mark Acked
// Marks packet as acknowledged and frees the memory associated with the payload.
// Inputs: sequence number
// Outputs: none
extern void buffer_mark_acked(unsigned short seqNum);
// Buffer To be Resent
// Returns a pointer to the node of a packet that should be resent if one exists, null if otherwise
// Inputs: none
// Outpus: pointer to the payload that should be resent.
extern payload_t * buffer_to_be_resent();
// returns the current send delay to be implemented in us.
extern void current_send_delay();
// returns true if every packet sent has been acked or false otherwise
extern unsigned char sender_done();
#endif
// Receiver only Functions:
#if defined receiver
// Buffer Insert
// Inserts data to the buffer (data meaning raw payload from the internet)
// Inputs: pointer to the internet data and the number of bytes of this data
// Outputs: The sequence number of the newly created node. (or -1 if buffer overflow)
extern int buffer_insert(payload_t * payload);
// Buffer To be Written
// Returns a pointer to the node of a packet that is ready to be written to file, if it exists.
// Inputs: none
// Outputs: pointer to the buffer node to be written to file.
extern payload_t * buffer_to_be_written();
// Buffer Mark Written
// Once the data is written to the file, call this to free up the memory.
// Inputs: sequence number of node to be freed
// Outputs: none
extern void buffer_mark_written(unsigned short seqNum);
unsigned char receiver_done();
extern short int seqs_done();
#endif
extern void init_buffers(){
int i;
#if defined sender
oldest_seq_not_acked = 0;
newest_seq_sent = -1;
average_rtt = 4000000; // 40 ms
average_throughput = 13000000; //1000 Mbps
fail_count = 0;
gain_count = 0;
current_speed = 4;
average_fail_count = 1;
no_drops = 0;
resent = 0;
clock_gettime(0, &last_speed_change);
#endif
#if defined receiver
oldest_seq_not_written = 0;
newest_seq_received = 0;
duplicates = 0;
#endif
for (i = 0; i < BUF_SIZE; i++){
ring_buffer[i].len = 0;
ring_buffer[i].payload = NULL;
ring_buffer[i].processed = YES;
ring_buffer[i].seqNum = i;
ring_buffer[i].time_sent.tv_sec = 0;
ring_buffer[i].time_sent.tv_nsec = 0;
ring_buffer[i].expires.tv_sec = 0;
ring_buffer[i].expires.tv_nsec = 0;
}
}
extern buffer_node * buffer_access(unsigned short seqNum){
#if defined sender
if (seqNum > newest_seq_sent || seqNum < oldest_seq_not_acked){
#if defined verbose
printf("Invalid buffer access: SEQ(%d).\n", seqNum);
#endif
return NULL;
}
#endif
#if defined receiver
if (seqNum > newest_seq_received || seqNum < oldest_seq_not_written){
#if defined verbose
printf("Invalid buffer access: SEQ(%d).\n", seqNum);
#endif
return NULL;
}
#endif
// Return the actual element:
return &(ring_buffer[seqNum % BUF_SIZE]);
}
// Sender only Functions:
#if defined sender
extern int buffer_insert(payload_t * payload){
if ((newest_seq_sent != -1) && ((newest_seq_sent - oldest_seq_not_acked) == (BUF_SIZE - 1))){
#if defined verbose
printf("Buffer Overflow (%d) (%lu).\n", newest_seq_sent, average_rtt);
#endif
average_throughput -= 1000;
if (average_throughput < 10000)
average_throughput = 10000;
return -1;
}
newest_seq_sent++;
payload->seqNum = newest_seq_sent;
ring_buffer[newest_seq_sent % BUF_SIZE].processed = NO;
ring_buffer[newest_seq_sent % BUF_SIZE].len = payload->length;
ring_buffer[newest_seq_sent % BUF_SIZE].seqNum = newest_seq_sent;
ring_buffer[newest_seq_sent % BUF_SIZE].payload = payload;
clock_gettime(0, &ring_buffer[newest_seq_sent % BUF_SIZE].time_sent);
clock_gettime(0, &ring_buffer[newest_seq_sent % BUF_SIZE].expires);
ring_buffer[newest_seq_sent % BUF_SIZE].expires.tv_nsec = (ring_buffer[newest_seq_sent % BUF_SIZE].expires.tv_nsec + average_rtt * 2) % 1000000000;
ring_buffer[newest_seq_sent % BUF_SIZE].expires.tv_sec += (ring_buffer[newest_seq_sent % BUF_SIZE].expires.tv_nsec + average_rtt * 2) / 1000000000;
return newest_seq_sent;
}
extern void buffer_mark_acked(unsigned short seqNum){
struct timespec now;
long difference;
if (seqNum > newest_seq_sent || seqNum < oldest_seq_not_acked){
#if defined verbose
printf("Invalid buffer node acked: SEQ(%d). (%lu)\n", seqNum, average_rtt);
#endif
return;
}
ring_buffer[seqNum % BUF_SIZE].processed = YES;
// printf("Fails: %d\n", fail_count);
if (fail_count < 3)
fail_count = 0;
if (fail_count == 0)
no_drops++;
else
no_drops = 0;
average_fail_count = ((float)average_fail_count * (float)0.99) + ((float)fail_count * (float)0.01);
if (no_drops == 100 && average_fail_count < 0.35){
struct timespec now;
clock_gettime(0, &now);
if (now.tv_sec > last_speed_change.tv_sec + 1){
current_speed++;
average_fail_count = 2;
clock_gettime(0, &last_speed_change);
}
}
if (average_fail_count > 3.5){
struct timespec now;
clock_gettime(0, &now);
if (now.tv_sec > last_speed_change.tv_sec + 1){
current_speed--;
average_fail_count = 0.3;
clock_gettime(0, &last_speed_change);
}
}
if (current_speed < 0)
current_speed = 0;
else if (current_speed > 6)
current_speed = 6;
fail_count = 0;
clock_gettime(0, &now);
difference = ((1000000000 * (now.tv_sec - ring_buffer[seqNum % BUF_SIZE].time_sent.tv_sec)) + (now.tv_nsec - ring_buffer[seqNum % BUF_SIZE].time_sent.tv_nsec)); // calculate the difference in us
if (difference <= 0)
difference = average_rtt;
if (((long)difference - (long)10000000) >= (long)average_rtt)
gain_count--;
else if (((long)difference + (long)30000000) <= (long)average_rtt)
gain_count++;
average_rtt = (float)(0.99) * (float)average_rtt + (float)(0.01) * (float)difference; //make the averge rtt take into acount the past rtt
free(ring_buffer[seqNum % BUF_SIZE].payload); // free the memory
ring_buffer[seqNum % BUF_SIZE].payload = NULL; // delete the invalid pointer
// if this was the oldest record, then increment
while (ring_buffer[oldest_seq_not_acked % BUF_SIZE].processed
&& oldest_seq_not_acked < (newest_seq_sent))
oldest_seq_not_acked++;
}
extern payload_t * buffer_to_be_resent(){
struct timespec now;
long difference;
int i;
clock_gettime(0, &now);
for (i=oldest_seq_not_acked; i <= newest_seq_sent; i++){
difference = ((1000000000 * (now.tv_sec - ring_buffer[i % BUF_SIZE].expires.tv_sec)) + (now.tv_nsec - ring_buffer[i % BUF_SIZE].expires.tv_nsec));
// if (difference > 5000000000){
// printf("Receiver went down.\n");
// exit(1);
// }
if ((difference > 0) && ring_buffer[i % BUF_SIZE].processed == NO){
fail_count++;
#if defined verbose
printf("Packet (%d) was lost.\n", i);
#endif
if (gain_count < 0)
gain_count /= 1.1;
average_throughput -= 100;
clock_gettime(0, &ring_buffer[i % BUF_SIZE].time_sent);
clock_gettime(0, &ring_buffer[i % BUF_SIZE].expires);
ring_buffer[i % BUF_SIZE].expires.tv_nsec = (ring_buffer[i % BUF_SIZE].expires.tv_nsec + average_rtt * 2) % 1000000000;
ring_buffer[i % BUF_SIZE].expires.tv_sec += (ring_buffer[i % BUF_SIZE].expires.tv_nsec + average_rtt * 2) / 1000000000;
resent++;
return ring_buffer[i % BUF_SIZE].payload;
}
}
return NULL;
}
extern void current_send_delay(){
struct timespec wait_time;
unsigned long delay;
char speed;
// if (gain_count > 200)
// speed = current_speed - 1;
// else
speed = current_speed;
printf("Gain: %d; RTT: %lu; Loss: %f; Speed: %d\n", gain_count, average_rtt, average_fail_count, current_speed);
switch(speed){
case 0: delay = MAX_DELAY; break;
case 1: delay = HIGHER_DELAY; break;
case 2: delay = HIGH_DELAY; break;
case 3: delay = MED_DELAY; break;
case 4: delay = LOW_DELAY; break;
case 5: delay = LOWER_DELAY; break;
case 6: delay = MIN_DELAY; break;
default: delay = MAX_DELAY; break;
};
wait_time.tv_nsec = delay % 10000000000;
wait_time.tv_sec = delay / 10000000000;
#if defined verbose
printf("PPS: %llu DELAY: %ld WAIT: %lu\n", pps, delay, wait_time.tv_nsec);
#endif
nanosleep(&wait_time, NULL);
return;
}
unsigned char sender_done(){
if (oldest_seq_not_acked == (newest_seq_sent))
return TRUE;
else
return FALSE;
}
#endif
#if defined receiver
extern int buffer_insert(payload_t * payload){
unsigned short seq_num;
seq_num = payload->seqNum; // pull out the sequence number from the payload
if (seq_num < oldest_seq_not_written){ // this is a duplicate and we can disregard it
#if defined verbose
printf("Duplicate packet (%d).\n", seq_num);
#endif
duplicates++;
return -1;
}
if (seq_num - oldest_seq_not_written >= BUF_SIZE){
#if defined verbose
printf("Buffer overflow Seq(%d).\n", seq_num);
#endif
return -2;
}
newest_seq_received = MAX(seq_num, newest_seq_received); // update the newest sequence recieved
ring_buffer[seq_num % BUF_SIZE].seqNum = seq_num;
ring_buffer[seq_num % BUF_SIZE].len = payload->length;
ring_buffer[seq_num % BUF_SIZE].processed = NO;
ring_buffer[seq_num % BUF_SIZE].payload = payload;
return seq_num;
}
extern payload_t * buffer_to_be_written(){
if (ring_buffer[oldest_seq_not_written % BUF_SIZE].processed == YES){ // if we have not received it yet then return null
return NULL;
}
return ring_buffer[(oldest_seq_not_written) % BUF_SIZE].payload; // otherwise send back the thing that we can now write.
}
extern void buffer_mark_written(unsigned short seqNum){
if (seqNum != oldest_seq_not_written){ // we should only have written the oldest piece that hasn't yet been put into the file
#if defined verbose
printf("Invalid mark written (%d).\n", seqNum);
#endif
}
if (ring_buffer[seqNum % BUF_SIZE].payload) // make sure we are not freeing a null pointer
free(ring_buffer[seqNum % BUF_SIZE].payload); // free the memory
ring_buffer[seqNum % BUF_SIZE].processed = YES; // mark as written
oldest_seq_not_written++; // increment the oldest not written
}
extern short int seqs_done(){
if (oldest_seq_not_written > 0)
return oldest_seq_not_written - 1;
else
return 0;
}
extern unsigned char receiver_done(){
if (oldest_seq_not_written == newest_seq_received)
return TRUE;
else
return FALSE;
}
#endif<file_sep>/OneDrive/Documentos/group5-master/mp2/up_down_test.sh
#!/bin/bash
# Pick one of these to test:
# exe="./ls_router"
exe="./vec_router"
echo "Launching routers."
cp ${exe} ${exe}_tmp
sudo perl utility/make_topology.pl utility/8x8gridtopo.txt
for ((num = 0; $num < 78; num++))
do
if (($num % 10 == 8 || $num % 10 == 9 || $num == 1 || $num == 15 || $num == 23 || $num == 30 || $num == 42 || $num == 57 || $num == 61 || $num == 5 || $num == 76 || $num == 73 || $num == 45)); then continue; fi
${exe} $num /dev/null logs/$num.log &
done
for ((num = 0; $num < 78; num++))
do
if (($num % 10 == 8 || $num % 10 == 9)); then continue; fi
if (($num == 1 || $num == 15 || $num == 23 || $num == 30 || $num == 42 || $num == 57 || $num == 61 || $num == 5 || $num == 76 || $num == 73 || $num == 45))
then
${exe}_tmp $num /dev/null logs/$num.log &
fi
done
while ((1))
do
read -p "Press enter to take down half the grid."
pkill vec_router_tmp
pkill ls_router_tmp
read -p "Press enter to put it back."
for ((num = 0; $num < 78; num++))
do
if (($num % 10 == 8 || $num % 10 == 9)); then continue; fi
if (($num == 1 || $num == 15 || $num == 23 || $num == 30 || $num == 42 || $num == 57 || $num == 61 || $num == 5 || $num == 76 || $num == 73 || $num == 45))
then
${exe}_tmp $num /dev/null logs/$num.log &
fi
done
read -p "Press enter to end."
done
pkill vec_router_tmp
pkill ls_router_tmp
pkill vec_router
pkill ls_router
rm ${exe}_tmp<file_sep>/OneDrive/Documentos/group5-master/mp2/partition_grid.sh
#!/bin/bash
# Pick one of these to test:
# exe="./ls_router"
exe="./vec_router"
echo "Launching routers."
# do this on a 10x10
sudo perl utility/make_topology.pl utility/10x10gridtopo.txt
for ((num = 0; $num < 100; num++))
do
$exe $num /dev/null logs/$num.log &
done
read -p "Press enter to sever the grid."
# Sever Grid:
sudo iptables -D OUTPUT -s 10.1.1.3 -d 10.1.1.4 -j ACCEPT ; sudo iptables -D OUTPUT -s 10.1.1.4 -d 10.1.1.3 -j ACCEPT
sudo iptables -D OUTPUT -s 10.1.1.13 -d 10.1.1.14 -j ACCEPT ; sudo iptables -D OUTPUT -s 10.1.1.14 -d 10.1.1.13 -j ACCEPT
sudo iptables -D OUTPUT -s 10.1.1.23 -d 10.1.1.24 -j ACCEPT ; sudo iptables -D OUTPUT -s 10.1.1.24 -d 10.1.1.23 -j ACCEPT
sudo iptables -D OUTPUT -s 10.1.1.33 -d 10.1.1.34 -j ACCEPT ; sudo iptables -D OUTPUT -s 10.1.1.34 -d 10.1.1.33 -j ACCEPT
sudo iptables -D OUTPUT -s 10.1.1.43 -d 10.1.1.44 -j ACCEPT ; sudo iptables -D OUTPUT -s 10.1.1.44 -d 10.1.1.43 -j ACCEPT
sudo iptables -D OUTPUT -s 10.1.1.53 -d 10.1.1.54 -j ACCEPT ; sudo iptables -D OUTPUT -s 10.1.1.54 -d 10.1.1.53 -j ACCEPT
sudo iptables -D OUTPUT -s 10.1.1.63 -d 10.1.1.64 -j ACCEPT ; sudo iptables -D OUTPUT -s 10.1.1.64 -d 10.1.1.63 -j ACCEPT
sudo iptables -D OUTPUT -s 10.1.1.73 -d 10.1.1.74 -j ACCEPT ; sudo iptables -D OUTPUT -s 10.1.1.74 -d 10.1.1.73 -j ACCEPT
sudo iptables -D OUTPUT -s 10.1.1.83 -d 10.1.1.84 -j ACCEPT ; sudo iptables -D OUTPUT -s 10.1.1.84 -d 10.1.1.83 -j ACCEPT
sudo iptables -D OUTPUT -s 10.1.1.93 -d 10.1.1.94 -j ACCEPT ; sudo iptables -D OUTPUT -s 10.1.1.94 -d 10.1.1.93 -j ACCEPT
read -p "Press enter to heal the grid."
# Heal Grid:
sudo iptables -I OUTPUT -s 10.1.1.3 -d 10.1.1.4 -j ACCEPT ; sudo iptables -I OUTPUT -s 10.1.1.4 -d 10.1.1.3 -j ACCEPT
sudo iptables -I OUTPUT -s 10.1.1.13 -d 10.1.1.14 -j ACCEPT ; sudo iptables -I OUTPUT -s 10.1.1.14 -d 10.1.1.13 -j ACCEPT
sudo iptables -I OUTPUT -s 10.1.1.23 -d 10.1.1.24 -j ACCEPT ; sudo iptables -I OUTPUT -s 10.1.1.24 -d 10.1.1.23 -j ACCEPT
sudo iptables -I OUTPUT -s 10.1.1.33 -d 10.1.1.34 -j ACCEPT ; sudo iptables -I OUTPUT -s 10.1.1.34 -d 10.1.1.33 -j ACCEPT
sudo iptables -I OUTPUT -s 10.1.1.43 -d 10.1.1.44 -j ACCEPT ; sudo iptables -I OUTPUT -s 10.1.1.44 -d 10.1.1.43 -j ACCEPT
sudo iptables -I OUTPUT -s 10.1.1.53 -d 10.1.1.54 -j ACCEPT ; sudo iptables -I OUTPUT -s 10.1.1.54 -d 10.1.1.53 -j ACCEPT
sudo iptables -I OUTPUT -s 10.1.1.63 -d 10.1.1.64 -j ACCEPT ; sudo iptables -I OUTPUT -s 10.1.1.64 -d 10.1.1.63 -j ACCEPT
sudo iptables -I OUTPUT -s 10.1.1.73 -d 10.1.1.74 -j ACCEPT ; sudo iptables -I OUTPUT -s 10.1.1.74 -d 10.1.1.73 -j ACCEPT
sudo iptables -I OUTPUT -s 10.1.1.83 -d 10.1.1.84 -j ACCEPT ; sudo iptables -I OUTPUT -s 10.1.1.84 -d 10.1.1.83 -j ACCEPT
sudo iptables -I OUTPUT -s 10.1.1.93 -d 10.1.1.94 -j ACCEPT ; sudo iptables -I OUTPUT -s 10.1.1.94 -d 10.1.1.93 -j ACCEPT
read -p "Press enter to end."
pkill vec_router
pkill ls_router<file_sep>/OneDrive/Documentos/alfredo7-master/mp1/http_server.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#define BACKLOG 10
void sigchld_handler(int s);
void *get_in_addr(struct sockaddr *sa);
int readline(int socket, char *buffer, int size) ;
int main(int argc, char *argv[]);
void sigchld_handler(int s) {
(void)s;
while(waitpid(-1, NULL, WNOHANG) > 0);
}
void *get_in_addr(struct sockaddr *sa) {
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int readline(int socket, char *buffer, int size) {
int i = 0;
char chr = '\0';
int line_size;
while((i < size - 1) && (chr != '\n')) {
line_size = recv(socket, &chr, 1, 0);
if (line_size > 0) {
if (chr == '\r') {
line_size = recv(socket, &chr, 1, MSG_PEEK);
if ((line_size > 0) && (chr == '\n'))
recv(socket, &chr, 1, 0);
else
chr = '\n';
}
buffer[i] = chr;
i++;
}
else {
chr = '\n';
}
}
buffer[i] = '\0';
return i;
}
int main(int argc, char *argv[]) {
int sockfd, client_fd;
int option = 1;
struct sockaddr_storage their_addr;
socklen_t sin_size;
struct sigaction sa;
char s[INET6_ADDRSTRLEN];
if (argc != 2) {
fprintf(stderr, "A port is needed\n");
exit(1);
}
struct addrinfo hints, *servinfo, *p;
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ((rv = getaddrinfo(NULL, argv[1] , &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("http_server: socket");
continue;
}
setsockopt(sockfd, SOL_SOCKET, (SO_REUSEPORT | SO_REUSEADDR), &option, sizeof(option));
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("http_server: bind");
continue;
}
break;
}
printf("Socket in %s\n", argv[1]);
freeaddrinfo(servinfo);
if (listen(sockfd, BACKLOG) == -1) {
perror("escuchar");
exit(1);
}
sa.sa_handler = sigchld_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("asignacion");
exit(1);
}
printf("listening...\n");
while(1) {
sin_size = sizeof their_addr;
client_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (client_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("\nConnected to %s\n", s);
if (!fork()) {
close(sockfd);
char request_line[1024];
int n;
n = readline(client_fd, request_line, sizeof(request_line));
printf("request: %s\n", request_line);
char discard[256];
discard[0] = 'A'; discard[1] = '\0';
while((n > 0) && strcmp(discard, "\n")) {
readline(client_fd, discard, sizeof(discard));
}
char method[32];
char uri[256];
char version[32];
int len = strlen(request_line);
char temp[len];
strcpy(temp, request_line);
char *pch;
pch = strtok(request_line, " ");
if (pch) {
strcpy(method, pch);
}
else {
strcpy(request_line, temp);
}
pch = strtok(NULL, " ");
if (pch) {
strcpy(uri, pch);
}
else {
strcpy(request_line, temp);
}
pch = strtok(NULL, "\n");
if (pch) {
strcpy(version, pch);
}
else {
strcpy(request_line, temp);
}
strcpy(request_line, temp);
if (rv == -1) {
char buffer1[1024];
sprintf(buffer1, "HTTP/1.0 400 Bad Request\r\n");
send(client_fd, buffer1, strlen(buffer1), 0);
sprintf(buffer1, "Content-Type: text/html\r\n");
send(client_fd, buffer1, strlen(buffer1), 0);
sprintf(buffer1, "\r\n");
send(client_fd, buffer1, strlen(buffer1), 0);
sprintf(buffer1, "<HTML><TITLE>Bad Request</TITLE>\r\n");
send(client_fd, buffer1, strlen(buffer1), 0);
sprintf(buffer1, "<BODY><P>The server could not fulfill\r\n");
send(client_fd, buffer1, strlen(buffer1), 0);
sprintf(buffer1, "your request because the request contained\r\n");
send(client_fd, buffer1, strlen(buffer1), 0);
sprintf(buffer1, "an error or that feature has not been implemented.</P>\r\n");
send(client_fd, buffer1, strlen(buffer1), 0);
sprintf(buffer1, "</BODY></HTML>\r\n");
send(client_fd, buffer1, strlen(buffer1), 0);
}
if (strcmp(method, "GET") != 0) {
char buffer2[1024];
sprintf(buffer2, "HTTP/1.0 400 Bad Request\r\n");
send(client_fd, buffer2, strlen(buffer2), 0);
sprintf(buffer2, "Content-Type: text/html\r\n");
send(client_fd, buffer2, strlen(buffer2), 0);
sprintf(buffer2, "\r\n");
send(client_fd, buffer2, strlen(buffer2), 0);
sprintf(buffer2, "<HTML><TITLE>Bad Request</TITLE>\r\n");
send(client_fd, buffer2, strlen(buffer2), 0);
sprintf(buffer2, "<BODY><P>The server could not fulfill\r\n");
send(client_fd, buffer2, strlen(buffer2), 0);
sprintf(buffer2, "your request because the request contained\r\n");
send(client_fd, buffer2, strlen(buffer2), 0);
sprintf(buffer2, "an error or that feature has not been implemented.</P>\r\n");
send(client_fd, buffer2, strlen(buffer2), 0);
sprintf(buffer2, "</BODY></HTML>\r\n");
send(client_fd, buffer2, strlen(buffer2), 0);
}
char file[256];
strcpy(file, uri+1);
FILE *fptr, *sock;
fptr = NULL;
fptr = fopen(file, "r");
if (fptr == NULL) {
char buffer3[1024];
sprintf(buffer3, "HTTP/1.0 404 Not Found\r\n");
send(client_fd, buffer3, strlen(buffer3), 0);
sprintf(buffer3, "Content-Type: text/html\r\n");
send(client_fd, buffer3, strlen(buffer3), 0);
sprintf(buffer3, "\r\n");
send(client_fd, buffer3, strlen(buffer3), 0);
sprintf(buffer3, "<HTML><TITLE>Not Found</TITLE>\r\n");
send(client_fd, buffer3, strlen(buffer3), 0);
sprintf(buffer3, "<BODY><P>The server could not fulfill\r\n");
send(client_fd, buffer3, strlen(buffer3), 0);
sprintf(buffer3, "your request because the resource specified\r\n");
send(client_fd, buffer3, strlen(buffer3), 0);
sprintf(buffer3, "is unavailable or nonexistent.</P>\r\n");
send(client_fd, buffer3, strlen(buffer3), 0);
sprintf(buffer3, "</BODY></HTML>\r\n");
send(client_fd, buffer3, strlen(buffer3), 0);
}
char buffer4[1024];
(void)file;
sprintf(buffer4, "HTTP/1.0 200 OK\r\n");
send(client_fd, buffer4, strlen(buffer4), 0);
sprintf(buffer4, "Content-Type: text\r\n");
send(client_fd, buffer4, strlen(buffer4), 0);
sprintf(buffer4, "\r\n");
send(client_fd, buffer4, strlen(buffer4), 0);
sock = fdopen(client_fd, "w");
char buffer5[4096];
do {
n = fread(buffer5, 1, sizeof(buffer5), fptr);
if (n < sizeof(buffer5)) {
if (!feof(fptr)) {
fprintf(stderr, "ERROR");
break;
}
}
fwrite(buffer5, 1, n, sock);
} while(!feof(fptr));
fclose(sock);
fclose(fptr);
close(client_fd);
exit(0);
}
close(client_fd);
}
return 0;
}<file_sep>/OneDrive/Documentos/alfredo7-master/mp1/http_client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
void *get_in_addr(struct sockaddr *sa);
int create_socket(char *hostname, char *port);
void divide(char *input, char *hostname, char *path, char *port);
int readline(int socket, char *buffer, int size) {
int i = 0;
char chr = '\0';
int line_size;
while((i < size - 1) && (chr != '\n')) {
line_size = recv(socket, &chr, 1, 0);
if (line_size > 0) {
if (chr == '\r') {
line_size = recv(socket, &chr, 1, MSG_PEEK);
if ((line_size > 0) && (chr == '\n'))
recv(socket, &chr, 1, 0);
else
chr = '\n';
}
buffer[i] = chr;
i++;
}
else {
chr = '\n';
}
}
buffer[i] = '\0';
return i;
}
int main(int argc, char* argv[]) {
int sockfd, numbytes;
char buf[2048];
char hostname[512];
char port[6];
char path[512];
char buffer[4096];
char status[32];
char location[1024];
int n, i;
if (argc != 2) {
fprintf(stderr, "ERROR\n");
exit(1);
}
char input[1024];
strcpy(input, argv[1]);
do{
divide(input, hostname, path, port);
printf("%s\n", hostname);
sockfd = create_socket(hostname, port);
char header[1024];
printf("http_client: sending GET\n");
sprintf(header, "GET %s HTTP/1.0\r\n", path);
send(sockfd, header, strlen(header), 0);
sprintf(header, "Host: %s\r\n", hostname);
send(sockfd, header, strlen(header), 0);
strcpy(header, "Connection: close\r\n");
send(sockfd, header, strlen(header), 0);
strcpy(header, "\r\n\r\n");
send(sockfd, header, strlen(header), 0);
n = readline(sockfd, buffer, sizeof(buffer));
for (i = 0; i < n; i++) {
if (buffer[i] == ' ') {
strcpy(status, buffer+i+1);
break;
}
}
n = readline(sockfd, buffer, sizeof(buffer));
buffer[n]='\0';
for (i = 0; i < n; i++) {
if (buffer[i] == '/') {
strcpy(input, buffer+i+2);
break;
}
}
}while(strncmp(status, "301 Moved Permanently", 21) == 0);
FILE *f = fopen("output", "w+");
n = read(sockfd, buffer, sizeof(buffer));
buffer[n] = '\0';
char *temp = strstr(buffer, "\r\n\r\n");
fprintf(f, "%s", temp+4);
while((n = read(sockfd, buffer, sizeof(buffer))) != 0) {
buffer[n] = '\0';
printf("%s",buffer);
fprintf(f,"%s" ,buffer);
}
fclose(f);
return 0;
}
int create_socket(char *hostname, char *port){
struct addrinfo hints, *servinfo;
int option = 1;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if((getaddrinfo(hostname, port, &hints, &servinfo)) != 0) {
perror("NO funciona");
exit(1);
}
int sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
setsockopt(sockfd, SOL_SOCKET, (SO_REUSEPORT | SO_REUSEADDR), &option, sizeof(option));
connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen);
/* if (p == NULL) {
fprintf(stderr, "http_client: unable to connect to %s\n", hostname);
exit(1);
}
*/
freeaddrinfo(servinfo);
return sockfd;
}
void divide(char *input, char *hostname, char *path, char *port){
char temporal[strlen(input)];
strcpy(temporal, input+7);
printf("Llegamos aqui\n");
char *pch;
pch = strchr(temporal, ':');
if (pch != NULL) {
pch[0]='\0';
strcpy(hostname, temporal);
char *pch1;
pch1 = strchr(pch+1, '/');
if(pch!=NULL){
pch1[0]='\0';
strcpy(path, pch1+1);
}else{
strcpy(path, "/");
}
strcpy(port, pch+1);
} else {
strcpy(port, "80");
char *pch1;
pch1 = strchr(temporal, '/');
if(pch1!=NULL){
pch1[0]='\0';
strcpy(path, pch1+1);
if(strncmp(path," ", 1)!=0){
strcpy(path,"/index.html");
}
}else{
strcpy(path, "/");
}
strcpy(hostname, temporal);
}
printf("Llegamos aqui\n");
}
<file_sep>/OneDrive/Documentos/group5-master/mp2/vec_router.c
// Router that Implements VEC Routing
// alfredo7 | cdgerth2
#include <pthread.h>
#include <time.h>
#include <inttypes.h>
#include <math.h>
#include <limits.h>
#include <fcntl.h>
#include "helper_fns.c"
void handleTopoPackets(char * recvBuf);
void * advertiseVector(void * unused_param);
void createTable();
// Declaration of locks and condition for advertisement
pthread_cond_t advr_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t advr_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t vector_lock = PTHREAD_MUTEX_INITIALIZER;
char advr_reasess = YES; // locked by advr_lock
char down_date = NO;
char poisoned = NO;
struct vectors {
int distance;
int successor;
char advertise;
};
struct vectors vector[256];
int main(int argcount, char ** args){
int i, j, k;
if(argcount != 4)
{
fprintf(stderr, "Usage: %s mynodeid initialcostsfile logfile\n\n", args[0]);
exit(1);
}
// Perform all the initialization steps.
init_router(args);
createTable();
// Start announce pthread
pthread_t announcerThread;
pthread_create(&announcerThread, 0, announceToNeighbors, (void*)0);
// Start advertize pthread
pthread_t advertizerThread;
pthread_create(&advertizerThread, 0, advertiseVector, (void*)0);
unsigned char recvBuf[recvBufSize];
int new_host = NO;
int num_down = 0;
int cost_changed = NO;
while(1)
{
new_host = fetchPacket(recvBuf); // get the packet.
if (new_host){ // Immediately send out an advertisement.
pthread_mutex_lock(&advr_lock);
advr_reasess = YES;
pthread_mutex_unlock(&advr_lock);
}
pthread_mutex_lock(&vector_lock); // don't advertise while we update neighboors
num_down = checkDownNeighboors(network_size); // will have to do something with this retval eventually
pthread_mutex_unlock(&vector_lock); // don't advertise while we update neighboors
pthread_mutex_lock(&vector_lock); // don't advertise while we update neighboors
cost_changed = handleNonTopoPackets(recvBuf);
pthread_mutex_unlock(&vector_lock); // don't advertise while we update neighboors
if (cost_changed){
pthread_mutex_lock(&advr_lock);
advr_reasess = YES;
pthread_mutex_unlock(&advr_lock);
//printf("C");
}
handleTopoPackets(recvBuf);
if (num_down){
pthread_mutex_lock(&advr_lock);
advr_reasess = YES;
down_date = YES;
pthread_mutex_unlock(&advr_lock);
for (i=0; i<num_down; i++){
vector[newly_down[i]].distance = INT_MAX;
routing_table[newly_down[i]] = -1;
for (k=0; k<256; k++){
if (vector[k].successor == newly_down[i]){
routing_table[k] = -1;
vector[k].distance = INT_MAX;
}
}
}
}
pthread_mutex_lock(&advr_lock);
if (advr_reasess == YES){
pthread_cond_signal(&advr_cond);
}
pthread_mutex_unlock(&advr_lock);
if (num_down){ // Now go to sleep and forget the world to fix routing loops
num_down = 0;
usleep(10);
fcntl(globalSocketUDP, F_SETFL, fcntl(globalSocketUDP, F_GETFL) | O_NONBLOCK);
while (recv(globalSocketUDP, NULL, 100000, 0) != -1) ;
fcntl(globalSocketUDP, F_SETFL, fcntl(globalSocketUDP, F_GETFL) & !O_NONBLOCK);
}
}
//(should never reach here)
fclose(log_fd);
close(globalSocketUDP);
return 0;
}
void handleTopoPackets(char * recvBuf){
if(!strncmp(recvBuf, "advr", 4))
{
int i, k, j = 4, dest, dist, origin, ttl;
char changed;
origin = *((int*)&recvBuf[j]); // this is the origin of the packet. (will be one of the neighboors.)
*((int*)&recvBuf[j]) = globalMyID; // make myself the origin of this packet that I will forward.
j += sizeof(int);
ttl = *((int*)&recvBuf[j]);
if (ttl > 0) {
// Update time to live.
ttl--;
*((int*)&recvBuf[j]) = ttl;
j += sizeof(int);
pthread_mutex_lock(&vector_lock);
changed = NO;
//We will compare if the distance is
for(i=0;i<256;i++){
// Read the destination and the distance it currently thinks it is.
dest = *((int*)&recvBuf[j]);
if (dest == -1) break; // we reached the end sentinel
if (dest > 255) break; // we have an error
vector[dest].advertise = YES;
dist = *((int*)&recvBuf[j+sizeof(int)]);
// Check if the distance to the destination through the origin node is less than the current distance we have on file:
// OR if this neighboor is giving us an update distance that has a higher cost.
if (dist == INT_MAX){
if (origin == vector[dest].successor) {
if (routing_table[dest] != -1){
routing_table[dest] = -1;
vector[dest].distance = INT_MAX;
changed = YES;
pthread_mutex_lock(&advr_lock);
down_date = YES;
pthread_mutex_unlock(&advr_lock);
}
}
} else if (((dist + neighboors[origin].cost) < vector[dest].distance) || (((dist + neighboors[origin].cost) != vector[dest].distance) && (vector[dest].successor == origin))){
vector[dest].distance = dist + neighboors[origin].cost;
routing_table[dest] = origin;
vector[dest].successor = origin;
changed = YES;
} else if ((dist + neighboors[origin].cost) == vector[dest].distance){ // tie breaking
if (origin < vector[dest].successor){
routing_table[dest] = origin;
if (vector[dest].successor != origin){
vector[dest].successor = origin;
changed = YES;
}
}
}
if (routing_table[dest] != -1){
dist += neighboors[origin].cost; // add the cost to this node to the distance.
*((int*)&recvBuf[j+sizeof(int)]) = dist;
}
j += 2 * sizeof(int);
}
pthread_mutex_unlock(&vector_lock);
if (changed){
pthread_mutex_lock(&advr_lock);
advr_reasess = YES;
pthread_cond_signal(&advr_cond);
pthread_mutex_unlock(&advr_lock);
// DEBUG:
printf(".");
fflush(stdout);
}
}
}
}
void * advertiseVector(void* unusedParam){
//We will send a message with "advrMyIDDestinationDistance" The destination will be all the vectors known (not a distance of infinity) in the table. The distance will be the one that will be in the table.
unsigned short i;
int j = 4;
int k;
char packetBuf[recvBufSize];
char tmpBuf[recvBufSize];
int packetBuflen;
int dest;
int offset = 1;
int network_size = 0;
packetBuf[0] = 'a'; packetBuf[1] = 'd'; packetBuf[2] = 'v'; packetBuf[3] = 'r';
*((int*)&packetBuf[j]) = globalMyID; // Set myself as the origin.
// sleep for random amount of time to avoid flooding the network on startup:
usleep(globalMyID);
struct timespec relTime;
struct timespec now;
pthread_mutex_lock(&advr_lock);
advr_reasess = YES;
pthread_mutex_unlock(&advr_lock);
while(1)
{
// Sending destination and distance
printf("x");
fflush(stdout);
if (advr_reasess){
pthread_mutex_lock(&advr_lock);
advr_reasess = NO;
pthread_mutex_unlock(&advr_lock);
pthread_mutex_lock(&vector_lock); // don't read an incomplete neighboors block.
j = 4 + sizeof(int);
*((int *)&packetBuf[j]) = 20; // time to live
j += sizeof(int);
network_size = down_date ? network_size : 0;
for (i=0; i<256; i++){
if (neighboors[i].up){ // perform checking to make sure that we have the min cost for directly connected nodes.
vector[i].advertise = YES;
if (neighboors[i].cost < vector[i].distance){
vector[i].distance = neighboors[i].cost;
vector[i].successor = i;
routing_table[i] = i;
} else if (neighboors[i].cost == vector[i].distance){
if (i < vector[i].successor){
vector[i].successor = i;
routing_table[i] = i;
}
}
}
if ( ( !down_date && vector[i].advertise) || (down_date && vector[i].advertise && vector[i].distance == INT_MAX)){ // only forward if we have or had some sort of route
*((int *)&packetBuf[j]) = i;
j += sizeof(int);
*((int *)&packetBuf[j]) = vector[i].distance;
j += sizeof(int);
network_size += down_date ? 0 : 1;
vector[i].advertise = down_date ? 0 : 1;
}
}
pthread_mutex_lock(&advr_lock);
down_date = NO;
pthread_mutex_unlock(&advr_lock);
*((unsigned int *)&packetBuf[j]) = -1; // End Sentinel
j += sizeof(int);
packetBuflen = j;
pthread_mutex_unlock(&vector_lock); // don't read an incomplete neighboors block.
}
for (i=0; i<256; i++){
if (neighboors[i].up){
memcpy(tmpBuf, packetBuf, packetBuflen);
j = 4 + (2 * sizeof(int));
for(k=0;k<256;k++){
// Read the destination and the distance it currently thinks it is.
dest = *((int*)&tmpBuf[j]);
if (dest == -1) break; // we reached the end sentinel
if (dest > 255) break; // we have an error
j += sizeof(int);
if (vector[dest].successor == i && i != globalMyID)
*((int*)&tmpBuf[j]) = INT_MAX;
j += sizeof(int);
}
j+= sizeof(int);
sendPacket(tmpBuf, j, i);
}
}
clock_gettime(CLOCK_REALTIME, &now);
relTime.tv_nsec = now.tv_nsec;
if (network_size > 100) offset = 2;
else offset = 1;
relTime.tv_sec = now.tv_sec + offset;
usleep(3 * network_size);
// Block until either: change in topology or 1 seconds is up.
pthread_mutex_lock(&advr_lock);
if (!advr_reasess)
pthread_cond_timedwait(&advr_cond, &advr_lock, &relTime);
pthread_mutex_unlock(&advr_lock);
}
}
void createTable(){
//We create a table in which it will introduce the neigboors distance, destination and successor, if they are not neighboors, the distance will be 16 (That is infinity).
int i;
pthread_mutex_lock(&vector_lock);
for(i=0;i<256;i++){
vector[i].distance = INT_MAX;
vector[i].advertise = NO;
vector[i].successor = globalMyID;
routing_table[i] = -1;
neighboors[i].up = NO;
}
vector[globalMyID].distance = 0;
vector[globalMyID].advertise = YES;
routing_table[globalMyID] = globalMyID;
pthread_mutex_unlock(&vector_lock);
}<file_sep>/OneDrive/Documentos/group5-master/mp2/readme.txt
# Please write down each person's responsibility in this group for this MP.
#
# General Overhead: cdgerth2
# Implement LS Routing: cdgerth2
# Implement VEC Routing: alfredo7
#<file_sep>/mp3/net_setup.sh
#!/bin/bash
sudo tc qdisc del dev enp0s3 root 2>/dev/null
sudo tc qdisc add dev enp0s3 root handle 1:0 netem delay 20ms
sudo tc qdisc add dev enp0s3 parent 1:1 handle 10: tbf rate 40Mbit burst 1mb latency 40ms<file_sep>/mp3/sender_main.c
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <pthread.h>
#include "buffers.c"
void reliablyTransfer(char* hostname, unsigned short int hostUDPport, char* filename, unsigned long long int bytesToTransfer);
void create_socket();
void read_file(char* filename, unsigned long long int bytesToTransfer);
int send_packet(payload_t * payload, int sock);
void * ack_listen(void* unusedParam);
void * resend_lost(void* unusedParam);
int ack;
int sock;
unsigned char sender_end = NO;
struct sockaddr_in receiveraddr;
pthread_mutex_t buf_lock = PTHREAD_MUTEX_INITIALIZER; // This locks the buffer across threads. Prevents data collisions.
unsigned short int udpPort;
char * hostname;
int main(int argc, char** argv)
{
unsigned long long int numBytes;
if(argc != 5)
{
fprintf(stderr, "usage: %s receiver_hostname receiver_port filename_to_xfer bytes_to_xfer\n\n", argv[0]);
exit(1);
}
udpPort = (unsigned short int)atoi(argv[2]);
numBytes = atoll(argv[4]);
hostname = argv[1];
init_buffers();
create_socket(argv[1], udpPort);
// Start listen for ack thread
pthread_t ackThread;
pthread_create(&ackThread, 0, ack_listen, (void*)0);
// // Start resend thread
// pthread_t resendThread;
// pthread_create(&resendThread, 0, resend_lost, (void*)0);
// Begin the transfer
reliablyTransfer(argv[1], udpPort, argv[3], numBytes);
close(sock);
}
void reliablyTransfer(char* hostname, unsigned short int hostUDPport, char* filename, unsigned long long int bytesToTransfer) {
read_file(filename, bytesToTransfer);
}
//Function that creates a socket, for the function send packet, it return the socket.
void create_socket(){ // sender and receiver will listen on the same port.
struct sockaddr_in bindAddr;
memset(&bindAddr, 0, sizeof(bindAddr));
sock = socket(AF_INET, SOCK_DGRAM, 0);
bindAddr.sin_family = AF_INET;
bindAddr.sin_port = 0; // auto assign a port
bindAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sock, (struct sockaddr*)&bindAddr, sizeof(struct sockaddr_in)) < 0)
{
perror("bind");
close(sock);
exit(1);
}
// Now build the client data structs:
struct hostent *receiver;
receiver = gethostbyname(hostname);
if (receiver == NULL){
perror("DNS Query");
}
memset(&receiveraddr, 0, sizeof(receiveraddr));
receiveraddr.sin_family = AF_INET;
receiveraddr.sin_port = htons(udpPort);
receiveraddr.sin_addr.s_addr = inet_addr(hostname); // THis assumes that the hostname will come as an ip address...
}
//Function that reads the file given.
void read_file(char* filename, unsigned long long int bytesToTransfer){
payload_t * buffer;
payload_t * resend_buffer;
unsigned char counter = 0;
unsigned short current_packet_size = 1468;
struct timespec delay;
delay.tv_sec = 0;
int result;
unsigned long bytes_read = 0;
FILE *fp = fopen(filename, "rb");
int read_len;
if(fp == NULL){
perror("File error");
exit(1);
}
read_len = 1;
//We copy the file into the buffer payload by payload:
while(bytes_read < bytesToTransfer){
counter++;
pthread_mutex_lock(&buf_lock);
resend_buffer = buffer_to_be_resent();
pthread_mutex_unlock(&buf_lock);
if (resend_buffer){
send_packet(resend_buffer, sock);
} else {
do {
buffer = (payload_t *) malloc(sizeof(payload_t)); // alocate a buffer to read file data into
} while (!buffer); // make sure we aren't handed a null buffer
read_len = fread(&(((unsigned short *)buffer)[2]), sizeof(char), MIN(current_packet_size, bytesToTransfer - bytes_read), fp); // read the file into that part of the buffer
if (read_len == 0){
printf("File is not as long as the number bytes you asked me to send.");
return;
}
bytes_read += read_len;
((unsigned short *)buffer)[0] = read_len; // put the length of the data in this packet into the payload
pthread_mutex_lock(&buf_lock);
result = buffer_insert(buffer);
pthread_mutex_unlock(&buf_lock);
while (result == -1){
current_send_delay();
pthread_mutex_lock(&buf_lock);
result = buffer_insert(buffer);
pthread_mutex_unlock(&buf_lock);
}
pthread_mutex_lock(&buf_lock);
send_packet(buffer, sock);
pthread_mutex_unlock(&buf_lock);
}
if ((counter % BURST_SIZE) == 0){
current_send_delay();
counter = 0;
}
}
// send a packet with no data (the end sentinel)
buffer = (payload_t *) malloc(sizeof(payload_t)); // alocate a buffer to read file data into
buffer->length = 0;
pthread_mutex_lock(&buf_lock);
buffer_insert(buffer);
int total_sent = buffer->seqNum;
send_packet(buffer, sock);
pthread_mutex_unlock(&buf_lock);
// Wait for evertyhing to be ack'ed and then exit:
while (!sender_done()){
pthread_mutex_lock(&buf_lock);
resend_buffer = buffer_to_be_resent();
pthread_mutex_unlock(&buf_lock);
if (resend_buffer){
send_packet(resend_buffer, sock);
}
current_send_delay();
}
fclose(fp);
float loss = (float)total_sent / (float)(total_sent + resent);
printf("Packet Loss: %f%%\n", loss);
}
//Function that sends a packet, returns the number of bytes sent.
int send_packet(payload_t * payload, int sock){
if (!payload) // sanity check
return -1;
sendto(sock, payload, payload->length + 4, 0, (struct sockaddr *) &receiveraddr, sizeof(receiveraddr));
return 0;
}
void * ack_listen(void* unusedParam){
payload_t buffer;
socklen_t socksize = sizeof(receiveraddr);
while (1){
recvfrom(sock, &buffer, 4, 0, (struct sockaddr *) &receiveraddr, &socksize);
if (buffer.length == 0){
pthread_mutex_lock(&buf_lock);
buffer_mark_acked(buffer.seqNum);
pthread_mutex_unlock(&buf_lock);
}
}
}<file_sep>/OneDrive/Documentos/group5-master/mp2/Makefile
#Makefile for MP2
CC=/usr/bin/gcc
CC_OPTS=-g3 -pthread
CC_LIBS=
CC_DEFINES=
CC_INCLUDES=
CC_ARGS=${CC_OPTS} ${CC_LIBS} ${CC_DEFINES} ${CC_INCLUDES}
# clean is not a file
.PHONY=clean
all: ls_router vec_router
ls_router: ls_router.c
@${CC} ${CC_ARGS} -o ls_router ls_router.c
vec_router: vec_router.c
@${CC} ${CC_ARGS} -o vec_router vec_router.c
clean:
@rm -f ls_router vec_router output *.o logs/*.log
| 518a49d72b685c5b73e41ba38d9b4b4f26e2dd77 | [
"Text",
"C",
"Makefile",
"Shell"
] | 14 | C | alfreddo98/Network-Projects | 4ec6537c3400912599a0ef5f1ec46f7a4c548339 | 32b100f508c684b439fe85f770dce3750db08eb6 |
refs/heads/master | <repo_name>ahmedMubarak2024/simplerestweb<file_sep>/src/main/java/hss/GenericResource.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hss;
import java.util.Vector;
import javax.servlet.ServletContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
/**
* REST Web Service
*
* @author Altysh
*/
@Path("/")
public class GenericResource {
@Context ServletContext context;
Vector<NewClass> list;
/**
* Creates a new instance of GenericResource
*/
public GenericResource() {
}
/**
* Retrieves representation of an instance of hss.GenericResource
* @return an instance of java.lang.String
*/
@GET
@Path("/get/{id}")
@Produces(MediaType.APPLICATION_JSON)
public NewClass getJson(@PathParam("id") int id) {
//TODO return proper representation object
// throw new UnsupportedOperationException();
list= (Vector<NewClass>) context.getAttribute("list");
if(list!=null)
{
for(NewClass classs:list)
if(classs.i==id)
return classs;
}
System.out.println("hham");
return new NewClass();
}
@GET
@Path("/get/{id}")
@Produces(MediaType.APPLICATION_XML)
public NewClass getJsonXml(@PathParam("id") int id) {
//TODO return proper representation object
// throw new UnsupportedOperationException();
System.out.println("hham");
list= (Vector<NewClass>) context.getAttribute("list");
if(list!=null)
{
for(NewClass classs:list)
if(classs.i==id)
return classs;
}
return new NewClass();
}
/**
* PUT method for updating or creating an instance of GenericResource
* @param content representation for the resource
*/
@POST
@Path("post")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void putJson(@FormParam("id") int id,
@FormParam("name") String name,
@FormParam("salary") double salary)
{
System.out.println(id +" "+name+" "+ salary);
list= (Vector<NewClass>) context.getAttribute("list");
if(list!=null)
{NewClass cla = new NewClass();
cla.setI(id);
cla.setS(name);
cla.setD(salary);
list.add(cla);
}else{
list= new Vector<>();
NewClass cla = new NewClass();
cla.setI(id);
cla.setS(name);
cla.setD(salary);
list.add(cla);
context.setAttribute("list", list);
}
}
@POST
@Path("post")
@Consumes("application/json")
public void putJson(NewClass n)
{
System.out.println("put josn");
list= (Vector<NewClass>) context.getAttribute("list");
if(list!=null)
{
list.add(n);
}else
{
list= new Vector<>();
list.add(n);
context.setAttribute("list", list);
}
}
@POST
@Path("post")
@Consumes(MediaType.APPLICATION_XML)
public void putXml(NewClass n)
{
System.out.println("put josn");
list= (Vector<NewClass>) context.getAttribute("list");
if(list!=null)
{
list.add(n);
}else
{
list= new Vector<>();
list.add(n);
context.setAttribute("list", list);
}
}
@PUT
@Path("update")
@Consumes("application/json")
public void update(NewClass n)
{
//System.out.println("put josn");
list= (Vector<NewClass>) context.getAttribute("list");
if(list!=null)
{
for(NewClass item:list)
{
if(item.getI()==n.getI())
{System.out.println("not null");
item.setD(n.getD());
}
}
// list.add(n);
}else
{
list= new Vector<>();
list.add(n);
context.setAttribute("list", list);
}
}
@PUT
@Path("update")
@Consumes(MediaType.APPLICATION_XML)
public void updateXml(NewClass n)
{
//System.out.println("put josn");
list= (Vector<NewClass>) context.getAttribute("list");
if(list!=null)
{
for(NewClass item:list)
{
if(item.getI()==n.getI())
{System.out.println("not null");
item.setD(n.getD());
}
}
// list.add(n);
}else
{
list= new Vector<>();
list.add(n);
context.setAttribute("list", list);
}
}
@DELETE
@Path("delete")
@Consumes("application/json")
public void delete(NewClass n)
{
//System.out.println("put josn");
list= (Vector<NewClass>) context.getAttribute("list");
if(list!=null)
{
for(NewClass item:list)
{
if(item.getI()==n.getI())
{
list.remove(item);
}
}
// list.add(n);
}else
{
list= new Vector<>();
//list.add(n);
context.setAttribute("list", list);
}
}
@DELETE
@Path("delete")
@Consumes(MediaType.APPLICATION_XML)
public void deleteXml(NewClass n)
{
//System.out.println("put josn");
list= (Vector<NewClass>) context.getAttribute("list");
if(list!=null)
{
for(NewClass item:list)
{
if(item.getI()==n.getI())
{
list.remove(item);
}
}
// list.add(n);
}else
{
list= new Vector<>();
//list.add(n);
context.setAttribute("list", list);
}
}
}
<file_sep>/src/main/java/hss/Hmada.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hss;
/**
*
* @author Altysh
*/
public class Hmada {
String s;
public Hmada(String hmad) {
s= hmad;
}
}
| 97ba0da8977fce9e94cfee5eaa2ad155a82f30cd | [
"Java"
] | 2 | Java | ahmedMubarak2024/simplerestweb | 117d252650f7292ccb7a495a39d52b5a97f096a7 | e9d6cb97c31ccdc396c3bccd6d35f6bc1d46b8cb |
refs/heads/main | <file_sep>#include "drive_detector.h"
#include <fstream>
#include <memory>
#include <numeric>
#include <cuda_runtime_api.h>
#include "debug_log.h"
#include "performance_count.h"
namespace lunchjet {
static size_t getMemorySize(const nvinfer1::Dims& dims, const int32_t elem_size)
{
return std::accumulate(dims.d, dims.d + dims.nbDims, 1, std::multiplies<int64_t>()) * elem_size;
}
class Logger : public nvinfer1::ILogger
{
void log(Severity severity, const char* msg) override
{
if (severity < Severity::kINFO)
debug_debug("TensorRT log: %d %s", static_cast<int>(severity) ,msg);
}
};
static Logger logger;
static DriveParameter value_on_error = {0.f, 0.f};
DriveDetector::DriveDetector(const std::string &model_file_path)
:engine_file_path(model_file_path),
engine(nullptr),
context(nullptr),
input_mem_size(0),
output_mem_size(0),
input_mem(nullptr),
output_mem(nullptr),
stream()
{
std::ifstream engine_file(engine_file_path, std::ios::binary);
if (engine_file.fail())
{
return;
}
//getting size of engine file
engine_file.seekg(0, std::ifstream::end);
auto fsize = engine_file.tellg();
engine_file.seekg(0, std::ifstream::beg);
std::vector<char> engine_data(fsize);
engine_file.read(engine_data.data(), fsize);
//get engine
unique_ptr_for_nv<nvinfer1::IRuntime> runtime{nvinfer1::createInferRuntime(logger)};
engine.reset(runtime->deserializeCudaEngine(engine_data.data(), fsize, nullptr));
if(engine == nullptr) {
std::cout << "deserializeCudaEngine() failed" << std::endl;
}
//get context
context.reset(engine->createExecutionContext());
if(!context) {
debug_err("createExecutionContext() failed");
}
//configure input tensor
std::string input_name("input:0");
auto input_index = engine->getBindingIndex(input_name.c_str());
std::cout << "input index: " << input_index << std::endl;
if(input_index == -1) {
debug_err("getBindingIndex() for input failed: %s", input_name.c_str());
}
auto input_dims = context->getBindingDimensions(input_index);
input_mem_size = getMemorySize(input_dims, sizeof(float));
//configure output tensor
std::string output_name("output");
auto output_index = engine->getBindingIndex(output_name.c_str());
std::cout << "output index: " << output_index << std::endl;
if(output_index == -1) {
debug_err("getBindingIndex() for output failed: %s", output_name.c_str());
}
auto output_dims = context->getBindingDimensions(output_index);
output_mem_size = getMemorySize(output_dims, sizeof(float));
// Allocate CUDA memory for input and output bindings
if (cudaMalloc(&input_mem, input_mem_size) != cudaSuccess)
{
debug_err("input cuda memory allocation failed, size = %zu bytes", input_mem_size);
}
if (cudaMalloc(&output_mem, output_mem_size) != cudaSuccess)
{
debug_err("ERROR: output cuda memory allocation failed, size = %zu bytes", output_mem_size);
}
cudaStream_t stream;
if (cudaStreamCreate(&stream) != cudaSuccess)
{
debug_debug("ERROR: cuda stream creation failed.");
}
}
DriveDetector::~DriveDetector()
{
cudaFree(input_mem);
cudaFree(output_mem);
}
DriveParameter DriveDetector::detect(const cv::Mat &image)
{
cv::Mat image_rgb, image_rgb_float;
cv::cvtColor(image, image_rgb, cv::COLOR_BGR2RGB);
image_rgb.convertTo(image_rgb_float, CV_32F);
// Copy image data to input binding memory
if (cudaMemcpyAsync(input_mem, image_rgb_float.data, input_mem_size, cudaMemcpyHostToDevice, stream) != cudaSuccess)
{
debug_debug("ERROR: CUDA memory copy of input failed, size = %zu bytes", input_mem_size);
return value_on_error;
}
// Run TensorRT inference
void* bindings[] = {input_mem, output_mem};
if (context->enqueueV2(bindings, stream, nullptr) == false)
{
debug_debug("ERROR: TensorRT inference failed");
return value_on_error;
}
// Copy predictions from output binding memory
auto output_buffer = std::unique_ptr<float[]>{new float[output_mem_size]};
if (cudaMemcpyAsync(output_buffer.get(), output_mem, output_mem_size, cudaMemcpyDeviceToHost, stream) != cudaSuccess)
{
debug_debug("ERROR: CUDA memory copy of output failed, size = %zu bytes", output_mem_size);
return value_on_error;
}
cudaStreamSynchronize(stream);
return {output_buffer[0], output_buffer[1]};
}
} //namespace lunchjet<file_sep>cmake_minimum_required(VERSION 3.10)
project("LunchJet")
#
# momo for send video stream from camera
#
set(MOMO_TARBALL_URL "https://github.com/shiguredo/momo/releases/download/2021.2.2/momo-2021.2.2_ubuntu-18.04_armv8_jetson_nano.tar.gz")
string(REGEX REPLACE "^.*/" "" MOMO_TARBALL_NAME ${MOMO_TARBALL_URL})
string(REGEX REPLACE "\.tar\.gz" "/" MOMO_DIR ${MOMO_TARBALL_NAME})
string(APPEND MOMO_CMD ${MOMO_DIR} "momo")
add_custom_command(
OUTPUT ${MOMO_TARBALL_NAME}
COMMAND "wget" ${MOMO_TARBALL_URL})
add_custom_command(
OUTPUT ${MOMO_CMD}
MAIN_DEPENDENCY ${MOMO_TARBALL_NAME}
COMMAND "tar" "-m" "-xvf" ${MOMO_TARBALL_NAME}
COMMAND "chmod" "u+x" ${MOMO_CMD}
)
add_custom_target(check_momo_version ALL COMMAND ${MOMO_CMD} "--version" DEPENDS ${MOMO_CMD})
#
# build lunchjet sources
#
add_subdirectory(src/i2c)
add_subdirectory(src/include)
add_subdirectory(src/pca9685)
add_subdirectory(src/rc_car_driver)
add_subdirectory(src/user_input_device)
add_subdirectory(src/rc_car_controller)
add_subdirectory(src/rc_car_server)
add_subdirectory(src/video_input_device)
add_subdirectory(src/drive_detector)
#
# scripts
#
add_subdirectory(scripts)
#
# build lunchjet tests
#
add_subdirectory(test)
#
# install artifacts
#
install(DIRECTORY DESTINATION /etc/lunchjet)
install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${MOMO_DIR} DESTINATION "/opt/lunchjet/momo" USE_SOURCE_PERMISSIONS)
install(FILES "lunchjet_momo.service" DESTINATION "/usr/lib/systemd/system/")
install(FILES "lunchjet_virtual_camera.service" DESTINATION "/usr/lib/systemd/system/")
install(FILES "lunchjet.conf" DESTINATION "/etc/modprobe.d/")
install(FILES "lunchjet_load.conf" DESTINATION "/etc/modules-load.d/")
install(FILES lunchjet_template.conf DESTINATION /etc/lunchjet)
install(CODE "message(\"install has finished!\")")
install(CODE "message(\"you can enable LunchJet with\")")
install(CODE "message(\" sudo systemctl enable --now lunchjet_momo.service\")")
install(CODE "message(\" sudo systemctl enable --now lunchjet_virtual_camera.service\")")<file_sep>cmake_minimum_required(VERSION 3.10)
project("LunchJet RC Car Server")
set(LOG_IMAGE_DIR /var/log/lunchjet/control/images)
set(LOG_ANNOTAION_DIR /var/log/lunchjet/control/annotations)
add_executable(lunchjet_rc_car_server rc_car_server.cpp main.cpp)
target_link_libraries(lunchjet_rc_car_server
lunchjet_include
lunchjet_rc_car_controller
lunchjet_rc_car_driver
lunchjet_video_input_device
lunchjet_drive_detector)
target_compile_definitions(lunchjet_rc_car_server
PRIVATE LOG_IMAGE_DIR="${LOG_IMAGE_DIR}"
PRIVATE LOG_ANNOTAION_DIR="${LOG_ANNOTAION_DIR}")
install(TARGETS lunchjet_rc_car_server DESTINATION /opt/lunchjet/)
install(FILES lunchjet_rc_car.service DESTINATION /usr/lib/systemd/system/)
install(DIRECTORY DESTINATION ${LOG_IMAGE_DIR})
install(DIRECTORY DESTINATION ${LOG_ANNOTAION_DIR})
<file_sep>cmake_minimum_required(VERSION 3.10)
project("LunchJet Video Input Device")
find_package( OpenCV REQUIRED )
add_library(lunchjet_video_input_device STATIC video_input_device.cpp)
target_link_libraries(lunchjet_video_input_device lunchjet_include pthread ${OpenCV_LIBS})
target_include_directories(lunchjet_video_input_device PUBLIC .)
target_include_directories(lunchjet_video_input_device PRIVATE ${OpenCV_INCLUDE_DIRS})<file_sep>#include <iostream>
#include "drive_detector.h"
#include "performance_count.h"
using namespace lunchjet;
int main(int argc, char *argv[])
{
if(argc < 3) {
std::cerr << "usage: " << argv[0] << "MODEL_FILE_NAME INPUT_IMAGE_FILENAME" << std::endl;
return -1;
}
DriveDetector dcon(argv[1]);
cv::Mat image = cv::imread(argv[2]);
for(int i = 0; i < 10; ++i) {
auto infer_start = time_now();
auto params = dcon.detect(image);
std::cout << "params: steer=" << params.steering
<< " throttle=" << params.throttle
<< " " << duration_ms_from(infer_start) << "ms" << std::endl;
}
return 0;
}<file_sep>cmake_minimum_required(VERSION 3.10)
project("LunchJet Test")
add_executable(i2c_verify_test i2c_verify_test.cpp)
target_link_libraries(i2c_verify_test lunchjet_i2c lunchjet_include)
add_executable(pca9685_test pca9685_test.cpp)
target_link_libraries(pca9685_test lunchjet_pca9685)
add_executable(rc_car_driver_test rc_car_driver_test.cpp)
target_link_libraries(rc_car_driver_test lunchjet_rc_car_driver)
add_executable(user_input_device_test user_input_device_test.cpp)
target_link_libraries(user_input_device_test lunchjet_user_input_device)
add_executable(rc_car_controller_test rc_car_controller_test.cpp)
target_link_libraries(rc_car_controller_test lunchjet_rc_car_controller)
add_executable(video_device_test video_device_test.cpp)
target_link_libraries(video_device_test lunchjet_video_input_device)
add_executable(drive_detector_test drive_detector_test.cpp)
target_link_libraries(drive_detector_test lunchjet_drive_detector)
<file_sep>#include "user_input_device.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <sys/select.h>
#include <thread>
#include "debug_log.h"
#include "string_utils.h"
namespace lunchjet {
UserInputDevice::UserInputDevice(const std::string &file_name, const std::atomic<bool> &stop_thread)
: file_name(file_name),
fd(-1),
stop_thread(stop_thread){}
UserInputDevice::~UserInputDevice()
{
if(waiting_thread.joinable()){
waiting_thread.join();
}
}
void UserInputDevice::add_listener(const std::vector<EventIndicator> &indicators, EventListener &listener)
{
std::lock_guard<std::mutex> guard(mutex_filters);
filters.push_back({indicators, listener});
}
int UserInputDevice::listen()
{
//set signal masks for the child thread
sigset_t block, old_block;
sigemptyset(&block);
sigaddset(&block, SIGINT);
sigaddset(&block, SIGTERM);
pthread_sigmask(SIG_BLOCK, &block, &old_block);
waiting_thread = std::thread([this](){listen_thread();});
//set original signal masks back
pthread_sigmask(SIG_SETMASK, &old_block, NULL);
return 0;
}
void UserInputDevice::notify_connect()
{
for(auto &filter : filters) {
filter.listener.on_connect();
}
}
void UserInputDevice::notify_error()
{
for(auto &filter : filters) {
filter.listener.on_error();
}
}
void UserInputDevice::forward_events(const struct input_event *events, int num_events)
{
for(int i = 0; i < num_events; ++i) {
const struct input_event &event = events[i];
for(auto &filter : filters){
for(auto &indicator : filter.indicators) {
if(event.type == indicator.type && event.code == indicator.code) {
filter.listener.on_receive(event);
break;
}
}
}
}
}
void UserInputDevice::notify_close()
{
for(auto &filter : filters) {
filter.listener.on_close();
}
}
void UserInputDevice::listen_thread()
{
struct input_event events[64];
bool error_occurred = false;
while(!stop_thread.load() && !error_occurred) {
if((fd = open(file_name.c_str(), O_RDONLY)) < 0) {
if(errno == ENOENT) {
std::this_thread::sleep_for(std::chrono::seconds(3));
continue;
}
else {
debug_err("user input device '%s' open() failed; %s", file_name.c_str(), errno2str().c_str());
notify_error();
break;
}
}
notify_connect();
//loop for select() and read()
while(!stop_thread.load()) {
fd_set read_fds;
FD_ZERO(&read_fds);
FD_SET(fd, &read_fds);
struct timeval time_out = {1, 0};//1 second
errno = 0;
int ret = select(fd + 1, &read_fds, NULL, NULL, &time_out);
if(stop_thread.load()) {
debug_notice("requested to stop");
break;
}
if(ret == -1) {
if(errno == EBADF) {
debug_notice("device closed");
notify_close();
break;
}
else {
debug_err("select() failed: %s", errno2str().c_str());
error_occurred = true;
notify_error();
break;
}
}
else if(ret == 0) { //select() exited with time out
continue;
}
errno = 0;
ret = read(fd, events, sizeof(events));
if(ret < static_cast<int>(sizeof(struct input_event))) {
notify_close();
debug_err("read() failed: %s", errno2str().c_str());
break;
}
forward_events(events, ret/sizeof(struct input_event));
}
close(fd);
fd = -1;
}
close(fd);
debug_notice("listen_thread() end");
}
} //namespace lunchjet<file_sep>#include "rc_car_controller.h"
#include <debug_log.h>
namespace lunchjet {
RCCarController::RCCarController(const std::string &device_file_name,
RCCarControllerListener &listener,
std::atomic<bool> &stop_thread)
: device(device_file_name, stop_thread),
listener(listener)
{
device.add_listener({
{EV_ABS, ABS_X},
{EV_ABS, ABS_RZ},
{EV_KEY, BTN_SOUTH},
{EV_KEY, BTN_TL},
{EV_ABS, ABS_Z}},
*this);
}
int RCCarController::listen()
{
listener.on_change_throttle(0);
listener.on_change_steering(0);
listener.on_change_brake(0);
return device.listen();
}
void RCCarController::on_connect()
{
listener.on_connect();
}
void RCCarController::on_error()
{
listener.on_error();
}
void RCCarController::on_receive(const struct input_event &event)
{
switch(event.code) {
case ABS_X:
listener.on_change_steering(convert_steering_value(event.value, 0, 65535));
break;
case ABS_RZ:
listener.on_change_throttle(convert_throttle_value(event.value, 0, 1023));
break;
case BTN_SOUTH:
listener.on_change_back(event.value);
break;
case BTN_TL:
if(event.value == 0) { //fire event when the key released
listener.on_select();
}
break;
case ABS_Z:
listener.on_change_brake(convert_throttle_value(event.value, 0, 1023));
break;
default:
debug_warning("unknown code:%d value:%d", event.code, event.value);
}
}
void RCCarController::on_close()
{
listener.on_close();
}
float RCCarController::convert_steering_value(int value, int range_min, int range_max)
{
float ave = (range_min + range_max)/2.0f;
float half_range = (range_max - range_min)/2.0f;
return (value - ave)/half_range;
}
float RCCarController::convert_throttle_value(int value, int range_min, int range_max)
{
return static_cast<float>(value - range_min)/(range_max - range_min);
}
}//namespace lunchjet<file_sep>#include <atomic>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <thread>
#include "rc_car_server.h"
using namespace lunchjet;
namespace {
std::atomic<bool> stop_controller_thread(false);
void signal_handler(int signal) {
stop_controller_thread.store(true);
}
}
int main(int argc, const char *argv[])
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = signal_handler;
sigfillset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
RCCarServer server(stop_controller_thread);
debug_notice("starting server...");
server.start();
debug_notice("server started");
pause();
debug_notice("terminating server...");
return 0;
}<file_sep>#include "pca9685.h"
#include <cmath>
#include <iostream>
#include "debug_log.h"
#include "string_utils.h"
namespace lunchjet {
const int RESOLUTION = 4096;
const uint8_t LED_ONOFF_START_ADDRESS = 0x08;
const uint8_t NUM_REGISTERS_PER_CHANNEL = 4;
PCA9685::PCA9685(uint32_t period_us,
uint8_t adapter_number, uint8_t device_address, uint32_t oscillator_frequency)
:period_us(period_us),
device(adapter_number, device_address)
{
int freq = std::round(static_cast<double>(1000 * 1000) / period_us);
int8_t pre_scale = static_cast<uint8_t>(
std::round((oscillator_frequency / (RESOLUTION * freq)) - 1));
//set PRE_SCALE
device.write(0xFE, pre_scale);
}
int PCA9685::start()
{
//turn off SLEEP bit on MODE1
return device.write(0x00, 0x01);
}
int PCA9685::reset()
{
//turn on RESTART bit on MODE1
return device.write(0x00, 0x91);
}
int PCA9685::set_pulse(uint8_t channel, uint32_t width_us)
{
float duty_rate = width_us/static_cast<double>(period_us);
uint16_t reg_value = static_cast<uint16_t>(std::round(RESOLUTION * duty_rate - 1));
uint8_t register_address = LED_ONOFF_START_ADDRESS + (NUM_REGISTERS_PER_CHANNEL * channel);
return device.transaction()
.add_write(register_address, reg_value & 0xFF) //set LED{channel}_OFF_L
.add_write(register_address + 1, reg_value >> 8) //set LED{channel}_OFF_H
.send();
}
}//namespace lunchjet
<file_sep>#include "i2c.h"
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <vector>
#include <cassert>
#include "debug_log.h"
#include "string_utils.h"
namespace lunchjet {
i2c_msg I2CWriteCommnand::msg() {
return {device_address, 0, static_cast<uint16_t>(data.size()), data.data()};
}
I2CWriteTransaction& I2CWriteTransaction::add_write(uint8_t register_address, uint8_t value) {
commands.push_back(I2CWriteCommnand(device.device_address(), register_address, value));
return *this;
}
int I2CWriteTransaction::send()
{
std::vector<i2c_msg> msgs;
for(auto &command : commands) {
msgs.push_back(command.msg());
}
struct i2c_rdwr_ioctl_data data = {msgs.data(), static_cast<uint32_t>(msgs.size())};
int ret;
errno = 0;
if((ret = ioctl(device.fd(), I2C_RDWR, &data)) < 0) {
debug_err("ioctl() failed: device:%02x reason:%s",
device.device_address(),
strerror(errno));
}
return ret;
}
I2CDevice::I2CDevice(uint8_t adapter_number, uint8_t device_address)
:adapter_number(adapter_number),
_device_address(device_address),
adapter_fd(0)
{
std::string dev_name = "/dev/i2c-" + std::to_string(adapter_number);
errno = 0;
adapter_fd = open(dev_name.c_str(), O_RDWR);
if(adapter_fd == -1) {
debug_err("%s open() error: %s", dev_name.c_str(), strerror(errno));
}
}
int I2CDevice::read(uint8_t register_address, uint8_t &value)
{
int ret;
std::vector<i2c_msg> msgs = {
{_device_address, 0, 1, ®ister_address},
{_device_address, I2C_M_RD, 1, &value}
};
struct i2c_rdwr_ioctl_data data = {msgs.data(), static_cast<uint32_t>(msgs.size())};
errno = 0;
if((ret = ioctl(adapter_fd, I2C_RDWR, &data)) < 0) {
debug_err("ioctl() failed: device:%02x register:%02x reason:%s",
_device_address,
register_address,
strerror(errno));
}
return ret;
}
int I2CDevice::write(uint8_t register_address, uint8_t value)
{
return transaction().add_write(register_address, value).send();
}
I2CDevice::~I2CDevice()
{
close(adapter_fd);
}
} //namespace lunchjet<file_sep>#include "rc_car_server.h"
#include <cmath>
#include <time.h>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include <map>
#include <algorithm>
#include "debug_log.h"
namespace {
const std::string MODEL_PATH = "/opt/lunchjet/model.trt";
const float THROTTLE_GAIN_FORWARD = 0.2f;
const float THROTTLE_GAIN_BACKWARD = 0.3f;
std::string get_log_filename_base() {
struct timespec ts;
clock_gettime(CLOCK_REALTIME_COARSE, &ts);
struct tm _tm;
localtime_r(&(ts.tv_sec), &_tm);
char time_str[20];
strftime(time_str, sizeof(time_str), "%Y_%m_%d_%H_%M_%S",&_tm);
char ms_str[5];
snprintf(ms_str, sizeof(ms_str), "_%03ld", (ts.tv_nsec / (1000 * 1000)));
return std::string(time_str) + std::string(ms_str);
}
}
namespace lunchjet {
RCCarServer::RCCarServer(std::atomic<bool> &stop_controller_thread)
: controller("/dev/input/event2", *this, stop_controller_thread),
video_device(2, [this](auto mat){handle_video(mat);}),
is_going_back(false),
is_connected(false),
steering(0.0f), throttle(0.0f),
throttle_magnification(THROTTLE_GAIN_FORWARD),
is_manual_drived(true),
detector(MODEL_PATH)
{
video_device.start_capture();
}
int RCCarServer::start()
{
return controller.listen();
}
void RCCarServer::on_connect()
{
debug_notice("controller connected");
is_connected = true;
};
void RCCarServer::on_change_steering(float value)
{
if(is_manual_drived) {
driver.steer(value);
steering = value;
}
}
void RCCarServer::on_change_throttle(float value)
{
if(is_manual_drived) {
if(is_going_back) {
driver.back(value * 0.3f);
}
else {
driver.go(value * throttle_magnification);
}
throttle = value;
}
}
void RCCarServer::on_change_brake(float value)
{
//when not braking(value = 0) , throttle_magnification bust be THROTTLE_GAIN_FORWARD
//when full braking(value = 1), throttle_magnification must be 0
throttle_magnification = THROTTLE_GAIN_FORWARD * (1 - value);
}
void RCCarServer::on_change_back(int value)
{
if(is_manual_drived) {
if(value) {
is_going_back = true;
}
else {
is_going_back = false;
}
}
}
void RCCarServer::upload_control_data()
{
#if 0
//upload training data to Google Cloud
debug_notice("stating upload control logs to Google drive...");
std::string shell_param = "PYTHONPATH=" + vars["PYTHONPATH"] +
" python3 /opt/lunchjet/scripts/upload_training_data.py"
" --root /var/log/lunchjet --rm /var/log/lunchjet";
debug_notice("launch : %s", shell_param.c_str());
int res = system(shell_param.c_str());
if(res == 0) {
debug_notice("finish uploading");
}
else {
debug_err("uploading failed : %s", strerror(errno));
}
#endif
}
void RCCarServer::on_select()
{
debug_debug("pressed select button");
//flip the mode
is_manual_drived = !is_manual_drived;
if(!is_manual_drived) {
debug_notice("now autonomous mode");
upload_control_data();
}
else {
debug_notice("now manual mode");
throttle_magnification = THROTTLE_GAIN_FORWARD;
this->on_change_steering(0.0f);
this->on_change_throttle(0.0f);
}
}
void RCCarServer::on_close()
{
debug_notice("controller disconnected");
is_connected = false;
}
void RCCarServer::record_control_data(cv::Mat &image)
{
if(!is_connected || std::abs(throttle) < 0.1) {
return;
}
std::string file_base = get_log_filename_base();
std::string image_file_name = file_base + ".jpg";
std::ofstream ofs_drive(std::string(LOG_ANNOTAION_DIR) + "/" + file_base + ".log");
if(!ofs_drive) {
debug_err("annotation log write failed");
return;
}
ofs_drive << image_file_name << " " << steering << " " << throttle << std::endl;
cv::imwrite(std::string(LOG_IMAGE_DIR) + "/" + image_file_name, image);
}
void RCCarServer::handle_video(cv::Mat &image)
{
if(is_manual_drived) {
record_control_data(image);
}
else {
auto params = detector.detect(image);
driver.steer(params.steering);
driver.go(params.throttle * throttle_magnification);
}
}
} //namespace lunchjet<file_sep># Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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 print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from googleapiclient.http import MediaFileUpload
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive']
#mime type of Google Drive's directory
DIR_MTYPE = 'application/vnd.google-apps.folder'
class GoogleDrive:
def __init__(self, client_secret_file, token_file):
self.creds = self._get_cred(client_secret_file=client_secret_file, token_file=token_file)
self.service = build('drive', 'v3', credentials=self.creds)
def _get_cred(self, client_secret_file, token_file):
creds = None
if os.path.exists(token_file):
creds = Credentials.from_authorized_user_file(token_file, SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
client_secret_file, SCOPES)
creds = flow.run_local_server(port=0)
with open(token_file, 'w') as token:
token.write(creds.to_json())
return creds
def create_file(self, name, content_file_name=None, *, mime_type=None, parent_dir_id=None):
paths = name.split('/')
file_name = paths[-1]
dir = '/'.join(paths[:-1])
body = {'name' : file_name}
if dir is not None and len(dir) > 0:
parent_dir_id = self.get_directory(dir, parent_dir_id=parent_dir_id).get('id')
if parent_dir_id is not None:
body['parents'] = [parent_dir_id]
if content_file_name is None:
content_file_name = name
media = MediaFileUpload(content_file_name, mimetype=mime_type, resumable=True)
file = self.service.files().create(
body = body,
media_body = media,
media_mime_type = mime_type
).execute()
return file
def create_directory(self, name, *, parent_dir_id=None):
body = {
'name' : name,
'mimeType': DIR_MTYPE
}
if parent_dir_id is not None:
body['parents'] = [parent_dir_id]
file = self.service.files().create(body = body).execute()
return file
def find_files(self, name, *, mime_type=None, parent_dir_id=None):
qs = [
"name = '{}'".format(name),
"trashed = false"] #exclude entries in trash
if mime_type is not None:
qs.append("mimeType='{}'".format(mime_type))
if parent_dir_id is not None:
qs.append("'{}' in parents".format(parent_dir_id))
q = None
if len(qs) > 0:
q = ' and '.join(qs)
page_token = None
files = []
while True:
response = self.service.files().list(q=q,
spaces='drive',
fields='nextPageToken, files(id, name)',
pageToken=page_token).execute()
for file in response.get('files', []):
files.append(file)
page_token = response.get('nextPageToken', None)
if page_token is None:
break
return files
def get_directory(self, name, *, parent_dir_id=None, force_create=True):
dir_names = name.split('/')
ret = None
pdi = parent_dir_id
for dir_name in dir_names:
dir = self.find_files(dir_name, mime_type=DIR_MTYPE, parent_dir_id=pdi)
if dir is not None and len(dir) > 0:
ret = dir[0]
else:
if force_create is True:
ret = self.create_directory(dir_name, parent_dir_id=pdi)
else:
return None
pdi = ret['id']
return ret
def test():
gdrive = GoogleDrive(client_secret_file='credentials.json', token_file='token.json')
file = gdrive.create_file('lunchbox/annotations/test.txt', 'test.txt')
print(str(file))
if __name__ == '__main__':
test()
<file_sep>#pragma once
#include <string>
#include <memory>
#include "opencv2/opencv.hpp"
#include "NvInfer.h"
namespace lunchjet {
struct DriveParameter {
float steering;
float throttle;
};
class DriveDetector {
public:
DriveDetector(const std::string &model_file_path);
~DriveDetector();
DriveParameter detect(const cv::Mat &image);
private:
struct InferDeleter
{
template <typename T>
void operator()(T* obj) const
{
if (obj) obj->destroy();
}
};
template <typename T> using unique_ptr_for_nv = std::unique_ptr<T, InferDeleter>;
std::string engine_file_path;
unique_ptr_for_nv<nvinfer1::ICudaEngine> engine;
unique_ptr_for_nv<nvinfer1::IExecutionContext> context;
size_t input_mem_size;
size_t output_mem_size;
void* input_mem;
void* output_mem;
cudaStream_t stream;
};
} //namespace lunchjet<file_sep>#pragma once
#include <stdint.h>
#include <vector>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
namespace lunchjet {
class I2CDevice;
/**
* a class represents an I2C write command
*/
class I2CWriteCommnand {
public:
I2CWriteCommnand() = delete;
/**
* @param[in] device_address a device address
* @param[in] register_address a register address within the device
* @param[in] value a register value to set
*/
I2CWriteCommnand(uint8_t device_address, uint8_t register_address, uint8_t value)
:device_address(device_address),
data({register_address, value}){}
~I2CWriteCommnand() = default;
/**
* create i2c_msg for the commands
*/
i2c_msg msg();
private:
uint8_t device_address;
std::vector<uint8_t> data;
};
/**
* a class represents an I2C command transaction
*/
class I2CWriteTransaction{
public:
/**
* @param device I2C device to send the transaction
*/
I2CWriteTransaction(I2CDevice &device) : device(device){};
~I2CWriteTransaction() = default;
/**
* add a write commands to the transaction
* @param[in] register_address register address
* @param[in] register_value register value
*/
I2CWriteTransaction& add_write(uint8_t register_address, uint8_t value);
/**
* send the transaction to the device
*/
int send();
private:
I2CDevice &device;
std::vector<I2CWriteCommnand> commands;
};
/**
* a class represents an I2C device
*/
class I2CDevice {
public:
I2CDevice() = delete;
/**
* @param[in] adapter_number an adapter number that contains the I2C device
* @param[in] device_address a device address in the device adapter
*/
I2CDevice(uint8_t adapter_number, uint8_t device_address);
~I2CDevice();
/**
* read value of an register
* @param[in] register_address an address of the register
* @param[out] value the value of the register
*/
int read(uint8_t register_address, uint8_t &value);
/**
* write value of an register
* @param[in] register_address an address of the register
* @param[in] value the value of the register
*/
int write(uint8_t register_address, uint8_t value);
/**
* create an transaction for inputting some commands for the device
*/
I2CWriteTransaction transaction() {
return I2CWriteTransaction(*this);
};
/**
* get the file descriptor of the device
* @return file descriptor
*/
int fd(){ return adapter_fd; }
/**
* get the address for the device
*/
uint8_t device_address() { return _device_address; }
private:
uint8_t adapter_number;
uint8_t _device_address;
int adapter_fd;
};
} //namespace lunchjet<file_sep>#pragma once
#include <atomic>
#include <memory>
#include "rc_car_controller.h"
#include "rc_car_driver.h"
#include "video_input_device.h"
#include "debug_log.h"
#include "string_utils.h"
#include "setting_variables.h"
#include "drive_detector.h"
namespace lunchjet
{
class RCCarServer : public RCCarControllerListener {
public:
RCCarServer() = delete;
RCCarServer(std::atomic<bool> &stop_controller_thread);
~RCCarServer() = default;
/**
* start processing
*/
int start();
//member functions for RCCarControllerListener
void on_connect() override;
void on_change_steering(float value) override;
void on_change_throttle(float value) override;
void on_change_brake(float value) override;
void on_change_back(int value) override;
void on_select() override;
void on_close() override;
private:
RCCarDriver driver;
RCCarController controller;
VideoInputDevice video_device;
bool is_going_back;
std::atomic<bool> is_connected;
std::atomic<float> steering, throttle;
std::atomic<float> throttle_magnification;
bool is_manual_drived;
SettingVariables vars;
DriveDetector detector;
void handle_video(cv::Mat &image);
void record_control_data(cv::Mat &image);
void upload_control_data();
};
} //namespace lunchjet<file_sep>cmake_minimum_required(VERSION 3.10)
project("LunchJet drive controller")
find_package( OpenCV REQUIRED )
find_path(TENSORRT_INCLUDE_DIR NvInfer.h)
find_library(TENSORRT_LIB nvinfer
PATHS /usr/local/cuda/targets/aarch64-linux/lib)
find_path(CUDA_RUNTIME_INCLUDE_DIR cuda_runtime_api.h
PATHS /usr/local/cuda/targets/aarch64-linux/include/)
find_library(CUDA_RUNTIME_LIB cudart
PATHS /usr/local/cuda/targets/aarch64-linux/lib)
add_library(lunchjet_drive_detector STATIC drive_detector.cpp)
target_include_directories(lunchjet_drive_detector PUBLIC .)
target_include_directories(lunchjet_drive_detector
PRIVATE ${OpenCV_INCLUDE_DIRS} ${TENSORRT_INCLUDE_DIR} ${CUDA_RUNTIME_INCLUDE_DIR})
target_link_libraries(lunchjet_drive_detector
lunchjet_include ${OpenCV_LIBS} ${TENSORRT_LIB} ${CUDA_RUNTIME_LIB})<file_sep>cmake_minimum_required(VERSION 3.10)
project("LunchJet PCA9685")
add_library(lunchjet_pca9685 STATIC pca9685.cpp)
target_link_libraries(lunchjet_pca9685 lunchjet_i2c)
target_include_directories(lunchjet_pca9685 PUBLIC .)<file_sep>#include "pca9685.h"
#include <iostream>
#include <thread>
using namespace lunchjet;
int main(int argc, const char *argv[])
{
PCA9685 driver(17.5 * 1000);
driver.set_pulse(0, 1.5 * 1000);
driver.set_pulse(1, 1.5 * 1000);
driver.start();
std::this_thread::sleep_for(std::chrono::seconds(2));
//servo motor control
//turn left
driver.set_pulse(0, 1.1 * 1000);
std::this_thread::sleep_for(std::chrono::seconds(2));
//neutral
driver.set_pulse(0, 1.5 * 1000);
std::this_thread::sleep_for(std::chrono::seconds(2));
//turn right
driver.set_pulse(0, 1.9 * 1000);
std::this_thread::sleep_for(std::chrono::seconds(2));
//neutral
driver.set_pulse(0, 1.5 * 1000);
std::this_thread::sleep_for(std::chrono::seconds(2));
//drive mortor control
//move backward
driver.set_pulse(1, 1.9 * 1000);
std::this_thread::sleep_for(std::chrono::seconds(1));
driver.set_pulse(1, 1.5 * 1000);
std::this_thread::sleep_for(std::chrono::seconds(1));
driver.set_pulse(1, 1.6 * 1000);
//neutral
std::this_thread::sleep_for(std::chrono::seconds(2));
driver.set_pulse(1, 1.5 * 1000);
//move forward
std::this_thread::sleep_for(std::chrono::seconds(2));
driver.set_pulse(1, 1.45 * 1000);
//neutral
std::this_thread::sleep_for(std::chrono::seconds(2));
driver.set_pulse(1, 1.5 * 1000);
// std::this_thread::sleep_for(std::chrono::seconds(3));
// driver.reset();
return 0;
}<file_sep>#pragma once
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <stdint.h>
#include <linux/input.h>
#include <atomic>
namespace lunchjet {
/**
* a class that represents an user input device
* @see https://www.kernel.org/doc/html/latest/input/input_uapi.html
*/
class UserInputDevice {
public:
/**
* @param[in] file_name device file name
* @param[in] stop_thread a flag to stop receiving the input events
*/
UserInputDevice(const std::string &file_name, const std::atomic<bool> &stop_thread);
~UserInputDevice();
class EventListener {
public:
/**
* an event handler for starting connection with the device
*/
virtual void on_connect(){}
/**
* an event handler for receiving input events
* @param[in] event an input event
*/
virtual void on_receive(const struct input_event &event) = 0;
/**
* an event handler for closing connection with the device
*/
virtual void on_close(){}
/**
* an event handler for occurring some error that can't be fixed (see errno for detail)
* after calling this function, the class will stop working.
*/
virtual void on_error(){exit(1);}
};
struct EventIndicator {
uint16_t type; //!< the type of the event. (see struct input_event::type)
uint16_t code; //!< the code of the event. (see struct input_event::type)
};
/**
* add a listener to receive input events
* @param[in] indicators
* @param[in] listener the listener
*/
void add_listener(const std::vector<EventIndicator> &indicators, EventListener &listener);
/**
* start receiving input events for the listener
* @return >= 0 on success, otherwise error (see errno)
*/
int listen();
private:
struct EventFilter {
std::vector<EventIndicator> indicators;
EventListener &listener;
};
std::string file_name;
std::vector<EventFilter> filters;
std::mutex mutex_filters;
int fd;
std::thread waiting_thread;
const std::atomic<bool> &stop_thread;
void listen_thread();
void notify_connect();
void notify_error();
void forward_events(const struct input_event *events, int num_events);
void notify_close();
};
}//namespace lunchjet<file_sep>cmake_minimum_required(VERSION 3.10)
project("LunchJet scripts")
file(GLOB files_in_package lunchjet/*.py)
install(FILES upload_training_data.py DESTINATION /opt/lunchjet/scripts)
install(FILES ${files_in_package} DESTINATION /opt/lunchjet/scripts/lunchjet)
<file_sep>cmake_minimum_required(VERSION 3.10)
project("LunchJet i2c")
add_library(lunchjet_i2c STATIC i2c.cpp)
target_link_libraries(lunchjet_i2c lunchjet_include)
target_include_directories(lunchjet_i2c PUBLIC .)<file_sep>cmake_minimum_required(VERSION 3.10)
project("LunchJet RC Car")
add_library(lunchjet_rc_car_driver STATIC rc_car_driver.cpp)
target_link_libraries(lunchjet_rc_car_driver lunchjet_pca9685)
target_include_directories(lunchjet_rc_car_driver PUBLIC .)<file_sep>#include "rc_car_driver.h"
namespace lunchjet {
enum RC_CAR_CH {
STEER_SERVO = 0,
DRIVE_MOTOR
};
static const uint32_t NEUTRAL_PULSE_WIDTH_US = 1.5 * 1000;
static const uint32_t MAX_PULSE_WIDTH_US = 1.95 * 1000;
static const uint32_t PULSE_WIDTH_RANGE_US
= MAX_PULSE_WIDTH_US - NEUTRAL_PULSE_WIDTH_US;
inline static uint32_t pulse_width(float value) {
return NEUTRAL_PULSE_WIDTH_US + (value * PULSE_WIDTH_RANGE_US);
}
RCCarDriver::RCCarDriver()
: driver(17.5 * 1000)
{
driver.set_pulse(STEER_SERVO, NEUTRAL_PULSE_WIDTH_US);
stop();
driver.start();
}
RCCarDriver::~RCCarDriver()
{
stop();
}
int RCCarDriver::steer(float value)
{
return driver.set_pulse(STEER_SERVO, pulse_width(value));
}
int RCCarDriver::go(float throttle)
{
//avoid to move backward
if(throttle < 0) {
throttle = 0.0f;
}
return driver.set_pulse(DRIVE_MOTOR, pulse_width(-throttle));
}
int RCCarDriver::back(float throttle)
{
if(throttle < 0) {
throttle = 0.0f;
}
return driver.set_pulse(DRIVE_MOTOR, pulse_width(throttle));
}
int RCCarDriver::stop()
{
driver.set_pulse(DRIVE_MOTOR, NEUTRAL_PULSE_WIDTH_US);
}
}//namespace lunchjet<file_sep>#pragma once
#include <stdint.h>
#include "i2c.h"
namespace lunchjet {
/**
* PCA 9685 LED controller
* @see https://www.nxp.com/docs/en/data-sheet/PCA9685.pdf
*/
class PCA9685 {
public:
/**
* @param[in] period_us period of sending pulses in microsecconds
*/
PCA9685(uint32_t period_us,
uint8_t adapter_number = DEFAULT_ADAPTER_NUMBER,
uint8_t device_address = DEFAULT_DEVICE_ADDRESS,
uint32_t oscillator_frequency = DEFAULT_OSCILLATOR_FREQUENCY);
~PCA9685() = default;
/**
* start sending the pulses of each channel
* @return 0 on success, otherwise error (see errno)
*/
int start();
/**
* reset the chip
* @return 0 on success, otherwise error (see errno)
*/
int reset();
/**
* set pulse without delay
* @param[in] channel channel number within 0-15
* @param[in] width_us pulse width in microsecconds
* @return 0 on success, otherwise error (see errno)
*/
int set_pulse(uint8_t channel, uint32_t width_us);
static const uint8_t DEFAULT_ADAPTER_NUMBER = 0x01;
static const uint8_t DEFAULT_DEVICE_ADDRESS = 0x40;
static const uint32_t DEFAULT_OSCILLATOR_FREQUENCY = 25 * 1000 * 1000;
private:
uint32_t period_us;
I2CDevice device;
};
}//namespace lunchjet<file_sep>cmake_minimum_required(VERSION 3.10)
project("LunchJet include")
add_library(lunchjet_include INTERFACE)
target_include_directories(lunchjet_include INTERFACE .)<file_sep>cmake_minimum_required(VERSION 3.10)
project("LunchJet User Input Device")
add_library(lunchjet_user_input_device STATIC user_input_device.cpp)
target_link_libraries(lunchjet_user_input_device lunchjet_include pthread)
target_include_directories(lunchjet_user_input_device PUBLIC .)<file_sep>#pragma once
#include "pca9685.h"
namespace lunchjet {
/**
* a class to drive RC car
*/
class RCCarDriver {
public:
RCCarDriver();
~RCCarDriver();
/**
* set steering value
* @param[in] value from -1.0 to 1.0. -1.0 means turning left. 1.0 means turning right.
* @return 0 on success, otherwise error (see errno)
*/
int steer(float value);
/**
* go forward with a specific throttle (memo: 0.084 is seemed to be a threshold to actual move)
* @param[in] throttle from 0.0 to 1.0. 0.0 means stopping. 1.0 means going with full throttle.
* @return 0 on success, otherwise error (see errno)
*/
int go(float throttle);
/**
* go backward with a specific throttle
* @param[in] throttle from 0.0 to 1.0. 0.0 means stopping. 1.0 means going with full throttle.
* @return 0 on success, otherwise error (see errno)
*/
int back(float throttle);
/**
* stop the drive motor
* @return 0 on success, otherwise error (see errno)
*/
int stop();
private:
PCA9685 driver;
};
}//namespace lunchjet<file_sep>#include <iostream>
#include <chrono>
#include <thread>
#include "video_input_device.h"
#include "string_utils.h"
using namespace lunchjet;
int main(int argc, const char *argv[])
{
std::cout << "start " << std::string(argv[0]) << std::endl;
VideoInputDevice device(2,
[](auto mat){std::cout << "complete: " << mat.cols << "x" << mat.rows << std::endl;});
if(!device.start_capture()) {
std::cerr << "start_capture() failed: " << errno2str() << std::endl;
return -1;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
return 0;
}
<file_sep>if '__file__' in globals():
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from lunchjet import GoogleDrive
import time
import tarfile
from argparse import ArgumentParser
import re
import pathlib
def unlink_files_in(dir_path):
for file in dir_path.glob('**/*'):
if file.is_file():
file.unlink()
def main():
parser = ArgumentParser(description="create tarball and upload it to Google Drive")
parser.add_argument('files', metavar='FILE', type=str, nargs='+', help='files to send')
parser.add_argument('--root', metavar='ROOT_DIR', type=str, nargs='?', default=None,
help='root directory of the archive. files in the archive is put in relateve path from this directory. this is usable if FILE(s) is absolute path')
parser.add_argument('--rm', action='store_true', help='delete sent files. if FILE is a directory, only files in the directory are to be deleted.')
args = parser.parse_args()
if args.root is None:
args.root = str()
# create tarball
tarball_name = "train_{}.tar.gz".format(time.strftime('%Y_%m_%d_%H_%M_%S'))
with tarfile.open(tarball_name, "w|gz") as archive:
for file in args.files:
#if --root are there, make the file path in the archive to be relative
relative_path = re.sub('^{}'.format(args.root), '', file)
relative_path = re.sub('^/', '', relative_path)
archive.add(file, arcname=relative_path)
print('create {}'.format(tarball_name))
# upload the tarball to Google Drive
gdrive = GoogleDrive(client_secret_file='/etc/lunchjet/credentials.json', token_file='/etc/lunchjet/token.json')
file = gdrive.create_file('lunchjet/' + tarball_name, tarball_name)
print('upload a file to gdrive : {}'.format(str(file)))
pathlib.Path(tarball_name).unlink()
# delete files if needed
if args.rm:
for file in args.files:
file_path = pathlib.Path(file)
if file_path.is_dir():
unlink_files_in(file_path)
else:
file_path.unlink()
if __name__ == '__main__':
main()
<file_sep>#pragma once
#include <functional>
#include <thread>
#include <atomic>
#include <opencv2/opencv.hpp>
namespace lunchjet {
class VideoInputDevice {
public:
/**
* function type for event handle with captured a image
*/
using ProcessingFunction = std::function<void(cv::Mat &)>;
VideoInputDevice() = delete;
/**
* @param[in] device_index N in /dev/videoN
*/
VideoInputDevice(int device_index, ProcessingFunction func);
~VideoInputDevice();
/**
* start capturing
* @return true if successful
*/
bool start_capture();
/**
* stop capturing
* @return true if successful
*/
bool stop_capture();
private:
void main_loop();
int device_index;
ProcessingFunction func;
std::thread thread;
std::atomic<bool> stop_thread;
};
} //namespace lunchjet<file_sep># LunchJet
[Jetson Nano](https://developer.nvidia.com/embedded/jetson-nano-developer-kit) as a RC controller on [Lunch Box](https://www.tamiya.com/english/products/58347lunchbox/index.htm), which is a RC car made by Tamiya


# system components

# data flow diagram

# prerequisite
[v2l4loopback](https://github.com/umlaeute/v4l2loopback) is needed to run the LunchJet.
```bash
$ git clone https://github.com/umlaeute/v4l2loopback
$ cd v4l2loopback
$ make && sudo make install
```
# build and install
```bash
$ mkdir build && cd build
build$ cmake .. && make VERBOSE=1 -j4 && sudo make install
```<file_sep>#pragma once
#include <fstream>
#include <string>
#include <map>
#include <memory>
#include "debug_log.h"
namespace lunchjet {
/**
* a class to store settings for the system
*/
class SettingVariables {
public:
SettingVariables() {
std::ifstream ifs("/etc/lunchjet/lunchjet.conf");
if(!ifs){
debug_notice("configuration file reading failed");
return;
}
int no_lines = 1;
auto buf = std::make_unique<char[]>(BUF_LEN);
while(!ifs.eof()) {
ifs.getline(buf.get(), BUF_LEN);
if(ifs.bad()) {
debug_warning("too long configuration string in line %d, skipping...", no_lines);
}
else {
add_key_value(std::string(buf.get()), no_lines);
}
}
}
std::string operator[](const std::string &key) {
return vars[key];
}
private:
static const int BUF_LEN = 1024;
std::map<std::string, std::string> vars;
void add_key_value(const std::string str, const int line) {
if(str.empty() || str[0] == '#') { //a line to be skipped
return;
}
auto pos = str.find("=");
if(pos == std::string::npos) {
debug_warning("line %d unrecognized", line);
return;
}
std::string key(str, 0, pos);
std::string value(str, pos+1, str.size()-(pos+1));
debug_notice("setting variable : %s=%s", key.c_str(), value.c_str());
vars.insert(std::make_pair(key, value));
}
};
} // namespace lunchjet
<file_sep>#pragma once
#include <string>
#include <atomic>
#include "user_input_device.h"
namespace lunchjet {
/**
* a class having call back functions for recieving events about RC car controller
*/
class RCCarControllerListener {
public:
/**
* an event handler for connection with the controller
*/
virtual void on_connect(){};
/**
* an event handler for occurring on the connection
*/
virtual void on_error(){exit(1);}
/**
* an event handler for receiving value of steering
* @param[in] value direction of steering. -1 for turning left, 1 for tuning right.
*/
virtual void on_change_steering(float value) = 0;
/**
* an event handler for receiving value for throttle
* @param[in] value throttle strength, 0 for stopping, 1 for full throttle.
*/
virtual void on_change_throttle(float value) = 0;
/**
* an event handler for receiving value for brake
* @param[in] value brake strength, 0 for not braking, 1 for full braking.
*/
virtual void on_change_brake(float value) = 0;
/**
* an event handler for recieving status of the back button
* @param[in] value status of the back button, 0 with pressed, 1 with released
*/
virtual void on_change_back(int value) = 0;
/**
* an event handler for selecting input (press select key)
* between AI and persons
*/
virtual void on_select(){}
/**
* an event handler for closing connnection with the controller
* (the class will retry to wait new connection)
*/
virtual void on_close(){}
};
/**
* a class for recieving events from RC car controller device
*/
class RCCarController : public UserInputDevice::EventListener {
public:
/**
* @param[in] device_file_name a file name of a controller devece (e.g., "/dev/input/event1")
* @param[in] listener a listener to receive input events about the controller
* @param[in] stop_thread a flag for stopping a thread in this instance
*/
RCCarController(const std::string &device_file_name,
RCCarControllerListener &listener,
std::atomic<bool> &stop_thread);
~RCCarController() = default;
/**
* start sending the input events to the listener
* @return >= 0 on success, otherwise error (see errno)
*/
int listen();
/**
* an function for internal use only, do not coll from users.
*/
virtual void on_connect() override;
/**
* an function for internal use only, do not coll from users.
*/
void on_receive(const struct input_event &event) override;
/**
* an function for internal use only, do not coll from users.
*/
void on_close() override;
/**
* an function for internal use only, do not coll from users.
*/
virtual void on_error() override;
private:
UserInputDevice device;
RCCarControllerListener &listener;
float convert_steering_value(int value, int range_min, int range_max);
float convert_throttle_value(int value, int range_min, int range_max);
};
}//namespace lunchjet<file_sep>#include "rc_car_controller.h"
#include <iostream>
#include <linux/input.h>
#include <linux/input-event-codes.h>
#include <atomic>
#include <signal.h>
#include <string.h>
#include <unistd.h>
using namespace lunchjet;
namespace {
std::atomic<bool> stop_controller_thread(false);
void signal_handler(int signal) {
stop_controller_thread.store(true);
}
}
using namespace lunchjet;
class ControllerListener : public RCCarControllerListener {
void on_change_steering(float value) override {
std::cout << "steering:" << value << std::endl;
}
void on_change_throttle(float value) override {
std::cout << "throttle:" << value << std::endl;
}
void on_change_back(int value) override {
if(value) {
std::cout << "back button pressed" << std::endl;
}
else {
std::cout << "back button released" << std::endl;
}
}
void on_change_brake(float value) override {
std::cout << "brake: " << value << std::endl;
}
};
int main(int argc, const char *argv[])
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = signal_handler;
sigfillset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
ControllerListener listener;
RCCarController controller("/dev/input/event2", listener, stop_controller_thread);
if(controller.listen() < 0) {
perror("listen() failed");
exit(1);
}
std::cout << "hello world" << std::endl;
pause();
return 0;
}<file_sep>cmake_minimum_required(VERSION 3.10)
project("LunchJet User Input Device")
add_library(lunchjet_rc_car_controller STATIC rc_car_controller.cpp)
target_link_libraries(lunchjet_rc_car_controller lunchjet_include lunchjet_user_input_device)
target_include_directories(lunchjet_rc_car_controller PUBLIC .)<file_sep>#include "user_input_device.h"
#include <iostream>
#include <linux/input.h>
#include <linux/input-event-codes.h>
#include <atomic>
#include <signal.h>
#include <string.h>
#include <unistd.h>
using namespace lunchjet;
namespace {
std::atomic<bool> stop_user_input_device_thread(false);
void signal_handler(int signal) {
stop_user_input_device_thread.store(true);
}
}
class Listener : public UserInputDevice::EventListener {
void on_connect() {
std::cout << "connect" << std::endl;
}
void on_receive(const struct input_event &event) override {
std::cout << "event type:" << event.type << " code:" << event.code << " value:" << event.value << std::endl;
}
void on_close() {
std::cout << "close" << std::endl;
}
};
int main(int argc, const char *argv[])
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = signal_handler;
sigfillset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
UserInputDevice device("/dev/input/event3", stop_user_input_device_thread);
Listener listener;
device.add_listener({{EV_ABS, ABS_X}, {EV_ABS, ABS_RZ}}, listener);
if(device.listen() == -1){
std::cout << "listen() failed" << std::endl;
exit(1);
}
pause();
std::cout << "exit main()" << std::endl;
return 0;
}<file_sep>from lunchjet.googledrive import *<file_sep>#include <iostream>
#include <iomanip>
#include <syslog.h>
#include <string.h>
#include "i2c.h"
#include "string_utils.h"
using namespace lunchjet;
int main(int argc, const char *argv[])
{
//
// This program tests I2C by doing read-write-verify with lunchjet::I2CDevice
//
if(argc < 5) {
std::cout << "usage: " << std::string(argv[0])
<< " ADAPTER_NUM DEVICE_ADDRESS REGISTER_ADDRESS REGISTER_VALUE" << std::endl;
exit(1);
}
uint8_t adapter_num = str2hex_u8(argv[1]);
uint8_t device_address = str2hex_u8(argv[2]);
uint8_t register_address = str2hex_u8(argv[3]);
uint8_t register_value = str2hex_u8(argv[4]);
openlog("i2c_test", LOG_CONS | LOG_PID, LOG_USER);
std::cout << "adp:" << hex2str(adapter_num) << " dev:" << hex2str(device_address)
<< " reg:" << hex2str(register_address) << " val:" << hex2str(register_value) << std::endl;
auto device = I2CDevice(adapter_num, device_address);
//read
uint8_t read_value;
if(device.read(register_address, read_value) > 0) {
std::cout << "read register value " << hex2str(read_value) << std::endl;
}
else {
std::cout << "read some error occurred: " << errno2str() << std::endl;
exit(1);
}
//write
if(device.write(register_address, register_value) > 0) {
std::cout << "write register value " << hex2str(register_value) << std::endl;
}
else {
std::cout << "write some error occurred: " << errno2str() << std::endl;
exit(1);
}
//read again
if(device.read(register_address, read_value) > 0) {
std::cout << "read register value " << hex2str(read_value) << std::endl;
}
else {
std::cout << "read some error occurred: " << errno2str() << std::endl;
exit(1);
}
//verify
if(register_value == read_value) {
std::cout << "verify success" << std::endl;
}
else {
std::cout << "verify failed" << std::endl;
exit(1);
}
return 0;
}<file_sep>#pragma once
#include <string>
#include <sstream>
#include <iomanip>
#include <string.h>
namespace lunchjet {
/**
* convers an hexadecimal value to an string
* @param[in] value the hexadecimal value
* @return the string
*/
template<typename T> std::string hex2str(T &&value)
{
std::stringstream ss_num;
ss_num << std::hex << std::setfill('0') << std::setw(sizeof(T)*2) << std::uppercase << static_cast<int>(value);
std::stringstream ss;
ss << "0x" << ss_num.str();
return ss.str();
}
/**
* gets an string associated with an errno
*/
inline std::string errno2str()
{
return std::string(strerror(errno));
}
/**
* converts an string that represents an number to 8 bit number
* @param[in] str the string
* @return the number
*/
inline uint8_t str2hex_u8(const std::string &str)
{
return static_cast<uint8_t>(std::stoi(str, nullptr, 0));
}
/**
* converts an string that represents an number to 8 bit number
* @param[in] str the string
* @return the number
*/
inline uint8_t str2hex_u8(const char *str)
{
return str2hex_u8(std::string(str));
}
} //namespace lunchjet
<file_sep>#include "rc_car_driver.h"
#include <iostream>
#include <thread>
#include <cmath>
using namespace lunchjet;
int main(int argc, const char *argv[])
{
RCCarDriver car;
//swing the steering
for(float s = 0.f; s <= 3.f; s+=0.05f) {
car.steer(std::sin(2*M_PI*s));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
//stop and go
for(float s = 0.f; s <= 2.f; s+=0.01f) {
auto throttle = 0.2/*max throttle cap*/ * ((-std::cos(2*M_PI*s)+1)/2);
car.go(throttle);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
return 0;
}<file_sep>#include "video_input_device.h"
#include <iostream>
#include <opencv2/videoio.hpp>
#include "debug_log.h"
namespace lunchjet
{
VideoInputDevice::VideoInputDevice(int device_index, ProcessingFunction func)
: device_index(device_index), func(func), stop_thread(false)
{
}
bool VideoInputDevice::start_capture()
{
stop_thread = false;
thread = std::thread([this]{main_loop();});
return true;
}
bool VideoInputDevice::stop_capture()
{
stop_thread = true;
if(thread.joinable()) {
thread.join();
}
return true;
}
VideoInputDevice::~VideoInputDevice()
{
stop_capture();
}
void VideoInputDevice::main_loop()
{
debug_notice("main loop start");
cv::VideoCapture device(device_index);
cv::Mat mat;
while(!stop_thread.load()) {
if(device.grab()) {
device.retrieve(mat);
func(mat);
}
}
debug_notice("main loop end");
}
} //namespace lunchjet<file_sep>#pragma once
#include <chrono>
/**
* get time point of now
*/
inline std::chrono::system_clock::time_point time_now()
{
return std::chrono::system_clock::now();
}
/**
* return duration in millisecconds until now from a ceartain time point
* @param[in] start point of the duration
* @return the duration in milliseconds
*/
inline auto duration_ms_from(std::chrono::system_clock::time_point &from)
{
return std::chrono::duration_cast<std::chrono::milliseconds>(time_now() - from).count();
}<file_sep>#pragma once
#include <syslog.h>
#define debug_debug( message, ... ) (syslog(LOG_DEBUG, "[%s]" message, __func__, ##__VA_ARGS__))
#define debug_info( message, ... ) (syslog(LOG_INFO, "[%s]" message, __func__, ##__VA_ARGS__))
#define debug_notice( message, ... ) (syslog(LOG_NOTICE, "[%s]" message, __func__, ##__VA_ARGS__))
#define debug_warning( message, ... ) (syslog(LOG_WARNING, "[%s]" message, __func__, ##__VA_ARGS__))
#define debug_err( message, ... ) (syslog(LOG_ERR, "[%s]" message, __func__, ##__VA_ARGS__))
#define debug_crit( message, ... ) (syslog(LOG_CRIT, "[%s]" message, __func__, ##__VA_ARGS__))
#define debug_alert( message, ... ) (syslog(LOG_ALERT, "[%s]" message, __func__, ##__VA_ARGS__))
#define debug_emerg( message, ... ) (syslog(LOG_EMERG, "[%s]" message, __func__, ##__VA_ARGS__))
| d0c5c1182da6a94787824eb0307f3d2232a55279 | [
"CMake",
"Markdown",
"Python",
"C",
"C++"
] | 44 | C++ | kimito/lunchjet | c765d51e6376f597aeea0cf878bced92d734d022 | 8f3bfde9b67bd9c1ef63ed0327560de0bc6db4d6 |
refs/heads/master | <file_sep># Generated by Django 2.1.3 on 2019-03-13 20:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0007_auto_20190312_2016'),
]
operations = [
migrations.RemoveField(
model_name='survey',
name='beaches',
),
]
<file_sep>import csv
from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListView,DetailView, CreateView, UpdateView, DeleteView
from .models import Post, Survey
from django.contrib.auth import login
from django.views.generic.base import TemplateView
from django.http import HttpResponse
from django.views.generic import TemplateView
from django.shortcuts import render, redirect
from blog.forms import SurveyForm
from django.template.context_processors import request
from django.forms.formsets import formset_factory
from lxml import html
import requests
from datetime import datetime
import blog.transferBeachValue
from blog import forms
from test.test_warnings.data.stacklevel import inner
import datetime
BEACHES = {
"Pismo Beach": "pismo",
"Morro Bay": "morro",
"Cayucos Beach": "cayucos",
"Oceano Beach": "oceano",
"Coronado Beach": "coronado",
"Zuma Beach": "zuma",
"Huntington Beach": "huntington",
"Imperial Beach": "imperial",
"Moonlight Beach": "moonlight",
"Silver Strand Beach": "silverStrand",
"Santa Monica Beach": "santaMonica",
"Avila Beach": "avila",
"Point Mugu Beach": "pointMugu",
}
websiteLibrary = {
"pismoST": "http://www.surf-forecast.com/breaks/Pismo-Beach-Pier/seatemp",
"pismoTC": "https://www.weatherforyou.com/reports/index.php?config=&forecast=zandh&pands=pismo+beach&Submit=Get+Weather",
"morroSeaTemp": "http://www.surf-forecast.com/breaks/Morro-Bay/seatemp",
"morroTempCoord":"https://www.weatherforyou.com/reports/index.php?config=&forecast=zandh&pands=Morro+Bay+State+Park&Submit=Get+Weather",
"cayucosST": "http://www.surf-forecast.com/breaks/Cayucos-Pier/seatemp",
"cayucosTC": "https://www.weatherforyou.com/reports/index.php?config=&forecast=zandh&pands=93430&Submit=Get+Weather",
"oceanoST": "http://www.surf-forecast.com/breaks/Oceano/seatemp",
"oceanoTC": "https://www.weatherforyou.com/reports/index.php?config=&forecast=zandh&pands=Oceano&Submit=Get+Weather",
"coronadoST": "http://www.surf-forecast.com/breaks/Coronado-Beaches/seatemp",
"coronadoTC": "https://www.weatherforyou.com/reports/index.php?config=&pass=&dpp=&forecast=zandh&config=&place=coronado&state=ca&country=us",
"zumaST": "http://www.surf-forecast.com/breaks/Zuma-Beach/seatemp",
"zumaTC": "https://www.weatherforyou.com/reports/index.php?place=zuma+beach&state=ca",
"huntingtonST": "http://www.surf-forecast.com/breaks/Huntington-Beach/seatemp",
"huntingtonTC": "https://www.weatherforyou.com/reports/index.php?config=&forecast=zandh&pands=Huntington+Beach&Submit=Get+Weather",
"imperialST": "http://www.surf-forecast.com/breaks/Imperial-Beach/seatemp",
"imperialTC": "https://www.weatherforyou.com/reports/index.php?config=&forecast=zandh&pands=Imperial+Beach&Submit=Get+Weather",
"moonlightST": "http://www.surf-forecast.com/breaks/Moonlight-Beach/seatemp",
"moonlightTC": "https://www.weatherforyou.com/reports/index.php?config=&forecast=zandh&pands=Moonlight+State+Beach&Submit=Get+Weather",
"silverStrandST": "http://www.surf-forecast.com/breaks/Silver-Strand/seatemp",
"silverStrandTC": "https://www.weatherforyou.com/reports/index.php?config=&forecast=zandh&pands=92118&Submit=Get+Weather",
"santaMonicST": "http://www.surf-forecast.com/breaks/Santa-Monic-Pier/seatemp",
"santaMonicaTC": "https://www.weatherforyou.com/reports/index.php?config=&forecast=zandh&pands=Santa+Monica+Pier&Submit=Get+Weather",
"avilaST": "https://www.seatemperature.org/north-america/united-states/avila-beach.htm",
"avilaTC": "https://www.weatherforyou.com/reports/index.php?config=&forecast=zandh&pands=93424&Submit=Get+Weather",
"pointMuguST": "http://www.surf-forecast.com/breaks/Point-Mugu/seatemp",
"pointMuguTC": "https://www.weatherforyou.com/reports/index.php?config=&forecast=zandh&pands=Point+Mugu&Submit=Get+Weather"
}
def home(request):
context ={
'surveys': Survey.objects.all()
}
return render(request, 'blog/home.html', context)
class selectBeach(LoginRequiredMixin, TemplateView):
template_name = 'blog/beach.html'
def get(self, request):
blog.transferBeachValue.beach = request.POST.get('beachValue', "")
return render(request, self.template_name)
def post(self,request):
blog.transferBeachValue.beach = request.POST.get('beachValue', "")
return redirect('survey-create')
class PostListView(LoginRequiredMixin, ListView):
model = Survey
template_name = 'blog/home.html'
context_object_name = 'surveys'
ordering = ['-date_posted']
class PostDetailView(DetailView):
model = Survey
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Survey
success_url = '/'
def test_func(self):
survey = self.get_object()
if self.request.user == survey.author or self.request.user.is_staff:
return True
return False
class SurveyView(LoginRequiredMixin, TemplateView):
template_name = 'blog/survey_form.html'
def get(self, request, **kwargs):
form = SurveyForm()
item = kwargs.get('pk')
beach = blog.transferBeachValue.beach
try:
url = (websiteLibrary[BEACHES[beach] + 'ST'])
page = requests.get(url)
tree = html.fromstring(page.content)
seaTemp = tree.xpath('//span[@class="temp"]/text()')
sTemp = (float(seaTemp[0]) * (9/5)) + 32
sTemp = str(sTemp) + ' F'
except:
sTemp = 0;
try:
url = (websiteLibrary[BEACHES[beach] + 'TC'])
page = requests.get(url)
tree = html.fromstring(page.content)
temp = tree.xpath('//span[@class="Temp"]/text()')
airTemp = temp[0]
except:
airTemp = ""
if(item != None):
object = Survey.objects.filter(pk=kwargs.get('pk'))
form.fields["surveyName"].initial = Survey.objects.only('surveyName').get(pk=kwargs.get('pk')).surveyName
form.fields["location"].initial = Survey.objects.only('location').get(pk=kwargs.get('pk')).location
form.fields["region"].initial = Survey.objects.only('region').get(pk=kwargs.get('pk')).region
form.fields["dateSampled"].initial = Survey.objects.only('region').get(pk=kwargs.get('pk')).dateSampled
form.fields["transNumber"].initial = Survey.objects.only('transNumber').get(pk=kwargs.get('pk')).transNumber
form.fields["startLat"].initial = Survey.objects.only('startLat').get(pk=kwargs.get('pk')).startLat
form.fields["startLong"].initial = Survey.objects.only('startLong').get(pk=kwargs.get('pk')).startLong
form.fields["endLat"].initial = Survey.objects.only('endLat').get(pk=kwargs.get('pk')).endLat
form.fields["endLong"].initial = Survey.objects.only('endLong').get(pk=kwargs.get('pk')).endLong
form.fields["clams"].initial = Survey.objects.only('clams').get(pk=kwargs.get('pk')).clams
form.fields["waterTemp"].initial = Survey.objects.only('waterTemp').get(pk=kwargs.get('pk')).waterTemp
form.fields["airTemp"].initial = Survey.objects.only('airTemp').get(pk=kwargs.get('pk')).airTemp
form.fields["startTime"].initial = Survey.objects.only('startTime').get(pk=kwargs.get('pk')).startTime
form.fields["endTime"].initial = Survey.objects.only('endTime').get(pk=kwargs.get('pk')).endTime
form.fields["lowTideTime"].initial = Survey.objects.only('lowTideTime').get(pk=kwargs.get('pk')).lowTideTime
form.fields["lowTide"].initial = Survey.objects.only('lowTide').get(pk=kwargs.get('pk')).lowTide
else:
form.fields["location"].initial = beach
form.fields["waterTemp"].initial = sTemp
form.fields["airTemp"].initial = airTemp
form.fields["dateSampled"].initial = datetime.datetime.today()
form.fields["clams"].initial = "No need to type anything here. This will be filled in automatically."
args = {'form': form}
return render(request, self.template_name, args)
def post(self, request, **kwargs):
item = kwargs.get('pk')
if(item == None):
form = SurveyForm(request.POST)
if form.is_valid():
item = form.save(commit=False)
item.author = request.user
item.save()
surveyName = form.cleaned_data['surveyName']
location = form.cleaned_data['location']
region = form.cleaned_data['region']
dateSampled = form.cleaned_data['dateSampled']
transNumber = form.cleaned_data['transNumber']
startLat = form.cleaned_data['startLat']
startLong = form.cleaned_data['startLong']
endLat = form.cleaned_data['endLat']
endLong = form.cleaned_data['endLong']
clams = form.cleaned_data['clams']
waterTemp = form.cleaned_data['waterTemp']
airTemp = form.cleaned_data['airTemp']
startTime = form.cleaned_data['startTime']
endTime = form.cleaned_data['endTime']
lowTideTime = form.cleaned_data['lowTideTime']
lowTide = form.cleaned_data['lowTide']
return redirect('blog-home')
else:
form = SurveyForm(request.POST)
if form.is_valid():
Survey.objects.filter(pk=kwargs.get('pk')).update(surveyName=form.cleaned_data['surveyName'])
Survey.objects.filter(pk=kwargs.get('pk')).update(location=form.cleaned_data['location'])
Survey.objects.filter(pk=kwargs.get('pk')).update(region=form.cleaned_data['region'])
Survey.objects.filter(pk=kwargs.get('pk')).update(dateSampled=form.cleaned_data['dateSampled'])
Survey.objects.filter(pk=kwargs.get('pk')).update(transNumber=form.cleaned_data['transNumber'])
Survey.objects.filter(pk=kwargs.get('pk')).update(startLat=form.cleaned_data['startLat'])
Survey.objects.filter(pk=kwargs.get('pk')).update(startLong=form.cleaned_data['startLong'])
Survey.objects.filter(pk=kwargs.get('pk')).update(endLat=form.cleaned_data['endLat'])
Survey.objects.filter(pk=kwargs.get('pk')).update(endLong=form.cleaned_data['endLong'])
Survey.objects.filter(pk=kwargs.get('pk')).update(clams=form.cleaned_data['clams'])
Survey.objects.filter(pk=kwargs.get('pk')).update(waterTemp=form.cleaned_data['waterTemp'])
Survey.objects.filter(pk=kwargs.get('pk')).update(airTemp=form.cleaned_data['airTemp'])
Survey.objects.filter(pk=kwargs.get('pk')).update(startTime=form.cleaned_data['startTime'])
Survey.objects.filter(pk=kwargs.get('pk')).update(endTime=form.cleaned_data['endTime'])
Survey.objects.filter(pk=kwargs.get('pk')).update(lowTideTime=form.cleaned_data['lowTideTime'])
Survey.objects.filter(pk=kwargs.get('pk')).update(lowTide=form.cleaned_data['lowTide'])
return redirect('blog-home')
args = {'form': form}
return render(request, self.template_name, args)
def about(request):
if not request.user.is_authenticated:
return redirect('login')
else:
return render(request, 'blog/about.html', {'title': 'About'})
@permission_required('admin.can_add_log_entry')
def DataDownload(request, **kwargs):
item = kwargs.get('pk')
location = Survey.objects.only('location').get(pk=kwargs.get('pk')).location
region = Survey.objects.only('region').get(pk=kwargs.get('pk')).region
date = Survey.objects.only('region').get(pk=kwargs.get('pk')).dateSampled
transNumber = Survey.objects.only('transNumber').get(pk=kwargs.get('pk')).transNumber
startLat = Survey.objects.only('startLat').get(pk=kwargs.get('pk')).startLat
startLong = Survey.objects.only('startLong').get(pk=kwargs.get('pk')).startLong
endLat = Survey.objects.only('endLat').get(pk=kwargs.get('pk')).endLat
endLong = Survey.objects.only('endLong').get(pk=kwargs.get('pk')).endLong
clamData = Survey.objects.only('clams').get(pk=kwargs.get('pk')).clams
filename = str(date) + str(location) + str(transNumber)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=' + filename + '".csv"'
writer = csv.writer(response, delimiter=',')
writer.writerow(['location', 'region', 'date', 'transNumber', 'startLat', 'startLong', 'endLat', 'endLong', 'section', 'size'])
i = 0
j = 0
outerClamArray = []
innerClamArray = []
size = ""
while j < len(clamData):
if(clamData[j] is '\n'):
outerClamArray.append(innerClamArray)
innerClamArray = []
size = ""
elif ((clamData[j] is not ':') and (clamData[j] is not ' ') and (clamData[j] is not '\r')):
size += clamData[j]
elif (size is ""):
size = size
else:
innerClamArray.append(size)
size = ""
j = j + 1
innerClamArray.append(size)
outerClamArray.append(innerClamArray)
i = 0
j = 0
for section in outerClamArray:
max = len(section)
while(i is not max):
if i == 0:
sec = outerClamArray[j][i];
i = i + 1
else:
writer.writerow([location, region, date, transNumber, startLat, startLong, endLat, endLong, sec, outerClamArray[j][i]])
i = i + 1
i = 0
j = j + 1
#for obj in items:
# writer.writerow([obj.title, obj.content])
return response<file_sep># Generated by Django 2.1.3 on 2019-03-13 00:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0005_survey_beaches'),
]
operations = [
migrations.AlterField(
model_name='survey',
name='beaches',
field=models.CharField(max_length=100),
),
]
<file_sep># Generated by Django 2.1.3 on 2019-03-13 23:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0008_remove_survey_beaches'),
]
operations = [
migrations.AlterField(
model_name='survey',
name='clams',
field=models.CharField(max_length=5000),
),
]
<file_sep># Generated by Django 2.1.3 on 2019-03-15 03:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0009_auto_20190313_1627'),
]
operations = [
migrations.AddField(
model_name='survey',
name='endTime',
field=models.CharField(default=0, max_length=50),
preserve_default=False,
),
migrations.AddField(
model_name='survey',
name='lowTide',
field=models.CharField(default=0, max_length=50),
preserve_default=False,
),
migrations.AddField(
model_name='survey',
name='lowTideTime',
field=models.CharField(default=0, max_length=50),
preserve_default=False,
),
migrations.AddField(
model_name='survey',
name='startTime',
field=models.CharField(default=0, max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='survey',
name='clams',
field=models.TextField(),
),
migrations.AlterField(
model_name='survey',
name='location',
field=models.CharField(max_length=200),
),
migrations.AlterField(
model_name='survey',
name='surveyName',
field=models.CharField(max_length=200),
),
]
<file_sep># Generated by Django 2.1.3 on 2019-03-11 23:18
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_auto_20190304_1555'),
]
operations = [
migrations.AddField(
model_name='survey',
name='surveyName',
field=models.CharField(default=django.utils.timezone.now, max_length=100),
preserve_default=False,
),
]
<file_sep>from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from django.core.validators import validate_comma_separated_integer_list
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.CharField(max_length=100, validators=[validate_comma_separated_integer_list])
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
class Survey(models.Model):
surveyName = models.CharField(max_length = 200)
location = models.CharField(max_length = 200)
region = models.CharField(max_length = 100)
dateSampled = models.DateTimeField(default=timezone.now)
transNumber = models.IntegerField()
startTime = models.CharField(max_length = 50)
endTime = models.CharField(max_length = 50)
lowTideTime = models.CharField(max_length = 50)
startLat = models.FloatField()
startLong = models.FloatField()
endLat = models.FloatField()
endLong = models.FloatField()
lowTide = models.CharField(max_length = 50)
clams = models.TextField()
waterTemp = models.CharField(max_length = 100)
airTemp = models.CharField(max_length = 100)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def str(self):
return self.surveyName
def get_absolute_url(self):
return reverse('survey-detail', kwargs={'pk': self.pk})<file_sep>beach = "Pismo Beach"<file_sep># Generated by Django 2.1.3 on 2019-03-13 00:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0004_survey_surveyname'),
]
operations = [
migrations.AddField(
model_name='survey',
name='beaches',
field=models.CharField(choices=[('pismo', 'Pismo Beach'), ('morro', 'Morro Bay'), ('cayucos', 'Cayucos Beach'), ('oceano', 'Oceano Beach'), ('coronado', 'Coronado Beach'), ('zuma', 'Zuma Beach'), ('huntington', 'Huntington Beach'), ('imperial', 'Imperial Beach'), ('moonlight', 'Moonlight Beach'), ('siverStrand', 'Siver Strand Beach'), ('santaMonica', 'Santa Monica Beach'), ('avila', 'Avila Beach'), ('pointMugu', 'point Mugu Beach')], default='pismo', max_length=100),
),
]
<file_sep>from django import forms
from blog.models import Survey
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Row, Column
from lxml import html
import requests
from datetime import datetime
from django.forms.widgets import HiddenInput
class SurveyForm(forms.ModelForm):
surveyName = forms.CharField(label='Survey Name')
location = forms.CharField(label='Beach')
region = forms.CharField()
dateSampled = forms.DateField(label='Date Sampled')
transNumber = forms.IntegerField(label='Transect Number')
startLat = forms.FloatField(label='Start Latitude')
startLong = forms.FloatField(label='Start Longitude')
endLat = forms.FloatField(label='End Latitude')
endLong = forms.FloatField(label='End Longitude')
startTime = forms.CharField(label='Start Time')
endTime = forms.CharField(label='End Time')
lowTideTime = forms.CharField(label='Low Tide Time')
lowTide = forms.CharField(label='Low Tide Height')
clams = forms.TextInput()
waterTemp = forms.CharField(label='Sea Temperature')
airTemp = forms.CharField(label='Temperature')
class Meta:
model = Survey
fields = {'surveyName', 'location', 'region', 'dateSampled', 'transNumber', 'startLat',
'startLong', 'endLat', 'endLong', 'clams', 'waterTemp', 'airTemp', 'startTime',
'endTime', 'lowTideTime', 'lowTide'}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
'surveyName',
Row(
Column('startTime', css_class='form-group col-md-6 mb-0'),
Column('endTime', css_class='form-group col-md-6 mb-0'),
Column('lowTideTime', css_class='form-group col-md-6 mb-0'),
Column('lowTide', css_class='form-group col-md-6 mb-0'),
css_class='form-row'),
Row(
Column('location', css_class='form-group col-md-6 mb-0'),
Column('region', css_class='form-group col-md-6 mb-0'),
Column('dateSampled', css_class='form-group col-md-6 mb-0'),
Column('transNumber', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
),
Row(
Column('startLat', css_class='form-group col-md-6 mb-0'),
Column('startLong', css_class='form-group col-md-6 mb-0'),
Column('endLat', css_class='form-group col-md-6 mb-0'),
Column('endLong', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
),
Row(
Column('waterTemp', css_class='form-group col-md-6 mb-0'),
Column('airTemp', css_class='form-group col-md-6 mb-0'),
),
'clams',
self.helper.add_input(Submit('submit', 'Submit', css_class='submitButton'))
)<file_sep># Generated by Django 2.1.3 on 2019-03-13 03:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_auto_20190312_1732'),
]
operations = [
migrations.AddField(
model_name='survey',
name='airTemp',
field=models.CharField(default=0, max_length=100),
preserve_default=False,
),
migrations.AddField(
model_name='survey',
name='waterTemp',
field=models.CharField(default=0, max_length=100),
preserve_default=False,
),
]
<file_sep># Generated by Django 2.1.3 on 2019-03-04 23:55
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('blog', '0002_auto_20190304_1543'),
]
operations = [
migrations.CreateModel(
name='Survey',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('location', models.CharField(max_length=100)),
('region', models.CharField(max_length=100)),
('dateSampled', models.DateTimeField(default=django.utils.timezone.now)),
('transNumber', models.IntegerField()),
('startLat', models.FloatField()),
('startLong', models.FloatField()),
('endLat', models.FloatField()),
('endLong', models.FloatField()),
('clams', models.TextField()),
('date_posted', models.DateTimeField(default=django.utils.timezone.now)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.RemoveField(
model_name='clam',
name='author',
),
migrations.DeleteModel(
name='Clam',
),
]
<file_sep>from django.contrib import admin
from .models import Survey
admin.site.register(Survey)<file_sep># Generated by Django 2.1.3 on 2019-03-04 23:43
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import re
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('blog', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Clam',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('location', models.CharField(max_length=100)),
('region', models.CharField(max_length=100)),
('dateSampled', models.DateField()),
('transNumber', models.IntegerField()),
('startLat', models.FloatField()),
('startLong', models.FloatField()),
('endLat', models.FloatField()),
('endLong', models.FloatField()),
('sectNumber', models.IntegerField()),
('size', models.IntegerField()),
('date_posted', models.DateTimeField(default=django.utils.timezone.now)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AlterField(
model_name='post',
name='content',
field=models.CharField(max_length=100, validators=[django.core.validators.RegexValidator(re.compile('^\\d+(?:,\\d+)*\\Z'), code='invalid', message='Enter only digits separated by commas.')]),
),
]
<file_sep>from django.urls import path
from .views import (
PostListView,
PostDetailView,
selectBeach,
PostDeleteView,
DataDownload
)
from . import views
from blog.views import SurveyView
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='survey-detail'),
path('post/new/', SurveyView.as_view(), name='survey-create'),
path('post/selectBeach/', selectBeach.as_view(), name='beach'),
path('post/<int:pk>/update', SurveyView.as_view(), name='survey-update'),
path('post/<int:pk>/delete', PostDeleteView.as_view(), name='survey-delete'),
path('about/', views.about, name='blog-about'),
path('post/<int:pk>/download/', DataDownload, name='blog-download_survey'),
]
| dce288a25d253a58acc9da182c64600a4fe0441b | [
"Python"
] | 15 | Python | cwjung479/PismoClam | 20b7df14c3164a823684f47df82adfdddaecb267 | 72ff7422c08fe38a3d010f25d1fabd8f27c0cf2d |
refs/heads/master | <repo_name>benbenbob1/motion2color<file_sep>/motiontest.py
import datetime
import time
import imutils
import warnings
import numpy as np
# and now the most important of all
import cv2
VIDEO_FEED_SIZE = [272, 204] #[width, height] in pixels
MIN_AREA = (VIDEO_FEED_SIZE[0]*VIDEO_FEED_SIZE[1])/25 #minimum area size, pixels
G_BLUR_AMOUNT = 13 #gaussian blur value
DIFF_THRESH = 50 #difference threshold value
LEARN_APPROVE = 15 #allowed difference between 'identical' frames
LEARN_TIME = 50 #number of identical frames needed to learn the background
FPS = 6
COLOR_SPREAD = 5 # number of margin leds before + after the colorbar to light up
FADE_AMT_PER_FRAME = 0.1 * 255 # amount to fade between every frame
camera = None
piCapture = None
useDisplay = True
isPi = False
try:
import picamera as pc
from picamera.array import PiRGBArray
isPi = True
except ImportError:
isPi = False
opcLED = True
ledController = None
if opcLED:
import opc
else:
import apa102
#METHODS
warnings.simplefilter("ignore")
person1Size = 0
person2Size = 0
numFramesIdentical = 0 #increases every nearly identical frame
lastFrame = None
numLeds = 0
leds = None
#[[r,g,b], [r,g,b], ...]
def sendLEDs(arr):
normalized = np.fmin(np.fmax(arr, 0), 255)
global ledController
if opcLED:
ledController.put_pixels(normalized, channel=0)
else:
for i in range(numLeds):
ledController.setPixel(
numLeds-i,
normalized[i][0], normalized[i][1], normalized[i][2]
)
ledController.setPixel(
numLeds+i,
normalized[i][0], normalized[i][1], normalized[i][2]
)
ledController.show()
def doLoop(isPi):
global leds
bgFrame = None
dilateKernel = cv2.getStructuringElement(cv2.MORPH_RECT,(10,15))
closeKernel = cv2.getStructuringElement(cv2.MORPH_RECT,(10,15))
leds = np.uint8([[0,0,0]] * numLeds)
# Returns:
# (
# bool: should continue loop,
# matrix?: background frame or None
# )
def processFrame(frame, bgFrame):
global person1Size, person2Size, numFramesIdentical, lastFrame, leds
leds = np.fmin(np.fmax(np.subtract(leds,FADE_AMT_PER_FRAME), 0), 255);
text = "No movement"
# resize frame
frame = imutils.resize(frame,
width=VIDEO_FEED_SIZE[0]
)
# convert it to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# blur it to reduce noise
gray = cv2.GaussianBlur(gray, (G_BLUR_AMOUNT, G_BLUR_AMOUNT), 0)
if (numFramesIdentical >= LEARN_TIME
or bgFrame is None
or lastFrame is None):
shouldUpdate = True
if (lastFrame is not None and bgFrame is not None):
bgDelta = cv2.absdiff(bgFrame, lastFrame)
frameDiffMax = np.uint8(
np.max(
np.max(bgDelta, axis=0),
axis=0)
)
if (frameDiffMax <= LEARN_APPROVE):
shouldUpdate = False
if shouldUpdate:
print "(Re)collecting background frame..."
lastFrame = gray.copy()
numFramesIdentical = 0
return (True, lastFrame)
# accumulate average frame
#cv2.accumulateWeighted(gray, avgFrame, 0.5)
grayDelta = cv2.absdiff(gray, lastFrame)
frameDelta = cv2.absdiff(gray, bgFrame)
threshold = cv2.threshold(frameDelta, DIFF_THRESH, 255,
cv2.THRESH_BINARY)[1]
lastFrame = gray
frameDiffMax = np.uint8(
np.max(
np.max(grayDelta, axis=0),
axis=0)
)
if (frameDiffMax <= LEARN_APPROVE):
numFramesIdentical += 1
else:
numFramesIdentical = 0
# dilate and then close - this fills in gaps
threshold = cv2.dilate(threshold, dilateKernel, iterations=1)
threshold = cv2.morphologyEx(threshold, cv2.MORPH_CLOSE, closeKernel)
try:
_, contours, _ = cv2.findContours(
threshold.copy(),
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE
)
except: #for pi
_, contours = cv2.findContours(
threshold.copy(),
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE
)
if person1Size > MIN_AREA:
person1Size -= 10000
if person2Size > MIN_AREA:
person2Size -= 10000
justMovement = np.float16(cv2.bitwise_and(frame, frame, mask=threshold))
justMovement[justMovement == 0] = np.nan
#TODO
#leds = np.uint8([[0,0,0]] * numLeds)
if contours is not None and len(contours) > 0:
text = "Movement detected"
for cont in contours:
contourArea = cv2.contourArea(cont)
# ignore areas smaller than MIN_AREA
if (contourArea < MIN_AREA or
contourArea < person1Size or
contourArea < person2Size):
continue
if (person1Size > person2Size):
person2Size = person1Size
person1Size = contourArea
text += " ["+str(contourArea)+"]"
(x1,y1,w,h) = cv2.boundingRect(cont)
x2 = min((x1+w), VIDEO_FEED_SIZE[0])
y2 = min((y1+h), VIDEO_FEED_SIZE[1])
matrixRect = justMovement[
y1:y2,
x1:x2
]
matrixRect[matrixRect == np.inf] = np.nan
mean = np.nanmean(
np.nanmean(matrixRect, axis=0),
axis=0)
if np.isnan(mean).any():
continue
avgCols = np.uint8([[mean]])
avgColHSV = cv2.cvtColor(avgCols, cv2.COLOR_BGR2HSV)
avgColHSV[0][0][1] = 255 # Saturation
avgColHSV[0][0][2] = 255 # Value
avgCols = cv2.cvtColor(avgColHSV, cv2.COLOR_HSV2BGR)
cv2.rectangle(
frame,
(x1,y1), (x2, y2),
(
int(avgCols[0][0][0]),
int(avgCols[0][0][1]),
int(avgCols[0][0][2])
),
thickness=4)
#except:
# print "Exception drawing box"
# print "X: "+str(x)+" Y: "+str(y)+" X+W: "+str(x+w)+" Y+H: "+str(y+h)
# continue
ledStartIdx = (x1 * numLeds) / VIDEO_FEED_SIZE[0]
ledEndIdx = (x2 * numLeds) / VIDEO_FEED_SIZE[0]
#print str(ledStartIdx)+" : "+str(ledEndIdx)
for l in range(1,COLOR_SPREAD):
colorAmt = 255 - (l / COLOR_SPREAD) * 255
col = [
int(avgCols[0][0][2] - colorAmt),
int(avgCols[0][0][1] - colorAmt),
int(avgCols[0][0][0] - colorAmt)
]
thisEnd = min(ledEndIdx+l, numLeds-1)
thisStart = max(ledStartIdx-l, 0)
leds[thisEnd] += col
leds[thisStart] += col
leds[ledStartIdx:ledEndIdx] += [
int(avgCols[0][0][2]),
int(avgCols[0][0][1]),
int(avgCols[0][0][0])
]
circleMargin = 5
circleRadius = 1
circleXStart = int(
(VIDEO_FEED_SIZE[0] / 2.0) -
( (numLeds / 2.0) * (circleMargin + circleRadius) )
)
circleY = int(VIDEO_FEED_SIZE[1] / 2.0)
for c in range(0,numLeds):
cv2.circle(
frame,
(circleXStart, circleY),
circleRadius,
(
int(leds[c][2]),
int(leds[c][1]),
int(leds[c][0])
)
)
circleXStart += circleMargin + circleRadius
else:
person1Size = 0
person2Size = 0
dateTimeStr = datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p")
'''
# putText(frame,text,origin,font_face,font_scale,color,thickness)
cv2.putText(frame, text, (10, 20), cv2.FONT_HERSHEY_PLAIN,
0.5, (255,0,0), 1)
cv2.putText(frame, dateTimeStr, (10, 30), cv2.FONT_HERSHEY_PLAIN,
0.5, (255,255,255), 1)
cv2.putText(frame, "Press q to quit", (10, 40), cv2.FONT_HERSHEY_PLAIN,
0.5, (255,255,255), 1)
'''
if useDisplay:
cv2.imshow("Feed", frame)
cv2.imshow("Movement", np.uint8(justMovement))
#cv2.imshow("Background", bgFrame)
#cv2.imshow("Threshold", threshold)
#cv2.imshow("Delta", frameDelta)
# exit on 'q' key press
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
return (False, None)
sendLEDs(leds.tolist())
return (True, None)
if (isPi):
print "Using Pi's PiCamera"
camera = pc.PiCamera()
camera.resolution = tuple(VIDEO_FEED_SIZE)
camera.framerate = FPS
piCapture = PiRGBArray(camera, size=tuple(VIDEO_FEED_SIZE))
time.sleep(2.5)
print("Pi video feed opened")
for f in camera.capture_continuous(
piCapture,
format="bgr",
use_video_port=True):
frame = f.array
(loop, bg) = processFrame(frame, bgFrame)
if (not loop):
piCapture.truncate(0)
break
elif (bg is not None):
piCapture.truncate(0)
bgFrame = bg
piCapture.truncate(0)
closeGently(isPi, None)
else:
print "Using CV2's VideoCapture"
# get video feed from default camera device
camera = cv2.VideoCapture(0)
while (True):
if not camera.isOpened():
time.sleep(2)
else:
break
print("CV2 video feed opened")
while (True):
# get single frame
response, frame = camera.read()
if not response:
print("Error: could not obtain frame")
# couldn't obtain a frame
break
(loop, bg) = processFrame(frame, bgFrame)
if (not loop):
break
elif (bg is not None):
bgFrame = bg
closeGently(isPi, camera)
def closeGently(isPi, camera):
if (not isPi):
camera.release()
print("Video feed closed")
cv2.destroyAllWindows()
#ENDMETHODS
print("Attaching to camera...")
if opcLED:
numLeds = 30
ledController = opc.Client('rpi.student.rit.edu:7890')
if ledController.can_connect():
print('Connected to LED OPC')
else:
numLeds = 180 # 180 * 2 strips
ledController = apa102.APA102(numLeds*2, 31)
doLoop(isPi)<file_sep>/README.md
# motion2color
Gets the color of any movement using OpenCV
## Install requirements:
`pip install -r requirements.txt`
(Might require sudo on a Raspberry Pi)
### Install Python OpenCV
* This is very difficult on a Mac, follow this tutorial:
> http://www.pyimagesearch.com/2016/11/28/macos-install-opencv-3-and-python-2-7/
* On Raspbian:
`sudo apt-get install python-opencv`
### SPIDev
Must be installed if using APA102 LEDs
`pip install spidev` | 05df098ea26534677fc890d7eda82a86b029c8e9 | [
"Markdown",
"Python"
] | 2 | Python | benbenbob1/motion2color | eb163ccc66205c9c0c0e3574401ed512b523ab60 | 3d4b4e5dc69ee89eb80847afc699a56ed6faa0a4 |
refs/heads/master | <repo_name>mizanmahi/maxinode<file_sep>/controller/product.js
const Product = require('../models/product')
exports.getAddProductPage = (req, res, next) => {
res.render('admin/add-product', {
path: '/admin/add-product',
pageTitle: 'Add Product'
});
}
exports.postProductPage = (req, res, next) => {
const product = new Product(req.body.title);
product.save();
console.log('aya tha');
res.redirect('/')
}
exports.getShopPage = (req, res, next) => {
Product.fetchAll(foods => {
res.render('shop/shop', {
pageTitle: 'FoodHub',
prods: foods,
path: '/'
})
})
} | 9ed50265bf3bd0490e97ced96e2ca0c3ca5aea5a | [
"JavaScript"
] | 1 | JavaScript | mizanmahi/maxinode | b0760227e4e428fe757e1882295aa4df2337d819 | b1f34f618b247fcba42dda3e9265e467dd8f04be |
refs/heads/master | <repo_name>MehdiAit/Success_v2.2<file_sep>/success_v1/src/com/success_v1/main/Main.java
package com.success_v1.main;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.success_v1.location.GpsTrack;
import com.success_v1.res.JSONParser;
import com.success_v1.reservation.ReservationTab;
import com.success_v1.successCar.R;
import com.success_v1.user.LogPage;
import com.success_v1.user.ProfilPage;
import com.success_v1.user.SessionManager;
public class Main extends Activity implements OnClickListener{
private Button btnsearch;
private Button btnReservation;
private Button btnCompte;
private TextView txtLocate;
// Session Manager Class
private SessionManager session;
private HashMap<String, String> user;
private ConnectivityManager wf;
private NetworkInfo info;
//Location
private ProgressDialog pDialog;
private JSONParser jParser = new JSONParser();
private JSONArray results;
private GpsTrack gps;
private static String jsonUrl_google_api = "http://maps.googleapis.com/maps/api/geocode/json?address=";
private static String jsonUrl_param = "&sensor=true&language=fr";
private String comune = "";
private String ville = "";
private Double latitude;
private Double longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acceuil);
getActionBar().setTitle(null);
//getActionBar().setDisplayHomeAsUpEnabled(true);
session = new SessionManager(getApplicationContext());
wf = (ConnectivityManager)this.getSystemService(CONNECTIVITY_SERVICE);
info = wf.getActiveNetworkInfo();
btnsearch = (Button)this.findViewById(R.id.btnsearch);
btnReservation= (Button)this.findViewById(R.id.btnReservations);
btnCompte = (Button)this.findViewById(R.id.btnCompte);
txtLocate = (TextView)findViewById(R.id.txtLocalMap);
btnsearch.setOnClickListener(this);
btnReservation.setOnClickListener(this);
btnCompte.setOnClickListener(this);
gps = new GpsTrack(getApplicationContext());
if(info != null && info.isConnectedOrConnecting())
{
//Log.d("wifi state","Connected");
new asyncRecup().execute();
}else
{
//Log.d("wifi state","Deconnected");
}
TranslateAnimation trans1 = new TranslateAnimation (0,0,800,0);
trans1.setStartOffset(600);
trans1.setFillAfter(true);
trans1.setDuration(800);
btnsearch.startAnimation(trans1);
TranslateAnimation trans2 = new TranslateAnimation (320,0,0,0);
trans2.setStartOffset(320);
trans2.setFillAfter(true);
trans2.setDuration(800);
btnReservation.startAnimation(trans2);
TranslateAnimation trans3 = new TranslateAnimation (0,0,400,0); /*gauche, droite, haut, bas */
trans3.setStartOffset(400);
//trans3.setFillAfter(true);
trans3.setDuration(800);
btnCompte.startAnimation(trans3);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 1)
{
if(resultCode == RESULT_OK)
{
user = session.getUserDetails();
Toast.makeText(getApplicationContext(), "Bienvenue a vous : "+ user.get(SessionManager.KEY_NOM), Toast.LENGTH_SHORT).show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId())
{
case R.id.SubMenuLogOut: session.logoutUser();finish();Toast.makeText(getApplicationContext(), "Deconnexion", Toast.LENGTH_SHORT).show();break;
case R.id.SubMenuNote:Toast.makeText(this, "Notez nous", Toast.LENGTH_SHORT).show();break;
case R.id.SubMenuAbout:Toast.makeText(this, "Qui somme-nous?", Toast.LENGTH_SHORT).show();break;
case R.id.eng:setLocal(Locale.ENGLISH);break;
case R.id.fr:setLocal(Locale.FRENCH);break;
case R.id.ch:setLocal(Locale.SIMPLIFIED_CHINESE);break;
case R.id.ar:setLocal(Locale.GERMANY);break; // just for the moment
}
return super.onOptionsItemSelected(item);
}
/************ Internationalisation *******************/
public void setLocal(Locale loc)
{
Resources res = getResources();
Configuration cnf = res.getConfiguration();
cnf.locale = loc;
res.updateConfiguration(cnf, res.getDisplayMetrics());
try {
Context ctx = this.createPackageContext(this.getPackageName(), CONTEXT_INCLUDE_CODE);
Intent restart = new Intent(ctx, Main.class);
startActivity(restart);
finish();
} catch (Exception e) {
// TODO: handle exception
}
}
/*************************************************************************/
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId())
{
case R.id.btnsearch:
Intent agenceActivity= new Intent(this,ReservationStep1.class);
agenceActivity.putExtra("comune", comune);
agenceActivity.putExtra("ville", ville);
if(info != null)
{
if(latitude == null || longitude == null)
{
agenceActivity.putExtra("latitude", "null");
agenceActivity.putExtra("longitude", "null");
}else
{
agenceActivity.putExtra("latitude", latitude.toString());
agenceActivity.putExtra("longitude", longitude.toString());
}
}else
{
agenceActivity.putExtra("latitude", "null");
agenceActivity.putExtra("longitude", "null");
}
startActivity(agenceActivity);
break;
case R.id.btnReservations:
if(info != null)
{
if(session.isLoggedIn())
{
startActivity(new Intent(this, ReservationTab.class));
}else
{
Intent compteActivity = new Intent(this,LogPage.class);
startActivityForResult(compteActivity,1);
}
}else
{
Toast.makeText(this, "Acune connexion dรฉtectรฉ", Toast.LENGTH_LONG).show();
}
break;
case R.id.btnCompte:
if(session.isLoggedIn())
{
Intent profilActivity= new Intent(this,ProfilPage.class);
startActivityForResult(profilActivity,2);
}else
{
Intent compteActivity = new Intent(this,LogPage.class);
startActivityForResult(compteActivity,1);
}
break;
}
}
public class asyncRecup extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Main.this);
pDialog.setMessage("Localisation en cours, Patientez ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
String url = jsonUrl_google_api+latitude.toString()+","+longitude.toString()+jsonUrl_param;
List<NameValuePair> param = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url, "GET", param);
try {
results = json.getJSONArray("results");
//Log.i("JsonArray",results.toString());
if(results.isNull(0))
{
comune = "null";
ville = "null";
latitude = null;
longitude = null;
}else
{
comune = results.getJSONObject(1).getJSONArray("address_components").getJSONObject(0).getString("long_name").toString();
ville = results.getJSONObject(1).getJSONArray("address_components").getJSONObject(1).getString("long_name").toString();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
txtLocate.setText(" "+comune+", "+ville);
pDialog.dismiss();
}
}
}
<file_sep>/success_v1/src/com/success_v1/vehicule/categorieListe.java
package com.success_v1.vehicule;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.internal.cn;
import com.success_v1.res.JSONParser;
import com.success_v1.res.config;
import com.success_v1.successCar.R;
import com.success_v1.user.SessionManager;
public class categorieListe extends Fragment {
private ProgressDialog pDialog;
private JSONParser jsonParser = new JSONParser();
private ArrayList<CategorieVehicule> cat_vehiculelist;
private JSONArray jsonTab = null;
//mettre un acc/mut pour la variable cat
String cat_type;
private String idAgence;
private String dateDepart;
private String dateRetour;
private String ville;
private String latitude;
private String longitude;
private ListView lv;
private AdapterCategorie ad;
private View rootView = null;
private static String url_all = config.getURL()+"get_categorie.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TAB = "tab_categorie";
private static final String TAG_ID = "id";
private static final String TAG_NOM = "nom";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_TARIF = "prix";
private static final String TAG_IMG = "image";
//private static final String TAG_TYPE = "type";
//private static final String TAG_IMG = "imageVehicule";
//private static final String TAG_ville_param = "ville_agence";
//private static final String TAG_IMG = "imageVehicule";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
super.onCreate(savedInstanceState);
rootView = inflater.inflate(R.layout.categorie_list, container, false);
Intent result = getActivity().getIntent();
dateDepart = result.getStringExtra("dateDepart");
dateRetour=result.getStringExtra("dateRetour");
ville =result.getStringExtra("ville");
latitude =result.getStringExtra("latitude");
longitude =result.getStringExtra("longitude");
Log.i("Date depart", dateDepart);
Log.i("Date retour", dateRetour);
cat_vehiculelist = new ArrayList<CategorieVehicule>();
new LoadAll().execute();
lv = (ListView)rootView.findViewById(R.id.listCategorie);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
CategorieVehicule idtest = new CategorieVehicule();
idtest = (CategorieVehicule) lv.getAdapter().getItem(arg2);
String nom = idtest.getName().toString();
Intent intent = new Intent(getActivity().getApplicationContext(), com.success_v1.vehicule.VehiculeListe.class);
intent.putExtra("nom_cat", nom);
intent.putExtra("id_agence", idAgence);
intent.putExtra("dateDepart", dateDepart);
intent.putExtra("dateRetour", dateRetour);
/********* it depande , if approximate agence location is checked then ville param's dosn't existe ********/
intent.putExtra("ville", ville);
intent.putExtra("latitude", latitude);
intent.putExtra("longitude", longitude);
startActivityForResult(intent,1);
}
}
);
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 1)
{
getActivity();
if(resultCode == Activity.RESULT_OK)
{
cat_vehiculelist = new ArrayList<CategorieVehicule>();
new LoadAll().execute();
Toast.makeText(getActivity().getApplicationContext(), "Test intent" , Toast.LENGTH_LONG).show();
}
}
}
class LoadAll extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Chargement...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("type", cat_type));
JSONObject json = jsonParser.makeHttpRequest(url_all, "GET", params);
Log.d("cate", json.toString() + idAgence);
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
jsonTab = json.getJSONArray(TAG_TAB);
for (int i = 0; i < jsonTab.length(); i++) {
JSONObject c = jsonTab.getJSONObject(i);
String id = c.getString(TAG_ID);
String mark = c.getString(TAG_NOM);
String model = c.getString(TAG_DESCRIPTION);
String price = c.getString(TAG_TARIF);
String image = c.getString(TAG_IMG);
CategorieVehicule categorie = new CategorieVehicule(id,mark,model,image,price);
cat_vehiculelist.add(categorie);
}
}else{
// Resultat de requete vide
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
getActivity().runOnUiThread(new Runnable() {
public void run() {
ad = new AdapterCategorie(getActivity(), cat_vehiculelist);
lv.setAdapter(ad);
}
});
}
}
}
<file_sep>/success_v1/src/com/success_v1/agence/Ville.java
package com.success_v1.agence;
public class Ville {
String num_ville;
String nom_ville;
public Ville(String num, String nom)
{
this.num_ville = num;
this.nom_ville = nom;
}
public Ville()
{
}
}
<file_sep>/README.md
Success_v2.2
============
Git/Eclips
<file_sep>/success_v1/src/com/success_v1/agence/Agence.java
package com.success_v1.agence;
public class Agence {
String id;
String nom;
String adresse;
public Agence (String nm, String det, String adr)
{
id = nm;
nom = det;
adresse=adr;
}
public Agence()
{
}
}
<file_sep>/success_v1/src/com/success_v1/reservation/ReservationList.java
package com.success_v1.reservation;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.success_v1.res.JSONParser;
import com.success_v1.res.config;
import com.success_v1.successCar.R;
import com.success_v1.user.SessionManager;
public class ReservationList extends Fragment{
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<Reservation> reservationlist;
JSONArray jsonTab = null;
SessionManager session;
private ListView lv;
View rootView = null;
private static String url_all = config.getURL()+"get_reservation.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TAB = "tab_reservation";
private static final String TAG_ID = "id";
private static final String TAG_DATE = "date_reservation";
private static final String TAG_DATEDEB = "dateDebLoc_reservation";
private static final String TAG_DATEFIN = "dateFinLoc_reservation";
private static final String TAG_PRIX = "prix_total";
private static final String TAG_IMG = "photo_vehicule";
String etat;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
super.onCreate(savedInstanceState);
rootView = inflater.inflate(R.layout.reservation_en_cours_list, container, false);
// Session class instance
session = new SessionManager(getActivity().getApplicationContext());
reservationlist = new ArrayList<Reservation>();
new LoadAllReservations().execute();
lv = (ListView) rootView.findViewById(R.id.lstReservationEnCours);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Reservation idtest = new Reservation();
idtest = (Reservation) lv.getAdapter().getItem(arg2);
String id = idtest.id.toString();
if(etat.equals("En cours"))
{
Intent intent = new Intent(getActivity(), ReservationEnCoursDetails.class);
intent.putExtra("id_get", id);
intent.putExtra("url_image", idtest.image.toString());
startActivityForResult(intent,10);
}
else
{
Intent intent = new Intent(getActivity(), ReservationValideDetails.class);
intent.putExtra("id_get", id);
intent.putExtra("url_image", idtest.image.toString());
startActivityForResult(intent,10);
}
}
}
);
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == 10)
{
if(resultCode == Activity.RESULT_OK)
{
reservationlist = new ArrayList<Reservation>();
new LoadAllReservations().execute();
}
}
}
class LoadAllReservations extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading .Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id_user", session.getIdUser()));
params.add(new BasicNameValuePair("etat", etat));
JSONObject json = jParser.makeHttpRequest(url_all, "GET", params);
Log.d("idUser",session.getIdUser());
Log.d("Tab resultat", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
jsonTab = json.getJSONArray(TAG_TAB);
for (int i = 0; i < jsonTab.length(); i++) {
JSONObject c = jsonTab.getJSONObject(i);
String id = c.getString(TAG_ID);
String date = c.getString(TAG_DATE);
String dateDeb = c.getString(TAG_DATEDEB);
String dateFin = c.getString(TAG_DATEFIN);
String prix = c.getString(TAG_PRIX);
String photo = c.getString(TAG_IMG);
Reservation reservationEnCours = new Reservation(id,date,dateDeb,dateFin,photo,prix);
reservationlist.add(reservationEnCours);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
getActivity().runOnUiThread(new Runnable() {
public void run() {
Adapter ad = new Adapter(getActivity(), reservationlist);
lv.setAdapter(ad);
Log.i("Thread","Hello thread");
}
});
}
}
}
<file_sep>/success_v1/src/com/success_v1/vehicule/VehiculeSearch.java
package com.success_v1.vehicule;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.success_v1.successCar.R;
public class VehiculeSearch extends Activity{
private TextView titleActionBar;
AutoCompleteTextView autoMarqueSearch;
AutoCompleteTextView autoModeleSearch;
Spinner spinCouleurSearch;
Button btnLaunchSearch;
ArrayAdapter<String> adapterMarques;
ArrayAdapter<String> adapterModeles;
private static final String[] MARQUES = new String[] {
"Audi", "BMW", "Alpha Romeo", "Wv", "Seat", "Ford", "Jeep", "Honda", "Hyundai", "Renault", "Dacia"
};
private static final String[] MODELES = new String[] {
"Fiesta", "R8", "Golf", "Polo", "Ibiza", "Leon", "Accent", "Eon", "Duster","Logan"
};
JSONObject detail_tab = new JSONObject();
public void toast(String txt, int leng)
{
Toast.makeText(this, txt, leng).show();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vehicule_page);
/*getActionBar().setDisplayShowHomeEnabled(false);
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.koutchy_actionbar);
titleActionBar = (TextView)findViewById(R.id.titleActionBar);
titleActionBar.setText("Recherche");*/
getActionBar().setTitle("");
autoMarqueSearch = (AutoCompleteTextView)findViewById(R.id.autoMarqueSearch);
autoModeleSearch = (AutoCompleteTextView)findViewById(R.id.autoModeleSearch);
spinCouleurSearch = (Spinner)findViewById(R.id.spinCouleurSearch);
btnLaunchSearch= (Button)findViewById(R.id.btnLaunchSearch);
adapterMarques = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, MARQUES);
autoMarqueSearch.setAdapter(adapterMarques);
adapterModeles= new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, MODELES);
autoModeleSearch.setAdapter(adapterModeles);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.color_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinCouleurSearch.setAdapter(adapter);
btnLaunchSearch.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
}
});
}
/*btnSearchCar.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent listCarActivity = new Intent(getBaseContext(), com.success_v1.vehicule.VehiculeTab.class);
// Parse the input date
Date inputDate = ConvertDate2("dd-MM-yyyy", btnDateDepart);
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
dateDepart = fmt.format(inputDate);
// Parse the input date
Date inputDate2 = ConvertDate2("dd-MM-yyyy", btnDateRetour);
SimpleDateFormat fmtt = new SimpleDateFormat("yyyy-MM-dd");
dateRetour= fmtt.format(inputDate2);
Date today = new Date();
Integer a = inputDate.compareTo(inputDate2);
Integer b = today.compareTo(inputDate);
today = getZeroTimeDate(today);
if((inputDate.compareTo(inputDate2) == 1) || (inputDate.compareTo(today) == -1))
{
toast("Dates incohรฉrentes", Toast.LENGTH_LONG);
}
else
{
listCarActivity.putExtra("dateDepart", dateDepart);
listCarActivity.putExtra("dateRetour", dateRetour);
listCarActivity.putExtra("ville", ville);
if (state== "Tourisme"){
listCarActivity.putExtra("typeVehicule", "Tourisme");
}
else if (state== "Utilitaire")
{
listCarActivity.putExtra("typeVehicule", "Utilitaire");
}
startActivity(listCarActivity);
}
}
}); */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
/*btnVilleDepart.setText(data.getCharSequenceExtra("nomVille"));
ville = btnVilleDepart.getText().toString();*/
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
<file_sep>/success_v1/src/com/success_v1/vehicule/Detail.java
package com.success_v1.vehicule;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.success_v1.res.JSONParser;
import com.success_v1.res.config;
import com.success_v1.successCar.R;
import com.success_v1.user.SessionManager;
public class Detail extends Activity {
private TextView id_vehicule;
private TextView model_vehicule;
private TextView marque_vehicule;
private TextView moteur_vehicule;
//private TextView couleur_vehicule;
//private TextView annee_vehicule;
//private TextView km_vehicule;
private TextView prix_vehicule;
private TextView genreUser;
private TextView prenomUser;
private TextView nomUser;
private TextView mailUser;
private TextView numeroUser;
//private TextView titleActionBar;
private ImageView imageCaisse;
//private ImageView logoEtape;
private TextView nbre_jours_reserv;
private TextView date_depart;
private TextView date_retour;
String date;
private SessionManager session;
private String pid;
private String pid_user;
private String date_depart_intent;
private String date_retour_intent;
private String url_image;
private String id_agence;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
private JSONParser jsonParser = new JSONParser();
private Integer numberDays;
private Integer carPrice;
private DateTime dt;
private DateTime dt2;
Intent result;
public void ConvertDate(String format, TextView txtdate)
{
date = new SimpleDateFormat(format).format(new Date());
txtdate.setText(date);
}
private static String url_detail = config.getURL()+"get_vehicule_detail.php";
private static String url_reservation = config.getURL()+"add_reservation.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_TAB = "vehicule_tab";
private static final String TAG_ID = "id";
private static final String TAG_MODEL = "modele";
private static final String TAG_ID_Agence = "id_agence";
//private static final String TAG_COLOR = "couleur";
private static final String TAG_ENGINE = "motorisation";
private static final String TAG_MARK = "marque";
//private static final String TAG_KM = "kilometrage";
//private static final String TAG_YEAR = "annee";
private static final String TAG_PRICE = "tarifJour";
private JSONObject detail_tab = new JSONObject();
private HashMap<String, String> user = new HashMap<String, String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vehicule_detail);
//getActionBar().setDisplayShowHomeEnabled(false);
/*getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.koutchy_actionbar);
titleActionBar = (TextView)findViewById(R.id.titleActionBar);
titleActionBar.setText("Crรฉation de la rรฉservation (3/3)");
logoEtape = (ImageView)findViewById(R.id.logoEtape3);
logoEtape.setVisibility(ImageView.VISIBLE);*/
getActionBar().setTitle("");
session = new SessionManager(getApplicationContext());
user = session.getUserDetails();
pid_user = user.get(SessionManager.KEY_ID);
Intent result = getIntent();
pid = result.getStringExtra("id_voiture");
date_depart_intent = result.getStringExtra("date_depart");
date_retour_intent = result.getStringExtra("date_retour");
url_image = result.getStringExtra("url_image");
Log.i("dt",date_depart_intent);
Log.i("dt_rt",date_retour_intent);
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
dt = formatter.parseDateTime(date_depart_intent);
DateTimeFormatter formatter2 = DateTimeFormat.forPattern("yyyy-MM-dd");
dt2 = formatter2.parseDateTime(date_retour_intent);
Log.i("aze",dt.toString());
numberDays = Days.daysBetween(dt, dt2).getDays() + 1;
id_vehicule = (TextView) findViewById(R.id.id_vehicule_recup);
model_vehicule = (TextView) findViewById(R.id.nom_vehicule_recup);//
marque_vehicule = (TextView) findViewById(R.id.marqueVehicule);//
moteur_vehicule = (TextView) findViewById(R.id.motorVehicule);
prix_vehicule = (TextView) findViewById(R.id.prixVehicule);
genreUser= (TextView) findViewById(R.id.txtGenreResume);
nomUser= (TextView) findViewById(R.id.txtNomResume);
prenomUser = (TextView) findViewById(R.id.txtPrenomResume);
mailUser = (TextView) findViewById(R.id.txtMailResume);
numeroUser = (TextView) findViewById(R.id.txtPhoneResume);
imageCaisse = (ImageView) findViewById(R.id.imgLogoCar);
date_depart = (TextView) findViewById(R.id.date_depart_recup);//
date_retour = (TextView) findViewById(R.id.date_retour_recup);//
nbre_jours_reserv = (TextView) findViewById(R.id.nbre_jours_reserv);//
prenomUser.setText(user.get(SessionManager.KEY_PRENOM));
nomUser.setText(user.get(SessionManager.KEY_NOM));
mailUser.setText(user.get(SessionManager.KEY_MAIL));
numeroUser.setText(user.get(SessionManager.KEY_NUM));
findViewById(R.id.btntestreseravation).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if(session.isLoggedIn())
{
new AddReservation().execute();
}
else
{
Intent intent = new Intent(getApplicationContext(), com.success_v1.user.LogPage.class);
startActivityForResult(intent,55);
}
}
});
new GetCarDetails().execute();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 55)
{
if(resultCode == RESULT_OK)
{
user = session.getUserDetails();
pid_user = user.get(SessionManager.KEY_ID);
prenomUser.setText(user.get(SessionManager.KEY_PRENOM));
nomUser.setText(user.get(SessionManager.KEY_NOM));
mailUser.setText(user.get(SessionManager.KEY_MAIL));
numeroUser.setText(user.get(SessionManager.KEY_NUM));
}
}
}
class GetCarDetails extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Detail.this);
pDialog.setMessage("Loading .Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id_get_voiture", pid));
JSONObject json = jsonParser.makeHttpRequest(url_detail, "GET", params);
Log.d("Detail", json.toString() + pid);
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray productObj = json.getJSONArray(TAG_TAB);
detail_tab = productObj.getJSONObject(0);
}else{
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
try {
id_vehicule.setText(detail_tab.getString(TAG_ID));
model_vehicule.setText(detail_tab.getString(TAG_MODEL));
marque_vehicule.setText(detail_tab.getString(TAG_MARK));
moteur_vehicule.setText(detail_tab.getString(TAG_ENGINE));
carPrice = Integer.valueOf(detail_tab.getString(TAG_PRICE));
carPrice = carPrice * numberDays;
nbre_jours_reserv.setText(numberDays.toString());
prix_vehicule.setText(carPrice.toString());
Picasso.with(getApplicationContext()).load(url_image).into(imageCaisse);
date_depart.setText(dt.toString("dd-MM-yyyy"));
date_retour.setText(dt2.toString("dd-MM-yyyy"));
/******* Convertisseur a revoire ***********/
//ConvertDate("dd-MM-yyyy", date_depart);
//ConvertDate("dd-MM-yyyy", date_retour);
id_agence = detail_tab.getString(TAG_ID_Agence);
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
}
class AddReservation extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Detail.this);
pDialog.setMessage("Reservation en cours ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id_vehicule", pid));
params.add(new BasicNameValuePair("id_user", pid_user));
params.add(new BasicNameValuePair("date_depart", date_depart_intent));
params.add(new BasicNameValuePair("date_retour", date_retour_intent));
params.add(new BasicNameValuePair("nb_jour", numberDays.toString()));
params.add(new BasicNameValuePair("prix_total", carPrice.toString()));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_reservation, "POST", params);
// check log cat fro response
Log.d("Test reservation", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
//Intent result = getIntent();
//setResult(RESULT_OK, result);
//finish();
// intent 2 recupe agence ID:
result = new Intent(Detail.this, com.success_v1.agence.Detail.class);
result.putExtra("id_agence", id_agence);
startActivityForResult(result,1);
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode == KeyEvent.KEYCODE_BACK)
{
setResult(RESULT_OK, result);
finish();
}
return super.onKeyDown(keyCode, event);
}
}
| 0e080292ce87dac0d13a04328e6057a8c8622823 | [
"Markdown",
"Java"
] | 8 | Java | MehdiAit/Success_v2.2 | dbaffbb32a4eba203bd4d8df2709d25f2d572fd4 | eee8433e74d8d64fa8089ddba380717ccd5f11e3 |
refs/heads/master | <file_sep># info-block
ๆฏไธไธช็ๆไพง่พนๅผนๅบๆก็jsๅฐๆไปถ๏ผๅคช่ไบไผผไนไธ่ฝ็ฎๅฐ็จๅบๅๅๅ๏ผ
## ไธป่ฆๅ่ฝ
ๅฏไปฅๅจ้กต้ขๅผนๅบไธไธชๆ็คบๆก๏ผๅจ็ป่ฟๅ
ฅๅจ็ปๆทกๅบ
ๆพ็คบๆถ้ด10s๏ผไนๅฏไปฅ่ชๅทฑๅ
ณ้ญ
## ่ฐ็จๆนๆณ
```javascript
addInfo(ๆ ้ข,ๅ
ๅฎน,่ๆฏ้ข่ฒ,ๆๅญ้ข่ฒ)
```
ๆ ้ข๏ผๅ
ๅฎนๅฟ
้กป้ข่ฎพ๏ผๅฆๅๅฐฑๆฏไธชๅฅไนๆฒกๆ็ๆกๆก
่ๆฏ้ข่ฒ้ป่ฎค๏ผrgba(233, 233, 233, 0.74)
ๆๅญ้ข่ฒ้ป่ฎค๏ผ#001f3f
<file_sep>function addInfo(h,ib,bgc = '',tc = '') {
if (h == undefined || ib == undefined){
h = '';
ib = '';
}
let body = document.getElementById('ibset');
let infoblock = document.createElement('div');
let button = '<div class="ib-x" onclick="ibxh()"><b>x</b></div>\n';
let head = '<h3>'+h+'</h3>\n' ;
let ibb = '<p>'+ib+'</p>\n';
let rand = Math.random();
infoblock.setAttribute('class','info-block fadenum');
infoblock.setAttribute('id',rand);
if (bgc !== ''){
infoblock.setAttribute('style', 'background-color:'+bgc+'');
}
if (tc !== ''){
infoblock.setAttribute('style', 'color:'+tc+'');
}
if (tc !== '' && bgc !== ''){
infoblock.setAttribute('style', 'color:'+tc+';' + 'background-color:'+bgc+'');
}
infoblock.innerHTML = button + head + ibb;
body.appendChild(infoblock);
setTimeout("document.getElementById('"+rand+"').classList.add('fadeout');",8300);
setTimeout("document.getElementById('"+rand+"').parentNode.removeChild(document.getElementById('"+rand+"'))", 10000);
}
function ibxh() {
let ibx = document.getElementsByClassName('info-block');
let ibxl = ibx.length;
ibx[ibxl - 1].classList.add('fadeout');
setTimeout("document.getElementsByClassName('info-block')[document.getElementsByClassName('info-block').length - 1].parentNode.removeChild(document.getElementsByClassName('info-block')[document.getElementsByClassName('info-block').length - 1])", 2000);
// ibx[ibxl - 1].parentNode.removeChild(ibx[ibxl - 1]);
}
| 8fe6ce9b1fe6d9419ce4c2f1d350f6e22e247acb | [
"Markdown",
"JavaScript"
] | 2 | Markdown | misaki-kiko/info-block | a9e359088f982e78731fd96cd519f38052d4262a | 6dad20f494fec46720645eb91c2df3333d4fca96 |
refs/heads/master | <repo_name>psztefko/ING-app<file_sep>/app/src/main/java/com/example/ing_app/ui/user/UserViewModel.kt
package com.example.ing_app.ui.user
import android.view.View
import androidx.databinding.ObservableField
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.ing_app.common.ResultType
import com.example.ing_app.common.Result
import com.example.ing_app.domain.User
import com.example.ing_app.repository.UserRepository
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.launch
import timber.log.Timber
class UserViewModel (private val userKey: Int = 0,
private val userRepository: UserRepository): ViewModel(){
private val _user: MutableLiveData<User> = MutableLiveData()
val user: LiveData<User>
get() = _user
private val _isErrorLiveData: MutableLiveData<Boolean> = MutableLiveData()
val isErrorLiveData: LiveData<Boolean>
get() = _isErrorLiveData
private val _navigateToSelectedPhotos = MutableLiveData<Int>()
val navigateToSelectedPhotos: LiveData<Int>
get() = _navigateToSelectedPhotos
private val _navigateToPosts = MutableLiveData<Boolean?>()
val navigateToPosts: LiveData<Boolean?>
get() = _navigateToPosts
// I am not sure if it's not better to do in fragment and add observer
val loadingVisibility: MutableLiveData<Int> = MutableLiveData()
val userVisibility: MutableLiveData<Int> = MutableLiveData()
val connectionError: MutableLiveData<Int> = MutableLiveData()
init {
getUser()
}
fun getUser() {
viewModelScope.launch {
loadingVisible()
val apiResult = userRepository.getUserFromPost(userKey)
updateUser(apiResult)
}
}
private fun updateUser(result: Result<User>) {
if (isResultSuccess(result.resultType)) {
Timber.d("onUpdateUserSuccess called")
_user.postValue(result.data)
userVisible()
} else {
onResultError()
}
}
fun onUserPhotosClicked(id: Int) {
_navigateToSelectedPhotos.value = id
}
fun displayPhotosCopmlete() {
_navigateToSelectedPhotos.value = null
}
fun doneNavigating() {
_navigateToPosts.value = null
}
fun onClose() {
_navigateToPosts.value = true
}
private fun isResultSuccess(resultType: ResultType): Boolean {
//tak
return resultType == ResultType.SUCCESS
}
private fun onResultError() {
errorVisible()
_isErrorLiveData.postValue(true)
}
private fun loadingVisible(){
userVisibility.value = View.GONE
connectionError.value = View.GONE
loadingVisibility.value = View.VISIBLE
}
private fun errorVisible() {
userVisibility.value = View.GONE
loadingVisibility.value = View.GONE
connectionError.value = View.VISIBLE
}
private fun userVisible(){
loadingVisibility.value = View.GONE
connectionError.value = View.GONE
userVisibility.value = View.VISIBLE
}
}<file_sep>/app/src/main/java/com/example/ing_app/common/ResultType.kt
package com.example.ing_app.common
enum class ResultType {
FAILURE,
SUCCESS
}<file_sep>/app/src/main/java/com/example/ing_app/ui/comments/CommentViewModel.kt
package com.example.ing_app.ui.comments
import android.view.View
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.ing_app.common.ResultType
import com.example.ing_app.common.Result
import com.example.ing_app.domain.Comment
import com.example.ing_app.repository.CommentRepository
import kotlinx.coroutines.launch
import timber.log.Timber
class CommentViewModel (private val commentKey: Int = 0,
private val commentRepository: CommentRepository): ViewModel() {
private val _comments: MutableLiveData<List<Comment>> = MutableLiveData()
val comments: LiveData<List<Comment>>
get() = _comments
private val _isErrorLiveData: MutableLiveData<Boolean> = MutableLiveData()
val isErrorLiveData: LiveData<Boolean>
get() = _isErrorLiveData
private val _navigateToPosts = MutableLiveData<Boolean?>()
val navigateToPosts: LiveData<Boolean?>
get() = _navigateToPosts
val loadingVisibility: MutableLiveData<Int> = MutableLiveData()
val connectionError: MutableLiveData<Int> = MutableLiveData()
val commentsVisibility: MutableLiveData<Int> = MutableLiveData()
init {
getComments()
}
fun getComments(){
loadingVisible()
viewModelScope.launch {
val apiResult = commentRepository.getCommentsFromPost(commentKey)
updateComments(apiResult)
}
}
private fun updateComments(result: Result<List<Comment>>) {
if (isResultSuccess(result.resultType)) {
_comments.postValue(result.data)
commentsVisible()
} else {
onResultError()
}
}
private fun isResultSuccess(resultType: ResultType): Boolean {
return resultType == ResultType.SUCCESS
}
fun doneNavigating() {
_navigateToPosts.value = null
}
fun onClose() {
_navigateToPosts.value = true
}
private fun onResultError() {
Timber.d("onCommentsError")
_isErrorLiveData.postValue(true)
errorVisible()
}
private fun commentsVisible(){
loadingVisibility.value = View.GONE
connectionError.value = View.GONE
commentsVisibility.value = View.VISIBLE
}
private fun errorVisible(){
commentsVisibility.value = View.GONE
loadingVisibility.value = View.GONE
connectionError.value = View.VISIBLE
}
private fun loadingVisible(){
commentsVisibility.value = View.GONE
connectionError.value = View.GONE
loadingVisibility.value = View.VISIBLE
}
}<file_sep>/app/src/main/java/com/example/ing_app/common/exception/CancelledFetchDataException.kt
package com.example.ing_app.common.exception
import java.lang.Exception
class CancelledFetchDataException : Exception()<file_sep>/app/src/androidTest/java/com/example/ing_app/MyTest.kt
package com.example.ing_app
import com.example.ing_app.modules.CommentModule
import com.example.ing_app.modules.ImageModule
import com.example.ing_app.modules.PostModule
import com.example.ing_app.modules.UserModule
import org.junit.Test
import org.koin.core.context.startKoin
import org.koin.test.KoinTest
class MyTest : KoinTest{
@Test
fun makeATestWithKoin() {
}
}<file_sep>/app/src/main/java/com/example/ing_app/database/PostsDao.kt
package com.example.ing_app.database
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
@Dao
interface PostsDao {
@Query("SELECT * FROM databasepost")
fun getPosts(): LiveData<List<DatabasePost>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(vararg posts: DatabasePost)
}<file_sep>/app/src/main/java/com/example/ing_app/modules/UserModule.kt
package com.example.ing_app.modules
import com.example.ing_app.network.user.UserApi
import com.example.ing_app.network.user.UserService
import com.example.ing_app.repository.UserRepository
import com.example.ing_app.ui.user.UserViewModel
import org.koin.android.ext.koin.androidContext
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
object UserModule {
val mainModule = module {
single { UserApi(androidContext()) }
single {
provideApiService(
get()
)
}
single { UserRepository(userService = get()) }
viewModel {(userId: Int) -> UserViewModel(userId, userRepository = get())}
}
private fun provideApiService(api: UserApi): UserService {
return api.getApiService()
}
}<file_sep>/app/src/main/java/com/example/ing_app/App.kt
package com.example.ing_app
import android.app.Application
import com.example.ing_app.modules.CommentModule
import com.example.ing_app.modules.ImageModule
import com.example.ing_app.modules.PostModule
import com.example.ing_app.modules.UserModule
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
import timber.log.Timber
class App : Application (){
var listofModules =
listOf(
PostModule.mainModule,
UserModule.mainModule,
CommentModule.mainModule,
ImageModule.mainModule
)
override fun onCreate() {
super.onCreate()
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
startKoin {
androidLogger()
androidContext(this@App)
modules(listofModules)
}
}
}<file_sep>/app/src/main/java/com/example/ing_app/ui/posts/PostFragment.kt
package com.example.ing_app.ui.posts
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.example.ing_app.R
import com.example.ing_app.databinding.FragmentPostBinding
import kotlinx.android.synthetic.main.fragment_post.*
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdSize
import com.google.android.gms.ads.AdView
import com.google.android.gms.ads.MobileAds
import timber.log.Timber
lateinit var mAdView : AdView
class PostFragment : Fragment(), SwipeRefreshLayout.OnRefreshListener {
private val viewModel: PostViewModel by sharedViewModel()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
swipeRefreshLayout.setOnRefreshListener() {
Timber.d("onRefreshListener")
onRefresh()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentPostBinding.inflate(inflater)
binding.lifecycleOwner = this
binding.viewModel = viewModel
val adapter = PostAdapter( UserClickListener {
userId -> viewModel.onPostUserClicked(userId)
},
CommentClickListener {
id -> viewModel.onPostCommentClicked(id)
})
binding.postsList.adapter = adapter
viewModel.posts.observe(viewLifecycleOwner, Observer {
it?.let {
adapter.submitList(it)
}
})
viewModel.navigateToSelectedUser.observe(viewLifecycleOwner, Observer {userId ->
userId?.let {
this.findNavController().navigate(PostFragmentDirections.postsToUsername(userId))
viewModel.displayUserComplete()
}
})
viewModel.navigateToSelectedComments.observe(viewLifecycleOwner, Observer {id ->
id?.let {
this.findNavController().navigate(PostFragmentDirections.postsToComments(id))
viewModel.displayCommentsComplete()
}
})
val adView = AdView(context)
adView.adSize = AdSize.SMART_BANNER
adView.adUnitId = getString(R.string.admob_banner_ad)
MobileAds.initialize(context) {}
mAdView = binding.adView
val adRequest = AdRequest.Builder().build()
mAdView.loadAd(adRequest)
return binding.root
}
override fun onRefresh() {
viewModel.getPosts()
swipeRefreshLayout.isRefreshing = false
}
}<file_sep>/app/src/main/java/com/example/ing_app/repository/CommentRepository.kt
package com.example.ing_app.repository
import com.example.ing_app.common.exception.CancelledFetchDataException
import com.example.ing_app.common.exception.NetworkException
import com.example.ing_app.common.Result
import com.example.ing_app.domain.Comment
import com.example.ing_app.network.comment.CommentService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import timber.log.Timber
class CommentRepository (private val commentService: CommentService){
suspend fun getCommentsFromPost(postId:Int): Result<List<Comment>> {
var result: Result<List<Comment>> = Result.success(emptyList())
withContext(Dispatchers.IO) {
try{
val request = commentService.getCommentsFromPost(postId)
val response = request.await()
Timber.d("onCommentsFromPostReceived $request")
request.let {
if (it.isCompleted) {
result = Result.success(response)
} else if (it.isCancelled) {
result = Result.failure(CancelledFetchDataException())
}
}
} catch (ex: Throwable) {
result = Result.failure(NetworkException())
Timber.d("onCommentReceived NetworkException")
}
}
return result
}
}<file_sep>/app/src/main/java/com/example/ing_app/ui/comments/CommentAdapter.kt
package com.example.ing_app.ui.comments
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.ing_app.databinding.CommentRowBinding
import com.example.ing_app.domain.Comment
class CommentAdapter :
ListAdapter<Comment, CommentAdapter.ViewHolder>(PostDiffCallback()) {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)
holder.bind(item)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder.from(parent)
}
class ViewHolder private constructor(val binding: CommentRowBinding):
RecyclerView.ViewHolder(binding.root) {
fun bind(item: Comment) {
binding.comment = item
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = CommentRowBinding.inflate(layoutInflater, parent , false)
return ViewHolder(binding)
}
}
}
}
class PostDiffCallback : DiffUtil.ItemCallback<Comment>() {
override fun areItemsTheSame(oldItem: Comment, newItem: Comment): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Comment, newItem: Comment): Boolean {
return oldItem == newItem
}
}<file_sep>/app/src/main/java/com/example/ing_app/ui/images/ImageViewModel.kt
package com.example.ing_app.ui.images
import android.view.View
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.ing_app.domain.Photo
import com.example.ing_app.repository.ImageRepository
import com.example.ing_app.common.Result
import com.example.ing_app.common.ResultType
import com.example.ing_app.domain.Album
import kotlinx.coroutines.launch
import timber.log.Timber
class ImageViewModel (private val userKey: Int = 0,
private val imageRepository: ImageRepository): ViewModel(){
private var _photosList = mutableListOf<Photo>()
val photosList: List<Photo>
get() = _photosList
private val _photos: MutableLiveData<List<Photo>> = MutableLiveData()
val photos: LiveData<List<Photo>>
get() = _photos
private val _isErrorLiveData: MutableLiveData<Boolean> = MutableLiveData()
val isErrorLiveData: LiveData<Boolean>
get() = _isErrorLiveData
private val _navigateToUser = MutableLiveData<Boolean?>()
val navigateToUser: LiveData<Boolean?>
get() = _navigateToUser
val connectionError: MutableLiveData<Int> = MutableLiveData()
val imagesVisibility: MutableLiveData<Int> = MutableLiveData()
val loadingVisibility: MutableLiveData<Int> = MutableLiveData()
init {
getAlbums()
}
// We can also take all albums and filter it but it is fine that way
//getting images from repository
fun getAlbums(){
_photosList = mutableListOf<Photo>()
viewModelScope.launch {
loadingVisible()
Timber.d("getAlbums userKey: $userKey")
val apiResult = imageRepository.getAlbumsFromUser(userKey)
Timber.d("getAlbums ${apiResult}")
getPhotos(apiResult)
}
}
private fun getPhotos(result: Result<List<Album>>) {
viewModelScope.launch {
if (isResultSuccess(result.resultType)) {
result.data?.forEach {
val apiResult = imageRepository.getPhotosFromAlbum(it.id)
Timber.d("getPhotos ${apiResult}")
updatePhotos(apiResult)
}
} else {
onResultError()
}
}
}
private fun updatePhotos(result: Result<List<Photo>>) {
if (isResultSuccess(result.resultType)) {
imagesVisible()
// TODO: Should add paging better and add another method for moving photos to mutable list
result.data?.forEach { photo -> _photosList.add(photo) }
Timber.d("last element of photosList: ${photosList.last()}")
_photos.postValue(photosList)
} else {
onResultError()
}
}
fun doneNavigating() {
_navigateToUser.value = null
}
fun onClose() {
_navigateToUser.value = true
}
private fun isResultSuccess(resultType: ResultType): Boolean {
return resultType == ResultType.SUCCESS
}
private fun onResultError() {
errorVisible()
_isErrorLiveData.postValue(true)
}
private fun imagesVisible(){
loadingVisibility.value = View.GONE
connectionError.value = View.GONE
imagesVisibility.value = View.VISIBLE
}
private fun errorVisible(){
imagesVisibility.value = View.GONE
loadingVisibility.value = View.GONE
connectionError.value = View.VISIBLE
}
private fun loadingVisible(){
imagesVisibility.value = View.GONE
connectionError.value = View.GONE
loadingVisibility.value = View.VISIBLE
}
}<file_sep>/app/src/main/java/com/example/ing_app/common/exception/NetworkException.kt
package com.example.ing_app.common.exception
import java.lang.Exception
class NetworkException : Exception()<file_sep>/app/src/main/java/com/example/ing_app/repository/UserRepository.kt
package com.example.ing_app.repository
import com.example.ing_app.common.Result
import com.example.ing_app.common.exception.CancelledFetchDataException
import com.example.ing_app.common.exception.NetworkException
import com.example.ing_app.domain.User
import com.example.ing_app.network.user.UserService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import timber.log.Timber
class UserRepository(private val userService: UserService) {
suspend fun getUserFromPost(postId: Int): Result<User> {
var result: Result<User> = Result.success(User())
withContext(Dispatchers.IO) {
try {
val request = userService.getUser(postId)
val response = request.await()
Timber.d("onUserReceived {$request}")
request.let {
if (it.isCompleted) {
result = Result.success(response)
} else if (it.isCancelled) {
result = Result.failure(CancelledFetchDataException())
}
}
} catch (ex: Throwable) {
result = Result.failure(NetworkException())
Timber.d("onUserReceived NetworkException")
}
}
return result
}
}<file_sep>/app/src/main/java/com/example/ing_app/modules/PostModule.kt
package com.example.ing_app.modules
import com.example.ing_app.network.post.PostApi
import com.example.ing_app.network.post.PostService
import com.example.ing_app.repository.PostRepository
import com.example.ing_app.ui.posts.PostViewModel
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
import org.koin.androidx.viewmodel.dsl.viewModel
object PostModule {
val mainModule = module {
single { PostApi(androidContext()) }
single {
providePostApiService(
get()
)
}
single { PostRepository(postService = get(), commentService = get(), userService = get()) }
viewModel { PostViewModel(postRepository = get())}
}
private fun providePostApiService(api: PostApi): PostService {
return api.getApiService()
}
}<file_sep>/app/src/main/java/com/example/ing_app/repository/ImageRepository.kt
package com.example.ing_app.repository
import com.example.ing_app.common.Result
import com.example.ing_app.common.exception.CancelledFetchDataException
import com.example.ing_app.common.exception.NetworkException
import com.example.ing_app.domain.Photo
import com.example.ing_app.domain.Album
import com.example.ing_app.network.image.ImageService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import timber.log.Timber
class ImageRepository (private val imageService: ImageService){
suspend fun getAlbumsFromUser(userId:Int): Result<List<Album>> {
var result: Result<List<Album>> = Result.success(emptyList())
withContext(Dispatchers.IO) {
try{
val request = imageService.getAlbumsFromUser(userId)
val response = request.await()
Timber.d("onAlbumFromUserReceived $request")
request.let {
if (it.isCompleted) {
result = Result.success(response)
} else if (it.isCancelled) {
result = Result.failure(CancelledFetchDataException())
}
}
} catch (ex: Throwable) {
result = Result.failure(NetworkException())
Timber.d("onAlbumReceived NetworkException")
}
}
return result
}
suspend fun getPhotosFromAlbum(albumId:Int): Result<List<Photo>> {
var result: Result<List<Photo>> = Result.success(emptyList())
withContext(Dispatchers.IO) {
try{
val request = imageService.getPhotosFromAlbum(albumId)
val response = request.await()
Timber.d("onPhotosFromAlbumReceived $request")
request.let {
if (it.isCompleted) {
result = Result.success(response)
} else if (it.isCancelled) {
result = Result.failure(CancelledFetchDataException())
}
}
} catch (ex: Throwable) {
result = Result.failure(NetworkException())
Timber.d("onPhotosReceived NetworkException")
}
}
return result
}
}<file_sep>/app/src/main/java/com/example/ing_app/repository/PostRepository.kt
package com.example.ing_app.repository
import com.example.ing_app.common.Result
import com.example.ing_app.common.exception.CancelledFetchDataException
import com.example.ing_app.common.exception.NetworkException
import com.example.ing_app.database.PostsDatabase
import com.example.ing_app.domain.Comment
import com.example.ing_app.domain.Post
import com.example.ing_app.domain.User
import com.example.ing_app.network.comment.CommentService
import com.example.ing_app.network.post.PostService
import com.example.ing_app.network.user.UserService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import timber.log.Timber
class PostRepository (private val postService: PostService,
private val commentService: CommentService,
private val userService: UserService) {
suspend fun getPosts() : Result<List<Post>> {
var result: Result<List<Post>> = Result.success(emptyList())
withContext(Dispatchers.IO) {
try {
val request = postService.getPosts()
val response = request.await()
Timber.d("onPostsReceived {$request}")
request.let {
if (it.isCompleted) {
result = Result.success(response)
}
else if (it.isCancelled) {
result = Result.failure(CancelledFetchDataException())
}
}
} catch (ex: Throwable) {
result = Result.failure(NetworkException())
Timber.d("onPostReceived NetworkException")
}
}
return result
}
suspend fun getUsers(): Result<List<User>> {
var result: Result<List<User>> = Result.success(emptyList())
withContext(Dispatchers.IO) {
try {
val request = userService.getUsers()
val response = request.await()
Timber.d("onUsersReceived {$request}")
request.let {
if (it.isCompleted) {
result = Result.success(response)
} else if (it.isCancelled) {
result = Result.failure(CancelledFetchDataException())
}
}
} catch (ex: Throwable) {
result = Result.failure(NetworkException())
Timber.d("onUserReceived NetworkException")
}
}
return result
}
suspend fun getComments(): Result<List<Comment>> {
var result: Result<List<Comment>> = Result.success(emptyList())
withContext(Dispatchers.IO) {
try{
val request = commentService.getComments()
val response = request.await()
Timber.d("onCommentsReceived $request")
request.let {
if (it.isCompleted) {
result = Result.success(response)
} else if (it.isCancelled) {
result = Result.failure(CancelledFetchDataException())
}
}
} catch (ex: Throwable) {
result = Result.failure(NetworkException())
Timber.d("onCommentReceived NetworkException")
}
}
return result
}
}<file_sep>/app/src/main/java/com/example/ing_app/ui/comments/CommentFragment.kt
package com.example.ing_app.ui.comments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.example.ing_app.databinding.FragmentCommentsBinding
import com.example.ing_app.ui.user.UserFragmentArgs
import kotlinx.android.synthetic.main.fragment_post.*
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.core.parameter.parametersOf
import timber.log.Timber
import kotlin.properties.Delegates
class CommentFragment : Fragment(), SwipeRefreshLayout.OnRefreshListener {
var args by Delegates.notNull<Int>()
private val viewModel: CommentViewModel by sharedViewModel {parametersOf(args)}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentCommentsBinding.inflate(inflater)
binding.lifecycleOwner = this
args = UserFragmentArgs.fromBundle(requireArguments()).id
Timber.d("On comment args given: ${args}")
binding.viewModel = viewModel
val adapter = CommentAdapter()
binding.commentsList.adapter = adapter
viewModel.comments.observe(viewLifecycleOwner, Observer {
it?.let {
adapter.submitList(it)
}
})
viewModel.navigateToPosts.observe(viewLifecycleOwner, Observer {
if (it == true) {
this.findNavController().navigate(
CommentFragmentDirections.commentsToPosts())
viewModel.doneNavigating()
}
})
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
swipeRefreshLayout.setOnRefreshListener() {
Timber.d("onRefreshListener")
onRefresh()
}
}
override fun onRefresh() {
viewModel.getComments()
swipeRefreshLayout.isRefreshing = false
}
}<file_sep>/app/src/main/java/com/example/ing_app/ui/images/BindingAdapter.kt
package com.example.ing_app.ui.images
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.ing_app.R
import com.example.ing_app.domain.Photo
import com.squareup.picasso.Picasso
@BindingAdapter("listData")
fun bindRecyclerView(recyclerView: RecyclerView, data: List<Photo>?) {
val adapter = recyclerView.adapter as PhotoGridAdapter
adapter.submitList(data)
}
@BindingAdapter("imageUrl")
fun bindImage(imgView: ImageView, imgUrl: String?) {
imgUrl?.let {
Picasso.get()
.load(imgUrl)
.resize(150,150)
.placeholder(R.drawable.loading_animation)
.error(R.drawable.ic_broken_image_black_24dp)
.into(imgView)
}
}<file_sep>/app/src/main/java/com/example/ing_app/ui/posts/PostViewModel.kt
package com.example.ing_app.ui.posts
import android.view.View
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.ing_app.common.Result
import com.example.ing_app.common.ResultType
import com.example.ing_app.domain.Comment
import com.example.ing_app.domain.User
import com.example.ing_app.ui.posts.Post as UiPost
import com.example.ing_app.repository.PostRepository
import kotlinx.coroutines.launch
import timber.log.Timber
class PostViewModel(private val postRepository: PostRepository) : ViewModel() {
private var _postsList = mutableListOf<UiPost>()
val postsList: List<UiPost>
get() = _postsList
private val _posts: MutableLiveData<List<UiPost>> = MutableLiveData()
val posts: LiveData<List<UiPost>>
get() = _posts
private val _navigateToSelectedUser = MutableLiveData<Int>()
val navigateToSelectedUser: LiveData<Int>
get() = _navigateToSelectedUser
private val _navigateToSelectedComments = MutableLiveData<Int>()
val navigateToSelectedComments: LiveData<Int>
get() = _navigateToSelectedComments
private val _isErrorLiveData = MutableLiveData<Boolean>()
val navigateToErrorScreen: MutableLiveData<Boolean>
get() = _isErrorLiveData
// TODO: Should change to private val and return not unmutable list
val loadingVisibility: MutableLiveData<Int> = MutableLiveData()
val connectionError: MutableLiveData<Int> = MutableLiveData()
val postsVisibility: MutableLiveData<Int> = MutableLiveData()
init {
getPosts()
}
//changed to public from private to access from PostFragment
fun getPosts() {
viewModelScope.launch {
loadingVisible()
Timber.d("getPosts")
val apiResultPosts = postRepository.getPosts()
Timber.d("getComments")
val apiResultComments = postRepository.getComments()
Timber.d("getUsers")
val apiResultUsers = postRepository.getUsers()
transformPost(apiResultPosts, apiResultComments, apiResultUsers)
}
}
private fun transformPost(
domainPost: Result<List<com.example.ing_app.domain.Post>>,
commentResult: Result<List<Comment>>,
userResult: Result<List<User>>
) {
_postsList = mutableListOf()
viewModelScope.launch {
if(isResultSuccess(domainPost.resultType) &&
isResultSuccess(userResult.resultType) &&
isResultSuccess(commentResult.resultType)) {
domainPost.data?.forEach { post ->
val userName = userResult.data!!.first { it.id == post.userId }
val commentsAmount = commentResult.data!!.filter { it.postId == post.id }
val postData = UiPost(
id = post.id,
userId = post.userId,
userName = userName.username,
title = post.title,
body = post.body,
commentsAmount = commentsAmount.size)
Timber.d("Postdata = $postData")
_postsList.add(postData)
if(postsList.isNotEmpty() && postsList.size % 10 == 0) {
updatePosts(postsList)
}
}
} else {
onResultError()
}
}
}
private fun updatePosts(result: List<UiPost>) {
postsVisible()
_posts.postValue(result)
}
private fun isResultSuccess(resultType: ResultType): Boolean {
return resultType == ResultType.SUCCESS
}
private fun onResultError() {
Timber.d("onPostsError")
_isErrorLiveData.postValue(true)
errorVisible()
}
fun onPostUserClicked(id: Int) {
_navigateToSelectedUser.value = id
}
fun onPostCommentClicked(id: Int) {
_navigateToSelectedComments.value = id
}
fun displayUserComplete() {
_navigateToSelectedUser.value = null
}
fun displayCommentsComplete() {
_navigateToSelectedComments.value = null
}
private fun postsVisible(){
loadingVisibility.value = View.GONE
connectionError.value = View.GONE
postsVisibility.value = View.VISIBLE
}
private fun loadingVisible(){
postsVisibility.value = View.GONE
connectionError.value = View.GONE
loadingVisibility.value = View.VISIBLE
}
private fun errorVisible() {
postsVisibility.value = View.GONE
loadingVisibility.value = View.GONE
connectionError.value = View.VISIBLE
}
}<file_sep>/app/src/main/java/com/example/ing_app/ui/posts/PostAdapter.kt
package com.example.ing_app.ui.posts
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.ing_app.databinding.PostRowBinding
// Two listeners (probably not the best idea but android docs are literally the worst)
class PostAdapter(private val userClickListener: UserClickListener, private val commentClickListener: CommentClickListener) :
ListAdapter<Post, PostAdapter.ViewHolder>(PostDiffCallback()) {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)
holder.bind(userClickListener, commentClickListener, item)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder.from(parent)
}
class ViewHolder private constructor(val binding: PostRowBinding):
RecyclerView.ViewHolder(binding.root) {
fun bind(userClickListener: UserClickListener, commentClickListener: CommentClickListener, item: Post) {
binding.post = item
binding.userClickListener = userClickListener
binding.commentClickListener = commentClickListener
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = PostRowBinding.inflate(layoutInflater, parent , false)
return ViewHolder(binding)
}
}
}
}
class PostDiffCallback : DiffUtil.ItemCallback<Post>() {
override fun areItemsTheSame(oldItem: Post, newItem: Post): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Post, newItem: Post): Boolean {
return oldItem == newItem
}
}
class UserClickListener(val ClickListener: (userId: Int) -> Unit) {
fun onUserClick(post: Post) {
ClickListener(post.userId)
}
}
class CommentClickListener(val ClickListener: (id: Int) -> Unit) {
fun onCommentClick(post: Post) = ClickListener(post.id)
}<file_sep>/app/src/main/java/com/example/ing_app/database/DatabasePost.kt
package com.example.ing_app.database
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.example.ing_app.ui.posts.Post
@Entity
data class DatabasePost (
@PrimaryKey
val id: Int,
val userId: Int,
val userName: String,
val title: String,
val body: String,
val commentsAmount: Int
)
fun List<DatabasePost>.asDomainModel(): List<Post> {
return map {
Post(
id = it.id,
userId = it.userId,
userName = it.userName,
title = it.title,
body = it.body,
commentsAmount = it.commentsAmount
)
}
}<file_sep>/app/src/main/java/com/example/ing_app/ui/images/ImageFragment.kt
package com.example.ing_app.ui.images
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.ing_app.databinding.FragmentImagesBinding
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import kotlinx.android.synthetic.main.fragment_post.*
import timber.log.Timber
import kotlin.properties.Delegates
class ImageFragment : Fragment(), SwipeRefreshLayout.OnRefreshListener {
var args by Delegates.notNull<Int>()
private val viewModel: ImageViewModel by viewModel{ parametersOf(args) }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentImagesBinding.inflate(inflater)
binding.lifecycleOwner = this
args = ImageFragmentArgs.fromBundle(requireArguments()).userId
binding.viewModel = viewModel
binding.photoGrid.adapter = PhotoGridAdapter()
viewModel.navigateToUser.observe(viewLifecycleOwner, Observer {
if (it == true) {
this.findNavController().navigate(
ImageFragmentDirections.imagesToPosts())
viewModel.doneNavigating()
}
})
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
swipeRefreshLayout.setOnRefreshListener() {
Timber.d("onRefreshListener")
onRefresh()
}
}
override fun onRefresh() {
viewModel.getAlbums()
swipeRefreshLayout.isRefreshing = false
}
}<file_sep>/app/src/main/java/com/example/ing_app/database/PostsDatabase.kt
package com.example.ing_app.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [DatabasePost::class], version = 1, exportSchema = false)
abstract class PostsDatabase() : RoomDatabase() {
abstract val postsDao: PostsDao
}
private lateinit var INSTANCE: PostsDatabase
fun getDatabase(context: Context): PostsDatabase {
synchronized(PostsDatabase::class.java) {
if(!::INSTANCE.isInitialized) {
INSTANCE = Room.databaseBuilder(context.applicationContext,
PostsDatabase::class.java,
"posts").build()
}
}
return INSTANCE
}<file_sep>/settings.gradle
rootProject.name='ING-app'
include ':app'
<file_sep>/app/src/main/java/com/example/ing_app/ui/images/PhotoGridAdapter.kt
package com.example.ing_app.ui.images
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.ListAdapter
import com.example.ing_app.databinding.PhotoGridBinding
import com.example.ing_app.domain.Photo
class PhotoGridAdapter :
ListAdapter<Photo, PhotoGridAdapter.PhotoViewHolder>(DiffCallback) {
class PhotoViewHolder(private var binding: PhotoGridBinding):
RecyclerView.ViewHolder(binding.root) {
fun bind(photo: Photo) {
binding.photo = photo
binding.executePendingBindings()
}
}
companion object DiffCallback : DiffUtil.ItemCallback<Photo>() {
override fun areItemsTheSame(oldItem: Photo, newItem: Photo): Boolean {
return oldItem === newItem
}
override fun areContentsTheSame(oldItem: Photo, newItem: Photo): Boolean {
return oldItem.id == newItem.id
}
}
override fun onCreateViewHolder(parent: ViewGroup,
viewType: Int): PhotoViewHolder {
return PhotoViewHolder(PhotoGridBinding.inflate(LayoutInflater.from(parent.context)))
}
override fun onBindViewHolder(holder: PhotoViewHolder, position: Int) {
val photo = getItem(position)
holder.bind(photo)
}
}<file_sep>/app/src/main/java/com/example/ing_app/common/Result.kt
package com.example.ing_app.common
data class Result<out T>(
var resultType: ResultType,
val data: T? = null,
val failure: Exception? = null
) {
companion object {
fun <T> success(data: T?): Result<T> {
return Result(ResultType.SUCCESS, data)
}
fun <T> failure(failure: Exception? = null): Result<T> {
return Result(ResultType.FAILURE, failure = failure)
}
}
}<file_sep>/README.md
<!-- TABLE OF CONTENTS -->
## Table of Contents
* [About the Project](#about-the-project)
* [Built With](#built-with)
* [Getting Started](#getting-started)
* [Prerequisites](#prerequisites)
* [Installation](#installation)
* [Roadmap](#roadmap)
* [Adictional Info](#additional-info)
<!-- ABOUT THE PROJECT -->
## About The Project
Main goal of our app is to download, parse and display data from [JSONPlaceholderAPI](http://jsonplaceholder.typicode.com/).
This task may look simple, but we have already discovered that it isnโt.
Through making this app we want to learn programming in Kotlin language starting from basic parts like learning the syntax to more complicated stuff like following the optimal architecture rules of MVVM.
<img src="./Screenshots/app2.gif" alt="Screenshot of application" width=200>
### Built With
This section provide information about frameworks and technologies that our project is currently using
* [Gradle](https://gradle.org/)
* [Retrofit](https://square.github.io/retrofit/)
* [Moshi](https://github.com/square/moshi)
* [Koin](https://insert-koin.io/)
* [Timber](https://github.com/JakeWharton/timber)
* [Material Icons](https://material.io/resources/icons/?style=baseline)
* [Picasso](https://square.github.io/picasso/)
<!-- GETTING STARTED -->
## Getting Started
Here you can find how to locally set our project.
### Prerequisites
To build and install that project you need gradle. We are using android studio to compile everything
* gradle
```sh
./gradlew build
```
### Installation
1. Clone the repo
```sh
git clone https://github.com/psztefko/ING-app.git
```
2. Build project with gradle
```sh
./gradlew build
```
3. Install apk on your phone or run it with avd
## Additional Info
Project is realized in collaboration with [ING Bank ลlฤ
ski](https://www.ing.pl/)
<!-- MARKDOWN LINKS & IMAGES -->
[contributors-shield]: https://img.shields.io/github/contributors/psztefko/ING-app?style=flat-square
[contributors-url]: https://github.com/psztefko/ING-app/graphs/contributors
[stars-shield]: https://img.shields.io/github/stars/psztefko/ING-app?style=flat-square
[stars-url]: https://github.com/psztefko/ING-app/stargazers
[issues-shield]: https://img.shields.io/github/issues/psztefko/ING-app?style=flat-square
[issues-url]: https://github.com/psztefko/ING-app/issues
<file_sep>/app/src/main/java/com/example/ing_app/network/post/PostService.kt
package com.example.ing_app.network.post
import com.example.ing_app.domain.Post
import kotlinx.coroutines.Deferred
import retrofit2.http.GET
interface PostService {
@GET("/posts")
fun getPosts(): Deferred<List<Post>>
}<file_sep>/build.gradle
buildscript {
ext {
kotlin_version = '1.3.72'
koin_version = '2.1.4'
core_version = '1.2.0'
nav_version = '2.2.2'
lifecycle_version = '2.2.2'
coroutines_kotlin_version = '1.3.4'
retrofit_version = '2.9.0'
moshi_version = '1.9.2'
timber_version = '4.7.1'
room_version = '2.2.5'
work_version = '2.3.4'
appcompat_version = '1.1.0'
constraint_layout_version = '1.1.3'
fragment_version = '1.2.3'
maps_version = '17.0.0'
picasso_version = '2.71828'
}
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
<file_sep>/app/src/main/java/com/example/ing_app/network/user/UserService.kt
package com.example.ing_app.network.user
import com.example.ing_app.domain.User
import kotlinx.coroutines.Deferred
import retrofit2.http.GET
import retrofit2.http.Path
interface UserService {
@GET("/users/{userId}")
fun getUser(@Path("userId") userId : Int): Deferred<User>
@GET("/users")
fun getUsers(): Deferred<List<User>>
}<file_sep>/app/src/main/java/com/example/ing_app/ui/user/UserListener.kt
package com.example.ing_app.ui.user
import com.example.ing_app.domain.User
import timber.log.Timber
class UserListener(val clickListener: (userId: Int) -> Unit) {
fun onPhotosClicked(user: User) {
clickListener(user.id)
Timber.d("onPhotosClicked: ${user.id}")
}
}<file_sep>/app/src/main/java/com/example/ing_app/network/user/UserApi.kt
package com.example.ing_app.network.user
import android.content.Context
import com.example.ing_app.R
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
class UserApi(private val context: Context){
private val BASE_URL = "https://jsonplaceholder.typicode.com"
// Build the Moshi object that Retrofit will be using, making sure to add the Kotlin adapter for
// full Kotlin compatibility.
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
// Creating own timeout limits
private var okBuilder = OkHttpClient.Builder()
.readTimeout(R.integer.read_timeout.toLong(), TimeUnit.MILLISECONDS)
.connectTimeout(R.integer.connect_timeout.toLong(), TimeUnit.MILLISECONDS)
.build()
// Use the Retrofit builder to build a retrofit object using a Moshi converter
// with our Moshi object.
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.baseUrl(BASE_URL)
.build()
fun getApiService(): UserService {
return retrofit.create(UserService::class.java)
}
}
<file_sep>/app/src/main/java/com/example/ing_app/network/image/ImageService.kt
package com.example.ing_app.network.image
import com.example.ing_app.domain.Album
import com.example.ing_app.domain.Photo
import kotlinx.coroutines.Deferred
import retrofit2.http.GET
import retrofit2.http.Query
interface ImageService {
@GET("/albums")
fun getAlbumsFromUser(@Query("userId") userId: Int): Deferred<List<Album>>
@GET("/photos")
fun getPhotosFromAlbum(@Query("albumId") albumId: Int): Deferred<List<Photo>>
}<file_sep>/app/src/main/java/com/example/ing_app/network/comment/CommentService.kt
package com.example.ing_app.network.comment
import com.example.ing_app.domain.Comment
import kotlinx.coroutines.Deferred
import retrofit2.http.GET
import retrofit2.http.Query
interface CommentService {
@GET("/comments")
fun getCommentsFromPost(@Query("postId") postId: Int): Deferred<List<Comment>>
@GET("/comments")
fun getComments(): Deferred<List<Comment>>
}<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'androidx.navigation.safeargs.kotlin'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
dataBinding {
enabled = true
}
defaultConfig {
applicationId "com.example.ing_app"
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
// Support libs
implementation "androidx.appcompat:appcompat:$appcompat_version"
implementation "androidx.constraintlayout:constraintlayout:$constraint_layout_version"
// Android KTX
implementation "androidx.core:core-ktx:$core_version"
// Navigation
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
// Lifecycle
implementation "androidx.navigation:navigation-fragment-ktx:$lifecycle_version"
implementation "androidx.navigation:navigation-ui-ktx:$lifecycle_version"
// Couroutines for getting off the UI thread
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_kotlin_version"
// TODO: Delete this
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
// Retrofit for networking
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:converter-moshi:$retrofit_version"
// Moshi for parsing the JSON format
implementation "com.squareup.moshi:moshi:$moshi_version"
implementation "com.squareup.moshi:moshi-kotlin:$moshi_version"
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
kapt "com.squareup.moshi:moshi-kotlin-codegen:$moshi_version"
// Logging
implementation "com.jakewharton.timber:timber:$timber_version"
// Google Maps
implementation "com.google.android.gms:play-services-maps:17.0.0"
// Google Ads
implementation 'com.google.android.gms:play-services-ads:19.1.0'
// Picasso for images
implementation "com.squareup.picasso:picasso:$picasso_version"
// Koin
implementation "org.koin:koin-android:$koin_version"
implementation "org.koin:koin-androidx-scope:$koin_version"
implementation "org.koin:koin-androidx-viewmodel:$koin_version"
implementation "org.koin:koin-androidx-fragment:$koin_version"
implementation "org.koin:koin-androidx-ext:$koin_version"
// Room database for cache and offline experience
implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"
// WorkManager for fetching data in background
// implementation "androidx.work:work-runtime-ktx:$work_version"
// Test libs
testImplementation 'junit:junit:4.13'
testImplementation 'org.mockito:mockito-core:2.+'
testImplementation "org.koin:koin-test:$koin_version"
// should be test implementation but it won't work
implementation "org.koin:koin-test:$koin_version"
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
<file_sep>/app/src/main/java/com/example/ing_app/modules/CommentModule.kt
package com.example.ing_app.modules
import com.example.ing_app.network.comment.CommentApi
import com.example.ing_app.network.comment.CommentService
import com.example.ing_app.repository.CommentRepository
import com.example.ing_app.ui.comments.CommentViewModel
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
import org.koin.androidx.viewmodel.dsl.viewModel
object CommentModule {
val mainModule = module {
single { CommentApi(androidContext()) }
single {
provideApiService(
get()
)
}
single { CommentRepository(commentService = get()) }
viewModel {(postId: Int) -> CommentViewModel(postId, commentRepository = get()) }
}
private fun provideApiService(api: CommentApi): CommentService {
return api.getApiService()
}
}<file_sep>/app/src/main/java/com/example/ing_app/ui/user/UserFragment.kt
package com.example.ing_app.ui.user
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.example.ing_app.databinding.FragmentUserBinding
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import kotlinx.android.synthetic.main.fragment_post.*
import kotlinx.android.synthetic.main.fragment_user.*
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import timber.log.Timber
import kotlin.properties.Delegates
import kotlinx.android.synthetic.main.fragment_post.swipeRefreshLayout as swipeRefreshLayout1
class UserFragment : Fragment(), OnMapReadyCallback, SwipeRefreshLayout.OnRefreshListener {
// Why kotlin sugested Delegates
var args by Delegates.notNull<Int>()
private val viewModel: UserViewModel by viewModel{ parametersOf(args) }
private lateinit var mMap: GoogleMap
private lateinit var latLng: LatLng
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentUserBinding.inflate(inflater)
binding.lifecycleOwner = this
args = UserFragmentArgs.fromBundle(requireArguments()).id
binding.userListener = UserListener {
it -> viewModel.onUserPhotosClicked(it)
}
binding.viewModel = viewModel
viewModel.navigateToSelectedPhotos.observe(viewLifecycleOwner, Observer {userId ->
userId?.let{
this.findNavController().navigate(
UserFragmentDirections.userToImages(userId))
viewModel.displayPhotosCopmlete()
}
})
viewModel.navigateToPosts.observe(viewLifecycleOwner, Observer {
if (it == true) {
this.findNavController().navigate(
UserFragmentDirections.userToPosts())
viewModel.doneNavigating()
}
})
viewModel.user.observe(viewLifecycleOwner, Observer {
if (it != null) {
val lat = it.address.geo.lat.toDouble()
val lng = it.address.geo.lng.toDouble()
latLng = LatLng(lat, lng)
mMap.addMarker(MarkerOptions().position(latLng))
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng))
}
})
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
map.onCreate(savedInstanceState)
map.onResume()
map.getMapAsync(this)
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
swipeRefreshLayout.setOnRefreshListener() {
Timber.d("onRefreshListener")
onRefresh()
}
}
override fun onRefresh() {
viewModel.getUser()
swipeRefreshLayout.isRefreshing = false
}
// https://developers.google.com/maps/documentation/android-sdk/map#mapview
// We don't really need fully interactive mode because we only show location
// We can easily use lite mode of google maps, but it's documented badly
}<file_sep>/app/src/main/java/com/example/ing_app/modules/ImageModule.kt
package com.example.ing_app.modules
import com.example.ing_app.network.image.ImageApi
import com.example.ing_app.network.image.ImageService
import com.example.ing_app.repository.ImageRepository
import com.example.ing_app.ui.images.ImageViewModel
import org.koin.android.ext.koin.androidContext
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
object ImageModule {
val mainModule = module{
single { ImageApi(androidContext()) }
single {
provideApiService(
get()
)
}
single { ImageRepository(imageService = get()) }
viewModel {(userId: Int) -> ImageViewModel(userId, imageRepository = get()) }
}
private fun provideApiService(api: ImageApi): ImageService {
return api.getApiService()
}
}
| 803f285bdb9c3c17da5b1b0e132f6994136ec7e7 | [
"Markdown",
"Kotlin",
"Gradle"
] | 39 | Kotlin | psztefko/ING-app | 22e9d2c487d75e0bb434359f4f610e95b13a7338 | 9118da3446faf3dc1118002e5628315f9c713eae |
refs/heads/master | <file_sep>var client = new Keen({
projectId: "55f93f85d2eaaa05a699de39",
readKey: "<KEY>"
});
Keen.ready(function(){
// ----------------------------------------
// Pageviews Area Chart
// ----------------------------------------
var pageviews_timeline = new Keen.Query("maximum", {
eventCollection: "cindemas",
target_property: "count",
groupBy: "์บ๋ฆญํฐ",
interval: "daily",
timeframe: "this_14_days"
});
client.draw(pageviews_timeline, document.getElementById("main-chart-1"), {
chartType: "linechart",
title: false,
height: 240,
width: "auto",
chartOptions: {
chartArea: {
height: "85%",
left: "5%",
top: "5%",
width: "80%"
},
isStacked: false
}
});
});
$(document).ready(function() {
$(document).ajaxStart(function () {
$('div.loading').show();
});
$('button.btn-character').on('click', function(e) {
var char_id = $(this).attr("data-char-id") - 1;
var collection_id = $(this).parent().attr('data-collection-id') - 1;
$.ajax({
url : "api/get_twit",
data : {
"character" : char_id,
"collection" : collection_id
}
})
.done(function (e) {
var result = $.parseJSON(e);
if(result["result"]["result"]) {
Toast.show({
message : "๋ฐ์ดํฐ๋ฅผ ๊ฐฑ์ ํ์ต๋๋ค. 3์ดํ ์๋ก๊ณ ์นจํฉ๋๋ค"
});
setTimeout(function () {
location.reload(true);
}, 3000);
} else {
switch (result["status"]["code"]){
case 429:
// reached twitter rate limit
var ttl = result["result"]["ttl"];
Toast.show({
message : "๋จ์๊ฐ์ ๋๋ฌด ๋ง์ ์์ฒญ์ ๋ณด๋์ต๋๋ค. " + ttl + "์ด ๊ธฐ๋ค๋ ค์ฃผ์ธ์",
background : "#FF3300",
position : Toast.POSITION_TOP
})
break;
case 1001:
// already refreshed event
Toast.show({
message : "๋ค๋ฅธ ๋๊ตฐ๊ฐ๊ฐ ์ ๋ณด๋ฅผ ๊ฐฑ์ ์ค์
๋๋ค. ์กฐ๊ธ ๊ธฐ๋ค๋ ค์ฃผ์ธ์",
background : "#FF3300",
position : Toast.POSITION_TOP
});
break;
case 1002:
// on refreshing twitter search
var ttl = result["result"]["ttl"];
Toast.show({
message : "์ค๋์ ์ ๋ณด๊ฐ ๊ฐฑ์ ๋์์ต๋๋ค. ๋ด์ผ ์ ๋ณด๋ " + ttl + "์ด ๊ธฐ๋ค๋ ค์ฃผ์ธ์",
background : "#FF3300",
position : Toast.POSITION_TOP
})
break;
case 1003:
// uncaught required parameters
Toast.show({
message : "์ ์ ํ์ง ๋ชปํ ํ๋ผ๋ฏธํฐ ์กฐํฉ",
background : "#FF3300",
position : Toast.POSITION_TOP
})
break;
case 500:
default:
// Unknown
Toast.show({
message : "์์ ์๋ ์๋ฌ ๋ฐ์. ํธ์ํฐ ์๋ฌ์ผ ๊ฐ๋ฅ์ฑ์ด ๋์ต๋๋ค",
background : "#FF3300",
position : Toast.POSITION_TOP
})
break;
}
}
});
});
});
<file_sep>#!/usr/bin/env python
# -*- coding:utf8 -*-
import os
from flask import Flask
from blueprint import PageBlueprint
import charcollection
page_bp = PageBlueprint('page', __name__, static_folder='../view/static', template_folder='../view/template')
@page_bp.route('/')
def main():
return page_bp.make_response(collections = charcollection.collections, storage = charcollection.storage)
<file_sep>#!/usr/bin/env python
# -*- coding:utf8 -*-
from __future__ import print_function
class PrintString(object):
def print_tokens(self, tokens, end="\n"):
""" https://github.com/jaepil/twkorean
"""
if isinstance(tokens, list):
print("[", end="")
elif isinstance(tokens, tuple):
print("(", end="")
for t in tokens:
if t != tokens[-1]:
elem_end = ", "
else:
elem_end = ""
if isinstance(t, (list, tuple)):
self.print_tokens(t, end=elem_end)
else:
print(t, end=elem_end)
if isinstance(tokens, list):
print("]", end=end)
elif isinstance(tokens, tuple):
print(")", end=end)
<file_sep>#!/usr/bin/env python
# -*- coding:utf8 -*-
import os
from flask import Flask
from application.apis import api_bp
from application.page import page_bp
app = Flask(__name__, static_url_path='/')
app.register_blueprint(api_bp)
app.register_blueprint(page_bp)
<file_sep>#!/usr/bin/env python
# -*- coding:utf8 -*-
import json
import flask
from flask import Blueprint, render_template
class APIResponseMaker(object):
def make_response(self, **kwargs):
return repr(dict(self._marshal_dict(kwargs)))
@classmethod
def _marshal_dict(cls, source_dict):
for name, value in source_dict.items():
if isinstance(value, dict):
yield (name, dict(cls._marshal_dict(value)))
elif isinstance(value, list):
yield (name, list(cls._marshal_list(value)))
elif hasattr(value, 'marshal'):
yield (name, value.marshal())
else:
yield (name, value)
@classmethod
def _marshal_list(cls, source_list):
for value in source_list:
if isinstance(value, dict):
yield (dict(cls._marshal_dict(value)))
elif isinstance(value, list):
yield (list(cls._marshal_list(value)))
elif hasattr(value, 'marshal'):
yield (value.marshal())
else:
yield value
class JSONAPIResponseMaker(APIResponseMaker):
RESPONSE_HEADERS = {
'Content-Type': 'application/json; charset=utf-8'
}
def make_response(self, **kwargs):
response_dict = dict(self._marshal_dict(kwargs))
response_text = json.dumps(response_dict, ensure_ascii=False, encoding='utf8')
response = flask.make_response(response_text)
response.headers.extend(self.RESPONSE_HEADERS)
return response
class APIBlueprint(Blueprint):
API_RESPONSE_MAKER_DICT = {
'json': JSONAPIResponseMaker()
}
def make_response(self, **kwargs):
api_response_maker = self.API_RESPONSE_MAKER_DICT['json']
return api_response_maker.make_response(**kwargs)
class PageResponseMaker(object):
def make_response(self, **kwargs):
if 'page' in kwargs:
return render_template(kwargs['page'], **kwargs)
else:
return render_template('index.html', **kwargs)
class PageBlueprint(Blueprint):
def make_response(self, **kwargs):
response_maker = PageResponseMaker()
return response_maker.make_response(**kwargs)
<file_sep>#!/usr/bin/env python
# -*- coding:utf8 -*-
import redis
REDIS_URL_CONFIG = "redis://h:p91di8krbhqtua66k6ktsrrs53s@ec2-54-235-152-160.compute-1.amazonaws.com:14039"
r = redis.from_url(REDIS_URL_CONFIG)
def redis_set(key, value, expire=None):
""" key: string
value: any value (not list, dict)
expire: integer (seconds)
"""
if expire is None:
r.set(key, value)
else:
r.setex(key, value, expire)
def redis_get(key):
return r.get(key)
def redis_ttl(key):
return r.ttl(key)
def expire_lock_twitter_search():
key = "rate-limit-search"
redis_set(key, True, 60 * 15)
return True
def exist_lock_twitter_search():
key = "rate-limit-search"
if redis_get(key):
return True
else:
return False
def ttl_exist_lock_twitter_search():
key = "rate-limit-search"
if redis_get(key):
return redis_ttl(key)
else:
return 0
def is_refreshed(collection, character):
return r.sismember(collection, character)
def refresh_expire_set(collection, character, seconds):
if r.sismember(collection, character):
return False
else:
r.sadd(collection, character)
r.expire(collection, seconds)
return True
if __name__ == '__main__':
print r.get("test")
print r.sismember("testset", "1")
pass
<file_sep>#!/usr/bin/env python
# -*- coding:utf8 -*-
from gettext import gettext as _
class APIStatusCode(object):
OK = 200
rate_limit = 429
unknown = 500
on_twitter_search = 1001
already_refreshed = 1002
uncaught_required = 1003
class APIStatus(object):
def __init__(self, code, memo):
self.code = code
self.memo = memo
def marshal(self):
return {
'code': int(self.code),
'memo': self.memo,
}
API_STATUS_OK = APIStatus(code=APIStatusCode.OK , memo=_('API_STATUS_OK'))
API_STATUS_UNKNOWN = APIStatus(code=APIStatusCode.unknown, memo=_('API_STATUS_UNKNOWN'))
API_STATUS_RATE_LIMIT = APIStatus(code=APIStatusCode.rate_limit, memo=_('API_STATUS_RATE_LIMIT'))
API_STATUS_ON_TWITTER_SEARCH = APIStatus(code=APIStatusCode.on_twitter_search, memo=_('API_STATUS_ON_TWITTER_SEARCH'))
API_STATUS_ALREADY_REFRESHED = APIStatus(code=APIStatusCode.already_refreshed, memo=_('API_STATUS_ALREADY_REFRESHED'))
API_STATUS_UNCAUGHT_REQUIRED = APIStatus(code=APIStatusCode.uncaught_required, memo=_('API_STATUS_UNCAUGHT_REQUIRED'))
<file_sep>#!/usr/bin/env python
# -*- coding:utf8 -*-
from app import app
app.run(debug=True, port=5000)
<file_sep>#!/usr/bin/env python
# -*- coding:utf8 -*-
import os
import datetime
from flask import Flask, request
from blueprint import APIBlueprint
from constants import API_STATUS_OK, API_STATUS_UNKNOWN, API_STATUS_RATE_LIMIT, API_STATUS_ON_TWITTER_SEARCH, API_STATUS_ALREADY_REFRESHED, API_STATUS_UNCAUGHT_REQUIRED
from TwitterSearch import TwitterSearchException
from keen_support import Keen
from tweet_support import TweetSearchSupport
import redis_support
import charcollection
api_bp = APIBlueprint('api', __name__, url_prefix='/api')
@api_bp.route('/get_twit', methods=['GET'])
def get_twit():
target_character_number = int(request.args.get("character"))
target_collection_number = int(request.args.get("collection"))
if target_collection_number is None or target_character_number is None:
return api_bp.make_response(status=API_STATUS_UNCAUGHT_REQUIRED, result={"result" : False})
if redis_support.exist_lock_twitter_search():
# On Twitter search caused rate limit
return api_bp.make_response(status=API_STATUS_RATE_LIMIT, result = {"result" : False, "ttl" : redis_support.ttl_exist_lock_twitter_search()})
try:
today = datetime.datetime.now().date()
tss = TweetSearchSupport()
ts = tss.get_ts()
keen = Keen()
character = charcollection.get_character(target_collection_number, target_character_number)
if character == False:
return api_bp.make_response(status=API_STATUS_UNCAUGHT_REQUIRED, result = {"result" : False})
collection = charcollection.get_collection(target_collection_number)
if collection == False:
return api_bp.make_response(status=API_STATUS_UNCAUGHT_REQUIRED, result = {"result" : False})
tso = tss.generate_tso([character.encode('UTF-8')], today)
count_dict = dict()
amount = 0
for tweet in ts.search_tweets_iterable(tso):
tweet_create_date = tss.to_datetime(tweet['created_at']).date()
timestamp = tweet_create_date.strftime("%Y-%m-%dT03:00:00.000Z")
if not count_dict.has_key(timestamp):
count_dict[timestamp] = 1
else:
count_dict[timestamp] += 1
seconds = (datetime.datetime.combine( datetime.datetime.now().date()
+ datetime.timedelta(days=1), datetime.datetime.min.time()) - datetime.datetime.now()).seconds
redis_support.refresh_expire_set(collection, target_character_number, seconds)
keen.add_girl(collection, character, count_dict)
return api_bp.make_response(status=API_STATUS_OK, result={ "result" : True })
except TwitterSearchException as e:
if e.code == 429:
# On Twitter search caused rate limit
redis_support.expire_lock_twitter_search()
return api_bp.make_response(status=API_STATUS_RATE_LIMIT, result={"result" : False, "ttl" : redis_support.ttl_exist_lock_twitter_search()})
else:
print e
return api_bp.make_response(status=API_STATUS_UNKNOWN, result=dict())
@api_bp.route('/add_event', methods=['GET'])
def add_event():
redis_support.redis_set("test", False)
print redis_support.redis_get("test")
return api_bp.make_response(status=API_STATUS_OK, result={"result" : redis_support.redis_get("test")})
@api_bp.route('/test_twitter', methods=['GET'])
def test_event():
try:
tss = TweetSearchSupport()
ts = tss.get_ts()
today = datetime.datetime.now().date()
tso = tss.generate_tso([u"๋ฏธ์ค".encode("UTF-8")],today, True)
count = 0
for tweet in ts.search_tweets_iterable(tso):
tweet_text = ('%s @%s tweeted: %s' % (tweet['created_at'], tweet['user']['screen_name'], tweet['text']))
print tweet_text
count += 1
return api_bp.make_response(status=API_STATUS_OK, result = {"result" : True , "count" : count})
except TwitterSearchException as e:
print e
return api_bp.make_response(status=API_STATUS_UNKNOWN, result=dict())
@api_bp.route('/test_user_tweet', methods=['GET'])
def test_user_tweet():
from twkorean import TwitterKoreanProcessor
from util import PrintString
ps = PrintString()
try:
tss = TweetSearchSupport()
ts = tss.get_ts()
today = datetime.datetime.now().date()
tso = tss.generate_user_order("Twins", today)
count = 0
foreign_tweet_counter = 0
hash_tags = set()
processor = TwitterKoreanProcessor()
for tweet in ts.search_tweets_iterable(tso):
tweet_text = ('%s @%s tweeted: %s' % (tweet['created_at'], tweet['user']['screen_name'], tweet['text']))
print tweet_text
tokens = processor.tokenize(tweet['text'])
new_tokens = []
for token in tokens:
foreign_flag = False
if token.pos == 'Foreign':
if not foreign_flag:
foreign_tweet_counter += 1
foreign_flag = True
elif token.pos == 'Hashtag':
hash_tags.add(token.text.encode('utf-8'))
new_tokens.append((token.text.encode('utf-8'), token.pos))
ps.print_tokens(new_tokens)
count += 1
print hash_tags
return api_bp.make_response(status=API_STATUS_OK, result = {"result" : True , "count" : count, "foreign_count" : foreign_tweet_counter, "used_hashtags" : list(hash_tags)})
except TwitterSearchException as e:
print e
return api_bp.make_response(status=API_STATUS_UNKNOWN, result=dict())
<file_sep>#!/usr/bin/env python
# -*- coding:utf8 -*-
from keen.client import KeenClient
keen_client = KeenClient(
project_id="55f93f85d2eaaa05a699de39",
write_key="8f77f837b629b8519e8d23c541fedc42d423f8f71dc10e2244b50e364e7034cb753d960ea31d7925d044a109233cdf55e88792d4fa9f16f4e2410a7e09309242565415ef3d7299526c2fbf6860603bd349d186f068f5bd940ff047c2f4a4f0959c1cda4c3c3208729524b233b096e4de",
read_key="<KEY>",
master_key="3855C83BD7B0720323E0B1E447149B01")
class Keen(object):
keen = None
def __init__(self):
self.keen = keen_client
def add_girl(self, collection, name, count_dict, **kwargs):
data_array = list()
for i in count_dict.keys():
if self.is_exist_girl(collection, name, i):
pass
else:
data_dict = dict()
data_dict["์บ๋ฆญํฐ"] = name
data_dict["keen"] = dict()
data_dict["count"] = count_dict[i]
data_dict["keen"]["timestamp"] = i
data_array.append(data_dict)
self.keen.add_events({
collection : data_array})
return True
def is_exist_girl(self, collection, name, timestamp, **kwargs):
return self.keen.count(collection, filters=[{"property_name" : "keen.timestamp", "operator" : 'eq', "property_value" : timestamp}, {"property_name" : "์บ๋ฆญํฐ", "operator" : 'eq', "property_value" : name}]) != 0
def test_function(self, **kwargs):
self.keen.add_events({
"test_cases" : [
{"user_name" : "nameuser4",
"keen" : {
"timestamp" : "2015-09-14T02:09:10.141Z"
},
"count" : 7
},
{"user_name" : "nameuser5",
"keen" : {
"timestamp" : "2015-09-14T02:09:10.141Z"
},
"count" : 4}]
})
return self.keen.count("test_cases", timeframe="this_14_days")
if __name__ == '__main__':
keen_client.add_events({
'test_cases' : [
{"user_name" : u"<NAME>",
"count" : 4}]})
<file_sep>Flask==0.10.1
gunicorn==19.3.0
itsdangerous==0.24
Jinja2==2.8
JPype1==0.6.1
keen==0.3.17
MarkupSafe==0.23
nltk==3.0.5
oauthlib==1.0.3
Padding==0.4
pycrypto==2.6.1
redis==2.10.3
requests==2.7.0
requests-oauthlib==0.5.0
six==1.9.0
TwitterSearch==1.0.1
twkorean==0.1.5
Werkzeug==0.10.4
wheel==0.24.0
<file_sep>#!/usr/bin/env python
# -*- coding:utf8 -*-
collections = ['cindemas']
cinde_characters = [u"์๋ถ์ผ ๋ฆฐ", u"ํผ๋ค ๋ฏธ์ค", u"์๋ง๋ฌด๋ผ ์ฐ์ฆํค", u"ํํ๋ฐ ์์ฆ", u"ํ์นด๊ฐํค ์นด์๋ฐ", u"์ฃ ๊ฐ์ฌํค ๋ฆฌ์นด", u"๋ฏธ๋ฌด๋ผ ์นด๋์ฝ", u"์นธ์ํค ๋์ฝ", u"๋ชจ๋ก๋ณด์ ํค๋ผ๋ฆฌ", u"๋ง์์นด์ ๋ฏธ์ฟ ", u"ํ๋ค ๋ฆฌ์๋", u"์ฃ ๊ฐ์ฌํค ๋ฏธ์นด", u"์ฝํ๋ํ ๋ฏธํธ", u"์นด์์๋ง ๋ฏธ์ฆํค", u"ํ ํ ํค ์์ด๋ฆฌ", u"์๋ฒ ๋๋", u"๋ํ ๋ฏธ๋๋ฏธ", u"ํ๋
ธ ์์นด๋ค", u"์ฝ์๋ฏธ์ฆ ์ฌ์น์ฝ", u"์๋ผ์ฌ์นด ์ฝ์ฐ๋ฉ", u"์์นด๊ธฐ ๋ฏธ๋ฆฌ์", u"์ฌ์ฟ ๋ง ๋ง์ ", u"์๋์คํ์ค", u"ํ์นด๋ชจ๋ฆฌ ์์ด์ฝ", u"์ค๊ฐํ ์น์๋ฆฌ", u"์นด๋ฏธ์ผ ๋์ค", u"ํธ์ ์ผ์ฝ", u"์ฝ๋ฐ์ผ์นด์ ์ฌ์", u"ํธ์ฃ ์นด๋ ", u"ํธ๋ฆฌ ์ ์ฝ", u"๋ฏธ์ผ๋ชจํ ํ๋ ๋ฐ๋ฆฌ์นด", u"์ฌ๊ฐ์ฌ์ ํ๋ฏธ์นด", u"ํ๋ฉ์นด์ ์ ํค", u"์ด์น๋
ธ์ธ ์ํค", u"ํ์ผ๋ฏธ ์นด๋๋ฐ", u"์ด์นํ๋ผ ๋๋", u"์ฌ์ฟ ๋ผ์ด ๋ชจ๋ชจ์นด", u"ํ์น๋ฐ๋ ์๋ฆฌ์ค", u"์นดํ๊ธฐ๋ฆฌ ์ฌ๋์", u"์์ค๋ฏธ ์์ฝ", u"์์ด๋ฐ ์ ๋ฏธ", u"๋ฌด์นด์ด ํ์ฟ ๋ฏธ"]
storage = list()
storage.append(cinde_characters)
def get_character(collection_number, character_number):
if collection_number >= len(collections):
return False
character_list = storage[collection_number]
if character_number >= len(character_list):
return False
return character_list[character_number]
def get_collection(collection_number):
return collections[collection_number]
if __name__ == "__main__":
print get_character(0, 1)
print get_character(1, 0)
print get_character(0, 45)
print get_collection(0)
<file_sep>#!/usr/bin/env python
# -*- coding:utf8 -*-
from TwitterSearch import *
import datetime
from email.utils import parsedate_tz
class MyTwitterSearchOrder(TwitterSearchOrder):
def set_since(self, date):
""" Sets 'since' parameter used to return \
only tweets generated after the given date
:param date : A datetime instance
:raises: TwitterSearchException
"""
if isinstance(date, datetime.date) and date <= datetime.date.today():
self.arguments.update({'since': '%s' % date.strftime('%Y-%m-%d')})
else:
raise TwitterSearchException(1007)
class TweetSearchSupport(object):
ts = None
def __init__(self):
self.ts = TwitterSearch(
consumer_key= 'Eu0zKf7WjndxhjGdNNbMIjnlz',
consumer_secret = '<KEY>',
access_token_key = '<KEY>',
access_token_secret='<KEY>')
def get_ts(self):
return self.ts
def generate_tso(self, name_list, start_date, or_operator=False):
""" name_list : ํธ์ํฐ ๊ฒ์์ ์ฌ์ฉํ ๊ฒ์์ด๋ค์ ๋ฆฌ์คํธ
start_date : ํธ์ํฐ ๊ฒ์์ด ๋๋๋ ๋ ์ง (GMT 0000 ๊ธฐ์ค)
or_operator : ๊ฒ์์ด ๋ฆฌ์คํธ๋ฅผ or๋ก ์ฎ์๊ฑด์ง ์ ๋ฌด
"""
tso = MyTwitterSearchOrder()
# tso = TwitterUserOrder('lys2419') # create a TwitterUserOrder to access specific user timeline
# for tweet in ts.search_tweets_iterable(tso):
# tweet_text = ('%s @%s tweeted: %s' % (tweet['created_at'], tweet['user']['screen_name'], tweet['text']))
# print tweet_text
tso.set_keywords(name_list, or_operator=or_operator)
# tso.set_language('jp')
tso.set_include_entities(False)
tso.set_since(start_date - datetime.timedelta(days=8))
tso.set_until(start_date - datetime.timedelta(days=1))
return tso
def generate_user_order(self, user_id, start_date, or_operator=False):
""" user_id : ํธ์ํฐ ๊ฒ์์ ํ๊ฒ ID
start_date : ํธ์ํฐ ๊ฒ์์ด ๋๋๋ ๋ ์ง (GMT 0000 ๊ธฐ์ค)
or_operator : ๊ฒ์์ด ๋ฆฌ์คํธ๋ฅผ or๋ก ์ฎ์๊ฑด์ง ์ ๋ฌด
"""
tso = TwitterUserOrder(user_id)
tso.set_include_entities(False)
return tso
def to_datetime(self, datestring):
""" referenced
http://stackoverflow.com/questions/7703865/going-from-twitter-date-to-python-datetime-date
"""
time_tuple = parsedate_tz(datestring.strip())
dt = datetime.datetime(*time_tuple[:6])
return dt - datetime.timedelta(seconds=time_tuple[-1])
if __name__ == '__main__':
import charcollection
character = charcollection.cinde_characters[0]
tss = TweetSearchSupport()
today = datetime.datetime.now().date()
tso = tss.generate_tso(character.encode('UTF-8'), today)
ts = tss.get_ts()
for tweet in ts.search_tweets_iterable(tso):
tweet_text = ('%s @%s tweeted: %s' % (tweet['created_at'], tweet['user']['screen_name'], tweet['text']))
print tweet_text
| bbb078a05d991e43a2f27f921c2414707b8fe9f9 | [
"JavaScript",
"Python",
"Text"
] | 13 | JavaScript | widian/deremasu-ranking | 50f4a196639abce590781b411bc56e620157e798 | c338543f7dcd7b5a3f64ea00862d85e98011de8d |
refs/heads/main | <repo_name>zhaolinzhang/mySpider<file_sep>/mySpider/pipelines.py
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import os
import csv
class MyspiderPipeline:
def __init__(self):
# csvๆไปถ็ไฝ็ฝฎ,ๆ ้ไบๅ
ๅๅปบ
store_file = os.path.dirname(__file__) + '/spiders/tieba.csv'
# ๆๅผ(ๅๅปบ)ๆไปถ
self.file = open(store_file, 'a+', encoding="utf-8", newline='')
# csvๅๆณ
self.writer = csv.writer(self.file, dialect="excel")
def process_item(self, item, spider):
if item['content']:
self.writer.writerow([item['url'], item['content'], item['timestamp']])
return item
def close_spider(self, spider):
self.file.close()<file_sep>/mySpider/spiders/tieba.py
import re
import json
import time
import scrapy
from . import helper
from scrapy.http import Request
from mySpider.items import MyspiderItem
class Myspider(scrapy.Spider):
name = 'tieba'
allowed_domains = ['baidu.com']
# baseurl_to_pages = {'https://tieba.baidu.com/f/search/res?isnew=1&kw=%D2%BB%C4%A8%D7%D4%B2%D0%B5%C4%D0%A6&qw=%D7%D4%B2%D0&un=&rn=10&sd=&ed=&sm=1&only_thread=1': 5,
# 'https://tieba.baidu.com/f/search/res?isnew=1&kw=%B2%D0%B7%C7%B2%A1&qw=%D7%D4%B2%D0&un=&rn=10&sd=&ed=&sm=1&only_thread=1': 1,
# 'https://tieba.baidu.com/f/search/res?isnew=1&kw=%D1%AA&qw=%D7%D4%B2%D0&un=&rn=10&sd=&ed=&sm=1&only_thread=1': 6,
# 'https://tieba.baidu.com/f/search/res?isnew=1&kw=%D2%D6%D3%F4&qw=%D7%D4%B2%D0&un=&rn=10&sd=&ed=&sm=1&only_thread=1': 20,
# 'https://tieba.baidu.com/f/search/res?isnew=1&kw=%D2%D6%D3%F4%D6%A2&qw=%D7%D4%B2%D0&un=&rn=10&sd=&ed=&sm=1&only_thread=1': 76,
# 'https://tieba.baidu.com/f/search/res?isnew=1&kw=%BE%AB%C9%F1%B2%A1&qw=%D7%D4%B2%D0&un=&rn=10&sd=&ed=&sm=1&only_thread=1': 3,
# 'https://tieba.baidu.com/f/search/res?isnew=1&kw=%D0%C4%C0%ED%D1%A7&qw=%D7%D4%B2%D0&un=&rn=10&sd=&ed=&sm=1&only_thread=1': 15,
# 'https://tieba.baidu.com/f/search/res?isnew=1&kw=%CB%AB%CF%E0%C7%E9%B8%D0%D5%CF%B0%AD&qw=%D7%D4%B2%D0&un=&rn=10&sd=&ed=&sm=1&only_thread=1': 1,
# 'https://tieba.baidu.com/f/search/res?isnew=1&kw=%C9%A5&qw=%D7%D4%B2%D0&un=&rn=10&sd=&ed=&sm=1&only_thread=1': 7}
baseurl_to_pages = {"https://tieba.baidu.com/f/search/res?isnew=1&kw=&qw=%D7%D4%B2%D0&rn=10&un=&only_thread=1&sm=1&sd=&ed=": 76,
"https://tieba.baidu.com/f/search/res?isnew=1&kw=&qw=%D7%D4%CE%D2%C9%CB%BA%A6&rn=10&un=&only_thread=1&sm=1&sd=&ed=": 38}
currenturl = ''
def start_requests(self):
for baseurl, pages in self.baseurl_to_pages.items():
for i in range (pages):
url = baseurl + "&pn=" + str(i+1)
time.sleep(1)
yield Request(url, self.parse)
def parse(self, response):
sel = scrapy.Selector(response)
posts = sel.xpath('//div[@class="s_post"]')
for post in posts:
link = post.xpath('./span/a/@href').extract_first()
self.currenturl = "https://tieba.baidu.com" + link
time.sleep(1)
yield Request(self.currenturl, self.detail_page_parse)
def detail_page_parse(self, response):
meta = response.meta
print("metadata: [" + str(meta) + "]")
for floor in response.xpath("//div[contains(@class, 'l_post')]"):
if not helper.is_ad(floor):
data = json.loads(floor.xpath("@data-field").extract_first())
print("data: [" + str(data) + "]")
item = MyspiderItem()
item['url'] = self.currenturl
content = floor.xpath(".//div[contains(@class,'j_d_post_content')]/text()").extract_first()
print("content: [" + str(helper.strip_blank(content)) + "]")
item['content'] = helper.strip_blank(content)
if 'date' in data['content'].keys():
timestamp = data['content']['date']
else:
timestamp = floor.xpath(".//span[@class='tail-info']")\
.re_first(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}')
print("timestamp: [" + str(timestamp) + "]")
item['timestamp'] = timestamp
yield item
time.sleep(1)<file_sep>/mySpider/spiders/helper.py
import re
def is_ad(s): #ๅคๆญๆฅผๅฑๆฏๅฆไธบๅนฟๅ
ad = s.xpath(u".//span[contains(text(), 'ๅนฟๅ')]")
# ๅนฟๅๆฅผๅฑไธญ้ดๆไธชspanๅซๆๅนฟๅไฟฉๅญ
return ad
def strip_blank(s): #ๆไธชไบบๅๅฅฝๅปๆ็ฉบ็ฝๅญ็ฌฆ
s = re.sub(r'\n[ \t]+\n', '\n', s)
s = re.sub(r' +', ' ', s) #ๅปๆๅคไฝ็็ฉบๆ ผ
s = re.sub(r'\n\n\n+', '\n\n', s) #ๅปๆ่ฟๅค็่ฟ็ปญๆข่ก
return s.strip() | 5e717889e9f0880f93057ff8c365f95ce7f7e553 | [
"Python"
] | 3 | Python | zhaolinzhang/mySpider | cdfa00848be9c7694eeb2d0b38dcadbc4655e146 | 347d4c4667312d21ae6524f4f2279f63f4dd8217 |
refs/heads/master | <repo_name>Starwaster/RealActiveRadiators<file_sep>/ModuleRealActiveRadiator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using KSP;
using KSP.Localization;
using Radiators;
namespace RealActiveRadiator
{
public class ModuleRealActiveRadiator : ModuleActiveRadiator
{
[KSPField()]
public FloatCurve cryoCoolerEfficiency;
[KSPField]
public double maxCryoEnergyTransfer = 500.0;
[KSPField]
public double maxCryoElectricCost = 10;
[KSPField]
public double cryoEnergyTransferScale = 1;
[KSPField]
protected bool cooledByOtherRadiators = false;
//[KSPField]
//protected double coolTemperatureThreshold = 297.6;
protected static string cacheAutoLOC_232071;
protected static string cacheAutoLOC_232067;
protected static string cacheAutoLOC_232036;
[KSPField(guiName = "AR:RefrCost", guiActive = false)]
public string D_RefrCost = "???";
protected int electricResourceIndex = -1;
protected int ECID = -1;
protected double baseElectricRate = 0;
protected double refrigerationThrottle = 1;
protected BaseField Dfld_RefrCost;
protected List<Part> compensatedParts = new List<Part> ();
public ModuleRealActiveRadiator () : base()
{
}
internal static void CacheLocalStrings()
{
ModuleRealActiveRadiator.cacheAutoLOC_232036 = Localizer.Format("#autoLOC_232036");
ModuleRealActiveRadiator.cacheAutoLOC_232067 = Localizer.Format("#autoLOC_232067");
ModuleRealActiveRadiator.cacheAutoLOC_232071 = Localizer.Format("#autoLOC_232071");
}
public override void OnAwake()
{
base.OnAwake();
electricResourceIndex = this.resHandler.inputResources.FindIndex(x => x.name == "ElectricCharge");
if (electricResourceIndex >= 0)
{
baseElectricRate = this.resHandler.inputResources[electricResourceIndex].rate;
ECID = this.resHandler.inputResources[electricResourceIndex].id;
}
if (cryoCoolerEfficiency == null)
cryoCoolerEfficiency = new FloatCurve();
if (cryoCoolerEfficiency.Curve.keys.Length == 0)
cryoCoolerEfficiency.Add(0f, 0.7f);
}
public override void OnStart(StartState state)
{
base.OnStart (state);
this.Dfld_RefrCost = base.Fields ["D_RefrCost"];
}
public new void FixedUpdate()
{
base.FixedUpdate();
if (this.Dfld_RefrCost != null)
this.Dfld_RefrCost.guiActive = PhysicsGlobals.ThermalDataDisplay;
}
public override string GetInfo()
{
StringBuilder stringBuilder = new StringBuilder();
if (this.resHandler.inputResources.Count > 0)
{
stringBuilder.Append(this.resHandler.PrintModuleResources(1.0));
}
stringBuilder.Append("\n<b><color=#99ff00ff>" + ModuleRealActiveRadiator.cacheAutoLOC_232036 + "</color></b>\n");
double num = this.maxEnergyTransfer;
stringBuilder.AppendFormat(Localizer.Format("#autoLOC_232038", new object[] {
num
}), new object[0]);
double num2 = 0.0;
int count = base.part.DragCubes.Cubes.Count;
while (count-- > 0)
{
DragCube dragCube = base.part.DragCubes.Cubes[count];
double num3 = (double)(dragCube.Area[0] + dragCube.Area[1] + dragCube.Area[2] + dragCube.Area[3] + dragCube.Area[4] + dragCube.Area[5]);
if (num3 > num2)
{
num2 = num3;
}
}
if (num2 != 0.0)
{
double num4 = base.part.skinMaxTemp * base.part.radiatorHeadroom;
num4 *= num4;
num4 *= num4;
stringBuilder.Append(Localizer.Format("#autoLOC_232057", new string[] {
(num2 * base.part.emissiveConstant * num4 * PhysicsGlobals.StefanBoltzmanConstant * 0.001).ToString ("F0")
}));
}
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.AppendFormat("{0:0.00}", this.energyTransferScale * 100.0);
stringBuilder.Append(Localizer.Format("#autoLOC_232060", new string[] {
stringBuilder2.ToString ()
}));
{
stringBuilder.Append(ModuleRealActiveRadiator.cacheAutoLOC_232067);
}
if (this.parentCoolingOnly)
{
stringBuilder.Append(ModuleRealActiveRadiator.cacheAutoLOC_232071);
}
if (maxCryoElectricCost > 0)
{
stringBuilder.Append("\n<b><color=#99ff00ff>Max Cryogenic Cooling</color></b>\n");
stringBuilder.Append(" <b><color=#00C3FFff>@20K = " + (CoolingEfficiency(20, 300) * maxCryoElectricCost).ToString("F2") + "kW" + "</color>\n");
stringBuilder.Append(" <b><color=#00C3FFff>@90K = " + (CoolingEfficiency(90, 300) * maxCryoElectricCost).ToString("F2") + "kW" + "</color>\n");
}
else
{
stringBuilder.Append("No cryogenic cooling capacity.\n");
}
return stringBuilder.ToString();
}
protected override void CheckPartCaches()
{
if (!this.partCachesDirty)
{
return;
}
this.activeRadiatorParts.Clear();
this.nonRadiatorParts.Clear();
this.compensatedParts.Clear();
int count = base.vessel.parts.Count;
ModuleActiveRadiator radPart;
while (count-- > 0)
{
Part part = base.vessel.parts[count];
if (radPart = part.FindModuleImplementing<ModuleActiveRadiator>())
{
// There can be other mods that inherit from ModuleActiveRadiator type.
// Need to ensure that the found part is actually a RealActiveRadiator.
if (radPart is ModuleRealActiveRadiator && !((ModuleRealActiveRadiator)radPart).cooledByOtherRadiators)
this.activeRadiatorParts.Add(part);
}
else
{
this.nonRadiatorParts.Add(part);
if (part.Modules.Contains("ModuleFuelTanks"))
{
this.compensatedParts.Add(part);
}
}
}
this.partCachesDirty = false;
}
//<summary>
// Returns the cooling efficiency taking into account both Carnot and efficiency % of Carnot of the cooler.
// This ONLY is valid for conditions where refrigeration is happening. Otherwise stock radiator conditions apply.
//</summary>
public double CoolingEfficiency(double coolingTemp, double hotTemp)
{
return Math.Max(coolingTemp / (hotTemp - coolingTemp) * cryoCoolerEfficiency.Evaluate((float)coolingTemp), 0);
}
protected override void InternalCooling(RadiatorData thisRadiator, int radCount)
{
if (!base.vessel.IsFirstFrame())
{
// TODO hard coding this for ElectricCharge but I may do something like this for all resource inputs IF there are likely to be other resource inputs
// and IF those other inputs are likely to need scaling...
double coolingEfficiency = 1;
double refrigerationCost = 0;
if (this.Dfld_RadCount.guiActive)
{
this.D_RadCount = radCount.ToString();
}
this.coolParts.Clear();
this.hotParts.Clear();
int count = this.nonRadiatorParts.Count;
while (count-- > 0)
{
Part part = this.nonRadiatorParts[count];
if (part.temperature > part.maxTemp * part.radiatorMax)
{
this.hotParts.Add(part);
}
}
int count2 = this.hotParts.Count;
for (int i = 0; i < count2; i++)
{
Part part2 = this.hotParts[i];
bool flag = true;
if (this.parentCoolingOnly)
{
flag = this.IsSibling(part2);
}
if (flag)
{
RadiatorData thermalData = RadiatorUtilities.GetThermalData(part2);
double energyDifference = thermalData.Energy - thermalData.MaxEnergy;
if (energyDifference > 0.0)
{
this.coolParts.Add(thermalData);
}
}
}
int cooledParts = this.coolParts.Count;
// Would have liked to do this part as coolParts was being built so the list doesn't have to be walked through twice
// but I don't know the amount of flux until after it's done being built - so if I want to throttle refrigeration I have to do this.
for (int i = 0; i < cooledParts; i++)
{
if (coolParts[i].Part.temperature < base.part.temperature)
{
RadiatorData partThermalData = this.coolParts[i];
coolingEfficiency = CoolingEfficiency(coolParts[i].Part.temperature, base.part.temperature);
double _maxCryoEnergyTransfer = maxCryoElectricCost * coolingEfficiency;
double excessHeat = (partThermalData.Energy - partThermalData.MaxEnergy);
excessHeat /= (double)(radCount + cooledParts);
double val = Math.Min(Math.Max(0, thisRadiator.EnergyCap - thisRadiator.Energy), _maxCryoEnergyTransfer);
double liftedHeatFlux = Math.Min(val, excessHeat) * Math.Min(1.0, cryoEnergyTransferScale) * refrigerationThrottle;
refrigerationCost += Math.Min(maxCryoElectricCost, liftedHeatFlux / coolingEfficiency);
}
}
for (int i = 0; i < this.compensatedParts.Count; i++)
{
Part part = compensatedParts[i];
if (!(part.temperature < part.maxTemp * part.radiatorMax))
{
double conductionFlux = part.thermalConductionFlux + part.skinToInternalFlux;
if (conductionFlux > 0 && part.temperature < base.part.temperature)
{
coolingEfficiency = CoolingEfficiency(part.temperature, base.part.temperature);
conductionFlux = Math.Min(conductionFlux, maxCryoElectricCost * coolingEfficiency);
conductionFlux *= refrigerationThrottle;
refrigerationCost += conductionFlux / coolingEfficiency;
}
}
}
if (electricResourceIndex >= 0)
{
this.resHandler.inputResources[electricResourceIndex].rate = baseElectricRate + refrigerationCost;
//double powerAvailability = this.resHandler.UpdateModuleResourceInputs(ref this.status, radCount, 0.9, false, false, true);
double ECAmount, ECMaxAmount;
this.part.GetConnectedResourceTotals(ECID, PartResourceLibrary.GetDefaultFlowMode(ECID), out ECAmount, out ECMaxAmount, true);
// if the craft has mixed radiator types then availability calculation may be wrong
double powerAvailability = ECAmount / ((refrigerationCost * radCount) + 0.1);
if (powerAvailability < 1.0)
{
// Looks like radiator count can include inactive radiators so this could throttle cooling down more than intended.
refrigerationThrottle = powerAvailability * 0.75 / radCount;
refrigerationCost *= refrigerationThrottle;
this.resHandler.inputResources[electricResourceIndex].rate = baseElectricRate + (refrigerationCost);
}
else if (refrigerationThrottle < 1.0)
{
// Try to increase the throttle if power reserves have increased to more than 10x what would be required.
if (powerAvailability >= 10 * refrigerationCost)
{
refrigerationThrottle += 0.001;
refrigerationCost *= refrigerationThrottle;
this.resHandler.inputResources[electricResourceIndex].rate = baseElectricRate + (refrigerationCost);
}
}
//this.resHandler.UpdateModuleResourceInputs(ref this.status, 1, 0.9, false, false, true);
refrigerationThrottle = Math.Min(refrigerationThrottle, 1);
if (this.Dfld_RefrCost.guiActive)
this.D_RefrCost = refrigerationCost.ToString("F4") + " (throttle = " + refrigerationThrottle.ToString("P0") + ")";
}
if (this.Dfld_CoolParts.guiActive)
{
this.D_CoolParts = StringBuilderCache.Format("{0}/{1}", new object[]
{
cooledParts,
this.hotParts.Count
});
}
for (int j = 0; j < cooledParts; j++)
{
RadiatorData radiatorData = this.coolParts[j];
bool useHeatPump = radiatorData.Part.temperature < base.part.temperature;
coolingEfficiency = CoolingEfficiency(coolParts[j].Part.temperature, base.part.temperature);
double _maxCryoEnergyTransfer = maxCryoElectricCost * coolingEfficiency;
double excessHeat = (radiatorData.Energy - radiatorData.MaxEnergy);
excessHeat /= (double)(radCount + cooledParts);
double _maxEnergyTransfer = radiatorData.Part.temperature >= base.part.temperature ? this.maxEnergyTransfer : _maxCryoEnergyTransfer;
double val = Math.Min(Math.Max(0, thisRadiator.EnergyCap - thisRadiator.Energy), _maxEnergyTransfer);
double liftedHeatFlux = Math.Min(val, excessHeat);
if (this.Dfld_XferBase.guiActive)
{
this.D_XferBase = liftedHeatFlux.ToString();
}
liftedHeatFlux *= Math.Min(1.0, useHeatPump ? cryoEnergyTransferScale : this.energyTransferScale);
if (useHeatPump)
liftedHeatFlux *= refrigerationThrottle;
if (liftedHeatFlux > 0.0)
{
radiatorData.Part.AddThermalFlux(-liftedHeatFlux);
base.part.AddThermalFlux(liftedHeatFlux);
}
if (this.Dfld_Excess.guiActive)
{
this.D_Excess = excessHeat.ToString();
}
if (this.Dfld_HeadRoom.guiActive)
{
this.D_HeadRoom = val.ToString();
}
if (this.Dfld_XferFin.guiActive)
{
this.D_XferFin = liftedHeatFlux.ToString();
}
}
for (int i = 0; i < this.compensatedParts.Count; i++)
{
Part part = this.compensatedParts[i];
if (!(part.temperature < Math.Round(part.maxTemp * part.radiatorMax, 4)))
{
double conductionFlux = part.thermalConductionFlux + part.skinToInternalFlux;
if (conductionFlux > 0)
{
double compensatedFlux = Math.Min(conductionFlux, CoolingEfficiency(part.temperature, this.part.temperature) * maxCryoElectricCost) * refrigerationThrottle / radCount;
part.AddThermalFlux(-compensatedFlux);
base.part.AddThermalFlux(compensatedFlux);
}
}
}
}
}
public void print(string msg)
{
MonoBehaviour.print ("[ModuleRealActiveRadiator] " + msg);
}
}
}
<file_sep>/README.md
Realistic version of KSP stock ModuleActiveRadiator class.
Has the following features:
* Can always cool parts regardless of ambient temperature. (unlike real radiators, stock KSP radiators will not pull heat if the ambient temperature is hotter than the radiator's temperature)
* If the cooled part is colder than the radiator's temperature then an added refrigeration cost (in ElectricCharge) will be incurred.
Refrigeration cost requires that the radiator config has an ElectricCharge RESOURCE input. The actual cost is static and determined by the maxCryoElectricCost field and a maximum cooling rate will be determined based on the formula: electric cost * coolingTemp / (radiator temp - coolingTemp) * cryo cooler efficiency (for the cool temperature)
cryoCoolerEfficiency uses a FloatCurve to map the efficiency of the cryocooler over a range of temperatures and is configurable via the part cfg (or upgraded via stock upgrade nodes)
Refrigeration cost requires that the radiator config has an ElectricCharge RESOURCE. If there is not enough electricity then refrigeration will be scaled back accordingly. Normal radiator cooling will still occur as long as the configured resource inputs can be satisfied. Refrigeration efficiency is determined according to the Carnot equation which determines the ideal refrigeration cost for a given rate of cooling (or conversely, the amount of cooling for a given input of power). The equation is cold temp / (hot temp - cold temp). This is the ideal efficiency assuming 100% efficient cooling apparatus. Such perfect cooling is not possible however which is where cryoCoolerEfficiency. This is the percent of Carnot so the final equation is cold temp / (hot temp - cold temp) * cryoCoolerEfficiency.
| 1723b26260149ec2a09bc5e63275e7bf7240500c | [
"Markdown",
"C#"
] | 2 | C# | Starwaster/RealActiveRadiators | b381f00ee486980a4570dc39cd70d1ca8a28758d | 0da0a6628b6965a3e3404ab9bb36bf5db2ec0e76 |
refs/heads/master | <repo_name>NUIG-ROCSAFE/CBRNeVirtualEnvironment<file_sep>/SOPRanking/RocsafeCode/Demo-IR/search_and_rank.py
import utils
import elastic_utils
import sys
import os
import insert_records
from elasticsearch import Elasticsearch
def main():
working_dir = os.path.dirname(os.path.realpath(__file__))
es = Elasticsearch()
db_conn, _, _, index_name = utils.get_config('main.ini')
search_terms = sys.argv[1:]
if len(search_terms) == 0:
print("Error: Include search terms in script parameters e.g. headache, pulmonary...")
exit(-1)
insert_records.insert(es, index_name)
print("searching for terms: ", search_terms)
search_terms = [search_term.strip() for search_term in search_terms]
sop_rankings_dict = elastic_utils.compute_ranking(es, index_name, "text", search_terms)
elastic_utils.insert_rank(sop_rankings_dict, search_terms, db_conn)
print(sop_rankings_dict)
if __name__ == '__main__':
main()
<file_sep>/PythonCode/Routing/ExifAddition/AddExifTest.py
import unittest
class generateRoutesForUnrealUtilsTest(unittest.TestCase):<file_sep>/PythonCode/Routing/ExifAddition/ExifUtils/core.py
# -*- coding: utf-8 -*-
from ExifUtils.helpers import verify_file_exists, verify_dir_exists, copy_file, convert_png_to_jpg
#dependencies:
#exiftool https://www.sno.phy.queensu.ca/~phil/exiftool/
#
import subprocess
import os
import sys
import configparser
import datetime
import re
import pathlib
def get_exiftool_commands(tags_values: dict, image_loc:str):
if tags_values:
commands_list = ['-' + key + '=' + str(value) if value else '-' + key for key, value in tags_values.items()]
else:
commands_list = []
commands_list.append(image_loc)
return commands_list
def run_exiftool(tags_values: dict, image_loc: str):
'''Runs exiftool with the given tags=value pairs in the tags_value dict'''
commands_list = get_exiftool_commands(tags_values, image_loc)
exiftool_location = "C:/Users/13383861/Dropbox/SoftwareDevelopment/miscProjects/ExifUtils_module/bin/exiftool-10.88/exiftool.exe"
#exiftool_location = #str(pathlib.Path(os.path.dirname(os.path.abspath(__file__))).joinpath("../bin/exiftool-10.88/exiftool"))
try:
return subprocess.check_output([exiftool_location] + commands_list)
except Exception as e:
raise type(e)('Could not run exiftool with commands: {}'.format(commands_list) + str(e)).with_traceback(sys.exc_info()[2])
def write_exif_gps_data(image_loc: str, gps_lat: float, gps_long: float, gps_alt: float = 32):
'''Writes exif data to a specified jpg image'''
return run_exiftool({'GPSLongitude': gps_long, 'GPSLatitude': gps_lat,
'GPSAltitude':'"{}"'.format(gps_alt), 'GPSVersionID':'3 2 0 0','gpsaltituderef':'0',
"-n": None, "GPSLatitudeRef": 'N', "GPSLongitudeRef": "W"}, image_loc)
#subprocess.check_output(["exiftool", '-GPSLongitude={}'.format(gps_long), '-GPSLatitude={}'.format(gps_lat), '-GPSAltitude="{}"'.format(gps_alt), #'-GPSVersionID=3 2 0 0','-gpsaltituderef=0', "-n", "-GPSLatitudeRef=N", "-GPSLongitudeRef=W", image_loc])
def write_exif_comment(image_loc: str, comment = ""):
return run_exiftool({'Comment': comment}, image_loc)
#subprocess.check_output(["exiftool", 'Comment={}'.format(comment), image_loc])
def write_exif_date_original( image_loc: str,date: str):
'''Writes the date that the image was take at. date should be in the form %Y:%m:%d %H:%M:%S'''
return run_exiftool({'datetimeoriginal': date}, image_loc)
#subprocess.check_output(["exiftool", '"-datetimeoriginal={}"'.format(date), image_loc])
def write_exif_date_modified(image_loc: str,date: str):
'''Writes the date that the image was take at. date should be in the form %Y:%m:%d %H:%M:%S'''
return run_exiftool({'filemodifydate': date}, image_loc)
def write_author(image_loc, author: str):
'''Writes the date that the image was take at. date should be in the form %Y:%m:%d %H:%M:%S'''
return run_exiftool({'author': author}, image_loc)
#subprocess.check_output(["exiftool", '"-datetimeoriginal={}"'.format(date), image_loc])
def process_image(from_file_location: str, to_dir_location: str, comment: str = None, tags: "list of strings"=None, date: str = None,
gps_lat: float = None, gps_long: float = None, gps_alt: float = 32):
'''Given a raw png image and metadata about that image, copies it to a specified location
in jpg format and writes metadata to exif'''
copy_file(from_file_location, to_dir_location)
file_name = os.path.basename(from_file_location)
copied_png_location = pathlib.Path(to_dir_location).joinpath(file_name)
print("converting {} to a jpg".format(str(copied_png_location)))
jpg_location = convert_png_to_jpg(str(copied_png_location))
if gps_lat!=None and gps_long!=None and gps_alt!=None:
write_exif_gps_data(str(jpg_location), gps_lat, gps_long, gps_alt)
if comment != None:
write_exif_comment(str(jpg_location),comment)
if date != None:
write_exif_date_original(str(jpg_location), str(date))
def get_exif_data(image_loc: str) -> bytes:
return run_exiftool({}, image_loc)
def get_exif_data_json(image_loc: str):
return {item.split(':')[0].strip():item.split(':')[1].strip() for item in filter(lambda item: item, run_exiftool({}, image_loc).decode().split('\n'))}
<file_sep>/RCode/requirements.R
install.packages("shiny")
install.packages("readtext")
install.packages("stringr")
install.packages("DT")
install.packages("shinycssloaders")
install.packages("shinydashboard")
install.packages("shinyWidgets")
install.packages("leaflet")
install.packages("ggmap")
install.packages("ini")
install.packages("shinyalert")<file_sep>/SOPRanking/RocsafeCode/Demo-IR/sop_server.py
import sqlite3
import utils
from flask import Flask
from flask import make_response
app = Flask(__name__)
def return_link(title, pdf_loc):
link_text = "View " + title + " PDF"
print(title)
link_location = "\'http://127.0.0.1:5000/%s\'" % (pdf_loc + title)
link = "<a href=" + link_location + " target=\"_blank\">%s</a>" % link_text
return link
def return_rank(db_loc, pdf_loc):
conn = sqlite3.connect(db_loc)
cur = conn.cursor()
sql = '''SELECT SOP.Title, rank.rank, rank.date, rank.SearchTerms from rank,SOP where rank.sopid = SOP.id
and date in (select max(date) FROM Rank) order by rank.rank desc'''
cur.execute(sql)
rows = cur.fetchall()
print(rows)
doc = "<html> \n"
doc += "<head> <title> SOP Ranking </title> \n "
# doc+= "<script type=\'text/javascript\'>"
# doc+="function sleep(delay) { \n"
# doc+="var start = new Date().getTime(); \n"
# doc+="while (new Date().getTime() < start + delay); \n"
# doc+=" } \n"
# doc+=" </script> \n"
doc += " <style> \n"
doc += " table { \n"
doc += " border-collapse: collapse; \n"
doc += " width: 100%; \n"
doc += " } \n"
doc += "th, td { \n"
doc += " text-align: left; \n"
doc += " padding: 8px; \ncolor: #00075f;\n"
doc += " } \n"
doc += " tr:nth-child(even) {background: #ffffff} \n"
doc += " tr:nth-child(odd) {background: #d9eff9} \n"
doc += " th { \n"
doc += " background: #3c8dbc; \n"
doc += " color: white; \n"
doc += " } \n"
doc += " </style> \n"
# doc+=" </head> \n"
# onload='sleep(50000); location.reload();')
doc += "</head> \n"
doc += "<body> <table> \n"
doc += "<tr>\n <th> Standard Operating Procedure Title</th>\n <th> Score </th>\n <th> Search Terms </th>\n " \
"<th> Date Computed </th>\n <th> Link </th>\n </tr>\n"
for row in rows:
link = return_link(row[0], pdf_loc)
doc += "<tr>\n"
doc = "%s\n<td>%s</td>\n<td>%s</td>\n<td>%s</td>\n<td>%s</td>\n<td>%s</td>" % (
doc, row[0], row[1], row[3], row[2], link)
doc += "</tr>\n"
doc += "</table> "
# doc+=" <Button onclick='location.reload()'> Refresh </Button> "
doc += " </body> </html> "
return doc
@app.route('/')
def return_sops():
db_conn, _, pdf_loc, _ = utils.get_config('main.ini')
return return_rank(db_conn, pdf_loc)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def print_text(path):
if "attack" not in path:
return ""
file_location = "%s.pdf" % path
pdf_file = open(file_location, "rb")
binary_pdf = pdf_file .read()
pdf_file.close()
response = make_response(binary_pdf)
response.headers['Content-Type'] = 'application/pdf'
response.headers['Content-Disposition'] = \
'inline; filename=%s.pdf' % 'path'
return response
def main():
# runs in port 5000 by default
app.run()
if __name__ == '__main__':
main()
<file_sep>/SOPRanking/RocsafeCode/Demo-IR/insert_records.py
import os
from elasticsearch import RequestError
def insert_sop(es, index_name, title, text, idno):
doc = {
'title': title,
'text': text
}
es.index(index=index_name, doc_type='sop', id=idno, body=doc)
def insert(es, index_name):
# insert SOP into
location = os.path.dirname(os.path.realpath(__file__)) + "/text/"
try:
es.indices.create(index=index_name)
except RequestError:
print("Index %s exists, continuing" % index_name)
for counter, title in enumerate(os.listdir(location)):
file_loc = "%s%s" % (location, title)
print("Reading file: " + file_loc)
text = open(file_loc, encoding='utf-8').read()
print("Inserting SOP: " + title)
insert_sop(es, index_name, title, text, counter)
<file_sep>/PythonCode/Routing/RouteGeneration/generateUnrealCoordinatesFromGPSRunner.py
import argparse
import sys
sys.path.append('..')
sys.path.append('../..')
from generateUnrealCoordinatesFromGPS import read_GPS_coords, write_UE4_coords, GenerateUECoordsFromGPS
from GPSCoordinate import GPSCoordinate
def main(GPS_CSV: 'file path to csv containing gps coordinates', desination_UE4_coord_file = 'file to save converted UE4 coordinates', GPS_home_pos: "GPSCoordinate which records where the RAV home position is located" = GPSCoordinate(53.2793, -9.0638)):
gps_coords = read_GPS_coords(GPS_CSV)
converter = GenerateUECoordsFromGPS(GPS_home_pos)
UE4_coords = converter.convert_GPS_list_to_UE4(gps_coords)
write_UE4_coords(desination_UE4_coord_file, UE4_coords)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Automatically write the python files necessary to send the specified number of RAVs on routes given by a file containing GPS coordinates')
#metavar is a name for the argument in usage messages.
#nargs -The number of command-line arguments that should be consumed.
parser.add_argument("GPS_CSV", type = str, metavar = "GPS_CSV", help = "CSV of GPS locations for RAV to visit")
parser.add_argument("desination_UE4_coord_file", type = str, metavar = "desination_UE4_coord_file", help = "file to save converted UE4 coordinates")
parser.add_argument("GPS_home_pos_lat", type = float, metavar = "GPS_home_pos_lat", nargs = '?', help = "latitude which records where the RAV home position is located")
parser.add_argument("GPS_home_pos_lng", type = float, metavar = "GPS_home_pos_lng", nargs = '?', help = "longitude which records where the RAV home position is located")
parser.add_argument("GPS_home_pos_alt", type = float, metavar = "GPS_home_pos_alt", nargs = '?', help = "altitude which records where the RAV home position is located")
args = vars(parser.parse_args())
print(args)
if args["GPS_home_pos_lat"] and args["GPS_home_pos_lng"]:
args["GPS_home_pos"] = GPSCoordinate(args["GPS_home_pos_lat"], args["GPS_home_pos_lng"], args["GPS_home_pos_alt"])
del args["GPS_home_pos_lat"]
del args["GPS_home_pos_lng"]
del args["GPS_home_pos_alt"]
main(**args)<file_sep>/PythonCode/Routing/AirSimPythonClient/RAVExecuteRoutes/rav_one_mapper.py
import io
import time
import os
from PIL import Image
from AirSimClient import *
gpsCoordsFile = open('D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\GPSCoords\GPSCoords2.txt', 'w')
AirSimgpsCoordsFile = open('D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\GPSCoords\AirSimGPSCoords2.txt', 'w')
AirSimgpsRelativeCoordsFile = open('D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\GPSCoords\AirSimRelativeGPSCoords2.txt', 'w')
port = 41452
print('Creating new client on port: ',41452)
# connect to the AirSim simulator
client = MultirotorClient(port=41452)
print('Confirming connection...')
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
state = client.getGpsLocation()
print("state: %s" % state)
print('Taking off...')
client.takeoff()
#wait before taking off
time.sleep(0.5)
print('Moving clear of tree line')
client.moveToPosition(client.getPosition().x_val, client.getPosition().y_val, client.getPosition().z_val-25, 6)
print('Client position: {}'.format(client.getPosition()))
client.moveToGPSPosition(GPSCoordinate(53.28600000000000136424205265939235687255859375, -9.0587999999999997413624441833235323429107666015625, 18.5), 7)
time.sleep(1)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_0.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_0.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.28600000000000136424205265939235687255859375, -9.0587999999999997413624441833235323429107666015625\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807806916220017552419449202716350555419921875, -9.0627300740897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_1.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_1.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2807806916220017552419449202716350555419921875, -9.0627300740897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807806916220017552419449202716350555419921875, -9.0629625321897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_2.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_2.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2807806916220017552419449202716350555419921875, -9.0629625321897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807806916220017552419449202716350555419921875, -9.0631949902897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_3.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_3.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2807806916220017552419449202716350555419921875, -9.0631949902897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807806916220017552419449202716350555419921875, -9.0634274483897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_4.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_4.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2807806916220017552419449202716350555419921875, -9.0634274483897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807806916220017552419449202716350555419921875, -9.0636599064897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_5.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_5.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2807806916220017552419449202716350555419921875, -9.0636599064897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807806916220017552419449202716350555419921875, -9.0638923645897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_6.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_6.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2807806916220017552419449202716350555419921875, -9.0638923645897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807806916220017552419449202716350555419921875, -9.0641248226897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_7.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_7.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2807806916220017552419449202716350555419921875, -9.0641248226897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807806916220017552419449202716350555419921875, -9.0643572807897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_8.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_8.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2807806916220017552419449202716350555419921875, -9.0643572807897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807806916220017552419449202716350555419921875, -9.0645897388897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_9.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_9.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2807806916220017552419449202716350555419921875, -9.0645897388897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805526089220017552419449202716350555419921875, -9.0645897388897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_10.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_10.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2805526089220017552419449202716350555419921875, -9.0645897388897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805526089220017552419449202716350555419921875, -9.0643572807897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_11.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_11.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2805526089220017552419449202716350555419921875, -9.0643572807897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805526089220017552419449202716350555419921875, -9.0641248226897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_12.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_12.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2805526089220017552419449202716350555419921875, -9.0641248226897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805526089220017552419449202716350555419921875, -9.0638923645897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_13.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_13.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2805526089220017552419449202716350555419921875, -9.0638923645897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805526089220017552419449202716350555419921875, -9.0636599064897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_14.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_14.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2805526089220017552419449202716350555419921875, -9.0636599064897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805526089220017552419449202716350555419921875, -9.0634274483897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_15.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_15.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2805526089220017552419449202716350555419921875, -9.0634274483897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805526089220017552419449202716350555419921875, -9.0631949902897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_16.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_16.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2805526089220017552419449202716350555419921875, -9.0631949902897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805526089220017552419449202716350555419921875, -9.0629625321897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_17.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_17.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2805526089220017552419449202716350555419921875, -9.0629625321897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805526089220017552419449202716350555419921875, -9.0627300740897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_18.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_18.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2805526089220017552419449202716350555419921875, -9.0627300740897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805526089220017552419449202716350555419921875, -9.0624976159897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_19.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_19.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2805526089220017552419449202716350555419921875, -9.0624976159897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805526089220017552419449202716350555419921875, -9.0622651578897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_20.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_20.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2805526089220017552419449202716350555419921875, -9.0622651578897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803245262220017552419449202716350555419921875, -9.0622651578897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_21.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_21.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2803245262220017552419449202716350555419921875, -9.0622651578897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803245262220017552419449202716350555419921875, -9.0620326997897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_22.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_22.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2803245262220017552419449202716350555419921875, -9.0620326997897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803245262220017552419449202716350555419921875, -9.0618002416897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_23.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_23.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2803245262220017552419449202716350555419921875, -9.0618002416897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2800964435220017552419449202716350555419921875, -9.0618002416897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_24.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_24.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2800964435220017552419449202716350555419921875, -9.0618002416897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2800964435220017552419449202716350555419921875, -9.0620326997897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_25.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_25.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2800964435220017552419449202716350555419921875, -9.0620326997897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2800964435220017552419449202716350555419921875, -9.0622651578897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_26.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_26.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2800964435220017552419449202716350555419921875, -9.0622651578897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2800964435220017552419449202716350555419921875, -9.0624976159897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_27.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_27.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2800964435220017552419449202716350555419921875, -9.0624976159897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2800964435220017552419449202716350555419921875, -9.0627300740897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_28.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_28.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2800964435220017552419449202716350555419921875, -9.0627300740897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2800964435220017552419449202716350555419921875, -9.0629625321897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_29.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_29.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2800964435220017552419449202716350555419921875, -9.0629625321897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2800964435220017552419449202716350555419921875, -9.0631949902897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_30.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_30.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2800964435220017552419449202716350555419921875, -9.0631949902897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2800964435220017552419449202716350555419921875, -9.0634274483897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_31.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_31.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2800964435220017552419449202716350555419921875, -9.0634274483897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2800964435220017552419449202716350555419921875, -9.0636599064897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_32.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_32.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2800964435220017552419449202716350555419921875, -9.0636599064897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2800964435220017552419449202716350555419921875, -9.0638923645897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_33.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_33.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2800964435220017552419449202716350555419921875, -9.0638923645897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803245262220017552419449202716350555419921875, -9.0638923645897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_34.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_34.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2803245262220017552419449202716350555419921875, -9.0638923645897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803245262220017552419449202716350555419921875, -9.0636599064897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_35.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_35.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2803245262220017552419449202716350555419921875, -9.0636599064897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803245262220017552419449202716350555419921875, -9.0634274483897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_36.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_36.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2803245262220017552419449202716350555419921875, -9.0634274483897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803245262220017552419449202716350555419921875, -9.0631949902897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_37.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_37.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2803245262220017552419449202716350555419921875, -9.0631949902897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803245262220017552419449202716350555419921875, -9.0629625321897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_38.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_38.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2803245262220017552419449202716350555419921875, -9.0629625321897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803245262220017552419449202716350555419921875, -9.0627300740897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_39.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_39.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2803245262220017552419449202716350555419921875, -9.0627300740897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803245262220017552419449202716350555419921875, -9.0624976159897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_40.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_40.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2803245262220017552419449202716350555419921875, -9.0624976159897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2800964435220017552419449202716350555419921875, -9.0615677835897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_41.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_41.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2800964435220017552419449202716350555419921875, -9.0615677835897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2800964435220017552419449202716350555419921875, -9.0613353254897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_42.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_42.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2800964435220017552419449202716350555419921875, -9.0613353254897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798683608220017552419449202716350555419921875, -9.0615677835897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_43.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_43.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2798683608220017552419449202716350555419921875, -9.0615677835897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794121954220017552419449202716350555419921875, -9.0620326997897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_44.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_44.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2794121954220017552419449202716350555419921875, -9.0620326997897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794121954220017552419449202716350555419921875, -9.0622651578897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_45.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_45.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2794121954220017552419449202716350555419921875, -9.0622651578897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794121954220017552419449202716350555419921875, -9.0624976159897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_46.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_46.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2794121954220017552419449202716350555419921875, -9.0624976159897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2791841127220017552419449202716350555419921875, -9.0624976159897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_47.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_47.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2791841127220017552419449202716350555419921875, -9.0624976159897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2791841127220017552419449202716350555419921875, -9.0629625321897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_48.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_48.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2791841127220017552419449202716350555419921875, -9.0629625321897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2791841127220017552419449202716350555419921875, -9.0634274483897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_49.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_49.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2791841127220017552419449202716350555419921875, -9.0634274483897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2791841127220017552419449202716350555419921875, -9.0638923645897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_50.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_50.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2791841127220017552419449202716350555419921875, -9.0638923645897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2791841127220017552419449202716350555419921875, -9.0643572807897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_51.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_51.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2791841127220017552419449202716350555419921875, -9.0643572807897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2791841127220017552419449202716350555419921875, -9.0648221969897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_52.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_52.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2791841127220017552419449202716350555419921875, -9.0648221969897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794121954220017552419449202716350555419921875, -9.0650546550897008183386788005009293556213378906250, 18.5), 2.0)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_53.png".format('example', saved_images_dir = 'D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file("D:\IJCAI2018\IJCAIDemoCodeAll\PythonCode\PythonClientGPSMapping\GPSMappings\Images"+"\Images2\Camera{}\image_53.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2794121954220017552419449202716350555419921875, -9.0650546550897008183386788005009293556213378906250\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
gpsCoordsFile.close()
AirSimgpsCoordsFile.close()
AirSimgpsRelativeCoordsFile.close()
<file_sep>/PythonCode/Dockerfile
FROM python:3.5-alpine
COPY .
WORKDIR .
RUN pip install -r requirements.txt
CMD ["python", "", "main:app"]
<file_sep>/SOPRanking/README.md
# How to set up elastic search instance
1. Install elastic search 6.3.0 (packaged with app)
<file_sep>/PythonCode/Routing/AirSimPythonClient/RAVExecuteRoutes/rav_zero_mapper.py
import io
import time
import os
import sys
#append folder level up to import AirSimClient
sys.path.append('..')
from PIL import Image
from AirSimClient import *
gpsCoordsFile = open('D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/GPSCoords/GPSCoords1.txt', 'w')
AirSimgpsCoordsFile = open('D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/GPSCoords/AirSimGPSCoords1.txt', 'w')
AirSimgpsRelativeCoordsFile = open('D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/GPSCoords/AirSimRelativeGPSCoords1.txt', 'w')
port = 41451
print('Creating new client on port: ',41451)
# connect to the AirSim simulator
client = MultirotorClient(port=41451)
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
state = client.getGpsLocation()
print("state: %s" % state)
print('Taking off...')
client.takeoff()
print('Moving clear of tree line')
client.moveToPosition(client.getPosition().x_val, client.getPosition().y_val, client.getPosition().z_val-25, 6)
print('Client position: {}'.format(client.getPosition()))
client.moveToGPSPosition(GPSCoordinate(53.27929999999999921556081972084939479827880859375, -9.0638000000000005229594535194337368011474609375, 55.0), 7)
time.sleep(1)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_0.png", image.image_data_uint8)
gpsCoordsFile.write('53.27929999999999921556081972084939479827880859375, -9.0638000000000005229594535194337368011474609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_1.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_2.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_3.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_4.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_5.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_6.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_7.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_8.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_9.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_10.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_11.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_12.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_13.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_14.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_15.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_16.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_17.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_18.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_19.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_20.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_21.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_22.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_23.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_24.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_25.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2790665126999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_26.png", image.image_data_uint8)
gpsCoordsFile.write('53.2790665126999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_27.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_28.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_29.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_30.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_31.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_32.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_33.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_34.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_35.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_36.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_37.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_38.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_39.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_40.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2788592588999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_41.png", image.image_data_uint8)
gpsCoordsFile.write('53.2788592588999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_42.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_43.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_44.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_45.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_46.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_47.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_48.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_49.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_50.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_51.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_52.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_53.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_54.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_55.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794810202999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_56.png", image.image_data_uint8)
gpsCoordsFile.write('53.2794810202999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_57.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_58.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_59.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2792737664999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_60.png", image.image_data_uint8)
gpsCoordsFile.write('53.2792737664999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_61.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_62.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_63.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_64.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_65.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_66.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_67.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_68.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_69.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_70.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_71.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_72.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_73.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_74.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_75.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_76.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_77.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_78.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2798955278999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_79.png", image.image_data_uint8)
gpsCoordsFile.write('53.2798955278999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_80.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_81.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_82.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_83.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_84.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_85.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_86.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_87.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_88.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_89.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796882740999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_90.png", image.image_data_uint8)
gpsCoordsFile.write('53.2796882740999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_91.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_92.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_93.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_94.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_95.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_96.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_97.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_98.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_99.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_100.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_101.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_102.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_103.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_104.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_105.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_106.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_107.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_108.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_109.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_110.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_111.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_112.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_113.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_114.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_115.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2803100354999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_116.png", image.image_data_uint8)
gpsCoordsFile.write('53.2803100354999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_117.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_118.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_119.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801027816999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_120.png", image.image_data_uint8)
gpsCoordsFile.write('53.2801027816999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_121.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_122.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_123.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_124.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_125.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_126.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_127.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_128.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_129.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_130.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_131.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_132.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_133.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_134.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_135.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_136.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_137.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_138.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2807245430999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_139.png", image.image_data_uint8)
gpsCoordsFile.write('53.2807245430999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_140.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_141.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_142.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_143.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_144.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_145.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_146.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_147.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_148.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_149.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2805172892999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_150.png", image.image_data_uint8)
gpsCoordsFile.write('53.2805172892999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_151.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0638355817000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_152.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0636149455000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_153.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0633943093000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_154.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0631736731000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_155.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0629530369000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_156.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0627324007000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_157.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0625117645000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_158.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0622911283000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_159.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0620704921000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_160.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0618498559000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_161.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0616292197000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_162.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0640562179000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_163.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0642768541000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_164.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0644974903000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2809317968999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375, 55.0), 2.2)
time.sleep(2)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene), ImageRequest(1, AirSimImageType.Scene), ImageRequest(4, AirSimImageType.Scene)])
print('Writing files to ', "D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Cameraexamplecamera"+ "/image_0.png")
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("D:/TempFiles/CBRNeVirtualEnvironment/RAVCollectedData/PNGImages"+"/ImagesRAV1" + "/Camera{}".format(camera_index+1)+ "/image_165.png", image.image_data_uint8)
gpsCoordsFile.write('53.2809317968999996556129190139472484588623046875, -9.0647181265000006517619112855754792690277099609375/n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'/n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(client.GPS_to_unreal.home_position_GPS.lat, gps_mapper.home_position_GPS.long, 55.0), 2.2)
time.sleep(2)
client.land()
client.armDisarm(False)
gpsCoordsFile.close()
AirSimgpsCoordsFile.close()
AirSimgpsRelativeCoordsFile.close()
<file_sep>/PythonCode/Routing/AirSimPythonClient/GPS/GPSCoordinateTest.py
from GPSCoordinate import GPSCoordinate
import unittest
class TestTTTBoard(unittest.TestCase):
def setUp(self):
self.OConnellStreetCoordinate = GPSCoordinate(53.3512416, -6.2629676, 0)
self.EyreSquareCoordinate = GPSCoordinate(53.2743394, -9.0514163)
self.NUIGCoordinate = GPSCoordinate(53.2809159, -9.0692133, 20)
def testLatLongAlt(self):
self.assertEqual(self.OConnellStreetCoordinate.lat, 53.3512416)
self.assertEqual(self.EyreSquareCoordinate.long, -9.0514163)
self.assertEqual(self.NUIGCoordinate.alt, 20)
def testGetMetresBetweenPoints(self):
self.assertAlmostEqual(GPSCoordinate.getMetresBetweenPoints(self.OConnellStreetCoordinate, self.EyreSquareCoordinate),185629, delta = 5000)
self.assertAlmostEqual(GPSCoordinate.getMetresBetweenPoints(self.EyreSquareCoordinate, self.NUIGCoordinate),1394 , delta = 50)
def testGetInitialBearing(self):
#taken from https://www.movable-type.co.uk/scripts/latlong.html
osaka = GPSCoordinate(35, 135)
baghdad = GPSCoordinate(35, 45)
self.assertAlmostEqual(osaka.get_initial_bearing(baghdad), 60, delta = 5)
self.assertAlmostEqual(baghdad.get_initial_bearing(osaka), 360-60, delta = 5)<file_sep>/SOPRanking/RocsafeCode/Demo-IR/elastic_utils.py
import sqlite3
from datetime import datetime
def insert_rank(sop_rankings_dict, search_terms, db_conn):
"""Insets new rankings into DB based on search terms"""
db_conn = sqlite3.connect(db_conn)
n = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cur = db_conn.cursor()
for i, score in sop_rankings_dict.items():
sql = '''insert into Rank(Date, Rank, SOPID, SearchTerms) values (?,?,?,?)'''
params = (str(n), score, i, str(search_terms))
cur.execute(sql, params)
db_conn.commit()
db_conn.close()
def format_synonyms(synonym_dict):
"""Takes a synonym dict and formats it to be written with elasticsearch"""
synonym_list = []
for word, synonyms in sorted(synonym_dict.items()):
for synonym in synonyms:
pair = "\t\t\t\t\t\t\"%s,%s\"" % (word.strip(), synonym.strip())
synonym_list.append(pair)
return synonym_list
def return_query(es, index_name, field, search_name):
res = es.search(index=index_name, body={"query": {"match": {field: str(search_name)}}})
sop_dict = res['hits']['hits']
for sop in sop_dict:
yield sop['_id'], sop['_score']
def return_all(es, index_name):
# print("return_all: index_name = " + index_name)
res = es.search(index=index_name, body={"query": {"match_all": {}}})
sop_dict = res['hits']['hits']
for sop in sop_dict:
yield sop['_id'], 0.0
def compute_ranking(es, index_name, field, search_name):
res = {}
for i, score in return_all(es, index_name):
res[i] = score
for i, score in return_query(es, index_name, field, search_name):
res[i] = score
return res
<file_sep>/RAVCollectedData/README.md
## This directory containing data collected by the RAV while surveying the scene.
- GPSCoords: The GPS waypoints that were visited by each RAV. This contains RecordedGPSCoords (relative to AirSim home position) and RecordedGPSCoordsRelative (relative to NUIG position). Default file name in these directory is RecordedGPSCoordsAgent<agent number>.txt
- JPGImagesWithExif: Processed JPG images collected by the RAV with exif data attached. This directory contains subdirectory named JPGImagesRAV<rav number>. The images recorded from each camera on the RAV are recorded in the subdirectories Camera<camera number>. Within each of these directory are images named image_<image number>.jpg.
- PNGImages: Raw png images gathered by RAVS. This directory contains subdirectory named ImagesRAV<rav number>. The images recorded from each camera on the RAV are recorded in the subdirectories Camera<camera number>. Within each of these directory are images named image_<image number>.jpg.<file_sep>/SOPRanking/RocsafeCode/Demo-IR/sop_tests.py
import os
import utils
import unittest
import elastic_utils
from elasticsearch import Elasticsearch
from sop_server import app
class SopTests(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
self.app.testing = True
self.es = Elasticsearch()
self.db_conn, self.sop_location, self.pdf_loc, self.index_name = utils.get_config('main.ini')
self.search_terms = 'headache'
def test_ini(self):
self.assertTrue(os.path.exists(self.db_conn))
self.assertTrue(os.path.exists(self.sop_location))
self.assertTrue(os.path.exists(self.pdf_loc))
def test_search(self):
headache_rankings = elastic_utils.compute_ranking(self.es, self.index_name, "text", self.search_terms)
self.assertDictEqual({'0': 0.0, '5': 0.0, '2': 0.0, '4': 0.0, '1': 0.45428392, '3': 0.0}, headache_rankings)
def test_flask(self):
result = self.app.get('/')
self.assertEqual(result.status_code, 200)
if __name__ == '__main__':
unittest.main()
<file_sep>/SOPRanking/RocsafeCode/Demo-IR/main.ini
[sqlite]
dblocation: ./dbs/sops.db
soplocation: ./text/
sopPDFlocation: ./pdf/
indexname: sops
<file_sep>/PythonCode/Routing/AirSimPythonClient/GPS/__init__.py
__all__ = ['RAVGPSMapper', 'GPSCoordinate']<file_sep>/SOPRanking/RocsafeCode/CBRN Scrape/scrapeCBRNE.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import string,itertools
import urllib2, codecs
import requests
from lxml import html
from time import sleep
from random import randint
from selenium import webdriver
from pyvirtualdisplay import Display
import time, re, pickle
from selenium import webdriver
from random import randint
location = "http://opencbrne.jrc.ec.europa.eu/page/%d?fchar=%s"
urlLocation = "http://opencbrne.jrc.ec.europa.eu/page/%d"
def returnChars():
chars = string.ascii_uppercase[:26]
for char in chars:
yield char
def returnNumbers():
for n in itertools.count():
yield n
def returnURL():
for c in returnChars():
for n in returnNumbers():
url = location %(n,c)
yield url
def readFile():
location = "CBRNEURLS.txt"
for l in open(location):
if not l.strip():
continue
yield l
def returnSynonym(text):
anchors = ["see:","see also:"]
if not text:
return ""
for anchor in anchors:
if anchor not in text.lower():
continue
index = text.lower().index(anchor)
index+=len(anchor)+1
return text[index:].strip()
return ""
def dumpText(outhandle, name, text):
name = name.strip()
text = text.strip()
text = text.encode('utf-8', 'ignore').decode('utf-8')
dumpText = "%s\n%s\n%s\n\n\n" % (name,text, "End Record")
outhandle.write(dumpText)
def scrapeSite():
d = {}
outhandle = codecs.open("PlainTextDumpCBRNE.txt","w","utf-8")
browser = webdriver.Edge("C:/Users/Brett/Downloads/Edge/MicrosoftWebDriver.exe")
timeout = -1
for url in readFile():
if url.strip() != "http://opencbrne.jrc.ec.europa.eu/page/7996" and timeout == -1:
print url
continue
print url
timeout = randint(7, 40)
browser.get(url)
time.sleep(timeout)
name = None
for a in browser.find_elements_by_xpath("//*[@id]"):
if str(a.get_attribute("id")).strip() != "cbrn_aj_title" and \
str(a.get_attribute("id")).strip() != "cbrn_aj_content":
continue
if str(a.get_attribute("id")).strip() == "cbrn_aj_title":
name = a.text
d[name] = None
elif str(a.get_attribute("id")).strip() == "cbrn_aj_content":
synonym = returnSynonym(a.text)
d[name] = synonym
dumpText(outhandle, name, a.text)
pickle.dump(d,open("synonyms.pck","wb"))
outhandle.close()
browser.quit
def processPages():
#location = "http://opencbrne.jrc.ec.europa.eu/page/%d"
location = "http://opencbrne.jrc.ec.europa.eu/page/0?fchar=%s"
browser = webdriver.Edge("C:/Users/Brett/Downloads/Edge/MicrosoftWebDriver.exe")
outhandle = open("CBRNEURLS.txt","w")
for w in returnChars():
url = location %(w)
browser.get(url)
time.sleep(10)
for a in browser.find_elements_by_xpath("//*[@id]"):
if str(a.get_attribute("id")).strip() != "cbrn_aj_index":
continue
for n in a.find_elements_by_xpath(".//a"):
try:
#print n.text.encode('ascii', 'ignore').decode('ascii')
#print n.tag_name
#print n.get_attribute("id")
#print n.get_attribute("name")
outhandle.write(n.get_attribute("href"))
outhandle.write("\n")
#print str(a.get_attribute("id")).strip() == "cbrn_aj_index"
#if str(a.get_attribute("id")).strip() == "cbrn_aj_index":
# print a.text.encode('ascii', 'ignore').decode('ascii')
# print a.tag_name
except:
continue
#print a.id
#break
browser.quit
outhandle.close()
def extractSynonyms():
d = {}
locations = ["PlainTextDumpCBRNE.txt.2","PlainTextDumpCBRNE.txt.1","PlainTextDumpCBRNE.txt"]
for location in locations:
ihandle = codecs.open (location,"r","utf-8")
text = ihandle.read()
ihandle.close()
records = text.split("End Record")
for record in records:
lines = record.split("\n")
synonym = returnSynonym(lines[-2])
if not synonym:
continue
d[lines[3].strip().lower()] = synonym.lower()
for i,t in d.items():
print i," ",t
pickle.dump(d,open("synonyms.pck","wb"))
extractSynonyms()
<file_sep>/PythonCode/Routing/ExifAddition/ExifUtils/helpers.py
import os
import shutil
from PIL import Image
def verify_file_exists(file_loc: str) -> bool:
return os.path.isfile(file_loc)
def verify_dir_exists(dir_loc: str) -> bool:
return os.path.isdir(dir_loc)
def copy_file(from_file_location: str, to_file_dir: str):
'''Copies a png file from one folder to another'''
#only tested for png files!
if not verify_file_exists(from_file_location):
raise Exception("File: {} does not exist".format(from_file_location))
if not verify_dir_exists(to_file_dir):
raise Exception("File: {} does not exist".format(to_file_dir))
if from_file_location[-4:] != '.png':
raise Exception("Source file extension must be .png, not {}".format(to_file_location[-3:]))
shutil.copy2(from_file_location, to_file_dir)
def convert_png_to_jpg(file_location: str, delete_png = True) -> "copied jpg location":
'''Converts a png file to a jpg file and removes the old png file'''
if not verify_file_exists(file_location):
raise Exception("File: {} does not exist".format(file_location))
if file_location[-4:] != '.png':
raise Exception("Source file extension must be .png, not {}".format(file_location[-3:]))
#Image.open(file_location).convert('RGB').save(file_location[:-3] + 'jpg')
Image.open(file_location).convert('RGB').save(file_location[:-3] + 'jpg',"JPEG", quality = 100)
os.remove(file_location)
return file_location[:-3] + 'jpg'<file_sep>/SOPRanking/RocsafeCode/Demo-IR/utils.py
import os
import configparser
def config_selection_map(section, config):
config_dict = {}
options = config.options(section)
for option in options:
try:
config_dict[option] = config.get(section, option)
if config_dict[option] == -1:
print("skip: %s" % option)
except Exception as e:
print("exception on %s!" % option)
print(e)
config_dict[option] = None
return config_dict
def get_abs_path(file):
return os.path.dirname(os.path.realpath(__file__)) + '/' + file
def get_config(ini_loc):
"""
Reads config file 'main.ini' and returns config values
Sample config file:
[sqlite]
dblocation: ./dbs/sops.db
soplocation: ./text/
sopPDFlocation: ./pdf/
indexname: sops
"""
config = configparser.ConfigParser()
config.read(os.path.dirname(os.path.realpath(__file__)) + '/' + ini_loc)
section = "sqlite"
config_dict = None
try:
config_dict = config_selection_map(section, config)
except configparser.NoSectionError:
print("Can't find section \'%s\' file: %s" % (section, ini_loc))
exit(-1)
db_conn = config_dict["dblocation"]
if db_conn.startswith('.'):
db_conn = get_abs_path(db_conn)
sop_location = config_dict["soplocation"]
if sop_location.startswith('.'):
sop_location = get_abs_path(sop_location)
pdf_loc = config_dict["soppdflocation"]
if pdf_loc.startswith('.'):
pdf_loc = get_abs_path(pdf_loc)
index_name = config_dict["indexname"]
if not os.path.isfile(db_conn):
db_err = "DB file: %s does not exist" % db_conn
print(db_err)
exit(-1)
if not os.path.isdir(sop_location):
sop_err = "SOP text file location: %s does not exist" % sop_location
print(sop_err)
exit(-1)
if not os.path.isdir(pdf_loc):
pdf_err = "Directory %s does not exist" % pdf_loc
print(pdf_err)
exit(-1)
if not index_name:
index_err = "Index name is not set in %s" % ini_loc
print(index_err)
exit(-1)
return db_conn, sop_location, pdf_loc, index_name
<file_sep>/PythonCode/Routing/ExifAddition/AddExifRunner.py
from AddExif import copy_png_files_and_convert_to_jpg, get_gps_coords_default, getConfig, get_RAV_image_dir, get_RAV_JPG_image_dir
import os
def main():
#write argparser for user to pass in which gps coords to use
rav_number = 1
config = getConfig()
gps_lats, gps_longs, gps_alts = get_gps_coords_default(rav_number)
png_folder = get_RAV_image_dir(rav_number)
print('png_folder: ', png_folder)
jpg_folder = get_RAV_JPG_image_dir(rav_number)
print('jpg_folder: ', jpg_folder)
#png_folder, jpg_folder, gps_lats, gps_longs, gps_alts = [], sorting_lambda = lambda file_name: #int(file_name.split('_')[1].replace('.png',''))
copy_png_files_and_convert_to_jpg(png_folder, jpg_folder, gps_lats, gps_longs, gps_alts)
if __name__ == '__main__':
main()<file_sep>/JavaCode/README.txt
Jar is configured to run with the following command line options:
1). working directory (should be IJCAIDemoAll)
2). number of RAVs
3). latitude spacing between grid points
4). longitude spacing between grid points
5). GPS coordinates of bounding polygon, in the form lat1 long1 lat2 long2 lat3 long3 etc.<file_sep>/PythonCode/README.md
## This directory contains:
- Routing: A directory which contains the python code required to send planned routes to unreal engine via the python api. <file_sep>/README.md
# ROCSAFE Technology Demo Code
ROCSAFE (**R**emotely **O**perated **CBRNe** **S**cene **A**ssessment and **F**orensic **E**xamination) is an EU horizon 2020 project that contains Aritificial Intelligence components. This repo contains:
- A release of a virtual environment which has developed for the project for simulation purposes. This was written using Unreal Engine version 4.16 and can be downloaded from the [releases page](https://github.com/NUIG-ROCSAFE/CBRNeVirtualEnvironment/releases).
- A user interface and associated code which allows the user to use/test the technologies developed.
- A data gathering pipeline which can be used to generate images and other data related in the scene and store them in a pre-defined format
## Requirements
In order to ensure that the code runs without issues, please check you have the following requirements:
- Windows 10+
- Python 3.5+
- Pip 18.0+
- R 3.5.0 +
- RStudio 1.0.153+
- JRE 1.8
- ElasticSearch 6.3.0
- BLOG (bayesian reasoning programming language, can be downloaded [here](https://bayesianlogic.github.io/pages/download.html)
- MaskRCNN (https://github.com/matterport/Mask_RCNN)
**Note:** This software was developed and tested using Windows 10, with Linux support planned. If you would like to use a virtualenv/pipenv rather than your base installation of python, you will need to modify start_up.bat and one_drone.bat, two_drone.bat, three_drone.bat.
We recommend the following config:
- Windows 10
- Python 3.5
- Pip 18.0
- R 3.5.0
- RStudio 1.0.153
- JRE 1.8
- ElasticSearch 6.3.0
- BLOG 0.9
## How to use the user interface
In Rstudio, once you have run Dependencies.R, open server.R. In the top right corner of the editor click run app.
## What's going on under the hood
## How can I extend/modify the code in this repo
<file_sep>/PythonCode/Routing/RouteGeneration/generateRoutesForUnrealRunner.py
import argparse
import sys
import os
import configparser
from generateRoutesForUnrealUtils import generate_route_text, save_python_to_file
def get_config() -> configparser.ConfigParser:
config = configparser.ConfigParser()
#read the global default config
config.read(os.getcwd().replace("\\", "/") + '/../../../../Config/config.ini')
print("Read config file from here: {}".format(os.getcwd().replace("\\", "/") + '/../../../../Config/config.ini'))
return config
def create_folders_if_dont_exist():
'''If default folders don't exist, create them'''
pass
def main(no_ravs, no_cameras = 1, rav_velocity = 4, rav_altitude = 35, RAV_route_execution_dir = "", RAV_recorded_GPS_waypoints_dir="", RAV_recorded_GPS_waypoints_relative_dir="", saved_images_dir=""):
config = get_config()
print('config: ', config.sections())
print("Generating routes for ", no_ravs, " ravs")
base_dir = os.path.abspath(__file__).split('PythonCode')[0].replace('\\', '/')[:-1]
print("Generating routes using base directory: {}".format(base_dir))
#READ DEFAULTS
RAVGPSRoutesDir = base_dir + config["DATA"]["PlannedAgentRoutesDir"]
#pull this out into separate file
if saved_images_dir == "":
#saved_images_dir = base_dir + "/PythonCode/PythonClientGPSMapping/GPSMappings/Images"
saved_images_dir = base_dir + config["DATA"]["CollectedPNGImagesDir"]
#create saved images directory if not already in existence
if not os.path.isdir(saved_images_dir):
#exit program and ask for valid path
print('Directory {} does not exist, creating'.format(saved_images_dir))
os.makedirs(saved_images_dir)
if RAV_recorded_GPS_waypoints_dir == "":
RAV_recorded_GPS_waypoints_dir = base_dir + config["DATA"]["RAVRecordedGPSWaypointsDir"]
#RAV_recorded_GPS_waypoints_dir = base_dir + "/PythonCode/PythonClientGPSMapping/GPSMappings/GPSCoords"
if RAV_recorded_relative_GPS_waypoints_dir == "":
RAV_recorded_relative_GPS_waypoints_dir = base_dir + config["DATA"]["RAVRecordedRelativeGPSWaypointsDir"]
if RAV_recorded_GPS_waypoints_file_format_str == "":
RAV_recorded_GPS_waypoints_file_format_str = config["DATA"]["RAVRecordedGPSWaypointsFileFormatStr"]
#create route execution directory if not already in existence
if RAV_route_execution_dir == "":
RAV_route_execution_dir = base_dir + config['PYTHON']['PythonRAVRouteExecutionDir']
#RAV_route_execution_dir = base_dir + "/PythonCode/PythonGridMapping/AirSimPythonClient"
#create recorded waypoints directory if not already in existence
if not os.path.isdir(RAV_recorded_GPS_waypoints_dir):
print('Directory {} does not exist, creating in default location'.format(saved_images_dir))
os.makedirs(RAV_recorded_GPS_waypoints_dir)
#create images directory
for rav_no in range(int(no_ravs)):
if not os.path.isdir(saved_images_dir + config['DATA']['RAVImagesDirFormatStr'].format(rav_no + 1)):
os.makedirs(saved_images_dir + config['DATA']['RAVImagesDirFormatStr'].format(rav_no + 1))
for camera_no in range(int(no_cameras)):
if not os.path.isdir(saved_images_dir + config['DATA']['RAVImagesDirFormatStr'].format(rav_no + 1) + config['DATA']['CameraImagesDirFormatStr'].format(camera_no+1)):
print('Directory {} does not exist, creating in default location'.format(saved_images_dir + config['DATA']['RAVImagesDirFormatStr'].format(rav_no + 1) + config['DATA']['CameraImagesDirFormatStr'].format(camera_no+1)))
os.makedirs(saved_images_dir + config['DATA']['RAVImagesDirFormatStr'].format(rav_no + 1) + config['DATA']['CameraImagesDirFormatStr'].format(camera_no+1))
for rav_no in range(int(no_ravs)):
#drone_number, gps_coords, gps_coords_file_dir, saved_images_dir, no_cameras = 1, rav_velocity = 5, rav_altitude = 35, sleep_time = 0.5, images: #bool = True, gps_locations: bool=True
#skip the header
#drone_number, gps_coordinates_text, RAV_recorded_GPS_waypoints_dir, RAV_recorded_GPS_waypoints_file_format_str, RAV_recorded_GPS_waypoints_relative_dir, saved_images_dir, rav_images_dir, camera_images_dir, image_file_format_str
python_code = generate_route_text(rav_no+1, ''.join(open(RAVGPSRoutesDir+"/Agent{}.csv".format(rav_no+1)).readlines()[1:]), RAV_recorded_GPS_waypoints_dir, RAV_recorded_GPS_waypoints_file_format_str, RAV_recorded_GPS_waypoints_relative_dir, RAV_saved_images_dir, config['DATA']['RAVImagesDirFormatStr'], config['DATA']['CameraImagesDirFormatStr'],config['DATA']['ImagesFileFormatStr'],no_cameras, rav_velocity = rav_velocity, rav_altitude=rav_altitude, sleep_time=2, images=True, gps_locations=True)
#assume that directory layout is that specified in IJCAIDemoCode
rav_no_dict={1:'zero', 2:'one', 3: 'two', 4: 'three'}
save_python_to_file(python_code, RAV_route_execution_dir + "/rav_{}_mapper.py".format(rav_no_dict[rav_no+1]))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Automatically write the python files necessary to send the specified number of RAVs on routes given by a file containing GPS coordinates')
#metavar is a name for the argument in usage messages.
#nargs -The number of command-line arguments that should be consumed.
parser.add_argument("no_ravs", type = int, metavar = "no_ravs", help = "Number of RAVS to use in the simulation")
parser.add_argument("no_cameras", type = int, metavar = "no_cameras", nargs='?', default = 1, help = "Number of cameras to record images from in the simulation")
parser.add_argument("rav_velocity", type = float, metavar = "rav_velocity", nargs='?', default = 5, help = "Velocticy at which RAVs will operate for simulation")
parser.add_argument("rav_altitude", type = float, metavar = "rav_altitude", nargs='?', default = 35, help = "Altitude at which RAVs will operate for simulation")
parser.add_argument("RAV_route_execution_dir", type = str, nargs='?', default = "", metavar = "RAV_route_execution_dir", help = "The directory in which to write the python routing files.")
parser.add_argument("saved_images_dir", type = str, nargs='?', default = "",metavar = "saved_images_dir", help = "The directory in which to save the recorded images.")
parser.add_argument("RAV_recorded_GPS_waypoints_dir", type = str, nargs='?', default = "",metavar = "RAV_recorded_GPS_waypoints_dir", help = "The directory in which to save the RAV gps routes.")
parser.add_argument("RAV_recorded_relative_GPS_waypoints_dir", type = str, nargs='?', default = "",metavar = "RAV_recorded_relative_GPS_waypoints_dir", help = "The directory in which to save the relative recorded RAV gps routes.")
parser.add_argument("RAV_recorded_GPS_waypoints_file_format_str", type = str, nargs='?', default = "",metavar = "RAV_recorded_GPS_waypoints_file_format_str", help = "The file format in which to save the recorded RAV gps routes.")
parser.add_argument("ImagesFileFormatStr", type = str, nargs='?', default = "",metavar = "ImagesFileFormatStr", help = "The file format in which to save the recorded RAV images.")
args = parser.parse_args()
print("args: ", vars(args))
main(**vars(args))
<file_sep>/PythonCode/config.ini
[DEFAULT]
RAVGPSRoutesDir = "/RCode/ShinyApp/Data/"
PNGImagesDir = "/RAVCollectedData/PNGImages/"
RAVRecordedGPSWaypoints = "/RAVCollectedData/GPSCoords/"
RAVRouteExecutionDir = "/PythonCode/Routing/AirSimPythonClient/RAVExecuteRoutes/"
<file_sep>/PythonCode/gen_airsim.py
import os
import sys
import shutil
#This only works for linux
if not os.path.isdir(os.path.expanduser("~/AirSim/")):
os.makedirs(os.path.expanduser("~/AirSim/"))
if not os.path.exists(os.path.expanduser("~/AirSim/settings.json")):
shutil.copy(sys.argv[1], os.path.expanduser("~/AirSim/settings.json"))
<file_sep>/SOPRanking/RocsafeCode/Demo-IR/elasticMain.py
import ConfigParser
import datetime
import json
import os
import pickle
import sqlite3
import sys
from datetime import datetime
from elasticsearch import Elasticsearch
global es
global indexName
global location
global soplocation
es = Elasticsearch()
# import logging
# import sys
# logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
# json functions
def returnMessage(strMsg, error=True):
if error:
error = {"error": strMsg}
print(json.dumps(error))
else:
message = {"message": strMsg}
print(json.dumps(strMsg))
# read ini-file
def setGlobalVariables():
global location
global soplocation
global indexName
inilocation = "./main.ini"
Config = ConfigParser.ConfigParser()
Config.read(inilocation)
section = "sqlite"
keys = None
try:
keys = ConfigSectionMap(section, Config)
except:
print("Can't find ini file: %s" % (inilocation))
exit()
location = keys["dblocation"]
soplocation = keys["soplocation"]
indexName = keys["indexname"]
if not os.path.isfile(location):
strError = "File %s does not exist" % (location)
returnMessage(strError)
exit()
if not os.path.isdir(soplocation):
strError = "Directory %s does not exist" % (soplocation)
returnMessage(strError)
exit()
if not indexName:
strError = "indexName not set"
returnMessage(strError)
exit()
def ConfigSectionMap(section, Config):
dict1 = {}
options = Config.options(section)
for option in options:
try:
dict1[option] = Config.get(section, option)
if dict1[option] == -1:
DebugPrint("skip: %s" % option)
except:
print("exception on %s!" % option)
dict1[option] = None
return dict1
# SQLite Functions
def returnRank():
global location
conn = sqlite3.connect(location)
cur = conn.cursor()
sql = "SELECT SOP.Title, rank.rank from rank,SOP where rank.sopid = SOP.id "
sql += " and date in (select max(date) FROM Rank) order by rank desc"
cur.execute(sql)
rows = cur.fetchall()
for row in rows:
print(row)
def insertRank(res, searchTerms):
global location
conn = sqlite3.connect(location)
print('entering to database location: ', location)
n = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cur = conn.cursor()
for i, score in res.items():
sql = '''insert into Rank(Date, Rank, SOPID, SearchTerms) values (?,?,?,?)'''
params = (str(n), score, i, str(searchTerms))
print('executing sql: {}'.format(params))
# print("result: ", cur.execute(sql, params))
cur.execute(sql, params)
conn.commit()
conn.close()
def insertSOP():
global location
conn = sqlite3.connect(location)
cur = conn.cursor()
xid = 0
for location, name in returnSOPS():
text = returntext(location)
name = name[0:-4]
sql = '''insert into SOP(ID, Title, Text) values (?,?,?)'''
text = text.decode("utf-8")
params = (xid, name, text)
cur.execute(sql, params)
conn.commit()
xid += 1
conn.close()
def returnSOPS():
global soplocation
for f in os.listdir(soplocation):
yield "%s%s" % (soplocation, f), f
def returntext(flocation):
inhandle = open(flocation, "r")
text = ""
for line in inhandle:
text += " " + line
inhandle.close()
return text
# ElasticSearch Functions
def returndoc():
for flocation, title in returnSOPS():
title = title[0:-4]
text = returntext(flocation)
doc = {
'title': title,
'text': text,
}
yield doc
def returnQuery(field, searchTerm):
res = es.search(index=indexName, body={"query": {"match": {field: searchTerm}}})
d = res['hits']['hits']
for dx in d:
yield dx['_id'], dx['_score']
def returnAll():
print("returnAll: indexName=" + indexName)
res = es.search(index=indexName, body={"query": {"match_all": {}}})
print("Results Returned")
print("RESULT : " + str(res))
d = res['hits']['hits']
print('d', d)
print("sELECT hITS : " + str(d))
for dx in d:
yield dx['_id'], 0.0
print("Finish returnAll")
def computeRanking(field, searchTerm):
res = {}
# try:
for i, score in returnAll():
res[i] = score
for i, score in returnQuery(field, searchTerm):
res[i] = score
print('compute ranking res: ', res)
# except:
# strError = "Elastic Search is Down"
# returnMessage(strError)
# exit()
return res
def returnSynoyms(d):
l = []
for word, synonyms in sorted(d.items()):
try:
print(word, ':', synonyms.split(','), ',')
except Exception as e:
print([], ',')
for synonym in synonyms.split(","):
pair = "\t\t\t\t\t\t\"%s,%s\"" % (word.strip(), synonym.strip())
l.append(pair)
return l
def addSynonyms():
d = pickle.load(open("../Synonyms/synonyms.pck", 'rb'))
l = returnSynoyms(d)
s = ",\n"
syns = s.join(l)
doc = "PUT /index/sops"
doc += "{ "
doc += " \"settings\": {\n"
doc += " \"analysis\": {\n"
doc += " \"filter\": {\n"
doc += " \"CBRNE_filter\": {\n"
doc += " \"type\": \"synonym\",\n"
doc += " \"synonyms\": [ \n"
doc += syns
doc += " }\n"
doc += " },\n"
doc += " \"analyzer\":{\n"
doc += " \"tokenizer\": \"standard\",\n"
doc += " \"CBRNE\":{\n"
doc += " \"filter\": [\n"
doc += " \"lowercase\",\n"
doc += " \"CBRNE_filter\"\n"
doc += " ]\n"
doc += " }\n"
doc += " }\n"
doc += "}\n}\n}"
# default search term
# searchTerm =""
# if len(sys.argv)==1:
# searchTerm ="chlorine, mustard gas"
# else:
# searchTerm = sys.argv[1]
# inhandle = open("terms.txt")
# for line in inhandle:
# searchTerm = line.strip()
# setGlobalVariables()
# #addSynonyms()
# res = computeRanking(field,searchTerm)
# insertRank(res)
# print(line)
# time.sleep(10)
# #strMsg = "Action Completed"
# #returnMessage(strMsg, False)
def main():
search_terms = sys.argv[1:]
searchTerm = None
print("searching for terms: ", search_terms)
for line in search_terms:
searchTerm = line.strip()
setGlobalVariables()
addSynonyms()
field = "text"
res = computeRanking("text", searchTerm)
print('res: ', res)
insertRank(res, search_terms)
# insertRank(res)
print(line)
print(res)
if __name__ == '__main__':
main()
<file_sep>/PythonCode/Routing/ExifAddition/AddExif.py
# -*- coding: utf-8 -*-
#dependencies:
#exiftool https://www.sno.phy.queensu.ca/~phil/exiftool/
#
import subprocess
import os
import configparser
import os
import re
from PIL import Image
from ExifUtils.core import write_exif_gps_data
from ExifUtils.helpers import verify_file_exists, verify_dir_exists, copy_file, convert_png_to_jpg
#parse config file, which contains locations of images gathered by RAV in AirSim
#and location of file where files with EXIF data attached should go
def copy_png_files_and_convert_to_jpg(png_folder, jpg_folder, gps_lats, gps_longs, gps_alts = [], sorting_lambda = lambda file_name: int(file_name.split('_')[1].replace('.png','').replace('.jpg',''))):
'''Given a folder containing png files and a corresponding csv file containing lat,
long, alt for images, will create a new folder in specified location, copy png files to
jpg and write GPS details to exif. If a file in png_folder is not png it will be copied to
to jpg folder but not converted.'''
#check that jpg_folder exists
if not verify_dir_exists(jpg_folder):
print('Creating folder: {}'.format(jpg_folder))
os.makedirs(jpg_folder)
else:
if os.listdir(jpg_folder) != []:
print('{} is not an empty directory, may accidentally overwrite images'.format(jpg_folder))
print(os.listdir(png_folder))
#first copy files from png_folder to jpg_folder if they are .png format
for png_file in os.listdir(png_folder):
try:
copy_file(png_folder + png_file, jpg_folder)
except Exception as e:
#don't try and deal with exception (may change this)
raise e
#now convert files to jpg
for unconverted_png_file in os.listdir(jpg_folder):
try:
convert_png_to_jpg(jpg_folder + unconverted_png_file)
except Exception as e:
#don't try and deal with exception (may change this)
raise e
#process images by adding gps exif data. Assume that gps_lats and gps_longs are valid
counter = 0
for jpg_file in sorted(os.listdir(jpg_folder), key = sorting_lambda):
write_exif_gps_data(jpg_folder + jpg_file, gps_lats[counter], gps_longs[counter], gps_alts[counter])
counter += 1
def parse_gps_coords_default(gps_coords_string: str, rav_number: int, altitude: int):
'''Gets lats, longs from default location in ROCSAFE project'''
lats = [float(coord.split(',')[0]) for coord in gps_coords.split('\n')]
longs = [float(coord.split(',')[1]) for coord in gps_coords.split('\n')]
try:
alts = [float(coord.split(',')[2]) for coord in gps_coords.split('\n')]
except IndexError:
alts = [altitude for i in range(len(lats))]
alts = [altitude for i in range(len(lats))]
return lats, longs, alts
#print("Working from directory: " + base_dir)
#files containing GPS locations
#print('reading: ', base_dir + config['DEFAULT']['gpslocations1'])
#gpslocations1 = open(base_dir + config['DEFAULT']['gpslocations1'], 'r' ).readlines()
#gpslocations2 = open(base_dir + config['DEFAULT']['gpslocations2'], 'r' ).readlines()
#gpslocations3 = open(base_dir + config['DEFAULT']['gpslocations3'], 'r' ).readlines()
#gpslocations_files = [gpslocations1]
#, gpslocations2, gpslocations3]
#print('gpslocations1: {}'.format(gpslocations1))
#the location of the folder to save images as jpg instead of png - this can actually be done from within airsim!
#images will be saved in JPGImages\Drone{}Camera{}.JPG
#JPGImages = base_dir + config['DEFAULT']['jpg_images_location']
#print('Using JPG Image directory: ', JPGImages)
#"D:\IJCAIDemoCode\PythonClientGPSMapping\GPSMappings\GPSAnnotatedImages\JPGImages"
#the location of the images saved by the RAVs from airsim. Must be in the format
#image_{number}.png examples: image_20.png image_1.png
#drone1Images = base_dir + config['DEFAULT']['drone1Images_location']
#drone2Images = base_dir + config['DEFAULT']['drone2Images_location']
#drone3Images = base_dir + config['DEFAULT']['drone3Images_location']
'''
def copy_png_files_and_convert_to_jpg(drone_index, drone_images, camera_number):
print('Copying files from directory {}'.format(drone_images))
print("Converting {} images taken from RAV {} to jpg".format(len(os.listdir(drone_images)), drone_index))
for image in sorted(os.listdir(drone_images), key=lambda x: int(re.findall("_[0-9]{1,4}", x)[0][1:])):
png_im_loc = drone_images + '\\{}'.format(image)
jpg_im_loc = JPGImages + '\Drone{}Camera{}'.format(drone_index, camera_number) + 'JPG' + '\\drone{}'.format(drone_index) + image.replace('png', 'jpg')
print('Converting {} to jpg: {}'.format(png_im_loc, jpg_im_loc))
im = Image.open(png_im_loc)
rgb_im = im.convert('RGB')
rgb_im.save(jpg_im_loc)
def write_exif_data(drone_index, camera_number):
#remove any temp images in directory that exiftool may have created previously
for image in os.listdir(JPGImages + '\Drone{}Camera{}JPG'.format(drone_index, camera_number)):
if '_original' in image:
os.remove(JPGImages + '\Drone{}Camera{}JPG'.format(drone_index, camera_number) + '\\' + image)
try:
gps_locs = gpslocations_files[drone_index-1]
for image_loc, gpsLocation in zip(sorted(os.listdir(JPGImages + '\Drone{}Camera{}JPG'.format(drone_index, camera_number)), key = lambda x: int(re.findall("_[0-9]{1,4}", x)[0][1:])), gpslocations_files[drone_index-1]):
#print(JPGImages + "\Drone{}Camera3JPG\{}'.format(drone_index, image_loc)")
print(["exiftool", '-GPSLongitude={}'.format(gpsLocation.split(',')[1].replace('\n','').replace(' ','').replace(' ','').replace(' ','').replace(' ','')), '-GPSLatitude={}'.format(gpsLocation.split(',')[0].replace('\n','').replace(' ','').replace(' ','').replace(' ','').replace(' ','')), '-GPSAltitude="32"', '-GPSVersionID=3 2 0 0','-gpsaltituderef=0', "-n", "-GPSLatitudeRef=N", "-GPSLongitudeRef=E", JPGImages + "\Drone{}Camera3JPG\{}".format(drone_index, image_loc)])
print(subprocess.check_output(["exiftool", '-GPSLongitude={}'.format(gpsLocation.split(',')[1].replace('\n','').replace(' ','').replace(' ','').replace(' ','').replace(' ','')), '-GPSLatitude={}'.format(gpsLocation.split(',')[0].replace('\n','').replace(' ','').replace(' ','').replace(' ','').replace(' ','')), '-GPSAltitude="32"', '-GPSVersionID=3 2 0 0','-gpsaltituderef=0', "-n", "-GPSLatitudeRef=N", "-GPSLongitudeRef=W", JPGImages + "\Drone{}Camera{}JPG\{}".format(drone_index, camera_number, image_loc)]))
except Exception as e:
print(e)
raise e
#print(subprocess.check_output(["exiv2", "pr", "-p", "a", "D:\IJCAIDemoCode\PythonClientGPSMapping\GPSMappings\Images\Images1\Camera3\image_4.png"]))
finally:
#remove any temp images in directory that exiftool may have created
for image in os.listdir(JPGImages + '\Drone{}Camera{}JPG'.format(drone_index, camera_number)):
#os.rename('D:\IJCAIDemoCode\PythonClientGPSMapping\GPSMappings\GPSAnnotatedImages\JPGImages\Drone{}Camera3JPG'.format(drone_index) + '\\' + image, 'D:\IJCAIDemoCode\PythonClientGPSMapping\GPSMappings\GPSAnnotatedImages\JPGImages\Drone{}Camera3JPG'.format(drone_index) + '\\' + 'drone3' + image)
if '_original' in image:
os.remove(JPGImages + '\Drone{}Camera{}JPG'.format(drone_index, camera_number) + '\\' + image)
'''
#copy_png_files_and_convert_to_jpg(1, drone1Images, 3)
#copy_png_files_and_convert_to_jpg(2, drone2Images, 3)
#copy_png_files_and_convert_to_jpg(3, drone3Images, 3)
#write_exif_data(1, 3)
#write_exif_data(2, 3)
#write_exif_data(3, 3)
<file_sep>/PythonCode/Routing/AirSimPythonClient/RAVExecuteRoutes/rav_three_mapper.py
from AirSimClient import *
import time
# connect to the AirSim simulator
client = MultirotorClient(port=41454)
#client1 = MultirotorClient(port=41452)
client.confirmConnection()
print('Seem to be connected...')
client.enableApiControl(True)
#client.armDisarm(True)
#client1.enableApiControl(True)
#client1.armDisarm(True)
state = client.getGpsLocation()
#s = pprint.pformat(state)
print("state: %s" % state)
print('Taking off...')
client.takeoff()
print('moving to first location')
i = ''
while i!='m':
i = input("Type 'm' to begin mapping the environment")
print('Moving clear of tree line')
client.moveToPosition(client.getPosition().x_val, client.getPosition().y_val, client.getPosition().z_val-30, 3)
print('Client position: {}'.format(client.getPosition()))
client.moveToGPSPosition(GPSCoordinate(53.282, -9.052, 50), 6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28021443763637, -9.057533053890909, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28006243978182, -9.057393670804545, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.27996362880909, -9.057695074313637, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.27981163095455, -9.057555691227273, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.2796596331, -9.05741630814091, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.27950763524546, -9.057276925054547, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.27935563739091, -9.057137541968181, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.27920363953636, -9.056998158881818, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.27905164168182, -9.056858775795455, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.278952830709095, -9.057160179304544, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.27910482856364, -9.057299562390908, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.279256826418184, -9.057438945477271, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.279408824272736, -9.057578328563636, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.27956082212728, -9.05771771165, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.279712819981825, -9.057857094736363, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.27986481783637, -9.057996477822726, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.280016815690914, -9.05813586090909, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28016881354546, -9.058275243995453, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.2803208114, -9.058414627081817, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.280472809254555, -9.05855401016818, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.2806248071091, -9.058693393254545, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.280776804963644, -9.058832776340909, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28092880281819, -9.058972159427272, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28108080067273, -9.059111542513635, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28123279852728, -9.059250925599999, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28138479638182, -9.059390308686362, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28153679423637, -9.059529691772726, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28168879209092, -9.059669074859091, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28184078994546, -9.059808457945454, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28199278780001, -9.059947841031818, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28214478565455, -9.060087224118181, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.282243596627275, -9.059785820609092, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28209159877273, -9.059646437522728, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.281939600918186, -9.059507054436365, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28178760306364, -9.059367671350001, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28163560520909, -9.059228288263636, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.281483607354545, -9.059088905177273, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.2813316095, -9.05894952209091, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.281179611645456, -9.058810139004546, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28102761379091, -9.058670755918182, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28087561593637, -9.058531372831819, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28072361808182, -9.058391989745456, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28057162022728, -9.05825260665909, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.280419622372726, -9.058113223572727, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28026762451818, -9.057973840486364, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28011562666364, -9.0578344574, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28036643549091, -9.057672436977272, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.280518433345456, -9.057811820063636, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28067043120001, -9.05795120315, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28082242905455, -9.058090586236364, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.2809744269091, -9.058229969322728, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28112642476364, -9.058369352409091, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.281278422618186, -9.058508735495455, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28143042047273, -9.058648118581818, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.281582418327275, -9.058787501668181, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28173441618182, -9.058926884754545, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28188641403637, -9.05906626784091, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.282038411890916, -9.059205650927273, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28219040974546, -9.059345034013637, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.282342407600005, -9.0594844171, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28135429787273, -9.062498452190908, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28120230001819, -9.062359069104545, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28105030216364, -9.062219686018182, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.2808983043091, -9.062080302931818, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.280746306454546, -9.061940919845453, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.280647495481816, -9.062242323354544, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28079949333637, -9.06238170644091, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28095149119091, -9.062521089527273, 50),6)
time.sleep(1)
client.moveToGPSPosition(GPSCoordinate(53.28110348904546, -9.062660472613636, 50),6)
time.sleep(1)<file_sep>/RCode/ShinyApp/utils.R
################### Put this in config ###################
odors <- c("smell_fruity",
"smell_odourless",
"smell_camphor",
"smell_wood",
"smell_chlorine",
"smell_mustard_radish_garlic",
"smell_unpleasant",
"smell_fish",
"smell_herring",
"smell_soap",
"smell_geranium",
"smell_bitter_almonds",
"smell_sour",
"smell_pungent",
"smell_apple_blossom",
"smell_sweet")
agents <-c("agent_nerve",
"agent_choking",
"agent_blister",
"agent_blood",
"agent_vomiting",
"agent_tear",
"agent_incapacitating_depressant_hallucinogen")
dispersion_methods <- c("dispersion_liquid",
"dispersion_gas",
"dispersion_vapours",
"dispersion_aerosol")
working_dir <<- paste(getwd(), '/../..', sep = '')
blog_code_loc <<- paste(working_dir, "/BlogCode", sep ='')
end_of_file <- readtext(paste(blog_code_loc, "/ChemProbReasoningSecondHalf.txt", sep = ''))$text
################### Put this in config ###################
concat_paths <- function(arg1,...){
inargs <- paste(arg1, ..., sep = "/")
inargs <- str_replace_all(string = inargs, pattern = "\\\\", replacement = "/")
inargs <- str_replace_all(string = inargs, pattern = "///", replacement = "/")
inargs <- str_replace_all(string = inargs, pattern = "//", replacement = "/")
return(inargs)
}
display_err <- function(err_title, err_msg) {
shinyalert(err_title, err_msg, type = "error")
}
RAVIcon <- makeIcon(
iconUrl = concat_paths(getwd(), "/www/RAVIcon.png"),
iconWidth = 35, iconHeight = 35,
iconAnchorX = 0, iconAnchorY = 0
)
check_dir_exists <- function(path, err_type, msg) {
if(isFALSE(dir.exists(path))){
display_err(err_type, msg)
}
}
check_file_exists <- function(filepath, err_type, msg) {
if(isFALSE(file.exists(filepath))){
display_err(err_type, msg)
}
}
check_config <- function(working_dir, config) {
err_type <- ""
# [JAVA]
err_type <- "Java Error"
if(config$JAVA$JavaBinLoc == ""){
x <- system("java -h")
if(x == 127){
display_err(err_type, "Could not find 'java' in PATH environment variable. Please fix PATH or enter java bin destination Config/config.ini [JAVA] JavaBinLoc.")
}
}
else {
check_file_exists(concat_paths(config$JAVA$JavaBinLoc, "java"), err_type, "Please fix [JAVA] JavaBinLoc in Config/config.ini.")
}
check_file_exists(concat_paths(working_dir, config$JAVA$JavaCodeLoc, config$JAVA$JavaMissionDesignerJar), err_type, "Please fix [JAVA] JavaCodeLoc/JavaMissionDesignerJar in Config/config.ini.")
# [BLOG]
err_type <- "Blog Error"
if(config$BLOG$BlogBinLoc == ""){
x <- system("blog -h")
if(x == 127){
display_err(err_type, "Could not find 'blog' in PATH environment variable. Please fix PATH or enter blog bin destination Config/config.ini [BLOG] BlogBinLoc.")
}
}
else {
check_file_exists(concat_paths(config$BLOG$BlogBinLoc, "blog"), err_type, "Please fix [BLOG] BlogBinLoc in Config/config.ini.")
}
check_file_exists(concat_paths(working_dir, config$BLOG$BlogCodeLoc, config$BLOG$BlogProgName), err_type, "BlogCodeLoc/BlogProgName doesn't exist, please fix [BLOG] BlogCodeLoc/BlogProgName in Config/config.ini.")
# [PYTHON]
err_type <- "Python Error"
x <- system(paste(config$PYTHON$PythonExe, " -V", sep = ""))
if(x == 127){
display_err(err_type, sprintf("Could not find '%s' in PATH environment variable. Please fix PATH or change PythonExe in Config/config.ini.", config$PYTHON$PythonExe))
}
check_dir_exists(concat_paths(working_dir, config$PYTHON$PythonDocRetrievalCodeLoc), err_type, "PythonDocRetrievalCodeLoc doesn't exist, please fix [PYTHON] PythonDocRetrievalCodeLoc in Config/config.ini.")
check_file_exists(concat_paths(working_dir, config$PYTHON$PythonDocRetrievalCodeLoc, config$PYTHON$PythonElasticMain ), err_type, "PythonElasticMain doesn't exist, please fix [PYTHON] PythonElasticMain in Config/config.ini.")
check_dir_exists(concat_paths(working_dir, config$PYTHON$PythonRAVRouteExecutionDir), err_type, "PythonRAVRouteExecutionDir doesn't exist, please fix [PYTHON] PythonRAVRouteExecutionDir in Config/config.ini.")
check_dir_exists(concat_paths(working_dir, config$PYTHON$PythonGenerateRouteDir), err_type, "PythonGenerateRouteDir doesn't exist, please fix [PYTHON] PythonGenerateRouteDir in Config/config.ini.")
check_file_exists(concat_paths(working_dir, config$PYTHON$PythonGenerateRouteDir, config$PYTHON$PythonGenerateRoutesFileLoc), err_type, "PythonGenerateRouteDir/PythonGenerateRoutesFileLoc doesn't exist, please fix [PYTHON] PythonGenerateRoutesFileLoc in Config/config.ini.")
# [BATCHSCRIPTS]
err_type <- "BatchScripts Error"
check_dir_exists(concat_paths(working_dir, config$BATCHSCRIPTS$BatchScriptsLoc), err_type, sprintf("%s doesn't exist, please fix [BATCHSCRIPTS] BatchScriptsLoc in Config/config.ini.", concat_paths(working_dir, config$BATCHSCRIPTS$BatchScriptsLoc)))
# [DATA]
err_type <- "Data Error"
check_dir_exists(concat_paths(working_dir, config$DATA$RAVGPSRoutesDir), err_type, sprintf("%s doesn't exist, please fix [DATA] RAVGPSRoutesDir in Config/config.ini.", concat_paths(working_dir, config$DATA$RAVGPSRoutesDir)))
check_dir_exists(concat_paths(working_dir, config$DATA$CollectedPNGImagesDir), err_type, sprintf("%s doesn't exist, please fix [DATA] CollectedPNGImagesDir in Config/config.ini.", concat_paths(working_dir, config$DATA$CollectedPNGImagesDir)))
check_dir_exists(concat_paths(working_dir, config$DATA$RAVRecordedGPSWaypoints), err_type, sprintf("%s doesn't exist, please fix [DATA] RAVRecordedGPSWaypoints in Config/config.ini.", concat_paths(working_dir, config$DATA$RAVRecordedGPSWaypoints )))
check_dir_exists(concat_paths(working_dir, config$DATA$UIImagesDir), err_type, sprintf("%s doesn't exist, please fix [DATA] UIImagesDir in Config/config.ini.", concat_paths(working_dir, config$DATA$UIImagesDir )))
check_dir_exists(concat_paths(working_dir, config$DATA$GPSPlannedAgentRoutesDir), err_type, sprintf("%s doesn't exist, please fix [DATA] GPSPlannedAgentRoutesDir in Config/config.ini.", concat_paths(working_dir, config$DATA$GPSPlannedAgentRoutesDir )))
}
run_blog <- function(blog_code_loc, blog_prog_name, blog_bin_loc, working_dir, odors_input, nerve_agents_input, dispersion_methods_input){
print("blog_code_loc")
print(concat_paths(blog_code_loc, blog_prog_name))
blog_file <- readtext(concat_paths(blog_code_loc, blog_prog_name))
if(!is.null(odors_input)){
odors_selected <- ifelse(!is.na(match(odors, odors_input)), TRUE, FALSE)
}
else{
odors_selected = rep(FALSE, length(odors))
}
if(!is.null(nerve_agents_input)){
agents_selected <- ifelse(!is.na(match(agents, nerve_agents_input)), TRUE, FALSE)
}
else{
agents_selected = rep(FALSE, length(agents))
}
if(!is.null(dispersion_methods_input)){
dispersal_methods_selected <- ifelse(!is.na(match(dispersion_methods, dispersion_methods_input)), TRUE, FALSE)
}
else{
dispersal_methods_selected = rep(FALSE, length(dispersion_methods))
}
names(odors_selected) = odors
names(agents_selected) = agents
names(dispersal_methods_selected) = dispersion_methods
dispersal_str = paste(paste(paste("obs", names(dispersal_methods_selected)), tolower(as.character(dispersal_methods_selected)), sep = '=', collapse = ';\n'),';', sep = '')
agent_str = paste(paste(paste("obs", names(agents_selected)), tolower(as.character(agents_selected)), sep = '=', collapse = ';\n'), ';', sep = '')
odor_str = paste(paste(paste("obs", names(odors_selected)), tolower(as.character(odors_selected)), sep = '=', collapse = ';\n'), ';', sep = '')
#paste all of the selected observations to create the string to write to the blog file
write_string = paste(odor_str, agent_str, dispersal_str, sep = '\n\n')
write_string <- paste(write_string, end_of_file, collapse = '\n')
writeLines(write_string, file(paste(blog_code_loc,"/ChemicalProbablisticReasoning.blog", sep='')))
print('blog_bin_loc')
print(blog_bin_loc)
if(blog_bin_loc != ""){
setwd(blog_bin_loc)
}
blog_code_output <- system2('blog', args=c (paste(blog_code_loc,'/ChemicalProbablisticReasoning.blog',sep='')), stdout= TRUE, wait= TRUE)
setwd(working_dir)
#write the result of the blog program
writeLines(blog_code_output, paste(blog_code_loc,"/output.txt", sep=''))
}
run_java <- function(java_bin_loc, java_code_loc, java_prog_name, working_dir, write_dir, no_ravs, locs, lat_spacing, lng_spacing){
print("java_bin_loc: ")
print(java_bin_loc)
if(!is.null(java_bin_loc)){
if(java_bin_loc != ""){
setwd(java_bin_loc)
}
}
#add jar and code location
#argsString <- paste("-jar", str_replace(java_code_loc, '/', '\\\\'))
argsString <- paste("-jar", java_code_loc)
#pass in the working directory to the java code
print(java_prog_name)
argsString <- paste(argsString, java_prog_name, sep='')
argsString <- paste(argsString, working_dir)
argsString <- paste(argsString, write_dir)
argsString <- paste(argsString, no_ravs)
argsString <- paste(argsString, lat_spacing)
argsString <- paste(argsString, lng_spacing)
#dat$lat <- c(53.28323, 53.28215, 53.27884, 53.27887, 53.28164)
#dat$long <- c(-9.062691,-9.055781,-9.057240,-9.065051,-9.067411)
argsString = paste(argsString, paste(locs$lat, locs$long, sep = ' ', collapse = ' '))
print(paste("Calling java", argsString))
result <<- system2("java", args = c(argsString), stdout = TRUE, wait = TRUE)
print(result)
if(length(result) == 4) {
display_err("Java Error", "Cannot create a polygon with less than 3 vertices.")
}
setwd(working_dir)
return(result)
}
gen_airsim <- function(python_exe, python_code_loc) {
argString <- concat_paths(python_code_loc, "gen_airsim.py")
argString <- paste(python_exe, argString, concat_paths(working_dir, "Config/settings.json"), sep=" ")
print(argString)
system(argString)
}
run_elasticMain <- function(python_exe, python_code_loc, script_name, search_terms){
err_type <- "Elastic Search Error."
print(search_terms)
if(is.null(search_terms)){
display_err(err_type, "Please select a search item.")
return()
}
print("search terms:")
print(search_terms)
#build up args to send to python
argString <- paste(search_terms, collapse = ' ')
argString <- paste(concat_paths(python_code_loc, script_name), argString, collapse = ' ')
print(paste("Calling python with arguments: ", argString))
#run elastic main
result <- system2(python_exe, args = argString)
print(result)
if(result == 1) {
display_err(err_type, "Elastic search is not running correctly, make sure elastic search is running on port 9200.")
}
}<file_sep>/PythonCode/Routing/RouteGeneration/generateRoutesForUnrealUtilsTest.py
import unittest
import sys
sys.path.append('..')
from generateRoutesForUnrealUtils import (generate_close_file_code, generate_image_requests_code, generate_record_gps_loc_code, generate_route_text, generate_save_images_code, generate_save_images_loc, get_connect_and_arm_code, get_imports, get_land_and_disarm_code, get_move_to_gps_position_string, get_recorded_GPS_coords_file, open_gps_coords_code, save_python_to_file)
#some very basic tests, hard-coded some parts
class generateRoutesForUnrealUtilsTest(unittest.TestCase):
def test_generate_save_images_code(self):
saved_images_dir = "C:/Images"
rav_images_dir = "/RAVImages"
drone_number = 1
camera_images_dir = "/Camera1"
file_name = "/image1.png"
#expected_code = "responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene)])"
expected_code = '''
for camera_number, image in enumerate(responses):
AirSimClientBase.write_file("{}", image.image_data_uint8)'''.format(saved_images_dir + rav_images_dir + str(drone_number) + camera_images_dir + file_name)
actual_code = generate_save_images_code(saved_images_dir, rav_images_dir, drone_number, camera_images_dir, file_name)
self.assertEqual(expected_code, actual_code)
def test_generate_image_requests_code(self):
expected_code = '''\nresponses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene), ImageRequest(2, AirSimImageType.Scene)])'''
actual_code = generate_image_requests_code(2)
self.assertEqual(actual_code, expected_code)
def test_get_move_to_gps_position_string(self):
lat, long, altitude = 23.12, -35.87, 50
velocity, sleep_time = 7, 0.5
#this shouldn't be hard-coded..
expected_code = "\nclient.moveToGPSPosition(GPSCoordinate(23.12, -35.87, 50), 7)\ntime.sleep(0.5)\n"
actual_code = get_move_to_gps_position_string(lat, long, altitude, velocity, sleep_time)
self.assertEqual(actual_code, expected_code)
def test_open_gps_coords_code(self):
expected_code = '''
RAVRecordedGPSWaypointsFileHandle = open('D:/Test/Test1.txt', 'w')'''
actual_code = open_gps_coords_code("RAVRecordedGPSWaypointsFileHandle","'D:/Test/Test1.txt'")
self.assertEqual(expected_code, actual_code)
def test_generate_record_gps_loc_code(self):
expected_code = '''
RAVRecordedGPSWaypointsFileHandle.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '/n')'''
actual_code = generate_record_gps_loc_code("client.getGpsLocation().latitude", "client.getGpsLocation().longitude", "RAVRecordedGPSWaypointsFileHandle")
def test_generate_route_text(self):
drone_number = 1
RAV_recorded_GPS_waypoints_dir = "/RAVCollectedData/GPSCoords/RecordedGPSCoords"
RAV_recorded_GPS_waypoints_file_format_str = "/RecordedGPSCoordsAgent{}.txt"
RAV_recorded_GPS_waypoints_relative_dir = "/RAVCollectedData/GPSCoords/RecordedGPSCoordsRelative"
saved_images_dir = "/RAVCollectedData/PNGImages"
rav_images_dir = "/ImagesRAV{}"
camera_images_dir = "/Camera{}"
image_file_format_str = "/image_{}.png"
no_cameras = 1
rav_velocity = 5
rav_altitude = 35
sleep_time = 0.5
images = True
gps_locations=True
lat1, long1, alt1 = 12, 23, 50
vel = 5
expected_code = '''
import io
import time
import os
import sys
#append folder level up to import AirSimClient
sys.path.append('..')
from PIL import Image
from AirSimClient import *
'''+'''
RAVRecordedGPSWaypointsFileHandle = open('/RAVCollectedData/GPSCoords/RecordedGPSCoords/RecordedGPSCoordsAgent1.txt', 'w')
RAVRelativeRecordedGPSWaypointsFileHandle = open('/RAVCollectedData/GPSCoords/RecordedGPSCoordsRelative/RecordedGPSCoordsAgent1.txt', 'w')
'''+'''
port = 41451
print('Creating new client on port: ',41451)
# connect to the AirSim simulator
client = MultirotorClient(port=41451)
''' + '''
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
print('Taking off...')
client.takeoff()
print('Moving clear of tree line')
client.moveToPosition(client.getPosition().x_val, client.getPosition().y_val, client.getPosition().z_val-25, 6)
print('Client position: {}'.format(client.getPosition()))\n
''' + '''
client.moveToGPSPosition(GPSCoordinate({}, {}, {}), {})
'''.format(lat1, long1, alt1, rav_velocity) + '''
time.sleep(1)
responses = client.simGetImages([ImageRequest(3, AirSimImageType.Scene)])''' + '''
for camera_index, image in enumerate(responses):
AirSimClientBase.write_file("/RAVCollectedData/PNGImages/ImagesRAV1/Camera1/image_1.png", image.image_data_uint8)
RAVRecordedGPSWaypointsFileHandle.write('{}, {}\n')
RAVRecordedGPSWaypointsFileHandle.flush()
RAVRelativeRecordedGPSWaypointsFileHandle.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
RAVRelativeRecordedGPSWaypointsFileHandle.flush()
'''.format(lat1, long1) + '''
RAVRecordedGPSWaypointsFileHandle.close()
RAVRelativeRecordedGPSWaypointsFileHandle.close()
client.land()
client.armDisarm(False)
'''
expected_code = expected_code.replace('\n\n', '\n')
actual_code = generate_route_text(drone_number,'''
lat, long, alt
12, 23, 20''',RAV_recorded_GPS_waypoints_dir, RAV_recorded_GPS_waypoints_file_format_str, RAV_recorded_GPS_waypoints_relative_dir, saved_images_dir, rav_images_dir, camera_images_dir, image_file_format_str, no_cameras = 1, rav_velocity = 5, rav_altitude = 35, sleep_time = 0.5, images= True, gps_locations=True).replace('\n\n','\n')
print('expected_code', expected_code)
print('actual_code', actual_code)
self.assertEqual(expected_code, actual_code)
if __name__ == '__main__':
unittest.main()<file_sep>/PythonCode/Routing/AirSimPythonClient/GPS/GPSCoordinate.py
import math
from collections import namedtuple
#theses are just structs
WGS84Ellipsoid = namedtuple("WGS84Ellipsoid", "WGSa WGSb WGSf")
WebMercator = namedtuple("WebMercator", "m1 m2 m3 m4 p1 p2 p3")
#This is outdated! Update with reference to java
class GPSCoordinate:
#m1 = 111132.92;
#m2 = -559.82;
#m3 = 1.175;
#m4 = -0.0023;
#p1 = 111412.84;
#p2 = -93.5;
#p3 = 0.118;
#semi-major axis
#WGSa = 6378137.0;
#semi-minor axis
#WGSb = 6356752.314245;
#reciprocal of flattening
#WGSf = 1 / 298.257223563;
TwoPi = 2.0 * math.pi;
Ellipsoid = WGS84Ellipsoid(6378137.0, 6356752.314245, 1 / 298.257223563)
WebMercatorProjection = WebMercator(111132.92, -559.82, 1.175, -0.0023, 111412.84, -93.5, 0.118)
def __init__(self, lat: float, long: float, alt = 0):
'''by default set the altitude to 0 (i.e. the point is on the earths surface'''
self._lat = lat
self._long = long
self._alt = alt
if not isinstance(lat, float):
try:
self._lat = float(self._lat)
except Exception as e:
raise e
if not isinstance(long, float):
try:
self._long = float(self._long)
except Exception as e:
raise e
if not isinstance(alt, float):
try:
self._alt = float(self._alt)
except Exception as e:
raise e
def __str__(self):
return '{lat}, {lng}, {alt}'.format(lat = self._lat, lng = self._long, alt = self._alt)
def __repr__(self):
return '{lat}, {lng}, {alt}'.format(lat = self._lat, lng = self._long, alt = self._alt)
@staticmethod
def _vincentyGeodesicDirect(coord, distance: float, initialBearing: float):
'''Given a gps coordinate, a desired distance(m) and an initial bearing, returns
the GPS coordinate that is the desired distance and bearing away from coord'''
if not isinstance(coord, self):
raise Exception("{} is not a GPS coordinate".format(coord))
if not isinstance(distance, float):
raise Exception("{} is not a float".format(distance))
if not isinstance(initialBearing, float):
raise Exception("{} is not a float".format(initialBearing))
Phi1 = math.radians(coord.lat)
Lambda1 = math.radians(coord.long);
Alpha1 = math.radians(initialBearing);
s = distance;
a = GPSCoordinate.Ellipsoid.WGSa;
b = GPSCoordinate.Ellipsoid.WGSb;
f = GPSCoordinate.Ellipsoid.WGSf;
sinAlpha1 = math.sin(Alpha1);
cosAlpha1 = math.cos(Alpha1);
tanU1 = (1-f) * math.tan(Phi1)
cosU1 = 1 / math.sqrt((1 + tanU1*tanU1))
sinU1 = tanU1 * cosU1;
Sigma1 = math.atan2(tanU1, cosAlpha1);
sinAlpha = cosU1 * sinAlpha1;
cosSqAlpha = 1 - sinAlpha*sinAlpha;
uSq = cosSqAlpha * (a*a - b*b) / (b*b);
A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
#cos2SigmaM, sinSigma, cosSigma, DeltaSigma;
Sigma = s / (b*A)
iterations = 0;
#hacked do while
cos2SigmaM = math.cos(2*Sigma1 + Sigma);
sinSigma = math.sin(Sigma);
cosSigma = math.cos(Sigma);
DeltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
SigmaPrime = Sigma;
Sigma = s / (b*A) + DeltaSigma;
while (abs(Sigma-SigmaPrime) > 1e-12 and ++iterations<100):
cos2SigmaM = math.cos(2*Sigma1 + Sigma);
sinSigma = math.sin(Sigma);
cosSigma = math.cos(Sigma);
DeltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
SigmaPrime = Sigma;
Sigma = s / (b*A) + DeltaSigma;
if (iterations >= 100):
raise Exception("Formula failed to converge"); #not possible!
x = sinU1*sinSigma - cosU1*cosSigma*cosAlpha1;
Phi2 = math.atan2(sinU1*cosSigma + cosU1*sinSigma*cosAlpha1, (1-f)*math.sqrt(sinAlpha*sinAlpha + x*x));
Lambda = math.atan2(sinSigma*sinAlpha1, cosU1*cosSigma - sinU1*sinSigma*cosAlpha1);
C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
L = Lambda - (1-C) * f * sinAlpha * (Sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
Lambda2 = (Lambda1+L+3*math.pi)%(2*math.pi) - math.pi; # normalise to -180..+180
Alpha2 = math.atan2(sinAlpha, -x);
Alpha2 = (Alpha2 + 2*math.pi) % (2*math.pi); # normalise to 0..360
return GPSCoordinate(math.degrees(Phi2), math.degrees(Lambda2), coord.alt);
@staticmethod
def _vincentyGeodesicInverse(from_coord, to_coord):
'''Given from and to gps coordinates, calculates the distance (m) between them'''
a = GPSCoordinate.Ellipsoid.WGSa
b = GPSCoordinate.Ellipsoid.WGSb
f = GPSCoordinate.Ellipsoid.WGSf
phiOne = math.radians(from_coord.lat);
phiTwo = math.radians(to_coord.lat);
lambdaOne = math.radians(from_coord.long);
lambdaTwo = math.radians(to_coord.long);
L = lambdaTwo - lambdaOne;
tanU1 = (1-f) * math.tan(phiOne);
cosU1 = 1 / math.sqrt((1 + tanU1*tanU1));
sinU1 = tanU1 * cosU1;
tanU2 = (1-f) * math.tan(phiTwo);
cosU2 = 1 / math.sqrt((1 + tanU2*tanU2));
sinU2 = tanU2 * cosU2;
sinSigma=0;
cosSigma=0;
Sigma=0;
cosSqAlpha=0;
cos2SigmaM=0;
Lambda = L
iterations = 0;
antimeridian = abs(L) > math.pi;
#first of do while
break_do_while = False
sinLambda = math.sin(Lambda);
cosLambda = math.cos(Lambda);
sinSqSigma = (cosU2*sinLambda) * (cosU2*sinLambda) + (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda);
if (sinSqSigma == 0):
if (iterations >= 1000):
raise Exception("Formula failed to converge");
uSq = cosSqAlpha * (a*a - b*b) / (b*b);
A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
DeltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
s = b*A*(Sigma-DeltaSigma);
return s
sinSigma = math.sqrt(sinSqSigma);
cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;
Sigma = math.atan2(sinSigma, cosSigma);
sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
cosSqAlpha = 1 - sinAlpha*sinAlpha;
cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha if cosSqAlpha != 0 else 0
#(cosSqAlpha != 0) ? (cosSigma - 2*sinU1*sinU2/cosSqAlpha) : 0; // equatorial line: cosSqAlpha=0 (S6)
C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
LambdaPrime = Lambda;
Lambda = L + (1-C) * f * sinAlpha * (Sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
iterationCheck = abs(Lambda)-math.pi if antimeridian else abs(Lambda)
#antimeridian ? abs(Lambda)-math.pi : abs(Lambda);
if (iterationCheck > math.pi):
raise Exception("Lambda > pi after " + iterations + " iterations.");
while (abs(Lambda-LambdaPrime) > 1e-12 and ++iterations<1000):
sinLambda = math.sin(Lambda);
cosLambda = math.cos(Lambda);
sinSqSigma = (cosU2*sinLambda) * (cosU2*sinLambda) + (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda);
if (sinSqSigma == 0):
break; # co-incident points
sinSigma = math.sqrt(sinSqSigma);
cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;
Sigma = math.atan2(sinSigma, cosSigma);
sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
cosSqAlpha = 1 - sinAlpha*sinAlpha;
cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha if cosSqAlpha != 0 else 0
#(cosSqAlpha != 0) ? (cosSigma - 2*sinU1*sinU2/cosSqAlpha) : 0;
# equatorial line: cosSqAlpha=0 (S6)
C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
LambdaPrime = Lambda;
Lambda = L + (1-C) * f * sinAlpha * (Sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
iterationCheck = abs(Lambda)-math.pi if antimeridian else abs(Lambda)
#antimeridian ? abs(Lambda)-math.pi : abs(Lambda);
#System.out.println("iterationCheck: " + iterationCheck);
if (iterationCheck > math.pi):
raise Exception("Lambda > pi after " + iterations + " iterations.");
if (iterations >= 1000):
raise Exception("Formula failed to converge");
uSq = cosSqAlpha * (a*a - b*b) / (b*b);
A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
DeltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
s = b*A*(Sigma-DeltaSigma);
return s;
def get_initial_bearing(self, end_coordinate):
'''Returns the initial bearing, which if followed in a straight line along a great-circle
arc will take you from the start point to the end point'''
y = math.sin(end_coordinate.long - self.long) * math.cos(end_coordinate.lat)
x = math.cos(self.lat) * math.sin(end_coordinate.lat) - (math.sin(self.lat) * math.cos(end_coordinate.lat) * math.cos(end_coordinate.long - self.long))
bearing = math.atan2(y,x)
return (math.degrees(bearing) + 360) % 360
@property
def lat(self):
return self._lat
@lat.setter
def lat(self, new_lat):
self._lat = new_lat
@property
def long(self):
return self._long
@long.setter
def long(self, new_long):
self._long = new_long
@property
def alt(self):
return self._alt
@alt.setter
def alt(self, new_alt):
self._alt = new_alt
def __str__(self):
return 'Lat: {}\t Long: {}\t Alt: {}'.format(self.lat, self.long, self.alt)
def __sub__(self, other):
return GPSCoordinate(self.lat - other.lat, self.long - other.long, self.alt - other.alt)
def __add__(self, other):
return GPSCoordinate(self.lat + other.lat, self.long + other.long, self.alt + other.alt)
def get_metres_to_other(self, otherCoord):
return GPSCoordinate._vincentyGeodesicInverse(self, otherCoord)
def get_lat_metres_to_other(self, otherCoord):
# delta = self - otherCoord
return GPSCoordinate._vincentyGeodesicInverse(self, GPSCoordinate(otherCoord.lat,self.long))
def get_long_metres_to_other(self, otherCoord):
# delta = self - otherCoord
#return GPSCoordinate.convert_long_degree_difference_to_metres(self.long, otherCoord.long, self.lat)
return GPSCoordinate._vincentyGeodesicInverse(self, GPSCoordinate(self.lat,otherCoord.long))
def get_alt_metres_to_other(self, other_coord):
return self.alt - other_coord.alt
# @staticmethod
# def getMetresBetweenPoints(p1: 'GPSCoordinate', p2: "GPSCoordinate") -> float:
# return math.sqrt(math.pow(p1.get_lat_metres_to_other(p2), 2) + math.pow(p1.get_long_metres_to_other(p2), 2))
@staticmethod
def getMetresBetweenPoints(p1: 'GPSCoordinate', p2: "GPSCoordinate") -> float:
return GPSCoordinate._vincentyGeodesicInverse(p1, p2)
#@staticmethod
#def convert_lat_degree_difference_to_metres(lat1, lat2) -> float:
# return abs(lat1 - lat2) * GPSCoordinate._getLenMetresOneDegreeLat(lat1)
#@staticmethod
#def convert_long_degree_difference_to_metres(long1, long2, lat) -> float:
# return abs(long1 - long2) * GPSCoordinate._getLenMetresOneDegreeLong(lat);
#@staticmethod
#def _getLenMetresOneDegreeLong(lat):
# lat = math.radians(lat);
# return (GPSCoordinate.WebMercatorProjection.p1 * math.cos(lat)) + (GPSCoordinate.WebMercatorProjection.p2 * math.cos(3 * lat)) +\
# (GPSCoordinate.WebMercatorProjection.p3 * math.cos(5 * lat))
#@staticmethod
#def _getLenMetresOneDegreeLat(lat):
# lat = math.radians(lat)
# return (GPSCoordinate.WebMercatorProjection.m1 + (GPSCoordinate.WebMercatorProjection.m2 * math.cos(2 * lat)) + (GPSCoordinate.WebMercatorProjection.m3 * math.cos(4 * lat)) +
# (GPSCoordinate.WebMercatorProjection.m4 * math.cos(6 * lat)))
#
# #run some tests
if __name__ == '__main__':
GPSCoordinate1 = GPSCoordinate(53.2745, -9.049, 0)
GPSCoordinate2 = GPSCoordinate(53.2779115341, -9.0597334278, 0)
print(GPSCoordinate1 - GPSCoordinate2)
print(GPSCoordinate1.lat) # #a 1.1 km walk
print('metres from NUIG to square: {}'.format(GPSCoordinate.getMetresBetweenPoints(GPSCoordinate1, GPSCoordinate2)))
# #metres from NUIG to square: 810.4670076485374<file_sep>/RCode/ShinyApp/ui.R
#
# This is the user-interface definition of a Shiny web application. You can
# run the application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
# install.packages("shiny")
# install.packages("readtext")
# install.packages("stringr")
# install.packages("DT")
# install.packages("shinycssloaders")
# install.packages("shinydashboard")
# install.packages("shinyWidgets")
# install.packages("leaflet")
# install.packages("ggmap")
library(shiny)
library(readtext)
library(stringr)
library(DT)
library(shinycssloaders)
library(shinydashboard)
library(shinyWidgets)
library(leaflet)
library(ggmap)
SOPRetrievalTerms = c('ammonia', 'eye irritation', 'pulmonary agent', 'coughing', 'dead insects',
'americium', 'headache', 'Cs137', 'cobalt', 'plume', 'fever', 'breathing problems',
'nose irritation', 'phosgene', 'dead birds', 'Co60', 'chlorine', 'yellow cloud',
'dead insects', 'gamma', 'green cloud', 'throat irritation',
'Am241', 'cesium', 'nausea', 'apnea')# Define UI for application that draws a histogram
header <- dashboardHeader(tags$li(class = "dropdown",
tags$style(".main-header {max-height: 100px}"),
tags$style(".main-header .logo {height: 100px}")),
title = tags$a(href='http://rocsafe.eu',
tags$img(src='ROCSAFE-Logo.png')), titleWidth = 450)
sidebar <- dashboardSidebar(
sidebarMenu(
tags$style(".left-side, .main-sidebar {padding-top: 100px}"),
menuItem("Bayesian Reasoning Analysis", tabName = "BayesianAnalysis", icon = icon("cogs")),
menuItem("Document Retrieval", tabName = "SOPRetrieval", icon = icon("database")),
menuItem("RAV Mission Planner", tabName = "RAVMissionPlanner", icon = icon("globe")),
menuItem("Image Analysis", tabName = "ImageAnalysis", icon = icon("image"))
)
)
body <- dashboardBody(
tags$style('background-image: url("www/ROCSAFE-logo-final.png"'),
tags$style(type = "text/css", "#map {height: calc(100vh - 80px) !important;}"),
tabItems(
tabItem(tabName = "BayesianAnalysis",
tags$style('background-image: url("ROCSAFE-logo-final.png")'),
sidebarLayout(
sidebarPanel(
checkboxGroupInput("odors", "Check the following odours if they are suspected/confirmed to be present:",
c("Fruity" = "smell_fruity",
"Odourless"= "smell_odourless",
"Camphor" = "smell_camphor",
"Wood" = "smell_wood",
"Chlorine" = "smell_chlorine",
"Mustard Radish Garlic"= "smell_mustard_radish_garlic",
"Unpleasant" = "smell_unpleasant",
"Fish" = "smell_fish",
"Herring" = "smell_herring",
"Soap" = "smell_soap",
"Geranium"="smell_geranium",
"Bitter_almonds"="smell_bitter_almonds",
"Sour"="smell_sour",
"Pungent" ="smell_pungent",
"Apple_blossom" ="smell_apple_blossom",
"Sweet" = "smell_sweet"
)),
checkboxGroupInput("nerve_agents", "Check the following nerve agents if they are suspected/confirmed to be present:",
c("Nerve"="agent_nerve",
"Choking"="agent_choking",
"Blister"="agent_blister",
"Blood"="agent_blood",
"Vomiting"="agent_vomiting",
"Tear"="agent_tear",
"Incapacitating Depressant Hallucinogen"="agent_incapacitating_depressant_hallucinogen"
)),
checkboxGroupInput("dispersion_methods", "Check the following dispersion methods if they are suspected/confirmed to be present:",
c("Liquid"="dispersion_liquid",
"Gas"="dispersion_gas",
"Vapours"="dispersion_vapours",
"Aerosol"="dispersion_aerosol")),
actionButton('do_blog_analysis','Show results of analysis')
),
mainPanel(
setBackgroundImage(src = "www/ROCSAFE-logo-final.png"),
DT::dataTableOutput("distPlot")%>% withSpinner(color="#0dc5c1", size=3)
#htmlOutput("frame")
)
)
),
tabItem(tabName = "SOPRetrieval",
fluidRow(column(width = 3,
selectizeInput("SOPRetrievalInput",width = '1000px', label = "Choose search terms", choices = SOPRetrievalTerms, multiple = TRUE), offset = 4),
column(width = 2, actionButton("RankTerms", label = "Rank terms", style='padding-top:5px; padding-bottom: 5px; margin-top: 26px'), offset = 0)),
br(),
br(),
column(width = 8,htmlOutput("frame")%>% withSpinner(color="#0dc5c1", size=3), offset = 1)
),
tabItem(tabName = "RAVMissionPlanner",
leafletOutput("map", height = 600) %>% withSpinner(color="#0dc5c1", size=3),
fluidRow(
column(width = 2,
actionButton('map_region','Show agent routes', width = "175px"),
offset = 3),
column(width = 2,
actionButton('plot_grid_points', 'Show planned waypoints', width = "175px"),
offset = 0),
column(width = 2,
actionButton("clear_region", 'Clear', width = "175px"),
offset = 0)),
br(),
fluidRow(
column(width = 2,
#switchInput(inputId="DataColletionMode", onLabel = "Demo", offStatus = TRUE, offLabel = "Collect Data", value = TRUE, width = "200px",labelWidth = 200, handleWidth = 200, size = 'large'),
switchInput(inputId="DataColletionMode", label = "Demo", value = FALSE, width = "200px"),
selectInput("no_ravs", label="Choose number of RAVs to be used", choices = c("1", "2", "3")),
selectInput("lat_spacing", label = "Choose the latitude spacing (m)", choices = c(20,25,30,40,50,100), selected = 30),
selectInput("lng_spacing", label = "Choose the longitude spacing (m)", choices = c(20,25,30,40,50,100), selected = 25),
selectInput("num_cameras", label = "Choose the number of cameras to use", choices = c(0,1,2,3,4), selected = 1),
selectInput("rav_altitude", label = "Choose the altitude at which RAVs will fly (m)", choices = c(25, 30, 35, 40), selected = 30),
selectInput("rav_veloctiy", label = "Choose the velocity at which RAVs will fly (m/s)", choices = c(1:10), selected = 3),
actionButton("show_analysis", label="Show analysis"),
actionButton("launch_agents", label = "Execute agent routes"),
offset = 0),
column(width = 5,
verbatimTextOutput("mission_report"),
offset = 2))
),
tabItem(tabName = "ImageAnalysis",
column(width = 5, imageOutput("unprocessed_image")),
column(width = 5, imageOutput("processed_image"))
)
# Application title
# Sidebar with a slider input for number of bins
# Show a plot of the generated distribution
)
)
dashboardPage(header, sidebar, body)<file_sep>/PythonCode/requirements.txt
flask
pillow
configparser
msgpack-rpc-python<file_sep>/PythonCode/Routing/AirSimPythonClient/RAVExecuteRoutes/rav_two_mapper.py
import io
import time
import os
from PIL import Image
from AirSimClient import *
os.chdir('..\..')
print('Working from directory: ', os.getcwd())
gpsCoordsFile = open(os.getcwd() + '\PythonClientGPSMapping\GPSMappings\GPSCoords\GPSCoords3.txt', 'w')
AirSimgpsCoordsFile = open(os.getcwd() + '\PythonClientGPSMapping\GPSMappings\GPSCoords\AirSimGPSCoords3.txt', 'w')
AirSimgpsRelativeCoordsFile = open(os.getcwd() + '\PythonClientGPSMapping\GPSMappings\GPSCoords\AirSimRelativeGPSCoords3.txt', 'w')
port = 41453
print('Creating new client on port: ',41453)
# connect to the AirSim simulator
client = MultirotorClient(port=41453)
print('Confirming connection...')
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
state = client.getGpsLocation()
print("state: %s" % state)
print('Taking off...')
client.takeoff()
#wait before taking off
time.sleep(0.5)
print('Moving clear of tree line')
client.moveToPosition(client.getPosition().x_val, client.getPosition().y_val, client.getPosition().z_val-25, 6)
print('Client position: {}'.format(client.getPosition()))
client.moveToGPSPosition(GPSCoordinate(53.27980000000000160298441187478601932525634765625, -9.056499999999999772626324556767940521240234375, 35), 7)
time.sleep(1)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_0.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_0.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.27980000000000160298441187478601932525634765625, -9.056499999999999772626324556767940521240234375\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2799150529579982395938714034855365753173828125, -9.0619885920718505859375000000000000000000000000000, 35), 5)
time.sleep(2)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_1.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_1.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2799150529579982395938714034855365753173828125, -9.0619885920718505859375000000000000000000000000000\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2799150529579982395938714034855365753173828125, -9.0623593329718505859375000000000000000000000000000, 35), 5)
time.sleep(2)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_2.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_2.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2799150529579982395938714034855365753173828125, -9.0623593329718505859375000000000000000000000000000\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2799150529579982395938714034855365753173828125, -9.0627300738718505859375000000000000000000000000000, 35), 5)
time.sleep(2)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_3.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_3.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2799150529579982395938714034855365753173828125, -9.0627300738718505859375000000000000000000000000000\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2799150529579982395938714034855365753173828125, -9.0631008147718505859375000000000000000000000000000, 35), 5)
time.sleep(2)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_4.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_4.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2799150529579982395938714034855365753173828125, -9.0631008147718505859375000000000000000000000000000\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796787731579982395938714034855365753173828125, -9.0631008147718505859375000000000000000000000000000, 35), 5)
time.sleep(2)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_5.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_5.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2796787731579982395938714034855365753173828125, -9.0631008147718505859375000000000000000000000000000\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796787731579982395938714034855365753173828125, -9.0627300738718505859375000000000000000000000000000, 35), 5)
time.sleep(2)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_6.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_6.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2796787731579982395938714034855365753173828125, -9.0627300738718505859375000000000000000000000000000\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2796787731579982395938714034855365753173828125, -9.0623593329718505859375000000000000000000000000000, 35), 5)
time.sleep(2)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_7.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_7.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2796787731579982395938714034855365753173828125, -9.0623593329718505859375000000000000000000000000000\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794424933579982395938714034855365753173828125, -9.0623593329718505859375000000000000000000000000000, 35), 5)
time.sleep(2)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_8.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_8.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2794424933579982395938714034855365753173828125, -9.0623593329718505859375000000000000000000000000000\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794424933579982395938714034855365753173828125, -9.0627300738718505859375000000000000000000000000000, 35), 5)
time.sleep(2)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_9.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_9.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2794424933579982395938714034855365753173828125, -9.0627300738718505859375000000000000000000000000000\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794424933579982395938714034855365753173828125, -9.0631008147718505859375000000000000000000000000000, 35), 5)
time.sleep(2)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_10.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_10.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2794424933579982395938714034855365753173828125, -9.0631008147718505859375000000000000000000000000000\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2794424933579982395938714034855365753173828125, -9.0634715556718505859375000000000000000000000000000, 35), 5)
time.sleep(2)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_11.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_11.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2794424933579982395938714034855365753173828125, -9.0634715556718505859375000000000000000000000000000\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
client.moveToGPSPosition(GPSCoordinate(53.2801513327579982395938714034855365753173828125, -9.0619885920718505859375000000000000000000000000000, 35), 5)
time.sleep(2)
responses = client.simGetImages([
ImageRequest(3, AirSimImageType.Scene)
])
print('Writing files to ', os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_12.png".format('example'))
for image_index, image in enumerate(responses):
AirSimClientBase.write_file(os.getcwd() + "\PythonClientGPSMapping\GPSMappings\Images\Images3\Camera{}\image_12.png".format(image_index+1) , image.image_data_uint8)
gpsCoordsFile.write('53.2801513327579982395938714034855365753173828125, -9.0619885920718505859375000000000000000000000000000\n')
gpsCoordsFile.flush()
AirSimgpsCoordsFile.write(str(client.getGpsLocation().latitude)+', '+str(client.getGpsLocation().longitude) + '\n')
AirSimgpsCoordsFile.flush()
AirSimgpsRelativeCoordsFile.write(str(client.getGPSLocationRelative().lat)+', '+ str(client.getGPSLocationRelative().long)+'\n')
AirSimgpsRelativeCoordsFile.flush()
print('NUIG relative GPS location: ', client.getGPSLocationRelative())
gpsCoordsFile.close()
AirSimgpsCoordsFile.close()
AirSimgpsRelativeCoordsFile.close()
<file_sep>/PythonCode/Routing/AirSimPythonClient/GPS/GPSToUnreal.py
import sys
sys.path.append('..')
from GPSCoordinate import GPSCoordinate
class GPSToUnreal:
# this is taken as origin (0,0)
# EYRE_SQUARE_COORD = GPSCoordinate(53.2745, -9.049, 0)
# NUIG
# EYRE_SQUARE_COORD = GPSCoordinate(53.276, -9.057, 0)
# not quite eyre square, but close enough!
#HOME_COORD = GPSCoordinate(53.280, -9.062, 0)
ORIGIN_GPS = GPSCoordinate(47.641468, -122.140165, 122)
# transormation that maps a GPS position from the microsoft office origin
# to the Eyre square coordinate
#DELTA_TRANSFORM = HOME_COORD - ORIGIN_GPS
# home_position_GPS is the home gps location of the drone in AirSim
def __init__(self, home_position_GPS: GPSCoordinate = GPSCoordinate(53.2793, -9.0638)):
'''Set the home gps coordinate of the rav'''
self.home_position_GPS = home_position_GPS
def getMoveToPosXYZFromGPSCoord(self, desired_GPS_position: GPSCoordinate):
'''Returns the XYZ Unreal Engine NED coordinatee position to move to in order to reach the desired gps position'''
if not isinstance(desired_GPS_position, GPSCoordinate):
raise Exception("Please provide a valid WGS84 GPS coordinate")
metres_lat = self.home_position_GPS.get_lat_metres_to_other(desired_GPS_position)
metres_long = self.home_position_GPS.get_long_metres_to_other(desired_GPS_position)
metres_alt = self.home_position_GPS.get_alt_metres_to_other(desired_GPS_position)
#check whether the lat/long difference is positive or negative (metres to other methods give abs values)
if desired_GPS_position.lat < self.home_position_GPS.lat:
metres_lat =- metres_lat
if desired_GPS_position.long < self.home_position_GPS.long:
metres_long =- metres_long
#altitudes in games engine are negative
return (metres_lat, metres_long, -abs(metres_alt))
def get_GPS_Pos(self, microsoft_relative_GPS_pos: GPSCoordinate):
'''AirSim calculates GPS position in relation to microsoft headquarters,
this method gives the GPS position relative to the home coordinate set by the constructor.'''
#calculate lat, long distance from current position to microsoft home coordinate
if not isinstance(microsoft_relative_GPS_pos, GPSCoordinate):
raise Exception("Please provide a valid WGS84 GPS coordinate")
#metres_lat = microsoft_relative_GPS_pos.get_lat_metres_to_other(GPSToUnreal.ORIGIN_GPS)
#metres_lng = microsoft_relative_GPS_pos.get_long_metres_to_other(GPSToUnreal.ORIGIN_GPS)
#if microsoft_relative_GPS_pos.lat < GPSToUnreal.ORIGIN_GPS.lat:
# metres_lat =- lat_dist
#if microsoft_relative_GPS_pos.long < GPSToUnreal.ORIGIN_GPS.long:
# metres_lat =- lng_dist
#if microsoft_relative_GPS_pos.alt:
# metres_alt = microsoft_relative_GPS_pos.alt
#then add this distance to home coordinate
#first calculate azimuth (will probably be ok to do this as dealing with small(ish) angles
bearing = GPSToUnreal.ORIGIN_GPS.get_initial_bearing(microsoft_relative_GPS_pos)
distance = microsoft_relative_GPS_pos.get_metres_to_other(GPSToUnreal.ORIGIN_GPS)
destination = GPSCoordinate._vincentyGeodesicDirect(self.home_position_GPS, distance, bearing)
return destination
#47.641468, -122.140165
#47.6477308, -122.1321476
#return GPSToUnreal.geoPoint_to_GPSCoordinate(microsoft_relative_GPS_pos) + GPSToUnreal.DELTA_TRANSFORM
<file_sep>/PythonCode/Routing/AirSimPythonClient/GPS/UE4Coord.py
class UE4Coord:
'''A coordinate which represents an objects location in an unreal engine environment'''
def __init__(self, x, y, z = 0):
self.x, self.y, self.z = x, y, z
if not isinstance(self.x, float):
try:
self.x = float(self.x)
except Exception as e:
raise(e)
if not isinstance(self.y, float):
try:
self.y = float(self.y)
except Exception as e:
raise(e)
if not isinstance(self.z, float):
try:
self.z = float(self.z)
except Exception as e:
raise(e)
def __add__(self, other):
return UE4Coord(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return UE4Coord(self.x - other.x, self.y - other.y, self.z - other.z)
def mul(self, int):
pass
def get_dist_to_other(self, other):
return ((self.x - other.x)**2 + (self.y - other.y)**2 + (self.z - other.z)**2)**0.5
def __eq__(self, other):
if self.x == other.x and self.y == other.y and self.z == other.z:
return True
else:
return False
def __str__(self):
return '{x}, {y}, {z}'.format(x = self.x, y = self.y, z = self.z)
def __repr__(self):
return '{x}, {y}, {z}'.format(x = self.x, y = self.y, z = self.z)<file_sep>/PythonCode/Routing/AirSimPythonClient/GPS/GPSToUnrealTest.py
#stdlib imports
import unittest
import sys
sys.path.append('..')
#3rd party imports
#user defined imports
from GPSToUnreal import GPSToUnreal
from GPSCoordinate import GPSCoordinate
class TestGPSToUnreal(unittest.TestCase):
def setUp(self):
self.OConnellStreetCoordinate = GPSCoordinate(53.3512416, -6.2629676, 0)
self.EyreSquareCoordinate = GPSCoordinate(53.2743394, -9.0514163)
self.NUIGCoordinate = GPSCoordinate(53.2809159, -9.0692133, 20)
def testGetMoveToPosXYZFromGPSCoord(self):
mapper1 = GPSToUnreal(self.NUIGCoordinate)
UECoord1 = mapper1.getMoveToPosXYZFromGPSCoord(self.EyreSquareCoordinate)
#nuig coordinate to eyre square coordinate
self.assertAlmostEqual(UECoord1[0], -731.3, delta = 10)
self.assertAlmostEqual(UECoord1[1], 1183, delta = 20)
#check that signs change
mapper2 = GPSToUnreal(self.EyreSquareCoordinate)
UECoord2 = mapper2.getMoveToPosXYZFromGPSCoord(self.NUIGCoordinate)
self.assertAlmostEqual(UECoord2[0], 730, delta = 20)
self.assertAlmostEqual(UECoord2[1], -1183, delta = 20)
nuigRectCoord1 = GPSCoordinate(53.2787637762, -9.0634679794)
nuigRectCoord2 = GPSCoordinate(53.2787637762, -9.0601420403)
nuigRectCoord3 = GPSCoordinate(53.2810987761, -9.0601420403)
nuigRectCoord4 = GPSCoordinate(53.2810987761, -9.0634679794)
mapper3 = GPSToUnreal(GPSCoordinate(53.280, -9.062, 0))
rect_coords = [nuigRectCoord1, nuigRectCoord2, nuigRectCoord3, nuigRectCoord4]
for coord in rect_coords:
print(mapper1.getMoveToPosXYZFromGPSCoord(coord))
def testGet_GPS_Pos(self):
mapper1 = GPSToUnreal(self.NUIGCoordinate)
#pos = mapper1.get_GPS_Pos()
redmond_campus_coord = GPSCoordinate(47.6477308, -122.1321476)
#should be 696 m lat, 600 long
#close enough
print(mapper1.get_GPS_Pos(redmond_campus_coord))
# self.assertAlmostEqual(OConnellStreetCoordinate.getMetresBetweenPoints(EyreSquareCoordinate),186270 delta = 5000)
# self.assertAlmostEqual(NUIGCoordinate.getMetresBetweenPoints(EyreSquareCoordinate),836 delta = 50)<file_sep>/RCode/ShinyApp/server.R
#
# This is the server logic of a Shiny web application. You can run the
# application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
# install.packages("shiny")
# install.packages("readtext")
library(shiny)
library(readtext)
library(ini)
source("utils.R")
#set the working directory to the top level
#working_dir = getwd()
working_dir <<- paste(getwd(), '/../..', sep = '')
setwd(working_dir)
print(paste("Working directory: ",getwd()))
#move all of this to a config file
config <<- read.ini("Config/config.ini")
clickedLocs <<- data.frame(lat=numeric(),lng=numeric())
names(clickedLocs) <- c("lat", "long")
#rav_positions <- data.frame("lat" = c(53.28, 53.286, 53.2798, 53.2793),
# "long" = c(-9.07, -9.0588, -9.0565, -9.0638),
# "text" = c("RAV1", "RAV2", "RAV3", "HOME POSITION"))
rav_positions <- data.frame("lat" = c(53.28, 53.283, 53.279, 53.275),
"long" = c(-9.07, -9.0588, -9.0565, -9.0638),
"text" = c("RAV1", "RAV2", "RAV3", "HOME POSITION"))
#bottom right, top right, top left, bottom left
bounding_rect <- data.frame("lat" =c(53.27959959,53.2805257315, 53.2801009832, 53.2791748417),
"long" = c(-9.0617270785, -9.0621271428, -9.0648776011, -9.0644775368))
get_lats = function(str){
return()
}
data_collection_rect <<- data.frame("lat" = c(53.2786520051, 53.2810475529, 53.2811390512, 53.2787435086),
"long" = c(-9.0647555694,-9.0649387627,-9.0615917771,-9.0614085838))
agent_route_analysis <<- ""
f_snapshot_old <<- fileSnapshot(concat_paths(working_dir, config$DATA$UIImagesDir), md5sum = TRUE)
#routes <<- ""
#Here's one we prepared earlier :P!
#dat$lat <- c(53.28323, 53.28215, 53.27884, 53.27887, 53.28164)
#dat$long <- c(-9.062691,-9.055781,-9.057240,-9.065051,-9.067411)
shinyServer(function(input, output, session) {
#check for new images every 10 seconds
autoInvalidate <- reactiveTimer(10000)
update_images <- reactiveVal(value = 0)
update_sops <- reactiveVal(value = 0)
agent_route_analysis_flag <- reactiveVal(value = 0)
blog_chem_likelihood_output <- eventReactive(input$do_blog_analysis,{
showNotification("Calculating likelihoods of threat", duration = 8, type = "message")
run_blog(concat_paths(working_dir,config$BLOG$BlogCodeLoc), config$BLOG$BlogProgName, concat_paths(working_dir, config$BLOG$BlogBinLoc), working_dir, isolate(input$odors), isolate(input$nerve_agents), isolate(input$dispersion_methods))
#print(concat_paths(working_dir, config$BLOG$BlogCodeLoc,"/output.txt"))
file = readtext(concat_paths(working_dir, config$BLOG$BlogCodeLoc,"/output.txt"))$text
#relevant_data = strsplit(file, 'Query Results')
x <- str_split(file, "Query Results", 2, TRUE)
#31 chemicals
chems <- lapply(str_split(x[2], "Distribution", 32, TRUE), function(x) substr(str_extract(x,"for ([a-z].*)"),5, nchar(str_extract(x,"for ([a-z].*)"))))
values_false <- lapply(str_split(x[2], "Distribution", 32, TRUE), function(x) substr(str_extract(x,"false\t[0-9].[0-9].*"),7, nchar(str_extract(x,"false\t[0-9].[0-9].*"))))
values_true <- lapply(str_split(x[2], "Distribution", 32, TRUE), function(x) substr(str_extract(x,"true\t[0-9].[0-9].*"),6, nchar(str_extract(x,"true\t[0-9].[0-9].*"))))
df <- data.frame('Chemical Name'=unlist(chems), 'Probability not present' = unlist(as.numeric(values_false)), 'Probability present' = unlist(as.numeric(values_true)))
df <- df[-c(1),]
rownames(df) <- seq(length = nrow(df))
brks <- quantile(df$Probability.present, probs = seq(0, 1, .05), na.rm = TRUE)
clrs <- round(seq(255, 40, length.out = length(brks) + 1), 0) %>%
{paste0("rgb(255,", ., ",", ., ")")}
df <- df[order(df$Probability.not.present, decreasing = FALSE),]
datatable(df) %>% formatStyle('Probability.present', backgroundColor = styleInterval(brks, clrs))
})
#Renders the data table for BLOG calculated threat likelihood
output$distPlot <- DT::renderDataTable({
#input$do_analysis
blog_chem_likelihood_output()
})
#Displays Brett's document retrieval procedure
output$frame <- renderUI({
update_sops()
tags$iframe(src="http://127.0.0.1:5000/", height=400, width=1400, frameBorder = 0)
#my_test <- tags$iframe(src="http://127.0.0.1:5000/", height=400, width=1400, frameBorder = 0)
#my_test
})
observeEvent(input$plot_grid_points,{
#hard code in data collection region
print('data collection mode: ')
print(isolate(input$DataColletionMode))
if(isolate(input$DataColletionMode)){
showNotification(paste("Using pre-defined rectangle to gather images: ", clickedLocs))
#clickedLocs <<- data.frame("lat" = c(53.2780931659, 53.2804041456, 53.281325917, 53.2790149872),
# "long" = c( -9.0648465368, -9.0661543305, -9.0615979824, -9.0602901886))
clickedLocs <<- data_collection_rect
}
agent_route_analysis<<-run_java(config$JAVA$JavaBinLoc, concat_paths(working_dir, config$JAVA$JavaCodeLoc), config$JAVA$JavaMissionDesignerJar, working_dir, config$DATA$PlannedAgentRoutesDir, isolate(input$no_ravs), clickedLocs, isolate(input$lat_spacing), isolate(input$lng_spacing))
print("found analysis")
#notify app that analysis can be displayed
agent_route_analysis_flag(agent_route_analysis_flag() + 1)
print(agent_route_analysis)
#grid_points <- read.csv("./RCode/ShinyApp/Data/gridPoints.csv", header = TRUE)
grid_points <- read.csv(concat_paths(working_dir, config$DATA$GPSPlannedAgentRoutesDir, config$DATA$RAVPlannedWaypointsFile), header = TRUE)
leafletProxy('map') %>% addPolygons(lng = clickedLocs$long, lat = clickedLocs$lat) %>% addCircles(lng = grid_points$long, lat = grid_points$lat, weight=1, radius=7, color='black', fillColor='orange', popup = paste(grid_points$lat, grid_points$long))
})
output$mission_report <- renderText({
input$show_analysis
print("Displaying analysis")
paste(agent_route_analysis, sep = '', collapse = '\n')
})
output$map <- renderLeaflet({
leaflet() %>%
setView(lng = -9.0615, lat = 53.2770, zoom = 15) %>%
addTiles(options = providerTileOptions(noWrap = TRUE)) %>%
addMarkers(lng = rav_positions$long, lat = rav_positions$lat, icon = RAVIcon) #%>%
#addPolygons(lng = bounding_rect$long, lat = bounding_rect$lat, opacity = 0.2, color = '#ff0000')
})
observeEvent(input$clear_region, {
clickedLocs<<-clickedLocs[0,]
leafletProxy('map') %>% clearShapes() %>% clearMarkers() %>%
addMarkers(lng = rav_positions$long, lat = rav_positions$lat, icon = RAVIcon) #%>%
#addPolygons(lng = bounding_rect$long, lat = bounding_rect$lat, opacity = 0.2, color = '#ff0000')
})
observeEvent(input$map_region, {
print("request issued to map region")
##add the last row to complete the polygon
rbind(clickedLocs, clickedLocs[1,])
#draw the polygon
leafletProxy('map') %>% addPolygons(lng = clickedLocs$long, lat = clickedLocs$lat) %>%
addMarkers(lng = rav_positions$long, lat = rav_positions$lat, icon = RAVIcon)
#hard code in data collection region
if(isolate(input$DataColletionMode)){
showNotification(paste("Using pre-defined rectangle to gather images: ", clickedLocs))
#clickedLocs <<- data.frame("lat" = c(53.2780931659, 53.2804041456, 53.281325917, 53.2790149872),
# "long" = c( -9.0648465368, -9.0661543305, -9.0615979824, -9.0602901886))
clickedLocs <<- data_collection_rect
}
#if(is.null(config$JAVA$JavaBinLoc)){
#assume that correct java version is installed
# config$JAVA$JavaBinLoc = "java"
#}
#get the java script to generate the routes for each rav
#java_bin_loc, java_code_loc, java_prog_name, working_dir, no_ravs, locs, lat_spacing, lng_spacing
#cat(paste0(concat_paths(working_dir, config$JAVA$JavaBinLoc), concat_paths(working_dir, config$JAVA$JavaCodeLoc), config$JAVA$JavaMissionDesignerJar, working_dir, isolate(input$no_ravs), clickedLocs, isolate(input$lat_spacing), isolate(input$lng_spacing)))
agent_routes <- run_java(config$JAVA$JavaBinLoc, concat_paths(working_dir, config$JAVA$JavaCodeLoc), config$JAVA$JavaMissionDesignerJar, working_dir, config$DATA$PlannedAgentRoutesDir, isolate(input$no_ravs), clickedLocs, isolate(input$lat_spacing), isolate(input$lng_spacing))
color_map <- c("blue","green","red")
names(color_map) <- c(1,2,3)
#check that agent routes exist
#then loop over number of agents and display planned routes on map
# #read the csvs that contain the routes for each agent
#points1 <-read.csv("./RCode/ShinyApp/Data/Agent1.csv", header = TRUE)
points1 <- read.csv(concat_paths(working_dir, config$DATA$RAVGPSRoutesDir, "/Agent1.csv"))
leafletProxy('map') %>% addCircles(lng = points1$long, lat = points1$lat, weight=1, radius=7, color='black', fillColor='blue', popup = paste("RAV1",paste(points1$lat, points1$long))) %>% addPolylines(lng = points1$long, lat = points1$lat, weight=1, color='blue', fillColor='blue')
if(isolate(input$no_ravs) > 1){
#points2 <- read.csv("./RCode/ShinyApp/Data/Agent2.csv")
points2 <- read.csv(concat_paths(working_dir, config$DATA$RAVGPSRoutesDir, "/Agent2.csv"))
leafletProxy('map') %>% addCircles(lng = points2$long, lat = points2$lat, weight=1, radius=7, color='black', fillColor='green', popup = paste("RAV2",paste(points2$lat, points2$long))) %>% addPolylines(lng = points2$long, lat = points2$lat, weight=1, color='green', fillColor='green')
}
if(isolate(input$no_ravs) > 2){
#points3 <- read.csv("./RCode/ShinyApp/Data/Agent3.csv")
points3 <- read.csv(concat_paths(working_dir, config$DATA$RAVGPSRoutesDir, "/Agent3.csv"))
leafletProxy('map') %>% addCircles(lng = points3$long, lat = points3$lat, weight=1, radius=7, color='black', fillColor='red', popup = paste("RAV3",paste(points3$lat, points3$long))) %>% addPolylines(lng = points3$long, lat = points3$lat, weight=1,color='red', fillColor='red')
}
})
observeEvent(input$launch_agents,{
# input = list()
# input$no_ravs = 4
# input$num_cameras = 4
# input$rav_veloctiy = 20.4
# input$rav_altitude = 37
#run generate_routes.py in order to generate routes for agents
###################### Put all of this into utils.py ######################
setwd(concat_paths(working_dir, config$PYTHON$PythonRAVRouteExecutionDir))
#setwd(paste(working_dir,"/PythonCode/PythonGridMapping/RoutePlotting", sep='', collapse=''))
#generateUnrealPlotRoutes - no_ravs, no_cameras, rav_route_write_dir, saved_images_dir, gps_coords_write_dir
gen_route_command <- paste(concat_paths(working_dir, config$PYTHON$PythonGenerateRouteDir, config$PYTHON$PythonGenerateRoutesFileLoc), isolate(input$no_ravs), isolate(input$num_cameras), isolate(input$rav_veloctiy), isolate(input$rav_altitude), collapse='')
print(paste("running python command", gen_route_command))
system2("python", args = c(gen_route_command))
###################### Put all of this into utils.py ######################
showNotification("Agents ready to execute planned routes", duration = 10, type = "message")
setwd(concat_paths(working_dir, config$BATCHSCRIPTS$BatchScriptsLoc))
noDrones = ifelse(isolate(input$no_ravs) == 1, "one", ifelse(isolate(input$no_ravs)==2, "two", "three"))
system2(paste(noDrones,"_drone.bat", sep="", collapse=""))
setwd(working_dir)
showNotification("RAVs executing planned routes in games engine")
})
## Observe mouse clicks and add circles
observeEvent(input$map_click, {
## Get the click info like had been doing
click <- input$map_click
clat <- click$lat
clng <- click$lng
address <- revgeocode(c(clng,clat))
clickedLocs <<- rbind(clickedLocs,c(as.numeric(clat), as.numeric(clng)))
names(clickedLocs) <<- c("lat", "long")
print("clickedLocs")
print(clickedLocs)
## Add the circle to the map proxy
## so you dont need to re-render the whole thing
## I also give the circles a group, "circles", so you can
## then do something like hide all the circles with hideGroup('circles')
returnMap <- leafletProxy('map') %>% # use the proxy to save computation
addCircles(lng=clng, lat=clat, group='circles',
weight=1, radius=8, color='black', fillColor='orange',
popup=address, fillOpacity=0.5, opacity=1)
if(nrow(clickedLocs)>0){
returnMap %>%addPolylines(data = clickedLocs, lng = ~long, lat = ~lat, weight = 2)
}
returnMap
})
output$processed_image <- renderImage({
update_images()
list(src = concat_paths(working_dir, config$DATA$UIImagesDir,config$DATA$MostRecentProcessImageFileLoc),
contentType = 'image/png',
width = 750,
height = 750,
alt = "No collected images to show")
}, deleteFile = FALSE)
output$unprocessed_image <- renderImage({
update_images()
list(src = concat_paths(working_dir, config$DATA$UIImagesDir, config$DATA$MostRecentImageRawFileLoc),
contentType = 'image/png',
width = 600,
height = 600,
alt = "No collected images to show")
}, deleteFile = FALSE)
observe({
autoInvalidate()
print("autoInvalidating")
print(Sys.time())
f_snapshot_new <<- fileSnapshot(concat_paths(working_dir, config$DATA$UIImagesDir), md5sum = TRUE)
#need to check that f_snapshots are not null so changes can be compared
if(!is.null(dim(f_snapshot_new)) && !is.null(dim(f_snapshot_old))){
if(TRUE %in% changedFiles(f_snapshot_old, f_snapshot_new)$changes){
#set flag to update images
update_images(update_images() + 1)
}
}
f_snapshot_old <<- f_snapshot_new
})
observeEvent(input$RankTerms, {
print("Ranking user terms")
value <- run_elasticMain(isolate(input$SOPRetrievalInput))
update_sops(update_sops() + 1)
})
observe({
print(input$DataColletionMode)
if(input$DataColletionMode){
updateSelectInput(session, "no_ravs", label="Choose number of RAVs to be used", choices = c(1:20), selected = 1)
updateSelectInput(session, "lat_spacing", label = "Choose the latitude spacing (m)", choices = c(1:500)/2, selected = 20)
updateSelectInput(session, "lng_spacing", label = "Choose the longitude spacing (m)", choices = c(1:500)/2, selected = 20)
#any more than 10 would definitely cause gpu to crash...
updateSelectInput(session, "num_cameras", label = "Choose the number of cameras to use", c(0:10), selected = 2)
updateSelectInput(session, "rav_altitude", label = "Choose the altitude at which RAVs will fly (m)", choices = c(1:400)/2, selected = 30)
updateSelectInput(session, "rav_veloctiy", label = "Choose the velocity at which RAVs will fly (m/s)", choices = c(1:80)/5, selected = 3)
}
else{
updateSelectInput(session, "no_ravs", label="Choose number of RAVs to be used", choices = c("1", "2", "3"), selected = 1)
updateSelectInput(session, "lat_spacing", label = "Choose the latitude spacing", choices = c(20,25,30,40,50,100), selected = 20)
updateSelectInput(session, "lng_spacing", label = "Choose the longitude spacing", choices = c(20,25,30,40,50,100), selected = 25)
updateSelectInput(session, "num_cameras", label = "Choose the number of cameras to use", choices = c(0,1,2,3,4), selected = 1)
updateSelectInput(session, "rav_altitude", label = "Choose the altitude at which RAVs will fly (m)", choices = c(25, 30, 35, 40), selected = 30)
updateSelectInput(session, "rav_veloctiy", label = "Choose the velocity at which RAVs will fly (m/s)", choices = c(1:10), selected = 3)
}
})
})<file_sep>/RCode/README.md
# IJCAIRDemoCode
<file_sep>/Config/config.ini
[JAVA]
; java related file paths and directories
JavaBinLoc=
JavaCodeLoc=/JavaCode
JavaMissionDesignerJar=/generateCoordinatesRevised.jar
[BLOG]
; BLoG (Bayesian LOGic related file paths and directories)
BlogBinLoc=
BlogCodeLoc=/BlogCode
BlogProgName=/ChemicalProbablisticReasoning.blog
[ELASTICSEARCH]
ElasticSearchBinLoc=elasticsearch-6.3.0/elasticsearch-6.3.0/bin
[UE4]
UE4Game=WindowsNoEditor/OS_01RadiationIntegr.exe
[R]
RVersion=C:/Program Files/R/R-3.5.0/bin/R.exe
[PYTHO]N
;virtual environment location - leave blank to use base installation
PythonVersion=D:/TempFiles/CBRNeVirtualEnvironment/Scripts/python.exe
;Brett's demo related related file paths and directories
PythonDocRetrievalCodeLoc=/SOPRanking/RocsafeCode/Demo-IR
PythonElasticMain=/search_and_rank.py
; directory where python routes can be executed from
PythonRAVRouteExecutionDir=/PythonCode/Routing/AirSimPythonClient/RAVExecuteRoutes
; directory where code takes planned GPS coordinates to visit and writes files in
; python api format
PythonGenerateRouteDir=/PythonCode/Routing/RouteGeneration
PythonGenerateRoutesFileLoc=/generateRoutesForUnreal.py
[BATCHSCRIPTS]
; batch script related file paths and directories
BatchScriptsLoc=Scripts/Windows
[BASHSCRIPTS]
;
BashScriptsLoc=Scripts/Unix
[DATA]
; stored data will reside in these files/directories
;this is correct RAVGPSRoutesDir=/RAVPlannedRoutes
RAVGPSRoutesDir=/RCode/ShinyApp/Data
;data related to the images collected by the rav
CollectedPNGImagesDir=/RAVCollectedData/PNGImages
CollectedJPGImagesDir=/RAVCollectedData/JPGImagesWithExif
RAVImagesDirFormatStr=/ImagesRAV{}
CameraImagesDirFormatStr=/Camera{}
ImagesFileFormatStr=/image_{}.png
;data related to the waypoint recorded as being visited by RAV
RAVRecordedGPSWaypointsDir=/RAVCollectedData/GPSCoords/RecordedGPSCoords
RAVRecordedRelativeGPSWaypointsDir=/RAVCollectedData/GPSCoords/RecordedGPSCoordsRelative
RAVRecordedGPSWaypointsFileFormatStr=/RecordedGPSCoordsAgent{}.txt
RAVPlannedWaypointsFile=/gridPoints.csv
; this is the correct line GPSPlannedAgentRoutesDir=/RAVPlannedRoutes/GPSPlannedRoutes
GPSPlannedAgentRoutesDir=/RCode/ShinyApp/Data
;RAVPlannedRoutes/UEPlannedRoutes
; Data related to the shiny UI
UIImagesDir=/RCode/ShinyApp/Data/Images
MostRecentProcessImageFileLoc=/mostRecentImageProcessed.jpg
MostRecentImageRawFileLoc=/mostRecentImageProcessed.jpg
<file_sep>/PythonCode/Routing/RouteGeneration/generateUnrealCoordinatesFromGPS.py
import sys
sys.path.append('../../Routing/AirSimPythonClient/GPS')
from GPSToUnreal import GPSToUnreal
from GPSCoordinate import GPSCoordinate
from UE4Coord import UE4Coord
def read_GPS_coords(gps_coords_file_path) -> "A list of gps coords":
'''Reads in a list of gps coordinates'''
try:
#read file but skip header
gps_coords = open(gps_coords_file_path, 'r').readlines()[1:]
except FileNotFoundError as e:
#don't handle this for now...
raise e
try:
gps_coords = [GPSCoordinate(coord.replace('\n','').split(',')[0], coord.replace('\n','').split(',')[1], coord.replace('\n','').split(',')[2])for coord in filter(lambda gps_coord: gps_coord != '\n', gps_coords)]
except IndexError as e:
#don't handle for now
gps_coords = [GPSCoordinate(coord.replace('\n','').split(',')[0], coord.replace('\n','').split(',')[1]) for coord in filter(lambda gps_coord: gps_coord != '\n', gps_coords)]
print('gps_coords: ',gps_coords)
return gps_coords
def write_UE4_coords(ue4_coords_file_path, UE4_coords: "a list of UE4 Coordinates"):
with open(ue4_coords_file_path, 'w') as out_file:
#write header
out_file.write('x, y, z\n')
for UE4_coord in UE4_coords:
print(UE4_coord)
out_file.write(UE4_coord.__str__())
out_file.write('\n')
class GenerateUECoordsFromGPS:
def __init__(self, home_position_GPS: GPSCoordinate = GPSCoordinate(53.2793, -9.0638), home_position_UE4 = UE4Coord(0,0,0)):
#set home gps position
self.home_position_GPS = home_position_GPS
self.home_position_UE4 = home_position_UE4
self.GPS_to_unreal_converter = GPSToUnreal(home_position_GPS)
def convert_GPS_to_UE4(self,gps_coordinate):
return UE4Coord(*self.GPS_to_unreal_converter.getMoveToPosXYZFromGPSCoord(gps_coordinate)) + self.home_position_UE4
def convert_GPS_list_to_UE4(self, gps_coordinates: "a list of gpscoordinates"):
ue4_coords = []
for gps_coordinate in gps_coordinates:
ue4_coords.append(self.convert_GPS_to_UE4(gps_coordinate))
return ue4_coords
<file_sep>/PythonCode/Routing/RouteGeneration/plot_routes.py
import folium
import sys
import time
import os
from collections import namedtuple
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
GPSCoordinate = namedtuple("GPSCoordinate", ["lat", "long"])
os.chdir('..\\..')
#gps_coords_loc = 'MissionResolverCode\\work_resolver_runner.txt'
gps_coords_loc = "D:\\IJCAIDemoCode\\CommsHubCode\\work_resolver_runner.txt"
locations = open(gps_coords_loc, 'r')
gps_coordinates = []
file_lines = locations.readlines()
colors = ['blue','green','red', 'yellow', 'black']
marker_sides = [i for i in range(3, 3 + len(colors)+1)]
color_counter = 0
map=folium.Map(location=[53.28174954176364, -9.061292838154545], tiles='Stamen Terrain',zoom_start=15)
points = []
for location in file_lines:
if location == '\n':
folium.PolyLine(points, color = colors[color_counter], weight = 3).add_to(map)
color_counter+=1
points = []
elif len(location.split(','))>1:
print(location)
location = location.replace('\n','')
gps_coordinates.append(GPSCoordinate(location.split(',')[0], location.split(',')[1]))
print('creating location: ', [location.split(',')[0], location.split(',')[1]])
folium.RegularPolygonMarker(location = [float(location.split(',')[0]), float(location.split(',')[1])],
fill_color = colors[color_counter], radius = 5, number_of_sides=marker_sides[color_counter]).add_to(map)
points.append((float(location.split(',')[0]), float(location.split(',')[1])))
folium.TileLayer('openstreetmap').add_to(map)
map_loc = '\\PythonClientGPSMapping\\rav_route_mapping.html'
#os.chdir('..\\..')
print('current directory: ' + os.getcwd())
map.save(os.getcwd() + map_loc)
browser = webdriver.Chrome()
browser.get(os.getcwd() + map_loc)
def show_path(driver, file_path):
driver.get('https://www.darrinward.com/lat-long/')
csv_input = driver.find_element_by_name('csv_file')
csv_input.send_keys(os.getcwd() + file_path)
wait = WebDriverWait(driver, 5)
element = wait.until(EC.element_to_be_clickable((By.ID, 'labels_show')))
time.sleep(0.5)
element = driver.find_element_by_id('labels_show')
if element.is_selected():
print('clicking labels_show')
time.sleep(1)
try:
element.click()
except Exception as e:
print(e)
print('clicked labels_show')
element = wait.until(EC.element_to_be_clickable((By.ID, 'line_show')))
time.sleep(0.5)
element = driver.find_element_by_id('line_show')
if element.is_selected():
print('clicking line_show')
time.sleep(1)
element.click()
print('clicked line_show')
driver.find_element_by_id('submitButton').click()
second_browser = webdriver.Chrome()
show_path(second_browser, '\\MissionResolverCode\\test_work_resolver31_all.csv')
third_browser = webdriver.Chrome()
show_path(third_browser, '\\MissionResolverCode\\test_work_resolver31_one.csv')
fourth_browser = webdriver.Chrome()
show_path(fourth_browser, '\\MissionResolverCode\\test_work_resolver31_two.csv')
fifth_browser = webdriver.Chrome()
show_path(fifth_browser, '\\MissionResolverCode\\test_work_resolver31_three.csv')
import sys
sys.exit(0)
third_browser = webdriver.Chrome()
third_browser.get('https://www.darrinward.com/lat-long/')
csv_input = third_browser.find_element_by_name('csv_file')
csv_input.send_keys(os.getcwd() + '\\MissionResolverCode\\test_work_resolver31_one.csv')
wait = WebDriverWait(third_browser, 5)
element = wait.until(EC.element_to_be_clickable((By.ID, 'labels_show')))
if element.is_selected():
element.click()
element = wait.until(EC.element_to_be_clickable((By.ID, 'line_show')))
if third_browser.find_element_by_id('line_show').is_selected():
third_browser.find_element_by_id('line_show').click()
time.sleep(2)
third_browser.find_element_by_id('submitButton').click()
fourth_browser = webdriver.Chrome()
fourth_browser.get('https://www.darrinward.com/lat-long/')
csv_input = fourth_browser.find_element_by_name('csv_file')
csv_input.send_keys(os.getcwd() + '\\MissionResolverCode\\test_work_resolver31_one.csv')
fourth_browser.find_element_by_id('labels_show').click()
fourth_browser.find_element_by_id('line_show').click()
fourth_browser.find_element_by_id('submitButton').click()
fifth_browser = webdriver.Chrome()
fifth_browser.get('https://www.darrinward.com/lat-long/')
csv_input = fifth_browser.find_element_by_name('csv_file')
csv_input.send_keys(os.getcwd() + '\\MissionResolverCode\\test_work_resolver31_one.csv')
fifth_browser.find_element_by_id('labels_show').click()
fifth_browser.find_element_by_id('line_show').click()
fifth_browser.find_element_by_id('submitButton').click()<file_sep>/PythonCode/Routing/AirSimPythonClient/README.md
## GPSMappings Direcory
This directory contains the python classes that convert GPS coordinates to unreal engine coordinates. Vincenty's formulas are used to calculate the conversions. AirSimClient is copied from the main AirSim repo and has been modified to contain a GPSToUnreal class which converts GPS coordinates to Unreal Engine NED coordinates. The unreal engine coordinates are relative the RAV's home position and can be used with AirSim RAVS.
## RAVRoutes Directory
This directory contains the files rav_<>_mapper.py, which will execute routes which are automatically written by generateRoutesForUnreal.py.
<file_sep>/CommandLineScripts/Unix/two_drone.sh
cd ../..
base_dir="$( cd "$(dirname "$0")" ; pwd -P )"
cd ./RAVCollectedData/PNGImages/ImagesRAV2
find -type f -iname '*.png' -delete
cd $base_dir
cd ./PythonCode/Routing/AirSimPythonClient/RAVExecuteRoutes
python3 rav_one_mapper.py
| 8fe2af32a03703f10ec12fee1c422814909760e2 | [
"Markdown",
"INI",
"Python",
"Text",
"R",
"Dockerfile",
"Shell"
] | 46 | Python | NUIG-ROCSAFE/CBRNeVirtualEnvironment | 440149886d7ecca6c774fc4148cf0a0718657ea8 | 821fc6e9d0f4ab4831b4fda84732fde94648f145 |
refs/heads/master | <repo_name>amiritka/golangtutor<file_sep>/main.go
package main
import (
"fmt"
"net/http"
"html/template"
//"github.com/gorilla/mux"
)
type ViewData struct{
Title string
Message []string
}
func main(){
data := ViewData{
Title : "Champion list!!",
Message : []string{"Tom", "Bob", "Nasty",},
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
tmpl, _ := template.ParseFiles("c:/users/admin/desktop/goworkspace/templates/userdie.html")
tmpl.Execute(w, data)
})
fmt.Println("Server...")
http.ListenAndServe(":8181", nil)
} | cd33411beb935d2744727e5fb57127aba42d98ce | [
"Go"
] | 1 | Go | amiritka/golangtutor | a5048dc2fdd9d6e63cb813786df58dbe9ee56352 | a45f087c7837373c8310f7b28ccfc51f3def5960 |
refs/heads/master | <repo_name>DevHyperCoder/calc-bot<file_sep>/src/index.ts
require("dotenv").config();
import { Client, Message, MessageEmbed } from "discord.js";
console.log(process.env.PREFIX);
async function helpCommand(msg: Message) {
await sendMessage(
msg,
`
add x y
multiply x y
divide x y
square x
sqrt x
lcm x y
hcf x y
isdivisible x y
iscoprime x y
isprime x
closetprime x
`,
false,
true
);
}
async function sendMessage(
message: Message,
c: number | string,
error = false,
help = false
) {
const e = new MessageEmbed()
.setTitle(message.content)
.setFooter(`Requested by: ${message.author.username}`)
.setDescription(c);
if (error) {
e.setColor("#FF0000");
}
if (help) {
e.setColor("#00FF00");
}
await message.channel.send(e);
}
async function main() {
const client = new Client();
client.on("ready", () => {
console.log("bot is up");
});
client.on("message", async (msg: Message) => {
if (msg.mentions.has(client.user!)) {
await helpCommand(msg);
}
if (!shouldParseMessage(process.env.PREFIX!, msg)) {
return;
}
const { args, command } = getCommandAndArgs(process.env.PREFIX!, msg);
switch (command) {
case "isdivisible": {
if (args.length < 2) {
sendMessage(msg, "", true);
break;
}
const n = parseInt(args[0]);
const n1 = parseInt(args[1]);
sendMessage(msg, n % n1 == 0 ? "true" : "false");
break;
}
case "multiply": {
if (args.length < 2) {
sendMessage(msg, "", true);
break;
}
const number1 = parseInt(args[0]);
const number2 = parseInt(args[1]);
sendMessage(msg, number1 * number2);
break;
}
case "divide": {
if (args.length < 2) {
sendMessage(msg, "", true);
break;
}
const number1 = parseInt(args[0]);
const number2 = parseInt(args[1]);
sendMessage(msg, number1 / number2);
break;
}
case "add": {
if (args.length < 2) {
sendMessage(msg, "", true);
break;
}
const number1 = parseInt(args[0]);
const number2 = parseInt(args[1]);
sendMessage(msg, number1 + number2);
break;
}
case "square": {
if (args.length < 1) {
sendMessage(msg, "", true);
break;
}
const n = parseInt(args[0]);
sendMessage(msg, n * n);
break;
}
case "sqrt": {
if (args.length < 1) {
sendMessage(msg, "", true);
break;
}
const n = parseInt(args[0]);
sendMessage(msg, Math.sqrt(n));
break;
}
case "hcf": {
if (args.length < 2) {
msg.reply("not enough args bruh");
sendMessage(msg, "", true);
break;
}
const number1 = parseInt(args[0]);
const number2 = parseInt(args[1]);
let hcf = getHCF(number1, number2);
sendMessage(msg, hcf);
break;
}
case "isprime": {
if (args.length < 1) {
sendMessage(msg, "", true);
break;
}
sendMessage(msg, isPrime(parseInt(args[0])));
break;
}
case "iscoprime": {
if (args.length < 2) {
sendMessage(msg, "", true);
break;
}
sendMessage(msg, isCoPrime(parseInt(args[0]), parseInt(args[1])));
break;
}
case "lcm": {
if (args.length < 2) {
sendMessage(msg, "", true);
break;
}
const number1 = parseInt(args[0]);
const number2 = parseInt(args[1]);
let lcm = getLCM(number1, number2);
sendMessage(msg, lcm);
break;
}
case "closetprime": {
if (args.length < 1) {
sendMessage(msg, "", true);
break;
}
sendMessage(msg, nearestPrime(parseInt(args[0])));
break;
}
case "help": {
await helpCommand(msg);
}
}
});
client.login(process.env.TOKEN);
}
function getCommandAndArgs(
prefix: String,
message: Message
): { args: Array<string>; command: String | undefined } {
const args = message.content.slice(prefix.length).trim().split(" ");
const command = args.shift()?.toLowerCase();
return { args, command };
}
function shouldParseMessage(prefix: string, msg: Message): Boolean {
const hasPrefix = msg.content.startsWith(prefix);
const isBot = msg.author.bot;
return hasPrefix && !isBot;
}
main();
function getHCF(number1: number, number2: number): number {
let hcf = 0;
for (let i = 1; i <= number1 && i <= number2; i++) {
// check if is factor of both integers
if (number1 % i == 0 && number2 % i == 0) {
hcf = i;
}
}
return hcf;
}
function getLCM(num1: number, num2: number): number {
let min = num1 > num2 ? num1 : num2;
// while loop
while (true) {
if (min % num1 == 0 && min % num2 == 0) {
return min;
}
min++;
}
}
function isPrime(num: number): string {
for (var i = 2; i < num; i++) if (num % i === 0) return "false";
return num > 1 ? "true" : "false";
}
function isCoPrime(num1: number, num2: number): string {
const smaller = num1 > num2 ? num1 : num2;
for (let ind = 2; ind < smaller; ind++) {
const condition1 = num1 % ind === 0;
const condition2 = num2 % ind === 0;
if (condition1 && condition2) {
return "false";
}
}
return "true";
}
function nearestPrime(num: number): number {
while (!isPrime(++num)) {}
return num;
}
| 8fecf65f99484d46c327c9e07dbead330a6a34f1 | [
"TypeScript"
] | 1 | TypeScript | DevHyperCoder/calc-bot | c178a621350b183b94db5eaddc579d2af395141e | 92ee46e9a880365d22960f1b3b322aed46a43a87 |
refs/heads/master | <repo_name>yxj9721/coding<file_sep>/video/js/a/houdunren.js
alert('ๅ็พไบบ'); | 43d60e4a731996f63582819c330b79c47870af17 | [
"JavaScript"
] | 1 | JavaScript | yxj9721/coding | d2b2bcf78d3edde6f0a1e0c2d734472447d9a352 | 0e08acd72a81791d6e41f0b60fef9a2447e6183d |
refs/heads/master | <repo_name>Doryski/Epl_results<file_sep>/dataframe_prep.py
# ---------------- importing modules ----------------
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.offline as pyo
import plotly.graph_objs as go
plt.style.use('ggplot')
# ---------------- loading dataset ---------------------
df = pd.read_excel('EPL_Set.xlsx', sheet_name='EPL_Set')
### ------------------- preparing dataframes ----------------
all_cols = ['Season', 'HomeTeam', 'AwayTeam', '1HHG', '1HAG', '1HR', '2HHG', '2HAG',
'2HR', 'FTHG', 'FTAG', 'FTR', '1HSumGoals', '2HSumGoals', 'FTSumGoals',
'1HScore', '2HScore', 'FTScore', '2.5', 'Winner', 'BothScored',
'2.5/Winner', '2.5/BothScored', 'Winner/BothScored', 'Result']
goal_cols = ['1HHG', '1HAG', '1HR', '2HHG', '2HAG',
'2HR', 'FTHG', 'FTAG', 'FTR']
sum_goals_cols = ['1HSumGoals', '2HSumGoals', 'FTSumGoals']
score_cols = ['1HScore', '2HScore', 'FTScore']
spec_cols = ['2.5', 'Winner', 'BothScored',
'2.5/Winner', '2.5/BothScored', 'Winner/BothScored', 'Result']
### --------------- visualizations -------------------
score1H = pd.DataFrame(data=df['1HR'].value_counts(sort=False)).T
score2H = pd.DataFrame(data=df['2HR'].value_counts(sort=False)).T
scoreFT = pd.DataFrame(data=df['FTR'].value_counts(sort=False)).T
scores = pd.concat([score1H, score2H, scoreFT], axis=0)
scores.index = ['First half', 'Second half','Full time']
# ------------------ percentage of whole column
scores_perc = scores.copy()
scores_perc['1'] = [round(scores_perc['1'][i]/np.sum(scores_perc['1'])*100, 1) for i in scores_perc.index]
scores_perc['X'] = [round(scores_perc['X'][i]/np.sum(scores_perc['X'])*100, 1) for i in scores_perc.index]
scores_perc['2'] = [round(scores_perc['2'][i]/np.sum(scores_perc['2'])*100, 1) for i in scores_perc.index]
# -------------- plotly visualization --------------------
trace0 = go.Bar(x=scores_perc.index, y=scores_perc['1'],
name='Home team win', marker=dict(color='green'), width=0.25)
trace1 = go.Bar(x=scores_perc.index, y=scores_perc['X'],
name='Draw', marker=dict(color='grey'), width=0.25)
trace2 = go.Bar(x=scores_perc.index, y=scores_perc['2'],
name='Away team win', marker=dict(color='blue'), width=0.25)
data = [trace0, trace1, trace2]
layout = go.Layout(title='Scores', yaxis=dict(title='%'), barmode=None)
fig = go.Figure(data=data, layout=layout)
pyo.plot(fig, filename="Scores_nested.html", auto_open=True)
# ------------------- heatmap full time goals ------------------
df_heatmap = pd.pivot_table(data=df, index='FTHG',columns='FTAG',values='FTR', aggfunc=lambda x: round(x.count()/len(df)*100, 1), fill_value=0.0)
ax = sns.heatmap(data=df_heatmap, cmap='Blues', linecolor="white", linewidths=.5, annot=True, fmt='.1f')
ax.set_title('Full time goals distribution percentage', pad=35, fontdict=dict(fontsize=14))
ax.set_xlabel('Away team goals')
ax.set_ylabel('Home team goals')
ax.xaxis.tick_top()
ax.xaxis.set_label_position('top')
plt.tight_layout()
plt.savefig('Goals_distribution_heatmap',bbox_inches='tight')
plt.show()
# ------------------- line plot full time scores ---------------
result = pd.DataFrame(data=df['Result'].value_counts())
result1 = result[result > 0.01*result.sum()].dropna()
result2 = result[result < 0.01*result.sum()].dropna().apply('sum')
result3 = pd.DataFrame(index=['Rest'], data=result2['Result'], columns=['Result'])
result1 = result1.append(result3).apply(lambda x: round(x/result1['Result'].sum()*100, 1))
data = [go.Scatter(x=result1.index, y=result1['Result'], marker=dict(color='blue', size=10),
line=dict(color='grey', width=3), name='Percentage of all results', showlegend=True)]
layout = go.Layout(title='Results\' distribution', yaxis=dict(title='%'), legend=dict(x=0.8, y=0.95))
fig = go.Figure(data=data, layout=layout)
pyo.plot(fig, filename="Results_dist.html", auto_open=True)
# -------------- violin plot distribution of goals' sums --------------
df_sum_goals = df[sum_goals_cols]
df_sum_goals = df_sum_goals.apply(lambda x: x.value_counts(sort=False)).fillna(0).astype(int)
df_sum_goals = df_sum_goals.apply(lambda x: round(x/len(df)*100, 1))
trace0 = go.Bar(x=df_sum_goals.index, y=df_sum_goals['1HSumGoals'], name='First half goals', marker=dict(color='green'))
trace1 = go.Bar(x=df_sum_goals.index, y=df_sum_goals['2HSumGoals'], name='Second half goals', marker=dict(color='blue'))
trace2 = go.Bar(x=df_sum_goals.index, y=df_sum_goals['FTSumGoals'], name='Full time goals', marker=dict(color='grey'))
data = [trace0, trace1, trace2]
layout = go.Layout(title='Sum of goals distribution', yaxis=dict(title='%'), legend=dict(x=0.8, y=0.95))
fig = go.Figure(data=data, layout=layout)
pyo.plot(fig, filename="Sum_goals_dist.html", auto_open=True)
# ----------------------- bar plot sums of goals -----------------
result_comparison = pd.DataFrame(df['HalfTvsFullT'].value_counts())
result_comparison = result_comparison.apply(lambda x: round(x/len(df)*100,1))
import squarify
x = 0.
y = 0.
width = 100.
height = 100.
values = result_comparison['HalfTvsFullT']
color_brewer = ['blue','blue','blue','green','green','green','green', 'grey', 'grey']
normed = squarify.normalize_sizes(values, width, height)
rects = squarify.squarify(normed, x, y, width, height)
shapes = []
annotations = []
counter = 0
for r in rects:
shapes.append(
dict(
type = 'rect',
x0 = r['x'],
y0 = r['y'],
x1 = r['x']+r['dx'],
y1 = r['y']+r['dy'],
line = dict(width=2, color='white'),
fillcolor = color_brewer[counter]
)
)
annotations.append(
dict(
x = r['x']+(r['dx']/2),
y = r['y']+(r['dy']/2),
text = values.index[counter] + ': ' + str(values[counter]) + '%',
showarrow = False,
font = dict(
color = "black",
size = 12
)
))
counter = counter + 1
if counter >= len(color_brewer):
counter = 0
trace0 = go.Scatter(
x = [ r['x']+(r['dx']/2) for r in rects ],
y = [ r['y']+(r['dy']/2) for r in rects ]
)
layout = go.Layout(
height=700,
width=700,
xaxis=dict(showgrid=False,zeroline=False, showticklabels=False),
yaxis=dict(showgrid=False,zeroline=False, showticklabels=False),
shapes=shapes,
annotations=annotations,
hovermode='closest', title='Half time result vs Full time result distribution'
)
# With hovertext
fig = dict(data=[trace0], layout=layout)
pyo.plot(fig, filename="Half_goals.html", auto_open=True)
# ----------------------- saving dataframes -----------------
df.to_excel('EPL_df.xlsx', sheet_name='Dataframe')
df.to_csv('EPL_df.csv', index=False)
scores.to_csv('scores.csv')
scores_perc.to_csv('scores_dist.csv')
df_sum_goals.to_csv('sum_goals_dist.csv')
| d3f96b75da7b40e1fccca6b9e1d719aa1a7ac7c9 | [
"Python"
] | 1 | Python | Doryski/Epl_results | d8ff04a851f8c070811cc67e21817d052e88e9d3 | 2d83c4b9be49d7403b2f2c93f16f8b5a453bed07 |
refs/heads/master | <repo_name>roshmani/Finalproject<file_sep>/src/navigation.js
import React from "react";
import { Link } from "react-router-dom";
export default function Navigation() {
return (
<div className="nav">
<ul className="navbar">
<li>
<Link to="/sharecode">Start Coding</Link>
</li>
<li>
<a href="/logout">Logout</a>
</li>
</ul>
</div>
);
}
<file_sep>/src/codeshare.js
import React from "react";
import axios from "./axios";
import { Link } from "react-router-dom";
export default class CodeShare extends React.Component {
constructor(props) {
super(props);
this.state = {};
console.log("id of user", this.props.id);
}
render() {
return (
<div className="codeShareMain">
<Link to={`/sharecode/${this.props.id}`}>
<h2 className="roomnav">Go to Coding Cube</h2>
</Link>
</div>
);
}
}
<file_sep>/src/login.js
import React from "react";
import axios from "./axios";
import { Link } from "react-router-dom";
export default class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
logged: false,
error: "",
emailid: "",
password: ""
};
this.login = this.login.bind(this);
this.handleChange = this.handleChange.bind(this);
}
render() {
return (
<div className="loginForm">
{this.state.error && (
<div className="error">
Email-id or password input seems to be wrong!!
</div>
)}
<h2 className="titletxt">SIGN IN</h2>
<input
type="email"
name="emailid"
onChange={this.handleChange}
placeholder="email-id"
/>
<input
type="<PASSWORD>"
name="password"
onChange={this.handleChange}
placeholder="<PASSWORD>"
/>
<button
type="submit"
className="loginButton"
onClick={this.login}
>
Sign In
</button>
<p>
Not Registered yet?..,<Link to="/register">Register</Link>
</p>
</div>
);
}
/* handles the change of values in input field and assigns to this.corrsponding*/
handleChange(e) {
this[e.target.name] = e.target.value;
}
login() {
axios
.post("/login", {
emailid: this.emailid,
password: this.<PASSWORD>
})
.then(({ data }) => {
if (data.success) {
this.setState({ fname: data.username, logged: true });
location.replace("/codecube");
} else {
this.setState({ error: true });
}
});
}
}
<file_sep>/sql/createtables.sql
DROP TABLE IF EXISTS codestore;
DROP TABLE IF EXISTS chats;
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id SERIAL primary key,
fname VARCHAR(255) not null,
lname VARCHAR(255) not null,
email VARCHAR(255) not null UNIQUE,
password VARCHAR(255) not NULL
);
CREATE TABLE codestore (
id SERIAL primary key,
coder_id INTEGER NOT NULL REFERENCES users(id) UNIQUE,
codetext VARCHAR not null,
changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE chats(
id SERIAL PRIMARY KEY,
room_id INTEGER NOT NULL,
sender_id INTEGER NOT NULL REFERENCES users(id),
send_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
message VARCHAR(1000) not null
);
<file_sep>/src/actions.js
export function loadUsers(users) {
return {
type: "ROOM_USERS",
users
};
}
export function userJoined(joinedUser) {
return {
type: "USER_JOINED",
joinedUser
};
}
export function userLeft(leftUserId) {
return {
type: "USER_LEFT",
leftUserId
};
}
export function updateCode(code) {
return {
type: "UPDATE_CODE",
code: code.code
};
}
export function chatMessages(messages) {
return {
type: "CHAT_MESSAGES",
messages
};
}
export function chatMessage(message) {
return {
type: "CHAT_MESSAGE",
message
};
}
<file_sep>/src/registration.js
import React from "react";
import axios from "./axios";
import { Link } from "react-router-dom";
export default class Registration extends React.Component {
constructor(props) {
super(props);
this.state = {
logged: false,
error: false,
fname: "",
lnmae: "",
emailid: "",
password: ""
};
this.submit = this.submit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
render() {
return (
<div className="regForm">
{this.state.error && (
<div className="error">
Something went wrong in Registration!!
</div>
)}
<h2 className="titletxt">CREATE YOUR ACCOUNT</h2>
<input
type="text"
name="fname"
onChange={this.handleChange}
placeholder="First name"
/>
<input
type="text"
name="lname"
onChange={this.handleChange}
placeholder="Last name"
/>
<input
type="email"
name="emailid"
onChange={this.handleChange}
placeholder="email-id"
/>
<input
type="<PASSWORD>"
name="password"
onChange={this.handleChange}
placeholder="<PASSWORD>"
/>
<button
type="submit"
className="regButton"
onClick={this.submit}
>
Register
</button>
<p>
Already a member?,<Link to="/login">Log In</Link>
</p>
</div>
);
}
/* handles the change of values in input field and assigns to this.corrsponding*/
handleChange(e) {
this[e.target.name] = e.target.value;
}
submit() {
axios
.post("/register", {
fname: this.fname,
lname: this.lname,
emailid: this.emailid,
password: this.password
})
.then(({ data }) => {
if (data.success) {
this.setState({ logged: true });
location.replace("/codecube");
} else {
this.setState({ error: true });
}
});
}
}
<file_sep>/src/socket.js
import * as io from "socket.io-client";
import {
loadUsers,
userJoined,
userLeft,
updateCode,
chatMessage,
chatMessages
} from "./actions";
let socket;
export function getSocket(store) {
if (!socket) {
socket = io.connect();
socket.on("loadUsers", data => {
store.dispatch(loadUsers(data));
});
socket.on("userJoined", data => {
console.log("user joined");
store.dispatch(userJoined(data));
});
socket.on("userLeft", leftUserId => {
console.log("user left");
store.dispatch(userLeft(leftUserId));
});
socket.on("updateCode", code => {
store.dispatch(updateCode(code));
});
socket.on("chatMessage", message => {
store.dispatch(chatMessage(message));
});
socket.on("chatMessages", messages => {
console.log("messages in socket.js");
store.dispatch(chatMessages(messages));
});
}
return socket;
}
export function emit(event, data) {
socket.emit(event, data);
}
<file_sep>/src/roomusers.js
import React, { Component } from "react";
import { connect } from "react-redux";
class RoomUsers extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
console.log("users:", this.props.users);
if (!this.props.users) {
return null;
}
return (
<div className="userwrapper">
<div className="users">
<h3>Current Coders in the cube</h3>
{this.props.users.map(user => (
<div className="roomuser" key={user.id}>
{user.fname} {user.lname}
</div>
))}
</div>
</div>
);
}
}
const mapUserstoProps = state => {
return {
users: state.users
};
};
export default connect(mapUserstoProps)(RoomUsers);
<file_sep>/src/app.js
import React from "react";
import { BrowserRouter, Route } from "react-router-dom";
import axios from "./axios";
import Navigation from "./navigation";
import CodeEditor from "./codeeditor";
import CodeShare from "./codeshare";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
axios.get("/getUserDetails").then(({ data }) => {
this.setState(data);
/************* or you can also do this to be explicit ***************************/
/*const { id, fname, lname, emailid, bio, imageUrl } = data;
this.setState({
id,
fname,
lname,
emailid,
bio,
imageUrl: imageurl
});*/
/*********************************************************************************/
});
}
render() {
if (!this.state.id) {
return <div>Loading...</div>;
}
const { fname, lname, id } = this.state;
return (
<BrowserRouter>
<div className="appwrapper">
<div className="mainAppdiv">
<div className="headerappdiv">
<div className="logobrand">
<h1 className="logotxt">
[ Code Cube ]
</h1>
</div>
<Navigation />
<div className="userloggeddiv">
<span className="userlogged">
{fname} {lname}
</span>
</div>
</div>
<div className="codesharewrapper">
<Route
exact
path="/sharecode"
render={() => <CodeShare id={id} />}
/>
<Route
exact
path="/sharecode/:id"
component={CodeEditor}
/>
</div>
</div>
</div>
</BrowserRouter>
);
}
}
<file_sep>/src/landingpage.js
import React from "react";
import { Link } from "react-router-dom";
export default function LandingPage() {
return (
<div className="landing">
<h2 className="landingtxt">Code together with others !</h2>
<h3>
Solve coding challenges with others realtime, Work together to
success..
</h3>
<div className="signupbtndiv">
<Link to="/register">
<p className="signupbtn">Sign Up</p>
</Link>
</div>
</div>
);
}
<file_sep>/codetogetherdb.js
var spicedpg = require("spiced-pg");
let dbURL;
if (process.env.DATABASE_URL) {
dbURL = process.env.DATABASE_URL;
} else {
const secrets = require("./secrets.json");
dbURL = secrets.dbURL;
}
const db = spicedpg(dbURL);
module.exports.regUsers = function(fname, lname, email, password) {
var query = `INSERT INTO users(fname,lname,email,password)
VALUES($1,$2,$3,$4) RETURNING id,fname,lname`;
return db.query(query, [
fname || null,
lname || null,
email || null,
password || null
]);
};
module.exports.checkEmail = function(emailid) {
var query = `SELECT * FROM users WHERE email=$1`;
return db.query(query, [emailid]);
};
module.exports.getUserDetails = function(userid) {
var query = `SELECT * FROM users WHERE id=$1`;
return db.query(query, [userid]);
};
module.exports.getUsersByIds = function(arrayOfIds) {
const query = `SELECT * FROM users WHERE id = ANY($1)`;
return db.query(query, [arrayOfIds]);
};
module.exports.getRecentMessages = function(room_id) {
const query = `SELECT users.id,fname, lname, chats.id as chatid,sender_id,to_char(send_at,'Day, DD-MM-YYYY HH12:MI:SS') as send_at,message
FROM chats
LEFT JOIN users
ON (sender_id = users.id)
WHERE room_id=$1
ORDER BY chatid DESC
LIMIT 3`;
return db.query(query, [room_id || null]);
};
module.exports.saveChatMsg = function(senderid, message, room_id) {
var query = `INSERT INTO chats(sender_id,message,room_id)
VALUES($1,$2,$3) RETURNING id as chatid,sender_id,to_char(send_at,'Day, DD-MM-YYYY HH12:MI:SS') as send_at,message`;
return db.query(query, [
senderid || null,
message || null,
room_id || null
]);
};
module.exports.getCode = function(coder_id) {
console.log("coder_id:", coder_id);
const query = `SELECT *
FROM codestore
WHERE coder_id=$1`;
return db.query(query, [coder_id || null]);
};
module.exports.saveCode = function(coder_id, code) {
console.log("running save chat msg");
var query = `INSERT INTO codestore(coder_id,codetext)
VALUES($1,$2)
ON CONFLICT (coder_id)
DO UPDATE SET codetext = $2 RETURNING *`;
return db.query(query, [coder_id || null, code || null]);
};
<file_sep>/src/welcome.js
import React from "react";
import { HashRouter, Route } from "react-router-dom";
import Registration from "./registration";
import LandingPage from "./landingpage";
import Login from "./login";
import { Link } from "react-router-dom";
export default function Welcome() {
return (
<HashRouter>
<div className="landingpagediv">
<div className="headerdiv">
<div className="logobrand">
<h1 className="logotxt">[Code Cube ]</h1>
</div>
<div className="signinbtndiv">
<Link to="/login">
<p className="signinbtn">Sign In</p>
</Link>
</div>
</div>
<div className="welcomediv">
<div className="componentdiv">
<Route exact path="/" component={LandingPage} />
<Route
exact
path="/register"
component={Registration}
/>
<Route path="/login" component={Login} />
</div>
</div>
</div>
</HashRouter>
);
}
<file_sep>/src/savebutton.js
import React, { Component } from "react";
import axios from "./axios";
export default class SaveButton extends Component {
constructor(props) {
super(props);
this.state = { code: this.props.code, filename: this.props.filename };
}
render() {
return (
<form method="GET" action="/savecode">
<button className="savefile">Save</button>
<input type="hidden" name="code" value={this.props.code} />
<input
type="hidden"
name="filename"
value={this.props.filename}
/>
</form>
);
}
}
<file_sep>/src/reducer.js
const INITIAL_STATE = {
users: [],
code: "",
messages: []
};
export function reducer(state = INITIAL_STATE, action) {
if (action.type == "ROOM_USERS") {
state = { ...state, users: action.users };
}
if (action.type == "USER_JOINED") {
state = {
...state,
onlineUsers: [action.joinedUser, ...state.users]
};
}
if (action.type == "USER_LEFT") {
state = {
...state,
users: state.users.filter(user => user.id != action.leftUserId)
};
}
if (action.type == "UPDATE_CODE") {
state = { ...state, code: action.code };
}
if (action.type == "CHAT_MESSAGES") {
state = { ...state, messages: action.messages };
}
if (action.type == "CHAT_MESSAGE") {
state = { ...state, messages: [...state.messages, action.message] };
}
return state;
}
| 4954e95632df9c7b67ccfee13027ced51eb315dd | [
"JavaScript",
"SQL"
] | 14 | JavaScript | roshmani/Finalproject | a2f8d4ffe0d8a1333ece5b8eb027e9d0e8dbc9ac | ab9fab55e0414007fab19eecf7d9aa0b46796f87 |
refs/heads/master | <repo_name>Ecalzo/3DWaveEquationCharting<file_sep>/README.md
# 3DWaveEquationCharting
Using D'Alembert's Solution to the wave equation and the matplotlib 3D library.

## Data, Data, Data
The graph is a solution to the wave equation given the following constraints:

I am providing this code for others to reference when using matplotlib and Axes 3D, since many nuances are encountered particularly when changing the plot's aesthetics.
<file_sep>/wave_equation_data.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 2 16:33:16 2018
@author: ec
"""
# countour map -- topographical data, or anything in 3 dimensions
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import AutoMinorLocator
import pandas as pd
import numpy as np
df = pd.read_csv('Data.csv')
xyz = np.array(df[['x','t','z']])
afont = {'fontname':'Arial'}
# reshaping into 2D arrays to function with matplotlib
x = xyz[:,0]
X = np.reshape(x, (33, 11))
y = xyz[:,1]
Y = np.reshape(y, (33, 11))
z = xyz[:,2]
Z = np.reshape(z, (33, 11))
fig = plt.figure(figsize=(10,7))
ax = fig.add_subplot(111, projection='3d')
# set x, y, and z labels, sizes and paddings
ax.set_xlabel('Distance', size = 15, labelpad=10, **afont)
ax.set_ylabel('Time', size = 15, labelpad=10, **afont)
ax.set_zlabel('Displacement', size=15, labelpad=5, **afont)
# set the tick size - set y and z first, then rotate x if needed
ax.tick_params(labelsize=10)
#ax.tick_params(axis='x', labelrotation=70)
plt.suptitle('Wave Displacement as a Function of Distance and Time with a = 1', size = 15)
# set the font of the labels
for tick in ax.get_xticklabels():
tick.set_fontname("Arial")
for tick in ax.get_yticklabels():
tick.set_fontname("Arial")
for tick in ax.get_zticklabels():
tick.set_fontname("Arial")
ax.plot_surface(X,Y,Z, rstride = 1, cstride = 1, cmap='hot', antialiased=True, shade=False)
#plt.savefig('heatMapGraph.png', dpi=600, bbox_inches='tight')
plt.show()
| af0b70c0053d2b23f4375a77c1933882bf3a8c46 | [
"Markdown",
"Python"
] | 2 | Markdown | Ecalzo/3DWaveEquationCharting | 1f4edecba81417642569a594a530abb2f4fc4543 | 0e61ab84a44205e2fd39396e88f11427f31322e5 |
refs/heads/master | <repo_name>AvianLearning/flask_event_list_lab<file_sep>/app/controller.py
from app import app
from flask import render_template, request, redirect
from app.models.add_event import *
from app.models.event import *
@app.route('/')
def index():
return render_template("index.html", title="Home", events=events)
<file_sep>/app/models/add_event.py
from app.models.event import *
event1 = Event("23/09/20", "CodeClan W3D3", 25, "Castle Terrace", "CSS")
event2 = Event("24/09/20", "CodeClan W3D4", 25, "Castle Terrace", "Flask")
events = [event1, event2]
def add_new_event(event):
events.append(event)
| deb46dc7005b8903e0ab79c230ab4bd2e0a84918 | [
"Python"
] | 2 | Python | AvianLearning/flask_event_list_lab | 1187622378456af6c99f54baa743e4ff4bee51b9 | 844044eca1076b1515592b825c7d59c0020eb99b |
refs/heads/main | <repo_name>zhlmnet/Remora<file_sep>/Firmware/FirmwareSource/Remora-OS5/FastAnalogIn/FastAnalogIn_LPC11UXX.cpp
#ifdef TARGET_LPC11UXX
#include "FastAnalogIn.h"
static inline int div_round_up(int x, int y)
{
return (x + (y - 1)) / y;
}
#define LPC_IOCON0_BASE (LPC_IOCON_BASE)
#define LPC_IOCON1_BASE (LPC_IOCON_BASE + 0x60)
#define MAX_ADC_CLK 4500000
static const PinMap PinMap_ADC[] = {
{P0_11, ADC0_0, 0x02},
{P0_12, ADC0_1, 0x02},
{P0_13, ADC0_2, 0x02},
{P0_14, ADC0_3, 0x02},
{P0_15, ADC0_4, 0x02},
{P0_16, ADC0_5, 0x01},
{P0_22, ADC0_6, 0x01},
{P0_23, ADC0_7, 0x01},
{NC , NC , 0 }
};
static int channel_usage[8] = {0,0,0,0,0,0,0,0};
FastAnalogIn::FastAnalogIn(PinName pin, bool enabled)
{
ADCnumber = (ADCName)pinmap_peripheral(pin, PinMap_ADC);
if (ADCnumber == (uint32_t)NC)
error("ADC pin mapping failed");
datareg = (uint32_t*) (&LPC_ADC->DR0 + ADCnumber);
// Power up ADC
LPC_SYSCON->PDRUNCFG &= ~ (1 << 4);
LPC_SYSCON->SYSAHBCLKCTRL |= ((uint32_t)1 << 13);
uint32_t pin_number = (uint32_t)pin;
__IO uint32_t *reg = (pin_number < 32) ? (__IO uint32_t*)(LPC_IOCON0_BASE + 4 * pin_number) : (__IO uint32_t*)(LPC_IOCON1_BASE + 4 * (pin_number - 32));
// set pin to ADC mode
*reg &= ~(1 << 7); // set ADMODE = 0 (analog mode)
uint32_t clkdiv = div_round_up(SystemCoreClock, MAX_ADC_CLK) - 1;
LPC_ADC->CR = (LPC_ADC->CR & 0xFF) // keep current channels
| (clkdiv << 8) // max of 4.5MHz
| (1 << 16) // BURST = 1, hardware controlled
| ( 0 << 17 ); // CLKS = 0, we stick to 10 bit mode
pinmap_pinout(pin, PinMap_ADC);
//Enable channel
running = false;
enable(enabled);
}
void FastAnalogIn::enable(bool enabled)
{
//If currently not running
if (!running) {
if (enabled) {
//Enable the ADC channel
channel_usage[ADCnumber]++;
LPC_ADC->CR |= (1<<ADCnumber);
running = true;
} else
disable();
}
}
void FastAnalogIn::disable( void )
{
//If currently running
if (running) {
channel_usage[ADCnumber]--;
if (channel_usage[ADCnumber]==0)
LPC_ADC->CR &= ~(1<<ADCnumber);
}
running = false;
}
unsigned short FastAnalogIn::read_u16( void )
{
unsigned int retval;
//If object is enabled return current value of datareg
if (running)
retval = *datareg;
//If it isn't running, enable it and wait until new value is written to datareg
else {
//Force a read to clear done bit, enable the ADC channel
retval = *datareg;
enable();
//Wait until it is converted
while(1) {
retval = *datareg;
if ((retval>>31) == 1)
break;
}
//Disable again
disable();
}
//Do same thing as standard mbed lib, unused bit 0-3, replicate 4-7 in it
retval &= ~0xFFFF003F;
retval |= (retval >> 6) & 0x003F;
return retval;
}
#endif //defined TARGET_LPC11UXX
<file_sep>/Firmware/FirmwareSource/Remora-OS5/FastAnalogIn/FastAnalogIn_KLXX_K20D50M.cpp
#if defined(TARGET_KLXX) || defined(TARGET_K20D50M)
#include "FastAnalogIn.h"
#include "clk_freqs.h"
#define MAX_FADC 6000000
#define CHANNELS_A_SHIFT 5
#ifdef TARGET_K20D50M
static const PinMap PinMap_ADC[] = {
{PTC2, ADC0_SE4b, 0},
{PTD1, ADC0_SE5b, 0},
{PTD5, ADC0_SE6b, 0},
{PTD6, ADC0_SE7b, 0},
{PTB0, ADC0_SE8, 0},
{PTB1, ADC0_SE9, 0},
{PTB2, ADC0_SE12, 0},
{PTB3, ADC0_SE13, 0},
{PTC0, ADC0_SE14, 0},
{PTC1, ADC0_SE15, 0},
{NC, NC, 0}
};
#endif
FastAnalogIn::FastAnalogIn(PinName pin, bool enabled)
{
if (pin == NC)
return;
ADCnumber = (ADCName)pinmap_peripheral(pin, PinMap_ADC);
if (ADCnumber == (ADCName)NC) {
error("ADC pin mapping failed");
}
SIM->SCGC6 |= SIM_SCGC6_ADC0_MASK;
uint32_t port = (uint32_t)pin >> PORT_SHIFT;
SIM->SCGC5 |= 1 << (SIM_SCGC5_PORTA_SHIFT + port);
uint32_t cfg2_muxsel = ADC_CFG2_MUXSEL_MASK;
if (ADCnumber & (1 << CHANNELS_A_SHIFT)) {
cfg2_muxsel = 0;
}
// bus clk
uint32_t PCLK = bus_frequency();
uint32_t clkdiv;
for (clkdiv = 0; clkdiv < 4; clkdiv++) {
if ((PCLK >> clkdiv) <= MAX_FADC)
break;
}
if (clkdiv == 4) //Set max div
clkdiv = 0x7;
ADC0->SC1[1] = ADC_SC1_ADCH(ADCnumber & ~(1 << CHANNELS_A_SHIFT));
ADC0->CFG1 = ADC_CFG1_ADIV(clkdiv & 0x3) // Clock Divide Select: (Input Clock)/8
| ADC_CFG1_MODE(3) // (16)bits Resolution
| ADC_CFG1_ADICLK(clkdiv >> 2); // Input Clock: (Bus Clock)/2
ADC0->CFG2 = cfg2_muxsel // ADxxb or ADxxa channels
| ADC_CFG2_ADACKEN_MASK // Asynchronous Clock Output Enable
| ADC_CFG2_ADHSC_MASK; // High-Speed Configuration
ADC0->SC2 = ADC_SC2_REFSEL(0); // Default Voltage Reference
pinmap_pinout(pin, PinMap_ADC);
//Enable channel
running = false;
enable(enabled);
}
void FastAnalogIn::enable(bool enabled)
{
//If currently not running
if (!running) {
if (enabled) {
//Enable the ADC channel
ADC0->SC3 |= ADC_SC3_ADCO_MASK; // Enable continuous conversion
ADC0->SC1[0] = ADC_SC1_ADCH(ADCnumber & ~(1 << CHANNELS_A_SHIFT)); //Start conversion
running = true;
} else
disable();
}
}
void FastAnalogIn::disable( void )
{
//If currently running
if (running) {
ADC0->SC3 &= ~ADC_SC3_ADCO_MASK; // Disable continuous conversion
}
running = false;
}
uint16_t FastAnalogIn::read_u16()
{
if (!running)
{
// start conversion
ADC0->SC1[0] = ADC_SC1_ADCH(ADCnumber & ~(1 << CHANNELS_A_SHIFT));
// Wait Conversion Complete
while ((ADC0->SC1[0] & ADC_SC1_COCO_MASK) != ADC_SC1_COCO_MASK);
}
if(running && ((ADC0->SC1[0]&ADC_SC1_ADCH_MASK) != (ADC_SC1_ADCH(ADCnumber & ~(1 << CHANNELS_A_SHIFT)))))
{
running = false;
enable();
while ((ADC0->SC1[0] & ADC_SC1_COCO_MASK) != ADC_SC1_COCO_MASK);
}
// Return value
return (uint16_t)ADC0->R[0];
}
#endif //defined TARGET_KLXX
| c9371298f3e75180aa8f202d0844cf79823ba2e8 | [
"C++"
] | 2 | C++ | zhlmnet/Remora | ae1513b7d3c906ac4ba21cc6faf11b504328d2ae | 3a209a8b16bfb828dea12a7c65db65acc62c09c3 |
refs/heads/master | <repo_name>ktsein/boris_bikes<file_sep>/spec/docking_station_spec.rb
require 'docking_station'
describe DockingStation do
it 'releases bike when user asks' do
expect(subject).to respond_to :release_bike
end
end
<file_sep>/spec/bike_spec.rb
require 'docking_station'
describe Bike do
it 'checks if the bike is working' do
expect(subject).to respond_to :working?
end
end
| 7677e3aafc43e81906401d957fa9060670ddeef7 | [
"Ruby"
] | 2 | Ruby | ktsein/boris_bikes | 397454eae0db027d28086e1a7c358131267b6559 | b779d518de1f39d1f186b874323733ffd2e39c51 |
refs/heads/master | <repo_name>darkvical/vaadin-mobile<file_sep>/src/main/java/com/vical/ui/util/DetallePersona.java
package com.vical.ui.util;
import org.apache.commons.lang3.StringUtils;
import com.vaadin.addon.touchkit.ui.NavigationManager;
import com.vaadin.addon.touchkit.ui.NavigationView;
import com.vaadin.addon.touchkit.ui.Popover;
import com.vaadin.server.FontAwesome;
import com.vaadin.ui.VerticalLayout;
import com.vical.domain.Persona;
public class DetallePersona extends Popover {
private static final long serialVersionUID = -954386005852977617L;
private Persona persona;
private VerticalLayout lytCotenendor;
private NavigationView content;
public DetallePersona() {
construir();
}
private void construir() {
setWidth("50%");
setHeight("50%");
lytCotenendor = new VerticalLayout();
content = new NavigationView(lytCotenendor);
setContent(content);
}
@Override
public void attach() {
super.attach();
if(persona != null){
lytCotenendor.addComponent(CreateComponent.crateLabel(
StringUtils.join(new String[]{persona.getNombre(), persona.getPaterno(),
persona.getMaterno()}, " "), FontAwesome.USER));
lytCotenendor.addComponent(CreateComponent.crateLabel(persona.getEmail(), FontAwesome.INBOX));
lytCotenendor.addComponent(CreateComponent.crateLabel(persona.getTelefono(), FontAwesome.PHONE));
}
}
public void open(NavigationManager navigationManager){
showRelativeTo(navigationManager);
}
public Persona getPersona() { return persona; }
public void setPersona(Persona persona) { this.persona = persona; }
}
<file_sep>/src/main/java/com/vical/ui/MenuView.java
package com.vical.ui;
import com.vaadin.addon.touchkit.ui.NavigationButton;
import com.vaadin.addon.touchkit.ui.NavigationButton.NavigationButtonClickEvent;
import com.vaadin.addon.touchkit.ui.NavigationButton.NavigationButtonClickListener;
import com.vaadin.addon.touchkit.ui.NavigationView;
import com.vaadin.addon.touchkit.ui.VerticalComponentGroup;
@SuppressWarnings("serial")
public class MenuView extends NavigationView implements NavigationButtonClickListener {
private static final String ID_REGISTRO = "id_registrar";
private static final String ID_LISTADO = "id_listado";
public MenuView() {
setCaption("Menu");
final VerticalComponentGroup content = new VerticalComponentGroup();
NavigationButton btnRegistro = new NavigationButton("Registro");
btnRegistro.setId(ID_REGISTRO);
btnRegistro.addClickListener(this);
NavigationButton btnListado = new NavigationButton("Listado");
btnListado.setId(ID_LISTADO);
btnListado.addClickListener(this);
content.addComponent(btnRegistro);
content.addComponent(btnListado);
setContent(content);
}
@Override
public void buttonClick(NavigationButtonClickEvent event) {
if(event.getComponent().getId().equals(ID_REGISTRO)){
getNavigationManager().navigateTo(new RegistroView());
} else if(event.getComponent().getId().equals(ID_LISTADO)){
getNavigationManager().navigateTo(new ListadoView());
}
}
}<file_sep>/src/main/java/com/vical/dao/nosql/PersonaDAOImpl.java
package com.vical.dao.nosql;
import java.util.List;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import com.vical.dao.IPersonaDAO;
import com.vical.domain.Persona;
@Repository
public class PersonaDAOImpl extends BaseDAOImpl<Persona, String> implements IPersonaDAO {
private static final long serialVersionUID = 5211963990736381599L;
@Override
public List<Persona> obtenerEntidades(Query query) {
return super.obtenerEntidades(query);
}
}
<file_sep>/src/main/java/com/vical/server/MobVicalRequestContextListener.java
package com.vical.server;
import javax.servlet.annotation.WebListener;
import org.springframework.web.context.request.RequestContextListener;
@WebListener
public class MobVicalRequestContextListener extends RequestContextListener {
}
<file_sep>/src/main/java/com/vical/gwt/client/MobVicPersistToServerRpc.java
package com.vical.gwt.client;
import com.vaadin.shared.communication.ServerRpc;
public interface MobVicPersistToServerRpc extends ServerRpc {
void persistToServer();
}
| 472a50815a18d76814ba9cff2aaca7fe52175e81 | [
"Java"
] | 5 | Java | darkvical/vaadin-mobile | b0c6c7112f426a691f61892b551dd7d507a81258 | 117315a9412f10aa052cff027ba9befa7d5c3aab |
refs/heads/master | <repo_name>amchaudhari/KDDMM<file_sep>/Truss_AOS/src/main/java/seakers/trussaos/architecture/TrussRepeatableArchitecture.java
package seakers.trussaos.architecture;
import org.moeaframework.core.Solution;
import org.moeaframework.core.Variable;
import org.moeaframework.core.variable.BinaryVariable;
import org.moeaframework.core.variable.EncodingUtils;
/**
* Design class for the binary design vector in the 2D 3x3 nodal grid case
*
* @author roshan94
*/
public class TrussRepeatableArchitecture extends Solution{
private static final long serialVersionUID = -3246610489443538032L;
private int NumberOfTrusses;
private boolean[] CompleteBooleanDesign;
private int[][] FullConnectivityArray = {{1,2}, {1,3}, {1,4}, {1,5}, {1,6}, {1,7}, {1,8}, {1,9},
{2,3}, {2,4}, {2,5}, {2,6}, {2,7}, {2,8}, {2,9},
{3,4}, {3,5}, {3,6}, {3,7}, {3,8}, {3,9},
{4,5}, {4,6}, {4,7}, {4,8}, {4,9},
{5,6}, {5,7}, {5,8}, {5,9},
{6,7}, {6,8}, {6,9},
{7,8}, {7,9},
{8,9}};
private int[][] DesignConnectivityArray;
public TrussRepeatableArchitecture(Solution solution) {
super(solution);
//// Extract the design as a boolean array
boolean[] BooleanDesign = getBooleanDesignArray(solution);
//design = EncodingUtils.getBinary(solution.getVariable());
//// Obtain corresponding Connectivity Array
DesignConnectivityArray= ConvertToFullConnectivityArray(BooleanDesign);
//// Compute number of trusses in the design
CompleteBooleanDesign = getCompleteBooleanDesignArray(BooleanDesign);
NumberOfTrusses = getTrussCount(CompleteBooleanDesign);
}
private int[][] ConvertToFullConnectivityArray(boolean[] CurrentDesign){
boolean[] FullDesign = getCompleteBooleanDesignArray(CurrentDesign);
int TrussCount = 0;
int[][] ConnArray = new int[FullDesign.length][2];
//design = EncodingUtils.getBinary(solution.getVariable());
for (int index = 0; index < FullDesign.length; index++){
boolean decision = FullDesign[index];
if (decision){
ConnArray[TrussCount] = FullConnectivityArray[index];
TrussCount += 1;
}
}
int[][] designConnArray;
designConnArray = sliceFullConnectivityArray(ConnArray, TrussCount);
return designConnArray;
}
private int getTrussCount(boolean[] CompleteDesign){
int numVars = CompleteDesign.length;
int TrussCount = 0;
for (int index = 0; index < numVars; index++){
boolean decision = CompleteDesign[index];
if (decision){
TrussCount += 1;
}
}
return TrussCount;
}
private boolean[] getBooleanDesignArray (Solution soln){
int numVars = soln.getNumberOfVariables();
boolean[] design = new boolean[numVars];
for (int index = 0; index < numVars; index++){
boolean decision = EncodingUtils.getBoolean(soln.getVariable(index));
design[index] = decision;
}
return design;
}
private boolean[] getCompleteBooleanDesignArray (boolean[] CurrentDesign){
return new boolean[]{CurrentDesign[0], CurrentDesign[1], CurrentDesign[2], CurrentDesign[3], CurrentDesign[4],
CurrentDesign[5], CurrentDesign[6], CurrentDesign[7], CurrentDesign[8], CurrentDesign[9],
CurrentDesign[10], CurrentDesign[11], CurrentDesign[12], CurrentDesign[13], CurrentDesign[14],
CurrentDesign[15], CurrentDesign[16], CurrentDesign[2], CurrentDesign[17], CurrentDesign[18],
CurrentDesign[19], CurrentDesign[20], CurrentDesign[21], CurrentDesign[22], CurrentDesign[23],
CurrentDesign[24], CurrentDesign[25], CurrentDesign[26], CurrentDesign[27], CurrentDesign[28],
CurrentDesign[29], CurrentDesign[30], CurrentDesign[22], CurrentDesign[0], CurrentDesign[31],
CurrentDesign[8]};
}
public boolean[] getBooleanDesignFromSolution (Solution solution) {
//// Extract the design as a boolean array
boolean[] BooleanDesign = getBooleanDesignArray(solution);
//design = EncodingUtils.getBinary(solution.getVariable());
//// Compute number of trusses in the design
return getCompleteBooleanDesignArray(BooleanDesign);
}
public int[][] getConnectivityArrayFromSolution (Solution solution) {
//// Extract the design as a boolean array
boolean[] BooleanDesign = getBooleanDesignArray(solution);
//// Obtain corresponding Connectivity Array
return ConvertToFullConnectivityArray(BooleanDesign);
}
private int[][] sliceFullConnectivityArray (int[][] fullConnectivityArray, int trussCount) {
int[][] connectivityArray = new int[trussCount][2];
for (int i = 0; i < trussCount; i++) {
for (int j = 0; j < 2; j++) {
connectivityArray[i][j] = fullConnectivityArray[i][j];
}
}
return connectivityArray;
}
public int getTrussCountFromSolution () {
return NumberOfTrusses;
}
public TrussRepeatableArchitecture getArchitectureFromConnectivityArray (int[][] connArray) {
boolean[] designFullBooleanArray = new boolean[FullConnectivityArray.length];
boolean contains = false;
int[] designFirstNodes = new int[connArray.length];
int[] designSecondNodes = new int[connArray.length];
for (int i = 0; i < connArray.length; i++) {
designFirstNodes[i] = connArray[i][0];
designSecondNodes[i] = connArray[i][1];
}
for (int i = 0; i < FullConnectivityArray.length; i++) {
int firstNode = FullConnectivityArray[i][0];
int secondNode = FullConnectivityArray[i][1];
for (int j = 0; j < connArray.length; j++) {
if (designFirstNodes[j] == firstNode) {
if (designSecondNodes[j] == secondNode) {
contains = true;
break;
}
}
}
designFullBooleanArray[i] = contains;
contains = false;
}
boolean[] designRepeatableBooleanArray = getRepeatableBooleanDesign(designFullBooleanArray);
Solution architecture = new Solution(32,2);
for (int i = 0; i < designRepeatableBooleanArray.length; i++) {
BinaryVariable var = new BinaryVariable(1);
EncodingUtils.setBoolean(var,designRepeatableBooleanArray[i]);
architecture.setVariable(i,var);
}
return new TrussRepeatableArchitecture(architecture);
}
private boolean[] getRepeatableBooleanDesign (boolean[] completeBooleanDesign) {
return new boolean[]{completeBooleanDesign[0], completeBooleanDesign[1], completeBooleanDesign[2],
completeBooleanDesign[3], completeBooleanDesign[4], completeBooleanDesign[5],
completeBooleanDesign[6], completeBooleanDesign[7], completeBooleanDesign[8],
completeBooleanDesign[9], completeBooleanDesign[10], completeBooleanDesign[11],
completeBooleanDesign[12], completeBooleanDesign[13], completeBooleanDesign[14],
completeBooleanDesign[15], completeBooleanDesign[16], completeBooleanDesign[18],
completeBooleanDesign[19], completeBooleanDesign[20], completeBooleanDesign[21],
completeBooleanDesign[22], completeBooleanDesign[23], completeBooleanDesign[24],
completeBooleanDesign[25], completeBooleanDesign[26], completeBooleanDesign[27],
completeBooleanDesign[28], completeBooleanDesign[29], completeBooleanDesign[30],
completeBooleanDesign[31], completeBooleanDesign[34]};
}
}
<file_sep>/Truss_AOS/src/main/java/seakers/trussaos/constraints/KnowledgeStochasticRanking.java
package seakers.trussaos.constraints;
import java.io.Serializable;
import java.util.*;
import org.moeaframework.core.EpsilonBoxDominanceArchive;
import org.moeaframework.core.PRNG;
import org.moeaframework.core.Solution;
import org.moeaframework.core.comparator.DominanceComparator;
/**
* This compound operator applies a series of operators with a specified
* probability in a random order.
*
* The computeProbability method is taken from the SetConsistency class from the EOSS-dev repo
*
* @author nozomihitomi, modified by @roshan94
*/
public class KnowledgeStochasticRanking implements DominanceComparator,
Serializable {
private static final long serialVersionUID = 3653864833347649396L;
/**
* The number of constraints to apply
*/
private final int numberConstraints;
/**
* the probabilities with which to apply the constraint (string property of
* architecture)
*/
private final HashMap<String, Double> probabilities;
/**
*
* Current archive
*/
private EpsilonBoxDominanceArchive archive;
public KnowledgeStochasticRanking(int numberOperators, EpsilonBoxDominanceArchive currentArchive) {
super();
this.numberConstraints = numberOperators;
this.probabilities = new HashMap<>(numberOperators);
this.archive = currentArchive;
}
public KnowledgeStochasticRanking(int numberOperators, Collection<String> constraints, EpsilonBoxDominanceArchive currentArchive) {
this.numberConstraints = numberOperators;
this.archive = currentArchive;
this.probabilities = new HashMap<>(numberOperators);
for (String str : constraints) {
this.probabilities.put(str, 1.0);
}
}
/**
* The constraint name that is a property of the architecture
*
* @param constraint name that is a property of the architecture
*/
public void appendConstraint(String constraint) {
probabilities.put(constraint, 1.0);
}
/**
* Updates the probability of applying the constraint
*
* @param constraint name that is a property of the architecture
* @param probability probability of applying the constraint
*/
public void updateProbability(String constraint, double probability) {
probabilities.replace(constraint, probability);
}
public Collection<String> getConstraints() {
return probabilities.keySet();
}
@Override
public int compare(Solution solution1, Solution solution2) {
double constraint1 = 0;
double constraint2 = 0;
int numApplied = 0;
ArrayList<String> constraints = new ArrayList<>(probabilities.keySet());
Collections.shuffle(constraints);
for (String str : constraints) {
if (numApplied >= numberConstraints) {
break;
}
double strProbability = computeProbability(str);
if (PRNG.nextDouble() < strProbability) {
constraint1 += (double) solution1.getAttribute(str);
constraint2 += (double) solution2.getAttribute(str);
}
updateProbability(str, strProbability);
}
if (constraint1 < constraint2) {
return -1;
} else if (constraint1 > constraint2) {
return 1;
} else {
return 0;
}
}
public double computeProbability(String constraintString) {
double constraintProbability = 0;
int consistentCount = 0;
for (Solution s : archive) {
if((double)s.getAttribute(constraintString) == 0){
consistentCount++;
}
}
constraintProbability = Math.max((double)consistentCount / (double)archive.getNumberOfDominatingImprovements(), 0.03);
return constraintProbability;
}
}
<file_sep>/Truss_AOS/src/main/python/hypervolume_computation.py
# -*- coding: utf-8 -*-
"""
Hypervolume computation post GA run in Java
@author: roshan94
"""
from PyGMO.util import *
import csv
import numpy as np
#### Read data from the appropriate csv file
# set to: true - to read results for fibre stiffness model run
# false - to read results for truss model run
fibre_stiffness = True
# set to: true - if Epsilon MOEA was used
# false - if AOS MOEA was used
eps_moea = True
filepath = 'C:\\SEAK Lab\\SEAK Lab Github\\KD3M3\\Truss_AOS\\result\\'
if eps_moea:
fileloc = 'Epsilon MOEA Runs\\'
if fibre_stiffness:
filename = 'Fibre Stiffness code run results\\EpsilonMOEA_emoea0_fibrestiffness_fullpop.csv'
else:
filename = 'Truss code run results\\EpsilonMOEA_emoea0_trussstiffness_fullpop.csv'
else:
fileloc = 'AOS MOEA Runs\\'
if fibre_stiffness:
filename = 'Fibre Stiffness code run results\\EpsilonMOEA_emoea0_fibrestiffness_fullpop.csv'
else:
filename = 'Truss code run results\\EpsilonMOEA_emoea0_trussstiffness_fullpop.csv'
full_filepath = filepath + fileloc + filename
with open(full_filepath,newline='') as csvfile:
data = [row for row in csv.reader(csvfile)]
designs = ["" for x in range(len(data)-1)]
num_func_evals = np.zeros((len(data)-1,1))
pen_obj1 = np.zeros((len(data)-1,1))
pen_obj2 = np.zeros((len(data)-1,1))
feas_scores = np.zeros((len(data)-1,1))
stab_scores = np.zeros((len(data)-1,1))
for x in range(len(data)-1):
designs[x] = data[x+1][0]
num_func_evals[x] = int(data[x+1][1])
pen_obj1[x] = float(data[x+1][2])
pen_obj2[x] = float(data[x+1][3])
feas_scores[x] = float(data[x+1][4])
stab_scores[x] = float(data[x+1][5])
n_des = len(designs)
des_array = np.zeros((n_des,36))
for x in range(n_des):
current_des = designs[x]
for y in range(36):
des_array[x][y] = int(current_des[y])
#### Compute true objectives
obj1 = np.zeros(n_des)
obj2 = np.zeros(n_des)
pen_fac = 1
if fibre_stiffness:
pen_fac = 2
for x in range(n_des):
pen = (np.log10(np.absolute(feas_scores[x])) + np.log10(np.absolute(stab_scores[x])))/2
obj1[x] = 15*(pen_obj1[x] + pen_fac*pen)
obj2[x] = -85000*(pen_obj2[x] + pen_fac*pen)
#### Compute and plot hypervolume values
<file_sep>/Truss_AOS/src/main/java/seakers/trussaos/initialization/BiasedInitialization.java
package seakers.trussaos.initialization;
import org.moeaframework.core.Initialization;
import org.moeaframework.core.Problem;
import org.moeaframework.core.Solution;
//import org.moeaframework.core.Variable;
import org.moeaframework.core.variable.BinaryVariable;
import org.moeaframework.core.variable.EncodingUtils;
//import java.lang.reflect.Array;
import java.util.ArrayList;
//import java.util.HashSet;
import java.util.Random;
/**
* Generates a biased random initialized population for the Truss GA problem wherein equal number of designs with 6, 12.
* 18 and 24 members in the 32 dimensional design vector are generated. In other words, 4 groups of designs are randomly
* generated.
*
* @author roshan94
*/
public class BiasedInitialization implements Initialization {
private final Problem problem;
private final int populationSize;
public BiasedInitialization(Problem problem, int populationSize) {
this.problem = problem;
this.populationSize = populationSize;
}
@Override
public Solution[] initialize() {
int solutionsPerGroup = (int) Math.round(populationSize/4);
Solution[] initialPopulation = new Solution[this.populationSize];
int solutionCount = 0;
// ArrayList<Solution> initialPopulation = new ArrayList<Solution>();
double[] numberOfMembers = {6,9,12,15};
Random rand = new Random();
boolean val;
for (int i = 0;i < 4;i++) {
double TrueProb = numberOfMembers[i]/32;
for (int j = 0;j < solutionsPerGroup;j++) {
Solution solution = this.problem.newSolution();
for (int k = 0;k < solution.getNumberOfVariables();++k) {
val = rand.nextFloat() < TrueProb;
BinaryVariable var = new BinaryVariable(1);
EncodingUtils.setBoolean(var,val);
solution.setVariable(k,var);
}
initialPopulation[solutionCount] = solution;
solutionCount++;
// initialPopulation.add(solution);
}
}
// return (Solution[]) initialPopulation.toArray();
return initialPopulation;
}
}
<file_sep>/Truss_AOS/src/main/java/seakers/trussaos/MOEARun.java
package seakers.trussaos;
import org.moeaframework.core.*;
import org.moeaframework.core.comparator.ChainedComparator;
import org.moeaframework.core.comparator.ParetoObjectiveComparator;
import org.moeaframework.core.operator.CompoundVariation;
import org.moeaframework.core.operator.OnePointCrossover;
import org.moeaframework.core.operator.binary.BitFlip;
import org.moeaframework.util.TypedProperties;
import seakers.aos.aos.AOSMOEA;
import seakers.aos.creditassignment.offspringparent.OffspringParentDomination;
import seakers.aos.operator.AOSVariation;
import seakers.aos.operator.AOSVariationOP;
import com.mathworks.engine.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.moeaframework.algorithm.EpsilonMOEA;
import org.moeaframework.core.operator.RandomInitialization;
import org.moeaframework.core.operator.TournamentSelection;
//import org.moeaframework.core.operator.real.PM;
//import org.moeaframework.core.operator.real.SBX;
import seakers.aos.operatorselectors.OperatorSelector;
import seakers.aos.operatorselectors.ProbabilityMatching;
import seakers.trussaos.initialization.BiasedInitialization;
import seakers.trussaos.operators.AddMember;
import seakers.trussaos.operators.RemoveIntersection;
import seakers.trussaos.constraints.DisjunctiveNormalForm;
import seakers.trussaos.constraints.KnowledgeStochasticRanking;
/**
* Executable class for the eMOEA run with/without AOS for the Truss Optimization problem.
*
* @author roshan94
*/
public class MOEARun {
/**
* pool of resources
*/
private static ExecutorService pool;
/**
* Executor completion services helps remove completed tasks
*/
private static CompletionService<Algorithm> ecs;
/**
* Matlab Engine for function evaluation
*/
private static MatlabEngine engine;
public static void main(String[] args) throws InterruptedException, ExecutionException, EngineException {
// Define problem parameters
//String csvPath = "C:\\SEAK Lab\\SEAK Lab Github\\KD3M3\\Truss_AOS\\src\\main\\java\\seakers\\trussaos";
String csvPath = System.getProperty("user.dir");
double targetStiffnessRatio = 1;
boolean useFibreStiffness = false;
boolean biasedInitialization = true;
/**
* Mode = 1 for conventional e-MOEA run
* = 2 for AOS MOEA run
* = 3 for soft constraints
*/
int mode = 1;
/**
* soft_con = 1 for DNF
* = 2 for ACH
*/
int soft_con = 2;
int numCPU = 1;
int numRuns = 1;
pool = Executors.newFixedThreadPool(numCPU);
ecs = new ExecutorCompletionService<>(pool);
engine = MatlabEngine.startMatlab();
//String userPathOutput = "";
//userPathOutput = engine.feval("userpath",csvPath);
//create the desired algorithm
//parameters and operators for search
double[] epsilonDouble = new double[]{0.01, 0.01};
TypedProperties properties = new TypedProperties();
//search paramaters set here
int popSize = 100;
int maxEvals = 10000;
properties.setInt("maxEvaluations", maxEvals);
properties.setInt("populationSize", popSize);
double mutationProbability = 1. / 32.;
properties.setDouble("mutationProbability", mutationProbability);
Variation singlecross;
Variation bitFlip;
Initialization initialization;
double crossoverProbability = 1.0;
// For AOS MOEA Run
boolean useStability = false;
boolean useFeasibility = false;
for (int i = 0; i < numRuns; i++) {
// Create a new problem class
TrussAOSProblem trussProblem = new TrussAOSProblem(csvPath,useFibreStiffness,targetStiffnessRatio,engine);
if (biasedInitialization){
initialization = new BiasedInitialization(trussProblem, popSize);
}
else {
initialization = new RandomInitialization(trussProblem, popSize);
}
// Initialize population structure for algorithm
Population population = new Population();
EpsilonBoxDominanceArchive archive = new EpsilonBoxDominanceArchive(epsilonDouble);
ChainedComparator comp = new ChainedComparator(new ParetoObjectiveComparator());
TournamentSelection selection = new TournamentSelection(2, comp);
switch(mode) {
case 1: // Conventional Epsilon MOEA Run
properties.setDouble("crossoverProbability", crossoverProbability);
singlecross = new OnePointCrossover(crossoverProbability);
bitFlip = new BitFlip(mutationProbability);
CompoundVariation var = new CompoundVariation(singlecross, bitFlip);
Algorithm eMOEA = new EpsilonMOEA(trussProblem, population, archive, selection, var, initialization);
ecs.submit(new EvolutionarySearch(eMOEA, properties, csvPath + File.separator + "result", "emoea" + String.valueOf(i) + "_biasedinit", engine, useFibreStiffness, targetStiffnessRatio));
break;
case 2: // AOS MOEA Run
//setup for saving results
properties.setBoolean("saveQuality", true);
properties.setBoolean("saveCredits", true);
properties.setBoolean("saveSelection", true);
// TESTING
//double onePointCrossoverProbability = 1.0;
//double twoPointCrossoverProbability = 0.8;
//double halfUniformCrossoverProbability = 0.75;
//double uniformCrossoverProbability = 0.6;
//ArrayList<Variation> operators = new ArrayList<>();
//add domain-independent heuristics
//operators.add(new CompoundVariation(new OnePointCrossover(onePointCrossoverProbability), new BitFlip(mutationProbability)));
//operators.add(new CompoundVariation(new TwoPointCrossover(twoPointCrossoverProbability), new BitFlip(mutationProbability)));
//operators.add(new CompoundVariation(new HUX(halfUniformCrossoverProbability), new BitFlip(mutationProbability)));
//operators.add(new CompoundVariation(new UniformCrossover(uniformCrossoverProbability), new BitFlip(mutationProbability)));
// IMPLEMENTATION WITH ACTUAL REPAIR OPERATORS
double[][] globalNodePositions = trussProblem.getNodalConnectivityArray();
ArrayList<Variation> operators = new ArrayList<>();
Variation addMember = new AddMember(useFeasibility, engine, globalNodePositions);
Variation removeIntersection = new RemoveIntersection(useStability, engine, globalNodePositions);
operators.add(new CompoundVariation(new OnePointCrossover(crossoverProbability), new BitFlip(mutationProbability)));
operators.add(addMember);
operators.add(removeIntersection);
// DisjunctiveNormalForm dnf = new DisjunctiveNormalForm(constraints);
// EpsilonKnoweldgeConstraintComparator epskcc = new EpsilonKnoweldgeConstraintComparator(epsilonDouble, dnf)
properties.setDouble("pmin", 0.1);
//create operator selector
//OperatorSelector operatorSelector = new AdaptivePursuit(operators, 0.8, 0.8, 0.1);
OperatorSelector operatorSelector = new ProbabilityMatching(operators, 0.6, 0.1);
//create credit assignment
//SetImprovementDominance creditAssignment = new SetImprovementDominance(archive, 1, 0);
OffspringParentDomination creditAssignment = new OffspringParentDomination(1.0,0.5,0.0);
//create AOS
//AOSVariation aosStrategy = new AOSVariationSI(operatorSelector, creditAssignment, popSize);
AOSVariation aosStrategy = new AOSVariationOP(operatorSelector,creditAssignment,popSize);
EpsilonMOEA emoea = new EpsilonMOEA(trussProblem, population, archive,
selection, aosStrategy, initialization, comp);
AOSMOEA aos = new AOSMOEA(emoea, aosStrategy, true);
aos.setName("constraint_adaptive");
ecs.submit(new EvolutionarySearch(aos, properties, csvPath + File.separator + "result", aos.getName() + String.valueOf(i), engine, useFibreStiffness, targetStiffnessRatio));
break;
case 3: // Soft Constraints
if (soft_con == 1){
globalNodePositions = trussProblem.getNodalConnectivityArray();
//operators = new ArrayList<>();
addMember = new AddMember(useFeasibility, engine, globalNodePositions);
removeIntersection = new RemoveIntersection(useStability, engine, globalNodePositions);
//operators.add(new CompoundVariation(new OnePointCrossover(crossoverProbability), new BitFlip(mutationProbability)));
//operators.add(addMember);
//operators.add(removeIntersection);
properties.setDouble("crossoverProbability", crossoverProbability);
singlecross = new OnePointCrossover(crossoverProbability);
bitFlip = new BitFlip(mutationProbability);
var = new CompoundVariation(singlecross, bitFlip);
HashMap<Variation, String> constraintOperatorMap = new HashMap<>();
constraintOperatorMap.put(addMember, "StabilityViolation");
constraintOperatorMap.put(removeIntersection, "FeasibilityViolation");
HashSet<String> constraints = new HashSet<>(constraintOperatorMap.values());
DisjunctiveNormalForm dnf = new DisjunctiveNormalForm(constraints);
// EpsilonKnoweldgeConstraintComparator epskcc = new EpsilonKnoweldgeConstraintComparator(epsilonDouble, dnf);
selection = new TournamentSelection(2, dnf);
emoea = new EpsilonMOEA(trussProblem, population, archive, selection, var, initialization, dnf);
ecs.submit(new EvolutionarySearch(emoea, properties, csvPath + File.separator + "result", "emoea_dnf" + String.valueOf(i), engine, useFibreStiffness, targetStiffnessRatio));
break;
}
else if (soft_con == 2) {
properties.setDouble("crossoverProbability", crossoverProbability);
singlecross = new OnePointCrossover(crossoverProbability);
bitFlip = new BitFlip(mutationProbability);
var = new CompoundVariation(singlecross, bitFlip);
globalNodePositions = trussProblem.getNodalConnectivityArray();
addMember = new AddMember(useFeasibility, engine, globalNodePositions);
removeIntersection = new RemoveIntersection(useStability, engine, globalNodePositions);
HashMap<Variation, String> constraintOperatorMap = new HashMap<>();
constraintOperatorMap.put(addMember, "StabilityViolation");
constraintOperatorMap.put(removeIntersection, "FeasibilityViolation");
HashSet<String> constraints = new HashSet<>(constraintOperatorMap.values());
KnowledgeStochasticRanking ksr = new KnowledgeStochasticRanking(constraintOperatorMap.size(), constraintOperatorMap.values(), archive);
selection = new TournamentSelection(2, ksr);
emoea = new EpsilonMOEA(trussProblem, population, archive, selection, var, initialization, ksr);
ecs.submit(new EvolutionarySearch(emoea, properties, csvPath + File.separator + "result", "emoea_ach" + String.valueOf(i), engine, useFibreStiffness, targetStiffnessRatio));
break;
}
default:
throw new IllegalArgumentException(String.format("%d is an invalid option", mode));
}
}
for (int i = 0; i < numRuns; i++) {
try {
Algorithm alg = ecs.take().get();
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(MOEARun.class.getName()).log(Level.SEVERE, null, ex);
}
}
pool.shutdown();
engine.close();
}
}
<file_sep>/Truss_AOS/src/main/java/seakers/trussaos/EvolutionarySearch.java
package seakers.trussaos;
import seakers.aos.aos.AOS;
import seakers.aos.history.AOSHistoryIO;
import seakers.trussaos.ResultIO;
import com.mathworks.engine.*;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import org.moeaframework.algorithm.AbstractEvolutionaryAlgorithm;
import org.moeaframework.core.Algorithm;
import org.moeaframework.core.Population;
import org.moeaframework.core.Solution;
import org.moeaframework.util.TypedProperties;
public class EvolutionarySearch implements Callable<Algorithm> {
private final String savePath;
private final String name;
private final Algorithm alg;
private final TypedProperties properties;
private static MatlabEngine engine;
private static boolean useFibreStiffness;
private static double targetStiffnessRatio;
public EvolutionarySearch(Algorithm alg, TypedProperties properties, String savePath, String name, MatlabEngine eng, boolean fibreStiffness, double targetRatio) {
this.alg = alg;
this.properties = properties;
this.savePath = savePath;
this.name = name;
engine = eng;
targetStiffnessRatio = targetRatio;
useFibreStiffness = fibreStiffness;
}
@Override
public Algorithm call() throws IOException, ExecutionException, InterruptedException {
int populationSize = (int) properties.getDouble("populationSize", 600);
int maxEvaluations = (int) properties.getDouble("maxEvaluations", 10000);
// run the executor using the listener to collect results
System.out.println("Starting " + alg.getClass().getSimpleName() + " on " + alg.getProblem().getName() + " with pop size: " + populationSize);
alg.step();
long startTime = System.currentTimeMillis();
HashSet<Solution> allSolutions = new HashSet<>();
Population initPop = ((AbstractEvolutionaryAlgorithm) alg).getPopulation();
for (int i = 0; i < initPop.size(); i++) {
initPop.get(i).setAttribute("NFE", 0);
allSolutions.add( initPop.get(i));
}
while (!alg.isTerminated() && (alg.getNumberOfEvaluations() < maxEvaluations)) {
if (alg.getNumberOfEvaluations() % 250 == 0) {
System.out.println("NFE: " + alg.getNumberOfEvaluations());
System.out.print("Popsize: " + ((AbstractEvolutionaryAlgorithm) alg).getPopulation().size());
System.out.println(" Archivesize: " + ((AbstractEvolutionaryAlgorithm) alg).getArchive().size());
}
alg.step();
Population pop = ((AbstractEvolutionaryAlgorithm) alg).getPopulation();
for(int i=1; i<3; i++){
Solution s = pop.get(pop.size() - i);
s.setAttribute("NFE", alg.getNumberOfEvaluations());
allSolutions.add(s);
}
}
alg.terminate();
long finishTime = System.currentTimeMillis();
System.out.println("Done with optimization. Execution time: " + ((finishTime - startTime) / 1000) + "s");
ResultIO resultIO = new ResultIO((TrussAOSProblem) alg.getProblem(),engine,useFibreStiffness,targetStiffnessRatio);
//String filename = savePath + File.separator + alg.getClass().getSimpleName() + "_" + name;
//ResultIO.savePopulation(((AbstractEvolutionaryAlgorithm) alg).getPopulation(), filename);
//ResultIO.savePopulation(new Population(allSolutions), filename + "_all");
//ResultIO.saveObjectives(alg.getResult(), filename);
String popCsvFilename;
if (useFibreStiffness) {
popCsvFilename = savePath + File.separator + alg.getClass().getSimpleName() + "_" + name + "_fibrestiffness_" + "fullpop" + ".csv";
}
else {
popCsvFilename = savePath + File.separator + alg.getClass().getSimpleName() + "_" + name + "_trussstiffness_" + "fullpop" + ".csv";
}
resultIO.savePopulationHistoryToCsv(allSolutions, popCsvFilename);
String csvFilename;
if (useFibreStiffness) {
csvFilename = savePath + File.separator + alg.getClass().getSimpleName() + "_" + name + "_fibrestiffness" + ".csv";
}
else {
csvFilename = savePath + File.separator + alg.getClass().getSimpleName() + "_" + name + "_trussstiffness" + ".csv";
}
resultIO.saveFinalResultToCsv(((AbstractEvolutionaryAlgorithm) alg).getPopulation(), csvFilename);
if (alg instanceof AOS) {
AOS algAOS = (AOS) alg;
if (properties.getBoolean("saveQuality", false)) {
AOSHistoryIO.saveQualityHistory(algAOS.getQualityHistory(), new File(savePath + File.separator + name + "_qual" + ".csv"), ",");
}
if (properties.getBoolean("saveCredits", false)) {
AOSHistoryIO.saveCreditHistory(algAOS.getCreditHistory(), new File(savePath + File.separator + name + "_credit" + ".csv"), ",");
}
if (properties.getBoolean("saveSelection", false)) {
AOSHistoryIO.saveSelectionHistory(algAOS.getSelectionHistory(), new File(savePath + File.separator + name + "_hist" + ".csv"), ",");
}
}
return alg;
}
}
| f1c4e2efdcfdc07ab5853b2ec7efab5ffd09c099 | [
"Java",
"Python"
] | 6 | Java | amchaudhari/KDDMM | 94d03bb86294e4bb8f489fe2f6315b36c689a824 | d3d4e11834ad6aee3d1558473712747a36ffef19 |
refs/heads/master | <file_sep>plotall <- function() {
source("plot1.R")
source("plot2.R")
source("plot3.R")
source("plot4.R")
plot1()
plot2()
plot3()
plot4()
}<file_sep>plot1 <- function () {
library(graphics)
source("read.file.R")
data <- read.file()
# Create the plot.
par(bg = "white", mfcol = c(1,1))
hist(data$Global_active_power, col="red", main = "Global Active Power", xlab = "Global Active Power (kilowatts)", bg = "white")
# Copy to PNG file.
dev.copy(png, file = "plot1.png")
dev.off()
}<file_sep>plot2 <- function() {
library(graphics)
source("read.file.R")
data <- read.file()
# Create the plot.
par(bg = "white", mfcol = c(1,1))
plot(data$Date, data$Global_active_power, type = "l", xlab = "",
ylab = "Global Active Power (kilowatts)")
# Copy to PNG file.
dev.copy(png, file = "plot2.png")
dev.off()
}<file_sep>read.file <- function() {
# Read in the file. Reading only the lines corresponding to
# 2007-02-01 and 2007-02-02.
data <- read.table(file="../household_power_consumption.txt", sep = ";", header = FALSE, na.strings="?", colClasses = c("character", "character", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric"), skip=66637, nrows=69518-66638, comment.char="")
# Convert the dates.
data$V1 <- strptime(paste(data$V1, data$V2), "%d/%m/%Y %T")
# Name the columns.
names(data) <- c("Date", "Time", "Global_active_power", "Global_reactive_power", "Voltage", "Global_intensity", "Sub_metering_1", "Sub_metering_2", "Sub_metering_3")
data
}<file_sep>plot3 <- function() {
library(graphics)
source("read.file.R")
data <- read.file()
# Create the plot.
par(bg = "white", mfcol = c(1,1))
plot(data$Date, data$Sub_metering_1, type = "l", xlab = "",
ylab = "Energy sub metering")
lines(data$Date, data$Sub_metering_2, type = "l", col = "red")
lines(data$Date, data$Sub_metering_3, type = "l", col = "blue")
legend("topright", col = c("black", "red", "blue"),
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
lty = "solid")
# Copy to PNG file.
dev.copy(png, file = "plot3.png")
dev.off()
}<file_sep>plot4 <- function() {
library(graphics)
source("read.file.R")
data <- read.file()
# Create the plot.
par(bg = "white", mfcol = c(2,2))
# Create the first plot.
plot(data$Date, data$Global_active_power, type = "l", xlab = "",
ylab = "Global Active Power")
# Create the second plot.
plot(data$Date, data$Sub_metering_1, type = "l", xlab = "",
ylab = "Energy sub metering")
lines(data$Date, data$Sub_metering_2, type = "l", col = "red")
lines(data$Date, data$Sub_metering_3, type = "l", col = "blue")
legend("topright", col = c("black", "red", "blue"),
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
lty = "solid", bty = "n")
# Create the third plot.
plot(data$Date, data$Voltage, type = "l", xlab = "datetime", ylab = "Voltage")
# Create fourth plot.
plot(data$Date, data$Global_reactive_power, type = "l", xlab = "datetime",
ylab = "Global_reactive_power")
# Copy to PNG file.
dev.copy(png, file = "plot4.png")
dev.off()
} | def0b6736fb610dc3b20a503254ac1e2cda308a5 | [
"R"
] | 6 | R | pizzic/ExData_Plotting1 | c86f0e3104e035ad2d4cb78eebcc820046727771 | 88f432c34dc456986bd6ba73915dd9dc2049a847 |
refs/heads/master | <file_sep>'use strict';
/*
#่ใๆน
1. ้็บใๅฎ่กใฏใในใฆdevใใฃใฌใฏใใชใฎไธญใง่กใใ
2. prdใใฃใฌใฏใใชใฏๆฌ็ชใซupใใใใฎใฎใฏใชใชใใฃใง่กใใ
*/
var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var imagemin = require('gulp-imagemin');
var coffee = require('gulp-coffee');
var plumber = require('gulp-plumber');
var browserSync = require('browser-sync');
var reload = browserSync.reload
//image minify
gulp.task('images',function(){
return gulp.src('dev/images/**/*').pipe(plumber()).pipe(imagemin({
progressive:true,
interlaced:true
})).pipe(gulp.dest('prd/images')).pipe(reload({stream:true,once:true}));
});
// compile scss file
gulp.task('scss', function () {
return gulp.src(['dev/styles/**/*.scss']).pipe(plumber())
.pipe(sass({
style: 'expanded',
precision: 10,
loadPath: ['dev/styles']
}))
.pipe(gulp.dest('dev/styles'))
});
gulp.task('coffee', function(){
return gulp.src(['dev/scripts/**/*.coffee']).pipe(plumber()).pipe( coffee({
bare:true
})).pipe( gulp.dest('dev/scripts') );
})
// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
return gulp.src('dev/**/*.html').pipe(gulp.dest('prd'))
});
// Watch Files For Changes & Reload
gulp.task('serve', function () {
browserSync.init(null, {
server: {
baseDir: ['dev']
}
});
gulp.watch(['dev/**/*.html'], ['html']);
gulp.watch(['dev/styles/**/*.scss'],['scss']);
gulp.watch(['dev/scripts/**/*.coffee'],['coffee']);
});
//Build Production Files
gulp.task('build', function(){
gulp.src('dev/index.html').pipe(gulp.dest('prd'));
gulp.src('dev/styles/**/*.css').pipe(gulp.dest('prd/styles'));
gulp.src('dev/scripts/**/*.js').pipe(gulp.dest('prd/scripts'));
gulp.run('images');
});
<file_sep># yohawing website template
| b4f1c3dc4d5325860609c91536ab078594fad5da | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | yohawing/yohawing-template | 80432a6b63dda7062ef218dd0aa892fc5782f0dc | 0bafca9f194bb6e98334d726d1b7935e437c8b8a |
refs/heads/master | <file_sep>from linkkit import linkkit
import time
from pi_info import *
def on_device_dynamic_register(rc, value, userdata):
if rc == 0:
print("dynamic register device success, rc:%d, value:%s" % (rc, value))
else:
print("dynamic register device fail,rc:%d, value:%s" % (rc, value))
# lk.on_device_dynamic_register = on_device_dynamic_register
def on_connect(session_flag, rc, userdata):
print("on_connect:%d,rc:%d,userdata:" % (session_flag, rc))
pass
def on_disconnect(rc, userdata):
print("on_disconnect:rc:%d,userdata:" % rc)
lk = linkkit.LinkKit(
host_name="cn-shanghai",
product_key="",
device_name="",
device_secret="",
product_secret="")
lk.thing_setup("model.json") #้
็ฝฎๆไปถ
lk.on_connect = on_connect
lk.on_disconnect = on_disconnect
lk.connect_async()
lk.start_worker_loop()
time.sleep(5)
while(1):
pass
<file_sep># aliyun-mqtt
raspberry connect with aliyun-iot by mqtt
่ฟๆฏๆๆ ่ๆดพ่ฟๆฅ้ฟ้ไบ็ไปฃ็ ๅคไปฝ
๏ผๆฒกๆๅๆๅกๅๅบ็ไปฃ็ ๏ผ
<file_sep>import time
from rpi_ws281x import Color
FiveColor= [Color(255,255,255),Color(0,0,0),Color(0,255,0),Color(255,0,0),Color(0,0,255)]
BaseColor = Color(100,165,0) #ๅบ่ฒ
ColorList = []
ColorList.append(FiveColor)
class LED():
def __init__(self,id):
self._led_id = id
self._index_color_list = 0
self._recycle = -1
self._cur_color_index = 0
self._last_time = 0
self._on_delay = 10 #ไบฎ็ฏๆถ้ด๏ผไปฅ10msไธบๅไฝ
def _set_color(self,color_id):
self._index_color_list = color_id
self._last_time = time.time()
def _set_cycle(self, cycle):
self._recycle = cycle
self._cur_color_index = -1
self._last_time = 0
def _set_delay(self,_on_delay):
self._on_delay = _on_delay
def get_cur_color(self):
if(time.time()-self._last_time> 0.01*self._on_delay):
self._last_time = time.time()
self._cur_color_index +=1
if(self._cur_color_index>=len(ColorList[self._index_color_list])):
self._cur_color_index = 0
self._recycle -=1
if self._recycle>0:
return ColorList[self._index_color_list][self._cur_color_index]
else:
return BaseColor
else:
return None
<file_sep>from multiprocessing import Process,Manager
from flask import Flask,request
from led_control import LedControl
LED_COUNT = 256
app = Flask(__name__)
cmd_queue = Manager().Queue()
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/led')
def led():
mod = request.args.get('m', '0')
function = request.args.get('f','0')
led_row = request.args.get('r','0')
led_column = request.args.get('c','0')
cycle = request.args.get('k','0')
delay = request.args.get('d','0')
data = {"mod":int(mod),"function":int(function),"led_row":int(led_row),
"led_column":int(led_column),"cycle":int(cycle),"delay":int(delay)}
cmd_queue.put(data)
return "recieve"
def _light(cmd_queue):
led_control = LedControl(32,8,2)
while(True):
led_control.light()
try:
data = cmd_queue.get(True,0.01)
except:
pass
else:
led_control.del_cmd(data)
if __name__ == '__main__':
data = {"mod":1,"function":7, "cycle":1,"delay":1}
cmd_queue.put(data)
# data = {"mod":1,"function":6, "cycle":1,"delay":1}
# cmd_queue.put(data)
# data = {"mod":1,"function":5, "cycle":1,"delay":1}
# cmd_queue.put(data)
# data = {"mod":1,"function":4, "cycle":1,"delay":1}
# cmd_queue.put(data)
# data = {"mod":1,"function":3, "cycle":1,"delay":1}
# cmd_queue.put(data)
# data = {"mod":1,"function":2, "cycle":1,"delay":1}
# cmd_queue.put(data)
# data = {"mod":1,"function":1, "cycle":1,"delay":1}
# cmd_queue.put(data)
# data = {"mod":1,"function":0, "cycle":1,"delay":1}
# cmd_queue.put(data)
process = Process(target=_light,args=(cmd_queue,))
process.daemon = True
process.start()
app.run(host='0.0.0.0')<file_sep>import time
import random
from rpi_ws281x import PixelStrip, Color
from led import LED
wan = [ [1,1,1,0,1],
[0,0,1,0,1],
[1,1,1,1,1],
[1,0,1,0,0],
[1,0,1,1,1]]
zhong = [[0,0,1,0,0],
[1,1,1,1,1],
[1,0,1,0,1],
[1,1,1,1,1],
[0,0,1,0,0]]
class LedControl():
def __init__(self,rows,columns,serial_type=1,led_pin=21):
##
# serial_type ไฟกๅท็บฟ่ฟๆฅๆนๅผ๏ผ 1่กจ็คบๅผๅญๅฝข่ฟ็บฟ๏ผ2่กจ็คบZๅญๅฝข่ฟ็บฟ
##
self.rows = rows
self.columns = columns
self.led_numbers = rows*columns
self._mod = 1
self.leds = []
for i in range(self.led_numbers):
self.leds.append(LED(i))
self.led_index = [[0 for i in range(self.columns)] for i in range(self.rows)]
if(serial_type == 1):
for i in range(0,rows,2):
for j in range(0,self.columns):
self.led_index[i][j] = i*self.columns+j
for i in range(1,rows,2):
for j in range(0,self.columns):
self.led_index[i][j] = (i+1)*self.columns-(j+1)
elif(serial_type==2):
for i in range(0,rows):
for j in range(0,columns):
self.led_index[i][j]= i*self.columns+j
elif(serial_type==3):
for i in range(rows-1,-1,-2):
for j in range(0,columns):
self.led_index[i][j]=j
for i in range(rows-2,-1,-2):
for j in range(0,columns):
self.led_index[i][j]=columns-1-j
for row in range(0,rows):
for j in range(0,columns):
self.led_index[row][j] = (rows-row-1)*columns+self.led_index[row][j]
self.strip = PixelStrip(self.led_numbers, led_pin)
self.strip.begin()
self.strip.setBrightness(255)
def del_cmd(self,paras):
self._mod = paras["mod"]
if(paras["mod"]==1): # ๅ
จไฝๆพ็คบ
if(paras["function"]==0):
self._symbolLeftToRight(wan,Color(100,100,0),500)
elif(paras["function"]== 1):
self._symbolRightToLeft(wan,Color(100,100,0),500)
elif(paras["function"]==2):
self._leftToRight(Color(100,100,0),50)
elif(paras["function"]==3):
self._symbolLeftToRight(zhong,Color(100,100,0),500)
elif(paras["function"]==4):
self._leftToRight(Color(100,100,0),50)
elif(paras["function"]==5):
self._rightToLeft(Color(100,100,0),50)
elif(paras["function"]==6):
self._bottomToTop(Color(100,100,0),50)
elif(paras["function"]==7):
self._topToBottom(Color(100,100,0),50)
elif(paras["mod"]==0): #ๅไธชๆพ็คบ
row = paras["led_row"]-1
col = paras["led_column"]-1
led_index = self.led_index[row][col]
self.leds[led_index]._set_color(0)
self.leds[led_index]._set_cycle(paras["cycle"])
self.leds[led_index]._set_delay(paras["delay"])
def light(self):
if(self._mod == 0): # ๅไธชๆพ็คบ
for i in range(self.led_numbers):
if(self.leds[i]._recycle>0):
color = self.leds[i].get_cur_color()
if(not color is None):
self.strip.setPixelColor(i,color)
print("็ฌฌiไธช็ฏ",i,color)
self.strip.show()
def _showGivenSymbolAt(self,symbol,x,y,color,bgcolor=Color(0,0,0)):
m = len(symbol)
n = len(symbol[0])
for i in range(m):
for j in range(n):
if(symbol[i][j]==1):
self.strip.setPixelColor( self.led_index[i+x][j+y],color)
else:
self.strip.setPixelColor(self.led_index[i+x][j+y],bgcolor)
self.strip.show()
def _colorWipe(self, color):
"""Wipe color across display a pixel at a time."""
for i in range(self.led_numbers):
self.strip.setPixelColor(i, color)
self.strip.show()
def _theaterChase(self, color, wait_ms=50, iterations=10):
"""Movie theater light style chaser animation."""
for j in range(iterations):
for q in range(3):
for i in range(0, self.led_numbers, 3):
self.strip.setPixelColor(i + q, color)
self.strip.show()
time.sleep(wait_ms / 1000.0)
for i in range(0, self.led_numbers, 3):
self.strip.setPixelColor(i + q, 0)
def _wheel(self,pos):
"""Generate rainbow colors across 0-255 positions."""
if pos < 85:
return Color(pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return Color(255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return Color(0, pos * 3, 255 - pos * 3)
def _rainbow(self, wait_ms=20, iterations=1):
"""Draw rainbow that fades across all pixels at once."""
for j in range(256 * iterations):
for i in range(self.led_numbers):
self.strip.setPixelColor(i, self._wheel((i + j) ) & 255)
self.strip.show()
time.sleep(wait_ms / 1000.0)
def _rainbowCycle(self, wait_ms=20, iterations=5):
"""Draw rainbow that uniformly distributes itself across all pixels."""
for j in range(256 * iterations):
for i in range(self.led_numbers):
self.strip.setPixelColor(i, self._wheel(
(int(i * 256 / self.strip.numPixels()) + j) & 255))
self.strip.show()
time.sleep(wait_ms / 1000.0)
def _theaterChaseRainbow(self, wait_ms=50):
"""Rainbow movie theater light style chaser animation."""
for j in range(256):
for q in range(3):
for i in range(0, self.led_numbers, 3):
self.strip.setPixelColor(i+q, self._wheel((i + j) ))
self.strip.show()
time.sleep(wait_ms / 1000.0)
for i in range(0, self.led_numbers, 3):
self.strip.setPixelColor(i+q, Color(0,0,0))
self.strip.show()
def _leftToRight(self,color,wait_ms=50):
for j in range(self.columns):
for i in range(self.rows):
self.strip.setPixelColor(self.led_index[i][j],color)
self.strip.show()
time.sleep(wait_ms/1000.0)
def _rightToLeft(self,color,wait_ms=50):
for j in reversed(range(self.columns)):
for i in range(self.rows):
self.strip.setPixelColor(self.led_index[i][j],color)
self.strip.show()
time.sleep(wait_ms/1000.0)
def _topToBottom(self,color,wait_ms=50):
for i in range(self.rows):
for j in range(self.columns):
self.strip.setPixelColor(self.led_index[i][j],color)
self.strip.show()
time.sleep(wait_ms/1000.0)
def _bottomToTop(self,color,wait_ms=50):
for i in reversed(range(self.rows)):
for j in range(self.columns):
self.strip.setPixelColor(self.led_index[i][j],color)
self.strip.show()
time.sleep(wait_ms/1000.0)
def _symbolLeftToRight(self,symbol,color,wait_ms):
for j in range(self.columns-len(symbol[0])):
self._showGivenSymbolAt(symbol,0,j,color)
time.sleep(wait_ms/1000.0)
self._colorWipe(Color(0,0,0))
def _symbolRightToLeft(self,symbol,color,wait_ms):
for j in reversed(range(self.columns-len(symbol[0]))):
self._showGivenSymbolAt(symbol,0,j,color)
time.sleep(wait_ms/1000.0)
self._colorWipe(Color(0,0,0))
if __name__ == "__main__":
led_control = LedControl(32,8,3)
led_control.strip.setBrightness(100)
led_control._theaterChase(Color(100,100,0),50)
led_control._rainbow(10,5)
for i in range(1):
led_control._leftToRight(Color(100,100,0),50)
led_control._rightToLeft(Color(0,0,0),50)
for i in range(1):
led_control._topToBottom(Color(100,100,0),50)
led_control._bottomToTop(Color(0,0,0),50)
led_control._rainbowCycle(10)
<file_sep># sudo python3 /home/ubuntu/ledcontrol/webserver.py
<file_sep>import os
import random
# Return CPU temperature as a character string
def getCPUtemp():
tempFile = open( "/sys/class/thermal/thermal_zone0/temp" )
cpu_temp = round(float(tempFile.read()) / 1000, 1)
tempFile.close()
return cpu_temp
# Return RAM information (unit=kb) in a list
# Index 0: total RAM
# Index 1: used RAM
# Index 2: free RAM
def getRAMinfo():
p = os.popen('free')
i = 0
while 1:
i = i + 1
line = p.readline()
if i==2:
return(line.split()[1:4])
# Return % of CPU used by user as a character string
def getCPUuse():
return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))
# Return information about disk space as a list (unit included)
# Index 0: total disk space
# Index 1: used disk space
# Index 2: remaining disk space
# Index 3: percentage of disk used
def getDiskSpace():
p = os.popen("df -h /")
i = 0
while 1:
i = i +1
line = p.readline()
if i==2:
return(line.split()[1:5])
def getUpTime():
res = float(os.popen("cat /proc/uptime").readline().split()[0])
return(round(res / 60))
#
def get_pi_info():
# CPU informatiom
CPU_temp = getCPUtemp()
CPU_usage = float(getCPUuse())
UP_time = getUpTime()
# RAM information
# Output is in kb, here I convert it in Mb for readability
RAM_stats = getRAMinfo()
RAM_total = round(int(RAM_stats[0]) / 1000,1)
RAM_used = round(int(RAM_stats[1]) / 1000,1)
RAM_free = round(int(RAM_stats[2]) / 1000,1)
# Disk information
DISK_stats = getDiskSpace()
DISK_total = DISK_stats[0]
DISK_used = DISK_stats[1]
DISK_remain = float(DISK_stats[2].strip('G'))
DISK_perc = DISK_stats[3]
pdata = {
'cpu_temperature': CPU_temp,
'cpu_usage': CPU_usage,
'remain_storage': DISK_remain,
'UpTime': UP_time
}
return pdata
if __name__ == '__main__':
print(get_pi_info())
| 001090098170455f2e63656b2bbd9084b6173e9c | [
"Markdown",
"Python",
"Shell"
] | 7 | Python | lijiecamel/aliyun-mqtt | b1d4e3a1dd9ba71f9fc08859917537f463c15a7b | d7850aef343a03d34eb576d6a8f32e298e5fc2aa |
refs/heads/master | <repo_name>XiaoChenqi/commonlib<file_sep>/src/main/java/com/ezdata/commonlib/core/mvp/BasePresenter.java
package com.ezdata.commonlib.core.mvp;
//import com.ezdata.xcqframeopencv.data.DataManager;
import com.ezdata.commonlib.data.DataManager;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;
/**
* <p>
* Base class that implements the Presenter interface and provides a base implementation for
* attachView() and detachView(). It also handles keeping a reference to the mvpView that
* can be accessed from the children classes by calling getMvpView().
* <p>
* Created by MSI-PC on 2018/4/3.
*/
public class BasePresenter<T extends MvpView> implements Presenter<T> {
//protected Subscription subscription;//่ฟๆฏrxjava1็็จๆณ
private T mMvpView;
public DataManager mDataManager;
//protected CompositeDisposable mCompositeDisposable;ๆๅจๆงๅถ่งฃ็ป่ฎข้
ไบไปถ็ๆนๅผๆถๅ๏ผๆไฝฟ็จ๏ผๆๆถไธ็จ่ฟ็งๆนๅผ
//public static Disposable disposable;//่งๅฏ่
ๅฏน่ขซ่งๅฏ่
็่ฎข้
ๅฏน่ฑก๏ผๅฏ็จไบๅๆถ่ฎข้
@Override
public void attachView(T mvpView) {
this.mMvpView = mvpView;
this.mDataManager = DataManager.getInstance();
}
@Override
public void detachView() {
this.mMvpView = null;
unsubscribe();
}
/**
* ๆ็ปๅฎๆทปๅ ๅฐ้ๅไธญ
* @param d
*/
protected void suscribe(Disposable d){
/**
* ็ฐๅจๅจbaseObserverไธญไฝฟ็จ่ชๅจ่งฃ็ป็ๆนๆณ๏ผไธไฝฟ็จๆๅจ่งฃ็ป
*/
// if(mCompositeDisposable==null){
// mCompositeDisposable = new CompositeDisposable();
// }
// mCompositeDisposable.add(d);
}
// private void unsubscribe() {
// if(subscription != null && !subscription.isUnsubscribed()){
// subscription.unsubscribe();
// }
// }
/**
* rxjava2็ๅๆถ่ฎข้
*/
private void unsubscribe(){
/**
* ็ฐๅจๅจbaseObserverไธญไฝฟ็จ่ชๅจ่งฃ็ป็ๆนๆณ๏ผไธไฝฟ็จๆๅจ่งฃ็ป
*/
// if(mCompositeDisposable != null&&!mCompositeDisposable.isDisposed()){
// mCompositeDisposable.dispose();
// }
//mCompositeDisposable.clear();
}
public T getMvpView() {
return mMvpView;
}
public boolean isViewAttached() {
return mMvpView != null;
}
public void checkViewAttached() {
if (!isViewAttached()) throw new MvpViewNotAttachedException();
}
public static class MvpViewNotAttachedException extends RuntimeException {
public MvpViewNotAttachedException() {
super("Please call Presenter.attachView(MvpView) before" +
" requesting data to the Presenter");
}
}
}
<file_sep>/src/main/java/com/ezdata/commonlib/net/NetWork_OkHttp3.java
package com.ezdata.commonlib.net;
import com.ezdata.commonlib.Constants.Constant;
import com.ezdata.commonlib.core.App;
import com.ezdata.commonlib.net.download.DownloadProgressListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit.RxJavaCallAdapterFactory;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class NetWork_OkHttp3 implements DownloadProgressListener {
private static NetWork_OkHttp3 instance;
/**
* ๆฒกๆๆ่ฟๅ็ฑปๅๆ้ ่ฟๅป็ Retrofit๏ผ
* ๆๅปบไบ่ถ
ๆถๆถ้ด๏ผbaseurl๏ผๆฆๆชๅจ๏ผ็ฌฌไธๆน๏ผ๏ผๅคดๆไปถ็ญ็ Retrofit
*/
private Retrofit partRetrofit;
private DownloadProgressListener listener;
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
public static NetWork_OkHttp3 getInstance() {
if (instance == null)
instance = new NetWork_OkHttp3();
return instance;
}
public static final int TIMEOUT = 30;
public NetWork_OkHttp3() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
//ไธไธๅฎ้่ฆๆทปๅ
//ๆทปๅ ็ปไธ็ๆฅๅฃๅๆฐ๏ผไพๅฆ๏ผ
//100ไธชๆฅๅฃ้ฝ้่ฆไผ useridๅtoken็ๆถๅ๏ผๅฏไปฅๅจ่ฟ้้
็ฝฎ
HttpUrl originalHttpUrl = chain.request().url();
HttpUrl url = originalHttpUrl.newBuilder()
// .addQueryParameter("platformKey", "app_video_request") ๆฏไธชๆฅๅฃ็ๅ
ฌๅ
ฑๅๆฐ
.build();
Request newRequest = chain.request().newBuilder()
//.addHeader("platformKey", "test_xcq") ๆฏไธชๆฅๅฃ็ๅ
ฌๅ
ฑheader
.url(url)
.build();
Response response = chain.proceed(newRequest);
return response;
}
};
OkHttpClient okHttp3Client = new OkHttpClient().newBuilder()
.cookieJar(new CookieJar() {
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url.host(), cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
})
.connectTimeout(TIMEOUT, TimeUnit.SECONDS)//่ฎพ็ฝฎ่ฟๆฅ่ถ
ๆถๆถ้ด
.readTimeout(TIMEOUT, TimeUnit.SECONDS)//่ฎพ็ฝฎ่ฏปๅ่ถ
ๆถๆถ้ด
.writeTimeout(TIMEOUT, TimeUnit.SECONDS)//่ฎพ็ฝฎๅๅ
ฅ่ถ
ๆถๆถ้ด
.addInterceptor(loggingInterceptor)//ๆทปๅ ๆฅๅฟๆฆๆชๅจ
.addInterceptor(interceptor)
.build();
Retrofit retrofit = new Retrofit.Builder().baseUrl(Constant.BASE_URL)
.addCallAdapterFactory(
RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(
App.getInstance().gson))
.client(okHttp3Client)
.build();
partRetrofit = retrofit;
}
public Retrofit getPartRetrofit() {
return partRetrofit;
}
@Override
public void update(long bytesRead, long contentLength, boolean done) {
}
}
<file_sep>/src/main/java/com/ezdata/commonlib/widget/MenuButton.java
package com.ezdata.commonlib.widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ezdata.commonlib.R;
import com.ezdata.commonlib.utils.PhoneUtils;
public class MenuButton extends LinearLayout implements Checkable {
private ImageView imgIcon;
private TextView tvName;
private ColorStateList textColor;
public MenuButton(Context context){
super(context);
}
public MenuButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.tabWidget);
imgIcon = new ImageView(context);
imgIcon.setClickable(false);
imgIcon.setImageResource(a.getResourceId(R.styleable.tabWidget_icMenu,
R.drawable.bg_circle));
tvName = new TextView(context);
tvName.setClickable(false);
tvName.setText(a.getString(R.styleable.tabWidget_text));
tvName.setGravity(Gravity.CENTER);
final int textSize = a.getInteger(R.styleable.tabWidget_textSize, 14);
// tvName.setTextSize(sp2px(context,a.getDimension(R.styleable.tabWidget_textSize, 10)));
tvName.setTextSize(TypedValue.COMPLEX_UNIT_SP,textSize);
textColor = a.getColorStateList(R.styleable.tabWidget_textColor);
tvName.setTextColor(textColor);
addView(imgIcon,
new LayoutParams(a.getLayoutDimension(
R.styleable.tabWidget_icWidth, 30), a
.getLayoutDimension(R.styleable.tabWidget_icHeight,
30)));
addView(tvName, new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
a.recycle();
try {
// setBackgroundResource(R.drawable.menu_default);
// setBckgroud(R.drawable.menu_default);
// setBackgroundColor(getResources().getColor(R.color.gray));
} catch (Exception e) {
}
}
public void init(Context context, int drawable, String name){
setOrientation(VERTICAL);
setGravity(Gravity.CENTER);
imgIcon = new ImageView(context);
imgIcon.setClickable(false);
imgIcon.setImageResource(drawable);
tvName = new TextView(context);
tvName.setClickable(false);
tvName.setText(name);
tvName.setGravity(Gravity.CENTER);
textColor = getResources().getColorStateList(R.color.main_text);
tvName.setTextColor(textColor);
addView(imgIcon,
new LayoutParams(PhoneUtils.dip2px(context,30), PhoneUtils.dip2px(context,30)));//30ๅ็ด ???
addView(tvName, new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
tvName.setTextColor(textColor.getColorForState(
new int[] { android.R.attr.state_pressed,android.R.attr.state_checkable }, 0));
imgIcon.setImageState(new int[] { android.R.attr.state_pressed,android.R.attr.checked,
android.R.attr.state_checkable }, true);
break;
case MotionEvent.ACTION_UP:
if(!checked){
tvName.setTextColor(textColor.getColorForState(
new int[] { }, 0));
imgIcon.setImageState(new int[] { }, true);
}
break;
default:
break;
}
return super.onTouchEvent(event);
}
private boolean checked = false;
@Override
public void setChecked(boolean checked) {
this.checked = checked;
if (checked) {
tvName.setTextColor(textColor.getColorForState(
new int[] { android.R.attr.state_pressed,
android.R.attr.state_checkable }, 0));
imgIcon.setImageState(new int[] {
android.R.attr.state_pressed,
android.R.attr.state_checked,
android.R.attr.state_checkable }, true);
// try {
//// // setBackgroundResource(R.drawable.menu_pressed);
//// setBckgroud(R.drawable.menu_pressed);
// tvName.setTextColor(getResources().getColor(R.color.blue));
// } catch (Exception e) {
// }
} else {
tvName.setTextColor(textColor.getColorForState(new int[] {}, 0));
imgIcon.setImageState(new int[] {}, false);
// try {
//// setBckgroud(R.drawable.menu_default);
// tvName.setTextColor(getResources().getColor(R.color.blue2_block));
// } catch (Exception e) {
// }
}
}
public void setBckgroud(int imgResource){
setBackgroundResource(imgResource);
}
@Override
public boolean isChecked() {
return checked;
}
@Override
public void toggle() {
setChecked(!checked);
}
@Override
public boolean performClick() {
toggle();
return super.performClick();
}
}
<file_sep>/src/main/java/com/ezdata/commonlib/utils/PhoneUtils.java
package com.ezdata.commonlib.utils;
import android.content.Context;
import java.lang.reflect.Field;
/**
* Created by Administrator on 2017/3/21.
*/
public class PhoneUtils {
private static PhoneUtils mPhoneUtils;
private Context mContext;
private PhoneUtils(Context c) {
mContext = c.getApplicationContext ();
}
public static PhoneUtils getInstance (Context context) {
if (mPhoneUtils == null)
synchronized (PhoneUtils.class) {
if (mPhoneUtils == null) {
mPhoneUtils = new PhoneUtils (context);
}
}
return mPhoneUtils;
}
// public static String getMacAddress(Context context) {
// WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
// String mac = wm.getConnectionInfo().getMacAddress();
// return mac == null ? "" : mac;
// }
public float getDensity () {
return mContext.getResources ().getDisplayMetrics ().density;
}
/**
* @return ่ฟๅๅฑๅน็ๅฎฝๅบฆ
*/
public int getScreenW () {
return mContext.getResources ().getDisplayMetrics ().widthPixels;
}
public int getScreenH () {
return mContext.getResources ().getDisplayMetrics ().heightPixels;
}
public int dp2px (int value) {
return (int) (0.5f + getDensity () * value);
}
/**
* ๆ นๆฎๆๆบ็ๅ่พจ็ไป dp ็ๅไฝ ่ฝฌๆไธบ px(ๅ็ด )
*/
public static int dip2px (Context context, float dpValue) {
return Math.round (context.getResources ().getDisplayMetrics ().density * dpValue);
}
/**
* convert px to its equivalent dp
*
* ๅฐpx่ฝฌๆขไธบไธไน็ธ็ญ็dp
*/
public static int px2dp(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* convert dp to its equivalent px
*
* ๅฐdp่ฝฌๆขไธบไธไน็ธ็ญ็px
*/
public static int dp2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
/**
* convert px to its equivalent sp
*
* ๅฐpx่ฝฌๆขไธบsp
*/
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
/**
* convert sp to its equivalent px
*
* ๅฐsp่ฝฌๆขไธบpx
*/
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
public int getStatusBarHeight () {
Class<?> c;
Object obj;
Field field;
int x, statusBar = 0;
try {
c = Class.forName ("com.android.internal.R$dimen");
obj = c.newInstance ();
field = c.getField ("status_bar_height");
x = Integer.parseInt (field.get (obj).toString ());
statusBar = mContext.getResources ().getDimensionPixelSize (x);
} catch (Exception e1) {
e1.printStackTrace ();
}
return statusBar;
}
}
<file_sep>/src/main/java/com/ezdata/commonlib/core/BaseToolBarActivity.java
package com.ezdata.commonlib.core;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ezdata.commonlib.R;
/**
* Created by MSI-PC on 2018/5/25.
*/
public abstract class BaseToolBarActivity extends BaseNoHandlerActivity {
public Toolbar mToolbar;
public TextView titleTv;
public RelativeLayout backRl;
@Override
protected void initToolbar(Bundle savedInstanceState) {
this.initToolbarHelper();
}
/**
* init the toolbar
*/
protected void initToolbarHelper() {
if (this.mToolbar == null) {
mToolbar = findView(R.id.toolBar);
titleTv = findViewById(R.id.titleTv);
backRl = findViewById(R.id.backRl);
}
}
public void setTitle(String title){
if(mToolbar!=null)
mToolbar.setTitle("");
if(titleTv!=null)
titleTv.setText(title);
}
public void setTitle(int id){
setTitle(getString(id));
}
protected void showBack() {
backRl.setVisibility(View.VISIBLE);
backRl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onToolbarBack();
}
});
}
protected abstract void onToolbarBack();
}
<file_sep>/src/main/java/com/ezdata/commonlib/Constants/Constant.java
package com.ezdata.commonlib.Constants;
/**
* Created by MSI-PC on 2018/4/4.
*/
public class Constant {
// www.efacedata.com
// API๏ผ9092
// ๅๆพ๏ผ9025
// ็ดๆญ๏ผ9026
//ๅ
ฌๅธๆต่ฏๅฐๅ
//public static final String BASE_URL = "http://192.168.3.101:9092";//ไธปๅฐๅ
//public static final String HLS_URL = "http://192.168.3.101:9025";//ไธปๅฐๅ
// public static final String BASE_URL = "http://192.168.3.80:9092";
// public static final String HLS_URL = "http://192.168.3.80:9025";//TODO ๅๅคด่ทๅ
public static final String BASE_URL = "http://192.168.3.252:9092";
public static final String HLS_URL = "http://192.168.3.252:9025";//TODO ๅๅคด่ทๅ
//ๅ
ฌๅธๅค็ฝๅฐๅ
// public static final String BASE_URL = "http://172.16.31.10:9092";
// public static final String HLS_URL = "http://172.16.31.10:9025";//TODO ๅๅคด่ทๅ
//็ฝ็ป่ฟๅๆญฃ็กฎ
public static final int CODE_OK=200;//
//ๅ่กจ็ญ้ๆกไปถ๏ผstrๅญ็ฌฆไธฒ๏ผๅญๅ
ฅshreprefrence็จ
public static final String SP_FACE = "SP_FACE";//ๆฐๆฎๅบๅ็งฐ
public static final String SELECTION_DATA = "SELECTION_DATA";//็ญ้ไฟกๆฏ
public static final String USER_DATA = "USER_DATA";//็จๆทไฟกๆฏ
public static final String BAIDU_FACE_DATA = "BAIDU_FACE_FATA";//็พๅบฆไบบ่ธไผ็จ็ๆฐๆฎๅบๅ็งฐ
/**
* ๅฏ็ ้ช่ฏ้กต้ข็่ทณ่ฝฌstrๅญ็ฌฆไธฒ
*/
public static final String MACHINE_ID = "machine_id";//ๅชๅฐๆด่กฃๆบ
public static final String INTENT_SOURCE = "intent_source";//ไปๅชไธช้กต้ข่ฟ่ก้ช่ฏ้กต้ข
public static final String LOGIN_PAGE = "login_page";//่กจ็คบไปๆณจๅ้กต้ข่ฟ่ก้ช่ฏ
public static final String PERSONAL_PAGE = "personal_page";//่กจ็คบไปไธชไบบไธญๅฟ่ฟ่ก้ช่ฏ
/**
* ๅข้ๆดๆฐappไฝฟ็จ็ๅธธ้
*/
public static final String APP_PATCH_NAME = "/currentVersion.patch";//ไธ่ฝฝ็่กฅไธ็ๅ็งฐ
public static final String LAST_APK_NAME = "/prison.apk";//ๅๆ็apk็ๅ็งฐ
/**
* ็พๅบฆๅๅๅฑ่ทณ่ฝฌๅธธ้
*/
public static final String BAIDU_CAMERA_DIRECTION = "baidu_camera_direction";//ๅ็ฝฎ่ฟๆฏๅ็ฝฎๆๅๅคด
}
| 936a9bc2c3926cf04961233af77e37d3daaee843 | [
"Java"
] | 6 | Java | XiaoChenqi/commonlib | 2ea32095b86f52d1bc02e2babf5a60f7629d0e1b | d8c32b58a3e2a9d865e8d3bdf9f200d82ce6eb19 |
refs/heads/master | <repo_name>joejcox/monsters<file_sep>/src/components/card/card.component.jsx
import React from "react";
import "./card.styles.css";
export const Card = ({ id, name, email }) => {
return (
<div className="cards__container--card">
<img alt="monster face" src={`https://robohash.org/${id}?set=set3`} />
<div className="card--info">
<h2>{name}</h2>
<h5>{email}</h5>
</div>
</div>
);
};
<file_sep>/src/App.js
import React from "react";
import "./App.css";
import { CardList } from "./components/card-list/card-list.component";
import { SearchBar } from "./components/search/search-bar.component";
export default class App extends React.Component {
state = {
monsters: [],
searchField: "",
};
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((users) =>
this.setState({
monsters: users,
})
);
}
handleChange = (e) => {
this.setState({
searchField: e.target.value,
});
};
render() {
const { monsters, searchField } = this.state;
const filteredMonsters = monsters.filter((monster) =>
monster.name.toLowerCase().includes(searchField.toLowerCase())
);
return (
<div className="App">
<h1>Monsters App!</h1>
<SearchBar change={(e) => this.handleChange(e)} />
<CardList monsters={filteredMonsters} />
</div>
);
}
}
<file_sep>/src/components/search/search-bar.component.jsx
import React from "react";
import "./search-barr.styles.css";
export const SearchBar = ({ change }) => {
return (
<input
className="monster-search"
type="search"
placeholder="Search monsters..."
onChange={change}
/>
);
};
<file_sep>/src/components/card-list/card-list.component.jsx
import React from "react";
import { Card } from "../card/card.component";
import "./card-list.styles.css";
export const CardList = ({ monsters }) => {
return (
<div className="cards__container">
{monsters.map(({ id, name, email }) => (
<Card key={id} id={id} name={name} email={email} />
))}
</div>
);
};
| 2316d5678f48642b640aa066d64d29ae1416529c | [
"JavaScript"
] | 4 | JavaScript | joejcox/monsters | ca965695b16989edac40054f491f11500c1876f4 | c324d5ecec622f442c3d3c46d5456959cfebb452 |
refs/heads/master | <repo_name>sarahfwood/GA-Homework-Ajax-Countries<file_sep>/starter-code/scripts/app.js
function init() {
const countryList = document.querySelector('#countries')
let countries = []
function getCountries() {
const countryFetch = fetch('https://restcountries.eu/rest/v2/all')
countryFetch
.then((resp) => resp.json())
.then((resp) => {
countries = resp
displayCountries()
})
.catch(err => console.error(err))
}
function displayCountry(name, nativeName, flag) {
return `<li>
<h3>${name}</h3>
<h6>${nativeName}</h6>
<svg width="350" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image xlink:href="${flag}" width="350" height="200"/>
</svg>
</li>`
}
function displayCountries() {
countryList.innerHTML = ''
const htmlArray = countries.map(country => {
return displayCountry(country.name, country.nativeName, country.flag)
})
countryList.innerHTML = htmlArray.join('')
}
function displayCountriesByRegion(region) {
countryList.innerHTML = ''
const htmlArray = countries
.filter(country => country.region === region)
.map(country => {
return displayCountry(country.name, country.nativeName, country.flag)
})
countryList.innerHTML = htmlArray.join('')
}
function displayCountriesByName(name) {
countryList.innerHTML = ''
const htmlArray = countries
.filter(country => country.name.toLowerCase().includes(name.toLowerCase()))
.map(country => {
return displayCountry(country.name, country.nativeName, country.flag)
})
countryList.innerHTML = htmlArray.join('')
}
const select = document.querySelector('select')
select.addEventListener('change', () => {
const region = select.value
if (region === 'All') {
displayCountries()
} else {
displayCountriesByRegion(region)
}
})
const input = document.querySelector('input')
input.addEventListener('input', () => {
const text = input.value
displayCountriesByName(text)
})
getCountries()
}
window.addEventListener('DOMContentLoaded', init) | df8e74f21d1457ab434bab857d21855d75067c88 | [
"JavaScript"
] | 1 | JavaScript | sarahfwood/GA-Homework-Ajax-Countries | 72087fdd72cd63ce71510bc9f967182bb8c72fc6 | 9765c1ea87c27c2bf3470416ba742f2352013473 |
refs/heads/master | <repo_name>nikunjsharma1/MockApi<file_sep>/app/src/main/java/com/nikunj/mockapp/ui/main/MainAdapter.kt
package com.nikunj.mockapp.ui.main
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupMenu
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.nikunj.mockapp.R
import com.nikunj.mockapp.model.ClassesName
import com.nikunj.mockapp.util.OnClickItemPackage
class MainAdapter(val context: Context, private val articlesM: MutableList<ClassesName>):
RecyclerView.Adapter<MainAdapter.ArticleViewHolder>() {
var clickItemPackage: OnClickItemPackage? =null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.layout,parent,false)
return ArticleViewHolder(view)
}
override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
val articles = articlesM?.get(position)
holder.name.text = articles.name
holder.dose1.text = articles.dose
holder.strenth.text = articles.strength
holder.save.setOnClickListener {
val popup = PopupMenu(context, holder.save)
popup.inflate(R.menu.menu_rec)
popup.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.menu1 -> {
clickItemPackage?.onClick(articles,position)
}
}
false
}
popup.show()
}
}
override fun getItemCount(): Int {
return articlesM.size
}
class ArticleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var save: ImageView =itemView.findViewById<ImageView>(R.id.deleteImg)
var name = itemView.findViewById<TextView>(R.id.namea)
var dose1 = itemView.findViewById<TextView>(R.id.dose)
var strenth = itemView.findViewById<TextView>(R.id.strength)
}
}<file_sep>/app/src/main/java/com/nikunj/mockapp/service/NetworkService.kt
package com.nikunj.mockapp.service
import com.google.gson.GsonBuilder
import com.nikunj.mockapp.model.*
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
interface NetworkService {
@GET("471a59e3-25a5-49ab-b0c7-c7827b3cddcf")
suspend fun getResults():Response<List<ClassesName>>
@GET("471a59e3-25a5-49ab-b0c7-c7827b3cddcf")
fun callgetResults() : Call<List<ClassesName>>
companion object{
operator fun invoke() : NetworkService {
return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://run.mocky.io/v3/")
.build()
.create(NetworkService::class.java)
}
}
}
<file_sep>/app/src/main/java/com/nikunj/mockapp/model/Asthma.kt
package com.nikunj.mockapp.model
class Asthma(
)<file_sep>/app/src/main/java/com/nikunj/mockapp/service/Retrofit.kt
package com.nikunj.mockapp.service
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object Retrofit {
val instance: NetworkService by lazy {
val retrofit = Retrofit.Builder()
.baseUrl("https://run.mocky.io/v3/")
.addConverterFactory(GsonConverterFactory.create())
.build()
retrofit.create(NetworkService::class.java)
}
}
<file_sep>/app/src/main/java/com/nikunj/mockapp/model/ClassName.kt
package com.nikunj.mockapp.model
import com.google.gson.annotations.SerializedName
data class ClassName(
@SerializedName("associatedDrug")
val DrugFirst: List<AssociatedDrug>,
@SerializedName("associatedDrug#2")
val DrugSecond: List<AssociatedDrug2>
)
<file_sep>/app/src/main/java/com/nikunj/mockapp/ui/LoginActivity.kt
package com.nikunj.mockapp.ui
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.nikunj.mockapp.R
import com.nikunj.mockapp.ui.main.HomeFragment
import com.nikunj.mockapp.ui.main.MainActivity
import kotlinx.android.synthetic.main.activity_login.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.*
class LoginActivity : AppCompatActivity() {
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
val currentDateTime = LocalDateTime.now()
val data=currentDateTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)).toString()
btn_login.setOnClickListener {
if (et_username.text.isNullOrEmpty() || et_password.text.isNullOrEmpty()){
Toast.makeText(this, "All Fields are Required",Toast.LENGTH_SHORT).show()
return@setOnClickListener
}else{
val intent= Intent(this@LoginActivity,MainActivity::class.java)
intent.putExtra("name",et_username.text.toString())
intent.putExtra("time",data)
startActivity(intent)
Toast.makeText(this@LoginActivity,"Welcome"+" "+et_username.text.toString() +" "+data, Toast.LENGTH_SHORT).show()
}
}
}
}<file_sep>/app/src/main/java/com/nikunj/mockapp/model/AssociatedDrug.kt
package com.nikunj.mockapp.model
data class AssociatedDrug(
val dose: String,
val name: String,
val strength: String
)<file_sep>/settings.gradle
rootProject.name = "Mock app"
include ':app'
<file_sep>/app/src/main/java/com/nikunj/mockapp/model/AssociatedDrugX.kt
package com.nikunj.mockapp.model
data class AssociatedDrugX(
val dose: String,
val name: String,
val strength: String
)<file_sep>/app/src/main/java/com/nikunj/mockapp/model/MedicationsClasse.kt
package com.nikunj.mockapp.model
data class MedicationsClasse(
val className: List<ClassName>,
val className2: List<ClassName2>
)<file_sep>/app/src/main/java/com/nikunj/mockapp/model/Diabete.kt
package com.nikunj.mockapp.model
data class Diabete(
val labs: List<Lab>,
val medications: List<Medication>
)<file_sep>/app/src/androidTest/java/com/nikunj/mockapp/local/ClassDatabaseTest.kt
package com.nikunj.mockapp.local
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import junit.framework.TestCase
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ClassDatabaseTest : TestCase(){
private lateinit var db :ClassDatabase
private lateinit var dao: ClassDao
@Before
public override fun setUp() {
val context =ApplicationProvider.getApplicationContext<Context>()
db = Room.inMemoryDatabaseBuilder(context, ClassDatabase::class.java).build()
dao = db.getClassDao()
}
@After
fun closeDb(){
db.close()
}
@Test
fun writeAndRead()= runBlocking{
val classesEntity=ClassesEntity("22mg","dhdhhd","high")
dao.addClass(classesEntity)
val entitys=dao.getAllClass()
assertThat(entitys.contains(classesEntity)).isTrue()
}
@Test
fun writeAndReadEmpty()= runBlocking{
val classesEntity=ClassesEntity("","","")
dao.addClass(classesEntity)
val entitys=dao.getAllClass()
assertThat(entitys.contains(classesEntity)).isTrue()
}
}<file_sep>/app/src/androidTest/java/com/nikunj/mockapp/ui/main/MainViewModelTest.kt
package com.nikunj.mockapp.ui.main
import android.content.Context
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.getOrAwait
import com.google.common.truth.Truth.assertThat
import com.nikunj.mockapp.local.ClassDao
import com.nikunj.mockapp.local.ClassDatabase
import com.nikunj.mockapp.local.ClassesEntity
import junit.framework.TestCase
import kotlinx.coroutines.runBlocking
import org.checkerframework.checker.fenum.qual.AwtAlphaCompositingRule
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.Rule
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MainViewModelTest : TestCase() {
private lateinit var db :ClassDatabase
private lateinit var dao: ClassDao
private lateinit var viewModel: MainViewModel
val context =ApplicationProvider.getApplicationContext<Context>()
@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
public override fun setUp() {
super.setUp()
viewModel= MainViewModel()
db = Room.inMemoryDatabaseBuilder(context, ClassDatabase::class.java).build()
dao = db.getClassDao()
}
@Test
fun testViewModel(){
viewModel.getAllClasses(context)
val result= viewModel.savedClassList.getOrAwait().find {
it.dose == "" && it.name=="asprin" && it.strength == "500 mg"
}
assertThat(result!=null).isTrue()
}
}<file_sep>/app/src/main/java/com/nikunj/mockapp/model/Mock.kt
package com.nikunj.mockapp.model
data class Mock(
val problems: List<Problem>
)<file_sep>/app/src/main/java/com/nikunj/mockapp/util/OnClickItemDelete.kt
package com.nikunj.mockapp.util
import com.nikunj.mockapp.local.ClassesEntity
interface OnClickItemDelete {
fun onClick (classesEntity: ClassesEntity,position: Int)
}<file_sep>/app/src/main/java/com/nikunj/mockapp/model/Medication.kt
package com.nikunj.mockapp.model
data class Medication(
val medicationsClasses: List<MedicationsClasse>
)<file_sep>/app/src/main/java/com/nikunj/mockapp/test/Validator.kt
package com.nikunj.mockapp.test
object Validator {
fun validate(username : String , passwordLength :Int): Boolean {
return !(passwordLength<6||username.isEmpty())
}
}<file_sep>/app/src/main/java/com/nikunj/mockapp/model/Problem.kt
package com.nikunj.mockapp.model
data class Problem(
val Asthma: List<Asthma>,
val Diabetes: List<Diabete>
)<file_sep>/app/src/main/java/com/nikunj/mockapp/model/AssociatedDrug2X.kt
package com.nikunj.mockapp.model
data class AssociatedDrug2X(
val dose: String,
val name: String,
val strength: String
)<file_sep>/app/src/main/java/com/nikunj/mockapp/ui/main/MainViewModel.kt
package com.nikunj.mockapp.ui.main
import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.nikunj.mockapp.local.ClassDatabase
import com.nikunj.mockapp.local.ClassesEntity
import com.nikunj.mockapp.model.ClassesName
import com.nikunj.mockapp.model.MedicationsClasse
import com.nikunj.mockapp.service.NetworkService
import com.nikunj.mockapp.util.ResponseWrapper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
class MainViewModel : ViewModel() {
val classList: MutableLiveData<ResponseWrapper<List<ClassesName>>> = MutableLiveData()
val savedClassList: MutableLiveData<List<ClassesEntity>> = MutableLiveData()
init {
getAllClass()
}
fun getAllClasses(context: Context) {
CoroutineScope(IO).launch {
savedClassList.postValue(ClassDatabase(context).getClassDao().getAllClass())
}
}
private fun getAllClass()
= viewModelScope.launch{
classList.postValue(ResponseWrapper.Loading())
try {
val response = NetworkService().getResults()
when{
response.isSuccessful->{
response.body()?.let {
Log.d("mainview",it.toString())
classList.postValue(ResponseWrapper.Success(it))
}
}
else -> {
classList.postValue(ResponseWrapper.Error(response.message()))
}
}
} catch (e: Exception){
classList.postValue(ResponseWrapper.Error("Something went Wrong :"+e.message))
}
}
}
<file_sep>/app/src/main/java/com/nikunj/mockapp/local/ClassDao.kt
package com.nikunj.mockapp.local
import androidx.room.*
@Dao
interface ClassDao {
@Insert
suspend fun addClass(classesEntity: ClassesEntity)
@Query("SELECT * FROM ClassesEntity ORDER BY id DESC")
fun getAllClass(): List<ClassesEntity>
@Delete
fun deleteClass(classesEntity: ClassesEntity)
}<file_sep>/app/src/test/java/com/nikunj/mockapp/test/ValidatorTest.kt
package com.nikunj.mockapp.test
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class ValidatorTest{
@Test
fun whenInputIsValid(){
val passwordLength = 6
val username = "nikunj"
val result = Validator.validate(username,passwordLength)
assertThat(result).isEqualTo(true)
}
@Test
fun whenInputIsInvalid(){
val passwordLength = 0
val username = ""
val result = Validator.validate(username,passwordLength)
assertThat(result).isEqualTo(false)
}
}<file_sep>/app/src/main/java/com/nikunj/mockapp/util/OnClickItemPackage.kt
package com.nikunj.mockapp.util
import com.nikunj.mockapp.model.ClassesName
interface OnClickItemPackage {
fun onClick (classesName: ClassesName,position: Int)
}<file_sep>/app/src/main/java/com/nikunj/mockapp/ui/saved/SavedFragment.kt
package com.nikunj.mockapp.ui.saved
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.nikunj.mockapp.R
import com.nikunj.mockapp.local.ClassDatabase
import com.nikunj.mockapp.local.ClassesEntity
import com.nikunj.mockapp.model.ClassesName
import com.nikunj.mockapp.model.MedicationsClasse
import com.nikunj.mockapp.service.NetworkService
import com.nikunj.mockapp.ui.BaseFragment
import com.nikunj.mockapp.ui.main.MainAdapter
import com.nikunj.mockapp.ui.main.MainViewModel
import com.nikunj.mockapp.util.OnClickItemDelete
import com.nikunj.mockapp.util.OnClickItemPackage
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.fragment_saved.*
import kotlinx.coroutines.launch
class SavedFragment : BaseFragment() {
lateinit var viewModel: MainViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_saved, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
createViewModel()
viewModel.getAllClasses(requireContext())
observeViewModel()
super.onViewCreated(view, savedInstanceState)
}
private fun observeViewModel() {
viewModel.savedClassList.observe(viewLifecycleOwner, Observer {
val layoutManager = LinearLayoutManager(requireContext())
savedRecycler.layoutManager = layoutManager
savedRecycler.adapter =
SavedAdapter(requireContext(), it as MutableList<ClassesEntity>)
})
}
private fun createViewModel() {
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
}
}<file_sep>/app/src/main/java/com/nikunj/mockapp/model/ClassesName.kt
package com.nikunj.mockapp.model
data class ClassesName(
val dose: String? = null,
val name: String? = null ,
val strength: String? = null
)
<file_sep>/app/src/main/java/com/nikunj/mockapp/model/Lab.kt
package com.nikunj.mockapp.model
data class Lab(
val missing_field: String
)<file_sep>/app/src/main/java/com/nikunj/mockapp/local/ClassesEntity.kt
package com.nikunj.mockapp.local
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.io.Serializable
@Entity
data class ClassesEntity(
val dose: String,
val name: String ,
val strength: String
) : Serializable {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
}<file_sep>/app/src/main/java/com/nikunj/mockapp/ui/main/HomeFragment.kt
package com.nikunj.mockapp.ui.main
import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.nikunj.mockapp.R
import com.nikunj.mockapp.local.ClassDatabase
import com.nikunj.mockapp.local.ClassesEntity
import com.nikunj.mockapp.model.*
import com.nikunj.mockapp.service.NetworkService
import com.nikunj.mockapp.ui.BaseFragment
import com.nikunj.mockapp.util.OnClickItemPackage
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class HomeFragment : BaseFragment() {
lateinit var viewModel: MainViewModel
private var mainAdapter: MainAdapter? = null
lateinit var api: NetworkService
private var res: MutableList<MedicationsClasse>? = null
var mList: MutableList<ClassesName> = ArrayList()
private lateinit var recycler: RecyclerView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// val name= activity?.intent?.extras?.getString("name")
// val date= activity?.intent?.extras?.getString("date")
// Toast.makeText(requireContext(),"Welcome"+" "+name.toString() +" "+date.toString(), Toast.LENGTH_SHORT).show()
createViewModel()
observeViewModel()
progress_bar_home.visibility = View.VISIBLE
super.onViewCreated(view, savedInstanceState)
}
private fun observeViewModel() {
viewModel.classList.observe(viewLifecycleOwner, Observer {
it.data?.let { it1 -> mList.addAll(it1) }
Log.d("mainview", it.data.toString())
if (it.data != null) {
mainAdapter = MainAdapter(requireContext(), it.data as MutableList<ClassesName>)
val layoutManager = LinearLayoutManager(requireContext())
packageRecycler.layoutManager = layoutManager
packageRecycler.adapter = mainAdapter
mainAdapter?.clickItemPackage = object : OnClickItemPackage {
override fun onClick(classesName: ClassesName, position: Int) {
launch {
context?.let {
classesName.name?.let { it1 ->
classesName.strength?.let { it2 ->
classesName.dose?.let { it3 ->
ClassesEntity(
it3,
it1, it2
)
}
}
}?.let { it2 -> ClassDatabase(it).getClassDao().addClass(it2) }
}
}
}
}
}
})
Handler().postDelayed({
progress_bar_home.visibility = View.INVISIBLE
}, 1500)
}
private fun createViewModel() {
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
}
}<file_sep>/app/src/androidTest/java/com/LiveDataExtentionFuction.kt
package com
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
fun<T> MutableLiveData<T>.getOrAwait(): T {
var data : T ? =null
val latch =CountDownLatch(1)
val observer =object :Observer<T>{
override fun onChanged(t: T) {
data = t
this@getOrAwait.removeObserver(this)
latch.countDown()
}
}
this.observeForever(observer)
try{
if(!latch.await(2,TimeUnit.SECONDS)){
throw TimeoutException("Live data never get value")
}
}finally {
this.removeObserver(observer)
}
return data as T
}<file_sep>/app/src/main/java/com/nikunj/mockapp/ui/saved/SavedAdapter.kt
package com.nikunj.mockapp.ui.saved
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupMenu
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.nikunj.mockapp.R
import com.nikunj.mockapp.local.ClassesEntity
import com.nikunj.mockapp.model.ClassesName
import com.nikunj.mockapp.util.OnClickItemDelete
import com.nikunj.mockapp.util.OnClickItemPackage
class SavedAdapter(val context: Context, private val articlesM: MutableList<ClassesEntity>):
RecyclerView.Adapter<SavedAdapter.ArticleViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.layout,parent,false)
return ArticleViewHolder(view)
}
override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
val articles = articlesM?.get(position)
holder.name.text = articles.name
holder.dose1.text = articles.dose
holder.strenth.text = articles.strength
holder.save.visibility=View.INVISIBLE
}
override fun getItemCount(): Int {
return articlesM.size
}
class ArticleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var save: ImageView =itemView.findViewById<ImageView>(R.id.deleteImg)
var name = itemView.findViewById<TextView>(R.id.namea)
var dose1 = itemView.findViewById<TextView>(R.id.dose)
var strenth = itemView.findViewById<TextView>(R.id.strength)
}
} | 1267eadf27ec6a76cab2a2ca2e6a39a54e644f29 | [
"Kotlin",
"Gradle"
] | 30 | Kotlin | nikunjsharma1/MockApi | 5ca14b628ba4b4405eb26f342180d8f6048df08f | 87ab584f9571e9da215a98b43c97fe1e305ed9b5 |
refs/heads/master | <repo_name>pparthasarathy/parthas_UdacityCppND_SystemMonitorProj<file_sep>/src/linux_parser.cpp
#include <dirent.h>
#include <unistd.h>
#include <string>
#include <vector>
#include "linux_parser.h"
using std::stof;
using std::string;
using std::to_string;
using std::vector;
// DONE: An example of how to read data from the filesystem
string LinuxParser::OperatingSystem() {
string line;
string key;
string value;
std::ifstream filestream(kOSPath); //"/etc/os-release"
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ' ', '_');
std::replace(line.begin(), line.end(), '=', ' ');
std::replace(line.begin(), line.end(), '"', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "PRETTY_NAME") {
std::replace(value.begin(), value.end(), '_', ' ');
return value;
}
}
}
}
return value;
}
// DONE: An example of how to read data from the filesystem
string LinuxParser::Kernel() {
string os, version, kernel;
string line;
std::ifstream stream(kProcDirectory + kVersionFilename); //"/proc"+"/version"
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> os >> version >> kernel;
}
return kernel;
}
// BONUS: Update this to use std::filesystem
vector<int> LinuxParser::Pids() {
vector<int> pids;
DIR* directory = opendir(kProcDirectory.c_str());
struct dirent* file;
while ((file = readdir(directory)) != nullptr) {
// Is this a directory?
if (file->d_type == DT_DIR) {
// Is every character of the name a digit?
string filename(file->d_name);
if (std::all_of(filename.begin(), filename.end(), isdigit)) {
int pid = stoi(filename);
pids.push_back(pid);
}
}
}
closedir(directory);
return pids;
}
// Done TODO: Read and return the system memory utilization
float LinuxParser::MemoryUtilization() {
u_int8_t count = 0;
string line;
string key;
long value[2]={0,0};
long MemTotal = 0;
long MemFree = 0;
long MemUsed = 0;
float MemUtilization = 0.0;
std::ifstream stream(kProcDirectory + kMeminfoFilename);//"/proc"+"/meminfo"
if (stream.is_open()) {
while (count < 2) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> key >> value[count];
++count;
}
}
MemTotal = value[0];
MemFree = value[1];
MemUsed = MemTotal - MemFree;
MemUtilization = (float) MemUsed/ (float) MemTotal;
return (float) MemUtilization;
}
// Done TODO: Read and return the system uptime
long LinuxParser::UpTime() {
string line = "";
long up_time = 0;
long idle_time = 0;
std::ifstream stream(kProcDirectory + kUptimeFilename); //"/proc"+"/uptime"
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> up_time >> idle_time;
}
return up_time;
}
// Done TODO: Read and return the number of jiffies for the system
long LinuxParser::Jiffies() {
// /proc/stat gives:
// cpu user nice system idle iowait irq softirq steal guest guest_nice
// cpu 1008620 1462 289235 50122643 22893 0 9784 0 0 0
// Total CPU time since boot = user+nice+system+idle+iowait+irq+softirq+steal
string line = "";
string cpu = "";
long user = 0;
long nice = 0;
long system = 0;
long idle = 0;
long iowait = 0;
long irq = 0;
long softirq = 0;
long steal = 0;
std::ifstream stream(kProcDirectory + kStatFilename); //"/proc"+"/uptime"
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> cpu >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal;
}
return (user+nice+system+idle+iowait+irq+softirq+steal);
}
// Done TODO: Read and return the number of active jiffies for the system
long LinuxParser::ActiveJiffies() {
// /proc/stat gives:
// cpu user nice system idle iowait irq softirq steal guest guest_nice
// cpu 1008620 1462 289235 50122643 22893 0 9784 0 0 0
// Total Active time since boot = user+nice+system+irq+softirq+steal
string line = "";
string cpu = "";
long user = 0;
long nice = 0;
long system = 0;
long idle = 0;
long iowait = 0;
long irq = 0;
long softirq = 0;
long steal = 0;
std::ifstream stream(kProcDirectory + kStatFilename); //"/proc"+"/uptime"
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> cpu >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal;
}
return (user+nice+system+irq+softirq+steal);
}
// Done TODO: Read and return the number of idle jiffies for the system
long LinuxParser::IdleJiffies() {
// /proc/stat gives:
// cpu user nice system idle iowait irq softirq steal guest guest_nice
// cpu 1008620 1462 289235 50122643 22893 0 9784 0 0 0
// Total CPU time since boot = user+nice+system+idle+iowait+irq+softirq+steal
string line = "";
string cpu = "";
long user = 0;
long nice = 0;
long system = 0;
long idle = 0;
long iowait = 0;
std::ifstream stream(kProcDirectory + kStatFilename); //"/proc"+"/uptime"
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> cpu >> user >> nice >> system >> idle >> iowait;
}
return (idle+iowait);
}
// Done TODO: Read and return the total number of processes
int LinuxParser::TotalProcesses() {
string line = "";
string key = "";
int value = 0;
std::ifstream stream(kProcDirectory + kStatFilename); //"/proc"+"/stat""}
if (stream.is_open()) {
while (std::getline(stream, line)) {
std::istringstream linestream(line);
linestream >> key >> value;
if (key == "processes") {
break;
}
}
}
return value;
}
// Done TODO: Read and return the number of running processes
int LinuxParser::RunningProcesses() {
string line = "";
string key = "";
int value = 0;
std::ifstream stream(kProcDirectory + kStatFilename); //"/proc"+"/stat""}
if (stream.is_open()) {
while (std::getline(stream, line)) {
std::istringstream linestream(line);
linestream >> key >> value;
if (key == "procs_running") {
break;
}
}
}
return value;
}
// Done TODO: Read and return the command associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::Command(int pid) {
string line = "";
std::ifstream stream(kProcDirectory + to_string(pid) + kCmdlineFilename); //"/proc/"+"pid"+"/cmdline"
if (stream.is_open()) {
std::getline(stream, line);
}
return line;
}
// Done TODO: Read and return the memory used by a process
// REMOVE: [[maybe_unused]] once you define the function
float LinuxParser::Ram(int pid) {
string line = "";
string key = "";
string value = "";
float result = 0;
const string keyname = "VmSize:";
std::ifstream stream(kProcDirectory + to_string(pid) + kStatusFilename); //"/proc/"+"pid"+"/status"
while (std::getline(stream, line)) {
if (line.compare(0, keyname.size(), keyname) == 0)
{
std::istringstream linestream(line);
linestream >> key >> value;
break;
}
}
if(value.empty())
{
result = (float) 0.0;
}
else
{
result = stof(value) * 0.001; //convert from KB to MB
}
return result;
}
// Done TODO: Read and return the user ID associated with a process
// REMOVE: [[maybe_unused]] once you define the function
int LinuxParser::Uid(int pid) {
string line = "";
string key = "";
int value = 0;
const string keyname = "Uid:";
std::ifstream stream(kProcDirectory + to_string(pid) + kStatusFilename); //"/proc/"+"pid"+"/status"
while (std::getline(stream, line)) {
if (line.compare(0, keyname.size(), keyname) == 0)
{
std::istringstream linestream(line);
linestream >> key >> value;
break;
}
}
return value;
}
// Done TODO: Read and return the user associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::User(int uid) {
string line = "";
string result = "";
std::ifstream stream(kPasswordPath); //"/etc/passwd"
string key = ":x:" + to_string(uid) + ":";
while (std::getline(stream, line)) {
if (line.find(key) != std::string::npos) {
result = line.substr(0, line.find(":"));
break;
}
}
return result;
}
// Done TODO: Read and return the uptime of a process
// REMOVE: [[maybe_unused]] once you define the function
long LinuxParser::UpTime(int pid) {
string line = "";
long starttime = 0; //#22- Time when the process started in clock ticks
long hertz = sysconf(_SC_CLK_TCK);
std::ifstream stream(kProcDirectory + to_string(pid) + kStatFilename); //"/proc/"+"pid"+"/stat"
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
for (int n=1; n<23; n++)
{
long val;
linestream >> val;
if(n==22) starttime = val;
}
}
return (long) (starttime / hertz);
}
// Done TODO: Read and return CPU utilization for specified process
float LinuxParser::CpuUtilization(int pid) {
long sysUptime = 0;
long utime = 0;//#14- CPU time spent in user code in clock ticks
long stime = 0; //#15- CPU time spent in kernel code in clock ticks
long cutime = 0; //#16- Waited-for children's CPU time spent in user code in clock ticks
long cstime = 0; //#17- Waited-for children's CPU time spent in kernel code in clock ticks
long starttime = 0; //#22- Time when the process started in clock ticks
long val = 0;
float total_time = 0.0;
float seconds = 0.0;
float cpuUtilization = 0.0;
string line = "";
long hertz = sysconf(_SC_CLK_TCK);
std::ifstream stream(kProcDirectory + to_string(pid) + kStatFilename); //"/proc/"+"pid"+"/stat"
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
for (int n=1; n<23; n++)
{
val = 0;
linestream >> val;
if(n==14) utime = val;
if(n==15) stime = val;
if(n==16) cutime = val;
if(n==17) cstime = val;
if(n==22) starttime = val;
}
}
total_time = (float) (utime+stime+cutime+cstime);
sysUptime = LinuxParser::UpTime();
seconds = (float) sysUptime - ((float)starttime / (float)hertz);
cpuUtilization = (total_time / (float)hertz) / float(seconds);
return cpuUtilization;
}<file_sep>/src/format.cpp
#include <string>
#include "format.h"
using std::string;
// Done TODO: Complete this helper function
// INPUT: Long int measuring seconds
// OUTPUT: HH:MM:SS
// REMOVE: [[maybe_unused]] once you define the function
string Format::ElapsedTime(long seconds) {
std::string time_string;
long hour = 0;
long min = 0;
long time = 0;
long sec = 0;
hour = seconds/3600;
time = seconds%3600;
min = time/60;
sec = seconds%60;
time_string = std::to_string(hour) + ":" + std::to_string(min) + ":" + std::to_string(sec);
return time_string;
}<file_sep>/src/processor.cpp
#include "processor.h"
#include "linux_parser.h"
#include <unistd.h>
// Done TODO: Returns the current CPU utilization over deltatime milliseconds
float Processor::Utilization() {
float totald = 0;
float idled = 0;
long PrevTotal = Jiffies();
long PrevIdle = IdleJiffies();
usleep(deltatime*1000); //usleep sleeps in micro seconds, so multiply by 1000 for milliseconds
totalJiffies = Jiffies();
idleJiffies = IdleJiffies();
activeJiffies = ActiveJiffies();
totald = (float) (totalJiffies - PrevTotal);
idled = (float) (idleJiffies - PrevIdle);
currentUtilization = (totald - idled)/totald;
return currentUtilization;
}
// Done TODO: Returns the aggregate CPU utilization
float Processor::OverallUtilization() {
totalJiffies = Jiffies();
idleJiffies = IdleJiffies();
activeJiffies = ActiveJiffies();
cpuUtilization = activeJiffies/totalJiffies;
return cpuUtilization;
}
// Done TODO: Read and return the number of jiffies for the system
long Processor::Jiffies() { return LinuxParser::Jiffies(); }
// Done TODO: Read and return the number of active jiffies for the system
long Processor::ActiveJiffies() { return LinuxParser::ActiveJiffies(); }
// Done TODO: Read and return the number of idle jiffies for the system
long Processor::IdleJiffies() { return LinuxParser::IdleJiffies(); }<file_sep>/include/processor.h
#ifndef PROCESSOR_H
#define PROCESSOR_H
#define deltatime 200 // delta time in milliseconds over which to calculate current utilization
class Processor {
public:
float Utilization(); // Done TODO: Returns the current CPU utilization over deltatime milliseconds
float OverallUtilization(); // Done TODO: Returns the aggregate CPU utilization
// Done TODO: Declare any necessary private members
private:
long totalJiffies = 0;
long idleJiffies = 0;
long activeJiffies = 0;
float cpuUtilization = 0.0;
float currentUtilization = 0.0;
long Jiffies();
long ActiveJiffies();
long IdleJiffies();
};
#endif | 4dc9f02cd3287d9b9eb5b0b866b909cde013528e | [
"C++"
] | 4 | C++ | pparthasarathy/parthas_UdacityCppND_SystemMonitorProj | b77a4392df9da94473328a907e3a961a8eb240be | 412fc2e0170f43d6f38941198a5fb57431d9b667 |
refs/heads/master | <repo_name>donatedTunic1290/certification-network<file_sep>/chaincode/contract.js
'use strict';
const {Contract} = require('fabric-contract-api');
class CertnetContract extends Contract {
constructor() {
// Provide a custom name to refer to this smart contract
super('org.certification-network.certnet');
}
/* ****** All custom functions are defined below ***** */
// This is a basic user defined function used at the time of instantiating the smart contract
// to print the success message on console
async instantiate(ctx) {
console.log('Certnet Smart Contract Instantiated');
}
/**
* Create a new student account on the network
* @param ctx - The transaction context object
* @param studentId - ID to be used for creating a new student account
* @param name - Name of the student
* @param email - Email ID of the student
* @returns
*/
async createStudent(ctx, studentId, name, email) {
// Create a new composite key for the new student account
const studentKey = ctx.stub.createCompositeKey('org.certification-network.certnet.student', [studentId]);
// Create a student object to be stored in blockchain
let newStudentObject = {
studentId: studentId,
name: name,
email: email,
school: ctx.clientIdentity.getID(),
createdAt: new Date(),
updatedAt: new Date(),
};
// Convert the JSON object to a buffer and send it to blockchain for storage
let dataBuffer = Buffer.from(JSON.stringify(newStudentObject));
await ctx.stub.putState(studentKey, dataBuffer);
// Return value of new student account created to user
return newStudentObject;
}
/**
* Get a student account's details from the blockchain
* @param ctx - The transaction context
* @param studentId - Student ID for which to fetch details
* @returns
*/
async getStudent(ctx, studentId) {
// Create the composite key required to fetch record from blockchain
const studentKey = ctx.stub.createCompositeKey('org.certification-network.certnet.student', [studentId]);
// Return value of student account from blockchain
let studentBuffer = await ctx.stub
.getState(studentKey)
.catch(err => console.log(err));
return JSON.parse(studentBuffer.toString());
}
/**
* Issue a certificate to the student after completing the course
* @param ctx
* @param studentId
* @param courseId
* @param gradeReceived
* @param originalHash
* @returns {Object}
*/
async issueCertificate(ctx, studentId, courseId, gradeReceived, originalHash) {
let msgSender = ctx.clientIdentity.getID();
let certificateKey = ctx.stub.createCompositeKey('org.certification-network.certnet.certificate',[courseId + '-' + studentId]);
let studentKey = ctx.stub.createCompositeKey('org.certification-network.certnet.student', [studentId]);
// Fetch student with given ID from blockchain
let student = await ctx.stub
.getState(studentKey)
.catch(err => console.log(err));
// Fetch certificate with given ID from blockchain
let certificate = await ctx.stub
.getState(certificateKey)
.catch(err => console.log(err));
// Make sure that student already exists and certificate with given ID does not exist.
if (student.length === 0 || certificate.length !== 0) {
throw new Error('Invalid Student ID: ' + studentId + ' or Course ID: ' + courseId + '. Either student does not exist or certificate already exists.');
} else {
let certificateObject = {
studentId: studentId,
courseId: courseId,
teacher: msgSender,
certId: courseId + '-' + studentId,
originalHash: originalHash,
grade: gradeReceived,
createdAt: new Date(),
updatedAt: new Date(),
};
// Convert the JSON object to a buffer and send it to blockchain for storage
let dataBuffer = Buffer.from(JSON.stringify(certificateObject));
await ctx.stub.putState(certificateKey, dataBuffer);
// Return value of new certificate issued to student
return certificateObject;
}
}
/**
*
* @param ctx
* @param studentId
* @param courseId
* @param currentHash
* @returns {Object}
*/
async verifyCertificate(ctx, studentId, courseId, currentHash) {
let verifier = ctx.clientIdentity.getID();
let certificateKey = ctx.stub.createCompositeKey('org.certification-network.certnet.certificate', [courseId + '-' + studentId]);
// Fetch certificate with given ID from blockchain
let certificateBuffer = await ctx.stub
.getState(certificateKey)
.catch(err => console.log(err));
// Convert the received certificate buffer to a JSON object
const certificate = JSON.parse(certificateBuffer.toString());
// Check if original certificate hash matches the current hash provided for certificate
if (certificate === undefined || certificate.originalHash !== currentHash) {
// Certificate is not valid, issue event notifying the student application
let verificationResult = {
certificate: courseId + '-' + studentId,
student: studentId,
verifier: verifier,
result: 'xxx - INVALID',
verifiedOn: new Date()
};
ctx.stub.setEvent('verifyCertificate', Buffer.from(JSON.stringify(verificationResult)));
return verificationResult;
} else {
// Certificate is valid, issue event notifying the student application
let verificationResult = {
certificate: courseId + '-' + studentId,
student: studentId,
verifier: verifier,
result: '*** - VALID',
verifiedOn: new Date()
};
ctx.stub.setEvent('verifyCertificate', Buffer.from(JSON.stringify(verificationResult)));
return verificationResult;
}
}
}
module.exports = CertnetContract;<file_sep>/README.md
# Distributed Student Certification
A hyperledger fabric network to demonstrate certificate creation, exchange and verification between education providers.
## Fabric Network
- 3 Organizations (IIT, MHRD, UpGrad)
- TLS Disabled
- 2 Peers per org
## Chaincode Functionality
- Create a student account
- Issue a new certificate
- Verify certificate
## Network Setup
1. Pre-setup
1. Generate Crypto Materials
```console
MacBook-Pro:network aakash$ cryptogen generate --config=./crypto-config.yaml
2. Generate Channel Artifacts
```console
MacBook-Pro:network aakash$ configtxgen -profile OrdererGenesis -channelID upgrad-sys-channel -outputBlock ./channel-artifacts/genesis.block
MacBook-Pro:network aakash$ configtxgen -profile CertificationChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID certificationchannel
MacBook-Pro:network aakash$ configtxgen -profile CertificationChannel -outputAnchorPeersUpdate ./channel-artifacts/iitMSPanchors.tx -channelID certificationchannel -asOrg iitMSP
MacBook-Pro:network aakash$ configtxgen -profile CertificationChannel -outputAnchorPeersUpdate ./channel-artifacts/mhrdMSPanchors.tx -channelID certificationchannel -asOrg mhrdMSP
MacBook-Pro:network aakash$ configtxgen -profile CertificationChannel -outputAnchorPeersUpdate ./channel-artifacts/upgradMSPanchors.tx -channelID certificationchannel -asOrg upgradMSP
2. Docker Network Setup
1. Start Docker Network
```console
MacBook-Pro:network aakash$ docker-compose -f ./docker-compose.yml up -d
3. Fabric Network Setup
1. SSH Into CLI Container
```console
MacBook-Pro:network aakash$ docker exec -it cli /bin/bash
2. Create Channel
```console
MacBook-Pro:network aakash$ CORE_PEER_LOCALMSPID="iitMSP"
MacBook-Pro:network aakash$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/iit.certification-network.com/users/Admin@iit.certification-network.com/msp
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer0.iit.certification-network.com:7051
MacBook-Pro:network aakash$ peer channel create -o orderer.certification-network.com:7050 -c certificationchannel -f ./channel-artifacts/channel.tx
3. Join Peer 0 - IIT
```console
MacBook-Pro:network aakash$ peer channel join -b certificationchannel.block
4. Join Peer 1 - IIT
```console
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer1.iit.certification-network.com:8051
MacBook-Pro:network aakash$ peer channel join -b certificationchannel.block
5. Join Peer 0 - MHRD
```console
MacBook-Pro:network aakash$ CORE_PEER_LOCALMSPID="mhrdMSP"
MacBook-Pro:network aakash$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/mhrd.certification-network.com/users/Admin@mhrd.certification-network.com/msp
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer0.mhrd.certification-network.com:9051
MacBook-Pro:network aakash$ peer channel join -b certificationchannel.block
6. Join Peer 1 - MHRD
```console
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer1.mhrd.certification-network.com:10051
MacBook-Pro:network aakash$ peer channel join -b certificationchannel.block
7. Join Peer 0 - UPGRAD
```console
MacBook-Pro:network aakash$ CORE_PEER_LOCALMSPID="upgradMSP"
MacBook-Pro:network aakash$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/upgrad.certification-network.com/users/Admin@upgrad.certification-network.com/msp
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer0.upgrad.certification-network.com:11051
MacBook-Pro:network aakash$ peer channel join -b certificationchannel.block
8. Join Peer 1 - UPGRAD
```console
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer1.upgrad.certification-network.com:12051
MacBook-Pro:network aakash$ peer channel join -b certificationchannel.block
9. Update Anchor Peer for IIT
```console
MacBook-Pro:network aakash$ CORE_PEER_LOCALMSPID="iitMSP"
MacBook-Pro:network aakash$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/iit.certification-network.com/users/Admin@iit.certification-network.com/msp
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer0.iit.certification-network.com:7051
MacBook-Pro:network aakash$ peer channel update -o orderer.certification-network.com:7050 -c certificationchannel -f ./channel-artifacts/iitMSPanchors.tx
10. Update Anchor Peer for MHRD
```console
MacBook-Pro:network aakash$ CORE_PEER_LOCALMSPID="mhrdMSP"
MacBook-Pro:network aakash$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/mhrd.certification-network.com/users/Admin@mhrd.certification-network.com/msp
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer0.mhrd.certification-network.com:9051
MacBook-Pro:network aakash$ peer channel update -o orderer.certification-network.com:7050 -c certificationchannel -f ./channel-artifacts/mhrdMSPanchors.tx
11. Update Anchor Peer for UPGRAD
```console
MacBook-Pro:network aakash$ CORE_PEER_LOCALMSPID="upgradMSP"
MacBook-Pro:network aakash$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/upgrad.certification-network.com/users/Admin@upgrad.certification-network.com/msp
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer0.upgrad.certification-network.com:11051
MacBook-Pro:network aakash$ peer channel update -o orderer.certification-network.com:7050 -c certificationchannel -f ./channel-artifacts/upgradMSPanchors.tx
## Install & Instantiate Chaincode
1. Run Chaincode in Dev Mode
1. SSH Into Chaincode Container
```console
MacBook-Pro:network aakash$ docker exec -it chaincode /bin/bash
2. Run Chaincode Node App In Dev Mode
```console
MacBook-Pro:network aakash$ npm run start-dev
2. Install Chaincode
1. SSH Into CLI Container
```console
MacBook-Pro:network aakash$ docker exec -it cli /bin/bash
2. Install Chaincode on Peer 0 - IIT
```console
MacBook-Pro:network aakash$ CORE_PEER_LOCALMSPID="iitMSP"
MacBook-Pro:network aakash$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/iit.certification-network.com/users/Admin@iit.certification-network.com/msp
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer0.iit.certification-network.com:7051
MacBook-Pro:network aakash$ peer chaincode install -n certnet -v 1.1 -l node -p /opt/gopath/src/github.com/hyperledger/fabric/peer/chaincode/
3. Install Chaincode on Peer 0 - MHRD
```console
MacBook-Pro:network aakash$ CORE_PEER_LOCALMSPID="mhrdMSP"
MacBook-Pro:network aakash$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/mhrd.certification-network.com/users/Admin@mhrd.certification-network.com/msp
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer0.mhrd.certification-network.com:9051
MacBook-Pro:network aakash$ peer chaincode install -n certnet -v 1.1 -l node -p /opt/gopath/src/github.com/hyperledger/fabric/peer/chaincode/
4. Install Chaincode on Peer 0 - UPGRAD
```console
MacBook-Pro:network aakash$ CORE_PEER_LOCALMSPID="upgradMSP"
MacBook-Pro:network aakash$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/upgrad.certification-network.com/users/Admin@upgrad.certification-network.com/msp
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer0.upgrad.certification-network.com:11051
MacBook-Pro:network aakash$ peer chaincode install -n certnet -v 1.1 -l node -p /opt/gopath/src/github.com/hyperledger/fabric/peer/chaincode/
3. Instantiate Chaincode
1. SSH Into CLI Container
```console
MacBook-Pro:network aakash$ docker exec -it cli /bin/bash
2. Instantiate Chaincode on Channel Using Peer 0 - IIT
```console
MacBook-Pro:network aakash$ CORE_PEER_LOCALMSPID="iitMSP"
MacBook-Pro:network aakash$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/iit.certification-network.com/users/Admin@iit.certification-network.com/msp
MacBook-Pro:network aakash$ CORE_PEER_ADDRESS=peer0.iit.certification-network.com:7051
MacBook-Pro:network aakash$ peer chaincode instantiate -o orderer.certification-network.com:7050 -C certificationchannel -n certnet -l node -v 1.1 -c '{"Args":["org.certification-network.certnet:instantiate"]}' -P "OR ('iitMSP.member','mhrdMSP.member','upgradMSP.member')"
4. View Container Logs
1. Start Peer 0 - IIT Container Logs
```console
MacBook-Pro:network aakash$ docker logs -f peer0.iit.certification-network.com
5. Test Chaincode
1. SSH Into Peer 0 - IIT
```console
MacBook-Pro:network aakash$ docker exec -it peer0.iit.certification-network.com /bin/bash
2. Invoke Create Student Function
```console
MacBook-Pro:network aakash$ peer chaincode invoke -o orderer.certification-network.com:7050 -C certificationchannel -n certnet -c '{"Args":["org.certification-network.certnet:createStudent","0001","<NAME>","<EMAIL>"]}'
3. Invoke Get Student Function
```console
MacBook-Pro:network aakash$ peer chaincode invoke -o orderer.certification-network.com:7050 -C certificationchannel -n certnet -c '{"Args":["org.certification-network.certnet:getStudent","0001"]}'
<file_sep>/chaincode/index.js
'use strict';
const certnetcontract = require('./contract.js');
module.exports.contracts = [certnetcontract];
<file_sep>/application/5_verifyCertificate.js
'use strict';
/**
* This is a Node.JS application to Verify A Student's Certificate
* Defaults:
* StudentID: 0001
* CourseID: PGDBC
* Certificate Hash: asdfgh
*/
const helper = require('./contractHelper');
async function main() {
try {
const certnetContract = await helper.getContractInstance();
// Register a listener to listen to custom events triggered by this contract
const eventListener = await certnetContract.addContractListener('verify-certificate-listener', 'verifyCertificate', (err, event) => {
if (!err) {
event.payload = JSON.parse(event.payload.toString());
console.log('\n\n*** NEW EVENT ***');
console.log(event);
console.log('\n\n');
} else {
console.log(err);
}
});
// Create a new student account
console.log('.....Verify Certificate Of Student');
const verificationBuffer = await certnetContract.submitTransaction('verifyCertificate', '0001', 'PGDBC', 'asdfg');
// process response
/*console.log('.....Processing Verify Certificate Transaction Response \n\n');
let verifyResult = JSON.parse(verificationBuffer.toString());
console.log(verifyResult);
console.log('\n\n.....Verify Certificate Transaction Complete!');*/
} catch (error) {
console.log(`\n\n ${error} \n\n`);
} finally {
// Disconnect from the fabric gateway
helper.disconnect();
}
}
main().then(() => {
console.log('.....API Execution Complete!');
}).catch((e) => {
console.log('.....Transaction Exception: ');
console.log(e);
console.log(e.stack);
process.exit(-1);
});<file_sep>/application/4_issueCertificate.js
'use strict';
/**
* This is a Node.JS application to Issue a Certificate to Student
* Defaults:
* StudentID: 0001
* CourseID: PGDBC
* Grade: A
* Certificate Hash: asdfgh
*/
const helper = require('./contractHelper');
async function main() {
try {
const certnetContract = await helper.getContractInstance();
// Create a new student account
console.log('.....Issue Certificate To Student');
const certificateBuffer = await certnetContract.submitTransaction('issueCertificate', '0001', 'PGDBC', 'A', 'asdfgh');
// process response
console.log('.....Processing Issue Certificate Transaction Response \n\n');
let newCertificate = JSON.parse(certificateBuffer.toString());
console.log(newCertificate);
console.log('\n\n.....Issue Certificate Transaction Complete!');
} catch (error) {
console.log(`\n\n ${error} \n\n`);
} finally {
// Disconnect from the fabric gateway
helper.disconnect();
}
}
main().then(() => {
console.log('.....API Execution Complete!');
}).catch((e) => {
console.log('.....Transaction Exception: ');
console.log(e);
console.log(e.stack);
process.exit(-1);
}); | c535f21da5ce2721c2adfa1893623bac508a09da | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | donatedTunic1290/certification-network | d45babdb19d18893e3b041e4077c86a33683e6f5 | db7c1207937b8a65d1f6f14b0d543de6617313fe |
refs/heads/master | <repo_name>superKaigon/TheCave<file_sep>/src/containers/inscription.jsx
import React, { Component } from 'react'
import { Field, reduxForm } from 'redux-form'
import { selectUser } from '../actions/index'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { browserHistory } from 'react-router'
import { SubmissionError } from 'redux-form'
import Modal from './modal'
class Inscription extends Component {
renderField = ({ input, label, type, meta: { touched, error } }) =>
<div>
<label>
{label}
</label>
<div>
<input {...input} placeholder={label} type={type} />
{touched &&
error &&
<span>
{error}
</span>}
</div>
</div>
render() {
const { error, handleSubmit, pristine, reset, submitting } = this.props
return (
<Modal>
<div className='modal2'>
<form className='default_margin_top' onSubmit={handleSubmit(this.submit.bind(this))}>
<Field
name="firstname"
type="text"
component={this.renderField}
label="Firstname"
/>
<Field
name="lastname"
type="text"
component={this.renderField}
label="Lastname"
/>
<Field
name="email"
type="text"
component={this.renderField}
label="Email"
/>
<Field
name="password"
type="text"
component={this.renderField}
label="Password"
/>
{error &&
<strong>
{error}
</strong>}
<div>
<button type="submit" className='btn btn-secondary' disabled={submitting}>
Log In
</button>
<button type="button" className='btn btn-secondary' disabled={pristine || submitting} onClick={reset}>
Clear Values
</button>
</div>
</form>
</div>
</Modal>
)
}
submit = (values) => {
// simulate server latency
if (!values.firstname) {
throw new SubmissionError({
firstname: 'Ce champ doit รชtre renseigner'
})
} else if (!values.lastname) {
throw new SubmissionError({
lastname: 'Ce champ doit รชtre renseigner'
})
} else if (!values.email) {
throw new SubmissionError({
email: 'Ce champ doit รชtre renseigner'
})
} else if (!values.password) {
throw new SubmissionError({
password: '<PASSWORD>'
})
} else {
const user = { firstname: values.firstname, lastname: values.lastname, email: values.email, password: values.password }
this.props.selectUser(user)
browserHistory.push('/')
}
}
}
const mapStateToProps = (state) => {
return {
users: state.users,
myUser: state.activeUser
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ selectUser: selectUser }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(reduxForm({ form: 'InscriptionForm' })(Inscription))<file_sep>/src/containers/ongletsSalle.jsx
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { selectSalle, selectTable } from '../actions/index'
class OngletsSalle extends Component {
render() {
const {mySalles} = this.props
return (
<nav className='row'>
<div className='col-md-12'>
{
mySalles.map((salle) => {
return (
<button className='col-md-4 btn btn-secondary'
key={salle.id}
onClick={() => this.selectSalle(salle)}
disabled = {salle.full == true}>
Salle {salle.id}
</button>
)
})
}
</div>
</nav>
)
}
selectSalle (salle) {
this.props.selectSalle(salle)
}
}
const mapStateToProps = (state) => {
return {
mySalles: state.salles
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ selectSalle: selectSalle, selectTable:selectTable }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(OngletsSalle)<file_sep>/src/routes.js
import React, { Component } from 'react';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router';
import App from './components/app';
import InfoCompte from './containers/infoCompte'
import Connection from './containers/connection'
import Inscription from './containers/inscription'
import ContactUs from './components/contactUs'
import WeAre from './components/weAre'
import PageCourante from './components/pageCourante'
import Salle from './containers/salle'
class Routes extends Component {
render() {
return (
<Router history={browserHistory}>
<Route path='/' component={App} routes = {Routes}>
<Route path='salle' component={Salle}/>
<Route path='weAre' component={WeAre} />
<Route path='contactUs' component={ContactUs} />
<Route path='connection' component={Connection} />
<Route path='inscription' component={Inscription} />
</Route>
</Router>
);
}
}
export default Routes;
<file_sep>/src/containers/connection.jsx
import React, { Component } from 'react'
import { Field, reduxForm } from 'redux-form'
import { selectUser } from '../actions/index'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { browserHistory } from 'react-router'
import { SubmissionError } from 'redux-form'
import { Link } from 'react-router'
import Modal from './modal'
class Connection extends Component {
renderField = ({ input, label, type, meta: { touched, error } }) =>
<div>
<label>
{label}
</label>
<div>
<input {...input} placeholder={label} type={type} />
{touched &&
error &&
<span>
{error}
</span>}
</div>
</div>
render() {
const { error, handleSubmit, pristine, reset, submitting } = this.props
return (
<Modal>
<div className = 'modal'>
<form className='default_margin_top' onSubmit={handleSubmit(this.submit.bind(this))}>
<Field
name="firstname"
type="text"
component={this.renderField}
label="Firstname"
/>
<Field
name="password"
type="text"
component={this.renderField}
label="Password"
/>
{error &&
<strong>
{error}
</strong>}
<div>
<button type="submit" className='btn btn-secondary' disabled={submitting}>
Log In
</button>
<button type="button" className='btn btn-secondary' disabled={pristine || submitting} onClick={reset}>
Clear Values
</button>
</div>
<div><Link to='inscription'><button type="button" className="btn btn-primary">Inscription</button></Link></div>
</form>
</div>
</Modal>
)
}
submit = (values) => {
// simulate server latency
const user = this.props.users.filter((user) => {
if (user.firstname == values.firstname && user.password == values.password) {
this.props.selectUser(user)
browserHistory.push('/')
}
})
if (!user[0]) {
throw new SubmissionError({
firstname: 'Wrong firstname',
password: '<PASSWORD>',
_error: 'Login Fail'
})
}
}
}
const mapStateToProps = (state) => {
return {
users: state.users
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ selectUser: selectUser }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(reduxForm({ form: 'ConnectionForm' })(Connection))<file_sep>/src/actions/index.js
export const selectSalle = (salle) => {
return {
type: 'SALLE_SELECTED',
payload: salle
}
}
export const selectTable = (table) => {
return {
type: 'TABLE_SELECTED',
payload: table
}
}
export const selectUser = (user) => {
return {
type: 'USER_SELECTED',
payload: user
}
}
<file_sep>/src/reducers/reducer_salle.jsx
const salleDemarage = [
{ id:'1',
image:'https://i.pinimg.com/236x/32/9c/11/329c1136511681e74f10ec2b45d3ccc2--fantasy-rpg-dark-fantasy.jpg',
full: false,
tables: [
{ id: '1', name: 'Table 1', occuped: false },
{ id: '2', name: 'Table 2', occuped: false },
{ id: '3', name: 'Table 3', occuped: false },
{ id: '4', name: 'Table 4', occuped: false }
]},
{ id:'2',
image:'https://i.pinimg.com/originals/95/23/90/952390fd9d9d9ac2b98b8118160805e0.jpg',
full: true,
tables: [
{ id: '1', name: 'Table 1', occuped: false },
{ id: '2', name: 'Table 2', occuped: false },
{ id: '3', name: 'Table 3', occuped: false },
{ id: '4', name: 'Table 4', occuped: false }
]},
{ id:'3',
image:'http://www.dundjinni.com/forums/uploads/supercaptain/table_and_chairs_sc.png',
full: false,
tables: [
{ id: '1', name: 'Table 1', occuped: false },
{ id: '2', name: 'Table 2', occuped: false },
{ id: '3', name: 'Table 3', occuped: false },
{ id: '4', name: 'Table 4', occuped: false }
]}
]
export default function (state = salleDemarage, action) {
switch (action.type) {
case 'TABLE_SELECTED':
return [...state].map((table) => {
if (action.payload == null){
return table
}
else if (table.id == action.payload.id) {
return action.payload
} else {
return table
}
})
}
return state
}<file_sep>/test/modal.jsx
import React, { PropTypes } from 'react';
import {
unstable_renderSubtreeIntoContainer as renderSubtreeIntoContainer,
unmountComponentAtNode
} from 'react-dom';
export default class Modal extends React.Component {
static displayName = 'ReactPortal';
/* static propTypes = {
isRendered: PropTypes.bool,
children: PropTypes.node,
portalContainer: PropTypes.node
}; */
/* static defaultProps = {
isRendered: true
};
state = {
mountNode: null
}; */
componentDidMount() {
this._renderPortal();
}
componentDidUpdate(prevProps) {
if (prevProps.isRendered && !this.props.isRendered ||
(prevProps.portalContainer !== this.props.portalContainer &&
prevProps.isRendered)) {
this._unrenderPortal();
}
if (this.props.isRendered) {
this._renderPortal();
}
}
componentWillUnmount() {
this._unrenderPortal();
}
_getMountNode = () => {
if (!this.state.mountNode) {
const portalContainer = this.props.portalContainer || document.body;
const mountNode = document.createElement('div');
mountNode.className = 'modal'
portalContainer.appendChild(mountNode);
this.setState({
mountNode
});
return mountNode;
}
return this.state.mountNode;
};
_renderPortal = () => {
const mountNode = this._getMountNode();
renderSubtreeIntoContainer(
this,
(
<div>
{this.props.children}
</div>
),
mountNode,
);
};
_unrenderPortal = () => {
if (this.state.mountNode) {
unmountComponentAtNode(this.state.mountNode);
this.state.mountNode.parentElement.removeChild(this.state.mountNode);
this.setState({
mountNode: null
});
}
};
render() {
return null;
}
};<file_sep>/src/containers/infoCompte.jsx
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link, browserHistory } from 'react-router'
import { selectUser, selectSalle, selectTable } from '../actions/index'
import Modal from './modal'
import Connection from './connection'
class InfoCompte extends Component {
render() {
const { user } = this.props
if (!user) {
return (
<div>
<Link to='connection'><button type="button" className="btn btn-secondary">Connexion</button></Link>
<Link to='inscription'><button type="button" className="btn btn-secondary">Inscription</button></Link>
</div>
)
}
return (
<div>
Bonjour {user.firstname}
<button type="button" className="btn btn-secondary" onClick={() => this.resetActive()}>Dรฉconnexion</button>
</div>
)
}
resetActive = () => {
this.props.selectUser(null)
this.props.selectSalle(null)
this.props.selectTable(null)
browserHistory.push('salle')
}
}
const mapStateToProps = (state) => {
return {
user: state.activeUser
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ selectUser: selectUser, selectSalle: selectSalle, selectTable: selectTable }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(InfoCompte)
<file_sep>/src/components/navBar.jsx
import React, { Component } from 'react';
import InfoCompte from '../containers/infoCompte';
import {Link} from 'react-router'
class NavBar extends Component {
render () {
return (
<nav className="navbar row">
<div className='col-md-8'>
<Link to ='salle'><button type="button" className="btn btn-secondary" >THE CAVE</button></Link>
<Link to = 'contactUs'><button type="button" className="btn btn-secondary" >Contact Us</button></Link>
<Link to ='weAre'><button type="button" className="btn btn-secondary" >Qui Sommes-nous ?</button></Link>
</div>
<div className='col-md-4'>
<InfoCompte/>
</div>
</nav>
)
}
}
export default (NavBar)
| 33ef527e9f211dfa66cfcccbd63b4dd82121ac11 | [
"JavaScript"
] | 9 | JavaScript | superKaigon/TheCave | 1bf526c226eeb4deba48a3f8985ff04fe0c85fb8 | caefc272a254c72b71e0b0f88be29e6b78a7298e |
refs/heads/master | <file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Text;
namespace SimponiApp.Models
{
public class TracerAlumni
{
public string ID_PERTANYAAN { get; set; }
public string ID_SURVEY { get; set; }
public string PERTANYAAN { get; set; }
public string TIPE_JAWABAN { get; set; }
public string IS_PUBLISHED { get; set; }
}
public class ListTracerAlumni
{
public string STATUS { get; set; }
public List<TracerAlumni> CONTENT { get; set; }
public string MESSAGE { get; set; }
}
public class JawabanTracerAlumni
{
public string ID_PERTANYAAN { get; set; }
public string PILIHAN { get; set; }
}
public class ListJawabanTracerAlumni
{
public string STATUS { get; set; }
public List<JawabanTracerAlumni> CONTENT { get; set; }
public string MESSAGE { get; set; }
}
public class TambahTracerAlumni
{
public string ID_PERTANYAAN { get; set; }
public string ID_SURVEY { get; set; }
public string ID_ALUMNI { get; set; }
public string JAWABAN { get; set; }
public string USERNAME { get; set; }
public string INSERT_DATE { get; set; }
public string IP_ADDRESS { get; set; }
}
public class SimpanTracerAlumni
{
public string STATUS { get; set; }
public string CONTENT { get; set; }
public string MESSAGE { get; set; }
}
}
<file_sep>๏ปฟ
using Newtonsoft.Json;
using SimponiApp.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SimponiApp.Services
{
public class RestaurantServices
{
private HttpClient _client;
public RestaurantServices()
{
_client = new HttpClient();
_client.MaxResponseContentBufferSize = 256000;
}
public async Task<List<Restaurant>> GetAll()
{
List<Restaurant> listRestaurant = new List<Restaurant>();
var uri = new Uri("http://172.16.58.3/api/Restaurant");
try
{
var response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
listRestaurant = JsonConvert.DeserializeObject<List<Restaurant>>(content);
}
return listRestaurant;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<bool> Update(Restaurant restaurant)
{
var uri = new Uri("http://16172.16.17.32/api/Restaurant");
try
{
var json = JsonConvert.SerializeObject(restaurant);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _client.PutAsync(uri, content);
if (response.IsSuccessStatusCode)
return true;
else
return false;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<bool> Delete(string id)
{
var uri = new Uri($"http://172.16.58.3/api/Restaurant/{id}");
try
{
var response = await _client.DeleteAsync(uri);
if (response.IsSuccessStatusCode)
return true;
else
return false;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimponiApp.Views
{
public class SimponiMasterDetailPageMenuItemMenuItem
{
public SimponiMasterDetailPageMenuItemMenuItem()
{
TargetType = typeof(SimponiMasterDetailPageDetailDetail);
}
public int Id { get; set; }
public string Title { get; set; }
public Type TargetType { get; set; }
}
}<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Text;
//
namespace SimponiApp.Models
{
public class Alumni
{
public string ID_ALUMNI { get; set; }
public string NPM { get; set; }
public string NAMA_MHS { get; set; }
public string USERNAME { get; set; }
}
public class WrapperAlumni
{
public string STATUS { get; set; }
public Alumni CONTENT { get; set; }
public string MESSAGE { get; set; }
}
}
<file_sep>๏ปฟusing Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SimponiApp.Helpers;
using SimponiApp.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SimponiApp.Services
{
public class LowonganService
{
private HttpClient _client;
public List<Lowongan> ListLowongan { get; set; }
public LowonganService()
{
_client = new HttpClient();
_client.MaxResponseContentBufferSize = 256000;
}
public async Task<List<Lowongan>> GetAllData()
{
ListLowongan data = null;
var uri = new Uri($"{Helpers.Pengaturan.BaseUrl}/lowongan");
try
{
var response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var cleaning = JsonConvert.DeserializeObject(content);
JObject json = JObject.Parse(cleaning.ToString());
data = JsonConvert.DeserializeObject<ListLowongan>(json.ToString());
}
return data.CONTENT;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
<file_sep>๏ปฟusing SimponiApp.Models;
using SimponiApp.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace SimponiApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class JawabSPage : ContentPage
{
private TracerAlumni _tracerAlumni;
private TracerStudyService _myService;
public List<JawabanTracerAlumni> JawabTracerAlumni { get; set; }
private string _pilihan = string.Empty;
public JawabSPage(TracerAlumni traceralumni)
{
InitializeComponent();
_tracerAlumni = traceralumni;
lblPertanyaan.Text = traceralumni.PERTANYAAN;
_myService = new TracerStudyService();
lvJawaban.ItemSelected += LvJawaban_ItemSelected;
btnSubmit.Clicked += BtnSubmit_Clicked;
}
private async void BtnSubmit_Clicked(object sender, EventArgs e)
{
try
{
var newJawab = new TambahTracerAlumni
{
ID_ALUMNI = Application.Current.Properties["idalumni"].ToString(),
ID_PERTANYAAN = _tracerAlumni.ID_PERTANYAAN,
ID_SURVEY = _tracerAlumni.ID_SURVEY,
USERNAME = Application.Current.Properties["alumni"].ToString(),
INSERT_DATE = DateTime.Now.ToShortDateString(),
JAWABAN = _pilihan,
IP_ADDRESS = ""
};
SimpanTracerAlumni result = await _myService.Insert(newJawab);
//await DisplayAlert("Keterangan", $"{JsonConvert.SerializeObject(newJawab)} - result {result.STATUS} - content: {result.CONTENT}","OK");
await Navigation.PopAsync();
}
catch (Exception ex)
{
await DisplayAlert("Kesalahan", ex.Message, "OK");
}
}
private void LvJawaban_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
JawabanTracerAlumni pilihan = (JawabanTracerAlumni)e.SelectedItem;
_pilihan = pilihan.PILIHAN;
btnSubmit.IsEnabled = true;
}
public JawabSPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
lvJawaban.ItemsSource = JawabTracerAlumni;
}
}
}<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Text;
namespace SimponiApp.Helpers
{
//
public class Pengaturan
{
public static string BaseUrl =
"http://api.uajy.ac.id/apisimponi/api/";
}
}
<file_sep>๏ปฟusing Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SimponiApp.Models;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SimponiApp.Services
{
public class LoginService
{
private HttpClient _client;
public LoginService()
{
_client = new HttpClient();
_client.MaxResponseContentBufferSize = 256000;
}
public async Task<Alumni> GetLogin(string username,string password)
{
WrapperAlumni wrapper = null;
var uri = new Uri($"{Helpers.Pengaturan.BaseUrl}/alumni/{username}?pwd={password}");
try
{
var response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var cleaning = JsonConvert.DeserializeObject(content);
JObject json = JObject.Parse(cleaning.ToString());
wrapper = JsonConvert.DeserializeObject<WrapperAlumni>(json.ToString());
}
return wrapper.CONTENT;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
<file_sep>๏ปฟusing SimponiApp.Models;
using SimponiApp.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace SimponiApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
private LoginService _myService;
public LoginPage()
{
InitializeComponent();
_myService = new LoginService();
}
protected async override void OnAppearing()
{
base.OnAppearing();
if (Application.Current.Properties.ContainsKey("alumni"))
{
await Navigation.PushAsync(new MenuTabbedPage());
}
}
private async void BtnLogin_Clicked(object sender, EventArgs e)
{
try
{
var data = await _myService.GetLogin(entryUsernameAlumni.Text,
entryPasswordAlumni.Text);
if (data != null)
{
Application.Current.Properties["alumni"] = data.NPM;
Application.Current.Properties["idalumni"] = data.ID_ALUMNI;
await Application.Current.SavePropertiesAsync();
await Navigation.PushAsync(new MenuTabbedPage());
}
else
{
await DisplayAlert("Keterangan", "Login Gagal","OK");
}
}
catch (Exception ex)
{
await DisplayAlert("Keterangan", ex.Message, "OK");
}
}
private async void BtnCekSession_Clicked(object sender, EventArgs e)
{
if (Application.Current.Properties.ContainsKey("alumni"))
{
var data = Application.Current.Properties["alumni"];
await DisplayAlert("Keterangan", $"Nama {data}", "OK");
}
else
{
await DisplayAlert("Keterangan", "Tidak Ditemukan", "OK");
}
}
}
}<file_sep>๏ปฟusing SimponiApp.Models;
using SimponiApp.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace SimponiApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LowonganPage : ContentPage
{
private LowonganService _myService;
public List<Lowongan> ListLowongan { get; set; }
public LowonganPage()
{
_myService = new LowonganService();
InitializeComponent();
}
protected async override void OnAppearing()
{
base.OnAppearing();
try
{
lvLowongan.ItemsSource = await _myService.GetAllData();
}
catch(Exception ex)
{
await DisplayAlert("Kesalahan", ex.Message, "OK");
}
}
private void MenuAbout_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new AboutPage());
}
}
}<file_sep>๏ปฟusing SimponiApp.Models;
using SimponiApp.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace SimponiApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DetailRestaurant : ContentPage
{
private RestaurantServices _myService;
public DetailRestaurant()
{
InitializeComponent();
_myService = new RestaurantServices();
btnEdit.Clicked += BtnEdit_Clicked;
btnDelete.Clicked += BtnDelete_Clicked;
}
private async void BtnDelete_Clicked(object sender, EventArgs e)
{
if(await DisplayAlert("Keterangan","Apakah anda yakin delete data?", "Yes", "No") == true)
{
try
{
var result = await _myService.Delete(txtID.Text);
if (result)
{
await DisplayAlert("Keterangan", "Data berhasil didelete", "OK");
await Navigation.PopAsync();
}
}
catch (Exception ex)
{
await DisplayAlert("Keterangan", ex.Message, "OK");
}
}
}
private async void BtnEdit_Clicked(object sender, EventArgs e)
{
try
{
var editResto = new Restaurant
{
restaurantid = Convert.ToInt32(txtID.Text),
namarestaurant = txtName.Text,
categoryid = Convert.ToInt32(txtCategoryID.Text)
};
var result = await _myService.Update(editResto);
await DisplayAlert("Keterangan", $"Data resto {editResto.namarestaurant} berhasil diedit", "OK");
await Navigation.PopAsync();
}
catch (Exception ex)
{
await DisplayAlert("Kesalahan", ex.Message, "OK");
}
}
}
}<file_sep>๏ปฟusing Newtonsoft.Json;
using SimponiApp.Models;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SimponiApp.Services
{
public class TracerStudyService
{
private HttpClient _client;
public TracerStudyService()
{
_client = new HttpClient();
_client.MaxResponseContentBufferSize = 256000;
}
//menampilkan data pertanyaan
public async Task<List<TracerAlumni>> GetAll(string idalumni)
{
ListTracerAlumni data = null;
var uri = new Uri($"{Helpers.Pengaturan.BaseUrl}/tracerstudyalumni?id_alumni={idalumni}");
try
{
var response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
data = JsonConvert.DeserializeObject<ListTracerAlumni>(content);
}
return data.CONTENT;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<List<JawabanTracerAlumni>> GetPertanyaan(string idpertanyaan)
{
ListJawabanTracerAlumni data = null;
var uri = new Uri($"{Helpers.Pengaturan.BaseUrl}/tracerstudyalumni?id_pertanyaan={idpertanyaan}");
try
{
var response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
data = JsonConvert.DeserializeObject<ListJawabanTracerAlumni>(content);
}
return data.CONTENT;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<SimpanTracerAlumni> Insert(TambahTracerAlumni tambahtracer)
{
var uri = new Uri($"{Helpers.Pengaturan.BaseUrl}/tracerstudyalumni/add");
try
{
var json = JsonConvert.SerializeObject(tambahtracer);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await _client.PostAsync(uri,content);
if (!response.IsSuccessStatusCode) {
throw new Exception("Tambah data gagal !");
}else
{
var dataresponse = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<SimpanTracerAlumni>(dataresponse.ToString());
return result;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Text;
namespace SimponiApp.Models
{
public class Restaurant
{
public int restaurantid { get; set; }
public string namarestaurant { get; set; }
public int categoryid { get; set; }
}
}
<file_sep>๏ปฟusing SimponiApp.Models;
using SimponiApp.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace SimponiApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TracerStudyPage : ContentPage
{
private TracerStudyService _myService;
public TracerStudyPage()
{
InitializeComponent();
_myService = new TracerStudyService();
lvTracerStudy.ItemSelected += LvTracerStudy_ItemSelected;
}
private async void LvTracerStudy_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
TracerAlumni item = (TracerAlumni)e.SelectedItem;
if (item.TIPE_JAWABAN == "T")
{
JawabTPage jawabTPage = new JawabTPage(item);
await Navigation.PushAsync(jawabTPage);
}else {
JawabSPage jawabSPage = new JawabSPage(item);
var pilihan = await _myService.GetPertanyaan(item.ID_PERTANYAAN);
jawabSPage.JawabTracerAlumni = pilihan;
await Navigation.PushAsync(jawabSPage);
}
/*await DisplayAlert(
"Keterangan",
$"ID Pertanyaan: {item.ID_PERTANYAAN} - Tipe:{item.TIPE_JAWABAN}", "OK");*/
}
protected async override void OnAppearing()
{
base.OnAppearing();
string idalumni = Application.Current.Properties["idalumni"].ToString();
try
{
lvTracerStudy.ItemsSource = await _myService.GetAll(idalumni);
}
catch (Exception ex)
{
await DisplayAlert("Kesalahan", $"Kesalahan: {ex.Message}", "OK");
}
}
}
}<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Text;
//
namespace SimponiApp.Models
{
public class Lowongan
{
public string ID_LOWONGAN_KERJA { get; set; }
public string PERUSAHAAN { get; set; }
public string TGL_SELESAI { get; set; }
}
public class ListLowongan
{
public string STATUS { get; set; }
public List<Lowongan> CONTENT { get; set; }
public string MESSAGE { get; set; }
}
}
<file_sep>๏ปฟusing Newtonsoft.Json;
using SimponiApp.Models;
using SimponiApp.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace SimponiApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class JawabTPage : ContentPage
{
private TracerStudyService _myService;
private TracerAlumni _tracerAlumni;
public JawabTPage(TracerAlumni traceralumni)
{
InitializeComponent();
_tracerAlumni = traceralumni;
_myService = new TracerStudyService();
lblPertanyaan.Text = traceralumni.PERTANYAAN;
btnSubmit.Clicked += BtnSubmit_Clicked;
}
private async void BtnSubmit_Clicked(object sender, EventArgs e)
{
try
{
var newJawab = new TambahTracerAlumni
{
ID_ALUMNI = Application.Current.Properties["idalumni"].ToString(),
ID_PERTANYAAN = _tracerAlumni.ID_PERTANYAAN,
ID_SURVEY = _tracerAlumni.ID_SURVEY,
USERNAME = Application.Current.Properties["alumni"].ToString(),
INSERT_DATE = DateTime.Now.ToShortDateString(),
JAWABAN = edJawaban.Text,
IP_ADDRESS=""
};
SimpanTracerAlumni result = await _myService.Insert(newJawab);
//await DisplayAlert("Keterangan", $"{JsonConvert.SerializeObject(newJawab)} - result {result.STATUS} - content: {result.CONTENT}","OK");
await Navigation.PopAsync();
}
catch (Exception ex)
{
await DisplayAlert("Kesalahan", ex.Message, "OK");
}
}
public JawabTPage()
{
InitializeComponent();
}
}
}<file_sep>๏ปฟusing SimponiApp.Models;
using SimponiApp.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace SimponiApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class RestaurantPage : ContentPage
{
private RestaurantServices _myService;
public RestaurantPage()
{
InitializeComponent();
_myService = new RestaurantServices();
lvRestaurant.ItemSelected += LvRestaurant_ItemSelected;
}
private async void LvRestaurant_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = (Restaurant)e.SelectedItem;
DetailRestaurant detailResto = new DetailRestaurant();
detailResto.BindingContext = item;
await Navigation.PushAsync(detailResto);
}
protected async override void OnAppearing()
{
base.OnAppearing();
lvRestaurant.ItemsSource = await _myService.GetAll();
}
}
} | 6ff8348058856e10faff0b42009c6ca18da5fb97 | [
"C#"
] | 17 | C# | ekurniawan/SimponiApp | 99065bf6327bf8e20180f8a1b99f677c965e88fa | edd6099ffc3edfa6b668d0f84e76508dea105b96 |
refs/heads/master | <repo_name>paraspatel11/MapKit<file_sep>/README.md
# MapKit
This project is to demonstrate ability to code in xcode and working knowldege of implementing Map Kit in iOS apps.
Functionality:
User can search for any address and the program shows the route to the destination along with a visual of starting point to destination and list of steps to take in order to reach the destination.


<file_sep>/Assignment_1/MapViewController.swift
//
// MapViewController.swift
// w4MapKit
//
// Created by Xcode User on 2019-09-25.
// Copyright ยฉ 2019 Xcode User. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController, UITextFieldDelegate, MKMapViewDelegate , UITableViewDelegate, UITableViewDataSource {
let locationManager = CLLocationManager()
let initialLocation = CLLocation(latitude: 43.655787, longitude: -79.73953)
let dropPin = MKPointAnnotation()
// Globalize the Drop Pin to Remove Old Pins
/*
let coordinates1 = CLLocation(latitude: 43.855787, longitude: -79.93953)
let coordinates2 = CLLocation(latitude: 43.455787, longitude: -79.93953)
let coordinates3 = CLLocation(latitude: 43.455787, longitude: -79.539536)
let coordinates4 = CLLocation(latitude: 43.855787, longitude: -79.53953)
let locationCoordinates = [coordinates1,coordinates2,coordinates3,coordinates4,coordinates1]
*/
@IBOutlet var myMapView : MKMapView!
@IBOutlet var tbLocEntered : UITextField!
@IBOutlet var tbLocEntered2 : UITextField!
@IBOutlet var tbLocEntered3 : UITextField!
/*
var locEnteredText = tbLocEntered.text!
var locEnteredText2 = tbLocEntered2.text!
var locEnteredText3 = tbLocEntered3.text!
*/
//variable for tableview - it is required when using MapKit
@IBOutlet var myTableView : UITableView!
var routeSteps = ["Enter a destination to see steps"] as NSMutableArray
//to hide keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return textField.resignFirstResponder()
}
//Method to center whatever is typed in textfield
let regionRadius : CLLocationDistance = 1000
func centerMapOnLocation(location : CLLocation)
{
let coordinateRegion = MKCoordinateRegion.init(center: location.coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
myMapView.setRegion(coordinateRegion, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
centerMapOnLocation(location: initialLocation)
let dropPin = MKPointAnnotation()
dropPin.coordinate = initialLocation.coordinate
dropPin.title = "Starting at Sheridan college"
myMapView.addAnnotation(dropPin)
myMapView.selectAnnotation(dropPin, animated: true)
drawRect()
// Do any additional setup after loading the view.
}
//to search for new location and drop pin on it
@IBAction func findNewLocation(sender : Any)
{
//self.myMapView.removeAnnotation(self.dropPin)
let locEnteredText = tbLocEntered.text!
let locEntered2Text = tbLocEntered2.text!
let locEntered3Text = tbLocEntered3.text!
// From Sheridan to Destination
let geoCoder = CLGeocoder()
// From Sheridan to Waypoint 1
let geoCoder2 = CLGeocoder()
// From Sheridan to Waypoint 2
let geoCoder3 = CLGeocoder()
geoCoder.geocodeAddressString(locEnteredText) { (placemarks, error) in
if let placemark = placemarks?.first{
let coordinates : CLLocationCoordinate2D = placemark.location!.coordinate
let newLocation = CLLocation(latitude: coordinates.latitude, longitude: coordinates.longitude)
self.centerMapOnLocation(location: newLocation)
let boxlatitude = coordinates.latitude
let boxlongitude = coordinates.longitude
if(boxlatitude <= 43.855787 && boxlatitude >= 43.455787)
{
if(boxlongitude <= -79.93953 && boxlongitude >= -79.53953)
{
let alert = UIAlertController(title: "!! Alert !!", message: "Address is in bounding box area", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
print("Worked")
}
}
/* else{
let alert = UIAlertController(title: "!! Alert !!", message: "Address is NOT in bounding box area", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}
*/
// Resets all existing overlay - Blue Line Erases
self.myMapView.removeOverlays(self.myMapView.overlays)
// Reset Pin Drop - Red Pin Erases
// self.myMapView.removeAnnotation(self.dropPin)
self.dropPin.coordinate = coordinates
self.dropPin.title = placemark.name
self.myMapView.addAnnotation(self.dropPin)
self.myMapView.selectAnnotation(self.dropPin, animated: true)
//for directions
let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: self.initialLocation.coordinate))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: coordinates))
request.requestsAlternateRoutes = false
request.transportType = .automobile
let directions = MKDirections(request: request)
directions.calculate(completionHandler: { (response, error) in
for route in response!.routes{
self.myMapView.addOverlay(route.polyline, level: MKOverlayLevel.aboveRoads)
self.myMapView.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
self.routeSteps.removeAllObjects()
for step in route.steps{
self.routeSteps.add(step.instructions)
}
// Draws Rectangle
self.drawRect()
self.myTableView.reloadData()
}//End of IF
})
} // If First Place Mark
}// End of Geo Coder Function
geoCoder2.geocodeAddressString(locEntered2Text) { (placemarks, error) in
if let placemark = placemarks?.first{
let coordinates : CLLocationCoordinate2D = placemark.location!.coordinate
let newLocation = CLLocation(latitude: coordinates.latitude, longitude: coordinates.longitude)
self.centerMapOnLocation(location: newLocation)
// Resets all existing overlay - Blue Line Erases
self.myMapView.removeOverlays(self.myMapView.overlays)
// Reset Pin Drop - Red Pin Erases
// self.myMapView.removeAnnotation(self.dropPin)
self.dropPin.coordinate = coordinates
self.dropPin.title = placemark.name
self.myMapView.addAnnotation(self.dropPin)
self.myMapView.selectAnnotation(self.dropPin, animated: true)
//for directions
let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: self.initialLocation.coordinate))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: coordinates))
request.requestsAlternateRoutes = false
request.transportType = .automobile
let directions = MKDirections(request: request)
directions.calculate(completionHandler: { (response, error) in
for route in response!.routes{
self.myMapView.addOverlay(route.polyline, level: MKOverlayLevel.aboveRoads)
self.myMapView.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
self.routeSteps.removeAllObjects()
for step in route.steps{
self.routeSteps.add(step.instructions)
}
// Draws Rectangle
self.drawRect()
self.myTableView.reloadData()
}//End of IF
})
}// If First Place Mark
}
geoCoder3.geocodeAddressString(locEntered3Text) { (placemarks, error) in
if let placemark = placemarks?.first{
let coordinates : CLLocationCoordinate2D = placemark.location!.coordinate
let newLocation = CLLocation(latitude: coordinates.latitude, longitude: coordinates.longitude)
self.centerMapOnLocation(location: newLocation)
// Resets all existing overlay - Blue Line Erases
self.myMapView.removeOverlays(self.myMapView.overlays)
// Reset Pin Drop - Red Pin Erases
//self.myMapView.removeAnnotation(self.dropPin)
self.dropPin.coordinate = coordinates
self.dropPin.title = placemark.name
self.myMapView.addAnnotation(self.dropPin)
self.myMapView.selectAnnotation(self.dropPin, animated: true)
//for directions
let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: self.initialLocation.coordinate))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: coordinates))
request.requestsAlternateRoutes = false
request.transportType = .automobile
let directions = MKDirections(request: request)
directions.calculate(completionHandler: { (response, error) in
for route in response!.routes{
self.myMapView.addOverlay(route.polyline, level: MKOverlayLevel.aboveRoads)
self.myMapView.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
self.routeSteps.removeAllObjects()
for step in route.steps{
self.routeSteps.add(step.instructions)
}
// Draws Rectangle
self.drawRect()
self.myTableView.reloadData()
}//End of IF
})
} // If First Place Mark
}// end of geocode 3
}// End of IBOutlet
//------------------------ Rect Radius Start-------------------------------
func drawRect() {
let coordinates1 = CLLocation(latitude: 43.855787, longitude: -79.93953)
let coordinates2 = CLLocation(latitude: 43.455787, longitude: -79.93953)
let coordinates3 = CLLocation(latitude: 43.455787, longitude: -79.53953)
let coordinates4 = CLLocation(latitude: 43.855787, longitude: -79.53953)
let locationCoordinates = [coordinates1,coordinates2,coordinates3,coordinates4,coordinates1]
let coordinates = locationCoordinates.map { $0.coordinate }
let polyLine = MKPolyline(coordinates: coordinates, count: coordinates.count)
self.myMapView.addOverlay(polyLine)
}
//------------------------ Rect Radius Stop -------------------------------
//------------------------ Check Alert Start-------------------------------
//------------------------ Check Alert Stop -------------------------------
//------------------------ Ploygon Method Start-------------------------------
/*
func addAnnotations() {
myMapView?.delegate = self
myMapView?.addAnnotations(places)
let overlays = places.map { MKCircle(center: $0.coordinate, radius: 100) }
myMapView?.addOverlays(overlays)
var locations = places.map { $0.coordinate }
let polyline = MKPolyline(coordinates: &locations, count: locations.count)
myMapView?.add(polyline)
}
*/
//------------------------ Ploygon Method Stop-------------------------------
//method to draw route lines
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
renderer.strokeColor = .blue
renderer.lineWidth = 3.0
return renderer
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return routeSteps.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 30
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let tableCell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell(style: .default, reuseIdentifier: "cell")
tableCell.textLabel?.text = routeSteps[indexPath.row] as? String
return tableCell
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
| 27e4255e5162b14aa41cc4921c66edaf56486c82 | [
"Markdown",
"Swift"
] | 2 | Markdown | paraspatel11/MapKit | f0fb18e0f870913ba14b19922efb4293de19c7d8 | 5f7d1593d00765756991a8033d183067b70a0d02 |
refs/heads/master | <file_sep>
import java.util.Random;
public class Producer implements Runnable{
Random generator =new Random();
Buffer SharedLocation;
public Producer(Buffer Shared)
{
SharedLocation=Shared;
}
public void run(){
int sum=0;
for(int count =1 ;count<=10 ;count++){
try{
Thread.sleep(generator.nextInt(3000));
SharedLocation.set(count);
sum+=count;
System.out.println(sum);
}
catch(InterruptedException exception){
exception.printStackTrace();
}
}
System.out.println("Producer done producing &Terminating");
}
}
<file_sep>//package osprojectsim;
import java.util.*;
public class Process {
public String name;
public int id;
public int size;
public int duration; //time remaining
public int pageTable[];
public int index;
public int Brust[];
public Process(String name,int id,int size,int duration){
Random rand = new Random();
this.name=name;
this.id = id;
System.out.println("intializing PID " + this.id +" process is "+ this.name);
Brust = new int[duration];
index = 0;
Brust = new int[duration];
for(int i=1;i<duration-1;i++){
Brust[i]=rand.nextInt(2);
}
Brust[0] = Brust[duration-1] = 1;
this.size=size;
this.duration=duration;
pageTable=new int[size];
}
}<file_sep>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class OsProjectSim {
public static void runFile(){
FileSystem F = new FileSystem();
F.open("This PC");
F.createFolder("Nadia");
F.createFolder("Yasmine");
F.createFolder("Yasmine");
F.open("Nadia");
F.createFolder("Documents");
F.open("Documents");
F.createFile("a", "txt");
F.createFile("b", "zip");
F.createFile("c", "pdf");
F.back();
F.createFolder("Pictures");
F.open("Pictures");
F.createFile("1", "jpg");
F.createFile("2", "jpg");
F.back();
F.createFile("Code","exe");
F.back();
F.open("Yasmine");
F.createFile("Eclipse","exe");
F.createFolder("Books");
F.open("Books");
F.createFile("Java", "pdf");
F.createFile("C++", "pdf");
F.back();
F.createFolder("Videos");
F.open("Videos");
F.createFile("a", "mp4");
F.createFile("b", "mp4");
F.back();
F.createFile("OS","java");
F.closeFolder();
}
public static void runCpu() {
Process p1 = new Process ("a",1,10,10);
Process p2 = new Process ("b",2,10,5);
Process p3 = new Process ("c",3,10,15);
CPU1 theCPU = new CPU1 ();
theCPU.readyQ.insert(p1);
theCPU.readyQ.insert(p2);
theCPU.readyQ.insert(p3);
theCPU.dispatcher();
}
public static void runMemory() {
MainMemory1 m = new MainMemory1();
Process p1=new Process("p1",1,50,3);
Process p2=new Process("p2",2,15,3);
Process p3=new Process("p3",3,3,3);
m.Allocation(p1);
m.Allocation(p2);
m.Allocation(p3);
m.Deallocation(p2);
}
public static void TestSync(){
ExecutorService application =Executors.newCachedThreadPool();
Buffer SharedLocation= new Synchronize();
application.execute(new Producer(SharedLocation));
application.execute(new Consumer(SharedLocation));
application.shutdown();
}
public static void main(String[] args) {
System.out.println("CPU Scheduling Test ");
runCpu();
System.out.println("Memory Test ");
runMemory();
System.out.println("Files Test ");
runFile();
System.out.println("Synchronization Test ");
TestSync();
}
}
<file_sep>import java.util.LinkedList;
class FolderOrFile{
String name;
String dateCreated;
Folder parent;
public FolderOrFile(String name, Folder parent){
this.name = name;
this.parent = parent;
}
}
class Folder extends FolderOrFile{
LinkedList<FolderOrFile> contents;
public Folder(String name, Folder parent){
super(name,parent);
contents = new LinkedList<FolderOrFile>();
}
}
class File extends FolderOrFile{
String extention;
String type;
public File(String name, String extention, Folder parent){
super(name,parent);
this.extention = extention;
}
}
public class FileSystem {
Folder mountPoint = new Folder("zero", null);
Folder root;
FolderOrFile temp;
Folder currentLocation;
public FileSystem(){
root = new Folder("This PC",mountPoint);
mountPoint.contents.add(root);
currentLocation = mountPoint;
}
public void createFolder(String name){
for(FolderOrFile F:currentLocation.contents){
if(F.name.equals(name)){
if(F instanceof Folder){
System.out.println("This destination already contains a folder named '" + name +"'.Choose another name!");
return;
}
}
}
Folder newFolder = new Folder(name,currentLocation);
currentLocation.contents.add(newFolder);
displayContents();
}
public void createFile(String name, String extention){
for(FolderOrFile F:currentLocation.contents){
if(F.name.equals(name)){
if(F instanceof File && ((File) F).extention.equals(name)){
System.out.println("There is already a file with this name in this location.");
return;
}
}
}
File newFile = new File(name,extention,currentLocation);
currentLocation.contents.add(newFile);
displayContents();
}
public void open (String name){
for(FolderOrFile F:currentLocation.contents){
if(F.name.equals(name)){
if(F instanceof Folder){
currentLocation = (Folder)F;
displayContents();
}
else{
System.out.println("File " + F.name + " is opend.\n");
}
}
}
}
public void copy(String name){
for(FolderOrFile F:currentLocation.contents){
if(F.name.equals(name)){
temp = F;
return;
}
}
}
public void cut(String name){
for(FolderOrFile F:currentLocation.contents){
if(F.name.equals(name)){
temp = F;
currentLocation.contents.remove(F);
return;
}
}
}
public void paste(){
if (temp == null)
return;
temp.parent = currentLocation;
currentLocation.contents.add(temp);
displayContents();
}
public void displayContents(){
int cnt = 0;
System.out.println(currentLocation.name+":");
for(FolderOrFile F:currentLocation.contents){
if(F instanceof Folder)
System.out.println(" "+F.name);
else if(F instanceof File)
System.out.println(" "+F.name +"."+ ((File)F).extention);
cnt ++;
}
if (cnt == 0)System.out.println(" This folder is empty");
System.out.print("\n");
}
public void rename(String oldName, String newName){
for(FolderOrFile F:currentLocation.contents){
if(F.name.equals(oldName)){
F.name = newName;
displayContents();
return;
}
}
}
public void delete(String name){
for(FolderOrFile F:currentLocation.contents){
if(F.name.equals(name)){
currentLocation.contents.remove(F);
return;
}
}
}
public void back(){
if (currentLocation.parent != null){
currentLocation = currentLocation.parent;
displayContents();
}
}
public void closeFile(String name){
System.out.println("File " + name + " has been closed.\n");
}
public void closeFolder(){
currentLocation = mountPoint;
}
}
| 03ec746311df0025f0bcd107e6ccff1fe40d4c8e | [
"Java"
] | 4 | Java | DoaaAwad/OSProjectSim | 095553af0626c7dfcf2ed446ebaffe76135e75b2 | d41d701db0b7da92e4151455f2524db658f32534 |
refs/heads/master | <file_sep>//Language: English
//Translator: ntoombs19
const translations = {
filter_01: "LA Enhancer",
filter_02: "Instructions",
filter_03: "Created by",
filter_04: "Load Pages",
filter_05: "to",
filter_06: "Enable",
filter_07: "Hide All/None",
filter_08: "Scout Attack",
filter_09: "No losses",
filter_10: "Some losses",
filter_11: "Lost, but damaged building(s)",
filter_12: "Lost,but scouted",
filter_13: "Lost",
filter_14: "Order By",
filter_15: "Distance",
filter_16: "Time",
filter_17: "Direction",
filter_18: "Ascending",
filter_19: "Descending",
filter_20: "Hide Hauls",
filter_21: "Full",
filter_22: "Partial",
filter_23: "Hide Attacks",
filter_24: "Greater Than",
filter_25: "Less Than",
filter_26: "Equal To",
filter_27: "Hide farms sent to in the last",
filter_28: "minutes",
filter_29: "Reset",
filter_30: "Hide Wall Lvl",
filter_31: "Hide Distances",
filter_32: "Hide",
filter_33: "Show",
filter_34: "continent(s)",
filter_35: "Hide scout reports with resources",
filter_36: "villages plundered in the last",
filter_37: "minute(s)",
filter_38: "Run default automatically",
filter_39: "All rows are hidden",
filter_40: "Loot Assistant",
filter_41: "Loot Assistant - Loading page",
filter_42: "Language",
filter_43: "Go to next village when...",
filter_44: "Not enough units available",
filter_45: "scouts are remaining",
filter_46: "Farming troops are available",
filter_47: "villages sent to in the last",
filter_48: "minute(s)",
filter_49: "Hot Keys",
filter_50: "Master Button Settings",
filter_51: "Skip next farm",
filter_52: "Previous village",
filter_53: "Next village",
filter_54: "If row matches profile",
filter_55: "click",
filter_56: "Skip",
filter_57: "A",
filter_58: "B",
filter_59: "C",
filter_60: "If row doesn't match any profiles, click",
filter_61: "dnes", //must be as it appears in tribalwars
filter_62: "vฤera", //must be as it appears in tribalwars
filter_63: "N",
instructions_01: "Checked report types will be hidden",
instructions_02: "Filters left unchecked will not be applied",
instructions_03: "Separate continents with a period. Example: 55.54.53",
instructions_04: "This filter will hide rows that were farmed \"n\" minutes ago. The default is 60 minutes. Changing the time will only affect newly farmed rows. Clicking reset will reset all the timers for each row but only the rows loaded.",
instructions_05: "Save and load your constious settings configurations here. Changing profiles will load the selected profile. The default will load automatically when the script is run.",
instructions_06: "Adjust page size to 100 for faster page loading",
dialog_01: "Are you sure you want to reset your recently farmed villages?",
dialog_02: "You are already on the default profile. Would you like to create a new profile and set it to default?",
dialog_03: "Profile name",
dialog_04: "You already have a profile with that name. Please choose another name",
dialog_05: "Your profile name cannot be empty. Please try again.",
dialog_06: "You cannot delete your default profile",
dialog_07: "You cannot export/import the default profile. To export these settings, create a new profile, then try exporting again.",
dialog_08: "Copy to clipboard: Ctrl+C, Enter",
dialog_09A: "[b]LA Enhancer: ",
dialog_09B: "[/b][spoiler][i][u]Instructions[/u]: To import this profile, copy the following line of code then import the copied settings by pasting them into the prompt after clicking import on the LA Enhancer Script settings panel[/i][code]",
dialog_09C: "[/code][/spoiler]",
dialog_10: "Profile Settings",
dialog_11: "Ctrl+V to paste here settings here",
dialog_12: "You already have a profile with that name.",
dialog_13: "Reload this script to see the new language. This page will refresh automatically.",
profile_01: "Settings profile",
profile_02: "Apply",
profile_03: "Reset",
profile_04: "New",
profile_05: "Set Default",
profile_06: "Delete",
profile_07: "Save Changes",
profile_08: "Export",
profile_09: "Import",
profile_10: "Default"
} | cd225f08dbd5aa7a94f41ecfc35dc14bcdf284a8 | [
"JavaScript"
] | 1 | JavaScript | syreanis/enhancer | 01a008b00561ef01d8f35093204d4d3ab4b9b797 | f8e84b98e99ce2c36c7a76cf16b4562f8fc0c4fe |
refs/heads/master | <file_sep>#ifndef NORMAL_DISTRIBUTION_CONFIDENCE_INTERVAL_H
#define NORMAL_DISTRIBUTION_CONFIDENCE_INTERVAL_H
#include "ruby.h"
void Init_confidence_interval( void );
#endif //NORMAL_DISTRIBUTION_CONFIDENCE_INTERVAL_H
<file_sep>#ifndef NORMAL_DISTRIBUTION_H
#define NORMAL_DISTRIBUTION_H
#include "model.h"
#include "confidence_interval.h"
#endif //NORMAL_DISTRIBUTION_H
<file_sep># frozen_string_literal: true
RSpec.describe NormalDistribution::ConfidenceInterval do
describe 'functionality' do
context 'with success' do
it 'correctly returns given bounds' do
interval = NormalDistribution::ConfidenceInterval.new -2.1, 4.4
expect(interval).to have_attributes lower_bound: -2.1,
upper_bound: 4.4
end
it 'includes value between bounds' do
interval = NormalDistribution::ConfidenceInterval.new -2.1, 4.4
expect(interval.include?(0.1)).to eq true
end
it 'does not include value between bounds' do
interval = NormalDistribution::ConfidenceInterval.new -2.1, 4.4
expect(interval.include?(4.41)).to eq false
end
end
context 'with raised error' do
it 'raises type error when lower bound is not a number' do
expect {
NormalDistribution::ConfidenceInterval.new 'hello', 4.4
}.to raise_error TypeError, 'no implicit conversion to float from string'
end
it 'raises type error when upper bound is not a number' do
expect {
NormalDistribution::ConfidenceInterval.new -2.1, 'world'
}.to raise_error TypeError, 'no implicit conversion to float from string'
end
it 'raises argument error when lower bound is greater then upper bound' do
expect {
NormalDistribution::ConfidenceInterval.new 4.0, 2.0
}.to raise_error ArgumentError, 'lower bound must not be greater then upper bound'
end
it 'raises error when #include? non-numerical argument' do
interval = NormalDistribution::ConfidenceInterval.new -2.1, 4.4
expect { interval.include?('hello') }.to raise_error TypeError,
'no implicit conversion to float from string'
end
end
end
end<file_sep># frozen_string_literal: true
module NormalDistribution
# Model class of normal distribution
#
# @since 0.1.0
class Model
# @!parse [ruby]
#
# # @return [Float] mean of data contained in model
# attr_reader :mean
#
# # @return [Float] standard deviation of data contained in model
# attr_reader :standard_deviation
#
# # Initializes normal distribution model from given data
# #
# # @param values [Array<Numeric>] non-empty array of numbers representing data for normal distribution construction
# def initialize(values)
# # This is stub used for indexing
# end
#
# # Calculates confidence interval for given probability in percentage
# #
# # @param percentage [Numeric] a number in interval <0, 100> representing probability in percentage
# # @return [ConfidenceInterval] an instance of ConfidenceInterval class
# #
# # @since 0.2.0
# def confidence_interval(percentage)
# # This is stub used for indexing
# end
end
end
<file_sep>///
/// https://github.com/lakshayg/erfinv
///
#ifndef NORMAL_DISTRIBUTION_ERF_INV_H
#define NORMAL_DISTRIBUTION_ERF_INV_H
#include <math.h>
long double t_erf_inv( long double x );
#endif //NORMAL_DISTRIBUTION_ERF_INV_H
<file_sep># frozen_string_literal: true
module NormalDistribution
# Confidence interval of normal distribution
#
# @since 0.2.0
class ConfidenceInterval
# @!parse [ruby]
#
# # @return [Float] lower bound of confidence interval
# attr_reader :lower_bound
#
# # @return [Float] upper bound of confidence interval
# attr_reader :upper_bound
#
# # Initializes confidence interval
# #
# # @param lower_bound [Numeric] lower bound of confidence interval
# # @param upper_bound [Numeric] upper bound of confidence interval
# def initialize(lower_bound, upper_bound)
# # This is stub used for indexing
# end
#
# # Decides, whether value is from the interval
# #
# # @param value [Numeric] value to be compared with interval bounds
# # @return [Boolean] true if value is from the interval. Otherwise returns false.
# def include?(value)
# # This is stub used for indexing
# end
end
end<file_sep>#include "confidence_interval.h"
static VALUE t_init( VALUE self, VALUE lower_bound, VALUE upper_bound ) {
double lower = NUM2DBL( lower_bound );
double upper = NUM2DBL( upper_bound );
if ( lower > upper ) {
rb_raise( rb_eArgError, "lower bound must not be greater then upper bound" );
}
rb_iv_set( self, "@lower_bound", lower_bound );
rb_iv_set( self, "@upper_bound", upper_bound );
return self;
}
static VALUE t_attr_get_upper_bound( VALUE self ) {
return rb_iv_get( self, "@upper_bound" );
}
static VALUE t_attr_get_lower_bound( VALUE self ) {
return rb_iv_get( self, "@lower_bound" );
}
static VALUE t_include( VALUE self, VALUE value ) {
double lower = NUM2DBL( rb_iv_get( self, "@lower_bound" ) );
double upper = NUM2DBL( rb_iv_get( self, "@upper_bound" ) );
double v = NUM2DBL( value );
return v < lower || v > upper ? Qfalse : Qtrue;
}
void Init_confidence_interval( void ) {
VALUE rb_mNormalDistribution = rb_path2class( "NormalDistribution" );
VALUE rb_cConfidenceInterval = rb_define_class_under( rb_mNormalDistribution, "ConfidenceInterval", rb_cObject );
rb_define_method( rb_cConfidenceInterval, "initialize", t_init, 2 );
rb_define_method( rb_cConfidenceInterval, "lower_bound", t_attr_get_lower_bound, 0 );
rb_define_method( rb_cConfidenceInterval, "upper_bound", t_attr_get_upper_bound, 0 );
rb_define_method( rb_cConfidenceInterval, "include?", t_include, 1 );
}
<file_sep># frozen_string_literal: true
require "mkmf"
create_makefile("normal_distribution/normal_distribution")
<file_sep># frozen_string_literal: true
require "normal_distribution/version"
require "normal_distribution/normal_distribution"
# Namespace for classes and modules serving for normal distribution based calculations
#
# @since 0.1.0
module NormalDistribution
end
<file_sep>require "bundler/gem_tasks"
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec)
require "rake/extensiontask"
task :build => :compile
Rake::ExtensionTask.new("normal_distribution") do |ext|
ext.lib_dir = "lib/normal_distribution"
end
task :default => [:clobber, :compile, :spec]
require "yard"
YARD_FILES = Dir["lib/**/*.rb", "ext/**/*.rb"]
YARD::Rake::YardocTask.new do |t|
t.files = YARD_FILES # optional
t.options = %w(-o doc --readme README.md) # optional
end
<file_sep># frozen_string_literal: true
module NormalDistribution
# Current version of NormalDistribution gem
VERSION = "0.2.0"
end
<file_sep>#ifndef NORMAL_DISTRIBUTION_MODEL_H
#define NORMAL_DISTRIBUTION_MODEL_H
#include "ruby.h"
#include "erf_inv.h"
#include "confidence_interval.h"
void Init_model( void );
#endif //NORMAL_DISTRIBUTION_MODEL_H
<file_sep>#include "normal_distribution.h"
void Init_normal_distribution( void ) {
rb_define_module( "NormalDistribution" );
Init_confidence_interval();
Init_model();
}
<file_sep>#include "model.h"
static double t_parse_percentage( VALUE percentage ) {
double perc = NUM2DBL( percentage );
if ( perc > 100 || perc < 0 ) {
rb_raise( rb_eArgError, "percentage must be between 0 and 100" );
}
return perc;
}
static double t_mean( double * data, long size ) {
double sum = .0;
for ( long i = 0 ; i < size ; ++ i ) {
sum += data[i];
}
return sum / size;
}
static double t_z_score( double percentage ) {
return sqrt( 2 ) * t_erf_inv( percentage / 100 );
}
static double t_variance( double * data, long size, double mean ) {
double * squared_diff = ALLOC_N( double, size );
for ( long i = 0 ; i < size ; ++ i ) {
squared_diff[i] = pow( mean - data[i], 2 );
}
double variance = t_mean( squared_diff, size );
free( squared_diff );
return variance;
}
static double t_stddev( double * data, long size, double mean ) {
return sqrt( t_variance( data, size, mean ) );
}
static double * t_parse_dbl_ary( VALUE ary, long * size ) {
Check_Type( ary, T_ARRAY );
long len = RARRAY_LEN( ary );
if ( len == 0 ) {
rb_raise( rb_eArgError, "data must not be empty" );
}
VALUE * values = RARRAY_PTR( ary );
double * d_data = ALLOC_N( double, len );
for ( int i = 0 ; i < len ; ++ i ) {
d_data[i] = NUM2DBL( values[i] );
}
*size = len;
return d_data;
}
static VALUE t_init( VALUE self, VALUE values ) {
long size;
double * data = t_parse_dbl_ary( values, &size );
double mean = t_mean( data, size );
double stddev = t_stddev( data, size, mean );
rb_iv_set( self, "@mean", rb_float_new( mean ) );
rb_iv_set( self, "@standard_deviation", rb_float_new( stddev ) );
xfree( data );
return self;
}
static VALUE t_confidence_interval( VALUE self, VALUE percentage ) {
double perc = t_parse_percentage( percentage );
double z = t_z_score( perc );
double stddev = NUM2DBL( rb_iv_get( self, "@standard_deviation" ) );
double mean = NUM2DBL( rb_iv_get( self, "@mean" ) );
double lower_bound = - z * stddev + mean;
double upper_bound = z * stddev + mean;
VALUE rb_cConfidenceInterval = rb_path2class( "NormalDistribution::ConfidenceInterval" );
VALUE interval = rb_funcall(
rb_cConfidenceInterval, rb_intern( "new" ), 2,
rb_float_new( lower_bound ),
rb_float_new( upper_bound )
);
return interval;
}
static VALUE t_attr_mean( VALUE self ) {
return rb_iv_get( self, "@mean" );
}
static VALUE t_attr_stddev( VALUE self ) {
return rb_iv_get( self, "@standard_deviation" );
}
void Init_model( void ) {
VALUE rb_mNormalDistribution = rb_path2class( "NormalDistribution" );
VALUE rb_cModel = rb_define_class_under( rb_mNormalDistribution, "Model", rb_cObject );
rb_define_method( rb_cModel, "initialize", t_init, 1 );
rb_define_method( rb_cModel, "confidence_interval", t_confidence_interval, 1 );
rb_define_method( rb_cModel, "mean", t_attr_mean, 0 );
rb_define_method( rb_cModel, "standard_deviation", t_attr_stddev, 0 );
}
<file_sep># frozen_string_literal: true
RSpec.describe NormalDistribution::Model do
describe 'functionality' do
subject { NormalDistribution::Model.new data }
context 'with successful evaluation' do
let(:data) { [1, 2, 2, 3, 3, 3, 4, 4, 5] }
it 'calculates correctly mean of data' do
expect(subject.mean).to eq 3
end
it 'calculates correctly standard deviation of data' do
expect(subject.standard_deviation).to be_within(0.0001).of(1.1547)
end
it 'calculates correctly confidence interval' do
interval = subject.confidence_interval(95)
expect(interval).to be_instance_of(NormalDistribution::ConfidenceInterval)
expect(interval.lower_bound).to be_within(0.0001).of(0.7368)
expect(interval.upper_bound).to be_within(0.0001).of(5.2631)
end
end
context 'with failure' do
context 'with invalid percentage value' do
let(:data) { [1, 2, 3] }
it 'raises error when greater then 100 %' do
expect { subject.confidence_interval(101) }.to raise_error ArgumentError,
'percentage must be between 0 and 100'
end
it 'raises error when lower then 0 %' do
expect { subject.confidence_interval(-1) }.to raise_error ArgumentError,
'percentage must be between 0 and 100'
end
it 'raises error when percentage is a string' do
expect {
subject.confidence_interval('invalid_type')
}.to raise_error TypeError, 'no implicit conversion to float from string'
end
end
context 'with invalid type of data' do
let(:data) { 'invalid_input' }
it 'raises error' do
expect { subject }.to raise_error TypeError, 'wrong argument type String (expected Array)'
end
end
context 'with empty data' do
let(:data) { [] }
it 'raises error' do
expect { subject }.to raise_error ArgumentError, 'data must not be empty'
end
end
context 'with non-numerical array of data' do
let(:data) { ['invalid_data'] }
it 'raises error' do
expect { subject }.to raise_error TypeError, 'no implicit conversion to float from string'
end
end
end
end
describe 'performance' do
specify 'constructor performs linearly depending on data' do
sizes = bench_range(8, 100_000)
data_arrays = sizes.map { |n| Array.new(n) { rand(n) } }
expect { |_, i|
NormalDistribution::Model.new data_arrays[i]
}.to perform_linear.in_range(sizes)
end
specify 'confidence interval calculation performs constantly' do
min, max = 8, 1_000_000
sizes = bench_range(min, max)
models = sizes.map do |n|
data = Array.new(n) { rand(n) }
NormalDistribution::Model.new data
end
percentages = sizes.map { |n| normalize(n, min: min, max: max) * 100 }
expect { |_, i|
models[i].confidence_interval percentages[i]
}.to perform_constant.in_range(sizes)
end
def normalize(n, min:, max:)
(n.to_f - min) / (max - min)
end
end
end | 1b5d54301151679370fb7ace33563e2e50e426f3 | [
"C",
"Ruby"
] | 15 | C | domcermak/normal_distribution | 6ca8ebdb066b9e72be0c1d55d5ace8f0f29510d8 | fd983ac9d91fdfaed02615e09b16d20077e134ee |
refs/heads/master | <repo_name>ShubhankarS/dynamodb-export<file_sep>/README.md
# dynamodb-export
Scan a Dynamodb table in batches, transform documents as needed and write them in batches to SQS in order to be consumed by another environment
<file_sep>/migrate.js
const AWS = require('aws-sdk');
const async = require('async');
AWS.config.update({
region: 'ap-southeast-1'
});
var dynamodb = new AWS.DynamoDB({
apiVersion: '2012-08-10'
});
const SQS = new AWS.SQS({
apiVersion: '2012-11-05'
});
//TODO replace queue URL
const QUEUE_URL = "https://sqs.ap-southeast-1.amazonaws.com/test-queue";
const batchSize = 500;
var params = {
TableName: "test-table",
Limit: batchSize,
ExclusiveStartKey: null
};
async.forever(
function(callback) {
dynamodb.scan(params, function(err, data) {
if (err) {
console.log(err, err.stack, params.ExclusiveStartKey)
callback(err)
} else {
var docs = data.Items;
docs = docs.map((entry) => {
//transform documents as needed
});
if (!docs || docs.length == 0) {
return callback("All documents finished!");
}
console.log('got docs', docs.length);
console.log('last eval key', data.LastEvaluatedKey);
if (data.LastEvaluatedKey) {
params.ExclusiveStartKey = data.LastEvaluatedKey;
}
var toSend = {
MessageBody: JSON.stringify(docs),
QueueUrl: QUEUE_URL,
DelaySeconds: 0
};
SQS.sendMessage(toSend, function(err, data) {
if (err) {
console.log("Error pushing to queue", QUEUE_URL, err.stack);
callback(err);
} else {
console.log(`Successfully processed ${docs.length} records.`);
if (!data.LastEvaluatedKey) {
return callback("All documents finished!");
} else {
callback();
}
}
});
}
});
},
function(err) {
console.log('err', err);
console.log('last eval was', params.ExclusiveStartKey);
}
); | fc2a9eee256381e0f6f470104691804483e38fca | [
"Markdown",
"JavaScript"
] | 2 | Markdown | ShubhankarS/dynamodb-export | 59115693f96213a59b45d9a1bb39db65b5e226cd | 7e762593a7cbb41db0b8c7716c20d18e033d90ae |
refs/heads/master | <repo_name>kjlundsgaard/guessing-game<file_sep>/game.py
# importing random module
from random import randint
#greet player
#get player name
name = raw_input("Hey! What's your name? ")
#print name in prompt
print "Hey %s, I'm thinking of a number between 1 and 100." % (name)
#choose random number beteen 1 and 100
def guessing_game():
number = randint(1, 100)
# print number
# get guess from player
guess = None
# making a list of guesses
guess_list = []
# score_list = []
# while True:
while guess != number:
# get guess
while True:
guess = raw_input("Take a guess: ")
try:
guess = int(guess)
break
except:
print "That's not a number, dummy! Try harder"
if guess < 1 or guess > 100:
print "That number is not between 1 and 100! Try again"
# if guess is in guess_list, print "you've already guessed that number"
elif guess in guess_list:
print "you've already guessed that number!"
#
else:
guess_list = guess_list.append(guess)
# if guess is incorrect:
if guess < number:
print "Your guess is too low! Try again."
elif guess > number:
print "Your guess is too high! Try again."
# if guess is correct:
else:
break
# congratulate player
guesses = len(guess_list)
# score_list = score_list.append(guesses)
# low_score =
print "Congratulations! The number was %d and you guessed it in %d tries" % (number, guesses)
print "Would you like to play again?"
play_again = raw_input("type 'y' if yes or 'n' if no: ").lower()
if play_again == 'y':
guessing_game()
else:
print "Thanks for playing, go enjoy real life."
guessing_game()
| 136cba3b69fd4d33c4f841ddd1505d108fbc47f3 | [
"Python"
] | 1 | Python | kjlundsgaard/guessing-game | 058328d3b6022084f8154664e80ad6d8f303de65 | d0d39d2ba665c4a8f3560bd2b3ae99c34821ee8c |
refs/heads/master | <repo_name>vstishenok/School<file_sep>/View/Print.cs
๏ปฟusing System;
using System.Collections.Generic;
using Model.Entity;
namespace View
{
public static class Print
{
private const string LIST_IS_EMPTY = "Sorry, pupils is empty...";
public static string Show(IEnumerable<Pupil> list)
{
string result = "";
IEnumerator<Pupil> iterator = list.GetEnumerator();
while (iterator.MoveNext())
{
result += iterator.Current + "\n";
}
return result.Length != 0? result : LIST_IS_EMPTY;
}
}
}<file_sep>/Model/Entity/SqlAbstractDAO.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Model.Entity
{
public class SqlAbstractDAO: IAbstractDAO
{
private string connectionString = "";
public IDbConnection GetConnection()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
public void ReleaseConnection(IDbConnection connection)
{
connection.Close();
}
}
}
<file_sep>/Util/Util.cs
๏ปฟusing System;
using System.Globalization;
using Model.Entity;
namespace Util
{
public static class Util
{
public static Pupil GetPupil()
{
Pupil pupil = new Pupil();
Console.Write("Enter surname: ");
pupil.Surname = Console.ReadLine();
Console.Write("Enter name: ");
pupil.Name = Console.ReadLine();
Console.Write("Enter passport: ");
pupil.Passport = Console.ReadLine();
Console.Write("Enter date (yyyy-mm-dd): ");
pupil.Birthday = DateTime.Parse(Console.ReadLine());
Console.Write("Enter rating (0-10): ");
pupil.Rating = float.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
return pupil;
}
}
}<file_sep>/Model/Interface/IAbstractDAO.cs
using System.Data;
namespace Model.Entity
{
public interface IAbstractDAO
{
IDbConnection GetConnection();
void ReleaseConnection(IDbConnection connection);
}
}<file_sep>/Model/Logic/Manager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using Model.Entity;
namespace Model.Logic
{
public class Manager
{
private const float PUPIL_MIN_RATING = 0;
private const float PUPIL_MAX_RATING = 10;
public static float CalculateAvgRating(IEnumerable<Pupil> list)
{
float avg = 0;
int count = 0;
IEnumerator<Pupil> iterator = list.GetEnumerator();
while (iterator.MoveNext())
{
avg += iterator.Current.Rating;
count++;
}
return (float)Math.Round(avg / count, 1);
}
public static IList<Pupil> GetPupilsMaxRating(IEnumerable<Pupil> list)
{
IList<Pupil> result = new List<Pupil>();
float maxRating = FindMaxRating(list);
if (maxRating != -1)
{
IEnumerator<Pupil> iterator = list.GetEnumerator();
while (iterator.MoveNext())
{
if (iterator.Current.Rating == maxRating)
{
result.Add(iterator.Current);
}
}
}
return result;
}
public static IList<Pupil> GetPupilsMinRating(IEnumerable<Pupil> list)
{
IList<Pupil> result = new List<Pupil>();
float minRating = FindMinRating(list);
if (minRating != -1)
{
IEnumerator<Pupil> iterator = list.GetEnumerator();
while (iterator.MoveNext())
{
if (iterator.Current.Rating == minRating)
{
result.Add(iterator.Current);
}
}
}
return result;
}
private static float FindMaxRating(IEnumerable<Pupil> list)
{
float maxRating = PUPIL_MIN_RATING;
IEnumerator<Pupil> iterator = list.GetEnumerator();
while (iterator.MoveNext())
{
if (iterator.Current.Rating > maxRating )
{
maxRating = iterator.Current.Rating;
}
}
return maxRating;
}
private static float FindMinRating(IEnumerable<Pupil> list)
{
float minRating = PUPIL_MAX_RATING;
IEnumerator<Pupil> iterator = list.GetEnumerator();
while (iterator.MoveNext())
{
if (iterator.Current.Rating < minRating)
{
minRating = iterator.Current.Rating;
}
}
return minRating;
}
}
}<file_sep>/README.md
# SchoolPupils
ะะพะฝัะพะปัะฝะพะต ะฟัะธะปะพะถะตะฝะธะต ะดะปั ัะตะดะฐะบัะธัะพะฒะฐะฝะธั ัะฟะธัะบะฐ ััะฐัะธั
ัั ัะบะพะปั ะฒ mssql
<file_sep>/Model/Entity/Pupil.cs
using System;
namespace Model.Entity
{
public class Pupil
{
private float rating;
public string Surname { get; set; }
public string Name { get; set; }
public string Passport { get; set; }
public DateTime Birthday { get; set; }
public float Rating
{
get => rating;
set
{
if (rating >= 0 && rating <= 10) rating = value;
}
}
public Pupil()
{
}
public Pupil(string surname, string name, string passport, DateTime birthday, float rating)
{
Surname = surname;
Name = name;
Passport = passport;
Birthday = birthday;
Rating = rating;
}
public override string ToString()
{
return "Surname: " + Surname +
", Name: " + Name +
", Passport: " + Passport +
", Birthday: " + Birthday.ToString("dd:MM:yyyy") +
", Rating: " + Rating.ToString("F1");
}
}
}<file_sep>/Model/Entity/SqlPupilDAO.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace Model.Entity
{
public class SqlPupilDAO : SqlAbstractDAO, IPupilDAO
{
private const string SELECT_ALL_PUPILS = "SELECT * FROM Pupil";
private const string SELECT_PUPIL = "SELECT * FROM Pupil WHERE pupil_id = @id";
private const string INSERT_PUPIL =
"INSERT INTO Pupil(surname, name, passport, birthday, rating) VALUES (@surname, @name, @passport, @birthday, @rating)";
private const string UPDATE_PUPIL =
"UPDATE Pupil SET surname = @surname, name = @name, passport = @passport, birthday = @birthday, rating = @rating WHERE pupil_id = @id";
private const string DELETE_PUPIL = "DELETE FROM Pupil WHERE pupil_id = @id";
private const string SELECT_COUNT = "SELECT count(pupil_id) FROM Pupil";
private const string MSG_NOT_PUPIL_GIVEN_ID_IN_DATABASE = "Pupil with given id is not present in database";
public IList<Pupil> GetAllPupils()
{
SqlConnection connection = (SqlConnection) GetConnection();
SqlCommand command = new SqlCommand(SELECT_ALL_PUPILS, connection);
SqlDataReader reader = command.ExecuteReader();
IList<Pupil> list = new List<Pupil>();
if (reader.HasRows)
{
while (reader.Read())
{
Pupil pupil = new Pupil();
pupil.Surname = reader.GetString(1);
pupil.Name = reader.GetString(2);
pupil.Passport = reader.GetString(3);
pupil.Birthday = reader.GetDateTime(4);
pupil.Rating = reader.GetFloat(5);
list.Add(pupil);
}
}
ReleaseConnection(connection);
return list;
}
public Pupil GetPupil(int id)
{
SqlConnection connection = null;
connection = (SqlConnection) GetConnection();
SqlCommand command = new SqlCommand(SELECT_PUPIL, connection);
SqlParameter idParam = new SqlParameter();
idParam.ParameterName = "@id";
idParam.Value = id;
idParam.SqlDbType = SqlDbType.Int;
idParam.Direction = ParameterDirection.Input;
command.Parameters.Add(idParam);
SqlDataReader reader = command.ExecuteReader();
Pupil pupil = new Pupil();
if (reader.HasRows)
{
reader.Read();
pupil.Surname = reader.GetString(1);
pupil.Name = reader.GetString(2);
pupil.Passport = reader.GetString(3);
pupil.Birthday = reader.GetDateTime(4);
pupil.Rating = reader.GetFloat(5);
}
ReleaseConnection(connection);
return pupil;
}
public void InsertPupil(Pupil pupil)
{
SqlConnection connection = (SqlConnection) GetConnection();
SqlCommand command = new SqlCommand(INSERT_PUPIL, connection);
SqlParameter surnameParam = new SqlParameter();
surnameParam.Value = pupil.Surname;
surnameParam.SqlDbType = SqlDbType.NVarChar;
surnameParam.ParameterName = "@surname";
surnameParam.Direction = ParameterDirection.Input;
command.Parameters.Add(surnameParam);
SqlParameter nameParam = new SqlParameter();
nameParam.Value = pupil.Name;
nameParam.SqlDbType = SqlDbType.NVarChar;
nameParam.ParameterName = "@name";
nameParam.Direction = ParameterDirection.Input;
command.Parameters.Add(nameParam);
SqlParameter passportParam = new SqlParameter();
passportParam.Value = pupil.Passport;
passportParam.SqlDbType = SqlDbType.NVarChar;
passportParam.ParameterName = "@passport";
passportParam.Direction = ParameterDirection.Input;
command.Parameters.Add(passportParam);
SqlParameter birthdayParam = new SqlParameter();
birthdayParam.Value = pupil.Birthday;
birthdayParam.SqlDbType = SqlDbType.DateTime;
birthdayParam.ParameterName = "@birthday";
birthdayParam.Direction = ParameterDirection.Input;
command.Parameters.Add(birthdayParam);
SqlParameter ratingParam = new SqlParameter();
ratingParam.Value = pupil.Rating;
ratingParam.SqlDbType = SqlDbType.Float;
ratingParam.ParameterName = "@rating";
ratingParam.Direction = ParameterDirection.Input;
command.Parameters.Add(ratingParam);
command.ExecuteNonQuery();
ReleaseConnection(connection);
}
public void DeletePupil(int id)
{
SqlConnection connection = (SqlConnection) GetConnection();
SqlCommand command = new SqlCommand(DELETE_PUPIL, connection);
SqlParameter idParam = new SqlParameter();
idParam.ParameterName = "@id";
idParam.Value = id;
idParam.SqlDbType = SqlDbType.Int;
idParam.Direction = ParameterDirection.Input;
command.Parameters.Add(idParam);
command.ExecuteNonQuery();
ReleaseConnection(connection);
}
public void UpdatePupil(Pupil pupil, int id)
{
SqlConnection connection = (SqlConnection) GetConnection();
SqlCommand command = new SqlCommand(UPDATE_PUPIL, connection);
SqlParameter idParam = new SqlParameter();
idParam.ParameterName = "@id";
idParam.Value = id;
idParam.SqlDbType = SqlDbType.Int;
idParam.Direction = ParameterDirection.Input;
command.Parameters.Add(idParam);
SqlParameter surnameParam = new SqlParameter();
surnameParam.Value = pupil.Surname;
surnameParam.SqlDbType = SqlDbType.NVarChar;
surnameParam.ParameterName = "@surname";
surnameParam.Direction = ParameterDirection.Input;
command.Parameters.Add(surnameParam);
SqlParameter nameParam = new SqlParameter();
nameParam.Value = pupil.Name;
nameParam.SqlDbType = SqlDbType.NVarChar;
nameParam.ParameterName = "@name";
nameParam.Direction = ParameterDirection.Input;
command.Parameters.Add(nameParam);
SqlParameter passportParam = new SqlParameter();
passportParam.Value = pupil.Passport;
passportParam.SqlDbType = SqlDbType.NVarChar;
passportParam.ParameterName = "@passport";
passportParam.Direction = ParameterDirection.Input;
command.Parameters.Add(passportParam);
SqlParameter birthdayParam = new SqlParameter();
birthdayParam.Value = pupil.Birthday;
birthdayParam.SqlDbType = SqlDbType.DateTime;
birthdayParam.ParameterName = "@birthday";
birthdayParam.Direction = ParameterDirection.Input;
command.Parameters.Add(birthdayParam);
SqlParameter ratingParam = new SqlParameter();
ratingParam.Value = pupil.Rating;
ratingParam.SqlDbType = SqlDbType.Float;
ratingParam.ParameterName = "@rating";
ratingParam.Direction = ParameterDirection.Input;
command.Parameters.Add(ratingParam);
command.ExecuteNonQuery();
ReleaseConnection(connection);
}
public int GetCountPupil()
{
SqlConnection connection = (SqlConnection) GetConnection();
SqlCommand command = new SqlCommand(SELECT_COUNT, connection);
int count = (int)command.ExecuteScalar();
ReleaseConnection(connection);
return count;
}
}
}<file_sep>/Model/Interface/IPupilDAO.cs
using System.Collections.Generic;
namespace Model.Entity
{
public interface IPupilDAO
{
IList<Pupil> GetAllPupils();
Pupil GetPupil(int id);
void InsertPupil(Pupil pupil);
void UpdatePupil(Pupil pupil, int id);
void DeletePupil(int id);
int GetCountPupil();
}
}<file_sep>/Controller/Program.cs
๏ปฟusing System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using Model.Entity;
using Model.Logic;
using static View.Print;
using static Util.Util;
namespace Controller
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Task \"School pupils\"\n");
IPupilDAO pupilDao = new SqlPupilDAO();
Console.WriteLine("Count pupils in database: " + pupilDao.GetCountPupil() + "\n");
//ะฒัะฒะพะด ะฝะฐ ะบะพะฝัะพะปั ะฒัะต ััะตะฝะธะบะพะฒ
IList<Pupil> list = pupilDao.GetAllPupils();
Console.WriteLine("Pupils information:\n" + Show(list));
//ะฒัะฒะพะด ะฝะฐ ะบะพะฝัะพะปั ะพะดะฝะพะณะพ ััะตะฝะธะบะฐ
Console.WriteLine("Print information pupil by id");
Console.Write("Enter id pupil: ");
int id = Int32.Parse(Console.ReadLine());
Console.WriteLine(pupilDao.GetPupil(id));
Console.WriteLine();
//ะดะพะฑะฐะฒะปะตะฝะธะต ััะตะฝะธะบะฐ ะฒ ะฑะฐะทั ะดะฐะฝะฝัั
Console.WriteLine("Add pupil in database");
pupilDao.InsertPupil(GetPupil());
list = pupilDao.GetAllPupils();
Console.WriteLine("Pupils information:\n" + Show(list));
Console.WriteLine();
//ัะดะฐะปะตะฝะธะต ััะตะฝะธะบะฐ ะฟะพ id
Console.WriteLine("Delete pupil in database by id");
Console.Write("Enter id pupil: ");
id = Int32.Parse(Console.ReadLine());
pupilDao.DeletePupil(id);
list = pupilDao.GetAllPupils();
Console.WriteLine("Pupils information:\n" + Show(list));
//ะพะฑะฝะพะฒะปะตะฝะธะต ะธะฝัะพัะผะฐัะธะธ ะพะฑ ััะตะฝะธะบะต ะฟะพ id
Console.WriteLine("Update information pupil in database by id");
Console.Write("Enter id pupil: ");
id = Int32.Parse(Console.ReadLine());
pupilDao.UpdatePupil(GetPupil(), id);
list = pupilDao.GetAllPupils();
Console.WriteLine("Pupils information:\n" + Show(list));
list = pupilDao.GetAllPupils();
Console.WriteLine("Average rating of all students: " + Manager.CalculateAvgRating(list));
Console.WriteLine();
Console.WriteLine("Students with min rating:\n" + Show(Manager.GetPupilsMinRating(list)));
Console.WriteLine("Students with max rating:\n" + Show(Manager.GetPupilsMaxRating(list)));
}
}
} | 9eb117e57d4f7ec97619d7ac6e9f60141230607c | [
"Markdown",
"C#"
] | 10 | C# | vstishenok/School | 0220bba6029c8668d836b6942ecba3b2b6cdd3ae | 71a076796feec773b28c4bd036054c71de9a8e34 |
refs/heads/master | <file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Multinet.Math.Impl
{
public class RungeKuttaMethod : INumericalMethod
{
private Dictionary<string, double> vars;
public RungeKuttaMethod()
{
vars = new Dictionary<string, double>();
vars["step"] = 0.02;
}
public double this[string name]
{
get
{
return vars[name];
}
set
{
vars[name] = value;
}
}
public double nextState(double runDuration, double state, TargetFunction f)
{
//4th Order Runge-Kutta ====================================================
double k1, k2, k3, k4;
double step = this["step"];
double pState = state;
k1 = f(state);
state = pState + 0.5 * step * k1;
k2 = f(state);
state = pState + 0.5 * step * k2;
k3 = f(state);
state = pState + step * k3;
k4 = f(state);
state = pState + (k1 + 2 * (k2 + k3) + k4) * step / 6.0;
if (state > 100)
{
state = 100;
}
else if (state < -100)
{
state = -100;
}
return state;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Multinet.Math
{
public class Tanh : Function
{
public double Exec(double v)
{
return System.Math.Tanh(v);
}
public double Min()
{
return -1.0;
}
public double Max()
{
return 1.0;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
namespace Multinet.Genetic
{
public class GeneticA
{
private List<Genome> genomes;
private MutationMethod mutationMethod;
private CrossoverMethod crossoverMethod;
private GenomeBuilderMethod builderMethod;
private GenomeTranslatorMethod translatorMethod;
private uint populationSize;
private double mutationRate;
private uint numberOfEvaluations;
private double survivalRate;
private uint minPopulationSize;
private bool selectDuplicatedGenome;
private int elitism;
private int validGenomes;
private int maxRetries = 1000;
public GeneticA(uint psize = 100, double mr = 0.05)
{
this.validGenomes = 0;
this.populationSize = psize;
this.mutationRate = mr;
this.survivalRate = 1.0;
this.numberOfEvaluations = 0;
this.minPopulationSize = 0;
this.elitism = 2;
this.selectDuplicatedGenome = false;
InitializeDefaultBehavior();
}
public int MaxRetries {
get {
return maxRetries;
}
set {
maxRetries = value;
}
}
public int Elitism
{
get
{
return elitism;
}
set
{
elitism = value;
}
}
public bool SelectDuplicatedGenome
{
get
{
return selectDuplicatedGenome;
}
set
{
selectDuplicatedGenome = value;
}
}
public uint MinPopulationSize
{
get
{
return minPopulationSize;
}
set
{
minPopulationSize = value;
}
}
public double SurvivalRate
{
get
{
return survivalRate;
}
set
{
survivalRate = value;
}
}
public List<Genome> Population
{
get
{
return genomes;
}
}
public GenomeTranslatorMethod Translator
{
get
{
return this.translatorMethod;
}
set
{
this.translatorMethod = value;
}
}
public uint PopulationSize
{
get
{
return populationSize;
}
set
{
this.populationSize = value;
}
}
public double MutationRate
{
get
{
return this.mutationRate;
}
set
{
this.mutationRate = value;
}
}
public GenomeBuilderMethod GenomeBuilder
{
get
{
return this.builderMethod;
}
set
{
this.builderMethod = value;
}
}
public CrossoverMethod Crossover
{
get
{
return this.crossoverMethod;
}
set
{
this.crossoverMethod = value;
}
}
public MutationMethod Mutation
{
get
{
return this.mutationMethod;
}
set
{
mutationMethod = value;
}
}
public void init()
{
CheckPrerequistes();
genomes = new List<Genome>();
numberOfEvaluations = 0;
for (uint i = 0; i < populationSize; i++)
{
genomes.Add(GenomeBuilder());
}
}
public void InitEvaluation(double[] statistic)
{
statistic[0] = double.MaxValue;
statistic[1] = double.MinValue;
statistic[2] = 0.0;
numberOfEvaluations = 0;
validGenomes = 0;
}
public void EndEvaluation(double[] statistic)
{
}
public double EvaluateOne(Genome genome, Evaluator evaluator, double[] statistic)
{
if (statistic == null || statistic.Length < 3)
{
throw new ArgumentException("Invalid array of statistic information.");
}
Evaluable evaluable = Translator(genome);
double fitness = evaluator.evaluate(evaluable);
if (fitness > 0) {
validGenomes++;
}
statistic[2] += fitness;
this.numberOfEvaluations++;
if (fitness < statistic[0])
{
statistic[0] = fitness;
}
if (fitness > statistic[1])
{
statistic[1] = fitness;
}
return fitness;
}
public void UpdateStatistic(double fitness, Problem prob)
{
this.UpdateStatistic(fitness, prob.Statistic);
}
public void UpdateStatistic(double fitness, double []statistic) {
if (fitness > 0) {
validGenomes++;
}
if (statistic == null || statistic.Length < 3)
{
throw new ArgumentException("Invalid array of statistic information.");
}
statistic[2] += fitness;
this.numberOfEvaluations++;
if (fitness < statistic[0])
{
statistic[0] = fitness;
}
if (fitness > statistic[1])
{
statistic[1] = fitness;
}
}
public uint NextGeneration(double[] statistic)
{
if (validGenomes == 0)
{
throw new Exception("Extinction!!");
}
List<Genome> parents = new List<Genome>();
List<Genome> children = new List<Genome>();
int n = genomes.Count();
genomes.Sort();
if (elitism > 0)
{
int added = 0;
for (int i = n - 1; i >= 0 && added < elitism; i--)
{
children.Add(genomes[i]);
added++;
}
}
int survivors = (int)(populationSize * survivalRate);
Dictionary<int, int> selected = new Dictionary<int, int>();
//Console.WriteLine("SURVIVORS: {0}", survivors);
int q = 0; //quantidade de sobreviventes adicionados
int retries = 0;
while (q < survivors)
{
double pos = Multinet.Math.PRNG.NextDouble(); //selecao de uma posicao aleatoria na roleta
//Console.WriteLine("POS: {0}", pos);
double region = 1.0;
for (int i = n-1; i > 0; i--)
{
Genome current = genomes[i];
double p = (current.Value / statistic[2]);
if ( pos <= region && !selected.ContainsKey(i))
{
selected[i] = i;
parents.Add(current);
q++;
break;
}
region -= p;
}
retries++;
if (retries > maxRetries) {
break;
}
//System.Console.WriteLine("COMP {0} {1}", position, region);
}
parents.Sort();
n = parents.Count();
// System.Console.WriteLine("PARENTS SIZE: {0}", n);
for (int i = n - 1; i >= 0; i--)
{
Genome g1 = parents.ElementAt(i);
for (int j = i; j >= 0 ; j--)
{
if (i != j)
{
Genome g2 = parents.ElementAt(j);
Genome child1 = crossoverMethod(g1, g2);
Genome child2 = crossoverMethod (g2, g1);
child1.Value = 0;
child2.Value = 0;
if (child1 != null)
{
mutationMethod(child1, MutationRate);
children.Add(child1);
if (children.Count >= populationSize) {
goto END_LOOP;
}
mutationMethod (child2, MutationRate);
children.Add (child2);
if (children.Count >= populationSize) {
goto END_LOOP;
}
}
}
}
}
END_LOOP:
uint m = (uint)children.Count();
if (m < minPopulationSize)
{
uint r = minPopulationSize - (uint)children.Count();
for (uint k = 0; k < r; k++)
{
children.Add(builderMethod());
}
}
genomes = children;
return (uint)genomes.Count();
}
private void CheckPrerequistes()
{
if (builderMethod == null)
{
throw new GenomeBuilderNotDefinedException();
}
if (translatorMethod == null)
{
throw new GenomeTranslatorNotDefinedException();
}
}
private void InitializeDefaultBehavior()
{
this.builderMethod = null;
this.crossoverMethod = CrossoverImpl.CrossoverMethod;
this.mutationMethod = MutationImpl.MutationMethod;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Multinet.Math
{
public interface INumericalMethod
{
double nextState(double runDuration, double currentState, TargetFunction machine);
double this[string var]
{
get;
set;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using Multinet.Net;
using Multinet.Genetic;
using Multinet.Utils;
using Multinet.Net.Impl;
using Multinet.Net.Ext;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Multinet.Sample
{
public class MatrixPatternOnlineProblem
{
private static Random rnd = new Random();
public int[][] state;
public long time;
public bool training = true;
public const int INPUT_SIZE = 9, HIDDEN_SIZE = 20, OUTPUT_SIZE = 1;
private const float REST = 0.0f;
private Problem problem;
private GeneticA genetic;
private Genome currentGenome;
public MatrixPatternOnlineProblem ()
{
genetic = new GeneticA(200, 0.005);
genetic.Translator = (Genome gen) => {
HIRON3 hiron3 = new HIRON3(INPUT_SIZE, HIDDEN_SIZE, OUTPUT_SIZE, gen);
hiron3.CreateParameters();
hiron3.CreateNeurons();
hiron3.CreateSynapses();
NeuralNet net = hiron3.Net;
//Console.WriteLine(net);
return net;
};
genetic.GenomeBuilder = () => {
Genome gen = new Genome();
Chromossome neuronGain = new Chromossome();
int n = INPUT_SIZE + HIDDEN_SIZE + OUTPUT_SIZE;
for (uint i = 0; i < n; i++)
{
neuronGain.AddGene(i, rnd.NextDouble());
}
int synapsesNumber = HIDDEN_SIZE * (INPUT_SIZE + OUTPUT_SIZE);
Chromossome synapses = new Chromossome();
Chromossome zeroProb = new Chromossome();
for (uint i = 0; i < synapsesNumber; i++)
{
synapses.AddGene(i, rnd.NextDouble());
zeroProb.AddGene(i, rnd.NextDouble());
}
gen.AddChromossome(0, neuronGain);
gen.AddChromossome(1, synapses);
gen.AddChromossome(2, zeroProb);
return gen;
};
genetic.MinPopulationSize = 200;
genetic.Elitism = 2;
problem = new Problem(genetic);
}
/// <summary>
/// Setup this simulation instance.
/// </summary>
public void Setup() {
state = new int[9][];
state [0] = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0};
state [1] = new int[]{0, 1, 0,
0, 1, 0,
0, 1, 0};
state [2] = new int[]{1, 0, 0,
0, 1, 0,
0, 0, 1};
state [3] = new int[]{1, 0, 0,
1, 0, 0,
1, 0, 0};
state [4] = new int[]{0, 0, 1,
0, 0, 1,
0, 0, 1};
state [5] = new int[]{1, 1, 1,
0, 0, 0,
0, 0, 0};
state [6] = new int[]{0, 0, 0,
1, 1, 1,
0, 0, 0};
state [7] = new int[]{0, 0, 0,
0, 0, 0,
1, 1, 1};
state [8] = new int[]{0, 0, 1,
0, 1, 0,
1, 0, 0};
time = 0;
problem.Start();
problem.StartEpoch();
problem.NextGenome(out currentGenome);
}
private double sum = 0;
/// <summary>
/// Evaluate the specified genome <code>gen<code> based in problem <code>p<code/>.
/// </summary>
/// <param name="p">P.</param>
/// <param name="gen">Gen.</param>
public void evaluate() {
currentGenome.Value = System.Math.Max(0.000001f, 10 - sum); //set genome fitness
genetic.UpdateStatistic(currentGenome.Value, problem);
sum = 0; //reset to next genome evaluation
}
/// <summary>
/// Gets a random state of current problem instance.
/// </summary>
/// <returns>The current state.</returns>
private int stateidx;
public int GetCurrentState() {
int[] nstates = {0, 1, 2, 3, 4, 5, 6, 7, 8};
int ss = stateidx;
stateidx++;
if (stateidx >= nstates.Length)
{
stateidx = 0;
}
return nstates[ss];
}
private int live = 0;
private const int MAX_LIFES = 9;
/// <summary>
/// Step this simulation instance.
/// </summary>
public bool Step () {
//Console.WriteLine ("Current Time: {0} ", time);
if (live >= MAX_LIFES) {
evaluate();
if (!problem.NextGenome(out currentGenome))
{
uint surviviors = problem.EndEpoch();
Console.WriteLine("Epoch {0} Statistic: MIN = {1}, MAX={2}, AVG={3}", problem.Epoch, problem.Statistic[0], problem.Statistic[1], problem.Statistic[2]/genetic.Population.Count);
if (problem.Epoch >= 10)
{
return false;
} else
{
problem.StartEpoch();
problem.NextGenome(out currentGenome);
}
if (surviviors < 0)
{
throw new Exception("Extinรงรฃo! Ninguรฉm conseguiu evoluir o suficiente!");
}
}
live = 0;
}
NeuralNet net = (NeuralNet)genetic.Translator(currentGenome);
int s = GetCurrentState ();
float e = (s == 4 ? 1.0f : 0.0f);
float c = NetDecision(s, net);
float erro = e - c;
sum += erro * erro;
time++;
live++;
return true;
}
public void Run(string path="genome.bin") {
FileStream stream = new FileStream (path, FileMode.Open);
BinaryFormatter form = new BinaryFormatter ();
Genome gen = (Genome) form.Deserialize (stream);
stream.Close();
NeuralNet net = (NeuralNet) genetic.Translator(gen);
int userc;
do
{
Console.WriteLine("Select a pattern [0, 8] or -1 to exit: ");
userc = int.Parse(Console.ReadLine());
if (userc < 0 || userc > 8)
{
break;
}
float c = NetDecision(userc, net);
Console.WriteLine("NET OUTPUT: {0}", c);
} while (userc >= 0);
}
/// <summary>
/// Run a simulation instance.
/// </summary>
public void Training() {
Setup ();
while (Step()) ;
List<Genome> pop = genetic.Population;
pop.Sort();
Genome last = pop[pop.Count-1];
last.Serialize ("genome.bin");
}
private float NetDecision(int stateIdx, NeuralNet net){
for (int i = 0; i < INPUT_SIZE; i++) {
net [i].ProccessInput (state[stateIdx][i] + REST);
}
net.Proccess ();
int t = INPUT_SIZE + HIDDEN_SIZE + OUTPUT_SIZE;
float outnet = (float)net[t - 1].GetOutput();
return outnet;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Multinet.Utils;
namespace Multinet.Genetic
{
[Serializable]
public class Chromossome
{
public static int GENE_SIZE = 32;
private Dictionary<uint, BitArray> genes;
public Chromossome()
{
genes = new Dictionary<uint, BitArray>();
}
public void AddGene(uint id, double value)
{
genes.Add(id, BitArrayUtils.ToBitArray(value));
}
public bool SetGene(uint id, BitArray gene)
{
genes[id] = gene;
return true;
}
public int Size
{
get
{
return this.genes.Count();
}
}
public void AddGene(uint id, uint value)
{
genes.Add(id, BitArrayUtils.ToBitArray(value));
}
public void AddGene(uint id, BitArray code)
{
genes.Add(id, code);
}
public BitArray GetGene(uint gid)
{
if (genes.ContainsKey(gid))
{
return (BitArray)genes[gid];
}
else
{
return null;
}
}
public ICollection<uint> GetKeys()
{
return genes.Keys;
}
public BitArray DelGene(uint id)
{
BitArray ret = GetGene(id);
genes.Remove(id);
return ret;
}
override
public string ToString()
{
string txt = "";
foreach (KeyValuePair<uint, BitArray> gene in genes)
{
txt += string.Format("{0}:{1} ", gene.Key, BitArrayUtils.ToNDouble(gene.Value));
}
return txt;
}
}
}
<file_sep>๏ปฟ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Multinet.Math;
namespace Multinet.Net.Impl
{
public class Beer1995Neuron : ANeuronImpl
{
public Beer1995Neuron()
{
this["outputgain"] = 1.0;
this["inputgain"] = 1.0;
this["inputweight"] = 1.0;
this["sensorweight"] = 1.0;
this["bias"] = 0.0;
SetFunction(new Multinet.Math.Sigmoid(), "neuronfunction");
}
public override double GetOutput(Neuron ne)
{
return (OutputAmp * GetPotential(ne) - OutputShift) * this["outputgain"];
}
public override double GetPotential(Neuron n)
{
return GetFunction("neuronfunction").Exec(n.State + this["bias"]);
}
public override double SetInput(Neuron ne, double inv)
{
//Console.WriteLine("INPUTGAIN: {0}", this["inputgain"]);
ne.SensorValue = inv * this["inputgain"];
return ne.SensorValue;
}
public override double Step(Neuron target, Net net, double state)
{
NeuralNet nnet = (NeuralNet)net;
int nNeurons = net.Size;
double s = 0;
double iw = this["inputweight"];
double sw = this["sensorweight"];
if (iw != 0)
{
foreach (Cell con in target.Incame)
{
Synapse syn = net[con.X, con.Y];
Neuron ne = net[syn.From];
double zi = ne.Implementation.GetPotential (ne);
double wij = syn.Intensity;
//Console.WriteLine("SYNAPSE({0}, {1}) = {2}", con.X, con.Y, wij);
s += wij * zi; //inputs of neuron id == column id
}
}
double sensorValue = target.SensorValue;
target.SensorValue = 0;
double nstate = (-state + (s * iw + sensorValue * sw + nnet.RestInput))/(target.TimeConst != 0 ? target.TimeConst: 0.00000001);
if (nstate < -100) {
nstate = -100;
} else if (nstate > 100) {
nstate = 100;
}
//Console.WriteLine("STATE: {0}", nstate);
return nstate;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Multinet.Math;
namespace Multinet.Net
{
/// <summary>
/// INeuronImpl is a contract to neuron basic utilities.
/// It provides neccessary interface to general network nodes.
/// </summary>
public interface INeuronImpl
{
bool UseNumericalMethod
{
get;
set;
}
/// <summary>
/// This method returns a function named (<code>funcname</code>).
/// </summary>
/// <param name="funcname">Function name</param>
/// <returns>Function implementation</returns>
Function GetFunction(string funcname);
/// <summary>
/// This method defines a function named <code>funcname</code>.
/// </summary>
/// <param name="f">Function</param>
/// <param name="funcname">Function name</param>
void SetFunction(Function f, string funcname);
/// <summary>
/// This indexer returns a variable value associated with a variable named <code>var</code>.
/// </summary>
/// <param name="var">variable name</param>
/// <returns>variable value</returns>
double this[string var]
{
get;
set;
}
/// <summary>
/// This method implements a basic equation that updates neuron state.
/// </summary>
/// <param name="target">Neuron to update</param>
/// <param name="net">Network with support neuron activity.</param>
/// <returns></returns>
double Step(Neuron target, Net net, double state);
/// <summary>
/// Returns neuron frequency potential.
/// </summary>
/// <param name="n">Target neuron.</param>
/// <returns>Neuron frequency potential</returns>
double GetPotential(Neuron n);
/// <summary>
/// This method defines a input value of neuron associated with sensor input.
/// </summary>
/// <param name="ne">Input neuron</param>
/// <param name="inv">Sensor value</param>
/// <returns></returns>
double SetInput(Neuron ne, double inv);
/// <summary>
/// This method returns a neuron output value associated with a network output.
/// </summary>
/// <param name="ne"></param>
/// <returns></returns>
double GetOutput(Neuron ne);
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Multinet.Math
{
public class Sigmoid : Function
{
public double Exec(double v)
{
double d = (1 + System.Math.Exp (-v));
if (d == 0.0) {
d = 0.00000000000001;
}
return 1.0 / d;
}
public double Min()
{
return 0.0;
}
public double Max()
{
return 1.0;
}
}
}
<file_sep>๏ปฟusing System;
using Multinet.Sample;
using Multinet.Genetic;
using Multinet.Net;
using Multinet.Net.Impl;
using Multinet.Utils;
using Multinet.Math;
namespace Multinet.App
{
class Program
{
public static void XOR()
{
XORProblem problem = new XORProblem();
problem.Run();
}
public static void MatrixPattern()
{
MatrixPatternOnlineProblem mp = new MatrixPatternOnlineProblem();
mp.Training();
mp.Run();
}
public static void run1()
{
int[] st = new int[2];
st[0] = 0;
st[1] = 0;
Multinet.Math.PRNG.SetSeed(Environment.TickCount);
int len = 200;
for (int i = 0; i < len; i++)
{
double c = Multinet.Math.PRNG.NextDouble();
System.Console.WriteLine(c);
if (c > 0.5)
{
st[0]++;
}
else
{
st[1]++;
}
}
Console.WriteLine("Head: {0}%, Tail: {1}%", (int)(100 * (st[0] / (float)len)), (int)(100 * (st[1] / (float)len)));
}
public static void testsimples()
{
Genome genome = new Genome();
Chromossome chrGain = new Chromossome();
chrGain.AddGene(0, 0.5);
chrGain.AddGene(1, 0.5);
chrGain.AddGene(2, 0.8);
Chromossome chrSyn = new Chromossome();
chrSyn.AddGene(0, 0.001);
chrSyn.AddGene(1, 0.0);
chrSyn.AddGene(2, 0.01);
Chromossome chrBias = new Chromossome();
chrBias.AddGene(0, 0.02);
chrBias.AddGene(1, 1.0);
chrBias.AddGene(2, 0.77);
genome.AddChromossome(0, chrGain);
genome.AddChromossome(1, chrSyn);
genome.AddChromossome(2, chrBias);
Multinet.Net.Ext.HIRON3 hiron = new Multinet.Net.Ext.HIRON3(1, 1, 1, genome);
hiron.CreateParameters();
hiron.CreateNeurons();
hiron.CreateSynapses();
NeuralNet net = hiron.Net;
Console.WriteLine(net);
double input = 0;
ConsoleKey inputInfo = ConsoleKey.C;
while (inputInfo == ConsoleKey.C)
{
Console.Write("Net Input: ");
input = double.Parse(Console.ReadLine());
net[0].ProccessInput(input);
net.Proccess();
System.Console.WriteLine("Net Output {0}", net[2].GetOutput());
Console.Write("Pressione C para continuar ou outra tecla para sair...");
inputInfo = Console.ReadKey().Key;
Console.WriteLine();
}
}
public static void Pattern()
{
MatrixPatternOfflineProblem problem = new MatrixPatternOfflineProblem();
problem.Run();
}
static void Main(string[] args)
{
MatrixPattern();
//XOR();
//run1();
Console.ReadKey();
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Multinet.Genetic
{
public interface Evaluator
{
double evaluate(Evaluable obj);
}
}
<file_sep>๏ปฟ/**
* This file contains basic implementation of a neuralnet with homeostatic properties.
* For more informations, contact me: <EMAIL>.
*/
using System;
using System.Collections.Generic;
using Multinet.Math;
namespace Multinet.Net
{
/// <summary>
/// This class encapsulates the key features of the neural nodes.
/// </summary>
public class Neuron
{
private Net net;
private int Id;
private double state;
private double sensorValue;
private double timeConstant;
private double duration;
private INeuronImpl neuronImpl;
private LinkedList<Cell> income;
private LinkedList<Cell> outcame;
public Neuron(int id)
{
this.income = new LinkedList<Cell>();
this.outcame = new LinkedList<Cell>();
this.state = 0.0;
this.Id = id;
this.sensorValue = 0.0;
this.timeConstant = 1.0;
this.duration = 1.0;
this.neuronImpl = new Multinet.Net.Impl.Beer1995Neuron();
}
public double Duration
{
get
{
return duration;
}
set
{
duration = value;
}
}
public LinkedList<Cell> Incame
{
get
{
return income;
}
}
public LinkedList<Cell> Outcame
{
get
{
return outcame;
}
}
public Net Network
{
get
{
return net;
}
set
{
net = value;
}
}
public int ID
{
get
{
return Id;
}
set
{
Id = value;
}
}
public double State
{
get
{
return state;
}
set
{
state = value;
}
}
public double SensorValue
{
get
{
return sensorValue;
}
set
{
sensorValue = value;
}
}
public double TimeConst
{
get
{
return timeConstant;
}
set
{
timeConstant = value;
}
}
public double ProccessInput(double input)
{
return this.Implementation.SetInput(this, input);
}
public double GetOutput()
{
return this.Implementation.GetOutput(this);
}
public double Proccess()
{
if (Implementation.UseNumericalMethod)
{
return (state = net.NumericalMethod.nextState(duration, state, onestep));
} else
{
return (state = onestep(state));
}
}
public INeuronImpl Implementation
{
get
{
return neuronImpl;
}
set
{
neuronImpl = value;
}
}
private double onestep(double state)
{
return neuronImpl.Step(this, net, state);
}
}
} //namespace end
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Multinet.Net;
namespace Multinet.Genetic
{
public delegate bool StopCondiction(Problem context);
public enum EventType
{
STOPPED_CONDICTION_SATISFIED,
POPULATION_EXTINCTION
}
public interface ProblemEventHandler
{
void handleGaStopped(Problem source, EventType type);
void handleCurrentStatistic(long popSize, long epoch, double[] statistic);
void handleCurrentPopulation(long epoch, Problem p, GeneticA genetic);
void handleEndPopulation(Problem p, GeneticA genetic);
}
public class DebugProblemEventHandler : ProblemEventHandler
{
public void handleCurrentPopulation(long epoch, Problem p, GeneticA genetic)
{
Console.WriteLine("Population at epoch {0} has {1} chromossomes.", epoch, genetic.PopulationSize);
}
public void handleCurrentStatistic(long popSize, long epoch, double[] statistic)
{
Console.WriteLine("Statistic(MINFITNESS={0}, MAXFITNESS={1}, AVG={2}", statistic[0], statistic[1], statistic[2]/popSize);
}
public void handleEndPopulation(Problem p, GeneticA genetic)
{
int q = genetic.Population.Count();
if (q > 0)
{
genetic.Population.Sort();
Genome better = genetic.Population.ElementAt(q - 1);
Evaluable eval = genetic.Translator(better);
Console.WriteLine("Evaluable Information: ");
Console.WriteLine(eval);
Console.WriteLine("FITNESS: {0}", p.EvaluatorEngine.evaluate(eval));
}
}
public void handleGaStopped(Problem source, EventType type)
{
if (type == EventType.POPULATION_EXTINCTION)
{
Console.WriteLine("Population Extinction!");
} else if (type == EventType.STOPPED_CONDICTION_SATISFIED)
{
Console.WriteLine("End of Training!");
}
}
}
public class Problem
{
private GeneticA geneticEngine;
private Evaluator evaluatorEngine;
private StopCondiction stopCondiction;
private ProblemEventHandler eventHandler;
private long epoch;
private double[] statistic;
public long Epoch {
get {
return epoch;
}
}
public Evaluator EvaluatorEngine
{
get
{
return evaluatorEngine;
}
}
public Problem(GeneticA genetic, Evaluator evaluator, StopCondiction method, ProblemEventHandler eventHandler)
{
this.evaluatorEngine = evaluator;
this.geneticEngine = genetic;
this.stopCondiction = method;
this.eventHandler = eventHandler;
}
public Problem(GeneticA genetic)
{
this.evaluatorEngine = null;
this.geneticEngine = genetic;
this.stopCondiction = null;
this.eventHandler = null;
}
public void Start()
{
statistic = new double[]{ double.MaxValue, double.MinValue, 0.0 };
geneticEngine.init();
epoch = 0;
}
private int currentGenome = 0;
public void StartEpoch()
{
geneticEngine.InitEvaluation(statistic);
currentGenome = 0;
}
public bool NextGenome(out Genome next)
{
if (currentGenome < geneticEngine.Population.Count) {
next = geneticEngine.Population.ElementAt(currentGenome++);
return true;
} else {
next = null;
return false;
}
}
public uint EndEpoch()
{
geneticEngine.EndEvaluation(statistic);
epoch++;
return geneticEngine.NextGeneration(statistic); //surviviors
}
public double[] Statistic
{
get
{
return statistic;
}
}
public void Run()
{
statistic = new double[] { double.MaxValue, double.MinValue, 0.0 };
geneticEngine.init();
epoch = 0;
while (true)
{
List<Genome> pop = geneticEngine.Population;
geneticEngine.InitEvaluation(statistic);
int n = pop.Count();
for (int j = 0; j < n; j++)
{
Genome gen = pop.ElementAt(j);
gen.Value = geneticEngine.EvaluateOne(gen, evaluatorEngine, statistic);
}
geneticEngine.EndEvaluation(statistic);
eventHandler.handleCurrentStatistic(n, epoch, statistic);
epoch++;
if (this.stopCondiction(this))
{
eventHandler.handleGaStopped(this, EventType.STOPPED_CONDICTION_SATISFIED);
break;
}
else
{
uint survivors = geneticEngine.NextGeneration(statistic);
if (survivors <= 0)
{
eventHandler.handleGaStopped(this, EventType.POPULATION_EXTINCTION);
break;
}
}
eventHandler.handleCurrentPopulation(epoch-1, this, this.geneticEngine);
}
eventHandler.handleEndPopulation(this, this.geneticEngine);
}
}
}
<file_sep>๏ปฟ/**
* This file contains basic implementation of genetic algorithm.
* For more informations, contact me: <EMAIL>
*/
using System;
namespace Multinet.Genetic
{
public class GenomeBuilderNotDefinedException : Exception {}
public class GenomeTranslatorNotDefinedException : Exception {}
public class IncompatibleGenomeException: Exception {}
public delegate void MutationMethod(Genome gen, double chance);
public delegate Genome CrossoverMethod(Genome g1, Genome g2);
public delegate Genome GenomeBuilderMethod();
public delegate Evaluable GenomeTranslatorMethod(Genome gen);
}
<file_sep>๏ปฟusing System;
using System.Collections;
using Multinet.Net;
using Multinet.Math;
using Multinet.Genetic;
using Multinet.Utils;
using Multinet.Net.Impl;
class OneNet : Net
{
public Neuron neuron;
public Synapse w = new Synapse();
override
public int Size
{
get
{
return 1;
}
}
override
public Neuron this[int id]
{
get
{
return neuron;
}
set
{
neuron = value;
}
}
override
public Synapse this[int i, int j]
{
get
{
return w;
}
}
override
public double GetDouble(string var)
{
throw new NotImplementedException();
}
override
public void SetDouble(string var, double v)
{
throw new NotImplementedException();
}
}
namespace Multinet.Test
{
class Test
{
public static void testBitArrayUtils()
{
BitArray array = BitArrayUtils.ToBitArray(1);
Console.WriteLine("LENGTH: {0}", array.Length);
Console.WriteLine("BITS: ");
Console.WriteLine(array.ToString());
for (int i = array.Length-1; i >= 0; i--)
{
Console.Write( (array.Get(i) ? "1": "0") );
}
Console.WriteLine();
array = BitArrayUtils.ToBitArray(uint.MaxValue);
Console.WriteLine("LENGTH: {0}", array.Length);
Console.WriteLine("BITS: ");
Console.WriteLine(array.ToString());
for (int i = array.Length - 1; i >= 0; i--)
{
Console.Write((array.Get(i) ? "1" : "0"));
}
Console.WriteLine();
double code = BitArrayUtils.ToNDouble(array);
System.Console.WriteLine("BITARRAY(uint32.MaxValue) = {0}", code);
}
public static void testRungeKutta4()
{
}
public static void testMutation()
{
Genome g1 = new Genome();
Chromossome ch1 = new Chromossome();
ch1.AddGene(0, BitArrayUtils.ToBitArray(0));
ch1.AddGene(1, BitArrayUtils.ToBitArray(1));
ch1.AddGene(2, BitArrayUtils.ToBitArray(2));
ch1.AddGene(3, BitArrayUtils.ToBitArray(3));
g1.AddChromossome(0, ch1);
MutationImpl.MutationMethod(g1, 1.0);
Chromossome ch = g1.GetChromossome(0);
for (int i = 0; i < ch.Size; i++)
{
BitArray g = ch.GetGene((uint)i);
System.Console.Write("{0} ", BitArrayUtils.ToUInt32(g));
}
System.Console.WriteLine();
}
public static void testCrossover()
{
Genome g1 = new Genome();
Genome g2 = new Genome();
Chromossome ch1 = new Chromossome();
ch1.AddGene(0, BitArrayUtils.ToBitArray(0));
ch1.AddGene(1, BitArrayUtils.ToBitArray(1));
ch1.AddGene(2, BitArrayUtils.ToBitArray(2));
ch1.AddGene(3, BitArrayUtils.ToBitArray(3));
Chromossome ch2 = new Chromossome();
ch2.AddGene(0, BitArrayUtils.ToBitArray(4));
ch2.AddGene(1, BitArrayUtils.ToBitArray(5));
ch2.AddGene(2, BitArrayUtils.ToBitArray(6));
ch2.AddGene(3, BitArrayUtils.ToBitArray(7));
g1.AddChromossome(0, ch1);
g2.AddChromossome(0, ch2);
Genome gen = CrossoverImpl.CrossoverMethod(g1, g2);
Chromossome ch = gen.GetChromossome(0);
for (int i = 0; i < ch.Size; i++)
{
BitArray g = ch.GetGene((uint)i);
System.Console.Write("{0} ", BitArrayUtils.ToUInt32(g));
}
System.Console.WriteLine();
}
public static void testBeer1995Neuron()
{
NeuralNet net = new NeuralNet();
int n1 = net.CreateNeuron();
int n2 = net.CreateNeuron();
int n3 = net.CreateNeuron();
int n4 = net.CreateNeuron();
int n5 = net.CreateNeuron();
Neuron ne1 = net[n1];
Neuron ne2 = net[n2];
Neuron ne3 = net[n3];
Neuron ne4 = net[n4];
Neuron ne5 = net[n5];
ne1.Implementation = new Beer1995Neuron();
ne2.Implementation = new Beer1995Neuron();
ne3.Implementation = new Beer1995Neuron();
ne4.Implementation = new Beer1995Neuron();
ne5.Implementation = new Beer1995Neuron();
net.CreateSynapse(n1, n3, 930);
net.CreateSynapse(n2, n3, 930);
net.CreateSynapse(n1, n4, 930);
net.CreateSynapse(n2, n4, 930);
net.CreateSynapse(n3, n5, 1.0);
net.CreateSynapse(n4, n5, 1.0);
ne1.Implementation["inputgain"] = 1000.0;
ne1.Implementation["outputgain"] = 1.0;
ne1.Implementation["inputweight"] = 0.0;
ne1.Implementation["sensorweight"] = 1.0;
ne1.TimeConst = 1.0;
ne2.Implementation["inputgain"] = 1000.0;
ne2.Implementation["outputgain"] = 1.0;
ne2.Implementation["inputweight"] = 0.0;
ne2.Implementation["sensorweight"] = 1.0;
ne2.TimeConst = 1.0;
ne3.Implementation["inputgain"] = 1.0;
ne3.Implementation["outputgain"] = 1.0;
ne3.Implementation["inputweight"] = -1.0;
ne3.Implementation["sensorweight"] = 0.0;
ne3.Implementation["bias"] = 100.0;
ne3.TimeConst = 1.0;
ne4.Implementation["inputgain"] = 1.0;
ne4.Implementation["outputgain"] = 1.0;
ne4.Implementation["inputweight"] = 1.0;
ne4.Implementation["sensorweight"] = 0.0;
ne4.Implementation["bias"] = 100.0;
ne4.TimeConst = 1.0;
ne5.Implementation["inputgain"] = 1.0;
ne5.Implementation["outputgain"] = 1.0;
ne5.Implementation["inputweight"] = 1.0;
ne5.Implementation["sensorweight"] = 0.0;
ne5.Implementation["bias"] = 0;
ne5.TimeConst = 1.0;
ne1.Implementation.SetInput(ne1, 0.0);
ne2.Implementation.SetInput(ne2, 0.0);
//Console.WriteLine(ne1.State);
net.Proccess();
//Console.WriteLine(ne1.State);
double v = ne3.GetOutput();
Console.WriteLine("OUTPUT = {0}", v);
}
public static void testHomeoestaticNet()
{
Neuron n = new Neuron(0);
n.TimeConst = 10;
n.Implementation["bias"] = 0;
n.Implementation["inputgain"] = 1.0;
n.Implementation["outputgain"] = 1.0;
n.Implementation["inputweight"] = 1.0;
n.Implementation["sensorweight"] = 1.0;
n.Implementation["weightgain"] = 20;
OneNet net = new OneNet();
net.neuron = n;
net[0, 0].Intensity = 0.2;
n.Network = net;
n.Incame.AddLast(new Cell(0, 0));
n.Outcame.AddLast(new Cell(0, 0));
n.ProccessInput(2.0);
bool stopped = false;
const double min = 0.4;
const double max = 0.5;
Console.WriteLine("********************************HELP**********************************");
Console.WriteLine("* This software lets you to control a single neuron!!!\t*");
Console.WriteLine("* Press C key to supply 2.0v to neuron input.\t*");
Console.WriteLine("* Press ESC to exit!\t*");
Console.WriteLine("* Press any other key to supply 0.0v to neuron input.\t*");
Console.WriteLine("* ---------------------------------------------------\t*");
Console.WriteLine("HUD shows: ");
Console.WriteLine("Plast({0}): where {0} is a plasticity level of neuron.");
Console.WriteLine("state({0}) : pot({1}) : w({2}), where: ");
Console.WriteLine("{0} is neuron state; {1} is neuron frequency potential; and {2} is a auto connection weight of the neuron.");
Console.WriteLine("* ---------------------------------------------------\t*");
while (!stopped)
{
double state = n.Proccess();
double pot = n.Implementation.GetPotential(n);
double p = 0.0;
if (pot < min)
{
p = 1 - pot / min;
}
else if (pot > max)
{
p = 1 - pot / max;
}
net.w.Intensity += 0.8 * p * (1 - pot);
Console.WriteLine("plast({0})", p);
Console.WriteLine("state({0}) : pot({1}) : w({2})", state, pot, net.w.Intensity);
Console.WriteLine("Press ESC to exit; C to supply 2.0v to neuron; or other key to supply 0.0v to neuron...");
ConsoleKeyInfo info = Console.ReadKey();
if (info.Key == ConsoleKey.Escape)
{
stopped = true;
}
else if (info.Key == ConsoleKey.C)
{
n.ProccessInput(2.0);
}
}
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using Multinet.Net;
using Multinet.Genetic;
using Multinet.Utils;
using Multinet.Net.Impl;
namespace Multinet.Sample
{
using rnd = Multinet.Math.PRNG;
public class PatternEvaluator : Evaluator
{
public bool logEnabled = false;
public bool LogEnabled
{
get
{
return this.logEnabled;
}
set
{
logEnabled = value;
}
}
public double evaluate(Evaluable obj)
{
double[][] inputs = new double[9][];
inputs[0] = new double[] { 0, 0, 0,
0, 0, 0,
0, 0, 0};
inputs[1] = new double[] { 1, 1, 1,
0, 0, 0,
0, 0, 0};
inputs[2] = new double[] { 1, 0, 0,
0, 1, 0,
0, 0, 1};
inputs[3] = new double[] { 0, 0, 0,
1, 1, 1,
0, 0, 0};
inputs[4] = new double[] { 0, 0, 0,
0, 0, 0,
1, 1, 1};
inputs[5] = new double[] { 0, 0, 1,
0, 1, 0,
1, 0, 0};
inputs[6] = new double[] { 1, 0, 0,
1, 0, 0,
1, 0, 0};
inputs[7] = new double[] { 0, 1, 0,
0, 1, 0,
0, 1, 0};
inputs[8] = new double[] { 0, 0, 1,
0, 0, 1,
0, 0, 1};
double[] outputs = { 0, 0, 0, 0, 1, 0, 0, 0, 0};
double error = 0;
NeuralNet net = (NeuralNet)obj;
for (uint i = 0; i < inputs.Length; i++)
{
double[] input = inputs[i];
for (uint k = 0; k < 9; k++)
{
net[0].ProccessInput(input[k]);
}
net.Proccess();
double y = net[net.Size-1].GetOutput();
double e = System.Math.Abs(y-outputs[i]);
error += e * e;
if (LogEnabled)
{
Console.WriteLine("{0}, {1}, {2} , {3}, {4}, {5}, {6}, {7}, {8}: {9}",
input[0], input[1], input[2], input[3], input[4], input[5], input[6],
input[7], input[8], y);
}
}
return 10.0 - error;
}
}
class MatrixPatternOfflineProblem
{
GeneticA genetic;
PatternEvaluator evaluator = new PatternEvaluator();
uint hiddenSize = 20;
uint inputSize = 9;
uint outputSize = 1;
private static bool stopCondiction(Problem problem){
return problem.Epoch >= 1000;
}
public MatrixPatternOfflineProblem()
{
genetic = new GeneticA(500);
genetic.Elitism = 1;
genetic.SurvivalRate = 0.1;
genetic.MutationRate = 0.0005;
genetic.MinPopulationSize = 500;
genetic.GenomeBuilder = () =>
{
Genome gen = new Genome();
Chromossome cr = new Chromossome();
uint numberOfGene = (inputSize+hiddenSize+outputSize) + hiddenSize * (inputSize + outputSize);
for (uint i = 0; i < numberOfGene; i++)
{
cr.AddGene(i, rnd.NextDouble());
}
Chromossome cr2 = new Chromossome();
uint numberOfGenes2 = hiddenSize * (inputSize + outputSize);
for (uint i = 0; i < numberOfGenes2; i++)
{
cr2.AddGene(i, rnd.NextDouble());
}
gen.AddChromossome(0, cr);
gen.AddChromossome(1, cr2);
return gen;
};
genetic.Translator = (Genome gen) =>
{
double wamp = 60;
double wshift = 30;
NeuralNet net = new NeuralNet();
Neuron[] ne = new Neuron[inputSize+hiddenSize+outputSize];
int[] neuronID = new int[ne.Length];
net.NumericalMethod = new Math.Impl.EulerMethod();
for (uint i = 0; i < neuronID.Length; i++)
{
neuronID[i] = net.CreateNeuron();
ne[i] = net[neuronID[i]];
ne[i].Implementation = new Beer1995Neuron();
}
Chromossome cr = gen.GetChromossome(0);
Chromossome cr2 = gen.GetChromossome(1);
uint idx = 0;
uint idxSyn = 0;
double zeroChance = 0.25;
for (int i = 0; i < inputSize; i++)
{
for (int j = 0; j < hiddenSize; j++)
{
Synapse syn = net.CreateSynapse(neuronID[i], neuronID[j], wamp * BitArrayUtils.ToNDouble(cr.GetGene(idx++)) - wshift);
double p = BitArrayUtils.ToNDouble(cr2.GetGene(idxSyn++));
if (p <= zeroChance)
{
syn.Intensity = 0.0;
}
}
}
for (int i = 0; i < hiddenSize; i++)
{
for (int j = 0; j < outputSize; j++)
{
Synapse syn = net.CreateSynapse(neuronID[inputSize + i], neuronID[ne.Length-1], wamp * BitArrayUtils.ToNDouble(cr.GetGene(idx++)) - wshift);
double p = BitArrayUtils.ToNDouble(cr2.GetGene(idxSyn++));
if (p <= zeroChance)
{
syn.Intensity = 0.0;
}
}
}
for (int i = 0; i < inputSize; i++)
{
ne[i].Implementation.UseNumericalMethod = false;
ne[i].Implementation["inputgain"] = 100 * BitArrayUtils.ToNDouble(cr.GetGene(idx++)) - 50;
ne[i].Implementation["outputgain"] = 1.0;
ne[i].Implementation["inputweight"] = 0.0;
ne[i].Implementation["sensorweight"] = 1.0;
ne[i].TimeConst = 1.0;
ne[i].Implementation["bias"] = 0.0;
}
for (int i = 0; i < hiddenSize; i++)
{
ne[9+i].Implementation["inputgain"] = 1.0;
ne[9+i].Implementation["outputgain"] = 1.0;
ne[9+i].Implementation["inputweight"] = 1.0;
ne[9+i].Implementation["sensorweight"] = 0.0;
ne[9+i].TimeConst = 4 * BitArrayUtils.ToNDouble(cr.GetGene(idx++)) + 0.001;
ne[9+i].Implementation["bias"] = 0.0;
}
int outidx = ne.Length - 1;
ne[outidx].Implementation = new AvgNeuron();
ne[outidx].Implementation["inputgain"] = 1.0;
ne[outidx].Implementation["outputgain"] = 2 * BitArrayUtils.ToNDouble(cr.GetGene(idx++));
ne[outidx].Implementation["inputweight"] = 1.0;
ne[outidx].Implementation["sensorweight"] = 0.0;
ne[outidx].TimeConst = 1.0;
ne[outidx].Implementation["bias"] = 0.0;
//net.NumericalMethod["step"] = 1.0 * BitArrayUtils.ToNDouble(cr.GetGene(7)) + 0.000001;
net.NumericalMethod["step"] = 0.5;
return net;
};
}
public void Run()
{
Problem problem = new Problem(genetic, evaluator, stopCondiction, new DebugProblemEventHandler());
problem.Run ();
int q = genetic.Population.Count;
if (q > 0)
{
genetic.Population.Sort();
Genome better = genetic.Population[q-1];
NeuralNet bnet = (NeuralNet)genetic.Translator(better);
Console.WriteLine("Synapses: ");
Console.WriteLine(bnet);
evaluator.LogEnabled = true;
Console.WriteLine("FITNESS: {0}", evaluator.evaluate(bnet));
}
}
}
}
<file_sep>๏ปฟusing System;
using Multinet.Net;
using System.Collections;
using Multinet;
using Multinet.Genetic;
using Multinet.Math;
using Multinet.Utils;
using Multinet.Net.Impl;
using System.Collections.Generic;
namespace Multinet.Net.Ext
{
public enum NeuronType {
INPUT,
HIDDEN,
OUTPUT
}
public delegate void CreateParametersHandler(HIRON3 net);
public delegate void ConfigureNeuronHandler(HIRON3 net, int id, NeuronType type);
public delegate void ConfigureSynapseHandler(HIRON3 net, Synapse syn, NeuronType fromType, NeuronType toType);
/// <summary>
/// HIRO3 is HIdden Recursive Operation is a network with three layers and recurive hidden layer.
/// In this network type, input and output layers are not recursive.
/// </summary>
public class HIRON3
{
private NeuralNet net;
private int[] input = null;
private int[] hidden = null;
private int[] output = null;
private int neurons = 0, synapses = 0;
private Genome genotype = null;
public HIRON3 (int inputSize, int hiddenSize, int outputSize, Genome genotype = null)
{
input = new int[inputSize];
output = new int[outputSize];
hidden = new int[hiddenSize];
neurons = inputSize + hiddenSize + outputSize;
synapses = hiddenSize * (inputSize + outputSize);
this.genotype = genotype;
chrNeuronIdx = 0;
chrSynIdx = 0;
}
private static uint chrNeuronIdx = 0;
public CreateParametersHandler createParametersHandler = (HIRON3 hiron) => {
//hiron.net.NumericalMethod = new Math.Impl.EulerMethod();
//hiron.net.NumericalMethod["step"] = 0.5;
};
public ConfigureNeuronHandler configureNeuronHandler = (HIRON3 hiron, int id, NeuronType type) => {
double gain;
Genome genotype = hiron.genotype;
Neuron ne = hiron.Net[id];
Chromossome chrGain = genotype.GetChromossome(0);
if (type == NeuronType.INPUT) {
if (genotype != null) {
gain = 100 * BitArrayUtils.ToNDouble(chrGain.GetGene(chrNeuronIdx)) - 50;
} else {
gain = 100 * Math.PRNG.NextDouble() - 50;
}
ne.Implementation = new Beer1995NeuronStateless();
ne.Implementation.UseNumericalMethod = false;
ne.Implementation["inputgain"] = gain;
ne.Implementation["outputgain"] = 1.0;
ne.Implementation["inputweight"] = 0.0;
ne.Implementation["sensorweight"] = 1.0;
ne.TimeConst = 1.0;
ne.Implementation["bias"] = 0.0;
}
if (type == NeuronType.HIDDEN) {
if (genotype != null) {
gain = 10 * BitArrayUtils.ToNDouble(chrGain.GetGene(chrNeuronIdx)) - 5;
} else {
gain = 10 * Math.PRNG.NextDouble() - 5;
}
ne.Implementation = new Beer1995NeuronStateless();
ne.Implementation.UseNumericalMethod = false;
ne.Implementation["inputgain"] = 1.0;
ne.Implementation["outputgain"] = 1.0;
ne.Implementation["inputweight"] = 1.0;
ne.Implementation["sensorweight"] = 0.0;
ne.TimeConst = 1.0;
ne.Implementation["bias"] = gain;
}
if (type == NeuronType.OUTPUT) {
if (genotype != null)
{
gain = 2 * BitArrayUtils.ToNDouble(chrGain.GetGene(chrNeuronIdx)) + 0.001;
}
else
{
gain = 2 * Math.PRNG.NextDouble() + 0.001;
}
ne.Implementation = new AvgNeuron();
ne.Implementation.UseNumericalMethod = false;
ne.Implementation["inputgain"] = 1.0;
ne.Implementation["outputgain"] = gain;
ne.Implementation["inputweight"] = 1.0;
ne.Implementation["sensorweight"] = 0.0;
ne.TimeConst = 1.0;
ne.Implementation["bias"] = 0.0;
}
chrNeuronIdx++;
if (chrNeuronIdx >= hiron.neurons) {
chrNeuronIdx = 0;
}
};
public Genome Genotype
{
get
{
return genotype;
}
}
private static uint chrSynIdx = 0;
public ConfigureSynapseHandler ConfigureSynapseHandler = (HIRON3 hiron, Synapse syn,
NeuronType fromType, NeuronType toType) => {
Chromossome chr = hiron.genotype.GetChromossome(1);
Chromossome chr2 = hiron.genotype.GetChromossome(2);
BitArray gene = chr.GetGene(chrSynIdx);
BitArray gene2 = chr2.GetGene(chrSynIdx++);
double chance = BitArrayUtils.ToNDouble(gene2);
if (chance >= 0.25)
{
syn.Intensity = 60 * BitArrayUtils.ToNDouble(gene) - 30;
} else
{
syn.Intensity = 0;
}
if (chrSynIdx >= hiron.synapses) {
chrSynIdx = 0;
}
};
public NeuralNet Net {
get {
return this.net;
}
}
public void CreateParameters()
{
net = new NeuralNet();
createParametersHandler(this);
}
public void CreateNeurons() {
for (int i = 0; i < input.Length; i++) {
input[i] = net.CreateNeuron();
this.configureNeuronHandler (this, input[i], NeuronType.INPUT);
}
for (int i = 0; i < hidden.Length; i++) {
hidden [i] = net.CreateNeuron ();
this.configureNeuronHandler (this, hidden [i], NeuronType.HIDDEN);
}
for (int i = 0; i < output.Length; i++) {
output [i] = net.CreateNeuron ();
this.configureNeuronHandler (this, output [i], NeuronType.OUTPUT);
}
}
public void CreateSynapses() {
for (int i = 0; i < input.Length; i++) {
for (int j = 0; j < hidden.Length; j++) {
Synapse syn = net.CreateSynapse (input[i], hidden[j], 0);
this.ConfigureSynapseHandler (this, syn, NeuronType.INPUT, NeuronType.HIDDEN);
}
}
for (int i = 0; i < hidden.Length; i++)
{
for (int j = 0; j < output.Length; j++)
{
Synapse syn = net.CreateSynapse(hidden[i], output[j], 0);
this.ConfigureSynapseHandler(this, syn, NeuronType.HIDDEN, NeuronType.OUTPUT);
}
}
}
public int CountNeurons
{
get
{
return neurons;
}
}
public int CountSynapses
{
get
{
return this.synapses;
}
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using Multinet.Net;
using Multinet.Genetic;
using Multinet.Utils;
using Multinet.Net.Impl;
namespace Multinet.Sample
{
using rnd = Multinet.Math.PRNG;
public class XOREvaluator : Evaluator
{
public bool logEnabled = false;
public bool LogEnabled
{
get
{
return this.logEnabled;
}
set
{
logEnabled = value;
}
}
public double evaluate(Evaluable obj)
{
double[][] inputs = new double[4][];
inputs[0] = new double[] { 0, 0 };
inputs[1] = new double[] { 1, 0 };
inputs[2] = new double[] { 0, 1 };
inputs[3] = new double[] { 1, 1 };
double[] outputs = { 0, 1, 1, 0 };
double error = 0;
NeuralNet net = (NeuralNet)obj;
for (uint i = 0; i < inputs.Length; i++)
{
double[] input = inputs[i];
net[0].ProccessInput(input[0]);
net[1].ProccessInput(input[1]);
net.Proccess();
double y = net[2].GetOutput();
double e = System.Math.Abs(y-outputs[i]);
error += e * e;
if (LogEnabled)
{
Console.WriteLine("{0}, {1} : {2}", input[0], input[1], y);
}
}
return 10.0 - error;
}
}
class XORProblem
{
GeneticA genetic;
XOREvaluator evaluator = new XOREvaluator();
private static bool stopCondiction(Problem problem){
//((XORProblem)problem)
if (problem.Epoch > 1000) {
return true;
}
return false;
}
public XORProblem()
{
genetic = new GeneticA(200);
genetic.Elitism = 2;
genetic.SurvivalRate = 0.5;
genetic.MutationRate = 0.0005;
genetic.MinPopulationSize = 200;
genetic.GenomeBuilder = () =>
{
Genome gen = new Genome();
Chromossome cr = new Chromossome();
cr.AddGene(0, rnd.NextDouble());
cr.AddGene(1, rnd.NextDouble());
cr.AddGene(2, rnd.NextDouble());
cr.AddGene(3, rnd.NextDouble());
cr.AddGene(4, rnd.NextDouble());
cr.AddGene(5, rnd.NextDouble());
cr.AddGene(6, rnd.NextDouble());
// cr.AddGene(7, rnd.NextDouble());
gen.AddChromossome(0, cr);
return gen;
};
genetic.Translator = (Genome gen) =>
{
NeuralNet net = new NeuralNet();
net.NumericalMethod = new Math.Impl.EulerMethod();
int n1 = net.CreateNeuron();
int n2 = net.CreateNeuron();
int n3 = net.CreateNeuron();
int n4 = net.CreateNeuron();
Neuron ne1 = net[n1];
Neuron ne2 = net[n2];
Neuron ne3 = net[n3];
Neuron ne4 = net[n4];
ne1.Implementation = new Beer1995Neuron();
ne2.Implementation = new Beer1995Neuron();
ne3.Implementation = new Beer1995Neuron();
ne4.Implementation = new Beer1995Neuron();
Chromossome cr = gen.GetChromossome(0);
net.CreateSynapse(n1, n3, 30 * BitArrayUtils.ToNDouble(cr.GetGene(0))-15);
net.CreateSynapse(n2, n3, 30 * BitArrayUtils.ToNDouble(cr.GetGene(1))-15);
net.CreateSynapse(n3, n4, 30 * BitArrayUtils.ToNDouble(cr.GetGene(2))-15);
ne1.Implementation.UseNumericalMethod = false;
ne1.Implementation["inputgain"] = 10 * BitArrayUtils.ToNDouble(cr.GetGene(3));
ne1.Implementation["outputgain"] = 1.0;
ne1.Implementation["inputweight"] = 0.0;
ne1.Implementation["sensorweight"] = 1.0;
ne1.TimeConst = 1.0;
ne1.Implementation["bias"] = 0.0;
ne2.Implementation.UseNumericalMethod = false;
ne2.Implementation["inputgain"] = 10 * BitArrayUtils.ToNDouble(cr.GetGene(4));
ne2.Implementation["outputgain"] = 1.0;
ne2.Implementation["inputweight"] = 0.0;
ne2.Implementation["sensorweight"] = 1.0;
ne2.TimeConst = 1.0;
ne2.Implementation["bias"] = 0.0;
ne3.Implementation["inputgain"] = 1.0;
ne3.Implementation["outputgain"] = 1.0;
ne3.Implementation["inputweight"] = 1.0;
ne3.Implementation["sensorweight"] = 0.0;
ne3.TimeConst = BitArrayUtils.ToNDouble(cr.GetGene(5)) + 0.001;
ne3.Implementation["bias"] = 0.0;
ne4.Implementation["inputgain"] = 1.0;
ne4.Implementation["outputgain"] = 2 * BitArrayUtils.ToNDouble(cr.GetGene(6));
ne4.Implementation["inputweight"] = 1.0;
ne4.Implementation["sensorweight"] = 0.0;
ne4.TimeConst = 1.0;
ne4.Implementation["bias"] = 0.0;
//net.NumericalMethod["step"] = 1.0 * BitArrayUtils.ToNDouble(cr.GetGene(7)) + 0.000001;
net.NumericalMethod["step"] = 0.5;
return net;
};
}
public void Run()
{
Problem problem = new Problem(genetic, evaluator, stopCondiction, new DebugProblemEventHandler());
problem.Run ();
int q = genetic.Population.Count;
if (q > 0)
{
genetic.Population.Sort();
Genome better = genetic.Population[q-1];
NeuralNet bnet = (NeuralNet)genetic.Translator(better);
Console.WriteLine("Synapses: ");
Console.WriteLine(bnet);
evaluator.LogEnabled = true;
Console.WriteLine("FITNESS: {0}", evaluator.evaluate(bnet));
}
}
}
}
<file_sep>๏ปฟusing System.Collections.Generic;
using System.Collections;
namespace Multinet.Genetic
{
public sealed class MutationImpl
{
public static void MutationMethod(Genome gen, double chance)
{
int c = 0;
int cm = 0;
ICollection<uint> ids = gen.GetKeys();
foreach (uint id in ids)
{
Chromossome chr = gen.GetChromossome(id);
ICollection<uint> genesKeys = chr.GetKeys();
foreach (uint gid in genesKeys)
{
BitArray gene = chr.GetGene(gid);
for (int i = 0; i < Chromossome.GENE_SIZE; i++)
{
double selected = Multinet.Math.PRNG.NextDouble();
if (selected <= chance)
{
gene.Set(i, !gene.Get(i));
}
}
}
}
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Collections;
using Multinet.Utils;
namespace Multinet.Genetic
{
public sealed class CrossoverImpl
{
public static int seed = -1;
public static int last_seed = -1;
public static Genome CrossoverMethod(Genome gen1, Genome gen2)
{
if (seed < 0)
{
seed = unchecked(DateTime.Now.Ticks.GetHashCode());
}
last_seed = seed;
Random rnd = new Random(seed);
Genome child = new Genome();
ICollection<uint> ids = gen1.GetKeys();
foreach (uint id in ids)
{
Chromossome chr1 = gen1.GetChromossome(id);
if (!gen2.Contains(id))
{
throw new IncompatibleGenomeException();
}
Chromossome chr2 = gen2.GetChromossome(id);
int m = System.Math.Min(chr1.Size, chr2.Size);
int m2 = System.Math.Max(chr1.Size, chr2.Size);
int point = (int)rnd.Next(m);
// Console.WriteLine("POINT: {0}", point);
Chromossome nchr = new Chromossome();
for (int i = 0; i < point; i++)
{
BitArray copy = BitArrayUtils.DeepClone(chr1.GetGene((uint)i));
nchr.AddGene((uint)i, copy);
}
for (int j = point; j < m2; j++)
{
BitArray copy = BitArrayUtils.DeepClone(chr2.GetGene((uint)j));
nchr.AddGene((uint)j, copy);
}
child.AddChromossome(id, nchr);
}
seed = -1;
return child;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace Multinet.Genetic
{
[Serializable]
public class Genome : Evaluable, IComparable
{
private Dictionary<uint, Chromossome> chromossomes;
private double score;
public Genome()
{
chromossomes = new Dictionary<uint, Chromossome>();
}
public double Value
{
get
{
return score;
}
set
{
score = value;
}
}
public ICollection<uint> GetKeys()
{
return chromossomes.Keys;
}
public void AddChromossome(uint id, Chromossome chr)
{
chromossomes.Add(id, chr);
}
public Chromossome DelChromossome(uint id)
{
Chromossome chr = chromossomes[id];
chromossomes.Remove(id);
return chr;
}
public bool Contains(uint id)
{
return chromossomes.ContainsKey(id);
}
public Chromossome GetChromossome(uint id)
{
return chromossomes[id];
}
public int Size()
{
return chromossomes.Count();
}
override
public string ToString()
{
string txt = "";
foreach (KeyValuePair<uint, Chromossome> chr in this.chromossomes)
{
txt += string.Format("{0}:{1}\n", chr.Key, chr.Value);
}
return txt;
}
public void Serialize(string path){
IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ();
System.IO.Stream stream = new System.IO.FileStream (path, System.IO.FileMode.Create,
System.IO.FileAccess.Write, System.IO.FileShare.None);
formatter.Serialize (stream, this);
stream.Close ();
}
public int CompareTo(object obj)
{
if (obj is Genome)
{
Genome g = (Genome)obj;
if (Value < g.Value)
{
return -1;
}
else if (Value > g.Value)
{
return 1;
}
else
{
return 0;
}
}
return -1;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Multinet.Utils
{
/// <summary>
/// This class contains a set of helper methods to array of bits manipulation.
/// </summary>
public sealed class BitArrayUtils
{
/// <summary>
/// This method get a real number in range [0.0, 1.0]. The real number
/// is stored in variable <code>value</code>. The variable <code>value</code> is
/// of type double, but it is assumed that the value stored in X is in the range [0,1].
/// The actual value provided is stored as an unsigned 32-bit integer.
/// </summary>
/// <param name="value">Normalized real value to be converted in a bit array.</param>
/// <returns>A 32-bit array that corresponds to the actual number in <code>value</code></returns>
public static BitArray ToBitArray(double value)
{
uint lvalue = (uint)(value * UInt32.MaxValue);
return ToBitArray(lvalue);
}
/// <summary>
/// This method get an unsigned int in range [0, MAX_VALUE]. The unsigned value
/// is stored in variable <code>value</code>. The variable <code>value</code> is
/// of type <code>uint</code>.
/// The actual value provided is stored as an unsigned 32-bit integer.
/// </summary>
/// <param name="value">Value to be stored.</param>
/// <returns>Array of bits that corresponds to value in variable <code>value</code>.</returns>
public static BitArray ToBitArray(uint value)
{
byte[] bytes = BitConverter.GetBytes(value);
return new BitArray(bytes);
}
/// <summary>
/// This method get an unsigned long in range [0, MAX_VALUE]. The unsigned value
/// is stored in variable <code>value</code>. The variable <code>value</code> is
/// of type <code>ulong</code>.
/// The actual value provided is stored as an unsigned 64-bit integer.
/// </summary>
/// <param name="value">Value to be stored.</param>
/// <returns>Array of bits that corresponds to value in variable <code>value</code>.</returns>
public static BitArray ToBitArray(ulong lvalue)
{
byte[] bytes = BitConverter.GetBytes(lvalue);
return new BitArray(bytes);
}
/// <summary>
/// Convert a bit array in a double value with 32 bits of precision.
/// </summary>
/// <param name="bitarray">Array of bits to be converted.</param>
/// <returns>Normalized real value found. Returned value is in range [0.0, 1.0].
/// Value 0.0 corresponds to unsigned integer value 0; value 1.0, corresponds
/// to unsigned value MAX_UINT_VALUE, MAX_UINT_VALUE is a maximum value of variable
/// of type uint.</returns>
public static double ToNDouble(BitArray bitarray)
{
double sum = 0.0;
for (int i = 0; i < bitarray.Length; i++)
{
int bit = (bitarray.Get(i) ? 1 : 0);
sum += System.Math.Pow(2, i) * bit;
}
return sum / UInt32.MaxValue;
}
public static uint ToUInt32(BitArray bitarray)
{
long sum = 0;
for (int i = 0; i < bitarray.Length; i++)
{
int bit = (bitarray.Get(i) ? 1 : 0);
sum += (long)System.Math.Pow(2, i) * bit;
}
return (uint)sum;
}
public static BitArray DeepClone(BitArray bitarray)
{
BitArray copy = new BitArray(bitarray.Length);
for (int i = 0; i < bitarray.Length; i++)
{
copy.Set(i, bitarray[i]);
}
return copy;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Multinet.Math;
namespace Multinet.Net.Impl
{
public class AvgNeuron : ANeuronImpl
{
public AvgNeuron()
{
this["outputgain"] = 1.0;
this["inputgain"] = 1.0;
this["inputweight"] = 1.0;
this["sensorweight"] = 1.0;
this["bias"] = 0.0;
SetFunction(new Multinet.Math.Sigmoid(), "neuronfunction");
}
public override double GetOutput(Neuron ne)
{
return (OutputAmp * GetPotential(ne) - OutputShift) * this["outputgain"];
}
public override double GetPotential(Neuron n)
{
return GetFunction("neuronfunction").Exec(n.State + this["bias"]);
}
public override double SetInput(Neuron ne, double inv)
{
ne.SensorValue = inv * this["inputgain"];
return ne.SensorValue;
}
public override double Step(Neuron target, Net net, double state)
{
NeuralNet nnet = (NeuralNet)net;
int nNeurons = net.Size;
double s = 0;
int count = 0;
double iw = this["inputweight"];
if (iw != 0)
{
foreach (Cell con in target.Incame)
{
Synapse syn = net[con.X, con.Y];
Neuron ne = net[syn.From];
double zi = ne.Implementation.GetPotential(ne);
double wij = syn.Intensity;
s += wij * zi; //inputs of neuron id == column id
count++;
}
}
double nstate = s / count;
if (nstate < -100)
{
nstate = -100;
}
else if (nstate > 100)
{
nstate = 100;
}
return nstate;
}
}
}
<file_sep>๏ปฟ/**
* This file contains basic implementation of neuralnet.
* For more informations, contact me: <EMAIL>.
*/
using System.Collections.Generic;
using Multinet.Math;
using Multinet.Genetic;
using System;
namespace Multinet.Net
{
public class NeuralNet : Net, Evaluable
{
private int size;
private Dictionary<int, Neuron> neurons;
private Dictionary<Cell, Synapse> synapses;
private double restInput = 0.0;
private Dictionary<string, double> vars;
private double value = 0.0;
private int nextID = 0;
public NeuralNet()
{
neurons = new Dictionary<int, Neuron>();
vars = new Dictionary<string, double>();
synapses = new Dictionary<Cell, Synapse>();
}
public double Value
{
get
{
return value;
}
set
{
this.value = value;
}
}
public Synapse CreateSynapse(int from, int to, double intensity)
{
if (neurons.ContainsKey(from) && neurons.ContainsKey(to))
{
Cell pos = new Cell(from, to);
Neuron ni = neurons[from];
Neuron nj = neurons[to];
ni.Outcame.AddLast(pos);
nj.Incame.AddLast(pos);
Synapse syn = new Synapse();
syn.From = from;
syn.To = to;
syn.Intensity = intensity;
synapses.Add(pos, syn);
return syn;
} else
{
return null;
}
}
public bool RemoveSynapse(Cell pos)
{
//TODO implements this method
return false;
}
public int CreateNeuron()
{
Neuron ne = new Neuron(nextID);
neurons[ne.ID] = ne;
ne.Network = this;
size++;
nextID++;
return ne.ID;
}
public bool RemoveNeuron(int id)
{
if (neurons.Remove(id))
{
size--;
//TODO clean unused synapses
return true;
}
return false;
}
public double RestInput
{
get
{
return restInput;
}
set
{
restInput = value;
}
}
override
public double GetDouble(string var)
{
return vars[var];
}
override
public void SetDouble(string var, double value)
{
vars[var] = value;
}
override
public int Size
{
get
{
return size;
}
}
override
public string ToString()
{
string txt="";
foreach (KeyValuePair<Cell, Synapse> pair in synapses)
{
txt += string.Format("({0}, {1}) => {2}\n", pair.Key.X, pair.Key.Y, pair.Value.Intensity);
}
return txt;
}
override
public Neuron this[int id]
{
get
{
return neurons[id];
}
set
{
neurons[id] = value;
}
}
public void Proccess()
{
foreach (KeyValuePair<int, Neuron> pair in neurons)
{
int id = pair.Key;
Neuron ne = pair.Value;
ne.Proccess();
}
}
override
public Synapse this[int x, int y]
{
get
{
Cell pos = new Cell(x, y);
if (synapses.ContainsKey(pos))
{
return synapses[pos];
} else
{
return null;
}
}
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Multinet.Math.Impl
{
public class EulerMethod : INumericalMethod
{
private Dictionary<string, double> vars;
public EulerMethod()
{
vars = new Dictionary<string, double>();
vars["step"] = 0.1;
}
public double this[string var]
{
get
{
return vars[var];
}
set
{
vars[var] = value;
}
}
public double nextState(double runDuration, double currentState, TargetFunction machine)
{
double h = this["step"];
currentState = currentState + h * machine(currentState);
return currentState;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Multinet.Math
{
public class Matrix
{
private Dictionary<Cell, double> weight;
private int size;
public Matrix(int s)
{
this.size = s;
this.weight = new Dictionary<Cell, double>();
}
public int Size
{
get
{
return size;
}
set
{
size = value;
}
}
public double this[int x, int y]
{
get
{
Cell pos = new Cell(x, y);
if (this.weight.ContainsKey(pos))
{
return this.weight[pos];
}
else
{
return 0;
}
}
set
{
this.weight.Add(new Cell(x, y), value);
}
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Multinet.Math;
namespace Multinet.Net
{
public abstract class ANeuronImpl : INeuronImpl
{
private Dictionary<string, double> doubleVars;
private Dictionary<String, Function> functions;
private bool useNumericalMethod;
private double outputShift, outputAmp;
public ANeuronImpl()
{
useNumericalMethod = true;
doubleVars = new Dictionary<string, double>();
functions = new Dictionary<string, Function>();
outputShift = 0.0;
outputAmp = 1.0;
}
public double OutputShift {
get {
return outputShift;
}
set {
outputShift = value;
}
}
public double OutputAmp {
get {
return outputAmp;
}
set {
outputAmp = value;
}
}
public bool UseNumericalMethod
{
get
{
return this.useNumericalMethod;
}
set
{
this.useNumericalMethod = value;
}
}
public double this[string var]
{
get
{
return doubleVars[var];
}
set
{
doubleVars[var] = value;
}
}
public Function GetFunction(string funcname)
{
return functions[funcname];
}
public void SetFunction(Function f, string funcname)
{
functions[funcname] = f;
}
public abstract double GetOutput(Neuron ne);
public abstract double GetPotential(Neuron n);
public abstract double SetInput(Neuron ne, double inv);
public abstract double Step(Neuron target, Net net, double state);
}
}
<file_sep>๏ปฟusing Multinet.Math;
using Multinet.Math.Impl;
namespace Multinet.Net
{
public abstract class Net
{
private INumericalMethod method;
public Net()
{
method = new EulerMethod();
}
public INumericalMethod NumericalMethod
{
get
{
return method;
}
set
{
method = value;
}
}
public abstract Synapse this[int i, int j]
{
get;
}
public abstract int Size
{
get;
}
public abstract double GetDouble(string var);
public abstract void SetDouble(string var, double v);
public abstract Neuron this[int idx]
{
get;
set;
}
}
}<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Multinet.Math
{
public interface Function
{
double Exec(double v);
double Min();
double Max();
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Multinet.Math
{
public class Cell
{
int x;
int y;
public Cell(int x, int y)
{
this.x = x;
this.y = y;
}
public int X
{
get
{
return x;
}
}
public int Y
{
get
{
return y;
}
}
public override bool Equals(object obj)
{
if (obj != null)
{
if (obj is Cell)
{
return ((obj as Cell).x == x && (obj as Cell).y == y);
}
}
return false;
}
public override int GetHashCode()
{
int hash = 7;
hash = 97 * hash + this.x;
hash = 97 * hash + this.y;
return hash;
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Multinet.Net
{
public class Synapse
{
private double intensity;
private int from, to;
public Synapse(int from = 0, int to = 0)
{
this.from = from;
this.to = to;
}
public double Intensity
{
get
{
return intensity;
}
set
{
intensity = value;
}
}
public int From
{
get
{
return from;
}
set
{
from = value;
}
}
public int To
{
get
{
return to;
}
set
{
to = value;
}
}
}
}
<file_sep>Introduction
============
**MultinetSharp** is an implementation of an experiment based on artificial neural networks.
Samples
========
**BallBalance** is a demonstration of the use of MultinetSharp. A controller is trained to control a bar that keeps a ball in the air.
<file_sep>๏ปฟusing System.Collections.Generic;
namespace Multinet.Math
{
public delegate double TargetFunction(double state);
public sealed class Utils
{
private Utils() { }
public static float[] softmax(float[] output)
{
float[] sm = new float[output.Length];
double sum = 0.0f;
for (int i = 0; i < output.Length; i++)
{
sum += System.Math.Exp(output[i]);
}
for (int i = 0; i < output.Length; i++)
{
sm[i] = (float)(System.Math.Exp(output[i]) / sum);
}
return sm;
}
}
public sealed class PRNG {
private PRNG() {}
private static RNGMersenneTwister rnd = new RNGMersenneTwister();
public static void SetSeed(long seed) {
rnd = new RNGMersenneTwister ((int)seed);
}
public static double NextDouble() {
return rnd.NextDoublePositive();
}
}
public class RNGMersenneTwister
{
// Class MersenneTwister generates random numbers
// from a uniform distribution using the Mersenne
// Twister algorithm.
private const int N = 624;
private const int M = 397;
private const uint MATRIX_A = 0x9908b0dfU;
private const uint UPPER_MASK = 0x80000000U;
private const uint LOWER_MASK = 0x7fffffffU;
private const int MAX_RAND_INT = 0x7fffffff;
private uint[] mag01 = { 0x0U, MATRIX_A };
private uint[] mt = new uint[N];
private int mti = N + 1;
public RNGMersenneTwister()
{ init_genrand((uint)System.DateTime.Now.Millisecond); }
public RNGMersenneTwister(int seed)
{ init_genrand((uint)seed); }
public RNGMersenneTwister(int[] init)
{
uint[] initArray = new uint[init.Length];
for (int i = 0; i < init.Length; ++i)
initArray[i] = (uint)init[i];
init_by_array(initArray, (uint)initArray.Length);
}
public static int MaxRandomInt
{ get { return 0x7fffffff; } }
public int Next()
{ return genrand_int31(); }
public int Next(int maxValue)
{ return Next(0, maxValue); }
public int Next(int minValue, int maxValue)
{
if (minValue > maxValue)
{
int tmp = maxValue;
maxValue = minValue;
minValue = tmp;
}
return (int)(System.Math.Floor((maxValue - minValue + 1) * genrand_real1() + minValue));
}
public float NextFloat()
{ return (float)genrand_real2(); }
public float NextFloat(bool includeOne)
{
if (includeOne)
{
return (float)genrand_real1();
}
return (float)genrand_real2();
}
public float NextFloatPositive()
{ return (float)genrand_real3(); }
public double NextDouble()
{ return genrand_real2(); }
public double NextDouble(bool includeOne)
{
if (includeOne)
{
return genrand_real1();
}
return genrand_real2();
}
public double NextDoublePositive()
{ return genrand_real3(); }
public double Next53BitRes()
{ return genrand_res53(); }
public void Initialize()
{ init_genrand((uint)System.DateTime.Now.Millisecond); }
public void Initialize(int seed)
{ init_genrand((uint)seed); }
public void Initialize(int[] init)
{
uint[] initArray = new uint[init.Length];
for (int i = 0; i < init.Length; ++i)
initArray[i] = (uint)init[i];
init_by_array(initArray, (uint)initArray.Length);
}
private void init_genrand(uint s)
{
mt[0] = s & 0xffffffffU;
for (mti = 1; mti < N; mti++)
{
mt[mti] =
(uint)(1812433253U * (mt[mti - 1] ^ (mt[mti - 1] >> 30)) + mti);
mt[mti] &= 0xffffffffU;
}
}
private void init_by_array(uint[] init_key, uint key_length)
{
int i, j, k;
init_genrand(19650218U);
i = 1; j = 0;
k = (int)(N > key_length ? N : key_length);
for (; k > 0; k--)
{
mt[i] = (uint)((uint)(mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1664525U)) + init_key[j] + j);
mt[i] &= 0xffffffffU;
i++; j++;
if (i >= N) { mt[0] = mt[N - 1]; i = 1; }
if (j >= key_length) j = 0;
}
for (k = N - 1; k > 0; k--)
{
mt[i] = (uint)((uint)(mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1566083941U)) - i);
mt[i] &= 0xffffffffU;
i++;
if (i >= N) { mt[0] = mt[N - 1]; i = 1; }
}
mt[0] = 0x80000000U;
}
uint genrand_int32()
{
uint y;
if (mti >= N)
{
int kk;
if (mti == N + 1)
init_genrand(5489U);
for (kk = 0; kk < N - M; kk++)
{
y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
mt[kk] = mt[kk + M] ^ (y >> 1) ^ mag01[y & 0x1U];
}
for (; kk < N - 1; kk++)
{
y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
mt[kk] = mt[kk + (M - N)] ^ (y >> 1) ^ mag01[y & 0x1U];
}
y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
mt[N - 1] = mt[M - 1] ^ (y >> 1) ^ mag01[y & 0x1U];
mti = 0;
}
y = mt[mti++];
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680U;
y ^= (y << 15) & 0xefc60000U;
y ^= (y >> 18);
return y;
}
private int genrand_int31()
{ return (int)(genrand_int32() >> 1); }
double genrand_real1()
{ return genrand_int32() * (1.0 / 4294967295.0); }
double genrand_real2()
{ return genrand_int32() * (1.0 / 4294967296.0); }
double genrand_real3()
{ return (((double)genrand_int32()) + 0.5) * (1.0 / 4294967296.0); }
double genrand_res53()
{
uint a = genrand_int32() >> 5, b = genrand_int32() >> 6;
return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using Multinet.Math;
namespace Multinet.Net.Impl
{
/// <summary>
/// Default neuron implementation.
/// This neuron implementation added homeostatic behavior to indivudual neuron.
/// For more informations, see documentation in INeuronImpl interface.
/// </summary>
public class HNeuron : ANeuronImpl
{
public HNeuron()
{
this["bias"] = 0.0;
this["inputgain"] = 1.0;
this["outputgain"] = 1.0;
this["inputweight"] = 1.0;
this["sensorweight"] = 1.0;
this["weightgain"] = 1.0;
this["stateshift"] = -5.0;
SetFunction(new Multinet.Math.Sigmoid(), "neuronfunction");
SetFunction(new Multinet.Math.Sin(), "weightfunction");
}
override
public double SetInput(Neuron ne, double inv)
{
ne.SensorValue = inv * this["inputgain"];
return ne.SensorValue;
}
override
public double GetPotential(Neuron n)
{
return GetFunction("neuronfunction").Exec(n.State + this["bias"]);
}
override
public double GetOutput(Neuron ne)
{
return GetPotential(ne) * this["outputgain"];
}
override
public double Step(Neuron target, Net net, double state)
{
int nNeurons = net.Size;
double s = 0;
foreach (Cell con in target.Incame)
{
Synapse syn = net[con.X, con.Y];
Neuron ne = net[syn.From];
double zi = ne.Implementation.GetPotential(ne);
double wij = syn.Intensity;
s += this["weightgain"] * GetFunction("weightfunction").Exec(wij) * zi; //inputs of neuron id == column id
}
double sensorValue = target.SensorValue;
target.SensorValue = 0;
double iw = this["inputweight"];
double sw = this["sensorweight"];
return (-(state - this["stateshift"]) + (s * iw + sensorValue * sw)) / target.TimeConst;
}
}
}
| a5015b524ca4660b1dad7cc88102585c77a28331 | [
"Markdown",
"C#"
] | 34 | C# | joaoCS/MultinetSharp | 5e160a45d76f3d1a78dea66c70078f854cbb60ec | e8f65dd51cd780312a3cd7f54da45df8e88c5c27 |
refs/heads/master | <repo_name>Jack-Madden/SEWT-Project<file_sep>/src/main/java/RegisterGUI.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RegisterGUI {
public JFrame getFrame() {
return frame;
}
public JFrame frame;
public JTextField addName;
public JTextField addSurname;
public JTextField addAddr1;
public JTextField addAddr2;
public JTextField addEirCode;
public JTextField addCity;
public JTextField addPhone;
public JTextField addPassword;
public JButton registerBttn;
DatabaseHandler databaseHandler = new DatabaseHandler();
public RegisterGUI(){
initialise();
} // Calculator()
public void initialise()
{
// Create frame
frame = new JFrame();
frame.setVisible(true);
frame.setTitle("Log In");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addName = new JTextField("Name", 50);
frame.getContentPane().add(addName, BorderLayout.NORTH);
addSurname = new JTextField("Surname", 50);
frame.getContentPane().add(addSurname, BorderLayout.NORTH);
addAddr1 = new JTextField("Addr1", 50);
frame.getContentPane().add(addAddr1, BorderLayout.NORTH);
addAddr2 = new JTextField("Addr2", 50);
frame.getContentPane().add(addAddr2, BorderLayout.NORTH);
addEirCode = new JTextField("eirCode", 50);
frame.getContentPane().add(addEirCode, BorderLayout.NORTH);
addCity = new JTextField("city", 50);
frame.getContentPane().add(addCity, BorderLayout.NORTH);
addPhone = new JTextField("phone", 50);
frame.getContentPane().add(addPhone, BorderLayout.NORTH);
addPassword = new JTextField("password", 50);
frame.getContentPane().add(addPassword, BorderLayout.NORTH);
registerBttn = new JButton("Log In");
registerBttn.setSize(50,50);
frame.getContentPane().add(registerBttn, BorderLayout.NORTH);
registerBttn.addActionListener(this.databaseHandler.createUser);
}
}
<file_sep>/SEWT-Project - Ver3/src/main/java/RegisterGUI.java
// Java program to implement
// a Simple Registration Form
// using Java Swing
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class RegisterGUI extends JFrame implements ActionListener {
// Components of the Form
private Container c;
private JLabel lableFirst;
private JTextPane tbFirstName;
private JLabel lableLast;
private JTextPane tbLastName;
private JLabel lableAddr1;
private JTextPane tbAddr1;
private JLabel lableAddr2;
private JTextPane tbAddr2;
private JButton sButten;
private JTextPane tbEIRCODE;
private JLabel lableNumber;
private JLabel lableEircode;
private JLabel lableCity;
private JTextPane tbCity;
private JLabel labelpassword;
private JTextPane tbpasword;
private JTextPane number;
private JButton vButten;
private JLabel res;
private JTextPane feedBack;
private JTextPane tbDataFirstname;
private JTextPane tbDataLastNAme;
private JTextPane tbDataAddr1;
private JTextPane tbDataAddr2;
private JTextPane tbDataEircode;
private JTextPane tbDataNumber;
private JTextPane tbDataCity;
// strings to hold the data in the select boxes
private String dates[]
= { "1", "2", "3", "4", "5",
"6", "7", "8", "9", "10",
"11", "12", "13", "14", "15",
"16", "17", "18", "19", "20",
"21", "22", "23", "24", "25",
"26", "27", "28", "29", "30",
"31" };
private String months[]
= { "Jan", "feb", "Mar", "Apr",
"May", "Jun", "July", "Aug",
"Sup", "Oct", "Nov", "Dec" };
private String years[]
= { "1995", "1996", "1997", "1998",
"1999", "2000", "2001", "2002",
"2003", "2004", "2005", "2006",
"2007", "2008", "2009", "2010",
"2011", "2012", "2013", "2014",
"2015", "2016", "2017", "2018",
"2019" };
public RegisterGUI()
{
JFrame frame = new JFrame();
frame.setTitle("ExamGui");
frame.setLocationRelativeTo(null);
frame.setSize(600,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8,3,5,10));
lableFirst = new JLabel();
lableFirst.setText("First Name");
tbFirstName = new JTextPane();
//tbFirstName.setText("");
tbDataFirstname = new JTextPane();
lableLast = new JLabel();
lableLast.setText("Last Name");
tbLastName = new JTextPane();
//tbLastName.setText("");
tbDataLastNAme = new JTextPane();
lableAddr1 = new JLabel();
lableAddr1.setText("Address 1");
tbAddr1 = new JTextPane();
tbAddr1.setText("");
tbDataAddr1 = new JTextPane();
lableAddr2 = new JLabel();
lableAddr2.setText("Address 2");
tbAddr2 = new JTextPane();
tbAddr2.setText("");
tbDataAddr2 = new JTextPane();
tbDataAddr2 = new JTextPane();
lableEircode = new JLabel();
lableEircode.setText("EIRCODE");
tbEIRCODE = new JTextPane();
tbEIRCODE.setText("");
tbDataEircode = new JTextPane();
lableNumber = new JLabel();
lableNumber.setText("Number");
number = new JTextPane();
number.setText("");
tbDataNumber = new JTextPane();
labelpassword = new JLabel();
labelpassword.setText("<PASSWORD>");
tbpasword = new JTextPane();
tbpasword.setText("");
tbpasword = new JTextPane();
lableCity = new JLabel();
lableCity.setText("City");
tbCity = new JTextPane();
tbCity.setText("");
tbDataCity = new JTextPane();
sButten = new JButton();
sButten.setText("Submit");
vButten = new JButton();
vButten.setText("Verify");
vButten.setVisible(false);
feedBack = new JTextPane();
feedBack.setEditable(false);
panel.add(lableFirst);
panel.add(tbFirstName);
panel.add(tbDataFirstname);
panel.add(lableLast);
panel.add(tbLastName);
panel.add(tbDataLastNAme);
panel.add(lableAddr1);
panel.add(tbAddr1);
panel.add(tbDataAddr1);
panel.add(lableAddr2);
panel.add(tbAddr2);
panel.add(tbDataAddr2);
panel.add(lableCity);
panel.add(tbCity);
panel.add(tbDataCity);
panel.add(lableEircode);
panel.add(tbEIRCODE);
panel.add(tbDataEircode);
panel.add(lableNumber);
panel.add(number);
panel.add(tbDataNumber);
//panel.add(labelpassword);
//panel.add(tbpasword);
panel.add(sButten);
panel.add(vButten);
panel.add(feedBack);
frame.getContentPane().add(panel);
frame.setVisible(true);
frame.setVisible(true);
sButten.addActionListener(this);
}
// method actionPerformed()
// to get the action performed
// by the user and act accordingly
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == sButten) {
System.out.println("Getting here");
String data = "Name = " + tbFirstName.getText();
String data1 = "Last Name = " + tbLastName.getText();
String data2 = "Address 1 = " + tbAddr1.getText();
String data3 = "Address 2 = " + tbAddr2.getText();
String data4 = "City = " + tbCity.getText();
String data5 = "Eirecode = " + tbEIRCODE.getText();
String data6 = "Number = " + number.getText();
String data7 = "Password = " + tbpasword.getText();
tbDataFirstname.setText(data );
tbDataFirstname.setEditable(false);
tbDataLastNAme.setText(data1 );
tbDataLastNAme.setEditable(false);
tbDataAddr1.setText(data2 );
tbDataAddr1.setEditable(false);
tbDataAddr2.setText(data3 );
tbDataAddr2.setEditable(false);
tbDataCity.setText(data4 );
tbDataCity.setEditable(false);
tbDataEircode.setText(data5 );
tbDataEircode.setEditable(false);
tbDataNumber.setText(data6 );
tbDataNumber.setEditable(false);
tbpasword.setText(data7 );
tbpasword.setEditable(false);
feedBack.setText("Registration Successfully..");
}
}
}
<file_sep>/SEWT-Project - Ver3/src/main/java/expenseLog.java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class expenseLog implements Runnable {
public JPanel expenseLog() {
try {
// Stores the separate lines in a List then to a 2d List
Scanner in = new Scanner(new File("Transactions.txt"));
List<String[]> lines = new ArrayList<>();
while(in.hasNextLine()) {
String line = in.nextLine().trim();
String[] splitted = line.split(", ");
lines.add(splitted);
}
// Convert List<String[]> to String[][]
String[][] result = new String[lines.size()][];
for(int i = 0; i<result.length; i++) {
result[i] = lines.get(i);
}
// Call balance
getBalance(result);
System.out.println("Transactions \n"+ Arrays.deepToString(result));
// 2d table model
DefaultTableModel tableModel = new DefaultTableModel(new Object[][] {
}, // Column names
new Object[] { "Description", "Amount" }
);
// Populate table
for(int i=0;i<result.length;i++){
String[] row = new String[result[i].length];
for(int j=0;j<result[i].length;j++){
row[j] = result[i][j];
}
tableModel.addRow(row);
}
// Add model to table
JTable table = new JTable(tableModel);
Font font = new Font("Verdana", Font.PLAIN, 12);
table.setFont(font);
table.setRowHeight(15);
JPanel panel = new JPanel();
panel.setSize(600, 900);
panel.add(new JScrollPane(table));
panel.setVisible(true);
// Get balance
float balance = getBalance(result);
// Remove extra decimals and cast to String
DecimalFormat df = new DecimalFormat("0.00");
String balString = df.format(balance);
// Add balance to table
tableModel.addRow(new Object[]{"", ""});
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
tableModel.addRow(new Object[]{"Balance", balString});
}
});
panel.updateUI();
// Create frame
JFrame frame = new JFrame();
frame.setSize(600, 400);
frame.add(panel);
frame.setVisible(true);
frame.dispose();
return panel;
} catch (FileNotFoundException ex) {
ex.printStackTrace();
System.out.println("File not found");
}
return null;
} // expenseLog()
public float getBalance(String [][] result){
float balance = 0;
// Check if the amount should be added or subtracted from balance
for(int i =0;i<result.length;i++){
if(result[i][1].contains("+")){
String positive = "";
positive = result[i][1];
String posAmount = positive.substring(1);
float f = Float.parseFloat(posAmount);
balance += f;
}
else if(result[i][1].contains("-")){
String negative = "";
negative = result[i][1];
String negAmount = negative.substring(1);
float f = Float.parseFloat(negAmount);
balance -= f;
}
}
System.out.printf("Balance is %.2f \n", balance);
return balance;
} // getBalance()
@Override
public void run() {
expenseLog();
}
}
<file_sep>/SEWT-Project - Ver3/src/main/java/Main.java
import javax.swing.*;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws Exception {
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (Exception e) {
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//ApplicationGUI application = new ApplicationGUI();
//application.initialise();
try {
LoginGUI login = new LoginGUI();
// login.initialise();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
<file_sep>/SEWT-Project - Ver3/src/main/java/ApplicationGUI.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ApplicationGUI extends expenseLog{
// Create Frame
public JFrame frame;
public JFrame getFrame() {
return frame;
}
// Classes
addTransaction addTransaction = new addTransaction();
expenseLog expenseLog = new expenseLog();
public ApplicationGUI(){
initialise();
} // ApplicationGUI()
public void initialise(){
// Create frame
frame = new JFrame();
frame.setVisible(true);
frame.setTitle("Expense Report");
//frame.setSize(700, 900);
frame.setSize(expenseLog().getSize());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Transaction Button
JButton transactionBttn = new JButton("Add Transaction");
frame.getContentPane().add(transactionBttn, BorderLayout.SOUTH);
transactionBttn.setSize(50,50);
transactionBttn.setLocation(80,30);
transactionBttn.addActionListener(this.addTransaction);
displayTrans();
} // initialise()
public void displayTrans(){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.add(expenseLog());
}
});
// frame.add(expenseLog());
}
} // ApplicationGUI class
| c92843cd763229c8eaac1073ac05ed5e232c33af | [
"Java"
] | 5 | Java | Jack-Madden/SEWT-Project | 0ac2991650604a1dd6ec3d811f9a32933679d956 | 89d740eccf8f9b519b99c9fe6a561d7df4c3acf8 |
refs/heads/master | <file_sep>package main
import (
"fmt"
"os"
)
const (
ExitCodeOK int = iota
ExitCodeError
)
func main() {
os.Exit(run(os.Args))
}
func run(args []string) int {
client, err := NewClient()
if err != nil {
fmt.Println(err)
return ExitCodeError
}
calendar, err := NewCalendar(client)
if err != nil {
fmt.Println(err)
return ExitCodeError
}
err = calendar.FetchEvents()
if err != nil {
fmt.Println(err)
return ExitCodeError
}
if len(calendar.EventList) > 0 {
for _, e := range calendar.EventList {
fmt.Println(e)
}
} else {
fmt.Println("No events found.")
}
return ExitCodeOK
}
<file_sep>package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"runtime"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/calendar/v3"
)
func NewClient() (*http.Client, error) {
json, err := ioutil.ReadFile(filepath.Join(baseDir(), "client_secret.json"))
if err != nil {
return nil, err
}
config, err := google.ConfigFromJSON(json, calendar.CalendarReadonlyScope)
if err != nil {
return nil, err
}
token, err := restoreToken()
if err != nil {
token, err = requestToken(config)
if err != nil {
return nil, err
}
err = saveToken(token)
if err != nil {
return nil, err
}
}
return config.Client(context.Background(), token), nil
}
func restoreToken() (*oauth2.Token, error) {
file, err := os.Open(filepath.Join(baseDir(), "token.json"))
if err != nil {
return nil, err
}
token := &oauth2.Token{}
err = json.NewDecoder(file).Decode(token)
defer file.Close()
return token, err
}
func requestToken(config *oauth2.Config) (*oauth2.Token, error) {
url := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf(`1. Go to the following link in your browser:
%v
2. Type the authorization code: `, url)
var code string
if _, err := fmt.Scan(&code); err != nil {
return nil, err
}
token, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
return nil, err
}
return token, nil
}
func saveToken(token *oauth2.Token) error {
file, err := os.OpenFile(filepath.Join(baseDir(), "token.json"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer file.Close()
json.NewEncoder(file).Encode(token)
return nil
}
func baseDir() string {
var dir string
switch runtime.GOOS {
case "windows":
dir = os.Getenv("APPDATA")
default:
dir = os.Getenv("HOME")
}
return filepath.Join(dir, ".gooce")
}
<file_sep>package main
import (
"net/http"
"time"
"google.golang.org/api/calendar/v3"
)
type Calendar struct {
EventList []*Event
service *calendar.Service
}
func NewCalendar(client *http.Client) (*Calendar, error) {
service, err := calendar.New(client)
if err != nil {
return nil, err
}
return &Calendar{service: service}, nil
}
func (calendar *Calendar) FetchEvents() error {
t := time.Now().Format(time.RFC3339)
evts, err := calendar.service.Events.List("primary").ShowDeleted(false).SingleEvents(true).TimeMin(t).MaxResults(10).OrderBy("StartTime").Do()
if err != nil {
return err
}
for _, item := range evts.Items {
calendar.EventList = append(calendar.EventList, NewEvent(item))
}
return nil
}
<file_sep>package main
import (
"fmt"
"google.golang.org/api/calendar/v3"
)
type Event struct {
summary string
date string
dateTime string
}
func NewEvent(event *calendar.Event) *Event {
return &Event{
summary: event.Summary,
date: event.Start.Date,
dateTime: event.Start.DateTime,
}
}
func (event *Event) String() string {
var date string
if event.dateTime != "" {
date = event.dateTime
} else {
date = event.date
}
return fmt.Sprintf("%s (%s)", event.summary, date)
}
<file_sep># gooce
[](https://opensource.org/licenses/MIT)
gooce is a CLI which exports Google Calendar events to text written in Go.
This is useful for pasting events to any text field.
## Usage
```
$ gooce
```
## Installation
At first, to use gooce you should create a new credential on https://console.cloud.google.com/apis/credentials and save the credential file as `~/.gooce/client_secret.json`.
Then you can install gooce by the following command:
```
$ go get github.com/kami-zh/gooce
```
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/kami-zh/gooce.
## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
| d795989c5e3e57c17cb2f6ee583ce481de2e1de5 | [
"Markdown",
"Go"
] | 5 | Go | zenizh/gooce | 4ec7914010edc05cee91cffb65424e0ef2e2035f | 91fde9eabc80f6015c9cf4af3e4ec57a099798d2 |
refs/heads/master | <repo_name>nkeynes/bazel-js-testcase<file_sep>/a/src/Bar.ts
export function getBar() {
return {bar: "hello"};
}
<file_sep>/b/src/index.ts
import {getBar} from "@testws/a/Bar";
console.log(getBar());
| 10596c6179df97ddc18c74c5e2d07505eb327dd2 | [
"TypeScript"
] | 2 | TypeScript | nkeynes/bazel-js-testcase | 05fdef8af91cf7671294996576e749fbe1dd620e | 3afd923d1dcd7e79578e608fc818d43a0eae32f5 |
refs/heads/main | <file_sep>import torch
import torch.nn as nn
import torch.nn.functional as F
'''modified from https://github.com/ndrplz/ConvLSTM_pytorch/'''
class ConvLSTMCell(nn.Module):
def __init__(self, input_dim, hidden_dim, kernel_size, bias=True, forget_bias=1.0):
"""
Initialize ConvLSTM cell.
Parameters
----------
input_dim: int
Number of channels of input tensor.
hidden_dim: int
Number of channels of hidden state.
kernel_size: (int, int)
Size of the convolutional kernel.
bias: bool
Whether or not to add the bias.
"""
super(ConvLSTMCell, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.kernel_size = kernel_size
self.padding = kernel_size[0] // 2, kernel_size[1] // 2
self.bias = bias
self.forget_bias = forget_bias # TODO: add or not
self.conv = nn.Conv2d(in_channels=self.input_dim + self.hidden_dim,
out_channels=4 * self.hidden_dim,
kernel_size=self.kernel_size,
padding=self.padding,
bias=self.bias)
torch.nn.init.xavier_normal_(self.conv.weight)
def forward(self, input_tensor, cur_state):
'''
:param input_tensor: B x input_dim x height x width
:param cur_state: B x 2hidden_dim x height x width
:return: h_next, [h_next, c_next]
'''
h_cur, c_cur = torch.split(cur_state, self.hidden_dim, dim=1)
combined = torch.cat([input_tensor, h_cur], dim=1) # concatenate along channel axis
combined_conv = self.conv(combined)
cc_i, cc_f, cc_o, cc_g = torch.split(combined_conv, self.hidden_dim, dim=1)
i = torch.sigmoid(cc_i)
f = torch.sigmoid(cc_f + self.forget_bias)
o = torch.sigmoid(cc_o)
g = torch.tanh(cc_g)
c_next = f * c_cur + i * g
h_next = o * torch.tanh(c_next)
return h_next, torch.cat([h_next, c_next], dim=1)
def init_hidden(self, batch_size, image_size):
height, width = image_size
return (torch.zeros(batch_size, self.hidden_dim, height, width, device=self.conv.weight.device),
torch.zeros(batch_size, self.hidden_dim, height, width, device=self.conv.weight.device))
class RNNmodule(nn.Module):
def __init__(self, img_channel, hidden_channel, adj_channel, kernel_size, pixelwise):
super(RNNmodule, self).__init__()
self.img_channel = img_channel
self.adj_channel = adj_channel
self.pixelwise = pixelwise
self.padding = kernel_size[0] // 2, kernel_size[1] // 2
self.in_cnv = nn.Conv2d(img_channel, hidden_channel, kernel_size, stride=1, padding=self.padding)
self.bn = nn.BatchNorm2d(hidden_channel, momentum=0.01) # TODO
self.RNNcell = ConvLSTMCell(hidden_channel, hidden_channel, kernel_size)
self.rnn_cnv = nn.Conv2d(hidden_channel, hidden_channel, kernel_size, stride=1, padding=self.padding)
if pixelwise:
self.out_cnv = nn.Conv2d(hidden_channel, adj_channel, kernel_size, stride=1, padding=self.padding)
else:
self.out_linear = nn.Linear(hidden_channel, 1)
# TODO: or kernel size=1
# TODO: or multi-adjustment using rnn
self.init_param()
def init_param(self):
torch.nn.init.xavier_normal_(self.in_cnv.weight)
torch.nn.init.xavier_normal_(self.rnn_cnv.weight)
if self.pixelwise:
torch.nn.init.xavier_normal_(self.out_cnv.weight)
self.bn.weight.data.normal_(1.0, 0.02)
self.bn.bias.data.fill_(0)
def forward(self, inputs, last_hidden):
b, c, h, w = inputs.size()
assert c == self.img_channel
if last_hidden == None:
last_hidden = torch.cat(self.RNNcell.init_hidden(b, (h, w)), dim=1)
conv = self.in_cnv(inputs)
conv = self.bn(conv)
conv = F.relu(conv)
rnn, new_hidden = self.RNNcell(conv, last_hidden)
rnn = self.rnn_cnv(rnn)
# rnn = self.bn(rnn)
rnn = F.relu(rnn)
if self.pixelwise:
adjs = F.relu(self.out_cnv(rnn))
adj_t = torch.split(adjs, 1, dim=1)
x = inputs
for i in range(self.adj_channel):
x = torch.pow(x, 1/adj_t[i]) # adj_t[i] B x 1 x h x w
else:
adjs = torch.mean(rnn, dim=[-1, -2])
adjs = F.relu(self.out_linear(adjs)) # B x 1
adjs = adjs.view(-1, 1, 1, 1)
x = torch.pow(inputs, 1/adjs)
# x_gray = torch.mean(x, dim=1, keepdim=True)
# xp = adjs[:, 0].view(-1, 1, 1, 1)
# yp = adjs[:, 1].view(-1, 1, 1, 1)
# x = (x_gray<=xp) * yp/xp * x + (x_gray>xp) * ((1-yp)/(1-xp) * x + (yp-xp)/(1-xp))
return x, adjs, new_hidden<file_sep># ColonLight
This repository includes the testing code and a model checkpoint for lighting enhancement of colonoscopic frame sequences.
To do the lighting adjustment for a frame sequence, simply run
```
bash test.sh
```
where `--chunk` is the path to original images. It will create a new folder `img_corr/` containing the enhanced images.
<file_sep>python code/test.py --chunk /playpen2/COLON_RNNSLAM_TEST/sequences/000/image/ \
--model_name gamma_thru10_first2prev2_ssimALL \
--gpu 1 --num_adj=1 \
--seq_num=10 \
--exp_patch=32 \
--epochs=7 | tee adj.log
<file_sep>import os
import time
import torch
import torchvision
from PIL import Image
import numpy as np
from dataloader import populate_chunk_list, single_chunk
from network import RNNmodule
def test(args, file_list=None):
with torch.no_grad():
network = RNNmodule(3, args.h_size, args.num_adj, (args.kernel, args.kernel), False).cuda()
network.load_state_dict(torch.load('%s%s_Epoch%d.pth' % (args.snapshots_path, args.model_name, args.epochs-1)))
print('load %s%s_Epoch%d.pth' % (args.snapshots_path, args.model_name, args.epochs-1))
network.eval()
img_seq = file_list
hiddens = None
for i, file in enumerate(img_seq):
if not file_list:
img = Image.open(args.validate_img + file)
else:
img = Image.open(file)
img = (np.asarray(img) / 255.0)
imgs = torch.from_numpy(img).permute(2, 0, 1).float()
imgs = imgs.cuda().unsqueeze(0)
start = time.time()
adj_img, adj_param, hiddens = network(imgs, hiddens)
end_time = (time.time() - start)
print(file, end_time, adj_param)
result_path = os.path.dirname(file).replace('image', 'img_corr')
if not os.path.exists(result_path):
os.makedirs(result_path)
if i<2:
torchvision.utils.save_image(imgs, os.path.join(result_path, os.path.basename(file)))
else:
torchvision.utils.save_image(adj_img, os.path.join(result_path, os.path.basename(file)))
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--gpu", default=0)
parser.add_argument("--chunk", type=str)
parser.add_argument("--model_name", type=str)
parser.add_argument('--snapshots_path', type=str, default="snapshots/")
parser.add_argument("--num_adj", type=int, default=1)
parser.add_argument("--seq_num", type=int, default=6)
parser.add_argument("--h_size", type=int, default=32)
parser.add_argument("--kernel", type=int, default=3)
parser.add_argument("--exp_patch", type=int, default=32)
parser.add_argument("--epochs", type=int, default=10)
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
chunk_list = single_chunk(args.chunk)
# chunk_list = populate_chunk_list('/home/zhangyb/projects/ColonData/sequences/')
for chunk in chunk_list:
# print(chunk[0].split('/')[-1])
chunk.sort()
test(args, chunk)
<file_sep>import os
import random
import glob
import numpy as np
from PIL import Image
import torch
import torch.utils.data as data
random.seed(100)
def populate_chunk_list(images_path):
image_list = []
file_list = os.listdir(images_path)
for f in file_list:
if os.path.isdir(images_path + f):
image_list.append(glob.glob(images_path + f + "/image/*.jpg"))
return image_list
def single_chunk(images_path):
image_list = glob.glob(images_path + "*.jpg")
return [image_list]
class sequential_loader(data.Dataset):
def __init__(self, images_path, seq_num, data_type, img_size=256):
if data_type == 'train':
self.chunk_list = populate_chunk_list(images_path)
else:
self.chunk_list = single_chunk(images_path)
if type(img_size) == list:
self.size = img_size
elif type(img_size) == int:
self.size = (img_size, img_size)
else:
raise TypeError("Img size unsupported!")
self.seq_num = seq_num
self.seq_list = []
for chunk in self.chunk_list:
chunk.sort()
for i in range(0, len(chunk)-self.seq_num, self.seq_num//2 if data_type == 'train' else self.seq_num):
self.seq_list.append(chunk[i:i+self.seq_num])
if data_type == 'train':
random.shuffle(self.seq_list)
print("Total %s chunks: %d" % (data_type, len(self.chunk_list)))
print("Total %s sequences: %d" % (data_type, len(self.seq_list)))
def __getitem__(self, index):
data_path = self.seq_list[index]
imgs = []
for img in data_path:
data = Image.open(img)
data = data.resize(self.size, Image.ANTIALIAS)
data = (np.asarray(data) / 255.0)
imgs.append(torch.from_numpy(data).float())
imgs = torch.stack(imgs)
return imgs.permute(0, 3, 1, 2)
def __len__(self):
return len(self.seq_list)
| 4f3cd743e8143ce7b625e0d4d71bc5e4dcd2ee97 | [
"Markdown",
"Python",
"Shell"
] | 5 | Python | adizhol/ColonLight | 77bdad166c6abd25df80b920a8e5b156cfe01f25 | d1bd3b02a4fc4c0bd370b5ceda7f896f0880870d |
refs/heads/master | <file_sep>word = raw_input()
length = len(word)
start = word[0:length/2]
if length % 2 == 0:
end = word[length/2:length]
else:
end = word[length/2+1:length]
isPalendrome = True
for i in range(0,len(start)):
if start[i] != end[len(end)-(i+1)]:
isPalendrome = False
break
if isPalendrome:
print word+" is a palendrome"
else:
print word+" is not a palendrome"
<file_sep>import sys
def fib(n):
a, b = 0, 1
while a < n:
print a, # The comma stops a newline
a, b = b, a+b
try:
val = int(sys.argv[1])
except ValueError:
val = 2000
fib(val)
| c6c0ec167a9a2840e67f5b5cea25a20d65a05550 | [
"Python"
] | 2 | Python | Organi/karanprojects | 943053d748ba9677581070abee697f5e55ec5538 | 9b9b016d40ecf42e3657c26a71ae2fcf4c9ee778 |
refs/heads/master | <file_sep>import Component from '@ember/component';
import { computed } from '@ember/object';
export default Component.extend({
totalBill: 0,
tipValue: 0,
tipAmount: computed('totalBill', 'tipValue', function() {
return this.get('totalBill') * parseFloat(this.get('tipValue'));
}),
totalBillWithTip: computed('totalBill', 'tipAmount', function() {
return this.get('tipAmount') + parseFloat(this.get('totalBill'));
}),
showTotal: computed('totalBillWithTip', function() {
return (
this.get('totalBillWithTip') > 0 && !isNaN(this.get('totalBillWithTip'))
);
}),
didReceiveAttrs: function() {
this._super(...arguments);
const inputAmount = this.get('inputAmount');
if (inputAmount && !isNaN(parseFloat(inputAmount))) {
this.set('totalBill', parseFloat(inputAmount));
}
},
actions: {
onTipChange: function(newTipValue) {
this.set('tipValue', newTipValue);
},
onSubmit: function(e) {
e.preventDefault();
}
}
});
<file_sep>import { helper } from '@ember/component/helper';
export function formatNumber([value]) {
return `${parseFloat(value).toFixed(2)}`;
}
export default helper(formatNumber);
| f033a3cb89ed7e0c3372674aba007a9776350868 | [
"JavaScript"
] | 2 | JavaScript | ima007/tippy-test | 16e31e0338fd19ef7257b9dd8f5d088446facae7 | dfb754f247e59f32ee6d1fdbfccbc006c496c05f |
refs/heads/main | <repo_name>a-msy/IEE-B<file_sep>/Media/report/6/image.c
#include "image.h"
Image *ImageAlloc(int w, int h)
{
Image *im = (Image *)malloc(sizeof(Image));
im->W = w;
im->H = h;
im->data = (unsigned char *)malloc(3 * w * h);
return im;
}
void ImageClear(Image *im){
for(int y=0;y<im->H;y++){
for(int x=0;x<im->W;x++){
IElem(im,x,y,0) = 0;
IElem(im,x,y,1) = 0;
IElem(im,x,y,2) = 0;
}
}
}
void mult33(double d[3][3],double a[3][3],double b[3][3]){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
d[i][j] = a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j];
}
}
}
void ImageImageProjectionAlpha(Image*id,Image*is,double a[3][3],double alpha){
int x,y,u,v;
double r;
for(y=0;y<id->H;y++) for(x=0;x<id->W;x++){
r=1/(a[2][0]*x+a[2][1]*y+a[2][2]);
u=r*(a[0][0]*x+a[0][1]*y+a[0][2]);
v=r*(a[1][0]*x+a[1][1]*y+a[1][2]);
if( isInsideImage(is,u,v) ){
IElem(id,x,y,0)+=IElem(is,u,v,0)*alpha,
IElem(id,x,y,1)+=IElem(is,u,v,1)*alpha,
IElem(id,x,y,2)+=IElem(is,u,v,2)*alpha;
}
}
}
Matrix *MatrixAlloc(int _H,int _W){
Matrix*mt=(Matrix*)malloc(sizeof(Matrix));
mt->W = _W;
mt->H = _H;
mt->data=(double*)malloc(mt->W*mt->H*sizeof(double));
return mt;
}<file_sep>/Media/report/8/panorama.c
#include "image.h"
#define TRIAL 1000000
int desc(int left[3], int right[3])
{
return right[2]-left[2];
}
void initRndAry(int rndAry[MAX]){
for(int i = 0; i<MAX; i++){
rndAry[i] = i;
}
srand(__rdtsc()); // __rdtsc ใซใคใใฆใฏ็ฌฌ๏ผๅใๅ็
ง๏ผ
}
void chooseFourNumbers(int rndAry[MAX]){
for(int i=0;i<4;i++){
int j, t;
j = (int)((long long)rand()*(MAX-i)/(RAND_MAX+1LL))+i; // ไนฑๆฐ้ขๆฐใฏ stdlib.h ใงๅฎฃ่จใใใฆใใ๏ผ
t = rndAry[i];
rndAry[i] = rndAry[j];
rndAry[j] = t;
}
}
void calcHomography(double H[3][3],double w[][4],int rndAry[MAX], Matrix *cmA, Matrix *vt, Matrix *mtR, Matrix *tmp){
int a = rndAry[0], b = rndAry[1], c = rndAry[2], d = rndAry[3];
double ww[][4] = {
w[a][0], w[a][1], w[a][2], w[a][3],
w[b][0], w[b][1], w[b][2], w[b][3],
w[c][0], w[c][1], w[c][2], w[c][3],
w[d][0], w[d][1], w[d][2], w[d][3],
};
// create A (col-major)
for(int i=0;i<4;i++){
Elem(cmA,0,i*2 )=ww[i][0];
Elem(cmA,1,i*2 )=ww[i][1];
Elem(cmA,2,i*2 )=1;
Elem(cmA,3,i*2 )=0;
Elem(cmA,4,i*2 )=0;
Elem(cmA,5,i*2 )=0;
Elem(cmA,6,i*2 )=-ww[i][0]*ww[i][2];
Elem(cmA,7,i*2 )=-ww[i][1]*ww[i][2];
Elem(cmA,0,i*2+1)=0;
Elem(cmA,1,i*2+1)=0;
Elem(cmA,2,i*2+1)=0;
Elem(cmA,3,i*2+1)=ww[i][0];
Elem(cmA,4,i*2+1)=ww[i][1];
Elem(cmA,5,i*2+1)=1;
Elem(cmA,6,i*2+1)=-ww[i][0]*ww[i][3];
Elem(cmA,7,i*2+1)=-ww[i][1]*ww[i][3];
Elem(vt ,0,i*2 )=ww[i][2];
Elem(vt ,0,i*2+1)=ww[i][3];
}
MatrixQRDecompColMajor(mtR,cmA);
MatrixMultT(tmp,vt,cmA);
MatrixSimeqLr(tmp,mtR);
H[0][0] = Elem(tmp,0,0);
H[0][1] = Elem(tmp,0,1);
H[0][2] = Elem(tmp,0,2);
H[1][0] = Elem(tmp,0,3);
H[1][1] = Elem(tmp,0,4);
H[1][2] = Elem(tmp,0,5);
H[2][0] = Elem(tmp,0,6);
H[2][1] = Elem(tmp,0,7);
H[2][2] = 1;
}
int calcScore(double H[3][3], double w[][4]){
int score=0;
for(int i=0;i<MAX;i++){
double x=w[i][0], y=w[i][1], u=w[i][2], v=w[i][3],
x_prime = H[0][0] * x + H[0][1] * y + H[0][2],
y_prime = H[1][0] * x + H[1][1] * y + H[1][2],
z_prime = H[2][0] * x + H[2][1] * y + H[2][2], // ๅคๆ่กๅใจ (x,y,1)^T ใฎ็ฉ
du = (x_prime/z_prime) - u,
dv = (y_prime/z_prime) -v; // (x,y) ใๅคๆใใๅบงๆจ(็ฌฌ2ๅใฎๆฆ่ฆใๅ็
ง)ใจ (u,v) ใฎๅทฎ
if(du*du+dv*dv < 4) score++;//w[i] ใฏๆญฃใใ;
else score += 0; //w[i] ใฏๆญฃใใใชใ;
}
return score;
}
void createPanorama(Matrix *id, Image *im, Image *im2, int bestH[3][3]){
double m0d[3][3]={
1,0,-100,
0,1,-100,
0,0,1
},m1d[3][3];
ImageImageProjectionAlpha(id,im,m0d,.5);
mult33(m1d,bestH,m0d);
ImageImageProjectionAlpha(id,im2,m1d,.5);
ImageWrite("panorama.jpg",id);
}
int main(int ac,char**av){
Image *im, *im2, *im3;
Matrix *imf, *mt, *id;
int N1, N2, N3, nm;
double w[999][4];
int x1[MAX+1][3], x2[MAX+1][3], x3[MAX+1][3];
double m0d[3][3]={
1,0,-100,
0,1,-100,
0,0,1
},m1d[3][3],m2d[3][3];
// ๅคๆฐใฎๅคๆ่กๅใใๆใไฟก้ ผๅบฆใฎ้ซใ่กๅใ้ธใถ(RANSAC)
double bestH[3][3];
int best_score = 0; // ๆขใซ็บ่ฆใใใๆ่ฏใฎๅคๆ่กๅใจๅพ็น
int rndAry[MAX];
Matrix *cmA, *vt, *mtR, *tmp; // ไฝๆฅญ้ ๅใใใใง็ขบไฟใใฆ calcHomography ใงไฝฟใ
/*av[1] = Wใฎๅค๏ผใใไปฅ้ใฏ็ปๅใใกใคใซๅ*/
im = ImageRead(av[1]);
printf("read1\n");
im2 = ImageRead(av[2]);
printf("read2\n");
imf = MatrixAlloc(im->H, im->W);
ImageFeature(imf, im, 7);
N1 = MatrixLocalMax(x1, imf, 7);
printf("N1:%d\n",N1);
ImageFeature(imf, im2, 7);
N2 = MatrixLocalMax(x2, imf, 7);
printf("N2:%d\n",N2);
mt = MatrixAlloc(N1, N2);
printf("mt\n");
calcSSDtable(mt, im, x1, N1, im2, x2, N2, 7);
printf("calcSSDtable\n");
nm = matchMethod2(w, mt, im, x1, N1, im2, x2, N2);
printf("nm:%d\n",nm);
// ๅคๆฐใฎๅคๆ่กๅใใๆใไฟก้ ผๅบฆใฎ้ซใ่กๅใ้ธใถ(RANSAC)
cmA = MatrixAlloc(8,8);
vt = MatrixAlloc(1,8);
mtR = MatrixAlloc(8,8);
tmp = MatrixAlloc(1,8);
printf("Alloc:cmA,vt,mtR,tmp\n");
initRndAry(rndAry);
printf("init andary\n");
for(int trial = 0; trial<TRIAL; trial++){
double H[3][3]; // ้ธใใ 4็นใใ่จ็ฎใใใๅคๆ่กๅใฎ็ฝฎใๅ ด
chooseFourNumbers(rndAry);
calcHomography(H,w,rndAry,cmA,vt,mtR,tmp);
int score = calcScore(H,w);
if(best_score < score){
bestH[0][0] = H[0][0];
bestH[0][1] = H[0][1];
bestH[0][2] = H[0][2];
bestH[1][0] = H[1][0];
bestH[1][1] = H[1][1];
bestH[1][2] = H[1][2];
bestH[2][0] = H[2][0];
bestH[2][1] = H[2][1];
bestH[2][2] = H[2][2];
best_score = score;
}
}
printf("best_score:%d\n",best_score);
id = ImageAlloc(1024,768);
ImageClear(id);
ImageImageProjectionAlpha(id,im,m0d,.333);
mult33(m1d,bestH,m0d);
ImageImageProjectionAlpha(id,im2,m1d,.333);
// 2ใจ๏ผ
im3 = ImageRead(av[3]);
printf("read3\n");
ImageFeature(imf, im3, 7);
N3 = MatrixLocalMax(x3, imf, 7);
printf("N3:%d\n",N3);
mt = MatrixAlloc(N2, N3);
printf("mt\n");
calcSSDtable(mt, im2, x2, N2, im3, x3, N3, 7);
printf("calcSSDtable\n");
nm = matchMethod2(w, mt, im2, x2, N2, im3, x3, N3);
printf("nm:%d\n",nm);
cmA = MatrixAlloc(8,8);
vt = MatrixAlloc(1,8);
mtR = MatrixAlloc(8,8);
tmp = MatrixAlloc(1,8);
printf("Alloc:cmA,vt,mtR,tmp\n");
initRndAry(rndAry);
printf("init andary\n");
for(int trial = 0; trial<TRIAL; trial++){
double H[3][3]; // ้ธใใ 4็นใใ่จ็ฎใใใๅคๆ่กๅใฎ็ฝฎใๅ ด
chooseFourNumbers(rndAry);
calcHomography(H,w,rndAry,cmA,vt,mtR,tmp);
int score = calcScore(H,w);
if(best_score < score){
bestH[0][0] = H[0][0];
bestH[0][1] = H[0][1];
bestH[0][2] = H[0][2];
bestH[1][0] = H[1][0];
bestH[1][1] = H[1][1];
bestH[1][2] = H[1][2];
bestH[2][0] = H[2][0];
bestH[2][1] = H[2][1];
bestH[2][2] = H[2][2];
best_score = score;
}
}
printf("best_score:%d\n",best_score);
mult33(m2d,bestH,m1d);
ImageImageProjectionAlpha(id,im3,m2d,.333);
ImageWrite("panorama.jpg",id);
printf("created\n");
return 0;
}<file_sep>/Media/Sources/easyProcess/image.c
#include "image.h"
union {int i; float f;} _inf={0x7f800000};
#define INFINITY _inf.f // 2้ๅฎ็พฉใจใฉใผใๅบใใชใ๏ผใใฎๅฎ็พฉใๅ้ค
#define INFINITY_INT _inf.i
Image *ImageAlloc(int w, int h)
{
Image *im = (Image *)malloc(sizeof(Image));
im->W = w;
im->H = h;
im->data = (unsigned char *)malloc(3 * w * h);
return im;
}
void ImageClear(Image *im){
for(int y=0;y<im->H;y++){
for(int x=0;x<im->W;x++){
IElem(im,x,y,0) = 0;
IElem(im,x,y,1) = 0;
IElem(im,x,y,2) = 0;
}
}
}
void mult33(double d[3][3],double a[3][3],double b[3][3]){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
d[i][j] = a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j];
}
}
}
void ImageImageProjectionAlpha(Image*id,Image*is,double a[3][3],double alpha){
int x,y,u,v;
double r;
for(y=0;y<id->H;y++) for(x=0;x<id->W;x++){
r=1/(a[2][0]*x+a[2][1]*y+a[2][2]);
u=r*(a[0][0]*x+a[0][1]*y+a[0][2]);
v=r*(a[1][0]*x+a[1][1]*y+a[1][2]);
if( isInsideImage(is,u,v) ){
IElem(id,x,y,0)+=IElem(is,u,v,0)*alpha,
IElem(id,x,y,1)+=IElem(is,u,v,1)*alpha,
IElem(id,x,y,2)+=IElem(is,u,v,2)*alpha;
}
}
}
Matrix *MatrixAlloc(int _H,int _W){
Matrix*mt=(Matrix*)malloc(sizeof(Matrix));
mt->W = _W;
mt->H = _H;
mt->data=(double*)malloc(mt->W*mt->H*sizeof(double));
return mt;
}
Image *ImageRead(const char *name)
{
int W, H;
Image *im;
char tmp[128];
sprintf(tmp, "convert %s ppm:-", name);
FILE *fp = popen(tmp, "r");
if (fp == NULL)
{
fprintf(stderr, "could not read %s\n", name);
return 0;
}
fscanf(fp, "%*s%d%d%*s%*c", &W, &H);
//fprintf(stderr,"w x h=%d %d\n",W,H);
im = ImageAlloc(W, H);
fread(im->data, 1, W * H * 3, fp);
pclose(fp);
return im;
}
void ImageWrite(const char *name, Image *im)
{
char tmp[128];
sprintf(tmp, "convert ppm:- %s", name);
FILE *fp = popen(tmp, "w");
if (fp == NULL)
{
fprintf(stderr, "could not write %s\n", name);
return;
}
fprintf(fp, "P6 %d %d 255\n", im->W, im->H);
fwrite(im->data, 1, im->W * im->H * 3, fp);
pclose(fp);
}
double ImageSSD(Image*im,int x1,int y1, Image*im2,int x2,int y2,int W){
int i,j;
double sr=0,sg=0,sb=0,dr,dg,db;
for(i=-W;i<=W;i++) for(j=-W;j<=W;j++){
dr = IElem(im, x1+j, y1+i, 0) - IElem(im2, x2+j , y2+i, 0);
dg = IElem(im, x1+j, y1+i, 1) - IElem(im2, x2+j , y2+i, 1);
db = IElem(im, x1+j, y1+i, 2) - IElem(im2, x2+j , y2+i, 2);
sr += dr*dr;
sg += dg*dg;
sb += db*db;
}
return sr+sg+sb;
}
void calcSSDtable(Matrix*mt,Image*im ,int x1[][3],int N1,Image*im2,int x2[][3],int N2,int W){
int i,j;
#pragma omp parallel for private (j)
for(i=0;i<N1;i++){
for(j=0;j<N2;j++){
Elem(mt,i,j) = ImageSSD(im ,x1[i][0],x1[i][1],im2,x2[j][0],x2[j][1], W);
}
}
}
int matchMethod1(double w[][4],Matrix*mt,Image*im ,int x1[][3],int N1,Image*im2,int x2[][3],int N2){
int i,j,k,ji,n=0;
for(i=0;i<N1;i++){
double sm=INFINITY,t;
for(j=0;j<N2;j++){
t = Elem(mt,i,j);
if(sm>t) sm=t, ji=j;
}
//printf("%d,%d,%d,%d,\n",x1[i][0],x1[i][1],x2[ji][0],x2[ji][1]);
// ไธใฎ printf ใง่กจ็คบใใใใใฎใ w[n][] ใซๆ ผ็ด.
w[n][0] = x1[i][0];
w[n][1] = x1[i][1];
w[n][2] = x2[ji][0];
w[n][3] = x2[ji][1];
n++;
for(k=0;k<N1;k++) { Elem(mt,k,ji)=INFINITY; }
}
printf("%d\n",n);
return n;
}
int matchMethod2(double w[][4],Matrix*mt,Image*im ,int x1[][3],int N1,Image*im2,int x2[][3],int N2){
int i,j,k,l,n = 0;
int minElem[3] = {0,0,INFINITY_INT};
//ใSSDใฎ่กจไธญใฎๆๅฐๅค
for(i=0;i<MAX;i++){//็นใฎๆฐใ ใ
for(j=0;j<mt->W;j++){//ๆจชๅน
for(k=0;k<mt->H;k++){//็ธฆๅน
if(Elem(mt,j,k) < minElem[2]){
minElem[0] = j;
minElem[1] = k;
minElem[2] = (int)Elem(mt,j,k);
//printf("%d,%d,%d\n",minElem[0],minElem[1],minElem[2]);
}
}
}
for(k=0;k<MAX;k++) Elem(mt,minElem[0],k)=INFINITY_INT;//ๆจชๅบๅฎใใฆ็็ ด
for(k=0;k<MAX;k++) Elem(mt,k,minElem[1])=INFINITY_INT;//็ธฆๅบๅฎใใฆ็็ ด
//MatrixPrint(mt);
//printf("%d,%d,%d,%d,\n",x1[minElem[0]][0],x1[minElem[0]][1],x2[minElem[1]][0],x2[minElem[1]][1]);
w[n][0] = x1[minElem[0]][0];
w[n][1] = x1[minElem[0]][1];
w[n][2] = x2[minElem[1]][0];
w[n][3] = x2[minElem[1]][1];
n++;
minElem[2]=INFINITY_INT;
}
return n;
}
void ImageFeature(Matrix*im2,Image*im,int W){//็นๅพด็นใใใ
int x,y,u,v,ix,iy;
for(y=W+1;y<im->H-W-1;y++) for(x=W+1;x<im->W-W-1;x++){
double ixx,ixy,iyy;
ixx=iyy=ixy=0;
for(v=-W;v<=W;v++)for(u=-W;u<=W;u++){
ix = IElem(im, x+u+1, y+v, 1) - IElem(im, x+u-1, y+v, 1);
iy = IElem(im, x+u, y+v+1, 1) - IElem(im, x+u, y+v-1, 1);
ixx += ix*ix; // ixx ใ ใใงใชใ ixy,iyy ใ่จ็ฎใใ๏ผ
iyy += iy*iy;
ixy += ix*iy;
}
DElem(im2,x,y) = ((ixx + iyy)-sqrt(pow(ixx+iyy,2.0)-4.0*(ixx*iyy-ixy*ixy)))/2.0;
}
}
int MatrixLocalMax(int w[][3], Matrix*im2, int W){//็นๅพด็นใใปใใจใซใใใใฉใใ
int x,y,u,v,n=0,a;
for(y=W+1;y<im2->H-W-1;y++) for(x=W+1;x<im2->W-W-1;x++){
double max=-1;
for(v=-W;v<=W;v++) for(u=-W;u<=W;u++){
if(DElem(im2, x+u, y+v) > max){
max = DElem(im2,x+u,y+v);
}
}
if( max == DElem(im2, x, y) ){
a = n;
if(n < MAX) { n++; }
for(;a>0 && w[a-1][2] < DElem(im2, x, y);a--){
w[a][0]=w[a-1][0]; w[a][1]=w[a-1][1]; w[a][2]=w[a-1][2];
}
w[a][0]=x; w[a][1]=y; w[a][2]=max;
}
}
return n; // ่จ้ฒใใ็นใฎๆฐ
}
double VP(double*a,double*b,int N){
double s=0;
int i;
for(i=0;i<N;i++) s += a[i] * b[i] ;
return s;
}
void VSS(double*d,double s,int N){
int i;
for(i=0;i<N;i++) d[i] *= s;
}
void VSA(double*d,double*a,double s,int N){
int i;
for(i=0;i<N;i++) d[i] += a[i] * s;
}
void MatrixClear(Matrix*mt){
memset(mt->data,0,mt->W*mt->H*sizeof(double));
}
void MatrixCopy(Matrix*mtD,Matrix*mt){
memmove(mtD->data,mt->data,mt->W*mt->H*sizeof(double));
}
void MatrixCopyT(Matrix*mtD,Matrix*mt){
int i,j;
for(i=0;i<mtD->H;i++)
for(j=0;j<mtD->W;j++)
Elem(mtD,i,j) = Elem(mt,j,i);
}
void MatrixMultT(Matrix*mtD,Matrix*mtA,Matrix*mtB){
// D = A B^T
int i,j;
for(i=0;i<mtA->H;i++){
for(j=0;j<mtB->H;j++){
Elem(mtD,i,j) = VP( Row(mtA,i), Row(mtB,j), mtA->W);
}
}
}
void MatrixQRDecompColMajor(Matrix*mtR,Matrix*mt){
double t;
int W = mt->W;
double **aT = (double **)malloc((sizeof (double *)) * mt->H);
for(int get=0; get<mt->H;get++){
aT[get] = Row(mt,get);
}
MatrixClear(mtR);
for(int i=0; i < W; i++){
for(int j=0; j <= i; j++){
if(j == i){
Elem(mtR,j,i) = t = sqrt(VP(aT[j],aT[i],W));
VSS(aT[i], 1/t, W);
}else{
Elem(mtR,j,i) = t = VP(aT[j], aT[i], W);
VSA(aT[i], aT[j], -t, W);
}
}
}
}
void MatrixSimeqLr(Matrix*mtB,Matrix*mtR){
// B = B L^{-1}
double * B = Row(mtB,0);
for(int i=mtR->W-1; 0<=i; i--){
for(int j=i+1; j<mtR->W; j++){
B[i] -= B[j]*Elem(mtR,i,j);
}
B[i] = B[i] / Elem(mtR,i,i);
}
}<file_sep>/Media/Sources/easyProcess/TKfilter.c
// cl /Ox TKfilter.c image.c image2.cxx && TKfilter 0.jpg
// gcc TKfilter.c image.c image2.c -lm -O3 -mavx2 -march=native -funroll-loops -fomit-frame-pointer && ./a.out 0.jpg
#include"image.h"
#include<math.h>
/*
The following should be defined (in image.h and image.c):
- structures Image and Matrix
- related macros (IElem, ,Elem, DElem)
- related functions (ImageAlloc, MatrixAlloc, ...)
*/
#define CPU_KHZ 3.9e+6
#ifdef _WIN32
#include<intrin.h>
#else
#define __rdtsc() ({ long long a,d; __asm__ volatile ("rdtsc":"=a"(a),"=d"(d)); d<<32|a; })
#endif
void ImageDrawBox(Image*im,int x,int y,int W){
int u,v;
for(v=-W;v<=W;v++){
for(u=-W;u<=W;u++){
IElem(im,x+u,y+v,0)=IElem(im,x+u,y+v,0) + 0xff >> 1;
IElem(im,x+u,y+v,1)=IElem(im,x+u,y+v,1) >> 1;
IElem(im,x+u,y+v,2)=IElem(im,x+u,y+v,2) >> 1;
}
}
}
void ImageMatrixWrite(Image*im,Matrix*mt,double s){
int x,y,p;
for(y=0;y<mt->H;y++) for(x=0;x<mt->W;x++){
double tmp=mt->data[y*mt->W+x]*s;
if(tmp>255) tmp=255;
im->data[(y*im->W+x)*3+0] = im->data[(y*im->W+x)*3+1] = im->data[(y*im->W+x)*3+2] = tmp;
}
}
// void ImageFeature(Matrix*im2,Image*im,int W){
// int x,y,u,v,ix,iy;
// for(y=W+1;y<im->H-W-1;y++) for(x=W+1;x<im->W-W-1;x++){
// double ixx,ixy,iyy;
// ixx=iyy=ixy=0;
// for(v=-W;v<=W;v++)for(u=-W;u<=W;u++){
// ix = IElem(im, x+u+1, y+v, 1) - IElem(im, x+u-1, y+v, 1);
// iy = IElem(im, x+u, y+v+1, 1) - IElem(im, x+u, y+v-1, 1);
// ixx += ix*ix; // ixx ใ ใใงใชใ ixy,iyy ใ่จ็ฎใใ๏ผ
// iyy += iy*iy;
// ixy += ix*iy;
// }
// DElem(im2,x,y) = ((ixx + iyy)+sqrt(pow(ixx+iyy,2.0)-4.0*(ixx*iyy-ixy*ixy)))/2.0; // ๅฎ้ใซใฏ [ixx,ixy;ixy,iyy] ใฎๅฐใใๆนใฎๅบๆๅคใๅ
ฅใใ๏ผ ่งฃใฎๅ
ฌๅผ
// }
// }
// int MatrixLocalMax(int w[][2], Matrix*im2){
// int x,y,u,v,W=7,n=0,a;
// for(y=W+1;y<im2->H-W-1;y++) for(x=W+1;x<im2->W-W-1;x++){
// double max=-1;
// for(v=-W;v<=W;v++) for(u=-W;u<=W;u++){
// // (x,y) ใไธญๅฟใจใใ 15x15 ใฎ็ฉๅฝข้ ๅๅ
ใง DElem(im2,x+u,y+v) ใฎๆๅคงๅคใๆขใ๏ผ
// }
// // ๆๅคงๅคใ DElem(im2,x,y) ใจ็ญใใใชใ๏ผ(x,y) ใ็นๅพด็นใจใใฆ่จ้ฒใใ๏ผ
// // a=n++; w[a][0]=x; w[a][1]=y;
// }
// return n; // ่จ้ฒใใ็นใฎๆฐ
// }
int main(int ac,char**av){
Image *im;
Matrix*im2;
int kk[9999][2], kw,i;
if(ac<1){ fprintf(stderr,"Specify an image to process.\n"); return 1; }
im=ImageRead(av[1]);
im2=MatrixAlloc(im->H,im->W);
long long start=__rdtsc();
ImageFeature(im2,im,7);
printf("%f msec\n",(__rdtsc()-start)/CPU_KHZ);
kw=MatrixLocalMax(kk,im2,7);
printf("%d\n",kw);
ImageMatrixWrite(im,im2,.001);
for(i=0;i<kw;i++){
ImageDrawBox(im,kk[i][0],kk[i][1],7);
printf("Draw\n");
}
ImageWrite("out.jpg",im);
return 0;
}<file_sep>/Media/Sources/easyProcess/ransac.c
#include "image.h"
#define TRIAL 1000000
void initRndAry(int rndAry[MAX]){
for(int i = 0; i<MAX; i++){
rndAry[i] = i;
}
srand(__rdtsc()); // __rdtsc ใซใคใใฆใฏ็ฌฌ๏ผๅใๅ็
ง๏ผ
}
void chooseFourNumbers(int rndAry[MAX]){
for(int i=0;i<4;i++){
int j, t;
j = (int)((long long)rand()*(MAX-i)/(RAND_MAX+1LL))+i; // ไนฑๆฐ้ขๆฐใฏ stdlib.h ใงๅฎฃ่จใใใฆใใ๏ผ
t = rndAry[i];
rndAry[i] = rndAry[j];
rndAry[j] = t;
}
}
void calcHomography(double H[3][3],double w[][4],int rndAry[MAX], Matrix *cmA, Matrix *vt, Matrix *mtR, Matrix *tmp){
int a = rndAry[0], b = rndAry[1], c = rndAry[2], d = rndAry[3];
double ww[][4] = {
w[a][0], w[a][1], w[a][2], w[a][3],
w[b][0], w[b][1], w[b][2], w[b][3],
w[c][0], w[c][1], w[c][2], w[c][3],
w[d][0], w[d][1], w[d][2], w[d][3],
};
// create A (col-major)
for(int i=0;i<4;i++){
Elem(cmA,0,i*2 )=ww[i][0];
Elem(cmA,1,i*2 )=ww[i][1];
Elem(cmA,2,i*2 )=1;
Elem(cmA,3,i*2 )=0;
Elem(cmA,4,i*2 )=0;
Elem(cmA,5,i*2 )=0;
Elem(cmA,6,i*2 )=-ww[i][0]*ww[i][2];
Elem(cmA,7,i*2 )=-ww[i][1]*ww[i][2];
Elem(cmA,0,i*2+1)=0;
Elem(cmA,1,i*2+1)=0;
Elem(cmA,2,i*2+1)=0;
Elem(cmA,3,i*2+1)=ww[i][0];
Elem(cmA,4,i*2+1)=ww[i][1];
Elem(cmA,5,i*2+1)=1;
Elem(cmA,6,i*2+1)=-ww[i][0]*ww[i][3];
Elem(cmA,7,i*2+1)=-ww[i][1]*ww[i][3];
Elem(vt ,0,i*2 )=ww[i][2];
Elem(vt ,0,i*2+1)=ww[i][3];
}
MatrixQRDecompColMajor(mtR,cmA);
MatrixMultT(tmp,vt,cmA);
MatrixSimeqLr(tmp,mtR);
H[0][0] = Elem(tmp,0,0);
H[0][1] = Elem(tmp,0,1);
H[0][2] = Elem(tmp,0,2);
H[1][0] = Elem(tmp,0,3);
H[1][1] = Elem(tmp,0,4);
H[1][2] = Elem(tmp,0,5);
H[2][0] = Elem(tmp,0,6);
H[2][1] = Elem(tmp,0,7);
H[2][2] = 1;
}
int calcScore(double H[3][3], double w[][4]){
int score=0;
for(int i=0;i<MAX;i++){
double x=w[i][0], y=w[i][1], u=w[i][2], v=w[i][3],
x_prime = H[0][0] * x + H[0][1] * y + H[0][2],
y_prime = H[1][0] * x + H[1][1] * y + H[1][2],
z_prime = H[2][0] * x + H[2][1] * y + H[2][2], // ๅคๆ่กๅใจ (x,y,1)^T ใฎ็ฉ
du = (x_prime/z_prime) - u,
dv = (y_prime/z_prime) -v; // (x,y) ใๅคๆใใๅบงๆจ(็ฌฌ2ๅใฎๆฆ่ฆใๅ็
ง)ใจ (u,v) ใฎๅทฎ
if(du*du+dv*dv < 10) score++;//w[i] ใฏๆญฃใใ;
else score += 0; //w[i] ใฏๆญฃใใใชใ;
}
return score;
}
void createPanorama(Matrix *id, Image *im, Image *im2, int bestH[3][3]){
double m0d[3][3]={
1,0,-100,
0,1,-100,
0,0,1
},m1d[3][3];
ImageImageProjectionAlpha(id,im,m0d,.5);
mult33(m1d,bestH,m0d);
ImageImageProjectionAlpha(id,im2,m1d,.5);
ImageWrite("dai8.jpg",id);
}
int main(int ac,char**av){
Image *im, *im2;
Matrix *imf, *mt, *id;
int N1, N2, nm;
double w[999][4];
/*av[1] = Wใฎๅค๏ผใใไปฅ้ใฏ็ปๅใใกใคใซๅ*/
im = ImageRead("0.jpg");
im2 = ImageRead("2.jpg");
imf = MatrixAlloc(im->H, im->W);
ImageFeature(imf, im, 7);
N1 = MatrixLocalMax(x1, imf, 7);
ImageFeature(imf, im2, 7);
N2 = MatrixLocalMax(x2, imf, 7);
int x1[][2]={
383, 465,
614, 440,
354, 500,
403, 462,
242, 528,
295, 498,
687, 482,
337, 514,
298, 554,
116, 406,
315, 495,
458, 471,
134, 501,
136, 457,
259, 538,
578, 460,
13, 562,
11, 474,
114, 505,
215, 526,
119, 196,
142, 517,
289, 328,
692, 453,
680, 452,
403, 319,
12, 538,
141, 412,
79, 407,
223, 244,
};
int x2[][2]={
636, 478,
544, 510,
604, 518,
490, 536,
655, 476,
588, 528,
368, 411,
546, 567,
387, 464,
269, 478,
208, 408,
564, 507,
207, 416,
385, 507,
275, 557,
367, 509,
393, 522,
535, 341,
716, 487,
367, 211,
299, 466,
462, 528,
148, 336,
507, 548,
274, 536,
152, 295,
321, 469,
332, 415,
658, 327,
127, 419,
};
mt = MatrixAlloc(N1, N2);
calcSSDtable(mt, im, x1, N1, im2, x2, N2, 7);
nm = matchMethod2(w, mt, im, x1, N1, im2, x2, N2);
// ๅคๆฐใฎๅคๆ่กๅใใๆใไฟก้ ผๅบฆใฎ้ซใ่กๅใ้ธใถ(RANSAC)
double bestH[3][3];
int best_score = 0; // ๆขใซ็บ่ฆใใใๆ่ฏใฎๅคๆ่กๅใจๅพ็น
int rndAry[MAX];
Matrix *cmA, *vt, *mtR, *tmp; // ไฝๆฅญ้ ๅใใใใง็ขบไฟใใฆ calcHomography ใงไฝฟใ
cmA = MatrixAlloc(8,8);
vt = MatrixAlloc(1,8);
mtR = MatrixAlloc(8,8);
tmp = MatrixAlloc(1,8);
initRndAry(rndAry);
for(int trial = 0; trial<TRIAL; trial++){
double H[3][3]; // ้ธใใ 4็นใใ่จ็ฎใใใๅคๆ่กๅใฎ็ฝฎใๅ ด
chooseFourNumbers(rndAry);
calcHomography(H,w,rndAry,cmA,vt,mtR,tmp);
int score = calcScore(H,w);
if(best_score < score){
bestH[0][0] = H[0][0];
bestH[0][1] = H[0][1];
bestH[0][2] = H[0][2];
bestH[1][0] = H[1][0];
bestH[1][1] = H[1][1];
bestH[1][2] = H[1][2];
bestH[2][0] = H[2][0];
bestH[2][1] = H[2][1];
bestH[2][2] = H[2][2];
best_score = score;
}
}
id = ImageAlloc(1024,768);
ImageClear(id);
createPanorama(id, im, im2, bestH);
return 0;
}
<file_sep>/Media/report/6/image.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
typedef struct _Image
{
unsigned char *data;
int W, H;
} Image;
typedef struct {
double *data;
int W,H;
} Matrix;
#define IElem(_im, _x, _y, _c) (_im)->data[(_y) * (_im)->W * 3 + (_x)*3 + (_c)]
#define Elem(_a,_b,_c) (_a)->data[(_a)->W*(_b)+(_c)]
#define DElem(_a,_b,_c) (_a)->data[(_a)->W*(_c)+(_b)]
#define isInsideImage(is, u, v) (0 <= u && u < is->W && 0 <= v && v < is->H)
Image *ImageAlloc(int W, int H);
Image *ImageRead(const char *name);
void ImageFree(Image *im);
void ImageWrite(const char *name, Image *im);
void ImageClear(Image *im);
void ImageImageProjectionAlpha(Image *id, Image *is, double a[3][3], double alpha);
void ImageDrawBox(Image *im, int x, int y,int W);
void mult33(double d[3][3],double a[3][3],double b[3][3]);
Matrix *MatrixAlloc(int _H,int _W);<file_sep>/Media/Sources/easyProcess/greedy.c
/*
cl /Ox greedy.c image.c image2.cxx ; greedy 0.jpg 2.jpg
gcc -O greedy.c image.c image2.c -lm ; ./a.out 0.jpg 2.jpg
*/
#include"image.h"
#include<math.h>
#define MAX 30
double ImageSSD(Image*im,int x1,int y1, Image*im2,int x2,int y2){
int i,j,W=7;
double sr=0,sg=0,sb=0,dr,dg,db;
for(i=-W;i<=W;i++) for(j=-W;j<=W;j++){
dr = IElem(im, x1+j, y1+i, 0) - IElem(im2, x2+j , y2+i, 0);
dg = IElem(im, x1+j, y1+i, 1) - IElem(im2, x2+j , y2+i, 1);
db = IElem(im, x1+j, y1+i, 2) - IElem(im2, x2+j , y2+i, 2);
sr += dr*dr;
sg += dg*dg;
sb += db*db;
}
return sr+sg+sb;
}
void calcSSDtable(Matrix*mt,Image*im ,int x1[][2],int N1,Image*im2,int x2[][2],int N2){
int i,j;
for(i=0;i<N1;i++){
for(j=0;j<N2;j++){
Elem(mt,i,j) = ImageSSD(im ,x1[i][0],x1[i][1],im2,x2[j][0],x2[j][1]);
//printf("%3d ",(int)Elem(mt,i,j)/100000);
}
//printf("\n");
}
}
void MatrixPrint(Matrix*mt){
int i,j;
for(i=0;i<mt->H;i++){
for(j=0;j<mt->W;j++){
printf("%d ",(int)Elem(mt,i,j)/100000);
}
printf("\n");
}
}
union {int i; float f;} _inf={0x7f800000};
#define INFINITY _inf.f // 2้ๅฎ็พฉใจใฉใผใๅบใใชใ๏ผใใฎๅฎ็พฉใๅ้ค
#define INFINITY_INT _inf.i
int matchMethod1(double w[][4],Matrix*mt,Image*im ,int x1[][2],int N1,Image*im2,int x2[][2],int N2){
int i,j,k,ji,n=0;
for(i=0;i<N1;i++){
double sm=INFINITY,t;
for(j=0;j<N2;j++){
t = Elem(mt,i,j);
if(sm>t) sm=t, ji=j;
}
printf("%d,%d,%d,%d,\n",x1[i][0],x1[i][1],x2[ji][0],x2[ji][1]);
// ไธใฎ printf ใง่กจ็คบใใใใใฎใ w[n][] ใซๆ ผ็ด.
w[n][0] = x1[i][0];
w[n][1] = x1[i][1];
w[n][2] = x2[ji][0];
w[n][3] = x2[ji][1];
n++;
for(k=0;k<N1;k++) { Elem(mt,k,ji)=INFINITY; }
}
printf("%d\n",n);
return n;
}
int matchMethod2(double w[][4],Matrix*mt,Image*im ,int x1[][2],int N1,Image*im2,int x2[][2],int N2){
int i,j,k,l,n = 0;
int minElem[3] = {0,0,INFINITY_INT};
//ใSSDใฎ่กจไธญใฎๆๅฐๅค
for(i=0;i<MAX;i++){//็นใฎๆฐใ ใ
for(j=0;j<mt->W;j++){//ๆจชๅน
for(k=0;k<mt->H;k++){//็ธฆๅน
if(Elem(mt,j,k) < minElem[2]){
minElem[0] = j;
minElem[1] = k;
minElem[2] = (int)Elem(mt,j,k);
//printf("%d,%d,%d\n",minElem[0],minElem[1],minElem[2]);
}
}
}
for(k=0;k<MAX;k++) Elem(mt,minElem[0],k)=INFINITY_INT;//ๆจชๅบๅฎใใฆ็็ ด
for(k=0;k<MAX;k++) Elem(mt,k,minElem[1])=INFINITY_INT;//็ธฆๅบๅฎใใฆ็็ ด
//MatrixPrint(mt);
printf("%d,%d,%d,%d,\n",x1[minElem[0]][0],x1[minElem[0]][1],x2[minElem[1]][0],x2[minElem[1]][1]);
w[n][0] = x1[minElem[0]][0];
w[n][1] = x1[minElem[0]][1];
w[n][2] = x2[minElem[1]][0];
w[n][3] = x2[minElem[1]][1];
n++;
minElem[2]=INFINITY_INT;
}
return n;
}
int main(int ac,char**av){
Image *im,*im2;
Matrix*mt;
int x1[][2]={
383, 465,
614, 440,
354, 500,
403, 462,
242, 528,
295, 498,
687, 482,
337, 514,
298, 554,
116, 406,
315, 495,
458, 471,
134, 501,
136, 457,
259, 538,
578, 460,
13, 562,
11, 474,
114, 505,
215, 526,
119, 196,
142, 517,
289, 328,
692, 453,
680, 452,
403, 319,
12, 538,
141, 412,
79, 407,
223, 244,
}, N1=MAX;
int x2[][2]={
636, 478,
544, 510,
604, 518,
490, 536,
655, 476,
588, 528,
368, 411,
546, 567,
387, 464,
269, 478,
208, 408,
564, 507,
207, 416,
385, 507,
275, 557,
367, 509,
393, 522,
535, 341,
716, 487,
367, 211,
299, 466,
462, 528,
148, 336,
507, 548,
274, 536,
152, 295,
321, 469,
332, 415,
658, 327,
127, 419,
}, N2=MAX;
if(ac<3) return 1;
im =ImageRead(av[1]);
im2=ImageRead(av[2]);
mt=MatrixAlloc(N1,N2);
calcSSDtable(mt,im,x1,N1,im2,x2,N2);
double w[999][4];
int nm;
nm=matchMethod2(w,mt,im,x1,N1,im2,x2,N2);//็นๅพด็นใฎๅฏพๅฟไปใ
return 0;
}<file_sep>/Media/Sources/easyProcess/homography.c
// cl /Ox homography.c image.c image2.cxx && homography 1.jpg out.jpg && out.jpg
// gcc --no-warnings -O homography.c image.c image2.c && ./a.out 1.jpg out.jpg && display out.jpg
#include"image.h"
// Following functions must be defined in image.c:
// ImageAlloc, ImageClear
void ImageImageProjection(Image*id,Image*is,double a[3][3]){
int x,y,u,v;
double r;
for(y=0;y<id->H;y++) for(x=0;x<id->W;x++){
r=1/(a[2][0]*x+a[2][1]*y+a[2][2]);
u=r*(a[0][0]*x+a[0][1]*y+a[0][2]);
v=r*(a[1][0]*x+a[1][1]*y+a[1][2]);
if( isInsideImage(is,u,v) ){
IElem(id,x,y,0)=IElem(is,u,v,0),
IElem(id,x,y,1)=IElem(is,u,v,1),
IElem(id,x,y,2)=IElem(is,u,v,2);
}
}
}
int main(int argc,char*argv[]){
Image *im,*im2;
// double a[][3]={
// .866 , -.5 , 160,
// .5 , .866 , -300,
// 0 , 0 , 1
// };
double a[][3]={
0.5, 0, 0,
0, 0.5, 0,
0, 0, 1
};
double b[][3]={
.866 , -.5 , 160,
.5 , .866 , -300,
-.001, 0 , 1
};
im=ImageRead(argv[1]);
im2=ImageAlloc(1024,768);
ImageClear(im2);
ImageImageProjection(im2,im,a);
ImageWrite(argv[2],im2);
return 0;
}<file_sep>/README.md
# ๅฒกๅฑฑๅคงๅญฆใๅทฅๅญฆ้จใๆ
ๅ ฑๅทฅๅญฆๅฎ้จBใใกใใฃใขใ้ณๅฃฐใIEE-B
<file_sep>/Media/Sources/easyProcess/image.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
typedef struct _Image
{
unsigned char *data;
int W, H;
} Image;
typedef struct {
double *data;
int W,H;
} Matrix;
#define IElem(_im, _x, _y, _c) (_im)->data[(_y) * (_im)->W * 3 + (_x)*3 + (_c)]
#define Elem(_a,_b,_c) (_a)->data[(_a)->W*(_b)+(_c)]
#define DElem(_a,_b,_c) (_a)->data[(_a)->W*(_c)+(_b)]
#define Row(_a,_b) ((_a)->data+(_a)->W*(_b))
#define isInsideImage(is, u, v) (0 <= u && u < is->W && 0 <= v && v < is->H)
#define MAX 30
#ifdef _WIN32
#include<intrin.h>
#else
#define __rdtsc() ({ long long a,d; __asm__ volatile ("rdtsc":"=a"(a),"=d"(d)); d<<32|a; })
#endif
Image *ImageAlloc(int W, int H);
Image *ImageRead(const char *name);
void ImageFree(Image *im);
void ImageWrite(const char *name, Image *im);
void ImageClear(Image *im);
void ImageImageProjectionAlpha(Image *id, Image *is, double a[3][3], double alpha);
void ImageDrawBox(Image *im, int x, int y,int W);
void mult33(double d[3][3],double a[3][3],double b[3][3]);
Matrix *MatrixAlloc(int _H,int _W);
double ImageSSD(Image*im,int x1,int y1, Image*im2,int x2,int y2,int W);
void calcSSDtable(Matrix*mt,Image*im ,int x1[][3],int N1,Image*im2,int x2[][3],int N2, int W);
int matchMethod1(double w[][4],Matrix*mt,Image*im ,int x1[][3],int N1,Image*im2,int x2[][3],int N2);
int matchMethod2(double w[][4],Matrix*mt,Image*im ,int x1[][3],int N1,Image*im2,int x2[][3],int N2);
void ImageFeature(Matrix*im2,Image*im,int W);
int MatrixLocalMax(int w[][3], Matrix*im2, int W);
void MatrixSimeqLr(Matrix*mtB,Matrix*mtR);
void MatrixQRDecompColMajor(Matrix*mtR,Matrix*mt);
void MatrixCopyT(Matrix*mtD,Matrix*mt);
void MatrixClear(Matrix*mt);
void MatrixCopy(Matrix*mtD,Matrix*mt);
void VSA(double*d,double*a,double s,int N);
void VSS(double*d,double s,int N);
double VP(double*a,double*b,int N);
<file_sep>/Media/Sources/easyProcess/lsq.c
// gcc lsq.c image.c image2.c -lm -O ; ./a.out
#include"image.h"
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
// basic vector operations
double VP(double*a,double*b,int N){
double s=0;
int i;
for(i=0;i<N;i++) s += a[i] * b[i] ;
return s;
}
void VSS(double*d,double s,int N){
int i;
for(i=0;i<N;i++) d[i] *= s;
}
void VSA(double*d,double*a,double s,int N){
int i;
for(i=0;i<N;i++) d[i] += a[i] * s;
}
#define Elem(_a,_b,_c) (_a)->data[(_a)->W*(_b)+(_c)]
#define Row(_a,_b) ((_a)->data+(_a)->W*(_b))
void MatrixClear(Matrix*mt){
memset(mt->data,0,mt->W*mt->H*sizeof(double));
}
void MatrixCopy(Matrix*mtD,Matrix*mt){
memmove(mtD->data,mt->data,mt->W*mt->H*sizeof(double));
}
void MatrixCopyT(Matrix*mtD,Matrix*mt){
int i,j;
for(i=0;i<mtD->H;i++)
for(j=0;j<mtD->W;j++)
Elem(mtD,i,j) = Elem(mt,j,i);
}
void MatrixPrint(Matrix*mt){
int i,j;
for(i=0;i<mt->H;i++){
for(j=0;j<mt->W;j++){
printf("%f ",Elem(mt,i,j));
}
printf("\n");
}
}
void MatrixMultT(Matrix*mtD,Matrix*mtA,Matrix*mtB){
// D = A B^T
int i,j;
for(i=0;i<mtA->H;i++){
for(j=0;j<mtB->H;j++){
Elem(mtD,i,j) = VP( Row(mtA,i), Row(mtB,j), mtA->W);
}
}
}
void MatrixQRDecompColMajor(Matrix*mtR,Matrix*mt){
// Gram-Schmidt orthonormalization (R and Q)
double t;//, *aT[] = { Row(mt,0), Row(mt,1), Row(mt,2), Row(mt,3), Row(mt,4), Row(mt,5), Row(mt,6), Row(mt,7) } ;
int W = mt->W;
double **aT = (double **)malloc((sizeof (double *)) * mt->H);
//็ธฆใซไผธใณใฆใใใ
for(int get=0; get<mt->H;get++){
aT[get] = Row(mt,get);
}
MatrixClear(mtR);
///////////
for(int i=0; i < W; i++){
for(int j=0; j <= i; j++){
// printf("%d,%d\n",i,j);
if(j == i){
Elem(mtR,j,i) = t = sqrt(VP(aT[j],aT[i],W));
VSS(aT[i], 1/t, W);
}else{
Elem(mtR,j,i) = t = VP(aT[j], aT[i], W);
VSA(aT[i], aT[j], -t, W);
}
}
}
// Elem(mtR,0,0) = t = sqrt(VP(aT[0],aT[0],W));
// VSS(aT[0], 1/t, W);
// ///////////
// Elem(mtR,0,1) = t = VP(aT[0], aT[1], W);
// VSA(aT[1], aT[0], -t, W);
// Elem(mtR,1,1) = t = sqrt(VP(aT[1],aT[1],W));
// VSS(aT[1], 1/t, W);
// ///////////
// Elem(mtR,0,2) = t = VP(aT[0], aT[2], W);
// VSA(aT[2], aT[0], -t, W);
// Elem(mtR,1,2) = t = VP(aT[1], aT[2], W);
// VSA(aT[2], aT[1], -t, W);
// Elem(mtR,2,2) = t = sqrt(VP(aT[2],aT[2],W));
// VSS(aT[2], 1/t, W);
// ////// ไปฅไธ็ฅ
}
void MatrixSimeqLr(Matrix*mtB,Matrix*mtR){
// B = B L^{-1}
double * B = Row(mtB,0);
for(int i=mtR->W-1; 0<=i; i--){
for(int j=i+1; j<mtR->W; j++){
B[i] -= B[j]*Elem(mtR,i,j);
}
B[i] = B[i] / Elem(mtR,i,i);
}
// B[7] = B[7] / Elem(mtR,7,7);
// B[6] = (B[6]-B[7]*Elem(mtR,6,7)) / Elem(mtR,6,6);
// B[5] = (B[5]-B[6]*Elem(mtR,5,6)-B[7]*Elem(mtR,5,7)) / Elem(mtR,5,5);
// B[4] = (B[4]-B[5]*Elem(mtR,4,5)-B[6]*Elem(mtR,4,6)-B[7]*Elem(mtR,4,7)) / Elem(mtR,4,4);
///// ไปฅไธ็ฅ
}
main(){
Matrix *cmA, *vt, *mtR, *tmp;
int i;
double w[][4]={ // (x,y,u,v)
// 256,218, 371,230,
// 347,220, 463,230,
// 263,367, 383,379,
// 413,315, 530,327,
//kaizen
// 147,535, 268,544,
// 116,209, 235,224,
// 509,205, 629,210,
// 432,517, 550,530
// //jibun
// 215,320, 315,319,
// 220,507, 320,506,
// 651,480, 751,479,
// 600,135, 700,134
//dai6
315,495,564,507,
259,538,507,548,
119,196,367,211,
142,517,393,522
};
cmA=MatrixAlloc(8,8);
vt=MatrixAlloc(1,8);
// create A (col-major)
for(i=0;i<4;i++){
Elem(cmA,0,i*2 )=w[i][0];
Elem(cmA,1,i*2 )=w[i][1];
Elem(cmA,2,i*2 )=1;
Elem(cmA,3,i*2 )=0;
Elem(cmA,4,i*2 )=0;
Elem(cmA,5,i*2 )=0;
Elem(cmA,6,i*2 )=-w[i][0]*w[i][2];
Elem(cmA,7,i*2 )=-w[i][1]*w[i][2];
Elem(cmA,0,i*2+1)=0;
Elem(cmA,1,i*2+1)=0;
Elem(cmA,2,i*2+1)=0;
Elem(cmA,3,i*2+1)=w[i][0];
Elem(cmA,4,i*2+1)=w[i][1];
Elem(cmA,5,i*2+1)=1;
Elem(cmA,6,i*2+1)=-w[i][0]*w[i][3];
Elem(cmA,7,i*2+1)=-w[i][1]*w[i][3];
Elem(vt ,0,i*2 )=w[i][2];
Elem(vt ,0,i*2+1)=w[i][3];
}
// solve Least-squares equation
mtR=MatrixAlloc(8,8);
MatrixQRDecompColMajor(mtR,cmA);
tmp=MatrixAlloc(1,8);
MatrixMultT(tmp,vt,cmA);
MatrixSimeqLr(tmp,mtR);
MatrixPrint(tmp);
//make Image
Image *im,*id;
id=ImageAlloc(1024,768);
ImageClear(id);
double m0d[][3]={
1,0,-100,
0,1,-100,
0,0,1
};
im = ImageRead("0.jpg");
ImageImageProjectionAlpha(id,im,m0d,.5);
double m10[][3]={
Elem(tmp,0,0), Elem(tmp,0,1), Elem(tmp,0,2),
Elem(tmp,0,3), Elem(tmp,0,4), Elem(tmp,0,5),
Elem(tmp,0,6), Elem(tmp,0,7), 1
}, m1d[3][3];
mult33(m1d,m10,m0d);
im = ImageRead("2.jpg");
ImageImageProjectionAlpha(id,im,m1d,.5);
ImageWrite("dai6.jpg",id);
}<file_sep>/Media/Sources/easyProcess/image2.c
#include "image.h"
Image *ImageRead(const char *name)
{
int W, H;
Image *im;
char tmp[128];
sprintf(tmp, "convert %s ppm:-", name);
FILE *fp = popen(tmp, "r");
if (fp == NULL)
{
fprintf(stderr, "could not read %s\n", name);
return 0;
}
fscanf(fp, "%*s%d%d%*s%*c", &W, &H);
//fprintf(stderr,"w x h=%d %d\n",W,H);
im = ImageAlloc(W, H);
fread(im->data, 1, W * H * 3, fp);
pclose(fp);
return im;
}
void ImageWrite(const char *name, Image *im)
{
char tmp[128];
sprintf(tmp, "convert ppm:- %s", name);
FILE *fp = popen(tmp, "w");
if (fp == NULL)
{
fprintf(stderr, "could not write %s\n", name);
return;
}
fprintf(fp, "P6 %d %d 255\n", im->W, im->H);
fwrite(im->data, 1, im->W * im->H * 3, fp);
pclose(fp);
}<file_sep>/Media/Sources/easyProcess/TKfilter2.c
// cl /Ox TKfilter.c image.c image2.cxx && TKfilter 0.jpg
// gcc TKfilter2.c image.c image2.c -lm -O3 -mavx2 -march=native -funroll-loops -fomit-frame-pointer && ./a.out 0.jpg 7
#include"image.h"
#include<math.h>
/*
The following should be defined (in image.h and image.c):
- structures Image and Matrix
- related macros (IElem, ,Elem, DElem)
- related functions (ImageAlloc, MatrixAlloc, ...)
*/
#define CPU_KHZ 3.9e+6
#ifdef _WIN32
#include<intrin.h>
#else
#define __rdtsc() ({ long long a,d; __asm__ volatile ("rdtsc":"=a"(a),"=d"(d)); d<<32|a; })
#endif
int desc(int left[3], int right[3])
{
return right[2]-left[2];
}
void ImageDrawBox(Image*im,int x,int y,int W){
int u,v;
for(v=-W;v<=W;v++){
for(u=-W;u<=W;u++){
IElem(im,x+u,y+v,0)=IElem(im,x+u,y+v,0) + 0xff >> 1;
IElem(im,x+u,y+v,1)=IElem(im,x+u,y+v,1) >> 1;
IElem(im,x+u,y+v,2)=IElem(im,x+u,y+v,2) >> 1;
}
}
}
void ImageMatrixWrite(Image*im,Matrix*mt,double s){
int x,y,p;
for(y=0;y<mt->H;y++) for(x=0;x<mt->W;x++){
double tmp=mt->data[y*mt->W+x]*s;
if(tmp>255) tmp=255;
im->data[(y*im->W+x)*3+0] = im->data[(y*im->W+x)*3+1] = im->data[(y*im->W+x)*3+2] = tmp;
}
}
void ImageFeature(Matrix*im2,Matrix*im3,Matrix*im4,Matrix*im5,Image*im,int W){
int x,y,u,v,ix,iy;
for(y=1;y<im->H-1;y++) for(x=W+1;x<im->W-W-1;x++){
double ixx,ixy,iyy;
ixx=iyy=ixy=0;
for(u=-W;u<=W;u++){
ix = IElem(im, x+u+1, y, 1) - IElem(im, x+u-1, y, 1);
iy = IElem(im, x+u, y, 1) - IElem(im, x+u, y-1, 1);
ixx += ix*ix;
iyy += iy*iy;
ixy += ix*iy;
}
DElem(im3,x,y) = ixx;
DElem(im4,x,y) = ixy;
DElem(im5,x,y) = iyy;
}
for(y=W+1;y<im->H-W-1;y++) for(x=W+1;x<im->W-W-1;x++){
double ixx,ixy,iyy;
ixx=iyy=ixy=0;
for(v=-W;v<=W;v++){
ixx += DElem(im3, x, y+v);
ixy += DElem(im4, x, y+v);
iyy += DElem(im5, x, y+v);
}
DElem(im2,x,y) = ((ixx + iyy)-sqrt(pow(ixx+iyy,2.0)-4.0*(ixx*iyy-ixy*ixy)))/2.0;
}
}
int MatrixLocalMax(int w[][3], Matrix*im2, Matrix*im3, int W){
int x,y,u,v,n=0,a=0;
// double max=-1;
// for(y=1;y<im2->H-1;y++) for(x=W+1;x<im2->W-W-1;x++){
// for(u=-W;u<=W;u++){
// if(DElem(im2, x+u, y) > max){
// DElem(im3,x,y) = DElem(im2, x+u, y);
// }
// }
// }
// for(y=W+1;y<im2->H-W-1;y++) for(x=W+1;x<im2->W-W-1;x++){
// for(v=-W;v<=W;v++){
// }
// }
for(y=W+1;y<im2->H-W-1;y++){
for(x=W+1;x<im2->W-W-1;x++){
double max=-1;
for(v=-W;v<=W;v++){
for(u=-W;u<=W;u++){
// (x,y) ใไธญๅฟใจใใ 15x15 ใฎ็ฉๅฝข้ ๅๅ
ใง DElem(im2,x+u,y+v) ใฎๆๅคงๅคใๆขใ๏ผ
if(DElem(im2, x+u, y+v) > max){
max = DElem(im2,x+u,y+v);
}
}
}
// ๆๅคงๅคใ DElem(im2,x,y) ใจ็ญใใใชใ๏ผ(x,y) ใ็นๅพด็นใจใใฆ่จ้ฒใใ๏ผ
if(max == DElem(im2,x,y)){
a = n++;
w[a][0] = x;
w[a][1] = y;
w[a][2] = max;
}
}
}
return n; // ่จ้ฒใใ็นใฎๆฐ
}
void debug(int w[][3],int kw){
for(int i=0; i<kw; i++){
printf("%d %d %d\n",w[i][0],w[i][1],w[i][2]);
}
}
void debug2(int w[][3],int kw){
for(int i=0; i<30; i++){
printf("%d,%d,\n",w[i][0],w[i][1]);
}
}
int main(int ac,char**av){
Image *im;
Matrix *im2,*im3,*im4,*im5;
int kk[9999][3], kw,i;
// av[2]ใๅฐใใใใใจใปใฐใใฉ
if(ac<1){ fprintf(stderr,"Specify an image to process.\n"); return 1; }
im=ImageRead(av[1]);
im2=MatrixAlloc(im->H,im->W);
im3=MatrixAlloc(im->H,im->W);
im4=MatrixAlloc(im->H,im->W);
im5=MatrixAlloc(im->H,im->W);
long long start=__rdtsc();
ImageFeature(im2,im3,im4,im5,im,atoi(av[2]));
kw = MatrixLocalMax(kk,im2,im3,atoi(av[2]));
printf("%f msec\n",(__rdtsc()-start)/CPU_KHZ);
qsort(kk, kw, sizeof(kk[0]),desc);
debug2(kk,kw);
ImageMatrixWrite(im,im2,.001);
for(i=0;i<30;i++) ImageDrawBox(im,kk[i][0],kk[i][1],atoi(av[2]));//ใใใง๏ผ๏ผๅใ ใใจใใซใงใใ
ImageWrite("out.jpg",im);
return 0;
}<file_sep>/Media/Sources/easyProcess/easyProcess.c
#include"image.h"
#include <math.h>
/* (x,y) ใ (xx,yy) ใไธญๅฟใจใใๅๅพ 256 ใฎๅๅ
ใๅคๅฎ */
int disk(double x,double y, double xx,double yy){
if((x-xx)*(x-xx)+(y-yy)*(y-yy)<65536) return 255;
return 0;
}
void Process(Image*dst,Image*src){
int x,y,q;
for(y=0;y<src->H;y++)
for(x=0;x<src->W;x++){
int qx = round((x)/2);
int qy = round((y)/2);
IElem(dst,x,y,0) = IElem(src,qx,qy,0);
IElem(dst,x,y,1) = IElem(src,qx,qy,1);
IElem(dst,x,y,2) = IElem(src,qx,qy,2);
// IElem(dst,x,y,0) = IElem(src,qx,qy,0)*disk(x,y,320,180)/256; // red at (x,y)
// IElem(dst,x,y,1) = IElem(src,qx,qy,0)*disk(x,y,260,300)/256; // green at (x,y)
// IElem(dst,x,y,2) = IElem(src,qx,qy,0)*disk(x,y,380,300)/256; // blue at (x,y)
}
}
int main(int argc,char**argv){
Image *src=ImageRead(argv[1]),
*dst=ImageAlloc(src->W,src->H);
Process(dst,src);
ImageWrite(argv[2],dst);
return 0;
}<file_sep>/Media/Sources/easyProcess/pano0.c
// cl /Ox pano0.c image.c image2.cxx && pano0 && 0.jpg
// gcc --no-warnings -O pano0.c image.c image2.c && ./a.out && display out.jpg
#include"image.h"
// Following functions must be defined in image.c:
// ImageAlloc, ImageClear.
void ImageImageProjectionAlpha(Image*id,Image*is,double a[3][3],double alpha){
int x,y,u,v;
double r;
for(y=0;y<id->H;y++) for(x=0;x<id->W;x++){
r=1/(a[2][0]*x+a[2][1]*y+a[2][2]);
u=r*(a[0][0]*x+a[0][1]*y+a[0][2]);
v=r*(a[1][0]*x+a[1][1]*y+a[1][2]);
if( isInsideImage(is,u,v) ){
IElem(id,x,y,0)+=IElem(is,u,v,0)*alpha,
IElem(id,x,y,1)+=IElem(is,u,v,1)*alpha,
IElem(id,x,y,2)+=IElem(is,u,v,2)*alpha;
}
}
}
int main(){
Image *im,*id;
id=ImageAlloc(1024,768);
ImageClear(id);
{
double m0d[][3]={
1,0,-100,
0,1,-100,
0,0,1
};
im=ImageRead("0.jpg");
ImageImageProjectionAlpha(id,im,m0d,.5);
double m10[][3]={
0.930421, 0.018946, 118.490952,
-0.043542, 0.976597, 22.193656,
-0.000097, 0.000002, 1.000000
}, m1d[3][3];
mult33(m1d,m10,m0d);
im = ImageRead("1.jpg");
ImageImageProjectionAlpha(id,im,m1d,.5);
}
ImageWrite("out.jpg",id);
return 0;
} | de12486e656f03ab5d00515c60cdd3acf5b9315d | [
"Markdown",
"C"
] | 15 | C | a-msy/IEE-B | 83e981ea8826bb502ddd77633876aee33b4d7905 | 4582694d8b411d3d6e959d788b7f59680a778e54 |
refs/heads/master | <file_sep>Meteor.methods ({
addChat: function(otherUserId) {
if(Meteor.userId()) {
var chatId;
// find a chat that has two users that match current user id
// and the requested user id
var filter = {$or:[
{user1Id:Meteor.userId(), user2Id:otherUserId},
{user2Id:Meteor.userId(), user1Id:otherUserId}
]};
var chat = Chats.findOne(filter);
if (!chat){// no chat matching the filter - need to insert a new one
chatId = Chats.insert({user1Id:Meteor.userId(), user2Id:otherUserId});
}
else {// there is a chat going already - use that.
chatId = chat._id;
} return chatId;
} },
updateMessages: function (chatId, messages) {
Chats.update(chatId, messages);
}
}); | 638be91ff76ab264ca36a3c1b9a3b02c04c7de2f | [
"JavaScript"
] | 1 | JavaScript | choco1050/ShareEat | ef75df19522fdc2bf90376fd3a242ffd34e0ac93 | ab094a53456d13b2e736abc28a39ba23aaaf8f1b |
refs/heads/master | <repo_name>bboyle/html5-constraint-validation-API<file_sep>/test/disabled.js
(function( $ ) {
'use strict';
module( 'environment', lifecycleCVAPI );
test( 'required fields are in test form', function() {
strictEqual( $( 'form#test' ).length, 1, 'form#test is present' );
strictEqual( $( 'form#test input#foo' ).length, 1, 'form#test contains input#foo' );
strictEqual( $( 'form#test input#disabled' ).length, 1, 'form#test contains input#disabled' );
ok( $( 'input#foo' ).attr( 'required' ), 'input#foo has @required' );
ok( $( 'input#disabled' ).attr( 'required' ), 'input#disabled has @required' );
ok( $( 'input#disabled' ).attr( 'disabled' ), 'input#foo has @disabled' );
});
module( 'validityState and disabled controls', lifecycleCVAPI );
test( 'disabled controls are always valid', 3, function() {
// make disabled invalid
$( '#disabled' ).val( '' );
strictEqual( $( '#disabled' )[ 0 ].checkValidity(), true, '#disabled .checkValidity() valid' );
// strictEqual( $( '#disabled' )[ 0 ].validity.valid, true, '#disabled .validity.valid valid' ); // IE 10.0.1008.16421 disagrees
// make foo valid
$( '#disabled' ).val( 'foo' );
strictEqual( $( '#disabled' )[ 0 ].checkValidity(), true, '#disabled .checkValidity() valid' );
strictEqual( $( '#disabled' )[ 0 ].validity.valid, true, '#disabled .validity.valid valid' );
});
module( 'invalid events and disabled controls', lifecycleCVAPI );
test( 'disabled controls never trigger invalid', 0, function() {
$( '#disabled' ).bind( 'invalid.TEST', function() {
ok( false, 'invalid event detected' );
});
// make disabled invalid
$( '#disabled' ).val( '' );
$( '#disabled' )[ 0 ].checkValidity(); // should not throw any invalid events
// teardown
$( '#disabled' ).unbind( 'invalid.TEST' );
});
module( 'submit and disabled controls', lifecycleCVAPI );
test( 'disabled controls never abort submit', 1, function() {
var submitted = 0;
$( '#test' ).bind( 'submit.TEST', function() {
submitted++;
ok( submitted <= 1, 'invalid event detected' );
});
// make foo valid
$( '#foo' ).val( 'foo' );
// make disabled invalid
$( '#disabled' ).val( '' );
$( '#test' ).trigger( 'submit' ); // should succeed, even tho #disabled would be invalid (if enabled)
// teardown
$( '#test' ).unbind( 'submit.TEST' );
});
}( jQuery ));
<file_sep>/test/submit.js
(function( $ ) {
'use strict';
module( 'environment', lifecycleCVAPI );
test( 'required fields are in test form', function() {
strictEqual( $( 'form#test' ).length, 1, 'form#test is present' );
strictEqual( $( 'form#test input#foo' ).length, 1, 'form#test contains input#foo' );
ok( $( 'input#foo' ).attr( 'required' ), 'input#foo has @required' );
});
test( 'form submission is counted', 2, function() {
var form = $( '#test' ),
submitted = 0,
submitDetection = function() {
submitted++;
ok( submitted <= 2, 'counting submit event' );
};
form.bind( 'submit.TEST', submitDetection );
// make form valid
$( '#foo' ).val( 'foo' );
form.trigger( 'submit' );
form.find( ':submit' )[ 0 ].click();
// teardown
form.unbind( 'submit.TEST' );
});
module( 'form submission', lifecycleCVAPI );
test( 'submit suppressed by invalid fields', 1, function() {
var form = $( '#test' ),
submitDetection = function() {
ok( false, 'submit event was not suppressed' );
}
;
form.bind( 'submit.TEST', submitDetection );
// make foo invalid
$( '#foo' ).val( '' );
form.trigger( 'submit' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, false, '#foo is invalid' );
// teardown
form.unbind( 'submit.TEST' );
});
test( 'submit allowed after correcting all invalid fields', 3, function() {
var form = $( '#test' ),
submitted = 0,
submitDetection = function() {
submitted++;
ok( submitted <= 1, 'submit event detected' );
}
;
form.bind( 'submit.TEST', submitDetection );
// make foo invalid
$( '#foo' ).val( '' );
$( '#test' ).trigger( 'submit' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, false, '#foo is invalid' );
// make foo valid
$( '#foo' ).val( 'foo' );
$( '#test :submit' )[ 0 ].click();
strictEqual( $( '#foo' )[ 0 ].validity.valid, true, '#foo is valid' );
// teardown
form.unbind( 'submit.TEST' );
});
}( jQuery ));
<file_sep>/test/pattern.js
(function( $ ) {
'use strict';
module( 'environment', lifecycleCVAPI );
test( 'pattern fields are in test form', function() {
strictEqual( $( 'form#test' ).length, 1, 'form#test is present' );
strictEqual( $( 'form#test input#foo' ).length, 1, 'form#test contains input#foo' );
strictEqual( $( 'form#test input#bar' ).length, 1, 'form#test contains input#bar' );
strictEqual( $( 'form#test input#part' ).length, 1, 'form#test contains input#part' );
strictEqual( $( 'form#test input#email' ).length, 1, 'form#test contains input#email' );
strictEqual( $( 'form#test input#email' )[ 0 ].getAttribute( 'type' ), 'email', 'input#email is an email field' );
});
test( 'patterns are present', function() {
strictEqual( $( '[pattern]' )[ 0 ], $( 'input#foo' )[ 0 ], 'input#foo is the first field with a pattern' );
strictEqual( $( '[pattern]' )[ 1 ], $( 'input#bar' )[ 0 ], 'input#bar is the 2nd field with a pattern' );
strictEqual( $( '[pattern]' )[ 2 ], $( 'input#part' )[ 0 ], 'input#part is the 3rd field with a pattern' );
strictEqual( $( '[pattern]' )[ 3 ], $( 'input#email' )[ 0 ], 'input#email is the 4th field with a pattern' );
strictEqual( $( '#foo' ).attr( 'pattern' ), 'foo', '#foo @pattern must match /^foo$/' );
strictEqual( $( '#bar' ).attr( 'pattern' ), '.*bar.*', '#bar @pattern must match /^.*bar.*$/' );
});
module( 'input validityState patternMismatch', lifecycleCVAPI );
test( 'validityState object present', function() {
$( '#foo' ).val( '' );
$( '#foo' )[0].checkValidity();
strictEqual( typeof $( '#foo' )[0].validity, 'object', 'validityState is present' );
strictEqual( typeof $( '#foo' )[0].validity.patternMismatch, 'boolean', 'validityState.patternMismatch is present' );
strictEqual( typeof $( '#foo' )[0].validity.valid, 'boolean', 'validityState.valid is present' );
});
test( 'validity.patternMismatch is false when blank', function() {
$( '#foo' ).val( '' );
$( '#foo' )[ 0 ].checkValidity();
strictEqual( $( '#foo' )[ 0 ].validity.patternMismatch, false, '#foo[value=""] validity.patternMismatch should be false' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, true, '#foo[value=""] validity.valid should be true' );
strictEqual( $( '#foo' )[ 0 ].validationMessage, "", '#foo[value=""] validitionMessage should be ""' );
});
test( 'validity.patternMismatch is false when pattern matches value', function() {
$( '#foo' ).val( 'foo' );
$( '#foo' )[ 0 ].checkValidity();
strictEqual( $( '#foo' )[ 0 ].validity.patternMismatch, false, '#foo[value="foo"] validity.patternMismatch should be false' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, true, '#foo[value="foo"] validity.valid should be true' );
strictEqual( $( '#foo' )[ 0 ].validationMessage, "", '#foo[value=""] validitionMessage should be ""' );
});
test( 'validity.patternMismatch is true when pattern does not match value', 2, function() {
$( '#foo' ).val( 'bar' );
$( '#foo' )[ 0 ].checkValidity();
strictEqual( $( '#foo' )[ 0 ].validity.patternMismatch, true, '#foo[value="bar"] validity.patternMismatch should be true' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, false, '#foo[value="bar"] validity.valid should be false' );
// in PhantomJS, the below test fails as validationMessage is not defined
// notStrictEqual( $( '#foo' )[ 0 ].validationMessage, "", '#foo[value=""] validitionMessage should not be an empty string' );
});
test( 'validity.patternMismatch is reset when an invalid value is removed', 5, function() {
$( '#foo' ).val( 'bar' );
$( '#foo' )[ 0 ].checkValidity();
strictEqual( $( '#foo' )[ 0 ].validity.patternMismatch, true, '#foo[value="bar"] validity.patternMismatch should be true' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, false, '#foo[value="bar"] validity.valid should be false' );
// in PhantomJS, the below test fails as validationMessage is not defined
// notStrictEqual( $( '#foo' )[ 0 ].validationMessage, "", '#foo[value=""] validitionMessage should not be an empty string' );
$( '#foo' ).val( '' );
$( '#foo' )[ 0 ].checkValidity();
strictEqual( $( '#foo' )[ 0 ].validity.patternMismatch, false, '#foo[value=""] validity.patternMismatch should be false' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, true, '#foo[value=""] validity.valid should be true' );
strictEqual( $( '#foo' )[ 0 ].validationMessage, "", '#foo[value=""] validitionMessage should be ""' );
});
test( 'validity.patternMismatch toggles as value is changed', function() {
$( '#foo' ).val( 'bar' );
$( '#foo' )[ 0 ].checkValidity();
strictEqual( $( '#foo' )[ 0 ].validity.patternMismatch, true, '#foo[value="bar"] validity.patternMismatch should be true' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, false, '#foo[value="bar"] validity.valid should be false' );
$( '#foo' ).val( 'foo' );
$( '#foo' )[ 0 ].checkValidity();
strictEqual( $( '#foo' )[ 0 ].validity.patternMismatch, false, '#foo[value="foo"] validity.patternMismatch should be false' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, true, '#foo[value="foo"] validity.valid should be true' );
$( '#foo' ).val( 'bar' );
$( '#foo' )[ 0 ].checkValidity();
strictEqual( $( '#foo' )[ 0 ].validity.patternMismatch, true, '#foo[value="bar"] validity.patternMismatch should be true' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, false, '#foo[value="bar"] validity.valid should be false' );
});
module( '@pattern behaviour', lifecycleCVAPI );
test( 'patterns are anchored', function() {
$( '#foo' ).val( 'foobarfoo' );
$( '#foo' )[ 0 ].checkValidity();
strictEqual( $( '#foo' )[ 0 ].validity.patternMismatch, true, '#foo[value="foobarfoo"] validity.patternMismatch should be true' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, false, '#foo[value="foobarfoo"] validity.valid should be false' );
$( '#bar' ).val( 'bar' );
$( '#bar' )[ 0 ].checkValidity();
strictEqual( $( '#bar' )[ 0 ].validity.patternMismatch, false, '#bar[value="bar"] validity.patternMismatch should be false' );
strictEqual( $( '#bar' )[ 0 ].validity.valid, true, '#bar[value="bar"] validity.valid should be true' );
$( '#bar' ).val( 'foobarfoo' );
$( '#bar' )[ 0 ].checkValidity();
strictEqual( $( '#bar' )[ 0 ].validity.patternMismatch, false, '#bar[value="foobarfoo"] validity.patternMismatch should be false' );
strictEqual( $( '#bar' )[ 0 ].validity.valid, true, '#bar[value="foobarfoo"] validity.valid should be true' );
});
test( 'regexp parsing is correct', function() {
// valid part numbers
$.each( [ '1ABC', '3BEN', '0ZZZ' ], function( index, element ) {
$( '#part' ).val( element );
$( '#part' )[ 0 ].checkValidity();
strictEqual( $( '#part' )[ 0 ].validity.patternMismatch, false, '#part[value="' + element + '"] validity.patternMismatch should be false' );
strictEqual( $( '#part' )[ 0 ].validity.valid, true, '#part[value="' + element + '"] validity.valid should be true' );
});
// invalid part numbers
$.each( [ '0', '123', '1abc', '1ABCD', '00ZZZ' ], function( index, element ) {
$( '#part' ).val( element );
$( '#part' )[ 0 ].checkValidity();
strictEqual( $( '#part' )[ 0 ].validity.patternMismatch, true, '#part[value="' + element + '"] validity.patternMismatch should be true' );
strictEqual( $( '#part' )[ 0 ].validity.valid, false, '#part[value="' + element + '"] validity.valid should be false' );
});
});
test( 'email @pattern', function() {
// valid email patterns
$.each( [ '<EMAIL>', '<EMAIL>' ], function( index, element ) {
$( '#email' ).val( element );
$( '#email' )[ 0 ].checkValidity();
strictEqual( $( '#email' )[ 0 ].validity.typeMismatch, false, '#email[value="' + element + '"] validity.typeMismatch should be false' );
strictEqual( $( '#email' )[ 0 ].validity.patternMismatch, false, '#email[value="' + element + '"] validity.patternMismatch should be false' );
strictEqual( $( '#email' )[ 0 ].validity.valid, true, '#email[value="' + element + '"] validity.valid should be true' );
});
// invalid email patterns
$.each( [ '<EMAIL>', '<EMAIL>' ], function( index, element ) {
$( '#email' ).val( element );
$( '#email' )[ 0 ].checkValidity();
strictEqual( $( '#email' )[ 0 ].validity.typeMismatch, false, '#email[value="' + element + '"] validity.typeMismatch should be false' );
strictEqual( $( '#email' )[ 0 ].validity.patternMismatch, true, '#email[value="' + element + '"] validity.patternMismatch should be true' );
strictEqual( $( '#email' )[ 0 ].validity.valid, false, '#email[value="' + element + '"] validity.valid should be false' );
});
// invalid email address
$.each( [ 'foo', '@' ], function( index, element ) {
$( '#email' ).val( element );
$( '#email' )[ 0 ].checkValidity();
strictEqual( $( '#email' )[ 0 ].validity.typeMismatch, true, '#email[value="' + element + '"] validity.typeMismatch should be true' );
strictEqual( $( '#email' )[ 0 ].validity.patternMismatch, true, '#email[value="' + element + '"] validity.patternMismatch should be true' );
strictEqual( $( '#email' )[ 0 ].validity.valid, false, '#email[value="' + element + '"] validity.valid should be false' );
});
});
}( jQuery ));
<file_sep>/test/change.js
(function( $ ) {
'use strict';
module( 'environment', lifecycleCVAPI );
test( 'required fields are in test form', function() {
strictEqual( $( 'form#test' ).length, 1, 'form#test is present' );
strictEqual( $( 'form#test input#foo' ).length, 1, 'form#test contains input#foo' );
ok( $( 'input#foo' ).attr( 'required' ), 'input#foo has @required' );
strictEqual( $( 'form#test :radio[name=flavour]#flavour-chocolate' ).length, 1, 'found :radio[name=flavour]#flavour-chocolate' );
strictEqual( $( 'form#test :radio[name=flavour]#flavour-strawberry' ).length, 1, 'found :radio[name=flavour]#flavour-strawberry' );
strictEqual( $( 'form#test :radio[name=flavour]#flavour-vanilla' ).length, 1, 'found :radio[name=flavour]#flavour-vanilla' );
strictEqual( $( 'form#test select#select-flavour' ).length, 1, 'found select#select-flavour' );
ok( $( 'select#select-flavour' ).attr( 'required' ), 'select#select-flavour is required' );
});
module( 'text onchange', lifecycleCVAPI );
test( 'validity flagged onchange', 2, function() {
// make foo invalid
$( '#foo' ).val( '' ).trigger( 'change' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, false, '#foo is invalid' );
// make foo valid
$( '#foo' ).val( 'foo' ).trigger( 'change' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, true, '#foo is valid' );
});
module( 'radio onchange', lifecycleCVAPI );
test( 'validity flagged onchange', 6, function() {
$( '#flavour-chocolate' ).trigger( 'change' );
strictEqual( $( '#flavour-chocolate' )[ 0 ].validity.valid, false, '#flavour-chocolate is invalid' );
strictEqual( $( '#flavour-strawberry' )[ 0 ].validity.valid, false, '#flavour-strawberry is invalid' );
strictEqual( $( '#flavour-vanilla' )[ 0 ].validity.valid, false, '#flavour-vanilla is invalid' );
// make valid
$( '#flavour-chocolate' )[ 0 ].click(); // triggers change? not in IE6!
$( '#flavour-chocolate' ).trigger( 'change' );
strictEqual( $( '#flavour-chocolate' )[ 0 ].validity.valid, true, '#flavour-chocolate is valid' );
strictEqual( $( '#flavour-strawberry' )[ 0 ].validity.valid, true, '#flavour-strawberry is valid' );
strictEqual( $( '#flavour-vanilla' )[ 0 ].validity.valid, true, '#flavour-vanilla is valid' );
});
module( 'select onchange', lifecycleCVAPI );
test( 'validity flagged onchange', 2, function() {
$( '#select-flavour' ).trigger( 'change' );
strictEqual( $( '#select-flavour' )[ 0 ].validity.valid, false, '#select-flavour is invalid' );
// make valid
$( '#select-flavour' )[ 0 ].selectedIndex = 1; // triggers change? nope
$( '#select-flavour' ).trigger( 'change' ); // triggers change?
strictEqual( $( '#select-flavour' )[ 0 ].validity.valid, true, '#select-flavour is valid' );
});
}( jQuery ));
<file_sep>/README.md
[](https://travis-ci.org/bboyle/html5-constraint-validation-API)
[](https://david-dm.org/bboyle/html5-constraint-validation-API#info=devDependencies)
[](https://saucelabs.com/u/benboyle-h5cvapi)
A partial polyfill for the HTML5 constraint validation API (form validation). Requires jQuery. Intended for use with jquery form validation UI scripts.
## Features implemented
* handle `@required` on `:text`, `textarea`, `select` and `:radio` controls
* fire `invalid` events
* support `form@novalidate`
* support `@type=email` and `validityState.typeMismatch`
* support `.setCustomValidity( message )`
* support `@pattern` and `validityState.patternMismatch`
<file_sep>/test/email.js
(function( $ ) {
'use strict';
function testEmail( value, valid ) {
var email = $( '#email' );
if ( valid !== false ) {
valid = true;
}
email.val( value );
email[ 0 ].checkValidity();
strictEqual( ! email[ 0 ].validity.typeMismatch, valid, value + ' is valid' );
}
module( 'environment', lifecycleCVAPI );
test( 'email fields are in test form', function() {
strictEqual( $( 'form#test' ).length, 1, 'form#test is present' );
strictEqual( $( 'form#test input#foo' ).length, 1, 'form#test contains input#foo' );
strictEqual( $( 'form#test input#email' ).length, 1, 'form#test contains input#email' );
});
test( 'email fields are type email', function() {
strictEqual( $( '#foo' )[ 0 ].type, 'text', 'input#foo is type text' );
strictEqual( $( '#email' )[ 0 ].getAttribute( 'type' ), 'email', 'input#email is type email' );
});
module( 'input validityState typeMismatch', lifecycleCVAPI );
test( 'validity.typeMismatch is false when blank', function() {
$( '#email,#foo' ).val( '' );
$( '#email' )[ 0 ].checkValidity();
$( '#foo' )[ 0 ].checkValidity();
strictEqual( $( '#email' )[ 0 ].validity.typeMismatch, false, '#email[value=""] validity.typeMismatch should be false' );
strictEqual( $( '#email' )[ 0 ].validity.valid, true, '#email[value=""] validity.valid should be true' );
strictEqual( $( '#foo' )[ 0 ].validity.typeMismatch, false, '#foo[value=""] validity.typeMismatch should be false' );
});
test( 'validity.typeMismatch is true when value is not an email address', function() {
$( '#email, #foo' ).val( 'foo' );
$( '#email' )[ 0 ].checkValidity();
$( '#foo' )[ 0 ].checkValidity();
strictEqual( $( '#email' )[ 0 ].validity.typeMismatch, true, '#email[value="foo"] validity.typeMismatch should be true' );
strictEqual( $( '#email' )[ 0 ].validity.valid, false, '#email[value=""] validity.valid should be false' );
strictEqual( $( '#foo' )[ 0 ].validity.typeMismatch, false, '#foo[value="foo"] validity.typeMismatch should be false' );
});
test( 'validity.typeMismatch is false when an email address is supplied', function() {
$( '#email,#foo' ).val( '<EMAIL>' );
$( '#email' )[ 0 ].checkValidity();
$( '#foo' )[ 0 ].checkValidity();
strictEqual( $( '#email' )[ 0 ].validity.typeMismatch, false, '#email[value="<EMAIL>"] validity.typeMismatch should be false' );
strictEqual( $( '#email' )[ 0 ].validity.valid, true, '#email[value=""] validity.valid should be true' );
strictEqual( $( '#foo' )[ 0 ].validity.typeMismatch, false, '#foo[value="<EMAIL>"] validity.typeMismatch should be false' );
});
test( 'standard email formats', 2, function() {
var formats = [
'<EMAIL>',
'<EMAIL>'
];
$.each( formats, function( indexInArray, valueOfElement ) {
testEmail( valueOfElement );
});
});
test( 'unusual email formats', 1, function() {
var formats = [
// TODO why do these fail in PhantomJS?
// 'foo@localhost',
// 'a@b',
'foo@127.0.0.1'
];
$.each( formats, function( indexInArray, valueOfElement ) {
testEmail( valueOfElement );
});
});
test( 'allowed complex email formats', 4, function() {
// http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
var formats = [
'customer/department=<EMAIL>',
'<EMAIL>',
'!def!xyz%<EMAIL>',
'_<EMAIL>'
];
$.each( formats, function( indexInArray, valueOfElement ) {
testEmail( valueOfElement );
});
});
test( 'disallowed complex email formats', 4, function() {
// html5 does not allow these formats
// http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
// http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
var formats = [
'"<EMAIL>"@<EMAIL>',
'"<NAME>"<EMAIL>',
'"Joe\\\\Blow"<EMAIL>',
'"<EMAIL>"@<EMAIL>'
];
$.each( formats, function( indexInArray, valueOfElement ) {
testEmail( valueOfElement, false );
});
});
}( jQuery ));
<file_sep>/test/checkValidity.js
(function( $ ) {
'use strict';
module( 'environment', lifecycleCVAPI );
test( 'required fields are in test form', 4, function() {
strictEqual( $( 'form#test' ).length, 1, 'form#test is present' );
strictEqual( $( 'form#test input#foo' ).length, 1, 'form#test contains input#foo' );
ok( $( 'input#foo' ).attr( 'required' ), 'input#foo has @required' );
strictEqual( $( 'input#foo' ).val(), '', 'input#foo has no initial value' );
});
module( '.checkValidity() reflects validity', lifecycleCVAPI );
test( 'invalid fields return false', 2, function() {
strictEqual( $( '#foo' )[ 0 ].checkValidity(), false, '.checkValidity() false for blank required field' );
strictEqual( $( '#foo' )[ 0 ].validity.valid, false, '.validity.valid false for blank required field' );
});
module( '.checkValidity() triggers invalid events', lifecycleCVAPI );
test( 'invalid fields trigger events', 3, function() {
// setup - detect invalid events
var invalidDetectedOnFoo = 0;
$( '#foo' ).bind( 'invalid.TEST', function() {
invalidDetectedOnFoo++;
strictEqual( invalidDetectedOnFoo, 1, 'invalid event detected on foo' );
});
strictEqual( $( '#foo' )[ 0 ].checkValidity(), false, 'foo is invalid' );
// make it valid
$( '#foo' ).val( 'foo' );
strictEqual( $( '#foo' )[ 0 ].checkValidity(), true, 'foo is valid' );
// teardown
$( '#foo' ).unbind( 'invalid.TEST' );
});
}( jQuery ));
| 2d62c3d69401420a25b7ddc3394aa118d3fbe013 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | bboyle/html5-constraint-validation-API | 8a660e606471a3bd07b84f5a7f8885841686caba | 1d8124c0cf7c9f1a7ad6ecf3ea87ec57d077fae5 |
refs/heads/master | <file_sep>from sympy import *
import math
import sympy
x=symbols("x")
expr=((x**2)-1)
n=input("Pick a number to raise and differentiate our function to ")
RaisedExpr=expand(expr**n)
while n>0:
value=sympy.diff(RaisedExpr,x)
n=n-1
RaisedExpr=value
print value | d2fbd6a14126cc0e6cda5ce206dbafb2c1d333c0 | [
"Python"
] | 1 | Python | sarahbonne/hello-darling | f568b7d3d875f1b7b575f953f779fe7bcfb42fe5 | 3b978d4d15d0f073f72fdf0fd015305950ccb3ba |
refs/heads/master | <repo_name>wgamagomes/sgm-sac-backend<file_sep>/dotnet-packages/sac/src/SGM.SAC.Domain/QuerySide/QueryHandlers/PropertyTaxQueryHandler.cs
๏ปฟusing MediatR;
using Newtonsoft.Json;
using SGM.SAC.Domain.Dto;
using SGM.SAC.Domain.HttpResponse;
using SGM.SAC.Domain.QuerySide.Queries;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace SGM.SAC.Domain.QuerySide.QueryHandlers
{
public class PropertyTaxQueryHandler : IRequestHandler<PropertyTaxQuery, PropertyTaxResult>
{
private readonly HttpClient _httpClient;
private readonly string _remoteServiceBaseUrl;
public PropertyTaxQueryHandler(HttpClient httpClient)
{
_httpClient = httpClient;
_remoteServiceBaseUrl = httpClient.BaseAddress.ToString();
}
public async Task<PropertyTaxResult> Handle(PropertyTaxQuery request, CancellationToken cancellationToken)
{
string responseString;
if (!request.IsRuralTax)
responseString = await _httpClient.GetStringAsync($"{_remoteServiceBaseUrl}/iptu/{request.PropertyRegistration}");
else
responseString = await _httpClient.GetStringAsync($"{_remoteServiceBaseUrl}/itr/{request.PropertyRegistration}");
var result = JsonConvert.DeserializeObject<PropertyTaxHttpResponse>(responseString);
result.PropertyRegistration = request.PropertyRegistration;
return PropertyTaxResult.Create(result);
}
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Infra.Data/Mongo/Contexts/GEPContextMongo.cs
๏ปฟusing MongoDB.Driver;
namespace SGM.GEP.Infra.Data.Mongo.Contexts
{
public class GEPContextMongo: BaseMongoContext
{
public GEPContextMongo(string connectionString)
: base(connectionString)
{
}
//public IMongoCollection<WhateverEntity> Projects => GetCollection<WhateverEntity>(Database);
}
}
<file_sep>/containers/api-sac/src/Filters/CustomAuthorize.cs
๏ปฟusing Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Linq;
using System.Security.Claims;
namespace SGM.SAC.Api.Filters
{
public class CustomAuthorizeAttribute : TypeFilterAttribute
{
public CustomAuthorizeAttribute(params string[] roles) : base(typeof(ClaimFilter))
{
Arguments = new Claim[] { new Claim(ClaimTypes.Role, string.Join(',', roles)) };
}
}
public class ClaimFilter : IAuthorizationFilter
{
private readonly Claim _claim;
public ClaimFilter(Claim claim)
{
_claim = claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
context.Result = new StatusCodeResult(401);
return;
}
if (!ValidateUserClaims(context.HttpContext, _claim.Type, _claim.Value))
{
context.Result = new StatusCodeResult(403);
}
}
public bool ValidateUserClaims(HttpContext context, string claimName, string claimValue)
{
bool authorized = false;
var allowedroles = claimValue.Split(',');
foreach (var role in allowedroles)
{
authorized = context.User.Claims.Any(c => c.Type == claimName && c.Value== role);
if (authorized)
break;
}
return authorized;
}
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Domain/HttpResponse/PropertyTaxHttpResponse.cs
๏ปฟusing System;
namespace SGM.SAC.Domain.HttpResponse
{
public class PropertyTaxHttpResponse
{
public int Id { get; set; }
public string PropertyRegistration { get; set; }
public bool IsRuralTax { get; set; }
public bool Succeeded { get; set; }
public string Content { get; set; }
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Domain/Dto/PropertyTaxDto.cs
๏ปฟnamespace SGM.SAC.Domain.Dto
{
public class PropertyTaxDto
{
public int Id { get; set; }
public string PropertyRegistration { get; set; }
public bool IsRuralTax { get; set; }
public bool Succeeded { get; set; }
public string Content { get; set; }
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Domain/Entities/Entity.cs
๏ปฟusing System;
namespace SGM.SAC.Domain.Entities
{
public class Entity
{
public Guid Id { get; private set; }
public DateTime LastUpdate { get; set; }
public DateTime InsertedAt { get; set; }
protected Entity()
{
Id = Guid.NewGuid();
InsertedAt = DateTime.UtcNow;
}
}
}<file_sep>/dotnet-packages/sac/src/SGM.SAC.Infra.Data/Mongo/Log/Logger.cs
๏ปฟusing SGM.GEP.Infra.Data.Mongo.Contexts;
using SGM.SAC.Domain.Infra.Logger;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace SGM.GEP.Infra.Data.Mongo.Log
{
public class Logger : ILogger
{
private readonly GEPContextMongo _context;
public Logger(GEPContextMongo context)
{
_context = context;
}
public async Task DebugAsync(string message, CancellationToken cancellationToken)
{
await _context.GetCollection<Log>().InsertOneAsync(new Log
{
Level = "Debug",
ErrorMessage = message
}
, cancellationToken: cancellationToken);
}
public async Task ErrorAsync(string message, Exception exception, CancellationToken cancellationToken)
{
await _context.GetCollection<Log>().InsertOneAsync(new Log
{
Level = "Error",
ErrorMessage = exception.Message,
Message = message,
StackTrace = exception.StackTrace,
InnerExceptionMessage = exception.InnerException?.Message
}
, cancellationToken: cancellationToken);
}
public async Task InfoAsync(string message, CancellationToken cancellationToken)
{
await _context.GetCollection<Log>().InsertOneAsync(new Log
{
Level = "Info",
ErrorMessage = message
}
, cancellationToken: cancellationToken);
}
public async Task WarnAsync(string message, CancellationToken cancellationToken)
{
await _context.GetCollection<Log>().InsertOneAsync(new Log
{
Level = "Warn",
ErrorMessage = message
}
, cancellationToken: cancellationToken);
}
public async Task LogAsync(LogLevel level, string message, CancellationToken cancellationToken, Exception exception = null)
{
switch (level)
{
case LogLevel.Error:
await ErrorAsync(message, exception, cancellationToken);
break;
case LogLevel.Warning:
await WarnAsync(message, cancellationToken);
break;
case LogLevel.Info:
await InfoAsync(message, cancellationToken);
break;
case LogLevel.Debug:
await DebugAsync(message, cancellationToken);
break;
default:
break;
}
}
}
}
<file_sep>/README.md
# sgm-sac-module
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Infra.Data/Mongo/Utils/UtcDateTimeSerializer.cs
๏ปฟusing MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using System;
namespace SGM.GEP.Infra.Data.Mongo.Utils
{
public class UtcDateTimeSerializer : DateTimeSerializer
{
public override DateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var value = base.Deserialize(context, args);
return DateTime.SpecifyKind(value, DateTimeKind.Utc);
}
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTime value)
{
value = DateTime.SpecifyKind(value, DateTimeKind.Utc);
base.Serialize(context, args, value);
}
}
}<file_sep>/dotnet-packages/sac/src/SGM.SAC.Infra.Data/EF/Contexts/SACContextEF.cs
๏ปฟusing Microsoft.EntityFrameworkCore;
namespace SGM.SAC.Infra.Data.Contexts.EF
{
public class SACContextEF : DbContext
{
public SACContextEF(DbContextOptions options)
:base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Domain/Dto/PropertyTaxResult.cs
๏ปฟusing SGM.SAC.Domain.HttpResponse;
namespace SGM.SAC.Domain.Dto
{
public class PropertyTaxResult
{
public PropertyTaxDto PropertyTax { get; private set; }
public static PropertyTaxResult Create(PropertyTaxHttpResponse httpResponse) => new PropertyTaxResult
{
PropertyTax = new PropertyTaxDto
{
PropertyRegistration = httpResponse.PropertyRegistration,
Content = httpResponse.Content,
Id = httpResponse.Id,
Succeeded = httpResponse.Succeeded,
IsRuralTax = httpResponse.IsRuralTax,
}
};
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Infra.Data/Mongo/Utils/MongoConnection.cs
๏ปฟusing MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
namespace SGM.GEP.Infra.Data.Mongo.Utils
{
public static class MongoConnection
{
private static readonly object Lock = new object();
private static bool _isRegistered;
private static readonly Dictionary<string, IMongoDatabase> Databases = new Dictionary<string, IMongoDatabase>();
public static IMongoDatabase GetDatabase(string connectionString)
{
var conn = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
lock (Lock)
{
Databases.TryGetValue(conn, out var database);
if (database != null) return database;
var urlBuilder = new MongoUrlBuilder(conn);
var databaseName = urlBuilder.DatabaseName;
if (databaseName == null)
databaseName = GetDatabaseNameDefault();
var client = new MongoClient(urlBuilder.ToMongoUrl());
database = client.GetDatabase(databaseName);
Register();
Databases[conn] = database;
return database;
}
}
private static void Register()
{
var conventionPack = new ConventionPack { new IgnoreExtraElementsConvention(true) };
ConventionRegistry.Register("IgnoreElements", conventionPack, type => true);
if (!_isRegistered)
{
BsonSerializer.RegisterSerializer(typeof(DateTime), new UtcDateTimeSerializer());
_isRegistered = true;
}
}
internal static string GetDatabaseNameDefault()
{
return $"SGM_GEP";
}
}
}<file_sep>/dotnet-packages/sac/src/SGM.SAC.Infra.Crosscutting/Startup/IStartup.cs
๏ปฟusing Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
namespace SGM.GEP.Infra.Crosscutting.Startup
{
public interface IStartup
{
void ConfigureServices(IServiceCollection services, IConfiguration config);
void ScheduleJobs(IScheduler scheduler);
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Domain/Extensions/AssertArgumentExtensions.cs
๏ปฟnamespace SGM.SAC.Domain.Extensions
{
public static class AssertArgumentExtensions
{
public static bool AssertArgumentIsEmpty(this string value) => (string.IsNullOrWhiteSpace(value));
public static bool AssertArgumentIsNull(this object @object) => @object == null;
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Infra.Data/Mongo/Repositories/GenericRepository.cs
๏ปฟusing MongoDB.Driver;
using SGM.SAC.Domain.Entities;
using SGM.SAC.Domain.Interfaces.Repositories;
using SGM.GEP.Infra.Data.Mongo.Contexts;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace SGM.SAC.Infra.Data.Mongo.Repositories
{
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : Entity
{
private readonly GEPContextMongo _context;
public GenericRepository(GEPContextMongo context)
{
_context = context;
}
public async Task AddAsync(TEntity entity, CancellationToken cancellationToken)
{
await _context.GetCollection<TEntity>().InsertOneAsync(entity, cancellationToken: cancellationToken);
}
public IQueryable<TEntity> GetAll()
{
return _context.GetCollection<TEntity>().AsQueryable();
}
public async Task<TEntity> GetByFilterAsync(Expression<Func<TEntity, bool>> filter, CancellationToken cancellationToken)
{
var queryResut = await _context.GetCollection<TEntity>().FindAsync(filter, cancellationToken: cancellationToken);
return await queryResut.FirstOrDefaultAsync(cancellationToken);
}
public async Task<TEntity> GetByIdAsync(Guid id, CancellationToken cancellationToken)
{
var queryResut = await _context.GetCollection<TEntity>().FindAsync(f => f.Id == id, cancellationToken: cancellationToken);
return await queryResut.FirstOrDefaultAsync(cancellationToken);
}
}
}
<file_sep>/containers/api-sac/src/Controllers/CitizenServiceController.cs
๏ปฟusing MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Polly.CircuitBreaker;
using SGM.SAC.Api.Constants;
using SGM.SAC.Api.Filters;
using SGM.SAC.Api.Models;
using SGM.SAC.Domain.QuerySide.Queries;
using System.Threading.Tasks;
namespace SGM.SAC.Api.Controllers
{
[ApiController]
[CustomAuthorize("admin", "citizen")]
[Route("[controller]")]
public class CitizenServiceController : ControllerBase
{
private readonly ILogger<CitizenServiceController> _logger;
private readonly IMediator _mediator;
public CitizenServiceController(ILogger<CitizenServiceController> logger, IMediator mediator)
{
_logger = logger;
_mediator = mediator;
}
[HttpPost]
[Route(Routes.PropertyTaxRoute)]
public async Task<ActionResult> GetPropertyTax([FromBody] PropertyTaxRequest request)
{
try
{
var result = await _mediator.Send(PropertyTaxQuery.Create(request.PropertyRegistration, (bool)request.IsRuralTax));
if (result == null)
return NotFound("Property tax was not found.");
return Ok(result);
}
catch (BrokenCircuitException)
{
return Problem("Service is inoperative, please try later on.", statusCode: 500);
}
}
}
}
<file_sep>/containers/api-sac/src/Constants/Routes.cs
๏ปฟnamespace SGM.SAC.Api.Constants
{
public static class Routes
{
public const string PropertyTaxRoute = "getPropertyTax";
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Infra.Data/Mongo/Log/Log.cs
๏ปฟusing SGM.SAC.Domain.Entities;
namespace SGM.GEP.Infra.Data.Mongo.Log
{
public class Log: Entity
{
public string StackTrace { get; set; }
public string ErrorMessage { get; set; }
public string InnerExceptionMessage { get; set; }
public string Level { get; set; }
public string Message { get; internal set; }
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Domain/Logger/ILogger.cs
๏ปฟusing System;
using System.Threading;
using System.Threading.Tasks;
namespace SGM.SAC.Domain.Infra.Logger
{
public interface ILogger
{
Task DebugAsync(string message, CancellationToken cancellationToken);
Task InfoAsync(string message, CancellationToken cancellationToken);
Task WarnAsync(string message, CancellationToken cancellationToken);
Task ErrorAsync(string message, Exception exception, CancellationToken cancellationToken);
Task LogAsync(LogLevel level, string message, CancellationToken cancellationToken , Exception exception = null);
}
public enum LogLevel
{
Error = 0,
Warning = 1,
Info = 2,
Debug = 3
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Infra.Data/Mongo/Contexts/BaseMongoContext.cs
๏ปฟusing MongoDB.Bson.Serialization;
using MongoDB.Driver;
using SGM.GEP.Infra.Data.Mongo.Utils;
using System.Linq;
namespace SGM.GEP.Infra.Data.Mongo.Contexts
{
public abstract class BaseMongoContext : IMongoContext
{
protected BaseMongoContext(string connectionString)
{
Database = MongoConnection.GetDatabase(connectionString);
Configuring();
}
public IMongoDatabase Database { get; }
protected virtual void Configure()
{
}
protected void Register<T>()
{
if (!BsonClassMap.IsClassMapRegistered(typeof(T)))
{
BsonClassMap.RegisterClassMap<T>();
}
}
private void Configuring()
{
Configure();
}
public IMongoCollection<T> GetCollection<T>(string name = null)
{
return name != null ? Database.GetCollection<T>(name) : GetCollection<T>(Database);
}
public IMongoCollection<T> GetCollection<T>(IMongoDatabase session)
{
var attrs = typeof(T).GetCustomAttributes(typeof(CollectionNameAttribute), false).OfType<CollectionNameAttribute>().FirstOrDefault();
var collectionName = attrs?.Name ?? typeof(T).Name;
return session.GetCollection<T>(collectionName);
}
}
}<file_sep>/containers/api-sac/src/Models/PropertyTaxRequest.cs
๏ปฟnamespace SGM.SAC.Api.Models
{
public class PropertyTaxRequest
{
public string PropertyRegistration { get; set; }
public bool? IsRuralTax { get; set; }
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Infra.Data/Mongo/Contexts/IMongoContext.cs
๏ปฟusing MongoDB.Driver;
namespace SGM.GEP.Infra.Data.Mongo.Contexts
{
public interface IMongoContext
{
IMongoDatabase Database { get; }
}
}<file_sep>/containers/api-sac/src/Models/Validators/PropertyTaxRequestValidator.cs
๏ปฟusing FluentValidation;
namespace SGM.SAC.Api.Models.Validators
{
public class PropertyTaxRequestValidator : AbstractValidator<PropertyTaxRequest>
{
public PropertyTaxRequestValidator()
{
RuleFor(r => r.PropertyRegistration)
.NotEmpty()
.WithMessage("Invalid PropertyRegistration value, should not be null or empty.");
RuleFor(r => r.IsRuralTax)
.NotNull()
.WithMessage("Invalid IsRuralTax flag value, should not be null.");
}
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Domain/Interfaces/Repositories/IGenericRepository.cs
๏ปฟusing SGM.SAC.Domain.Entities;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace SGM.SAC.Domain.Interfaces.Repositories
{
public interface IGenericRepository<TEntity>
where TEntity : Entity
{
Task AddAsync(TEntity entity, CancellationToken cancellationToken);
Task<TEntity> GetByIdAsync(Guid id, CancellationToken cancellationToken);
IQueryable<TEntity> GetAll();
Task<TEntity> GetByFilterAsync(Expression<Func<TEntity, bool>> filter, CancellationToken cancellationToken);
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Domain/QuerySide/Queries/PropertyTaxQuery.cs
๏ปฟusing MediatR;
using SGM.SAC.Domain.Dto;
namespace SGM.SAC.Domain.QuerySide.Queries
{
public class PropertyTaxQuery: IRequest<PropertyTaxResult>
{
public string PropertyRegistration { get; private set; }
public bool IsRuralTax { get; private set; }
public static PropertyTaxQuery Create(string propertyRegistration, bool isRuralTax) => new PropertyTaxQuery { PropertyRegistration = propertyRegistration, IsRuralTax = isRuralTax };
}
}
<file_sep>/dotnet-packages/sac/src/SGM.SAC.Infra.Data/Mongo/Utils/CollectionNameAttribute.cs
๏ปฟusing System;
namespace SGM.GEP.Infra.Data.Mongo.Utils
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class CollectionNameAttribute : Attribute
{
public string Name { get; private set; }
public CollectionNameAttribute(string name)
{
Name = name;
}
}
}<file_sep>/dotnet-packages/sac/src/SGM.SAC.Infra.Crosscutting/BootStrappings/ServicesBootStrap.cs
๏ปฟusing MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Polly;
using Polly.Extensions.Http;
using SGM.SAC.Domain.Dto;
using SGM.SAC.Domain.QuerySide.Queries;
using SGM.SAC.Domain.QuerySide.QueryHandlers;
using SGM.SAC.Domain.Settings;
using System;
using System.Net.Http;
using System.Text;
namespace SGM.SAC.Infra.Crosscutting.Bootstrappings
{
public class ServicesBootStrap
{
protected ServicesBootStrap() { }
public static void RegisterServices(IServiceCollection services, IConfiguration config)
{
// MediatR
services.AddMediatR(typeof(ServicesBootStrap).Assembly);
// Settings
var authSettingsSection = config.GetSection("AuthSettings");
services.Configure<AuthSettings>(authSettingsSection);
var authSettings = authSettingsSection.Get<AuthSettings>();
var key = Encoding.ASCII.GetBytes(authSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
// Query Handlers
services.AddHttpClient<IRequestHandler<PropertyTaxQuery, PropertyTaxResult>, PropertyTaxQueryHandler>(client =>
{
client.BaseAddress = new Uri(config.GetSection("BaseAddress").Value);
}).AddPolicyHandler(GetRetryPolicy())
.AddPolicyHandler(GetCircuitBreakerPolicy());
}
static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}
static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.CircuitBreakerAsync(3, TimeSpan.FromSeconds(30));
}
}
}
| 08ec7ac26afc9bdb6bfcc35fca388f6d4c1460b8 | [
"Markdown",
"C#"
] | 27 | C# | wgamagomes/sgm-sac-backend | be435134490cba685fd5632059e24f7d45741129 | fdca50a27f5cbe5823b78f15cbbc8325e4989848 |
refs/heads/main | <file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int num;
system("cls");
cout<<"Enter the Number:";
cin>>num;
int fact = 1;
for(int i=1;i<=num;i++)
{
fact = fact*i;
}
cout<<"The factorial of"<<ends<<num<<ends<<"is:"<<fact<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int num;
cout<<"Enter the number:";
cin>>num;
int temp = num,sum = 0;
for(int i = 1;i < temp;i++)
{
if(temp%i == 0)
{
sum = sum+i;
}
}
if(sum == num)
{
printf("PERFECT NUMBER.");
}
else
printf("NOT A PERFECT NUMBER.");
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int max(int b[], int x)
{
int large = b[0];
for(int i=1;i<x;i++)
{
if(b[i] > large)
{
large = b[i];
}
}
cout<<"LARGE:"<<large<<endl;
}
int main()
{
int n;
cout<<"Enter the no. of Elements:";
cin>>n;
int a[n];
cout<<"The Elements are"<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
max(a,n);
}
<file_sep>#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
long n;
long a = 0,b = 1,c;
cout<<"Enter the series:";
cin>>n;
for(int i=0;i<=n;i++)
{
cout<<a<<endl;
c = a+b;
a = b;
b = c;
}
getch();
}
<file_sep>#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int n,sum = 0;
cout<<"Enter the number:";
cin>>n;
sum = (n*(n+1)/2);
cout<<"SUM:"<<sum<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int l,u;
cout<<"Enter the Lower limit:";
cin>>l;
cout<<"Enter the Upper Limit:";
cin>>u;
if(l>u)
{
cout<<"NOT POSSIBLE."<<endl;
}
else
{
for(int i = l;i <= u;i++)
{
int temp = i,sum = 0;
for(int j = 1;j < temp;j++)
{
if(temp%j == 0)
{
sum = sum+j;
}
}
if(sum == i)
{
cout<<i<<endl;
}
}
}
getch();
}
<file_sep>#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int num,i = 2;
int flag = 0;
cout<<"Enter the number:";
cin>>num;
do
{
if(num%i == 0)
{
flag = 1;
}
i++;
}
while(i<=num/2);
if(flag == 1)
{
cout<<num<<ends<<"is not a prime number."<<endl;
}
else
cout<<num<<ends<<"is a prime number."<<endl;
getch();
}
<file_sep>#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;
int main()
{
int l,u;
int flag;
cout<<"Enter the LOWER LIMIT:";
cin>>l;
cout<<"Enter the UPPER LIMIT:";
cin>>u;
for(int i=l;i<=u;i++)
{
if(i == 0||i == 1)
continue;
flag = 0;
for(int j=2;j<=i/2;j++)
{
if(i%j == 0)
{
flag = 1;
}
}
if(flag == 0)
{
cout<<i<<endl;
}
}
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int num;
cout<<"Enter the Number:";
cin>>num;
int sum = 0;
for(int i = 1;i < num;i++)
{
if(num%i == 0)
{
sum = sum+i;
}
}
if(sum>num)
{
cout<<"ABUNDANT NUMBER."<<endl;
}
else
cout<<"NOT AN ABUNDANT NUMBER."<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int num;
cout<<"Enter the number:";
cin>>num;
int rem = 0,sum = 0;
int temp = num;
while(temp!=0)
{
rem = temp%10;
sum = sum+rem;
temp = temp/10;
}
if(num%sum == 0)
{
cout<<"HARSHAD NUMBER."<<endl;
}
else
cout<<"NOT AN HARSHAD NUMBER."<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int SWAP2BEST(int brr[], int x)
{
for(int i=0;i<x;i++)
{
int temp = 0;
if(brr[i]%10==0)
{
temp = brr[i];
brr[i] = brr[i+1];
brr[i+1] = temp;
i++;
}
}
cout<<"AFTER CHANGES"<<endl;
for(int i=0;i<x;i++)
{
cout<<brr[i]<<endl;
}
}
int main()
{
int n;
cout<<"Enter the size of the array:";
cin>>n;
int arr[n];
cout<<"The Elements are:"<<endl;
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
cout<<"BEFORE CHANGES"<<endl;
for(int i=0;i<n;i++)
{
cout<<arr[i]<<endl;
}
SWAP2BEST(arr,n);
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int main()
{
system("cls");
int n;
cout<<"Enter the natural numbers whose sum is to be calculated:";
cin>>n;
int sum = 0;
for(int i=1;i<=n;i++)
{
sum+=i;
}
cout<<"SUM:"<<sum<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int l,u;
cout<<"Enter the Lower Number:";
cin>>l;
cout<<"Enter the Upper Number:";
cin>>u;
for(int i = l;i <= u;i++)
{
int temp = i,rem = 0,sum = 0;
while(temp!=0)
{
rem = temp%10;
int fact = 1;
for(int j = 1;j <= rem;j++)
{
fact = fact*j;
}
sum = sum+fact;
temp = temp/10;
}
if(sum == i)
{
cout<<i<<endl;
}
}
getch();
}
<file_sep>#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int a,b,c;
cout<<"Enter the value of a b and c"<<endl;
cin>>a>>b>>c;
if(a>b && a>c)
{
cout<<a<<" is Greater than "<<b<<" and "<<c<<endl;
}
else if(b>c && b>a)
{
cout<<b<<" is Greater than "<<a<<" and "<<c<<endl;
}
else if(c>a && c>b)
{
cout<<c<<" is Greater than "<<a<<" and "<<b<<endl;
}
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
char str[40];
cin>>str;
int length = 0;
for(int i = 0;str[i] != '\0';i++)
{
length++;
}
for(int i = length-1;i >= 0;i--)
{
cout<<str[i];
}
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int main()
{
system("cls");
int number;
cout<<"Enter the Number:";
cin>>number;
if(number>0)
{
cout<<"The Number"<<ends<<number<<ends<<"is POSITIVE"<<endl;
}
else if(number==0)
{
cout<<"ZERO is entered"<<endl;
}
else
cout<<"The Number"<<ends<<number<<ends<<"is NEGATIVE"<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int main()
{
int year;
cout<<"Enter the Year : ";
cin>>year;
if((year%400 == 0) || (year%4 == 0 && year%100 != 0) )
{
cout<<year<<ends<<"is a LEAP YEAR."<<endl;
}
else
cout<<year<<ends<<"is not an LEAP YEAR."<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int num,rem = 0,sum = 0;
cout<<"Enter the Number:";
cin>>num;
int temp = num;
while(temp!=0)
{
rem = temp%10;
int fact = 1;
for(int j = 1;j<=rem;j++)
{
fact = fact*j;
}
sum = sum+fact;
temp = temp/10;
}
if(sum == num)
{
cout<<"STRONG NUMBER."<<endl;
}
else
cout<<"NOT A STRONG NUMBER."<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int decimal;
int binary = 0,temp = 1,rem = 0;
cout<<"Enter the Decimal Number:";
cin>>decimal;
while(decimal!=0)
{
rem = decimal%2;
binary = binary + rem*temp;
temp = temp*10;
decimal = decimal/2;
}
cout<<"Binary Number:"<<binary<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int num;
cout<<"Enter the Number:";
cin>>num;
int i;
for(i=1;i<=num;i++)
{
if(num%i == 0)
{
cout<<i<<endl;
}
}
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
char str[100];
cin>>str;
int length = 0;
for(int i = 0;str[i]!='\0';i++)
{
length++;
}
int flag = 0;
for(int i = 0;i < length;i++)
{
if(str[i] == str[length-i-1])
{
flag = 1;
}
}
if(flag == 1)
{
cout<<"PALINDROME."<<endl;
}
else
cout<<"NOT PALINDROME."<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int l,u;
cout<<"Enter the LOWER LIMIT:";
cin>>l;
cout<<"Enter the UPPER LIMIT:";
cin>>u;
for(int i = l;i <= u;i++)
{
int temp = i, count = 0;
int dou = i*i;
while(temp!=0)
{
count++;
temp = temp/10;
}
int mul = 1,sum = 0;
for(int j = 1;j <= count;j++)
{
mul = mul*10;
}
sum = dou%mul;
if(sum == i)
{
cout<<i<<endl;
}
}
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int main()
{
system("cls");
int num,count = 0;
cout<<"Enter the number:";
cin>>num;
int temp = num;
int tEMP = num;
while(temp!=0)
{
count+=1;
temp = temp/10;
}
int rem = 0,sum = 0;
while(tEMP!=0)
{
rem = tEMP%10;
int pow = 1;
for(int i = 1;i <= count;i++)
{
pow = pow*rem;
}
sum = sum+pow;
tEMP = tEMP/10;
}
if(sum == num)
{
cout<<"ARMSTRONG NUMBER."<<endl;
}
else
cout<<"NOT AN ARMSTRONG NUMBER."<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int num;
cout<<"Enter the Number:";
cin>>num;
int dou = num*num;
int node = num,count = 0;
while(node!=0)
{
count++;
node = node/10;
}
int mul = 1,sum = 0;
for(int i = 1;i <= count; i++)
{
mul = mul*10;
}
sum = dou%mul;
if(sum == num)
{
cout<<"AUTOMORPHIC NUMBER."<<endl;
}
else
cout<<"NOT AN AUTOMORPHIC NUMBER"<<endl;
getch();
}
<file_sep>#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int num, flag = 0;
cout<<"Enter the number:";
cin>>num;
for(int i=2;i<=num/2;i++)
{
if(num%i == 0)
{
flag = 1;
}
}
if(flag == 0)
{
cout<<num<<ends<<"is prime number."<<endl;
}
else
{
cout<<num<<ends<<"is not a prime number."<<endl;
}
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int num,val;
cout<<"Enter the number:";
cin>>num;
cout<<"Enter the value:";
cin>>val;
int rem = 0,count=0;
while(num!=0)
{
rem = num%10;
if(rem == val)
{
count++;
}
num = num/10;
}
cout<<"No. of Counts:"<<count<<endl;
getch();
}
<file_sep>#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;
int palindromeORNot(int n)
{
int rem = 0,sum = 0;
while(n!=0)
{
rem = n%10;
sum = sum*10+rem;
n = n/10;
}
return sum;
}
int main()
{
system("cls");
int num;
cout<<"Enter the number:";
cin>>num;
palindromeORNot(num);
if(num == palindromeORNot(num))
{
cout<<"Palindrome."<<endl;
}
else
cout<<"Not Palindrome."<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int l,u;
cout<<"ENTER THE LOWER LIMIT:";
cin>>l;
cout<<"ENTER THE UPPER LIMIT:";
cin>>u;
for(int i = l;i <= u;i++)
{
int sum = 0;
for(int j = 1;j < i;j++)
{
if(i%j == 0)
{
sum+=j;
}
}
if(sum>i)
{
cout<<i<<endl;
}
}
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int base,exp;
cout<<"Enter the Number:";
cin>>base;
cout<<"Enter the Exponent:";
cin>>exp;
int res = 1;
for(int i=1;i<=exp;i++)
{
res = res*base;
}
cout<<"The power of"<<ends<<base<<ends<<"with exponent"<<ends<<exp<<ends<<"is:"<<res<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int max(int b[], int x)
{
int small = b[0];
for(int i=1;i<x;i++)
{
if(b[i] < small)
{
small = b[i];
}
}
cout<<"SMALL:"<<small<<endl;
}
int main()
{
int n;
cout<<"Enter the no. of Elements:";
cin>>n;
int a[n];
cout<<"The Elements are"<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
max(a,n);
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int binary;
int decimal = 0,rem = 0,temp = 1;
cout<<"Enter the Binary Number:";
cin>>binary;
while(binary!=0)
{
rem = binary%10;
decimal = decimal+rem*temp;
temp = temp*2;
binary = binary/10;
}
cout<<"The Decimal Number is:"<<decimal<<endl;
getch();
}
<file_sep>#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int number;
cout<<"Enter the Number:";
cin>>number;
if(number%2 == 0)
{
cout<<"The Number"<<ends<<number<<ends<<"is EVEN."<<endl;
}
else
cout<<"The Number"<<ends<<number<<ends<<"is ODD."<<endl;
getch();
}
<file_sep>#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int l,u;
cout<<"Enter the lower limit:";
cin>>l;
cout<<"Enter the upper limit:";
cin>>u;
for(int i = l;i <= u;i++)
{
int temp = i,rem = 0,sum = 0;
while(temp!=0)
{
rem = temp%10;
sum = sum+rem;
temp = temp/10;
}
if(i%sum == 0)
{
cout<<i<<endl;
}
}
getch();
}
<file_sep>#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int a,b;
cout<<"Enter the value of a and b"<<endl;
cin>>a>>b;
if(a>b)
{
cout<<a<<ends<<"is Greater than"<<ends<<b<<endl;
}
else if(b>a)
{
cout<<b<<ends<<"is Greater than"<<ends<<a<<endl;
}
else
cout<<a<<" and "<<b<<ends<<"are equal"<<endl;
getch();
}
| 84d5c80fe6232e6083ac683589d7e53febbc8164 | [
"C++"
] | 34 | C++ | abhijeetmurmu1997/c-plus-plus-programming | b3a602fcc48d617509817b41612a371264ce0c18 | 97ddac1a6ad03bf3bc5b812185a120e6b800b557 |
refs/heads/master | <repo_name>eguitarz/mailgun-rails<file_sep>/app/controllers/letters_controller.rb
class LettersController < ApplicationController
API_KEY = ENV['MAILGUN_KEY']
API_DOMAIN = ENV['MAILGUN_DOMAIN']
API_URL = "https://api:#{API_KEY}@api.mailgun.net/v2/#{API_DOMAIN}/messages"
def index
@letters = Letter.all
end
def show
@letter = Letter.find(params[:id])
@url = API_URL
end
def edit
@letter = Letter.find(params[:id])
end
def update
@letter = Letter.find(params[:id])
flash[:notice] = flash[:error] = ''
if @letter.update(letter_params)
flash.new[:notice] = 'updated'
else
flash.new[:error] = 'failed to update'
end
redirect_to letter_path(params[:id])
end
def destroy
@letter = Letter.find(params[:id])
@letter.destroy()
redirect_to :letters
end
def new
@letter = Letter.new
end
def create
@letter = Letter.new(letter_params)
flash[:notice] = flash[:error] = ''
if @letter.save
flash.new[:notice] = 'created a mail'
else
flash.new[:error] = 'failed to create mails'
end
redirect_to :letters
end
def upload_template
respond_to do |format|
format.json { render :json => {:file => params[:files]} }
end
end
private
def letter_params
params.require(:letter).permit(:title, :from, :to, :cc, :bcc, :campaign_id, :body)
end
end
<file_sep>/db/migrate/20140123131820_add_data_to_letter.rb
class AddDataToLetter < ActiveRecord::Migration
def change
add_column :letters, :title, :string, :default => 'Sample', :null => false
add_column :letters, :from, :string, :default => '', :null => false
add_column :letters, :to, :string, :default => '', :null => false
add_column :letters, :body, :string
add_column :letters, :compaign_id, :string
end
end
<file_sep>/db/migrate/20140123162558_add_cc_bcc.rb
class AddCcBcc < ActiveRecord::Migration
def change
add_column :letters, :cc, :string
add_column :letters, :bcc, :string
end
end
<file_sep>/config/routes.rb
MailgunRails::Application.routes.draw do
resources :letters
post 'upload_template' => 'letters#upload_template'
root 'letters#index'
end
<file_sep>/README.md
mailgun-rails
=============
A rails based website for mailgun users. You can edit your html mail via this web.
Why?
----
Mailgun did not provide interface to edit html mail, so I make one for this.
Features
----
- support html mail preview
- support templates
- support mailgun
<file_sep>/db/migrate/20140123144229_remove_title_default.rb
class RemoveTitleDefault < ActiveRecord::Migration
def change
change_column :letters, :title, :string, :default => '', :null => true
end
end
<file_sep>/db/migrate/20140123142049_change_campaign_id.rb
class ChangeCampaignId < ActiveRecord::Migration
def change
remove_column :letters, :campaing_id
add_column :letters, :campaign_id, :string
end
end
<file_sep>/db/migrate/20140123141431_fix_campaign_id.rb
class FixCampaignId < ActiveRecord::Migration
def change
remove_column :letters, :compaign_id
add_column :letters, :campaing_id, :string
end
end
| 111dc97058f015d37820a5195da450ea64af5b72 | [
"Markdown",
"Ruby"
] | 8 | Ruby | eguitarz/mailgun-rails | 9bd3bcf6eb945885d6ba5a832c5771f32019610f | d0cffce52c889ee742f446775fd6c8d25a88d8e1 |
refs/heads/master | <file_sep>
# Add by pfzhang
"""Simple layer DSL wrapper to ease creation of neural nets."""
from tvm import relay
def bitserial_conv2d(data, weight=None, **kwargs):
"""Wrapper of bitserial_conv2d which automatically creates weights if not given
Parameters
----------
data: relay.Expr
The input expression.
weight: relay.Expr
The weight to bitserial_conv2d
kwargs: dict
Additional arguments
Returns
---------
result: relay.Expr
The result
"""
name = kwargs.get('name')
kwargs.pop('name')
if not weight:
weight = relay.var(name + '_weight')
return relay.nn.bitserial_conv2d(data, weight, **kwargs)<file_sep>
import numpy as np
import tvm
from tvm import te
from tvm import relay
from tvm.relay import testing
import binary_layers
"""The params of models"""
vgg16 = {
'conv2d': {
# params: {input_channel, input_height, input_weight, ouptut_channel, kernel_size,
# stride, padding}
'qconv_2': {'params': [64, 224, 224, 64, 3, 1, 1]},
'qconv_3': {'params': [64, 224, 224, 128, 3, 1, 1]},
'qconv_4': {'params': [128, 112, 112, 128, 3, 1, 1]},
'qconv_5': {'params': [128, 112, 112, 256, 3, 1, 1]},
'qconv_6': {'params': [256, 56, 56, 256, 3, 1, 1]},
'qconv_7': {'params': [256, 56, 56, 256, 3, 1, 1]},
'qconv_8': {'params': [256, 56, 56, 512, 3, 1, 1]},
'qconv_9': {'params': [512, 28, 28, 512, 3, 1, 1]},
'qconv_10': {'params': [512, 28, 28, 512, 3, 1, 1]},
'qconv_11': {'params': [512, 28, 28, 512, 3, 1, 1]},
'qconv_12': {'params': [512, 28, 28, 512, 3, 1, 1]},
'qconv_13': {'params': [512, 14, 14, 512, 3, 1, 1]},
'qconv_14': {'params': [512, 14, 14, 512, 3, 1, 1]},
'qconv_15': {'params': [512, 14, 14, 512, 3, 1, 1]},
'qconv_16': {'params': [512, 14, 14, 512, 3, 1, 1]},
},
}
def get_bitserial_conv2d_nchw(model, layer_name, batch_size=1, dtype='int8',
activation_bits=2, weight_bits=2, out_dtype='int16'):
"""get the bitserial 2D convolution here, the input layout is 'nchw' """
params = model['conv2d'][layer_name]['params']
image_shape = params[0], params[1], params[2]
data_shape = (batch_size, ) + image_shape
output_channel = params[3]
kernel_size = params[4]
# The weight shape should be OIHW
weight_shape = output_channel, params[0], kernel_size, kernel_size
stride = params[5]
padding = params[6]
data = relay.var("data", shape=data_shape, dtype=dtype)
weight = relay.var(layer_name + "_weight", shape=weight_shape, dtype=dtype)
net = binary_layers.bitserial_conv2d(data=data, weight=weight, strides=(stride, stride),
padding=(padding, padding), channels=output_channel,
kernel_size=(kernel_size, kernel_size),
activation_bits=activation_bits, weight_bits=weight_bits,
pack_dtype='uint8', out_dtype=out_dtype,
name=layer_name)
net = relay.Function(relay.analysis.free_vars(net), net)
mod, params = testing.create_workload(net)
# We only needs to return this three variables
return mod, params, data_shape
def get_bitserial_conv2d_nhwc(model, layer_name, batch_size=1, dtype='int8', activation_bits=2, weight_bits=2, out_dtype='int16'):
"""get the bitserial 2D convolution here, the input layout is 'nchw' """
params = model['conv2d'][layer_name]['params']
# The image shape should be hwc
image_shape = params[1], params[2], params[0]
# The data shape should be nhwc
data_shape = (batch_size, ) + image_shape
output_channel = params[3]
kernel_size = params[4]
# the weight shape should be HWIO
weight_shape = kernel_size, kernel_size, params[0], output_channel
stride = params[5]
padding = params[6]
data = relay.var("data", shape=data_shape, dtype=dtype)
weight = relay.var(layer_name + "_weight", shape=weight_shape, dtype=dtype)
net = binary_layers.bitserial_conv2d(data=data, weight=weight, strides=(stride, stride),
padding=(padding, padding), channels=output_channel,
kernel_size=(kernel_size, kernel_size),
activation_bits=activation_bits, weight_bits=weight_bits,
data_layout='NHWC', kernel_layout='HWIO', # Have to define here.
pack_dtype='uint8', out_dtype=out_dtype,
name=layer_name)
net = relay.Function(relay.analysis.free_vars(net), net)
mod, params = testing.create_workload(net)
# We only needs to return this three variables
return mod, params, data_shape
if __name__ == '__main__':
mod, params, data_shape = get_bitserial_conv2d_nchw(vgg16, 'qconv_2')
print(mod)
print(params)
<file_sep>
import os
import numpy as np
import tvm
from tvm import te
from tvm import autotvm
from tvm import relay
import tvm.relay.testing
from tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner
from tvm.contrib.util import tempdir
import tvm.contrib.graph_runtime as runtime
import models
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--activation_bits', type=int, default=2, help="The bit number of activations.")
parser.add_argument('--weight_bits', type=int, default=2, help='The bit number of weights')
parser.add_argument('--result_file', required=True, help='The result file.')
parser.add_argument('--input_layout', default='nchw', choices=['nhwc', 'nchw'], help='The input layout.')
args = parser.parse_args()
dtype = 'int8'
activation_bits = int(args.activation_bits)
weight_bits = int(args.weight_bits)
output_file = open(args.result_file, 'w')
output_file.write("layer,mean_time,dev\n")
target = tvm.target.create('llvm -device=arm_cpu -target=aarch64-linux-gnu')
# Also replace this with the device key in your tracker
device_key = 'jetson-nano'
# Set this to True if you use android phone
use_android = False
#### TUNING OPTION ####
def tune_tasks(tasks,
measure_option,
tuner='xgb',
n_trial=1000,
early_stopping=None,
log_filename='tuning.log',
use_transfer_learning=True):
# create tmp log file
tmp_log_file = log_filename + ".tmp"
if os.path.exists(tmp_log_file):
os.remove(tmp_log_file)
for i, tsk in enumerate(reversed(tasks)):
prefix = "[Task %2d/%2d] " % (i+1, len(tasks))
# create tuner
if tuner == 'xgb' or tuner == 'xgb-rank':
tuner_obj = XGBTuner(tsk, loss_type='rank')
elif tuner == 'xgb_knob':
tuner_obj = XGBTuner(tsk, loss_type='rank', feature_type='knob')
elif tuner == 'ga':
tuner_obj = GATuner(tsk, pop_size=50)
elif tuner == 'random':
tuner_obj = RandomTuner(tsk)
elif tuner == 'gridsearch':
tuner_obj = GridSearchTuner(tsk)
else:
raise ValueError("Invalid tuner: " + tuner)
if use_transfer_learning:
if os.path.isfile(tmp_log_file):
tuner_obj.load_history(autotvm.record.load_from_file(tmp_log_file))
# do tuning
tsk_trial = min(n_trial, len(tsk.config_space))
tuner_obj.tune(n_trial=tsk_trial,
early_stopping=early_stopping,
measure_option=measure_option,
callbacks=[
autotvm.callback.progress_bar(tsk_trial, prefix=prefix),
autotvm.callback.log_to_file(tmp_log_file)
])
# pick best records to a cache file
autotvm.record.pick_best(tmp_log_file, log_filename)
os.remove(tmp_log_file)
########################################################################
# Finally, we launch tuning jobs and evaluate the end-to-end performance.
def tune_and_evaluate(tuning_opt, layer_name='qconv_2', input_layout='nchw'):
# extract workloads from relay program
global output_file
print("Extract tasks...")
if input_layout == 'nchw':
mod, params, input_shape = models.get_bitserial_conv2d_nchw(models.vgg16, layer_name,
activation_bits=activation_bits, weight_bits=weight_bits)
else:
mod, params, input_shape = models.get_bitserial_conv2d_nhwc(models.vgg16, layer_name,
activation_bits=activation_bits, weight_bits=weight_bits)
tasks = autotvm.task.extract_from_program(mod["main"], target=target,
params=params,
ops=(relay.op.get("nn.bitserial_conv2d"),))
# run tuning tasks
print("Tuning...")
tune_tasks(tasks, **tuning_opt)
log_file = tuning_opt['log_filename']
print('Extract the best from %s' % log_file)
specific_layer = log_file.split('.')[0]
# compile kernels with history best records
with autotvm.apply_history_best(log_file):
print("Compile...")
with relay.build_config(opt_level=3):
graph, lib, params = relay.build_module.build(
mod, target=target, params=params)
# export library
tmp = tempdir()
if use_android:
from tvm.contrib import ndk
filename = "net.so"
lib.export_library(tmp.relpath(filename), ndk.create_shared)
else:
filename = "net.tar"
lib.export_library(tmp.relpath(filename))
# upload module to device
print("Upload...")
remote = autotvm.measure.request_remote(device_key, '0.0.0.0', 9190,
timeout=10000)
remote.upload(tmp.relpath(filename))
rlib = remote.load_module(filename)
# upload parameters to device
ctx = remote.context(str(target), 0)
module = runtime.create(graph, rlib, ctx)
data_tvm = tvm.nd.array((np.ones(input_shape)).astype(dtype))
module.set_input('data', data_tvm)
module.set_input(**params)
# evaluate
print("Evaluate inference time cost...")
ftimer = module.module.time_evaluator("run", ctx, number=1, repeat=10)
prof_res = np.array(ftimer().results) * 1000 # convert to millisecond
print("Mean inference time (std dev): %.2f ms (%.2f ms)" %
(np.mean(prof_res), np.std(prof_res)))
output_file.write(specific_layer + ',' + str(np.mean(prof_res)) + ',' + str(np.std(prof_res)) + '\n')
network = 'vgg16'
# deal with the convolution operation
for layer_name in models.vgg16['conv2d'].keys():
log_file = "%s_%s_%s_A%dW%d.log" % (network, layer_name, args.input_layout, activation_bits, weight_bits)
tuning_option = {
'log_filename': log_file,
'tuner': 'random',
'n_trial': 1000,
'early_stopping': 800,
'measure_option': autotvm.measure_option(
builder=autotvm.LocalBuilder(
build_func='ndk' if use_android else 'default'),
runner=autotvm.RPCRunner(
device_key, host='0.0.0.0', port=9190,
number=5,
timeout=10,
),),
}
tune_and_evaluate(tuning_option, layer_name, input_layout=args.input_layout)
output_file.close()
| a5e7facfdd0cf514964ce9887636126e54f9d773 | [
"Python"
] | 3 | Python | kuafu1994/QNNEngine | 2e3a0d7908bb1ebe7f5f75f197e12395e5e07cf5 | 937ee76db1f0bb7771b2241bd2230f4a60127c97 |
refs/heads/master | <repo_name>MrRumIsGodLike/QuestionBank<file_sep>/01_07.py
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# 1.ๅธธ่ง่งฃๆณ
# N = len(matrix)
# # ๆฒฟ็ไธปๅฏน่ง็บฟไบคๆข
# for i in range(N):
# for j in range(i):
# matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# for i in range(N):
# matrix[i] = matrix[i][::-1]
# 2.ๅผๆ่ฎก็ฎ
# https://blog.csdn.net/lewky_liu/article/details/85219084
n = len(matrix)
for i in range(n):
matrix[i].reverse()
for i in range(n):
for j in range(n - i):
if matrix[i][j] == matrix[n - j - 1][n - i - 1]:
continue
matrix[i][j] = matrix[i][j] ^ matrix[n - j - 1][n - i - 1]
matrix[n - j - 1][n - i - 1] = matrix[i][j] ^ matrix[n - j - 1][n - i - 1]
matrix[i][j] = matrix[i][j] ^ matrix[n - j - 1][n - i - 1]
<file_sep>/README.md
# QuestionBank
Cracking the Coding Interview (LeetCode version)
The Python implementation of Cracking the Coding Interview.
<file_sep>/01_03.py
class Solution:
def replaceSpaces(self, S: str, length: int) -> str:
# 1.ๆดๅ
# res = list(S)
# for p in range(length):
# if res[p] == ' ':
# res[p] = '%20'
# return ''.join(res[:length])
# 2.็ฒพ็ฎ
# return '%20'.join(S[:length].split(' '))
# 3.ๆ็ฒพ็ฎ
return S[:length].replace(' ','%20')<file_sep>/01_06.py
class Solution:
def compressString(self, S: str) -> str:
# ๅบ็ฐ1ๆฌก้ฟๅบฆๅ 1 ๅบ็ฐ2ๆฌก้ฟๅบฆไธๅ ๅบ็ฐ2ๆฌกไปฅไธ้ฟๅบฆๅๅฐ
S += '-'
cnt,res = 1,""
for i in range(1,len(S)):
if S[i] == S[i-1]:
cnt += 1
else:
res += (S[i-1] + str(cnt))
cnt = 1
return S[:-1] if len(res) >= len(S) - 1 else res
<file_sep>/01_08.py
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# 1.่ฎฐๅฝ้ถๅ
็ด ็่กๅๅ
็ป
n = len(matrix)
m = len(matrix[0])
tmp = []
for i in range(n):
for j in range(m):
if matrix[i][j] == 0:
tmp.append((i, j))
for i, j in tmp:
for k in range(n):
matrix[k][j] = 0
for l in range(m):
matrix[i][l] = 0
<file_sep>/01_05.py
class Solution:
def oneEditAway(self, first: str, second: str) -> bool:
# ๆๅ
ฅใๅ ้คใๆฟๆข
# ๆๅค้่ฆไธๆฌก็ผ่พๆไฝ
# 1.็ผ่พ่ท็ฆป๏ผ๏ผ๏ผ
# 2.ๅๆ้ ๅ้ฟๅบฆไธๅๅ้ฟๅบฆ็ธๅไธค็งๆ
ๅต
if abs(len(first) - len(second)) >= 2:
return False
count = 0
if len(first) == len(second):
for i in range(len(first)):
if first[i] != second[i]:
count += 1
if count == 2:
return False
return True
if len(first) < len(second):
first, second = second, first
for i in range(len(first)):
if first[0:i] + first[i + 1:] == second:
return True
return False
<file_sep>/01_04.py
class Solution:
def isPower(self,n):
if n < 1:
return False
i = 1
while i <= n:
if i == n:
return True
i <<= 1
return False
def canPermutePalindrome(self, s: str) -> bool:
# ๅๅธ่กจ/Counterๆฐๆฎ็ปๆ
# ไฝ่ฟ็ฎ: ๅฅๆฐ็ๅญ็ฌฆไธชๆฐไธบ0ๆ1
mark = 0
for c in s:
move = ord(c)
mark ^= 1 << move
# ๅๅซๅคๆญๅฅๅถ
return mark == 0 or self.isPower(mark)<file_sep>/01_01.py
class Solution:
def isUnique(self, astr: str) -> bool:
# 1.ๅญๅ
ธ็ญ้
# 2.set (AC)
# a = set(astr)
# if len(a) == len(astr):
# return True
# else:
# return False
# 3.ไฝ่ฟ็ฎ
mark = 0
for char in astr:
move = ord(char) - ord('a')
if (mark & (1 << move)) != 0:
return False
else:
mark |= (1 << move)
return True | 653526baf970446e97a3feb956c1a1a1792955ce | [
"Markdown",
"Python"
] | 8 | Python | MrRumIsGodLike/QuestionBank | 4a8ed025439a151cc3ed90eea9aa7523f2546f90 | 0983e49d3466c4b61988bda2834316a437d925d9 |
refs/heads/main | <repo_name>sanadriu/blog-with-api<file_sep>/assets/js/components/navigation.js
import { insertPostCards } from "./postCard.js";
import { clearPostCards } from "./postCard.js";
export function navigationListener() {
document.querySelector("#navigation").addEventListener("click", async function (event) {
const navButtons = this.querySelectorAll(".page-link");
const prevButton = navButtons[0];
const nextButton = navButtons[2];
if (event.target === prevButton) {
await goPrevPage(navButtons);
} else if (event.target === nextButton) {
await goNextPage(navButtons);
}
});
}
async function goNextPage(navButtons) {
if (navButtons[2].disabled) return;
sessionStorage.start = parseInt(sessionStorage.start) + parseInt(sessionStorage.limit);
clearPostCards();
const posts = await insertPostCards();
updatePrevPageButton(navButtons[0]);
updateNextPageButton(navButtons[2], posts);
updateCurrentPageIndex(navButtons[1], 1);
}
async function goPrevPage(navButtons) {
if (navButtons[0].disabled) return;
sessionStorage.start = parseInt(sessionStorage.start) - parseInt(sessionStorage.limit);
clearPostCards();
const posts = await insertPostCards();
updatePrevPageButton(navButtons[0]);
updateNextPageButton(navButtons[2], posts);
updateCurrentPageIndex(navButtons[1], -1);
}
function updateNextPageButton(nextButton, posts) {
if (posts.length < parseInt(sessionStorage.limit)) {
nextButton.parentElement.classList.add("disabled");
nextButton.disabled = true;
} else {
nextButton.parentElement.classList.remove("disabled");
nextButton.disabled = false;
}
}
function updatePrevPageButton(prevButton) {
if (sessionStorage.start == 0) {
prevButton.parentElement.classList.add("disabled");
prevButton.disabled = true;
} else {
prevButton.parentElement.classList.remove("disabled");
prevButton.disabled = false;
}
}
function updateCurrentPageIndex(pageButton, num) {
pageButton.textContent = parseInt(pageButton.textContent) + num;
}
<file_sep>/assets/js/utils/searchParentTarget.js
export default function searchParentTarget(element, conditionCb) {
if (!element) return null;
if (conditionCb(element)) return element;
return searchParentTarget(element.parentElement, conditionCb);
}
<file_sep>/assets/js/init.js
import { insertPostCards } from "./components/postCard.js";
document.addEventListener("DOMContentLoaded", async function () {
sessionStorage.start = 0;
sessionStorage.limit = 12;
sessionStorage.url = "http://localhost:3000";
await insertPostCards();
});
<file_sep>/assets/js/components/postComment.js
import { getPostComments } from "../requests.js";
export async function insertPostComments(id) {
const postCommentSection = document.querySelector("#post-comments-section").children[0];
const comments = await getPostComments(id);
comments.forEach((comment) => {
const postCommentCard = createPostCommentCard(comment);
postCommentSection.insertAdjacentHTML("beforeend", postCommentCard);
});
}
export function clearPostComments() {
document.querySelector("#post-comments-section").children[0].innerHTML = null;
}
function createPostCommentCard(comment) {
const template = `
<div data-component="post-comment">
<article class="card shadow-sm mb-3" data-comment-id=${comment.id}>
<div class="card-body p-3">
<h6>${comment.name}</h6>
<p class="fs-6 m-0">${comment.body}</p>
</div>
<div class="card-footer p-3">
<p class="fs-7 text-black-50 text-end m-0">By <span class="fst-italic">${comment.email}</span></p>
</div>
</article>
</div>
`;
return template;
}
<file_sep>/assets/js/components/modal.js
import { getPost, getUser, updatePost, deletePost, getPostImage } from "../requests.js";
import { insertPostCards, clearPostCards } from "./postCard.js";
import { insertPostComments } from "./postComment.js";
export function modalPostListener() {
const modal = document.querySelector("#modal");
modal.addEventListener("click", async function (event) {
const target = event.target;
const id = sessionStorage.postId;
if (target.matches("[data-action~='load-editor']") || target.matches("[data-action~='load-editor'] *")) {
await updateModalEditorContent(id);
} else if (target.matches("[data-action~='load-post']") || target.matches("[data-action~='load-post'] *")) {
await updateModalPostContent(id);
await insertPostComments(id);
} else if (target.matches("[data-action~='close-modal']") || target.matches("[data-action~='close-modal'] *")) {
closeModal();
} else if (target.matches("[data-action~='save-post']") || target.matches("[data-action~='save-post'] *")) {
const form = document.forms["post-editor-form"];
const response = await updatePost(id, {
title: form.elements["post-title"].value,
body: form.elements["post-content"].value,
});
if (response.ok) {
clearPostCards();
await insertPostCards();
}
displayEditPostMessage(response);
} else if (target.matches("[data-action~='delete-post']") || target.matches("[data-action~='delete-post'] *")) {
const response = await deletePost(id);
if (response.ok) {
clearPostCards();
await insertPostCards();
}
displayRemovePostMessage(response);
}
});
}
function displayEditPostMessage(response) {
const modal = document.querySelector("#modal");
if (response.ok) {
const message = modal.querySelector("#post-editor-ok");
const messageBs = new bootstrap.Collapse(message);
messageBs.show();
setTimeout(() => messageBs.hide(), 4000);
} else {
const message = modal.querySelector("#post-editor-error");
const messageBs = new bootstrap.Collapse(message);
messageBs.show();
setTimeout(() => messageBs.hide(), 4000);
}
}
function displayRemovePostMessage(response) {
const modal = document.querySelector("#modal");
if (response.ok) {
const message = modal.querySelector("#post-delete-ok");
const messageBs = new bootstrap.Collapse(message);
const buttons = modal.querySelector("#modal-delete .modal-footer");
const buttonsBs = new bootstrap.Collapse(buttons);
messageBs.show();
buttonsBs.hide();
setTimeout(() => {
messageBs.hide();
buttonsBs.show();
closeModal();
}, 4000);
} else {
const message = modal.querySelector("#post-delete-error");
const messageBs = new bootstrap.Collapse(message);
messageBs.show();
setTimeout(() => messageBs.hide(), 4000);
}
}
function closeModal() {
const modal = document.querySelector("#modal");
const modalBs = bootstrap.Modal.getInstance(modal);
modalBs.hide();
const postSectionBs = new bootstrap.Collapse(modal.querySelector("#modal-post"), { toggle: false });
const editSectionBs = new bootstrap.Collapse(modal.querySelector("#modal-editor"), { toggle: false });
const deleteSectionBs = new bootstrap.Collapse(modal.querySelector("#modal-delete"), { toggle: false });
postSectionBs.show();
editSectionBs.hide();
deleteSectionBs.hide();
}
export async function updateModalPostContent(id) {
const modal = document.querySelector("#modal-post");
const post = await getPost(id);
const user = await getUser(post.userId);
const img = await getPostImage(post.id);
modal.querySelector("#post-image").src = img.download_url;
modal.querySelector("#post-title").textContent = post.title;
modal.querySelector("#post-content").textContent = post.body;
modal.querySelector("#user-name").textContent = user.name;
modal.querySelector("#user-email").textContent = user.email;
sessionStorage.postId = id;
}
export async function updateModalEditorContent(id) {
const post = await getPost(id);
const form = document.forms["post-editor-form"];
form.elements["post-title"].value = post.title;
form.elements["post-content"].textContent = post.body;
}
| 18cde95bd8c03ac9443a849a9702bf47683d07c9 | [
"JavaScript"
] | 5 | JavaScript | sanadriu/blog-with-api | fd6378a578674ce016fdf0fe06741ecaab7099b2 | 6f33763c0cf67bb7b1bfcd7f3bb1725ffea70150 |
refs/heads/master | <file_sep>#-----------------------------------------------------#
# vsm measurement plot v0.6 ----#
# former name: vsm_plt_v05_id_Hc-i.py ----#
# author: tatsunootoshigo, <EMAIL> #
#-----------------------------------------------------#
# Imports
import numpy as np
import peakutils
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.gridspec as gridspec
from scipy import stats
from matplotlib.font_manager import FontProperties
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.ticker import MaxNLocator, MultipleLocator, FormatStrFormatter
# script version
version = '0.6'
version_name = 'hst_hcms_ploter_' + version + '.py'
# some useful constants
cm = 1e-2
nm = 1e-9
mu0 = 4*np.pi*1e-7
mega = 1e+6
tesla = 1e+4 # Gauss to tesla
# =================== SAMPLE DATA STARTS HERE =================
sample_mdate = '311118'
sample_id = 'E2978'
sample_no = 0
sample_bg = 'sub'
# measurment configuration
hdir = 'inpl'
label_hdir = r'$\parallel$'
#label_hdir = r'$\perp$'
slayer_step = 0.5
#slayer5 = r'$1W$'
#slayer4 = r'$Mg$'
slayer3 = r'$AlO_x$'
slayer2 = r'$Fe-Si$'
slayer1 = r'$W$'
substrate = r'$SiSi0_2$'
# sample dimensions in cm
sample_l = 1.0
sample_w = 1.0
# ferromagnetic layer thickness in nm
sample_fml_d = 30.0
# ferromagnetic layer volume in cm^3
sample_fml_vol = (sample_l*sample_w*sample_fml_d*1e+2)*cm**3
# calibration coefficient for the perp & inpl
cal_coeff = 4.961 / 2.808
# number of decimal points to display in tick labels
xprec = 0
yprec = 0
# set axes range to some nice round value
xmin = -50
xmax = 50
ymin = -10000
ymax = 10000
deskew_points = 10
deskew_fit_range = np.arange(-2.0, 2.0, 0.01)
# number of points for linear fit of Hc from OO for each quadrant pair
Hc_fit_points_q23 = 8
Hc_fit_points_q14 = 8
Hc_creep_q14 = 35
Hc_creep_q23 = 35
# plot Hc fit line in a specific range
Hc_fit_range_q23 = np.arange(-1.0, 1.0, 0.01) # start, stop, step
Hc_fit_range_q14 = np.arange(-3.0, 3.0, 0.01) # start, stop, step
# number of points for linear fit of Ms from OO for each quadrant pair
Ms_fit_points_q12 = 8
Ms_fit_points_q34 = 8
Ms_creep_q12 = 0
Ms_creep_q34 = 0
# plot Ms fit line in a specific range
Ms_fit_range_q12 = np.arange(-3.0, 3.0, 0.01) # start, stop, step
Ms_fit_range_q34 = np.arange(-1.0, 1.0, 0.01) # start, stop, step
# ===================================================================
# output pdf
out_pdf = 'VSM_hcms_plot_' + hdir + '_' + sample_id + '.pdf'
out_svg = 'VSM_hcms_plot_' + hdir + '_' + sample_id + '.svg'
# plot legend lables
label_inpl = r'$\parallel$'
label_perp = r'$\perp$'
sdelimiter = r'$\rfloor\lfloor$'
# axes labels for the mu0M vs. mu0H plots
axis_label_mu0M = r'$\mu_0 M\, / \, G$'
axis_label_mu0H = r'$\mu_0 H\, / \, G$'
axis_label_mu0Ms = r'$\mu_0 M_s\, / \, T$'
axis_label_mu0Hk = r'$\mu_0 H_k\, / \, T$'
axis_label_th = r'$thickness\, / \, nm$'
# position and vertical separation of entries
mshk_legend_x = -1.45
mshk_legend_y = 1.35
mshk_legend_y_sep = 0.3
def vsm_open_in(sample_mdate, sample_id, sample_no):
file_inpl = sample_mdate + sample_id + '-ii.txt'
#file_perp = sample_mdate + sample_id + '-p.txt'
# load raw data from text file, skiprows=12 --> gets rid of the vsm file headder
x1, y1 = np.loadtxt(file_inpl, skiprows=12 ,unpack=True)
#x2, y2 = np.loadtxt(file_perp, skiprows=12 ,unpack=True)
# recalculate units to get mu0*M vs. mu0*H plot in teslas
tx1 = x1
ty1 = y1 * 4*np.pi*1e+3 / sample_fml_vol
#tx2 = x2 / tesla
#ty2 = y2 * 4*np.pi*1e+3 / sample_fml_vol / tesla * cal_coeff
return np.array([tx1, ty1]);
def gen_plot_title(sample_no):
# sample label describing the layers
sample_label = '[' + substrate + sdelimiter + slayer1 + sdelimiter + slayer2 + sdelimiter + slayer3 + ']'
# plot title using sample label
plt_title = sample_label + ' id: ' + sample_id
return plt_title;
def custom_axis_formater(custom_title, custom_x_label, custom_y_label, xmin, xmax, ymin, ymax, xprec, yprec):
# get axes and tick from plot
ax = plt.gca()
major_tx_no_x = 5
major_tx_no_y = 8
# set the number of major and minor bins for x,y axes
# prune='lower' --> remove lowest tick label from x axis
xmajorLocator = MaxNLocator(major_tx_no_x, prune='lower')
xmajorFormatter = FormatStrFormatter('%.'+ np.str(xprec) + 'f')
xminorLocator = MaxNLocator(5*major_tx_no_x)
ymajorLocator = MaxNLocator(major_tx_no_y)
ymajorFormatter = FormatStrFormatter('%.'+ np.str(yprec) + 'f')
yminorLocator = MaxNLocator(5*major_tx_no_y)
# format major and minor ticks width, length, direction
ax.tick_params(which='both', width=2, direction='in', labelsize=24)
ax.tick_params(which='major', length=6)
ax.tick_params(which='minor', length=4)
# set axes thickness
ax.spines['top'].set_linewidth(2)
ax.spines['bottom'].set_linewidth(2)
ax.spines['right'].set_linewidth(2)
ax.spines['left'].set_linewidth(2)
ax.xaxis.set_major_locator(xmajorLocator)
ax.yaxis.set_major_locator(ymajorLocator)
ax.xaxis.set_major_formatter(xmajorFormatter)
ax.yaxis.set_major_formatter(ymajorFormatter)
# for the minor ticks, use no labels; default NullFormatter
ax.xaxis.set_minor_locator(xminorLocator)
ax.yaxis.set_minor_locator(yminorLocator)
# grid and axes are drawn below the data plot
ax.set_axisbelow(True)
# add x,y grids to plot area
ax.xaxis.grid(True, zorder=0, color='lightgray', linestyle='-', linewidth=1)
ax.yaxis.grid(True, zorder=0, color='lightgray', linestyle='-', linewidth=1)
# set axis labels
ax.set_xlabel(custom_x_label, fontsize=24)
ax.set_ylabel(custom_y_label, fontsize=24)
# set plot title
ax.set_title(custom_title, loc='right', fontsize=24)
return;
def gen_mshk_legend(mshk_array):
# get axes and tick from plot
ax = plt.gca()
# add to plot calculated values of M_k and H_k
ax.text(mshk_legend_x, mshk_legend_y, r'$\parallel \mu_0 M_s =$' + np.str(np.round(mshk_array[4], 2)) + r'$T$')
ax.text(mshk_legend_x, mshk_legend_y - mshk_legend_y_sep, r'$\parallel \mu_0 H_k =$' + np.str(np.round(mshk_array[6], 2)) + r'$T$')
ax.text(mshk_legend_x, mshk_legend_y - 2.0*mshk_legend_y_sep, r'$\perp \mu_0 M_s =$' + np.str(np.round(mshk_array[5], 2)) + r'$T$')
ax.text(mshk_legend_x, mshk_legend_y - 3.0*mshk_legend_y_sep, r'$\perp \mu_0 H_k =$' + np.str(np.round(mshk_array[7], 2)) + r'$T$')
return;
def vsm_fit_hst_Hc(vsm_data, Hc_fit_points_q23, Hc_fit_points_q14, Hc_creep_q14, Hc_creep_23):
# liear fit of the hysteresis loops for each of quadrant pairs
tx_half = (vsm_data.shape[1] - 1) / 2
ty_half = (vsm_data.shape[1] - 1) / 2
# pick a range of points from the calculated data definde by fit_points_inpl/perp
xq14 = vsm_data[0, np.int_(tx_half - Hc_creep_q23 - Hc_fit_points_q23):np.int_(tx_half - Hc_creep_q23)]
xq23 = vsm_data[0, np.int_(2*tx_half - Hc_creep_q14 - Hc_fit_points_q14):np.int_(2*tx_half - Hc_creep_q14)]
yq14 = vsm_data[1, np.int_(ty_half - Hc_creep_q23 - Hc_fit_points_q23):np.int_(ty_half - Hc_creep_q23)]
yq23 = vsm_data[1, np.int_(2*ty_half - Hc_creep_q14 - Hc_fit_points_q14):np.int_(2*ty_half - Hc_creep_q14)]
# calculate linear fit parameters
slope_q14, intercept_q14, r_value_q14, p_value_q14, std_err_q14 = stats.linregress(xq14, yq14)
slope_q23, intercept_q23, r_value_q23, p_value_q23, std_err_q23 = stats.linregress(xq23, yq23)
#print(slope_q14, slope_q23)
#print(intercept_q14, intercept_q23)
print('=================================')
print('Hc1: ', intercept_q14 / slope_q14, 'Hc2: ', intercept_q23 / slope_q23, 'mean Hc:', 0.5*(np.absolute(intercept_q14 / slope_q14) + np.absolute(intercept_q23 / slope_q23)))
print('---------------------------------')
print('slope_q12: ', slope_q14)
print('intercept_q12: ', intercept_q14)
print('r_value_q12: ', r_value_q14)
print('std_err_q12:', std_err_q14)
print('---------------------------------')
print('slope_q34: ', slope_q23)
print('intercept_q34: ', intercept_q23)
print('r_value_q34', r_value_q23)
print('std_err_q34', std_err_q23)
plt.figtext(0.2, 0.04, r'$H_c^{(q14)}:$ ' + ' a: ' + np.str(slope_q14) + ' b: ' + np.str(intercept_q14) + ' ' + r'$R^2:$' + np.str(r_value_q14*r_value_q14) + ' S: ' + np.str(std_err_q14), size=14)
plt.figtext(0.2, 0.02, r'$H_c^{(q23)}:$' + ' a: ' + np.str(slope_q23) + ' b: ' + np.str(intercept_q23) + ' ' + r'$R^2:$ ' + np.str(r_value_q23*r_value_q23) + ' S: ' + np.str(std_err_q23), size=14)
return np.array([slope_q14, slope_q23, intercept_q14, intercept_q23]);
def vsm_fit_hst_Ms(vsm_data, Ms_fit_points_q12, Ms_fit_points_q34, Ms_creep_q12, Ms_creep_34):
# liear fit of the hysteresis loops for each of quadrant pairs
tx_half = (vsm_data.shape[1] - 1) / 2
ty_half = (vsm_data.shape[1] - 1) / 2
# pick a range of points from the calculated data definde by fit_points_inpl/perp
xq12 = vsm_data[0, np.int_(tx_half - Ms_creep_q34 - Ms_fit_points_q34):np.int_(tx_half - Ms_creep_q34)]
xq34 = vsm_data[0, np.int_(2*tx_half - Ms_creep_q12 - Ms_fit_points_q12):np.int_(2*tx_half - Ms_creep_q12)]
yq12 = vsm_data[1, np.int_(ty_half - Ms_creep_q34 - Ms_fit_points_q34):np.int_(ty_half - Ms_creep_q34)]
yq34 = vsm_data[1, np.int_(2*ty_half - Ms_creep_q12 - Ms_fit_points_q12):np.int_(2*ty_half - Ms_creep_q12)]
# calculate linear fit parameters
slope_q12, intercept_q12, r_value_q12, p_value_q12, std_err_q12 = stats.linregress(xq12, yq12)
slope_q34, intercept_q34, r_value_q34, p_value_q34, std_err_q34 = stats.linregress(xq34, yq34)
print('=================================')
print('Ms12: ', intercept_q12, 'Ms34: ', intercept_q34, 'Ms_mean: ', 0.5*(np.absolute(intercept_q12) + np.absolute(intercept_q34)))
print('---------------------------------')
print('slope_q12: ', slope_q12)
print('intercept_q12: ', intercept_q12)
print('r_value_q12: ', r_value_q12)
print('std_err_q12:', std_err_q12)
print('---------------------------------')
print('slope_q34: ', slope_q34)
print('intercept_q34: ', intercept_q34)
print('r_value_q34', r_value_q34)
print('std_err_q34', std_err_q34)
plt.figtext(0.2, 0.08, r'$M_s^{(q12)}:$ ' + ' a: ' + np.str(slope_q12) + ' b: ' + np.str(intercept_q12) + ' ' + r'$R^2:$' + np.str(r_value_q12*r_value_q12) + ' S: ' + np.str(std_err_q12), size=14)
plt.figtext(0.2, 0.06, r'$M_s^{(q34)}:$' + ' a: ' + np.str(slope_q34) + ' b: ' + np.str(intercept_q34) + ' ' + r'$R^2:$ ' + np.str(r_value_q34*r_value_q34) + ' S: ' + np.str(std_err_q34), size=14)
return np.array([slope_q12, slope_q34, intercept_q12, intercept_q34]);
def vsm_plot_anno_Hc(fit_params):
Hc1 = -1.0*(fit_params[2] / fit_params[0])
Hc2 = -1.0*(fit_params[3] / fit_params[1])
Hc_mean = 0.5*( np.absolute(Hc1) + np.absolute(Hc2) )
# plot annotations
ax = plt.gca()
#ax.text(Hc1-1.0, 0, r'$H_{c1}: $' + np.str(np.round(Hc1, 3)) , fontsize=15)
ax.annotate(r'$H_{c1}: $' + np.str(np.round(Hc1, 3)),
xy=(Hc1, 0), # theta, radius
xytext=(0.2, 0.5), # fraction, fraction
textcoords='axes fraction',
arrowprops=dict(arrowstyle="simple", color='blue'),
horizontalalignment='left',
verticalalignment='center',
fontsize=20
)
ax.annotate(r'$H_{c2}: $' + np.str(np.round(Hc2, 3)),
xy=(Hc2, 0), # theta, radius
xycoords='data',
xytext=(0.8, 0.5), # fraction, fraction
textcoords='axes fraction',
arrowprops=dict(arrowstyle="simple", color='red'),
horizontalalignment='right',
verticalalignment='center',
fontsize=20
)
ax.annotate(r'$H_c: $' + np.str(np.round(Hc_mean, 3)),
xy=(0, 0), # theta, radius
xycoords='data',
xytext=(0.95, 0.5), # fraction, fraction
textcoords='axes fraction',
#arrowprops=dict(facecolor='red', width=1.0, shrink=0.05),
horizontalalignment='right',
verticalalignment='center',
fontsize=20
)
return;
def vsm_plot_anno_Ms(fit_params):
Ms1 = fit_params[2]
Ms2 = fit_params[3]
Ms_mean = 0.5*( np.absolute(Ms1) + np.absolute(Ms2) )
# plot annotations
ax = plt.gca()
#ax.text(Hc1-1.0, 0, r'$H_{c1}: $' + np.str(np.round(Hc1, 3)) , fontsize=15)
ax.annotate(r'$M_{s1}: $' + np.str(np.round(Ms1, 3)),
xy=(-6000, Ms1), # theta, radius
xytext=(0.165, 0.25), # fraction, fraction
textcoords='axes fraction',
arrowprops=dict(arrowstyle="simple", color='green'),
horizontalalignment='left',
verticalalignment='center',
fontsize=20
)
ax.annotate(r'$M_{s2}: $' + np.str(np.round(Ms2, 3)),
xy=(6000, Ms2), # theta, radius
xycoords='data',
xytext=(0.83, 0.75), # fraction, fraction
textcoords='axes fraction',
arrowprops=dict(arrowstyle="simple", color='magenta'),
horizontalalignment='right',
verticalalignment='center',
fontsize=20
)
ax.annotate(r'$M_s: $' + np.str(np.round(Ms_mean, 3)),
xy=(0, 0), # theta, radius
xycoords='data',
xytext=(0.95, 0.95), # fraction, fraction
textcoords='axes fraction',
#arrowprops=dict(facecolor='red', width=1.0, shrink=0.05),
horizontalalignment='right',
verticalalignment='center',
fontsize=20
)
return;
def vsm_data_deskew(vsm_data, deskew_points):
tx_quater = (vsm_data.shape[1] - 1) / 4
ty_quater = (vsm_data.shape[1] - 1) / 4
xi1 = np.concatenate((vsm_data[0, 0:np.int_(deskew_points)], vsm_data[0, np.int_(vsm_data.shape[1] - 1 - deskew_points):np.int_(vsm_data.shape[1] - 1)]))
yi1 = np.concatenate((vsm_data[1, 0:np.int_(deskew_points)], vsm_data[1, np.int_(vsm_data.shape[1] - 1 - deskew_points):np.int_(vsm_data.shape[1] - 1)]))
# calculate linear fit parameters
slope_deskew, intercept_deskew, r_value_deskew, p_value_deskew, std_err_deskew = stats.linregress(xi1,yi1)
print(slope_deskew, intercept_deskew)
xd1 = vsm_data[0]
yd1 = vsm_data[1] - slope_deskew*vsm_data[0]
return np.array([xd1, yd1]);
###################################### plot this and that ############################################
def vsm_hst_plot(vsm_data, fit_params_Hc, fit_params_Ms):
# plot the data
# 'ro-' -> red circles with solid line
#if np.size(fit_params_Hc) == None and np.size(fit_params_Ms) == None:
# tx1, = plt.plot(vsm_data[0], vsm_data[1], 'co-', label=label_hdir)
# plt.legend([tx1], [label_hdir], loc='upper left', fontsize=20 , frameon=False)
#
#elif np.size(fit_params_Hc) != None and np.size(fit_params_Ms) == None:
# tx1, = plt.plot(vsm_data[0], vsm_data[1], 'co-', label=label_hdir)
# tx2, = plt.plot(vsm_data[0], fit_params_Hc[0]*vsm_data[0] + fit_params_Hc[2], 'b--')
# tx3, = plt.plot(vsm_data[0], fit_params_Hc[1]*vsm_data[0] + fit_params_Hc[3], 'r--')
# plt.legend([tx1, tx2, tx3], [label_hdir, r'$fit$', r'$fit$'], loc='upper left', fontsize=20 , #frameon=False)
#elif np.size(fit_params_Hc) == None and np.size(fit_params_Ms) != None:
# tx1, = plt.plot(vsm_data[0], vsm_data[1], 'co-', label=label_hdir)
# tx2, = plt.plot(vsm_data[0], fit_params_Ms[0]*vsm_data[0] + fit_params_Ms[2], 'g--')
# tx3, = plt.plot(vsm_data[0], fit_params_Ms[1]*vsm_data[0] + fit_params_Ms[3], 'm--')
# # display the legend for the defined labels
# plt.legend([tx1, tx2, tx3], [label_hdir, r'$fit$', r'$fit$'], loc='upper left', fontsize=20 , frameon=False)
#elif np.size(fit_params_Hc) != None and np.size(fit_params_Ms) != None:
tx1, = plt.plot(vsm_data[0], vsm_data[1], 'co-', label=label_hdir)
tx2, = plt.plot(vsm_data[0], fit_params_Hc[0]*vsm_data[0] + fit_params_Hc[2], 'b-.')
tx3, = plt.plot(vsm_data[0], fit_params_Hc[1]*vsm_data[0] + fit_params_Hc[3], 'r-.')
tx4, = plt.plot(vsm_data[0], fit_params_Ms[0]*vsm_data[0] + fit_params_Ms[2], 'g-.')
tx5, = plt.plot(vsm_data[0], fit_params_Ms[1]*vsm_data[0] + fit_params_Ms[3], 'm-.')
# display the legend for the defined labels
plt.legend([tx1, tx2, tx3, tx4, tx5], [label_hdir, r'$fit\;q23$', r'$fit\;q14$', r'$fit\;q12$', r'$fit\;q34$'], loc='lower right', fontsize=20 , frameon=True)
# fitted line for the inplane loop
# plt.plot(deskew_fit_range, fit_params[0]*deskew_fit_range + fit_params[1],'g-', label=label_inpl + 'fit')
# set x,y limits
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
return;
# Create a new figure of size 8x8 inches, using 100 dots per inch
# protip: A4 is 8.3 x 11.7 inches
fig = plt.figure(figsize=(16, 16), dpi=72)
fig.canvas.set_window_title('hst_hcms_plot_' + sample_mdate + sample_id)
# verison name text
plt.figtext(0.84, 0.99, version_name, size=14)
spec = gridspec.GridSpec(ncols=1, nrows=1)
# load raw data from measuremnt files for sample_no: 3
vsm_files_in = vsm_open_in(sample_mdate, sample_id, sample_no)
vsm_data_deskewed = vsm_data_deskew(vsm_files_in, deskew_points)
vsm_fit_params_Hc = vsm_fit_hst_Hc(vsm_data_deskewed, Hc_fit_points_q23, Hc_fit_points_q14, Hc_creep_q14, Hc_creep_q23)
vsm_fit_params_Ms = vsm_fit_hst_Ms(vsm_data_deskewed, Ms_fit_points_q12, Ms_fit_points_q34, Ms_creep_q12, Ms_creep_q34)
xy1 = fig.add_subplot(spec[0,0])
# set title of the plot
plt_title = gen_plot_title(0)
# plot hysteresis loops and fited data
vsm_hst_plot(vsm_data_deskewed, vsm_fit_params_Hc, vsm_fit_params_Ms)
# format axis and add labels
vsm_plot_anno_Hc(vsm_fit_params_Hc)
vsm_plot_anno_Ms(vsm_fit_params_Ms)
custom_axis_formater(plt_title, axis_label_mu0H, axis_label_mu0M, xmin, xmax, ymin, ymax, xprec, yprec)
plt.subplots_adjust(left=0.15, bottom=0.15, wspace=0.0, hspace=0.0)
fig.tight_layout(pad=11.0, w_pad=0.0, h_pad=0.0)
# Write a pdf file with fig and close
pp = PdfPages(out_pdf)
pp.savefig(fig)
pp.close()
fig = plt.savefig(out_svg)
# Show plot preview
plt.show()
<file_sep># hst_hcms_plot
VSM measurement data ploter with fitting
| 1962c65a2ffc4c27c82b262e28a2f3c973c1d386 | [
"Markdown",
"Python"
] | 2 | Python | tatsunootoshigoio/hsthcms | 77b3df941d5f17f093c125b564952b3da43d7d3f | a7041a05ff955ec7bf356efdaa88be5f9d51915d |
refs/heads/master | <file_sep><?php
/**
* Controller is the customized base controller class.
* All controller classes for this application should extend from this base class.
*/
class Controller extends CController
{
/**
* @var string the default layout for the controller view. Defaults to '//layouts/column1',
* meaning using a single column layout. See 'protected/views/layouts/column1.php'.
*/
public $layout='//layouts/main';
/**
* @var array context menu items. This property will be assigned to {@link CMenu::items}.
*/
public $menu=array();
/**
* @var array the breadcrumbs of the current page. The value of this property will
* be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
* for more details on how to specify this property.
*/
public $breadcrumbs=array();
/**
* @var User who accessed the page
*/
public $user;
/**
* @var Calendar calendar that is being viewed
*/
public $currentCalendar;
/**
* @var Calendar[] all calendars, user can access (his own and that were shared with him)
*/
public $calendars;
public function __construct() {
$this->user = User::model()->findByPk(Yii::app()->user->id);
if ($this->user) {
$this->calendars = $this->user->calendars;
$currentCalendarId = CHttpRequest::getParam('calendarId');
if ($currentCalendarId) {
$this->currentCalendar = Calendar::model()->findByPk($currentCalendarId);
}
// navigation links
foreach ($this->calendars as $calendar) {
if ($calendar->id == $currentCalendarId) continue;
$this->menu[] = array(
'title' => htmlspecialchars($calendar->name),
'link_args' => array('calendar/view', 'calendarId' => $calendar->id, 'date' => date('Y-m-d'), 'view' => 'month')
);
}
}
}
}<file_sep><?php if ($error) : ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>
<?php if ($successMsg) : ?>
<div class="alert alert-success"><?php echo $successMsg; ?></div>
<?php endif; ?>
<h1>Settings</h1>
<div class="row">
<div class="col-lg-3 col-md-3">
<h3>Change password</h3>
<form role="form" method="post">
<input type="hidden" name="op" value="change_pass"/>
<div class="form-group">
<input type="<PASSWORD>" class="form-control" id="inputPassword" placeholder="Current <PASSWORD>" name="user[password_current]">
</div>
<div class="form-group">
<input type="<PASSWORD>" class="form-control" id="inputPassword" placeholder="<PASSWORD>" name="user[password]">
</div>
<div class="form-group">
<input type="<PASSWORD>" class="form-control" id="inputPassword2" placeholder="Repeat <PASSWORD>" name="user[password_repeat]">
</div>
<button type="submit" class="btn btn-primary pull-right">Change</button>
</form>
</div>
<div class="col-lg-3 col-md-3">
<h3>Change information</h3>
<form role="form" method="post">
<input type="hidden" name="op" value="change_data"/>
<div class="form-group">
<input type="text" class="form-control" id="inputPassword" placeholder="E-mail" name="user[email]" value="<?php echo $user->email;?>">
</div>
<button type="submit" class="btn btn-primary pull-right">Save</button>
</form>
</div>
</div><file_sep><?php
class CalendarController extends Controller {
public function __construct() {
parent::__construct();
}
public function filters() {
return array(
'accessControl',
);
}
public function accessRules() {
return array(
array('deny',
'actions'=>array('index', 'view', 'search', 'get', 'save', 'delete', 'share', 'export'),
'users'=>array('?'),
)
);
}
/**
* Main page. List of calendars
*/
public function actionIndex() {
$this->render('calendar/index');
}
/**
* Calendar view (month/week/day)
* @param integer $calendarId
* @param string $date date format - d.m.Y OR Y-m-d
* @param string $view month, week or day view
*/
public function actionView($calendarId, $date = null, $view = 'month') {
if (!$date) {
$date = date('d.m.Y');
}
$view = strtolower($view);
if ( !($dateElements = DateHelper::parseDate($date)) || !in_array($view, array('day','month','week')) ) {
die('Wrong input');
}
if (!AccessHelper::hasAccess($this->user, $this->currentCalendar)) {
die('No access!');
}
// events search conditions (calendar id & date interval)
$params = array();
$criteria = new CDbCriteria;
$criteria->addCondition('calendar_id=:calendar_id');
$params[':calendar_id'] = $this->currentCalendar->id;
if ($view == 'week') {
$startDate = DateHelper::firstDayOfWeek($dateElements['year'], $dateElements['month'], $dateElements['day']);
$criteria->addCondition('DATE(time_start)>=:date AND DATE(time_start)<:date + INTERVAL 1 WEEK');
$params[':date'] = $startDate;
} elseif ($view == 'day') {
$criteria->addCondition('DATE(time_start)=:date');
$params[':date'] = date('Y-m-d', strtotime($date));
} else {
$criteria->addCondition('DATE(time_start)>=:date AND DATE(time_start)<:date + INTERVAL 1 MONTH');
$params[':date'] = date('Y-m-01', strtotime($date));
$view = 'month';
}
$criteria->params = $params;
$events = Event::model()->findAll($criteria);
$this->render(
'calendar/' . $view,
array('events' => $events, 'date' => $date) + $dateElements
);
}
/**
* Search view. Search results.
*/
public function actionSearch() {
$keyword = CHttpRequest::getParam('keyword');
$criteria = new CDbCriteria;
$criteria->condition = '(name LIKE :keyword OR description LIKE :keyword)
AND calendar_id IN (SELECT calendar_id FROM calendar_user WHERE user_id = :user_id)';
$criteria->params = array(':keyword' => "%{$keyword}%", ':user_id'=>$this->user->id);
$events = Event::model()->findAll($criteria);
$this->render(
'calendar/search',
array('events' => $events)
);
}
/**
* Ajax, json. Returns calendar information.
* @param integer $calendarId
*/
public function actionGet($calendarId) {
settype($calendarId, 'integer');
if (Yii::app()->request->isAjaxRequest && AccessHelper::hasAccess($this->user, $this->currentCalendar)) {
$calendar = Calendar::model()->findByPk($calendarId);
if ($calendar) {
echo json_encode(
array(
'id' => $calendar->id,
'name' => $calendar->name
)
);
return;
}
}
throw new CHttpException(403,'Error');
}
/**
* Ajax. Saves(updates) calendar information.
*/
public function actionSave() {
if (Yii::app()->request->isAjaxRequest) {
$calendarId = CHttpRequest::getParam('calendarId');
$calendarName = CHttpRequest::getParam('calendarName');
$calendar = Calendar::model()->findByPk($calendarId);
if ($calendar) {
if (!AccessHelper::canModify($this->user, $calendar)) {
throw new CHttpException(403,'Error');
}
$calendar->name = $calendarName;
$calendar->save();
} else {
$calendar = new Calendar;
$calendar->name = $calendarName;
$calendar->time_created = date('Y-m-d H:i:s');
$calendar->owner_id = Yii::app()->user->id;
if ($calendar->save()) {
$calendarUser = new CalendarUser;
$calendarUser->user_id = Yii::app()->user->id;
$calendarUser->calendar_id = $calendar->id;
$calendarUser->save();
} else {
throw new CHttpException(403, 'Error');
}
}
return;
}
throw new CHttpException(403,'Error');
}
/**
* Ajax. Adds rights to other user to see calendar and its events
*/
public function actionShare() {
if (Yii::app()->request->isAjaxRequest && AccessHelper::canModify($this->user, $this->currentCalendar)) {
$calendarId = CHttpRequest::getParam('calendarId');
$username = CHttpRequest::getParam('username');
$user = User::model()->findByAttributes(array('username' => $username));
if ($user) {
$calendarUser = new CalendarUser();
$calendarUser->user_id = $user->id;
$calendarUser->calendar_id = $calendarId;
$calendarUser->save();
return;
} else {
throw new CHttpException(404, 'User not found');
}
}
throw new CHttpException(403,'Error');
}
/**
* Deletes calendar
* @param integer $calendarId
*/
public function actionDelete($calendarId) {
if (AccessHelper::canModify($this->user, $this->currentCalendar)) {
Calendar::model()->deleteByPk($calendarId);
$this->redirect(array('calendar/index'));
}
}
/**
* Exports calendar as ICS file.
* @param integer $calendarId
*/
public function actionExport($calendarId) {
$calendar = Calendar::model()->findByPk($calendarId);
if ($calendar) {
if (!AccessHelper::hasAccess($this->user, $calendar)) {
die('Access denied!');
} else {
ExportHelper::exportICS($calendar);
}
} else {
throw new CHttpException(403,'Error');
}
}
}<file_sep><?php
class ExportHelper {
/**
* Creates ICS file from calendar object
* @param Calendar $calendar
* @param boolean $forceDownload
* @param string $filename
* @return string returns output if $forceDownload is false
*/
public static function exportICS(Calendar $calendar, $forceDownload = true, $filename = 'export.ics') {
$output = <<<OUTPUT
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
OUTPUT;
foreach ($calendar->events as $event) {
$str= <<<OUTPUT
\nBEGIN:VEVENT
UID:{uid}
LOCATION:{location}
DTSTAMP:{created}
DTSTART:{start}
DTEND:{end}
SUMMARY:{event_name}
DESCRIPTION:{description}
END:VEVENT\n
OUTPUT;
$created = date('Ymd', strtotime($event->time_created)).'T'. date('His', strtotime($event->time_created)).'Z';
$start = date('Ymd', strtotime($event->time_start)).'T'. date('His', strtotime($event->time_start)).'Z';
$end = $event->time_end ? date('Ymd', strtotime($event->time_end)).'T'. date('His', strtotime($event->time_end)).'Z' : $start;
$str = str_replace('{event_name}', strtoupper(str_replace(' ', '_', $event->name)), $str);
$str = str_replace('{location}', $event->location, $str);
$str = str_replace('{created}', $created, $str);
$str = str_replace('{start}', $start, $str);
$str = str_replace('{end}', $end, $str);
$str = str_replace('{description}', $event->description, $str);
$str = str_replace('{uid}', "{$event->id}@calendar", $str);
$output.= $str;
}
$output .= "END:VCALENDAR";
//set correct content-type-header
if ($forceDownload) {
header("Content-type: text/calendar; charset=utf-8");
header("Content-Disposition: inline; filename={$filename}");
echo $output;
}
return $output;
}
}<file_sep>calendar
========
PHP Yii calendar, TTU project
========
PHP calendar created using Yii 2.0, Bootstap 3, JQuery 1.10.2 and Google Maps API.
Database SQL file is in /protected/data folder.
<file_sep><?php
class User extends CActiveRecord {
public $passwordRepeat;
public $isPasswordChanged = false;
public static function model($className=__CLASS__) {
return parent::model($className);
}
public function tableName() {
return 'user';
}
public function relations() {
return array(
'calendars'=>array(self::MANY_MANY, 'Calendar', 'calendar_user(calendar_id, user_id)'),
);
}
public function beforeSave() {
if(parent::beforeSave() && $this->isNewRecord) {
$this->password = UserIdentity::encodePassword($this->password);
$this->registration_time = date('Y-m-d H:i:s');
}
if ($this->isPasswordChanged) {
$this->password = UserIdentity::encodePassword($this->password);
}
return true;
}
public function rules() {
return array(
array('username, password', 'required'),
array('username', 'length', 'min' => 4, 'max'=>20),
array('password', 'length', 'min' => 4),
array('passwordRepeat', 'required', 'on'=>'register'),
array('passwordRepeat', 'required', 'on'=>'changePassword'),
array('password', 'compare', 'compareAttribute'=>'passwordRepeat', 'on'=>'register'),
array('password', 'compare', 'compareAttribute'=>'passwordRepeat', 'on'=>'changePassword'),
array('username', 'unique'),
array('email', 'email'),
);
}
}<file_sep><?php
class AccessHelper {
/**
* Returns true if user can access calendar or event in given calendar
* @param User $user
* @param Calendar $calendar
* @return boolean
*/
public static function hasAccess(User $user, Calendar $calendar) {
foreach ($calendar->users as $calendUser) {
if ($user->id == $calendUser->id) {
return true;
}
}
return false;
}
/**
* Returns true if user can modifiy/delete calendar or create/modify/delete event in given calendar
* @param User $user
* @param Calendar $calendar
* @return boolean
*/
public static function canModify(User $user, Calendar $calendar) {
return $calendar->owner_id == $user->id;
}
}<file_sep><?php
class EventController extends Controller {
public function __construct() {
parent::__construct();
}
public function filters() {
return array(
'accessControl',
);
}
public function accessRules() {
return array(
array('deny',
'actions'=>array('id', 'create', 'edit', 'delete', 'get'),
'users'=>array('?'),
)
);
}
/**
* Event information
* @param integer $eventId
*/
public function actionId($eventId) {
$event = Event::model()->findByPk($eventId);
if (!$event) {
throw new CHttpException(404, 'Event not found!');
exit;
}
if (!AccessHelper::hasAccess($this->user, $event->calendar)) {
throw new CHttpException(403, 'Forbidden');
exit;
}
$this->render(
'event/id',
array('event' => $event)
);
}
/**
* New event page
* @param integer $calendarId
* @param string $date
*/
public function actionCreate($calendarId, $date = null) {
$errorMsg = NULL;
$event = new Event();
$event->setDateStart($date);
if (CHttpRequest::getParam('event')) {
$eventData = CHttpRequest::getParam('event');
$event->calendar_id = $calendarId;
$event->name = $eventData['name'];
$event->time_start = $eventData['time_start'];
$event->time_end = $eventData['time_end'];
$event->location = $eventData['location'];
$event->description = $eventData['description'];
if ($event->validate()) {
if ($event->save()) {
$this->redirect(array('event/id', 'eventId' => $event->id));
} else {
$errorMsg = 'Error occured!';
}
} else {
$errorMsg = CHtml::errorSummary($event);
}
}
$this->render(
'event/create',
array('event' => $event, 'errorMsg' => $errorMsg)
);
}
/**
* Ajax, json. Returns events for given calendar and date
* @param integer $calendarId
* @param string $date
*/
public function actionGet($calendarId, $date) {
if (Yii::app()->request->isAjaxRequest) {
$dbDate = date('Y-m-d', strtotime($date));
$eventsArr = array();
$events = Event::model()->findAllBySql(
'SELECT * FROM event WHERE calendar_id=:calendar_id AND DATE(time_start)=:date ORDER BY time_start ASC',
array('calendar_id'=>$calendarId, 'date'=>$dbDate)
);
foreach ($events as $event) {
$time = $event->getFTimeInterval();
// removing date. Example: 03.12.2013 14:00 - 04.12.2013 00:00 => 14:00 - 04.12.2013 00:00
$time = trim(str_replace($date, '', $time));
$eventsArr[] = array(
'id' => $event->id,
'name' => htmlspecialchars($event->name),
'time' => $time,
'location' => htmlspecialchars($event->location),
'description' => $event->description
);
}
echo json_encode($eventsArr);
return;
}
throw new CHttpException(403,'Error');
}
/**
* Saves (updates) event information.
*/
public function actionEdit($eventId) {
$errorMsg = NULL;
$event = Event::model()->findByPk($eventId);
if (!$event) {
throw new CHttpException(404, 'Event not found!');
exit;
}
if (!AccessHelper::hasAccess($this->user, $event->calendar)) {
throw new CHttpException(403, 'Forbidden');
exit;
}
if (CHttpRequest::getParam('event')) {
$eventData = CHttpRequest::getParam('event');
$event->name = $eventData['name'];
$event->time_start = $eventData['time_start'];
$event->time_end = $eventData['time_end'];
$event->location = $eventData['location'];
$event->description = $eventData['description'];
if ($event->validate()) {
if ($event->save()) {
$this->redirect(array('event/id', 'eventId' => $event->id));
} else {
$errorMsg = 'Error occured!';
}
} else {
$errorMsg = CHtml::errorSummary($event);
}
}
$this->render(
'event/edit',
array('event' => $event, 'errorMsg' => $errorMsg)
);
}
/**
* Deletes event
*/
public function actionDelete($eventId) {
$event = Event::model()->findByPk($eventId);
if ($event) {
$calendarId = $event->calendar_id;
$eventDate = $event->getDateStart();
if (!AccessHelper::hasAccess($this->user, $event->calendar)) {
throw new CHttpException(403, 'Forbidden');
exit;
}
Event::model()->deleteByPk($eventId);
$this->redirect(array('calendar/view', 'calendarId' => $calendarId, 'date' => $eventDate));
} else {
throw new CHttpException(404, 'Not Found');
exit;
}
}
}<file_sep><h3>Search</h3>
<table class="table table-justify">
<?php foreach($events as $event) : ?>
<tbody>
<tr>
<td><?php echo CHtml::link(htmlspecialchars($event->name),array('event/id', 'eventId' => $event->id));?></td>
<td><?php echo $event->description;?></td>
<td><?php echo $event->getFTimeInterval();?></td>
</tr>
</tbody>
<?php endforeach; ?>
</table><file_sep><?php /* @var $this Controller */ ?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<link href="<?php echo Yii::app()->request->baseUrl; ?>/assets/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="<?php echo Yii::app()->request->baseUrl; ?>/assets/css/style.css" rel="stylesheet" media="screen">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/html5shiv.js"></script>
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<ul class="nav navbar-nav">
<li class="dropdown">
<?php if (isset($this->currentCalendar)) : ?>
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><?php echo htmlspecialchars($this->currentCalendar->name);?> <b class="caret"></b></a>
<?php else : ?>
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Calendars <b class="caret"></b></a>
<?php endif; ?>
<ul class="dropdown-menu">
<li><?php echo CHtml::link('All calendars', array('calendar/index'));?></li>
<li class="divider"></li>
<?php foreach($this->menu as $link) : ?>
<li><?php echo CHtml::link($link['title'], $link['link_args']);?></li>
<?php endforeach; ?>
<li class="divider"></li>
<li><a href="javascript:showCalendarFormModal();">New calendar</a></li>
</ul>
</li>
</ul>
<form class="navbar-form navbar-left" role="search" method="post" action="index.php?r=calendar/search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name="keyword" value="<?php echo CHttpRequest::getParam('keyword');?>">
</div>
<input type="submit" class="btn btn-default" value="Submit">
</form>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav navbar-right">
<li><?php echo CHtml::link('<span class="glyphicon glyphicon-cog"></span> Settings', array('user/settings'));?></li>
<li><?php echo CHtml::link('<span class="glyphicon glyphicon-log-out"></span> Logout', array('user/logout'));?></li>
</ul>
</div><!-- /.navbar-collapse -->
</nav>
<div class="container">
<?php echo $content; ?>
</div>
<div class="modal fade" id="eventsModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<?php if (isset($this->currentCalendar) && AccessHelper::canModify($this->user, $this->currentCalendar)) : ?>
<a href="#" class="btn btn-default btn-xs pull-left" id="addEventBtn">Add</a>
<?php endif; ?>
<h4 class="modal-title text-center">Event</h4>
</div>
<div class="modal-body">
<table class="table table-justify table-condensed" id="eventsSmallList">
<tbody></tbody>
</table>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<div class="modal fade" id="calendarModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="calendarModalTitle">New calendar</h4>
</div>
<div class="modal-body">
<input type="hidden" name="id"/>
<label for="calendarName">Calendar name</label>
<input type="text" class="form-control" id="calendarName" placeholder="Calendar name" name="name">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="saveCalendarBtn">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/bootstrap.min.js"></script>
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/ckeditor/ckeditor.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/js.js"></script>
<script>
$(document).ready(function () {
google.maps.event.addDomListener(window, 'load', initialize);
});
</script>
<script>
$(document).ready(function () {
CKEDITOR.replace('cke');
});
</script>
</body>
</html><file_sep><?php if (AccessHelper::canModify($this->user, $event->calendar)) : ?>
<div class="pull-right">
<?php echo CHtml::link('New event', array('event/create', 'calendarId' => $event->calendar_id), array('class' => 'btn btn-default'));?>
<div class="btn-group">
<?php echo CHtml::link('Edit', array('event/edit', 'eventId' => $event->id), array('class' => 'btn btn-default'));?>
<?php echo CHtml::link('Delete', array('event/delete', 'eventId' => $event->id), array('class' => 'btn btn-default'));?>
</div>
</div>
<?php endif; ?>
<h2 class="text-center">
<?php
echo CHtml::link(
htmlspecialchars($event->calendar->name),
array('calendar/view', 'calendarId' => $event->calendar_id, 'view'=>'month', 'date'=>$event->getDateStart())
);?> /
<?php echo htmlspecialchars($event->name);?>
</h2>
<div class="row">
<div class="col-md-6 col-lg-6">
<p><span class="text-muted">When?</span> <?php echo $event->getFTimeInterval();?></p>
<p><span class="text-muted">What?</span><br/> <?php echo $event->description;?></p>
</div>
<div class="col-md-offset-1 col-lg-offset-1 col-md-5 col-lg-5">
<span class="text-muted">Where?</span> <span id="inputWhere"><?php echo htmlspecialchars($event->location); ?></span><br/>
<div id="map-canvas"></div>
</div>
</div>
<file_sep><a href="javascript:showCalendarFormModal();" class="btn btn-default pull-right">New calendar</a>
<h3>All calendars</h3>
<div class="clearfix"></div>
<table class="table mt20">
<tbody>
<?php foreach ($this->user->calendars as $calendar) :?>
<tr>
<td>
<?php
echo CHtml::link(
htmlspecialchars($calendar->name),
array('calendar/view', 'calendarId' => $calendar->id, 'date' => date('Y-m-d'), 'view' => 'month')
);
?>
</td>
<td><?php echo $calendar->eventsCount; ?> events</td>
<td><?php echo $calendar->usersCount - 1; ?> shares</td>
<td class="w200">
<?php echo CHtml::link('Export', array('calendar/export', 'calendarId' => $calendar->id), array('class'=>'btn btn-default btn-xs'));?>
<?php if (AccessHelper::canModify($this->user, $calendar)) : ?>
<a href="javascript:showCalendarFormModal(<?php echo $calendar->id;?>);" class="btn btn-default btn-xs">Edit</a>
<?php echo CHtml::link('Delete', array('calendar/delete', 'calendarId' => $calendar->id), array('class'=>'btn btn-danger btn-xs'));?>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table><file_sep><?php
class NavigationHelper {
/**
* Common function to create links
* @param string $title
* @param integer $calendarId
* @param string $date
* @param string $view
* @param string $diff
* @return string
*/
protected static function calendarLink($title, $calendarId = null, $date = null, $view, $diff) {
if (!$calendarId) $calendarId = CHttpRequest::getParam('calendarId');
if (!$date) $date = CHttpRequest::getParam('date');
return CHtml::link(
$title,
array('calendar/view', 'calendarId' => $calendarId, 'date' => date('Y-m-d', strtotime($date . ' ' . $diff)) , 'view' => $view)
);
}
/**
* @param integer $calendarId
* @param string $date
* @return string
*/
public static function nextMonthLink($calendarId = null, $date = null) {
return self::calendarLink('›', $calendarId, $date, 'month', 'first day of next month');
}
public static function prevMonthLink($calendarId = null, $date = null) {
return self::calendarLink('‹', $calendarId, $date, 'month', 'first day of previous month');
}
public static function nextWeekLink($calendarId = null, $date = null) {
return self::calendarLink('›', $calendarId, $date, 'week', '+7 days');
}
public static function prevWeekLink($calendarId = null, $date = null) {
return self::calendarLink('‹', $calendarId, $date, 'week', '-7 days');
}
public static function nextDayLink($calendarId = null, $date = null) {
return self::calendarLink('›', $calendarId, $date, 'day', '+1 days');
}
public static function prevDayLink($calendarId = null, $date = null) {
return self::calendarLink('‹', $calendarId, $date, 'day', '-1 days');
}
}<file_sep><?php if (AccessHelper::canModify($this->user, $this->currentCalendar)) : ?>
<div class="btn-group pull-right">
<a id="shareCalendarBtn" class="btn btn-default">Share calendar</a>
<?php
echo CHtml::link(
'New Event',
array('event/create', 'calendarId' => $this->currentCalendar->id, 'date' => $date),
array('class' => 'btn btn-default')
);
?>
</div>
<?php endif; ?>
<div class="row">
<div class="col-lg-2">
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Month view <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>
<?php
echo CHtml::link(
'Week view',
array('calendar/view', 'calendarId' => $this->currentCalendar->id, 'date' => $date, 'view' => 'week')
);
?>
</li>
<li>
<?php
echo CHtml::link(
'Day view',
array('calendar/view', 'calendarId' => $this->currentCalendar->id, 'date' => $date, 'view' => 'day')
);
?>
</li>
</ul>
</div>
</div>
</div>
<h1 class="text-center">
<?php echo NavigationHelper::prevMonthLink(); ?>
<?php echo DateHelper::monthName($month); ?>
<?php echo $year; ?>
<?php echo NavigationHelper::nextMonthLink(); ?>
</h1>
<div class="clearfix mt20"></div>
<table class="table table-bordered calendar">
<tbody>
<?php
$dayNumber = 0;
$flag = false;
for ($i = 0; $i < 6; $i++) :
?>
<tr>
<?php for ($j = 1; $j <= 7; $j++) : ?>
<td>
<?php
if ($i == 0 && $j == DateHelper::dayOfTheWeek($year, $month, 1)) {
$flag = true;
}
if ($flag && $dayNumber < DateHelper::daysInMonth($year, $month)) {
++$dayNumber;
$date = date("d.m.Y", strtotime("{$year}-{$month}-{$dayNumber}"));
echo "<a href=\"javascript:showEventsModal({$this->currentCalendar->id}, '{$date}');\" class=\"pull-right\">{$dayNumber}</a>";
}
$e = 0;
foreach ($events as $event) {
if ($e++ > 3) break;
if ($event->isHappeningOn(date("Y-m-d", strtotime("{$year}-{$month}-{$dayNumber}")))) {
echo "<div class=\"eventSmall\">";
echo CHtml::link(htmlspecialchars($event->name), array('event/id', 'eventId' => $event->id));
echo "</div>";
}
}
?>
</td>
<?php endfor; ?>
</tr>
<?php endfor; ?>
</tbody>
</table><file_sep><?php if (isset($errorMsg) && $errorMsg) : ?>
<div class="alert alert-danger"><?php echo $errorMsg; ?></div>
<?php endif; ?>
<h2 class="text-center">New event</h2>
<div class="row" style="height:100%;">
<div class="col-md-6 col-lg-6">
<form role="form" method="post">
<div class="form-group">
<label for="inputName">Event name</label>
<input type="text" class="form-control" id="inputName" placeholder="Event name" name="event[name]" value="<?php echo $event->name;?>"/>
</div>
<div class="form-group">
<label>When?</label>
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" placeholder="dd.mm.yyyy hh:mm" name="event[time_start]" value="<?php echo $event->getFTimeStart();?>"/>
</div>
—
<div class="form-group">
<input type="text" class="form-control" placeholder="dd.mm.yyyy hh:mm" name="event[time_end]" value="<?php echo $event->getFTimeEnd();?>"/>
</div>
</div>
</div>
<div class="form-group">
<label for="inputWhere">Where?</label>
<input type="text" class="form-control" id="inputWhere" placeholder="Location" name="event[location]" value="<?php echo $event->location;?>"/>
</div>
<div class="form-group">
<label for="inputName">What?</label>
<textarea id="cke" name="event[description]"><?php echo $event->description;?></textarea>
</div>
<input type="submit" class="btn btn-primary" value="Save">
</form>
</div>
<div class="col-md-offset-1 col-lg-offset-1 col-md-5 col-lg-5">
<span class="text-muted">You can point on the map or write location address if you want.</span><br/>
<div id="map-canvas"></div>
</div>
</div><file_sep>-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Dec 27, 2013 at 01:07 PM
-- Server version: 5.5.25
-- PHP Version: 5.3.13
--
-- Database: `calendar`
--
-- --------------------------------------------------------
--
-- Table structure for table `calendar`
--
CREATE TABLE IF NOT EXISTS `calendar` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(30) COLLATE utf8_estonian_ci NOT NULL,
`time_created` datetime NOT NULL,
`owner_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `owner_id` (`owner_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_estonian_ci AUTO_INCREMENT=12 ;
-- --------------------------------------------------------
--
-- Table structure for table `calendar_user`
--
CREATE TABLE IF NOT EXISTS `calendar_user` (
`calendar_id` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`calendar_id`,`user_id`),
KEY `calendar_user_ibfk_2` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_estonian_ci;
-- --------------------------------------------------------
--
-- Table structure for table `event`
--
CREATE TABLE IF NOT EXISTS `event` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`calendar_id` int(10) unsigned NOT NULL,
`time_start` datetime NOT NULL,
`time_end` datetime DEFAULT NULL,
`name` varchar(255) COLLATE utf8_estonian_ci NOT NULL,
`location` varchar(200) COLLATE utf8_estonian_ci DEFAULT NULL,
`description` text COLLATE utf8_estonian_ci NOT NULL,
`time_created` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `calendar_id` (`calendar_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_estonian_ci AUTO_INCREMENT=14 ;
--
-- Table structure for table `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(20) COLLATE utf8_estonian_ci NOT NULL,
`password` varchar(40) COLLATE utf8_estonian_ci NOT NULL,
`email` varchar(255) COLLATE utf8_estonian_ci NOT NULL,
`registration_time` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_estonian_ci AUTO_INCREMENT=5 ;
--
-- Constraints for table `calendar`
--
ALTER TABLE `calendar`
ADD CONSTRAINT `calendar_ibfk_1` FOREIGN KEY (`owner_id`) REFERENCES `user` (`id`) ON UPDATE CASCADE;
--
-- Constraints for table `calendar_user`
--
ALTER TABLE `calendar_user`
ADD CONSTRAINT `calendar_user_ibfk_1` FOREIGN KEY (`calendar_id`) REFERENCES `calendar` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `calendar_user_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `event`
--
ALTER TABLE `event`
ADD CONSTRAINT `event_ibfk_1` FOREIGN KEY (`calendar_id`) REFERENCES `calendar` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;<file_sep><?php
class UserController extends Controller {
public function __construct() {
parent::__construct();
}
public function filters() {
return array(
'accessControl',
);
}
public function accessRules() {
return array(
array('deny',
'actions'=>array('settings'),
'users'=>array('?'),
)
);
}
/**
* Login page
*/
public function actionLogin() {
$this->layout = false;
$username = CHttpRequest::getParam('username');
$password = CHttpRequest::getParam('password');
$error = NULL;
if ($username && $password) {
$identity = new UserIdentity($username,$password);
if($identity->authenticate()) {
Yii::app()->user->login($identity);
$this->redirect(array('calendar/index'));
} else {
$error = 'Auth failed!'; // $identity->errorMessage;
}
}
$this->render('/user/login', array('error' => $error));
}
/**
* Logout
*/
public function actionLogout() {
Yii::app()->user->logout();
$this->redirect(array('user/login'));
}
/**
* Registration page
*/
public function actionRegister() {
$this->layout = false;
$user = new User;
$error = NULL;
// if POST request
if (CHttpRequest::getParam('user')) {
$userData = CHttpRequest::getParam('user');
$user->setScenario('register');
$user->username = $userData['username'];
$user->password = $userData['<PASSWORD>'];
$user->passwordRepeat = $userData['<PASSWORD>_<PASSWORD>'];
$user->email = $userData['email'];
if ($user->validate()) {
if ($user->save()) {
$this->redirect(array('user/login'));
} else {
$error = 'Error saving user data!';
}
} else {
$error = CHtml::errorSummary($user);
}
}
$this->render('/user/register', array('user'=>$user, 'error'=>$error));
}
/**
* User settings
*/
public function actionSettings() {
$this->user = $user = User::model()->findByPk(Yii::app()->user->id);
$this->calendars = $this->user->calendars;
$error = NULL;
$successMsg = NULL;
// if POST request
if (CHttpRequest::getParam('user')) {
$userData = CHttpRequest::getParam('user');
if (CHttpRequest::getParam('op') == 'change_pass') {
// user wants to change password
$identity = new UserIdentity($user->username, $userData['<PASSWORD>']);
if($identity->authenticate()) {
$user->setScenario('changePassword');
$user->password = $<PASSWORD>['<PASSWORD>'];
$user->passwordRepeat = $<PASSWORD>['<PASSWORD>'];
$user->isPasswordChanged = true;
} else {
$error = 'You entered invalid password!';
}
} elseif (CHttpRequest::getParam('op') == 'change_data') {
// user wants to update information (email...)
$user->email = $userData['email'];
}
// validating and updating data
if ($user->validate() && !$error) {
if ($user->save()) {
$successMsg = 'Data successfully changed!';
} else {
$error = 'Error saving user data!';
}
} elseif (!$error) {
$error = CHtml::errorSummary($user);
}
}
$this->render('/user/settings', array('user'=>$user, 'error'=>$error, 'successMsg'=>$successMsg));
}
}<file_sep><?php
class Calendar extends CActiveRecord {
public static function model($className=__CLASS__) {
return parent::model($className);
}
public function tableName() {
return 'calendar';
}
public function relations() {
return array(
'users'=>array(self::MANY_MANY, 'User', 'calendar_user(calendar_id, user_id)'),
'owner'=>array(self::BELONGS_TO, 'User', 'owner_id'),
'events'=>array(self::HAS_MANY, 'Event', 'calendar_id'),
'eventsCount'=>array(self::STAT, 'Event', 'calendar_id'),
'usersCount'=>array(self::STAT, 'User', 'calendar_user(calendar_id, user_id)'),
);
}
public function beforeSave() {
parent::beforeSave();
$this->name = trim($this->name);
if (!$this->name) {
$this->name = '(no name)';
}
return true;
}
}<file_sep><?php
class Event extends CActiveRecord {
public static function model($className=__CLASS__) {
return parent::model($className);
}
public function tableName() {
return 'event';
}
public function relations() {
return array(
'calendar'=>array(self::BELONGS_TO, 'Calendar', 'calendar_id'),
);
}
public function beforeSave() {
if(parent::beforeSave() && $this->isNewRecord) {
$this->time_created = date('Y-m-d H:i:s');
}
$this->name = trim($this->name);
if (!$this->name) {
$this->name = '(no name)';
}
$this->time_start = date('Y-m-d H:i:00', strtotime($this->time_start));
$this->time_end = $this->time_end ? date('Y-m-d H:i:00', strtotime($this->time_end)) : null;
return true;
}
public function rules() {
return array(
array('name, time_start', 'required')
);
}
/*
* ==============================================================
*/
public function isHappeningOn($date, $hour = null) {
if ($hour === NULL) {
return $date == date('Y-m-d', strtotime($this->time_start));
} else {
if ($hour < 10) {
$hour = '0'.$hour;
}
return date('Y-m-d H', strtotime($this->time_start)) == "{$date} {$hour}";
}
}
public function getDateStart() {
return date('d.m.Y', strtotime($this->time_start));
}
public function getFTimeStart() {
if ($this->time_start) {
return date('d.m.Y H:i', strtotime($this->time_start));
}
return null;
}
public function getFTimeEnd() {
if ($this->time_end) {
return date('d.m.Y H:i', strtotime($this->time_end));
}
return null;
}
public function getFTimeInterval() {
$return = '';
if ($this->time_start) {
if ($this->time_end) {
$return = $this->getFTimeStart();
$return.= ' - ';
$return.= $this->getFTimeEnd();
} else {
$return = date('d.m.Y H:i', strtotime($this->time_start));
$return = str_replace("00:00", '', $return);
}
}
if ($this->time_start == $this->time_end) {
$return = date('d.m.Y H:i', strtotime($this->time_start));
}
return $return;
}
public function setDateStart($date) {
if (!$date) {
$date = date('d.m.Y');
}
$this->time_start = date('Y-m-d H:00:00', strtotime($date));
}
}<file_sep><?php /* @var $this Controller */ ?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<link href="<?php echo Yii::app()->request->baseUrl; ?>/assets/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="<?php echo Yii::app()->request->baseUrl; ?>/assets/css/style.css" rel="stylesheet" media="screen">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/html5shiv.js"></script>
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="row">
<div class="col-lg-4 col-lg-offset-4 col-md-4 col-md-offset-4">
<?php if ($error) : ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>
</div>
<div class="well col-lg-2 col-lg-offset-5 col-md-2 col-md-offset-5">
<h1 class="mt0">Registration</h1>
<form role="form" method="post">
<div class="form-group">
<input type="text" class="form-control" id="inputUsername" placeholder="Username" name="user[username]" value="<?php echo $user->username;?>"/>
</div>
<div class="form-group">
<input type="<PASSWORD>" class="form-control" id="inputPassword" placeholder="<PASSWORD>" name="user[password]">
</div>
<div class="form-group">
<input type="<PASSWORD>" class="form-control" id="inputPassword2" placeholder="<PASSWORD>" name="user[password_repeat]">
</div>
<div class="form-group">
<input type="text" class="form-control" id="inputEmail" placeholder="Email (not required)" name="user[email]" value="<?php echo $user->email;?>"/>
</div>
<button type="submit" class="btn btn-primary btn-block">Register</button>
</form>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/bootstrap.min.js"></script>
<script src="<?php echo Yii::app()->request->baseUrl; ?>/assets/js/js.js"></script>
</body>
</html><file_sep><?php
class DateHelper {
/**
* Returns number of days in given month
* @param integer $year
* @param integer $month
* @return integer 28-31
*/
public static function daysInMonth($year, $month) {
return cal_days_in_month(CAL_GREGORIAN, $month, $year);
}
/**
* Returns month name
* @param integer $month
* @return string
*/
public static function monthName($month) {
return date("F", mktime(0, 0, 0, $month, 10));
}
/**
* Returns day of the week by given date
* @param integer $year
* @param integer $month
* @param integer $day
* @return integer 1-7 (Monday-Sunday)
*/
public static function dayOfTheWeek($year, $month, $day) {
$dayOfTheWeek = date('w', mktime(0, 0, 0, $month, $day, $year));
$dayOfTheWeek = $dayOfTheWeek == 0 ? 7 : $dayOfTheWeek;
return (int) $dayOfTheWeek;
}
/**
* Example:
* 31.12.2013 is Tuesday
* Function below will return 30.12.2013 (first day of the week)
* @param integer $year
* @param integer $month
* @param integer $day
* @return string
*/
public static function firstDayOfWeek($year, $month, $day) {
$dayOfWeek = self::dayOfTheWeek($year, $month, $day);
if ($dayOfWeek == 1) {
// given day is the first
return date('Y-m-d', strtotime("{$year}-{$month}-{$day}"));
}
return date('Y-m-d', strtotime("{$year}-{$month}-{$day} -{$dayOfWeek} day +1 day"));
}
/**
* Validates and parses date. Returns date elements (day, month, year) as array
* @param string $date
* @return array
*/
public static function parseDate($date) {
if (preg_match("/[0-9]{4}-[0-1][0-9]-[0-3][0-9]/", $date) || preg_match("/[0-3][0-9][.][0-1][0-9][.][0-9]{4}/", $date)) {
$returnArray = array(
'year' => date('Y', strtotime($date)),
'month' => date('m', strtotime($date)),
'day' => date('d', strtotime($date))
);
if (checkdate($returnArray['month'], $returnArray['day'], $returnArray['year'])) {
return $returnArray;
}
}
return NULL;
}
} | 1fe9cb1b2be58552b96619e2275219679147e89f | [
"Markdown",
"SQL",
"PHP"
] | 21 | PHP | dmkaaa/calendar | a769bdabaa483762d6a9541369f3ab57456b98ac | 715a64c1336230204413e2725e8199333700e4db |
refs/heads/master | <file_sep><?php get_header(); the_post(); ?>
<div class="error error--404">
<h2>404</h2>
<p class="lead text-warning">
Sorry, the content you requested does not seem to exist.
</p>
</div>
<?php get_footer(); ?><file_sep> <div id="menu_left">
<br />
<a href="<?php echo get_home_url(); ?>" class="no-underline"><img src="<?php echo get_bloginfo('template_url'); ?>/css/mads_logo.jpg" alt="Elizabethan Madrigal Singers of Aberystwyth - Logo" width="180" height="346" /></a>
<hr />
<?php
wp_nav_menu(array(
'theme_location' => 'main-menu',
'container' => false,
'menu_class' => 'dropdown dropdown-horizontal'
));
?>
<hr />
<a href="http://www.facebook.com/AberMADs" class="no-underline" target="_blank"><img src="<?php echo get_bloginfo('template_url'); ?>/css/facebook_faded.png" id="icon_facebook" alt="Facebook Icon" /></a>
<a href="http://www.twitter.com/AberMADs" class="no-underline" target="_blank"><img src="<?php echo get_bloginfo('template_url'); ?>/css/twitter_faded.png" id="icon_twitter" alt="Twitter Icon" /></a>
<a href="http://www.youtube.com/user/AberMADs" class="no-underline" target="_blank"><img src="<?php echo get_bloginfo('template_url'); ?>/css/youtube_faded.png" id="icon_youtube" alt="YouTube Icon" /></a>
<a href="<?php echo get_home_url(); ?>/contact/" class="no-underline"><img src="<?php echo get_bloginfo('template_url'); ?>/css/email_faded.png" id="icon_email" alt="Email Icon" /></a>
</div><file_sep><?php
// support for menus in theme
function register_my_menus() {
register_nav_menus(
array(
'main-menu' => __( 'Main Menu' )
)
);
}
add_action( 'init', 'register_my_menus' );<file_sep> </div>
</div>
<?php wp_footer(); ?>
<div id="footer">
Copyright © 2012-<?php echo date("Y", time()); ?> <NAME>, Aberystwyth.
</div>
</body>
</html><file_sep># AberMads theme
This repository contains the WordPress theme for the [official website of the Elizabethan Madrigal Singers](http://abermads.co.uk) of Aberystwyth University.
The site is hosted by and was initially developed by [<NAME>](http://twitter.com/ChrisBAshton) but is now maintained by the society's committee.<file_sep><?php
get_header();
function formatTime($unixEpochWithMilliseconds) {
return date("M, Y", $unixEpochWithMilliseconds / 1000);
}
global $curauth;
$user = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
?>
<h1><?php echo $user->display_name; ?></h1>
<table id="profile">
<tbody><tr>
<th colspan="2">
Basic Information
</th>
</tr>
<tr>
<td width="35%">
<table id="profile_picture">
<tbody><tr>
<td class="center">
<?php echo get_avatar( $user->ID, '128', 'http://1.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s=128', $user->display_name); ?>
<br>
<b><?php echo $user->display_name; ?></b>
</td>
</tr>
</tbody></table>
</td>
<td width="65%">
<table id="profile_information">
<tbody><tr>
<td class="right" width="40%">
Status:
</td>
<td class="center" width="60%">
<?php
$currentlyInMads = get_field('in_mads', 'user_' . $user->ID);
echo $currentlyInMads ? 'Currently in Mads' : 'Ex-Mad';
?>
</td>
</tr>
<tr>
<td class="right">
Joined:
</td>
<td class="center">
<?php echo formatTime(get_field('date_joined', 'user_' . $user->ID)); ?>
</td>
</tr>
<?php
if (!$currentlyInMads) {
?>
<tr>
<td class="right">
Left:
</td>
<td class="center">
<?php echo formatTime(get_field('date_left', 'user_' . $user->ID)); ?>
</td>
</tr>
<?php
}
?>
<?php
$committeePosition = the_field('committee_position', 'user_' . $user->ID);
if ($committeePosition) {
?>
<tr>
<td class="right">
Committee:
</td>
<td class="center">
<?php echo $committeePosition; ?>
</td>
</tr>
<?php
}
?>
<tr>
<td class="right">
Voice:
</td>
<td class="center">
<?php echo the_field('voice_type', 'user_' . $user->ID);?>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<th colspan="2">
Profile
</th>
</tr>
<tr>
<td colspan="2">
<?php echo apply_filters('the_content', $user->description); ?>
</td>
</tr>
</tbody>
</table>
<?php
get_footer();
?><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title><?php wp_title('«', true, 'right'); ?> <?php bloginfo('name'); ?></title>
<meta name="description" content="The Official Website of the Aberystwyth Elizabethan Madrigal Singers, more affectionately known as 'Mads'." />
<link rel="stylesheet" type="text/css" href="<?php echo get_bloginfo('template_url'); ?>/style.css" />
<link rel="shortcut icon" href="<?php echo get_bloginfo('template_url'); ?>/favicon.ico" />
<!-- START GOOGLE ANALYTICS -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-33296344-1']);
_gaq.push(['_setDomainName', 'abermads.co.uk']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<!-- END GOOGLE ANALYTICS -->
<?php wp_head(); ?>
</head>
<body>
<div id="container">
<?php get_sidebar(); ?>
<div id="main">
| 366d83eafd83c1aec3897b4cae5013ec1851d89a | [
"Markdown",
"PHP"
] | 7 | PHP | ChrisBAshton/abermads-theme | 372386b3e0ea5134750d264b416a5a2aa52cb6e0 | 726a3f1efc5d9198ce643b0ce7d434d03db6801a |
refs/heads/master | <repo_name>crashsonu/HelloWin32<file_sep>/HelloWin32/main.c
/*
All function can be called in main function of this file.
main file.
*/
//
#include<stdio.h>
void main()
{
// // makePiramid(12);
// // e_making(7, 3);
// // dynamicPiramid(11);
// //int_typeCast();
// my_loop();
my_p(5);
}
<file_sep>/HelloWin32/console_io_func.c
/*reads a single byte character from input. It is not defined in standard C . getch() is a way to get a user inputted character.
It can be used to hold program execution, but the "holding" is simply a side-effect of its primary purpose, which is to wait until the user enters a character.
getch is non standard function defined in conio.h.
It holds the output screen until we press any key from the keyboard
getch() function is usually declared before the end of main() function*/
#include<stdio.h>
#include<conio.h>
//char main()
//{
// char a;
// printf(" enter any character : ");
// getch();
//}
/* getche()
Like getch(), this is also a non-standard function present in conio.h.
It reads a single character from the keyboard and displays immediately on output screen without waiting for enter key.
But when you use DOS shell in Turbo C, double g, i.e., 'gg'*/
//void main()
//{
// printf("%c\n", getche());
//}<file_sep>/HelloWin32/learn_sizeof_func.c
/*
Detail explanation about c sizeof function.
NEED:-
Many programs must know the storage size of a particular datatype. Though for any given implementation of C or C++
the size of a particular datatype is constant, the sizes of even primitive types in C and C++ may be defined differently
for different platforms of implementation. For example, runtime allocation of array space may use the following code,
in which the sizeof operator is applied to the cast of the type int:
USE:-
The sizeof operator computes the required memory storage space of its operand. The operand is written following the keyword sizeof
and may be the symbol of a storage space, e.g., a variable, type name, or an expression. If it is a type name, it must be enclosed
in parentheses. The result of the operation is the size of the operand in bytes, or the size of the memory representation.
For expressions it evaluates to the representation size for the type that would result from evaluation of the expression,
which is not performed.
For example:-
since
sizeof (char) is defined to be 1[1],
sizeof (int) is defined to be 4[1],
sizeof (float) is defined to be 4[1],
sizeof (double) is defined to be 8[1],
RESOURCE:-
https://en.wikipedia.org/wiki/Sizeof
*/
#include<stdio.h>
void learn_size_of_func()
{
int my_array[] = { 1,2,3,4,5,6,7,8,9 };
printf("The element in my array = %d\n", sizeof(my_array)/sizeof(int));
char my_name[] = "sonali";
printf("size of my name= %d\n", sizeof(my_name)-1);
printf("-----------------------------------------------\n");
printf("size of char = %d\n", sizeof(char));
printf("size of int = %d\n", sizeof(int));
printf("size of float = %d\n", sizeof(float));
printf("size of double = %d\n", sizeof(double));
printf("size of long double = %d\n", sizeof(long double));
}
<file_sep>/README.md
# HelloWin32
C Codes Snippets for Learning
<file_sep>/HelloWin32/get_grades_of_marks.c
/*
This code will get you the grades according to your marks.
in this file you will learn following points.
1. conditions (if, else if, else).
2. operators (&&, ||, ==, >, <, <=, >=).
*/
#include<stdio.h>
void get_grades()
{
int marks;
printf("Enter your marks : ");
scanf("%d", &marks);
if (marks >40 && marks<60)
{
printf(" The student is pass .... by getting c grade");
}
else if (marks > 60 && marks<80)
{
printf(" Student is pass .... by getting B grade");
}
else if (marks > 80 && marks <100)
{
printf(" student is pass... by gating A grade");
}
else if (marks == 100)
{
printf(" Congrats..!! You got out of marks");
}
else if (marks > 100 || marks<0)
{
printf(" You entered wrong value");
}
else
{
printf(" student is fail, better luck next time");
}
}
<file_sep>/HelloWin32/functions.c
#include<stdio.h>
int add(int a, int b)
/*
@ This function will add two values which can be use in any other function.
Args:-
a (int): first value
b (int): second value
Return:-
c (int): addition of a and b.
*/
{
int c;
c = a + b;
return c;
}
float div(int a, int b)
/*
@ This function will divide any two values which can be use in any other function.
*/
{
// here we in the function we take int value to div function, but still you want to result in float,
// then you should have to convert type (like integer to float) by cast float to the variables, as i shown in below.
float d = (float) a / b;
return d;
}
int sub(int a)
/*
@ This function will subtract any value by 10 which can be use in any other function.
*/
{
int g;
g = a - 10;
return g;
}
void func_tester_main()
/*
@ In this functin we can call and test above functions.
*/
{
int x, y, s, m;
float j;
printf("Enter your two number : \n");
scanf("%d %d", &x, &y);
s = add(x, y);
printf("The sum of given values is : %d\n", s);
m = sub(s);
printf("The output from the sub function : %d\n", m);
j = div(x, y);
printf("The division of the given values is : %f", j);
}
int pyramid_using_func(int row)
/*
@ In this function we make pyramid using custom values
costom values= "its a changable value" ,we can pass any values related
to its data type while calling function in main function.
Here we calling i.e. pyramid_using_func() in the function where its costom value is 5;
it returns..
*
* *
* * *
* * * *
* * * * *
*/
{
int column_v, i, j, s, k;
column_v = (int)row * 2 - 1;
s = (int)row - 1;
for (i = 1; i <= row; i++)
{
for (k = s; k >= 1; k--)
{
printf(" ");
}
for (j = 1; j <= i; j++)
{
printf("* ");
}
printf("\n");
s--;
}
}
int digit_pyramid_func(int row)
/*
@ It will print a digit pyramid of given rows.
*/
{
int i, j, k, l, m = 1;
j == row;
k = row - 1;
for (i = 1; i <= row; i++)
{
for (l = k; l >= 1; l--)
{
printf(" ");
}
for (j = 1; j <= i; j++)
{
printf("%d ", m);
}
printf("\n");
k--;
}
}
int digit_pyramid_func2(int row)
/*
@ It will print table pyramid of given number.
*/
{
int i, j, c = 1, d, e, u;
if (row % 2 != 0)
{
printf(" enter row in even number in function to get perfect side pyramid \n");
}
d = row / 2;
e = row * d + d;
for (i = 1; i <= row; i++)
{
for (j = 1; j <= i; j++)
{
if (c <= e)
{
printf("%d ", c* row);
c++;
}
}
printf("\n");
}
}
int simple_table(int my_no)
/*
@ prints simple table of given number.
*/
{
int i;
for (i = 1; i <= 10; i++)
{
printf("%d\n", i*my_no);
}
}
<file_sep>/HelloWin32/for_loop_examples.c
/*
For Loop Examples.
started learning for loop examples.
*/
#include<stdio.h>
void simpleForLoop()
/*
@ Create Simple for loop.
*/
{
int i;
for (i=0; i<=5; i++)
{
printf("%d\n", i);
}
}
void incrementalLoop()
/*
@ Make increamental loop to print output like this.
*
* *
* * *
* * * *
* * * * *
*/
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
printf("* ");
}
printf("\n");
}
}
void decrementalLoop()
/*
@ Make decremental loop to print output like this.
* * * * *
* * * *
* * *
* *
*
*/
{
int i, j;
for (i = 5; i >0 ; --i)
{
for (j = i; j > 0; --j)
{
printf("* ");
}
printf("\n");
}
}
void simplePiramid()
/*
@ it will print piramid structure using default values.
*
* *
* * *
* * * *
* * * * *
*/
{
int i, j, a, b;
b = 4;
for (i = 1; i <= 5; i++)
{
for (a = 1; a <= b; a++)
{
printf(" ");
}
b--;
for (j = 1; j <= i; j++)
{
printf("* ");
}
printf("\n");
}
}
void sidePiramid()
/*
@ it will print side piramid which looks like bellow.
*
* *
* * *
* * * *
* * *
* *
*
*/
{
int i, j, x;
x = 3;
for (i = 1; i <= 7; i++)
{
if (i <= 4)
{
for (j = 1; j <= i; j++)
{
printf("* ");
}
}
else
{
for (j = x; j >= 1; j--)
{
printf("* ");
}
x--;
}
printf("\n");
}
}
void printEvenNumberMethod1()
/*
@ Printing even numbers using if else method.
*/
{
int i;
for (i = 0; i <= 100; i++)
{
if (i % 2 == 0)
{
printf("%d", i);
}
else
{
printf(" ");
}
}
}
void printEvenNumberMethod2()
/*
@ Printing even numbers using for loop with 2 step increment.
*/
{
for (int i = 2; i <= 100; i = i + 2)
{
printf("%d\n", i);
}
}
void startFilledSquare()
/*
@ it wiil print output like this.
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
*/
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= 5; j++)
{
printf("* ");
}
printf("\n");
}
}
void hollowSquare()
/*
@ this program will print hollow square star pattern, it will look like bellow.
* * * * *
* *
* *
* *
* * * * *
*/
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= 5; j++)
{
if (i == 1 || i == 5 || j == 1 || j == 5)
{
printf("* ");
}
else
{
printf(" ");
}
}
printf("\n");
}
}
void oddDesign()
/*
@ it will print design looks like this.
*****
** **
* * *
** **
*****
*/
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= 5; j++)
{
if (i == 1 || i == 5 || j == 1 || j == 5 || j == 5 - i + 1 || j == 5 - i - 1 || i == j)
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
}
void dynamicPiramid(int baseValue)
/*
@ This function will make piramid using given value.
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
Args:-
baseValue (int): enter number of piramid size.
Return:-
None.
*/
{
int i, j, x, z, a;
z = baseValue - 1;
a = baseValue;
if (a % 2 == 0)
{
printf("Sorry...! You enetered even value plz enter odd value for pyramid\n");
return;
}
for (i = 1; i <= baseValue; i++)
{
// this for loop for the spaces before the first star.
for (x = z; x >= 1; x--)
{
printf(" ");
}
// To decrease spaces value frm 4 to 0; this is defined out of loop becouse it should not be refreshed everytime.
z--;
// This for loop to print stars.
for (j = 1; j <= i; j++)
{
printf("* ");
}
printf("\n");
}
}
void e_character_pattern(int vValue, int hValue)
/*
@this function will design the "E" in the star pattern which is looks like bellow.
* * *
*
*
* * *
*
*
* * *
*/
{
int i, j;
int newVal = (float)vValue / 2 + 0.5;
for (i = 1; i <= vValue; i++)
{
for (j = 1; j <= hValue; j++)
{
if (i == 1 || i == newVal || i == vValue || j == 1)
{
printf("* ");
}
}
printf("\n");
}
}
int print_alphabts()
/*
@ it will return alphabets between A-Z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
*/
{
char b;
for (b = 'A'; b <= 'Z'; b++)
{
printf("%c ", b);
}
}
int print_alphabts1()
/*
@ This is the second way to write alphabets by ASCII no. given to uppercase alphbets ...it will return
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
*/
{
int i;
for (i = 65; i <= 90; i++)
{
printf("%c ", i);
}
}
int print_alpha()
/*
@ it will return
A
AB
ABC
ABCD
ABCDE
ABCDEF
*/
{
int i, j;
char ch = 'A';
for (i = 1; i <= 6; i++)
{
for (j = 1; j <= i; j++)
{
printf("%c", ch);
ch++;
}
ch = 'A';
printf("\n");
}
}
int print_alpha2()
/*
@ It will return
A
BB
CCC
DDDD
EEEEE
*/
{
int i, j;
char ch = 'A';
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
printf("%c", ch);
}
ch++;
printf("\n");
}
}
int print_alpha3()
/*
@ It will return
A
BC
DEF
GHIJ
KLMNO
*/
{
int i, j, a = 65; // cause by ASCII( American Standard Code for Information Interchange) values of characters defined..
// for uppercase char is A--Z= 65-90 & lowercase char is a--z= 97-122.
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
printf("%c", a);
a++;
}
printf("\n");
}
}
int print_int()
/*
@ this will return
1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910
*/
{
int i, j, b = 1;
for (i = 1; i <= 10; i++)
{
for (j = 1; j <= i; j++)
{
printf("%d", b);
b++;
}
b = 1;
printf("\n");
}
}
int print_int2()
/*
@ this will return
1
22
333
4444
55555
*/
{
int i, j, b = 1;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
printf("%d", b);
}
b++;
printf("\n");
}
}
void print_int2_1()
/*
@ this will return
55555
4444
333
22
1
*/
{
int i, j, b = 5;
for (i = 5; i >= 1; i--)
{
for (j = 1; j <= i; j++)
{
printf("%d", b);
}
b--;
printf("\n");
}
}
int print_int3()
/*
@ this will return
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
*/
{
int i, j, b = 1;
for (i = 1; i <= 8; i++)
{
for (j = 1; j <= i; j++)
{
printf("%d ", b);
b++;
}
printf("\n");
}
}
int print_int3_1()
/*
@ This will print as function print_int3 bt when u hace limit of values we can use the it statement....pgm will return
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
*/
{
int i, j, b = 1;
for (i = 1; i <= 8; i++)
{
for (j = 1; j <= i; j++)
{
if (b >= 1 && b <= 15)
{
printf("%d ", b);
b++;
}
}
printf("\n");
}
}
int print_int_pyramid()
/*
@ It will return pyramid {note that if we dont want refresh the value print it below at last after printf}
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
*/
{
int i, j, a, b = 1;
int c = 8;
for (i = 1; i <= 9; i++)
{
for (j = c; j >= 1; j--)
{
printf(" ");
}
for (a = 1; a <= i; a++)
{
printf("%d ", b);
}
b++;
printf("\n");
// note that if we dont want refresh the value print it below at last after printf.
c--;
}
}
int print_1_100_num()
/*
@ print 1 to 100 numbers.
*/
{
int i;
for (i = 1; i <= 100; i++)
{
printf("%d ", i);
}
}
<file_sep>/HelloWin32/get_factorial.c
/*
Get factorial of given number.
for eg. factorial of 6 = 6*5*4*3*2*1 = 720
*/
#include<stdio.h>
int get_factor()
/*
@ to get factorial number run this function.
*/
{
int i, no, fact = 1;
printf("ennter ur number ");
scanf("%d", &no);
for (i = 1; i <= no; i++)
fact = fact * i;
printf("Factorial of %d = %d\n", no, fact);
}
<file_sep>/HelloWin32/data_types.c
#include<stdio.h>
void int_typeCast()
/*
@ Type casting it will convert float value to integer value.
when u enter an float value but its data type is an integer then it will not consider the value after point, it will consider the float value as integer value.
*/
{
int a,b;
b = (int) 4.7;
printf("%d\n", b);
a = (int) 4.7 + (int) 4.5;
printf("%d", a);
}
<file_sep>/HelloWin32/test.c
#include<stdio.h>
void making_A()
{
int i, j, x, y,z;
y = 4;
for (i = 1; i <= 5; i++)
{
for (x = 1; x <= y; x++)
{
printf(" ");
}
y--;
for (j = 1; j <= 10; j++)
{
for (z = 1; z <= 9; z = z + 2)
{
printf(" ");
if (i == 3 || i == 3 || j == j + 2)
{
printf("*");
}
else
{
printf(" ");
}
}
}
printf("\n");
}
}
void hi_the()
{
int i, j, k, l;
for (i = 1; i<= 11; i++)
{
for (j = 10; j>= i; j--)
{
// These is for spaces before every 1st star after new line
printf(" ");
}
for (k = 1; k<= 3/*(this will print horizontal value ...no. of columns it changable)*/; k++)
{
// this is for left side column
printf("*");
}
for (l = 1; l<= i; l++)
{
//this is the middle portion of character ' A '
if (i> 4 && i<7)
{
printf("**");
}
else
{
printf(" ");//add two space
}
}
for (k = 1; k<= 3; k++)
{
// this is for right side column
printf("*");
}
//for (j = 10; j>= i; j--)
//{
// printf(" ");//add space here
//}
printf("\n");
}
}
//void main()
//{
// int i, j, k, l;
// for (i = 1; i <= 15; i++)
// {
// for (j = 9; j <= i; j--)
// {
// printf(" ");
// }
// for (k = 1; k <= 2; k++)
// {
// printf("*");
// }
// for (l = 1; l <= i; i++)
// {
// if (i == 7)
// {
// printf("**");
// }
// else
// {
// printf(" ");
// }
//
// }
// for (k = 1; k <= 1; k++)
// {
// printf("*");
// }
//
// for (j = 9; j >= i; j--)
// {
// printf(" ");
// }
//
// printf("\n");
//
// }
//}
<file_sep>/HelloWin32/alphabets.c
#include<stdio.h>
int print_alpha_x()
/*
@ Print char x. output should be like below.
* *
* *
* *
* *
*
* *
* *
* *
* *
*/
{
int i, j, l, k = 1;
for (i = 1; i <= 9; i++)
{
for (j = 1; j <= i; j++)
{
if (i == j)
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
/*printf("\n");
for (i = 9; i >= 1; i--)
{
for (j = 9; j == i; j--)
{
if (i == j)
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}*/
}
} | 96922dcbe39542b3a4e695e45ed465e5baf27683 | [
"Markdown",
"C"
] | 11 | C | crashsonu/HelloWin32 | 2c17c6064802bb2a2a3d9958651d84dcbcecc094 | bdec032997f9edb683e5bb7493d7f8ffda60e76c |
refs/heads/master | <file_sep>def odometer(oksana):
speed_list = [values for i,values in enumerate(oksana) if not i%2]
time_list = [values for i,values in enumerate(oksana) if i%2]
Distance = speed_list[0]*time_list[0]
for i in range(1, (len(speed_list))):
Distance += speed_list[i]*(time_list[i]-time_list[i-1])
i += 1
return Distance
<file_sep>def squirrel(N):
res = 1
if N == 1 or N == 0:
return 1
else:
for n in range(1, N+1):
res = res * n
res_str = str(res)
return int(res_str[0])
| f1df2c7a870abf2070f8aa27560de7518b23797f | [
"Python"
] | 2 | Python | loky131313/sBobrovsky_course | 930a580432a44a1ac10f1f501fb7a304fd3e0c7f | ae26e0dd076d4744203498f84817777471e50231 |
refs/heads/master | <repo_name>Jmackas/Learning_JS<file_sep>/Miscellaneous/Annotating JavaScript to HTML Output.js
// Syntax
document.getElementById('LinkedHtmlID').innerHTML = "Stuff that should be output, can be a variable";
| e96a3b18fa78db887f2dce04f14881cb93a671b1 | [
"JavaScript"
] | 1 | JavaScript | Jmackas/Learning_JS | fd1afe7659f7d045eff0ac5553fc558bd8ad6c14 | 750d06d8bd26f2b5811cc7caa6d3d5ba354c10db |
refs/heads/master | <file_sep>public class Runs implements jade.content.Predicate {
private Milage _milage;
private Car _car;
public Milage getMilage() {
return _milage;
}
public void setMilage(Milage _milage) {
this._milage = _milage;
}
public Car getCar() {
return _car;
}
public void setCar(Car _car) {
this._car = _car;
}
}
<file_sep>import jade.content.Concept;
import jade.content.onto.BasicOntology;
import jade.content.onto.Ontology;
import jade.content.onto.OntologyException;
import jade.content.schema.*;
import javax.print.DocFlavor;
public class CarOntology extends Ontology {
public static final String ONTOLOGY_NAME = "Car-ontology";
public static final String CAR = "car";
public static final String REGISTRATION = "registration";
public static final String MODEL = "model";
public static final String MANUFACTURED = "manufactured";
public static final String MILAGE = "milage";
public static final String INTERVAL = "interval";
public static final String MEASUREMENTUNIT = "measurementUnit";
public static final String RUNS = "runs";
public static final String RUNS_MILAGE = "milage";
private static Ontology theInstance = new CarOntology();
public static Ontology getInstance(){
return theInstance;
}
private CarOntology() {
super(ONTOLOGY_NAME, BasicOntology.getInstance());
try {
add(new ConceptSchema(CAR), Car.class);
add(new ConceptSchema(MILAGE), Milage.class);
add(new PredicateSchema(RUNS), Runs.class);
ConceptSchema cs = (ConceptSchema) getSchema(CAR);
cs.add(REGISTRATION, (PrimitiveSchema)getSchema(BasicOntology.STRING));
cs.add(MODEL, (PrimitiveSchema)getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
cs.add(MANUFACTURED, (PrimitiveSchema)getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
cs = (ConceptSchema)getSchema(MILAGE);
cs.add(INTERVAL, (PrimitiveSchema)getSchema(BasicOntology.INTEGER));
cs.add(MEASUREMENTUNIT, (PrimitiveSchema)getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
PredicateSchema ps = (PredicateSchema)getSchema(RUNS);
ps.add(CAR, (ConceptSchema)getSchema(CAR));
ps.add(MILAGE, (ConceptSchema)getSchema(MILAGE));
} catch (OntologyException oe) {
oe.printStackTrace();
}
}
}
<file_sep>package packageSort;
public class BubbleSortMethod extends SortWay{
@Override
public void sortOnMyWay(Integer[] arr, Integer size) throws ZeroElementsException{
System.out.print("Array before sort: ");
printArray(arr);
if (arr.length == 0) {throw new ZeroElementsException();}
if (size == 1) {return;}
for (int i = 0; i < arr.length; i++){
if(arr[i] > arr[i+1]){swap(arr[i], arr[i+1]);} }
sortOnMyWay(arr, size-1);
System.out.println("Array after bubble sort");
printArray(arr);
checkTimeOfSort();
}
}
<file_sep>package packageTarget;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class TargetProblemSolution {
HashMap<Float, Integer> myIntegers = new HashMap<Float, Integer>();
public void convertArray(float[] arr){
if (arr.length == 0){throw new EmptyStackException(); }
for (int i = 0; i < arr.length; i++){
myIntegers.put(arr[i], i);
}
}
public int[] solution(float[] array, float target){
float diffrence = 0;
int[] arrIndex = new int[2];
boolean existedPair = false;
if (array.length == 0) {throw new EmptyStackException();}
Iterator it = myIntegers.entrySet().iterator();
while (it.hasNext()){
Map.Entry myElement = (Map.Entry)it.next();
diffrence = target - (float)myElement.getKey();
if (!myIntegers.containsKey(diffrence)){
it.remove();
continue;
} else {
arrIndex[0] = (int) myElement.getValue();
arrIndex[1] = myIntegers.get(diffrence);
break;
}
}
if (!existedPair){
throw new IllegalArgumentException();
}
return arrIndex;
}
}
<file_sep>import java.util.Locale;
public class Square extends Figure implements Print{
double Side;
double Area, Parimeter;
Square(double newSide){
this.Side = newSide;
}
@Override
public double calculatePerimeter() {
this.Parimeter = 4 * this.Side;
return this.Parimeter;
}
@Override
public double calculateArea() {
this.Area = Math.pow(this.Side, 2);
return this.Area;
}
@Override
public void print() {
System.out.println("It's a square.");
System.out.println(String.format(Locale.US, "Side: %.2f", this.Side));
System.out.println(String.format(Locale.US, "Parimeter: %.2f", this.Parimeter));
System.out.println(String.format(Locale.US, "Area: %.2f", this.Area));
}
}
<file_sep>import jade.content.Concept;
public class Milage implements Concept {
private Integer _interval;
private String _measurementUnit = "Unit";
public Integer getInterval() {
return _interval;
}
public void setInterval(Integer _interval) {
this._interval = _interval;
}
public String getMeasurementUnit() {
return _measurementUnit;
}
public void setMeasurementUnit(String _measurementUnit) {
this._measurementUnit = _measurementUnit;
}
}
<file_sep>import jade.core.Agent;
import jade.core.behaviours.Behaviour;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.ThreadedBehaviourFactory;
import java.util.concurrent.ThreadFactory;
public class klasa_4_2 extends Agent {
private ThreadedBehaviourFactory tbf = new ThreadedBehaviourFactory();
@Override
protected void setup() {
Behaviour c1 = new CyclicBehaviour() {
@Override
public void action() {
System.out.println("cyclic1");
}
};
Behaviour c2 = new CyclicBehaviour() {
@Override
public void action() {
System.out.println("cyclic2");
}
};
addBehaviour(tbf.wrap(c1));
addBehaviour(tbf.wrap(c2));
}
}
<file_sep>import jade.core.Agent;
import jade.core.behaviours.OneShotBehaviour;
import jade.core.behaviours.SequentialBehaviour;
import jade.core.behaviours.Behaviour;
public class klasa_3_2 extends Agent {
protected void setup() {
SequentialBehaviour myBehaviour1 = new SequentialBehaviour(this);
Behaviour task1 = new ThreeSteps();
Behaviour task2 = new ThreeSteps();
Behaviour task3 = new ThreeSteps();
myBehaviour1.addSubBehaviour(task1);
myBehaviour1.addSubBehaviour(task2);
myBehaviour1.addSubBehaviour(task3);
addBehaviour(myBehaviour1);
}
class ThreeSteps extends Behaviour {
private int step = 1;
public void action() {
switch (step) {
case 1:
System.out.println("Krok" + step);
break;
case 2:
System.out.println("Krok " + step);
break;
case 3:
System.out.println("Krok " + step);
break;
}
step++;
}
public boolean done() {
return step == 4;
}
public int onEnd() {
return super.onEnd();
}
}}
<file_sep>package packageSort;
public class GnomeSortMethod extends SortWay {
@Override
public void sortOnMyWay(Integer[] arr, Integer size) throws ZeroElementsException{
Integer index = 0;
if (arr.length == 0) {throw new ZeroElementsException();}
System.out.print("Array before sort: ");
printArray(arr);
while (index<size){
if(index == 0){index++;}
if(arr[index] >= arr[index-1]){
index++;} else{
swap(arr[index], arr[index-1]);
index--;
}
}
System.out.println("Array after bubble sort");
printArray(arr);
checkTimeOfSort();
}
}
<file_sep>import java.util.Locale;
public class Triangle extends Figure implements Print{
public double Area, Parimeter;
public double Sides[] = new double[3];
public Triangle(double newSide1, double newSide2, double newSide3) {
this.Sides[0] = newSide1;
this.Sides[1] = newSide2;
this.Sides[2] = newSide3;
}
@Override
public double calculatePerimeter() {
this.Parimeter = this.Sides[0] + this.Sides[1] + this.Sides[2];
return this.Parimeter;
}
@Override
public double calculateArea() {
double halfParimeter = (this.Sides[0] + this.Sides[1] + this.Sides[2])/2;
this.Area = halfParimeter * (halfParimeter-this.Sides[0]) * (halfParimeter-this.Sides[1]) * (halfParimeter-this.Sides[2]);
this.Area = Math.sqrt(this.Area);
return this.Area;
}
@Override
public void print() {
System.out.println("It's triangle");
System.out.println(String.format(Locale.US, "Side 1: %.2f, Side 2: %.2f, Side3: %.2f", this.Sides[0], this.Sides[1], this.Sides[2]));
System.out.println(String.format(Locale.US, "Parimeter: %.2f", this.Parimeter));
System.out.println(String.format(Locale.US, "Area: %.2f", this.Area));
return;
}
}
<file_sep>package packageSubstring;
import java.util.EmptyStackException;
public class SearchSubstring{
public int substring(String a, String b){
if (b.length() == 0 || a.length() == 0){
throw new EmptyStackException();
}
if (b.length() < a.length()){
System.out.println("This strings can not be a substring.");
int error = -1;
return error;
}
if(!b.contains(a)){
System.out.println("This strings can not be a substring.");
int error = -1;
return error;
}
int countOfStrings = 0;
//check from longer string
int i = 0;
int j = 0;
int k = 0; // count of compatibility points
while(i < b.length()){
while(j < a.length()){
if(b.charAt(i) == a.charAt(j)){
j++;
k++;
i++;
break;
} else { j++; }
if(j == a.length()&& k!= 0){
countOfStrings++;
k = 0;
}
}
}
return countOfStrings;
}
}
<file_sep>import packageSort.*;
import packageMatrix.*;
import packageSubstring.*;
import packageTarget.*;
import packageNotExistedValue.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] argv){
Integer[] arr = {2,5, 5,6,8,3};
float[] arrayToTarget = {2, 4, 3, 2};
String firstString = "abcd";
String secondString = "cdabcdlk";
List<Integer> listToTestSolution = new ArrayList<>();
listToTestSolution.add(4);
listToTestSolution.add(5);
listToTestSolution.add(34);
listToTestSolution.add(-5);
listToTestSolution.add(1);
BubbleSortMethod newBubbleSort = new BubbleSortMethod();
try {
newBubbleSort.sortOnMyWay(arr, arr.length);
} catch (ZeroElementsException e){
System.err.println("Zero elements in array!");
}
List<MatrixInteger> matrixList= new ArrayList<MatrixInteger>();
matrixList.add(new MatrixInteger(4));
matrixList.add(new MatrixInteger(4));
for(MatrixInteger it: matrixList){ it.print(); }
MatrixInteger matrix3 = matrixList.get(0).addMatrixes(matrixList.get(1));
matrixList.add(matrix3);
SearchSubstring newSearcher = new SearchSubstring();
newSearcher.substring(firstString, secondString);
List<MatrixString> matrixStringList = new ArrayList<MatrixString>();
matrixStringList.add(new MatrixString(4));
matrixStringList.add(new MatrixString(4));
for(MatrixString it: matrixStringList){ it.print(); }
MatrixString matrix5 = matrixStringList.get(0).addMatrixes(matrixStringList.get(1));
matrixStringList.add(matrix5);
TargetProblemSolution newSolution = new TargetProblemSolution();
newSolution.convertArray(arrayToTarget);
SolutionOfNotExistedValue newFoundNumber = new SolutionOfNotExistedValue();
try{
newFoundNumber.solution(listToTestSolution);
} catch (EmptyArrayException e){
System.err.println("Your Array is empty!");
} catch (TooBigArrayException e){
System.err.println("Your array is too big!"); }
}
}
<file_sep>package sample;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ResourceBundle;
import java.util.Set;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swt.FXCanvas;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.shape.Circle;
import javafx.util.Callback;
import static sample.Windows.CreateAddNewItemWindow;
public class Controller {
public static ObservableList<Task> tODOList = FXCollections.observableArrayList();
@FXML
private ListView<Task> listTODO = new ListView<>(tODOList);
@FXML
private ListView<Task> listDoing;
@FXML
private Label labelDoing;
@FXML
private GridPane mainWindow;
@FXML
private Button newTaskButton;
@FXML
private Label labelDone;
@FXML
private Label labelTODO;
@FXML
private ListView<Task> listDone;
@FXML
void addNewTask(ActionEvent event) {
try{
CreateAddNewItemWindow();
} catch(IOException e){
e.printStackTrace();
}
}
@FXML
void initialize() {
assert listTODO != null : "fx:id=\"listTODO\" was not injected: check your FXML file 'sample.fxml'.";
assert listDoing != null : "fx:id=\"listDoing\" was not injected: check your FXML file 'sample.fxml'.";
assert labelDoing != null : "fx:id=\"labelDoing\" was not injected: check your FXML file 'sample.fxml'.";
assert mainWindow != null : "fx:id=\"mainWindow\" was not injected: check your FXML file 'sample.fxml'.";
assert newTaskButton != null : "fx:id=\"newTaskButton\" was not injected: check your FXML file 'sample.fxml'.";
assert labelDone != null : "fx:id=\"labelDone\" was not injected: check your FXML file 'sample.fxml'.";
assert labelTODO != null : "fx:id=\"labelTODO\" was not injected: check your FXML file 'sample.fxml'.";
assert listDone != null : "fx:id=\"listDone\" was not injected: check your FXML file 'sample.fxml'.";
listTODO.setCellFactory(new Callback<ListView<Task>, ListCell<Task>>() {
@Override public ListCell<Task> call(ListView<Task> list) {
return new ColorRectCell();
}
});
}
static class ColorRectCell extends ListCell<Task> {
private Circle getCircle(){
Circle rect = new Circle(5);
// rect.setFill(Color.web(getItem().getPriorityColor()));
return rect;
}
public void updateItem(Task item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
setTooltip(null);
}
else{
setText(getItem().getTitle());
setGraphic(getCircle());
Tooltip tooltip = new Tooltip();
tooltip.setText(getItem().getDescription());
setTooltip(tooltip);
}
}
}
}
<file_sep>import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.Behaviour;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
public class AgWys extends Agent {
protected void setup() {
addBehaviour(new TwoSteps());
}
class TwoSteps extends Behaviour {
private int step = 1;
public void action() {
switch (step) {
case 1:
ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
msg.addReceiver(new AID("ToMe", AID.ISLOCALNAME));
msg.setContent("All of me");
send(msg);
case 2:
ACLMessage msgRec = myAgent.receive();
if(msgRec == null){
System.out.println("I have not any message!");
block();
//doDelete();
//step++;
} else {
System.out.println(msgRec.getContent());
doDelete();
}
}
step++;
}
public boolean done() {
return step == 3;
}
public int onEnd() {
myAgent.doDelete();
return super.onEnd();
}
}
protected void takeDown() {
System.out.println("Agent "+getLocalName()+": terminating");
}
}
<file_sep>import jade.content.Concept;
public class Car implements Concept {
private String _registration;
private String _model;
private String _manufactured;
public String getRegistration() {
return _registration;
}
public String getModel() {
return _model;
}
public String getManufactured() {
return _manufactured;
}
public void setRegistration(String _registration) {
this._registration = _registration;
}
public void setModel(String _model) {
this._model = _model;
}
public void setManufactured(String _manufactured) {
this._manufactured = _manufactured;
}
}
<file_sep>public class Item implements Print, Comparable<Item>{
String name;
ItemCondition condition;
Double weight;
Integer amount;
Item(String newName){
this.name = newName;
this.condition = ItemCondition.NEW;
this.weight = 0.0;
this.amount = 0;
};
Item(String newName, ItemCondition newCondition, Double newWeigtht, Integer newAmount){
this.name = newName;
this.condition = newCondition;
this.weight = newWeigtht;
this.amount = newAmount;
}
@Override
public void print() {
System.out.println(String.format("Product: %s", this.name));
System.out.println("Condition: " + this.condition);
System.out.println(String.format("Weight: %.2f", this.weight));
System.out.println(String.format("Amount: %d", this.amount));
}
@Override
public int compareTo(Item exampleItem){
return name.compareTo(exampleItem.name);
}
}
| 95cc2121d9c73211b4ae00f8e123f5caf30c2d9a | [
"Java"
] | 16 | Java | katgiadla/Java_Small_Projects | daa55c7379b9d00c2d09b325aa1a8e655a2bb0d3 | 086554f22bc3651b529fa6d0d415c4fe301ca79d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.