public MenuItem(Sub method, string description) { this.Method = method; this.Description = description; this.Key = ConsoleKey.NoName; }
public void Eval_ShouldAddTwoInteger() { var a = new Lit(7); var b = new Lit(8); var sub = new Sub(a, b); Assert.That(sub.Accept(new IntegerEval()), Is.EqualTo(-1)); }
public void Print_ShouldPrintExpression() { var a = new Lit(7); var b = new Lit(8); var sub = new Sub(a, b); Assert.That(sub.Accept(new Print()), Is.EqualTo("7-8")); }
public MenuItem(Sub method, string description, ConsoleKey key) { this.Method = method; this.Description = description; this.Key = key; }
public P5Code(string _name, int[] _proto, System.Type _class, string _method, bool main) { subref = (Sub)System.Delegate.CreateDelegate(typeof(Sub), _class, _method); scratchpad = null; is_main = main; name = _name; proto = _proto; }
public P5Code(string _name, int[] _proto, System.Delegate code, bool main) { subref = (Sub)code; scratchpad = null; is_main = main; name = _name; proto = _proto; }
public void Can_build_node_sorted() { // arrange var sub = new Sub(); sub.Id = GuidUtil.NewSequentialId(); sub.Name = "test"; var author = new User(); author.Id = GuidUtil.NewSequentialId(); author.UserName = "******"; var comments = ConvertTestNodesToComments(new List<TestNodeTreeSorted> { TestNodeTreeSorted.Create(10, TestNodeTreeSorted.Create(5), TestNodeTreeSorted.Create(4, TestNodeTreeSorted.Create(2), TestNodeTreeSorted.Create(20))), TestNodeTreeSorted.Create(9, TestNodeTreeSorted.Create(3, TestNodeTreeSorted.Create(1)), TestNodeTreeSorted.Create(12)) }); foreach (var comment in comments) { comment.SubId = sub.Id; comment.AuthorUserId = author.Id; } SetupComments(comments); _membershipService.Setup(x => x.GetUsersByIds(It.IsAny<List<Guid>>())).Returns(new List<User> {author}); _subDao.Setup(x => x.GetSubsByIds(It.IsAny<List<Guid>>())).Returns(new List<Sub> {sub}); // act var tree = _commentTreeBuilder.GetCommentTree(Guid.Empty); var treeContext = _commentTreeContextBuilder.Build(tree, comments.ToDictionary(x => x.Id, x => (double) x.SortConfidence)); var nodes = _commentNodeHierarchyBuilder.Build(tree, treeContext, null); //assert Assert.That(nodes, Has.Count.EqualTo(2)); Assert.That(nodes[0].As<CommentNode>().Comment.Comment.SortConfidence, Is.EqualTo(10)); Assert.That(nodes[0].As<CommentNode>().Children, Has.Count.EqualTo(2)); Assert.That(nodes[0].As<CommentNode>().Children[0].As<CommentNode>().Comment.Comment.SortConfidence, Is.EqualTo(5)); Assert.That(nodes[0].As<CommentNode>().Children[1].As<CommentNode>().Comment.Comment.SortConfidence, Is.EqualTo(4)); Assert.That(nodes[0].As<CommentNode>().Children[1].Children, Has.Count.EqualTo(2)); Assert.That(nodes[0].As<CommentNode>().Children[1].Children[0].As<CommentNode>().Comment.Comment.SortConfidence, Is.EqualTo(20)); Assert.That(nodes[0].As<CommentNode>().Children[1].Children[1].As<CommentNode>().Comment.Comment.SortConfidence, Is.EqualTo(2)); Assert.That(nodes[1].As<CommentNode>().Comment.Comment.SortConfidence, Is.EqualTo(9)); Assert.That(nodes[1].As<CommentNode>().Children, Has.Count.EqualTo(2)); Assert.That(nodes[1].As<CommentNode>().Children[0].As<CommentNode>().Comment.Comment.SortConfidence, Is.EqualTo(12)); Assert.That(nodes[1].As<CommentNode>().Children[1].As<CommentNode>().Comment.Comment.SortConfidence, Is.EqualTo(3)); Assert.That(nodes[1].As<CommentNode>().Children[1].Children, Has.Count.EqualTo(1)); Assert.That(nodes[1].As<CommentNode>().Children[1].Children[0].As<CommentNode>().Comment.Comment.SortConfidence, Is.EqualTo(1)); }
public static void Main(string[] args) { /* for(int i=0; i<args.Length; i++) Console.WriteLine(args[i]); Console.WriteLine("--------"); foreach(string arg in args) Console.WriteLine(arg); */ Base b = new Base(); Console.WriteLine("Base add(1,3)={0}", b.add(1, 3)); Base s = new Sub(); Console.WriteLine("Sub add(1,3)={0}", s.add(1, 3)); }
public Func <TParent, ISub <TMessage> > MergeWith(IVDomNodeProperty property) { return(Optional(property) .TryCast <IVDomNodeProperty <TParent, TMessage, TValue> >() .Bind(p => equalityComparer.Equals(p.Value, Value) ? Some(Unit.Default) : None ) .Some(_ => new Func <TParent, ISub <TMessage> >(o => Sub.None <TMessage>())) .None(() => new Func <TParent, ISub <TMessage> >(o => { propertyInfo.SetValue(o, Value); return Sub.None <TMessage>(); }))); }
// switch statement on the sub we want to show first private void ShowSub(Sub sub) { transform.Find("mainSub").gameObject.SetActive(false); transform.Find("howToPlaySubMenu").gameObject.SetActive(false); switch (sub) { case Sub.Main: transform.Find("mainSub").gameObject.SetActive(true); break; case Sub.HowToPlay: transform.Find("howToPlaySubMenu").gameObject.SetActive(true); break; } }
public IEnumerable <Sub> GetRolePermissionsWithSite(int roleId) { //回傳的list List <Sub> list = new List <Sub>(); //取得角色擁有權限的網頁編號 BusinessLogic businessLogic = new BusinessLogic(); List <int> siteIdList = (businessLogic.GetPermissionsData()).Where(p => p.RoleId == roleId && p.Enable == true).Select(a => a.SiteId).ToList(); List <Sub> allSite = businessLogic.GetSub(); foreach (var item in siteIdList) { Sub tmpSub = allSite.Single(s => s.SiteId == item); list.Add(tmpSub); } return(list); }
/// <summary> /// Analyzes the specified expression. /// </summary> /// <param name="exp">The expression.</param> /// <returns> /// The result of analysis. /// </returns> public override IExpression Analyze(Arcsec exp) { if (!Helpers.HasVariable(exp, Variable)) { return(new Number(0)); } var abs = new Abs(exp.Argument.Clone()); var sqr = new Pow(exp.Argument.Clone(), new Number(2)); var sub = new Sub(sqr, new Number(1)); var sqrt = new Sqrt(sub); var mul = new Mul(abs, sqrt); var div = new Div(exp.Argument.Clone().Analyze(this), mul); return(div); }
public void AddValueToDB(int id, string name, Employee employee) { using (var session = NHibernateHelper.OpenSession()) { using (var transaction = session.BeginTransaction()) { Sub sub = new Sub(); sub.Name = name; sub.Employee = (employee == null) ? 0 : employee.ID; session.Save(sub); transaction.Commit(); } } }
public void GetSubPosts_Paging() { var session = User.Login(Configuration.GetKey("username"), Configuration.GetKey("password")); var page_00 = Sub.GetListing(session, SubRedditToTestWith); var page_01 = Sub.GetListing(session, SubRedditToTestWith, page_00.After); var page_02 = Sub.GetListing(session, SubRedditToTestWith, page_01.After); var page_03 = Sub.GetListing(session, SubRedditToTestWith, page_02.After); var page_04 = Sub.GetListing(session, SubRedditToTestWith, page_03.After); Assert.IsTrue(page_00.Count > 0); Assert.IsTrue(page_01.Count > 0); Assert.IsTrue(page_02.Count > 0); Assert.IsTrue(page_03.Count > 0); Assert.IsTrue(page_04.Count > 0); }
public CreateSubResponse Handle(CreateSub command) { var sub = new Sub { Id = GuidUtil.NewSequentialId(), Name = command.Name, SidebarText = command.SidebarText }; _subService.InsertSub(sub); return(new CreateSubResponse { SubId = sub.Id }); }
public void Complex() { var sub = new Sub(); poco.Complex = sub; A.CallTo(() => pocoFactory.FromEmbeddedEntity(typeof(Sub), A <Entity> ._)).Returns(sub); var prop = poco.GetType().GetProperty("Complex"); var value = EntityValueFactory.FromPropertyInfo(poco, prop, entityFactory, new List <string>()); var actual = PocoValueFactory.FromEntityValue(prop, value, pocoFactory); Assert.IsType <Sub>(actual); Assert.Same(sub, actual); }
public EditorSub(EditorLine el, bool isLine = false) { EL = el; InitializeComponent(); if (isLine) { SetIsLine(); ESub = new Sub("Name", "Info"); } else { ESub = new Sub("LineName", "Info"); } DisplayEditorName(); DisplayEditorInfo(); }
public ActionResult kskcselect(string subID) { try { string[] subIDs; subIDs = subID.Split(','); Sub subss = new Sub(); Student stu = new Student(); SelectSub ss = new SelectSub(); string num = Request.Cookies["studentInfo"]["studentNum"]; int stuid = bLLStudent.Details(c => c.StuNum == num).FirstOrDefault().StuID; stu = bLLStudent.Details(c => c.StuNum == num).FirstOrDefault(); string msg = ""; for (int i = 0; i < subIDs.Length; i++) { stu = null; int nowdi = int.Parse(subIDs[i]); subss = bllSub.Details(c => c.SubID == nowdi).FirstOrDefault(); if (bllselectsub.Details(c => c.StuID == stuid && c.SubID == nowdi).Count() != 0) { msg = "您已选择这门课程,不允许重复选择!~"; } else if (subss.ClassPeople < subss.NeedPeople) { int peopels = subss.ClassPeople + 1; subss.ClassPeople = peopels; ss.StuID = stuid; ss.SubID = nowdi; bllselectsub.Add(ss); bllSub.Edit(subss); bllselectsub.SaveChange(); bllSub.SaveChange(); msg = "ok"; } else { msg = "此课程选课人数已满!,不允许选课"; } } return(Content(msg)); } catch { return(Content("没有相应的数据,请刷新重试!")); } }
public void CanRemoveEvents() { Player player1 = new Player("1"); Rft map = new Rft(3000, 3000); Outpost outpost = new Outpost("0", new RftVector(map, 0, 0), player1, OutpostType.Generator); outpost.AddDrillers(10); Sub sub = new Sub("1", outpost, outpost, new GameTick(), 10, player1); CombatEvent arriveEvent = new CombatEvent(sub, outpost, new GameTick(5)); game.TimeMachine.AddEvent(arriveEvent); Assert.AreEqual(1, game.TimeMachine.GetQueuedEvents().Count); Assert.AreEqual(arriveEvent, game.TimeMachine.GetQueuedEvents()[0]); game.TimeMachine.RemoveEvent(arriveEvent); Assert.AreEqual(0, game.TimeMachine.GetQueuedEvents().Count); }
public void Add_InsertNewComment_ReturnCommentWithFilledProperties(int newsId, int commentId) { // Arrange var comment = new Comment(); var currentUtc = DateTime.UtcNow; Use <ICommentsProvider>() .Setup(c => c.Create(newsId, comment)) .Returns(commentId); // Act var actualResult = Sub.Add(newsId, comment); // Assert Assert.AreEqual(commentId, actualResult.Id); Assert.That(currentUtc, Is.LessThan(actualResult.CreatedAtUtc)); }
public async Task GetAsync_FindAllCommentsByNewsId_ReturnCommentsForNews(int newsId) { // Arrange var expectedCommentsCollection = new NewsCollection().Data .First(w => w.Id == newsId) .Comments; Use <ICommentsRepository>() .Setup(s => s.QueryAsync(It.IsAny <CommentSpecifications>())) .ReturnsAsync(expectedCommentsCollection); // Act var actualResult = await Sub.GetAsync(newsId); // Assert CollectionAssert.AreEqual(expectedCommentsCollection, actualResult); }
private static void MethodInfoInvokePerformanceTest() { object o = new object(); Sub sub = new Sub(); MethodInfo methodInfo = sub.GetType().GetMethod(methodName); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = loop / 1000; i > 0; i--) { methodInfo.Invoke(sub, new object[] { 1, o }); } stopwatch.Stop(); WriteResult("MethodInfo.Invoke", stopwatch.ElapsedMilliseconds, loop / 1000); Sub[] array = null; }
public void CanRemoveEvents() { Player player1 = new Player(1); Rft map = new Rft(3000, 3000); Outpost outpost = new Outpost(new RftVector(map, 0, 0), player1, OutpostType.Generator); outpost.AddDrillers(10); Sub sub = new Sub(outpost, outpost, new GameTick(), 10, player1); CombatEvent arriveEvent = new CombatEvent(sub, outpost, GameTick.FromTickNumber(5), outpost.GetTargetPosition(sub.GetCurrentPosition(), sub.GetSpeed())); Game.TimeMachine.AddEvent(arriveEvent); Assert.AreEqual(1, Game.TimeMachine.GetQueuedEvents().Count); Assert.AreEqual(arriveEvent, Game.TimeMachine.GetQueuedEvents()[0]); Game.TimeMachine.RemoveEvent(arriveEvent); Assert.AreEqual(0, Game.TimeMachine.GetQueuedEvents().Count); }
public ActionResult Index(Sub sandwich) { // "Name" Price double[] subPrice = new double[] { 1, 2, 3, 4, 5 }; string subName = Enum.GetName(typeof(SubName), sandwich.SubName); double priceName = subPrice[(int)sandwich.SubName]; //"Size" price double[] sizePrice = new double[] { 2, 3, 4, 5 }; string size = Enum.GetName(typeof(Size), sandwich.Size); double priceSize = sizePrice[(int)sandwich.Size]; //"Deal" Price double[] dealPrice = new double[] { 0, 1, 1.25 }; string deal = Enum.GetName(typeof(Meal), sandwich.Meal); double priceDeal = dealPrice[(int)sandwich.Meal]; //Calculate double unitPrice = (priceName * priceSize); double preTaxPrice = priceDeal + (priceName * priceSize); double taxPrice = preTaxPrice * 0.15; double totalPrice = preTaxPrice + taxPrice; DateTime today = DateTime.Today; string date = today.ToLongDateString(); // Send to Receipt String unitPrice2 = Convert.ToDecimal(unitPrice).ToString("C"); String dealPrice2 = Convert.ToDecimal(priceDeal).ToString("C"); String preTaxPrice2 = Convert.ToDecimal(preTaxPrice).ToString("C"); String taxPrice2 = Convert.ToDecimal(taxPrice).ToString("C"); String totalPrice2 = Convert.ToDecimal(totalPrice).ToString("C"); ViewData["subName"] = subName; ViewData["subSize"] = size; ViewData["subDeal"] = deal; ViewData["UnitPrice"] = unitPrice2; ViewData["dealPrice"] = dealPrice2; ViewData["preTaxPrice"] = preTaxPrice2; ViewData["tax"] = taxPrice2; ViewData["totalPrice"] = totalPrice2; ViewData["date"] = date; return(View("Receipt")); }
static void Main(string[] args) { while (true) { Add add = (x, y) => x + y; Sub sub = (x, y) => x - y; Mul mul = (x, y) => x * y; Div div = (x, y) => x / y; Console.WriteLine("Введите команду: Add - сложение, Sub - вычитание, Mul - умножение, Div - деление."); string userComand = Console.ReadLine(); Console.WriteLine("Введите числа для операции: \nПервое число:"); double a = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Второе число: "); double b = Convert.ToDouble(Console.ReadLine()); switch (userComand) { case "Add": case "add": Console.WriteLine("Сумма = " + add(a, b)); break; case "Sub": case "sub": Console.WriteLine("Вычитание = " + sub(a, b)); break; case "Mul": case "mul": Console.WriteLine("Умножение = " + mul(a, b)); break; case "Div": case "div": if (a == 0 || b == 0) { Console.WriteLine("Деление на ноль!"); } else { Console.WriteLine("Деление = " + div(a, b)); } break; } } }
public async Task GetAsync_FindNonExistentNews_ReturnNotFound(int newsId) { // Arrange var expectedNewsQuery = new NewsCollection().Data .Where(w => w.Id == newsId) .ToList(); Use <INewsRepository>() .Setup(s => s.QueryAsync(It.IsAny <NewsSpecifications>())) .ReturnsAsync(expectedNewsQuery); // Act var actualResult = await Sub.GetAsync(newsId); // Assert Assert.IsInstanceOf <NotFoundResult>(actualResult); }
public static void Main(String[] args) { DelegateClass obj = new DelegateClass(); // creating object of delegate Add delAdd = new Add(obj.Sum);// pass the parameter using class object "obj" Sub delSub = new Sub(obj.Subtract); Div delDiv = new Div(obj.Division); delAdd(20, 10); // pass the values to the methods by delegate object delSub(40, 50); delDiv(60, 30); //Another way by using "Invoke" method //delAdd.Invoke(20, 10); //delSub.Invoke(20, 10); }
static void Main(string[] args) { var env = new System.Collections.Generic.Dictionary<string, int>(); env.Add("z",5); env.Add("x",2); Expr e1 = new Add(new CstI(17), new Var("z")).Simplify(); Expr e2 = new Mul(new Var("x"), new Var("z")).Simplify(); Expr e3 = new Sub(new Mul(new CstI(17), new CstI(5)), new Var("z")).Simplify(); Expr e4 = new Add(new CstI(17), new CstI(0)).Simplify(); System.Console.Out.WriteLine(e1.ToString() + " = " + e1.Eval(env)); System.Console.Out.WriteLine(e2.ToString() + " = " + e2.Eval(env)); System.Console.Out.WriteLine(e3.ToString() + " = " + e3.Eval(env)); System.Console.Out.WriteLine(e4.ToString() + " = " + e4.Eval(env)); System.Console.ReadLine(); }
public Acceleration(ValBus input_pos1, ValBus input_pos2, ValBus magnitude_output) { this.input_pos1 = input_pos1; this.input_pos2 = input_pos2; this.mag_output = magnitude_output; // Constants double MASS_OF_ARGON = 39.948; // Constant processes var const_mass_of_argon = new Constants(MASS_OF_ARGON); // Calculation processes var sub = new Sub(); // TODO: Add calculations for more dimensions Force force = new Force(mag_output); // Piping sub.difference through magnitude var magnitude_pipe = new nPipe((long)Deflib.Magnitude_depth.n); // Piping sub.difference through force var force_pipe = new nPipe((long)Deflib.Force_depth.n); var mul = new Mul(); var div_mass = new Div(); sub.minuend = input_pos2; sub.subtrahend = input_pos1; // magnitude calculation mag_input = sub.difference; // pipe sub.difference through magnitude magnitude_pipe.first.input = sub.difference; // pipe sub.difference through force force_pipe.first.input = magnitude_pipe.last.output; mul.multiplicant = force.output; mul.multiplier = force_pipe.last.output; div_mass.divident = mul.product; div_mass.divisor = const_mass_of_argon.output; output = div_mass.quotient; }
public void Update_ChangeNewsById_ReturnNoContentResult() { // Arrange var news = new News { Id = 0 }; Use <INewsRepository>() .Setup(s => s.Update(news)) .Returns(news); // Act var actualResult = Sub.Update(news.Id, news); // Assert Assert.IsInstanceOf <NoContentResult>(actualResult); }
public void Update_ChangeNonExistentNews_ReturnNotFoundResult() { // Arrange var news = new News { Id = 100 }; Use <INewsRepository>() .Setup(s => s.Update(news)) .Returns((News)null); // Act var actualResult = Sub.Update(100, news); // Assert Assert.IsInstanceOf <NotFoundResult>(actualResult); }
private void button1_Click(object sender, EventArgs e) { Subject s = new Subject(); s.SubjectName = textBox3.Text; s.FullMarks = float.Parse(textBox4.Text); s.TheoryMarks = float.Parse(textBox5.Text); s.PracticalMarks = float.Parse(textBox6.Text); textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; textBox6.Text = ""; MessageBox.Show("Added Successfully !!! :)"); Sub.Add(s); }
public void Update_UseNewsWithDuplicatedId_ReturnInvalidOperationException() { // Arrange var news = new News { Id = 0 }; Use <INewsRepository>() .Setup(s => s.Update(news)) .Throws <InvalidOperationException>(); // Act ActualValueDelegate <object> updateDelegate = () => Sub.Update(news.Id, news); // Assert Assert.That(updateDelegate, Throws.TypeOf <InvalidOperationException>()); }
void SubBatch(object obj) { var m = Sub.Dequeue(); if (m != null) { PipeLine = m.PipeLine; scripts = m.scripts; vertex = m.vertex; uv = m.uv; uv1 = m.uv1; uv2 = m.uv2; uv3 = m.uv3; colors = m.colors; Batch(); Main.Enqueue(m); } }
public void PassiveChainTest() { //Nested Adds var add3 = new Add().And(new Add().And(new Add())); Assert.AreEqual(3, add3.Execute(0)); var sub5 = new Sub().And(new Sub().And(new Sub().And(new Sub().And(new Sub())))); Assert.AreEqual(10, sub5.Execute(15)); //Continous adds to Root var sub2 = new Add().And(new Sub()).And(new Sub()).And(new Sub()); Assert.AreEqual(3, sub2.Execute(5)); var add5 = new Add(); for (int i = 0; i < 4; i++) add5.And(new Add()); Assert.AreEqual(5, add5.Execute(0)); }
[Test] public void GetNonVirtualInvokerByInstance_InvokesSub_OnLoseParameterMatch() { Sub s1 = new Sub(); Sub s2 = new Sub(); var d = s1.GetNonVirtualInvoker <LostParameterByInstanceDelegate>(typeof(Base), "PublicVirtualInstance"); int intout; new Base().PublicVirtualInstance(3445, "objectb", s2, out intout); string expected = Sub.JustCalled; int expectedOut = intout; Sub.JustCalled = null; var result = d(3445, "objectb", s2, out intout); Assert.AreSame(s1, result); Assert.AreEqual(expected, Sub.JustCalled); Assert.AreEqual(expectedOut, intout); }
public void CanGoToAnEvent() { Player player1 = new Player("1"); Rft map = new Rft(3000, 3000); Outpost outpost = new Generator("0", new RftVector(map, 0, 0), player1); outpost.GetComponent <DrillerCarrier>().AddDrillers(10); Sub sub = new Sub("1", outpost, outpost, new GameTick(), 10, player1); CombatEvent arriveEvent = new CombatEvent(sub, outpost, new GameTick(5)); _game.TimeMachine.AddEvent(arriveEvent); Assert.AreEqual(2, _game.TimeMachine.GetQueuedEvents().Count); Assert.AreEqual(arriveEvent, _game.TimeMachine.GetQueuedEvents()[0]); _game.TimeMachine.GoTo(arriveEvent); Assert.AreEqual(arriveEvent.GetOccursAt().GetTick(), _game.TimeMachine.GetCurrentTick().GetTick()); Assert.AreEqual(1, _game.TimeMachine.GetQueuedEvents().Count); }
public void EventsSwitchQueuesWhenPassedForward() { Player player1 = new Player("1"); Rft map = new Rft(3000, 3000); Outpost outpost = new Generator("0", new RftVector(map, 0, 0), player1); outpost.GetComponent <DrillerCarrier>().AddDrillers(10); Sub sub = new Sub("1", outpost, outpost, new GameTick(), 10, player1); CombatEvent arriveEvent = new CombatEvent(sub, outpost, new GameTick(5)); _game.TimeMachine.AddEvent(arriveEvent); Assert.AreEqual(2, _game.TimeMachine.GetQueuedEvents().Count); Assert.AreEqual(arriveEvent, _game.TimeMachine.GetQueuedEvents()[0]); // Go past the tick _game.TimeMachine.Advance(6); Assert.AreEqual(1, _game.TimeMachine.GetQueuedEvents().Count); }
private static Cal SelectToCal(string opt, int num1, int num2) { Cal cal = null; switch (opt) { case "+": cal = new Add(num1, num2); break; case "-": cal = new Sub(num1, num2); break; case "*": cal = new Multiple(num1, num2); break; default:; break; } return(cal); }
private static void DynamicMethodInvokePerformanceTest() { Sub[] array = null; Base sub = new Sub(); DynamicMethod dynamicMethod = Utils.CreateDynamicMethod(typeof(Base).GetMethod(methodName)); object o = new object(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = loop / 1000; i > 0; i--) { dynamicMethod.Invoke(null, new object[] { sub, 1, o }); } stopwatch.Stop(); WriteResult("DynamicMethod.Invoke", stopwatch.ElapsedMilliseconds, loop / 1000); }
static string Example1() { Pirate p = new Pirate(); StringLiteral s1 = new StringLiteral("H\ae\bl\fl\vo\0 \'P\"arrot!\n"); Call c1 = new Call("print", s1); StmtList sl = new StmtList(); CallStmt cs1 = new CallStmt(c1); sl.Add(cs1); Sub main = new Sub("main", sl); p.Add(main); StringWriter sw = new StringWriter(); PirateWriter pv = new PirateWriter(sw); DynamicVisitor.accept(p, pv); return sw.ToString(); }
static string Example3() { Pirate p = new Pirate(); StmtList sl1 = new StmtList(); Sub joe = new Sub("joe", sl1); p.Add(joe); LocalDecl ld1 = new LocalDecl(); ld1.type = new StringType(); NamedReg name = new NamedReg(); name.name = "name"; IdList idl1 = new IdList(); idl1.Add(name); ld1.id_list = idl1; sl1.Add(ld1); Assign a1 = new Assign(); a1.lval = name; StringLiteral s1 = new StringLiteral(); s1.value = " Joe!"; a1.rval = s1; sl1.Add(a1); Assign a2 = new Assign(); StringLiteral s2 = new StringLiteral(); s2.value = "Hi!"; TmpStringReg tsr0 = new TmpStringReg(); tsr0.number = 0; a2.lval = tsr0; a2.rval = s2; sl1.Add(a2); Assign a3 = new Assign(); TmpStringReg tsr1 = new TmpStringReg(); tsr1.number = 1; BinaryCat bc1 = new BinaryCat(); bc1.a = tsr0; bc1.b = name; a3.lval = tsr1; a3.rval = bc1; sl1.Add(a3); AssignCat a4 = new AssignCat(); a4.lval = tsr1; StringLiteral s3 = new StringLiteral(); s3.value = "\n"; a4.rval = s3; sl1.Add(a4); CallStmt cs1 = new CallStmt(); Call c1 = new Call(); c1.func = "print"; c1.args = tsr1; cs1.call = c1; sl1.Add(cs1); StringWriter sw = new StringWriter(); PirateWriter pv = new PirateWriter(sw); DynamicVisitor.accept(p, pv); return sw.ToString(); }
static string Example6() { AtomExprList ael1 = new AtomExprList(); Call c1 = new Call("foo", ael1); CallStmt cs1 = new CallStmt(c1); NumLiteral n1 = new NumLiteral(3.14); TmpNumReg tnr0 = new TmpNumReg(0); Assign a1 = new Assign(tnr0, n1); TmpIntReg tir0 = new TmpIntReg(0); IntLiteral i1 = new IntLiteral(42); StringLiteral s1 = new StringLiteral("hi"); AtomExprList ael2 = new AtomExprList(); ael2.Add(tir0); ael2.Add(i1); ael2.Add(s1); Call c2 = new Call("bar", ael2); CallStmt cs2 = new CallStmt(c2); NamedReg a = new NamedReg("a"); LocalDecl ld1 = new LocalDecl(new IntType(), a); NamedReg b = new NamedReg("b"); LocalDecl ld2 = new LocalDecl(new NumType(), b); NamedReg c = new NamedReg("c"); LocalDecl ld3 = new LocalDecl(new StringType(), c); TmpNumReg tnr2 = new TmpNumReg(2); NumLiteral n2 = new NumLiteral(2.7); Assign a2 = new Assign(tnr2, n2); StringLiteral s2 = new StringLiteral("hello yourself"); AtomExprList ael3 = new AtomExprList(); ael3.Add(tnr2); ael3.Add(s2); Call c3 = new Call("baz", ael3); RegList rl4 = new RegList(); rl4.Add(a); rl4.Add(b); rl4.Add(c); Assign a3 = new Assign(rl4, c3); StmtList sl1 = new StmtList(); sl1.Add(cs1); sl1.Add(a1); sl1.Add(cs2); sl1.Add(ld1); sl1.Add(ld2); sl1.Add(ld3); sl1.Add(a2); sl1.Add(a3); Sub main = new Sub("main", sl1); StringLiteral s3 = new StringLiteral("Foo!\n"); Call c4 = new Call("print", s3); CallStmt cs3 = new CallStmt(c4); StmtList sl2 = new StmtList(); sl2.Add(cs3); Sub foo = new Sub("foo", sl2); NamedReg i = new NamedReg("i"); ParamDecl pd1 = new ParamDecl(new NumType(), i); NamedReg answer = new NamedReg("answer"); ParamDecl pd2 = new ParamDecl(new IntType(), answer); NamedReg message = new NamedReg("message"); ParamDecl pd3 = new ParamDecl(new StringType(), message); StringLiteral s4 = new StringLiteral("Bar!\n"); Call print1 = new Call("print", s4); CallStmt cs4 = new CallStmt(print1); Call print2 = new Call("print", i); CallStmt cs5 = new CallStmt(print2); StringLiteral s5 = new StringLiteral("\n"); Call print3 = new Call("print", s5); CallStmt cs6 = new CallStmt(print3); Call print4 = new Call("print", answer); CallStmt cs7 = new CallStmt(print4); CallStmt cs8 = new CallStmt(print3); Call print5 = new Call("print", message); CallStmt cs9 = new CallStmt(print5); StmtList sl3 = new StmtList(); sl3.Add(pd1); sl3.Add(pd2); sl3.Add(pd3); sl3.Add(cs4); sl3.Add(cs5); sl3.Add(cs6); sl3.Add(cs7); sl3.Add(cs8); sl3.Add(cs9); Sub bar = new Sub("bar", sl3); NamedReg e = new NamedReg("e"); ParamDecl pd4 = new ParamDecl(new NumType(), e); NamedReg msg = new NamedReg("msg"); ParamDecl pd5 = new ParamDecl(new StringType(), msg); StringLiteral s6 = new StringLiteral("Baz!\n"); Call print7 = new Call("print", s6); CallStmt cs10 = new CallStmt(print7); Call print8 = new Call("print", e); CallStmt cs11 = new CallStmt(print8); Call print9 = new Call("print", s5); CallStmt cs12 = new CallStmt(print9); Call print10 = new Call("print", msg); CallStmt cs13 = new CallStmt(print10); AtomExprList ael4 = new AtomExprList(); ael4.Add(new IntLiteral(1000)); ael4.Add(new NumLiteral(1.23)); ael4.Add(new StringLiteral("hi from baz")); ReturnStmt rs1 = new ReturnStmt(ael4); StmtList sl4 = new StmtList(); sl4.Add(pd4); sl4.Add(pd5); sl4.Add(cs10); sl4.Add(cs11); sl4.Add(cs12); sl4.Add(cs13); sl4.Add(rs1); Sub baz = new Sub("baz", sl4); Pirate p = new Pirate(); p.Add(main); p.Add(foo); p.Add(bar); p.Add(baz); StringWriter sw = new StringWriter(); PirateWriter pv = new PirateWriter(sw); DynamicVisitor.accept(p, pv); return sw.ToString(); }
public SubWrapped Wrap(Sub sub, User currentUser = null) { return Wrap(new List<Sub> { sub }, currentUser)[0]; }
/// <summary>Gets an array of all expressions contained in a CSV route.</summary> /// <param name="folder">The platform-specific absolute path to the folder where the main route file is stored.</param> /// <param name="file">The platform-specific absolute path to the file that contains the cell.</param> /// <param name="fallback">The fallback encoding.</param> /// <param name="expressions">The list of expressions.</param> /// <param name="expressionCount">The number of expressions.</param> /// <param name="with">The last argument to the With command.</param> private static void GetExpressionsFromCsvFile(string folder, string file, Encoding fallback, ref Expression[] expressions, ref int expressionCount, ref Sub[] subs, ref int subCount, ref string with) { /* * Read all lines from the file. * */ string[] lines = OpenBveApi.Text.GetLinesFromFile(file, fallback); /* * Now, split the lines on comma boundaries. * Ignore comments, then preprocess and add * expressions from all remaining cells. * */ for (int i = 0; i < lines.Length; i++) { if (lines[i].Length != 0) { string[] cells = lines[i].Split(','); for (int j = 0; j < cells.Length; j++) { if (cells[j].Length != 0) { cells[j] = cells[j].Trim(); if (cells[j].Length != 0) { if (cells[j][0] != ';') { PreprocessAndAddExpressions(folder, file, false, fallback, i, j, cells[j], ref expressions, ref expressionCount, ref subs, ref subCount, ref with); } } } } } } }
public void UpdateSub(Sub sub) { _conn.Perform(conn => conn.Update(sub)); }
// static functions /// <summary>Sets a $Sub variable to a specified value.</summary> /// <param name="subs">The list of $Sub variables.</param> /// <param name="subCount">The number of $Sub variables.</param> /// <param name="index">The non-negative index to the $Sub variable that is to be set.</param> /// <param name="value">The value for the $Sub variable to be set.</param> internal static void Set(ref Sub[] subs, ref int subCount, int index, string value) { for (int i = 0; i < subCount; i++) { if (subs[i].Index == index) { subs[i].Value = value; return; } } if (subCount == subs.Length) { Array.Resize<Sub>(ref subs, subs.Length << 1); } subs[subCount] = new Sub(index, value); subCount++; }
static string Example5() { NamedReg x1 = new NamedReg(); x1.name = "x1"; NamedReg x2 = new NamedReg(); x2.name = "x2"; IdList idl1 = new IdList(); idl1.Add(x1); idl1.Add(x2); LocalDecl ld1 = new LocalDecl(); ld1.type = new NumType(); ld1.id_list = idl1; AtomExprList ael1 = new AtomExprList(); ael1.Add(x1); ael1.Add(x2); ReturnStmt rs1 = new ReturnStmt(); rs1.rv = ael1; StmtList sl1 = new StmtList(); sl1.Add(ld1); sl1.Add(rs1); Sub abc = new Sub("abc", sl1); Pirate p = new Pirate(); p.Add(abc); StringWriter sw = new StringWriter(); PirateWriter pv = new PirateWriter(sw); DynamicVisitor.accept(p, pv); return sw.ToString(); }
public SubWrapped(Sub sub) { Sub = sub; }
/// <summary>Gets an array of all expressions contained in an RW/CSV route.</summary> /// <param name="folder">The platform-specific absolute path to the folder where the main route file is stored.</param> /// <param name="file">The platform-specific absolute path to the file that contains the cell.</param> /// <param name="isRw">Whether the route is of RW format.</param> /// <param name="fallback">The fallback encoding.</param> /// <param name="expressions">Receives the expressions.</param> /// <returns>An array of expressions.</returns> private static void GetExpressionsFromFile(string folder, string file, bool isRw, Encoding fallback, out Expression[] expressions) { /* * First, extract expressiosn from the file. * */ expressions = new Expression[4096]; int expressionCount = 0; Sub[] subs = new Sub[16]; int subCount = 0; if (isRw) { string section = "Invalid"; GetExpressionsFromRwFile(folder, file, fallback, ref expressions, ref expressionCount, ref subs, ref subCount, ref section); } else { string with = null; GetExpressionsFromCsvFile(folder, file, fallback, ref expressions, ref expressionCount, ref subs, ref subCount, ref with); } for (int i = 0; i < expressionCount; i++) { if (IO.IsTrackPosition(expressions[i].CsvEquivalentCommand)) { expressions[i].Type = ExpressionType.Position; } else if (expressions[i].CsvEquivalentCommand.StartsWith("Track.", StringComparison.OrdinalIgnoreCase)) { expressions[i].Type = ExpressionType.Track; } else { expressions[i].Type = ExpressionType.General; } } Array.Resize<Expression>(ref expressions, expressionCount); }
/// <summary>Gets an array of all expressions contained in a RW route.</summary> /// <param name="folder">The platform-specific absolute path to the folder where the main route file is stored.</param> /// <param name="file">The platform-specific absolute path to the file that contains the cell.</param> /// <param name="fallback">The fallback encoding.</param> /// <param name="expressions">The list of expressions.</param> /// <param name="expressionCount">The number of expressions.</param> /// <param name="section">The last opened section.</param> private static void GetExpressionsFromRwFile(string folder, string file, Encoding fallback, ref Expression[] expressions, ref int expressionCount, ref Sub[] subs, ref int subCount, ref string section) { /* * Read all lines from the file. * */ string[] lines = OpenBveApi.Text.GetLinesFromFile(file, fallback); for (int i = 0; i < lines.Length; i++) { if (lines[i].Length != 0) { lines[i] = lines[i].Trim(); } } /* * Find the first section in the file. * The text prior to the first section * is the file's comments. * */ int start; StringBuilder descriptions = new StringBuilder(); for (start = 0; start < lines.Length; start++) { if (lines[start].Length != 0 && lines[start][0] == '[') { break; } else { descriptions.AppendLine(lines[start]); } } if (descriptions.Length != 0) { if (expressions.Length == expressionCount) { Array.Resize<Expression>(ref expressions, expressions.Length << 1); } expressions[expressionCount] = new Expression(file, 0, 0, "Route.Comment", null, null, new string[] { descriptions.ToString().Trim() }); expressionCount++; } /* * For the rest of the file, the syntax of each * line depends on the section. * */ bool isRailwaySection = section.Equals("Railway", StringComparison.OrdinalIgnoreCase); for (int i = start; i < lines.Length; i++) { if (lines[i].Length != 0) { if (lines[i][0] == '[') { /* * A new section is started. * */ int semicolon = lines[i].IndexOf(';'); if (semicolon >= 0) { lines[i] = lines[i].Substring(0, semicolon).TrimEnd(); } if (lines[i][lines[i].Length - 1] == ']') { section = lines[i].Substring(1, lines[i].Length - 2).Trim(); string sectionLower = section.ToLowerInvariant(); switch (sectionLower) { case "structure": IO.ReportInvalidData(file, i, 0, "The [Structure] section is invalid in RW routes. Use [Object] instead."); break; case "track": IO.ReportInvalidData(file, i, 0, "The [Track] section is invalid in RW routes. Use [Railway] instead."); break; } isRailwaySection = sectionLower == "railway"; } else { IO.ReportInvalidData(file, i, 0, "A section must end in a closing bracket."); section = "Invalid"; isRailwaySection = false; } } else if (isRailwaySection) { /* * The line from the [Railway] section. * */ int semicolon = lines[i].IndexOf(';'); if (semicolon >= 0) { lines[i] = lines[i].Substring(0, semicolon).TrimEnd(); } if (lines[i].Length != 0) { PreprocessAndAddExpressions(folder, file, true, fallback, i, 0, lines[i], ref expressions, ref expressionCount, ref subs, ref subCount, ref section); } } else { /* * A line from a other section. * */ int semicolon = lines[i].IndexOf(';'); if (semicolon >= 0) { int equals = lines[i].IndexOf('='); if (equals == -1 | equals > semicolon) { lines[i] = lines[i].Substring(0, semicolon).TrimEnd(); } } if (lines[i].Length != 0) { PreprocessAndAddExpressions(folder, file, true, fallback, i, 0, lines[i], ref expressions, ref expressionCount, ref subs, ref subCount, ref section); } } } } }
/// <summary>Preprocesses a cell for the $-group of commands and adds the resulting expressions to a specified list of expressions.</summary> /// <param name="folder">The platform-specific absolute path to the folder where the main route file is stored.</param> /// <param name="file">The platform-specific absolute path to the file that contains the cell.</param> /// <param name="isRw">Whether the route is of RW format.</param> /// <param name="fallback">The fallback encoding.</param> /// <param name="row">The zero-based row at which the cell is stored.</param> /// <param name="column">The zero-based column at which the cell is stored.</param> /// <param name="cell">The non-empty content of the trimmed CSV cell or the trimmed RW line.</param> /// <param name="expressions">The list of expressions.</param> /// <param name="expressionCount">The number of expressions.</param> /// <param name="withOrSection">The last argument to the With command for CSV files, or the last opened section for RW files.</param> /// <remarks>For RW files, the line is further split at at sign boundaries after preprocessing but before expressions are extracted.</remarks> private static void PreprocessAndAddExpressions(string folder, string file, bool isRw, Encoding fallback, int row, int column, string cell, ref Expression[] expressions, ref int expressionCount, ref Sub[] subs, ref int subCount, ref string withOrSection) { /* * Find $Chr, $Rnd and $Sub directives from right to left * and substitute their results back into the cell. * */ for (int i = cell.Length - 1; i >= 0; i--) { if (cell[i] == '$' ) { for (int j = i + 1; j <= cell.Length; j++) { if (cell[j] == '(') { for (int k = j + 1; k < cell.Length; k++) { if (cell[k] == '(') { IO.ReportInvalidData(file, row, column, "Invalid opening paranthesis."); return; } else if (cell[k] == ')') { string argumentSequence = cell.Substring(j + 1, k - j - 1); string[] arguments = argumentSequence.Split(';'); for (int h = 0; h < arguments.Length; h++) { arguments[h] = arguments[h].Trim(); } string command = cell.Substring(i, j - i); switch (command.ToLowerInvariant()) { case "$chr": { if (IO.CheckArgumentCount(file, row, column, command, arguments.Length, 1, 1, false)) { int value; if (IO.ParseInt(file, row, column, command, arguments, 0, "codepoint", 0, 1114111, 0, out value)) { if (value < 0xD800 | value > 0xDFFF) { string substitute = char.ConvertFromUtf32(value); cell = cell.Substring(0, i) + substitute + cell.Substring(k + 1); } else { IO.ReportInvalidData(file, row, column, command, "The codepoint is in the range of surrogates. For characters outside the basic multilingual plane, use the corresponding codepoint directly."); return; } } else { return; } } else { return; } } break; case "$rnd": { if (IO.CheckArgumentCount(file, row, column, command, arguments.Length, 2, 2, false)) { int minimum; if (IO.ParseInt(file, row, column, command, arguments, 0, "minimum", int.MinValue, int.MaxValue, 0, out minimum)) { int maximum; if (IO.ParseInt(file, row, column, command, arguments, 1, "maximum", int.MinValue, int.MaxValue, 0, out maximum)) { if (minimum <= maximum) { int number = RandomNumberGenerator.Next(minimum, maximum + 1); string substitute = number.ToString(System.Globalization.CultureInfo.InvariantCulture); cell = cell.Substring(0, i) + substitute + cell.Substring(k + 1); } else { IO.ReportInvalidData(file, row, column, command, "Minimum must be less than or equal to Maximum."); return; } } else { return; } } else { return; } } else { return; } } break; case "$sub": { bool assignment = false; for (int h = k + 1; h < cell.Length; h++) { if (cell[h] == '=') { assignment = true; if (IO.CheckArgumentCount(file, row, column, command, arguments.Length, 1, 1, false)) { int index; if (IO.ParseInt(file, row, column, command, arguments, 0, "index", 0, int.MaxValue, 0, out index)) { string value = cell.Substring(h + 1).TrimStart(); Sub.Set(ref subs, ref subCount, index, value); cell = cell.Substring(0, i); } else { return; } } else { return; } } else if (!char.IsWhiteSpace(cell[h])) { break; } } if (!assignment) { if (IO.CheckArgumentCount(file, row, column, command, arguments.Length, 1, 1, true)) { int index; if (IO.ParseInt(file, row, column, command, arguments, 0, "index", 0, int.MaxValue, 0, out index)) { string value; if (Sub.Get(subs, subCount, index, out value)) { cell = cell.Substring(0, i) + value + cell.Substring(k + 1); } else { IO.ReportInvalidData(file, row, column, command, "A $Sub variable is queried which has not been defined."); return; } } else { return; } } else { return; } } } break; case "$include": if (IO.CheckArgumentCount(file, row, column, command, arguments.Length, 1, int.MaxValue, true)) { int count = (arguments.Length + 1) / 2; string[] files = new string[count]; double[] weights = new double[count]; double weightsTotal = 0.0; for (int h = 0; h < count; h++) { files[h] = OpenBveApi.Path.CombineFile(folder, arguments[2 * h]); if (h == count - 1 && (arguments.Length & 1) == 1) { weights[h] = 1.0; } else { if (!IO.ParseDouble(file, row, column, command, arguments, 2 * h + 1, "weight" + h.ToString(CultureInfo.InvariantCulture), 0.0, double.MaxValue, 1.0, out weights[h])) { weights[h] = 1.0; } } weightsTotal += weights[h]; } double number = RandomNumberGenerator.NextDouble() * weightsTotal; int index = count - 1; for (int h = 0; h < count; h++) { number -= weights[h]; if (number < 0.0) { index = h; break; } } if (System.IO.File.Exists(files[index])) { if (isRw) { GetExpressionsFromRwFile(folder, files[index], fallback, ref expressions, ref expressionCount, ref subs, ref subCount, ref withOrSection); } else { GetExpressionsFromCsvFile(folder, files[index], fallback, ref expressions, ref expressionCount, ref subs, ref subCount, ref withOrSection); } } else { IO.ReportMissingFile(file, row, column, command, files[index]); } cell = cell.Substring(0, i) + cell.Substring(k + 1); } else { return; } break; default: IO.ReportInvalidData(file, row, column, command, "The directive is not recognized."); return; } break; } } break; } else if (cell[j] == ')') { IO.ReportInvalidData(file, row, column, "Missing closing paranthesis."); return; } } } } /* * If the cell is not empty, create * an expression from it and add it * to the list of expressions. * */ if (cell.Length != 0) { cell = cell.Trim(); if (cell.Length != 0) { if (isRw) { /* * RW file. * */ if (withOrSection.Equals("railway", StringComparison.OrdinalIgnoreCase)) { /* * Inside the [Railway] section, multiple expressions * may be chained together. Split them apart at @-sign * boundaries, where the @-sign is considered to be * part of the following cell. * */ column = 0; while (true) { int atSign = cell.IndexOf('@', 1); if (atSign >= 1) { string text = cell.Substring(0, atSign).TrimEnd(); if (text.Length != 0) { if (expressionCount == expressions.Length) { Array.Resize<Expression>(ref expressions, expressions.Length << 1); } Expression expression; if (GetExpressionFromRwCell(file, row, column, text, withOrSection, out expression)) { expressions[expressionCount] = expression; expressionCount++; } } cell = cell.Substring(atSign); column++; } else { break; } } if (cell.Length != 0) { if (expressionCount == expressions.Length) { Array.Resize<Expression>(ref expressions, expressions.Length << 1); } Expression expression; if (GetExpressionFromRwCell(file, row, column, cell, withOrSection, out expression)) { expressions[expressionCount] = expression; expressionCount++; } } } else { /* * Outside the [Railway] section, only one * expression per line is allowed. * */ if (expressionCount == expressions.Length) { Array.Resize<Expression>(ref expressions, expressions.Length << 1); } Expression expression; if (GetExpressionFromRwCell(file, row, column, cell, withOrSection, out expression)) { expressions[expressionCount] = expression; expressionCount++; } } } else { /* * CSV file. * */ if (cell[0] != ';') { if (expressionCount == expressions.Length) { Array.Resize<Expression>(ref expressions, expressions.Length << 1); } Expression expression; if (GetExpressionFromCsvCell(file, row, column, cell, ref withOrSection, out expression)) { expressions[expressionCount] = expression; expressionCount++; } } } } } }
/// <summary>Gets the value of a specified $Sub variable.</summary> /// <param name="subs">The list of $Sub variables.</param> /// <param name="subCount">The number of $Sub variables.</param> /// <param name="index">The non-negative index to the $Sub variable that is to be queried.</param> /// <param name="value">Receives the value of the queried $Sub variable on success.</param> /// <returns>A value indicating whether the $Sub variable could be retrieved.</returns> internal static bool Get(Sub[] subs, int subCount, int index, out string value) { for (int i = 0; i < subCount; i++) { if (subs[i].Index == index) { value = subs[i].Value; return true; } } value = null; return false; }
/// <exception cref="System.Exception"></exception> protected override void Store() { var sub = new Sub ("super", "sub"); Store(sub); }
static string Example4() { StmtList sl1 = new StmtList(); Sub foo = new Sub("foo", sl1); Pirate p = new Pirate(); p.Add(foo); ParamDecl pd1 = new ParamDecl(); pd1.type = new IntType(); IdList idl1 = new IdList(); NamedReg n = new NamedReg(); n.name = "n"; idl1.Add(n); pd1.id_list = idl1; sl1.Add(pd1); ParamDecl pd2 = new ParamDecl(); pd2.type = new StringType(); IdList idl2 = new IdList(); NamedReg message = new NamedReg(); message.name = "message"; idl2.Add(message); pd2.id_list = idl2; sl1.Add(pd2); StringWriter sw = new StringWriter(); PirateWriter pv = new PirateWriter(sw); DynamicVisitor.accept(p, pv); return sw.ToString(); }
public void InsertSub(Sub sub) { _conn.Perform(conn => conn.Insert(sub)); }
static string Example2() { NamedReg a = new NamedReg("a"); NamedReg b = new NamedReg("b"); NamedReg c = new NamedReg("c"); NamedReg det = new NamedReg("det"); IdList rl1 = new IdList(); rl1.Add(a); rl1.Add(b); rl1.Add(c); rl1.Add(det); LocalDecl ld1 = new LocalDecl(new NumType(), rl1); IntLiteral il3 = new IntLiteral(2); Assign a12 = new Assign(a, il3); IntLiteral il4 = new IntLiteral(-3); Assign a13 = new Assign(b, il4); IntLiteral il5 = new IntLiteral(-2); Assign a14 = new Assign(c, il5); UnaryNeg un1 = new UnaryNeg(b); TmpNumReg tnr0 = new TmpNumReg(0); Assign a1 = new Assign(tnr0, un1); TmpNumReg tnr1 = new TmpNumReg(1); BinaryMul bm1 = new BinaryMul(b, b); Assign a2 = new Assign(tnr1, bm1); TmpNumReg tnr2 = new TmpNumReg(2); IntLiteral il1 = new IntLiteral(4); BinaryMul bm2 = new BinaryMul(il1, a); Assign a3 = new Assign(tnr2, bm2); BinaryMul bm3 = new BinaryMul(tnr2, c); Assign a4 = new Assign(tnr2, bm3); TmpNumReg tnr3 = new TmpNumReg(3); IntLiteral il2 = new IntLiteral(2); BinaryMul bm4 = new BinaryMul(il2, a); Assign a5 = new Assign(tnr3, bm4); BinarySub bs1 = new BinarySub(tnr1, tnr2); Assign a6 = new Assign(det, bs1); TmpNumReg tnr4 = new TmpNumReg(4); Call sqrt = new Call("sqrt", det); Assign a7 = new Assign(tnr4, sqrt); NamedReg x1 = new NamedReg("x1"); NamedReg x2 = new NamedReg("x2"); IdList rl2 = new IdList(); rl2.Add(x1); rl2.Add(x2); LocalDecl ld2 = new LocalDecl(new NumType(), rl2); BinaryAdd ba1 = new BinaryAdd(tnr0, tnr4); Assign a8 = new Assign(x1, ba1); BinaryDiv bd1 = new BinaryDiv(x1, tnr3); Assign a9 = new Assign(x1, bd1); BinarySub bs2 = new BinarySub(tnr0, tnr4); Assign a10 = new Assign(x2, bs2); AssignDiv a11 = new AssignDiv(x2, tnr3); StringLiteral s1 = new StringLiteral("Answers to ABC formula are:\n"); Call c1 = new Call("print", s1); CallStmt print1 = new CallStmt(c1); StringLiteral s2 = new StringLiteral("x1 = "); Call c2 = new Call("print", s2); CallStmt print2 = new CallStmt(c2); Call c3 = new Call("print", x1); CallStmt print3 = new CallStmt(c3); StringLiteral s4 = new StringLiteral("\nx2 = "); Call c4 = new Call("print", s4); CallStmt print4 = new CallStmt(c4); Call c5 = new Call("print", x2); CallStmt print5 = new CallStmt(c5); StringLiteral s6 = new StringLiteral("\n"); Call c6 = new Call("print", s6); CallStmt print6 = new CallStmt(c6); StmtList sl1 = new StmtList(); sl1.Add(ld1); sl1.Add(a12); sl1.Add(a13); sl1.Add(a14); sl1.Add(a1); sl1.Add(a2); sl1.Add(a3); sl1.Add(a4); sl1.Add(a5); sl1.Add(a6); sl1.Add(a7); sl1.Add(ld2); sl1.Add(a8); sl1.Add(a9); sl1.Add(a10); sl1.Add(a11); sl1.Add(print1); sl1.Add(print2); sl1.Add(print3); sl1.Add(print4); sl1.Add(print5); sl1.Add(print6); Sub foo = new Sub("foo", sl1); Pirate p = new Pirate(); p.Add(foo); StringWriter sw = new StringWriter(); PirateWriter pv = new PirateWriter(sw); DynamicVisitor.accept(p, pv); return sw.ToString(); }
private static void Download( Video video, string videoName, string targetFolder, string tempFolder, SubDivXManager subDivXManager, Sub selectedSub) { var tempRarFile = Path.Combine(tempFolder, "subtmp.rar"); if (Directory.Exists(tempFolder)) { Directory.Delete(tempFolder, true); } Console.WriteLine("Downloading sub to {0}", tempRarFile); subDivXManager.DownloadSub(tempRarFile, selectedSub.DownloadUrl); var rarFilesExtracted = new List<string>(); var rarFiles = new List<string>(); rarFiles.AddRange(Directory.GetFiles(tempFolder, "*.rar", SearchOption.TopDirectoryOnly)); rarFiles.AddRange(Directory.GetFiles(tempFolder, "*.zip", SearchOption.TopDirectoryOnly)); while (rarFiles.Any()) { foreach (var rarFile in rarFiles) { if (!RarArchive.IsRarFile(rarFile)) { using (var zipFile = new ZipFile(rarFile)) { zipFile.ExtractAll(tempFolder, ExtractExistingFileAction.OverwriteSilently); } } else { RarArchive.WriteToDirectory(rarFile, tempFolder, ExtractOptions.Overwrite); } rarFilesExtracted.Add(rarFile); } rarFiles.Clear(); rarFiles.AddRange(Directory.GetFiles(tempFolder, "*.rar", SearchOption.TopDirectoryOnly)); rarFiles.AddRange(Directory.GetFiles(tempFolder, "*.zip", SearchOption.TopDirectoryOnly)); rarFiles.RemoveAll(item => rarFilesExtracted.Contains(item)); } var subFiles = new List<string>(); subFiles.AddRange(Directory.GetFiles(tempFolder, "*.sub", SearchOption.TopDirectoryOnly)); subFiles.AddRange(Directory.GetFiles(tempFolder, "*.srt", SearchOption.TopDirectoryOnly)); if (subFiles.Where(item => item.IndexOf(video.ReleaseGroup, StringComparison.OrdinalIgnoreCase) > -1).Any()) { subFiles.RemoveAll(item => item.IndexOf(video.ReleaseGroup, StringComparison.OrdinalIgnoreCase) < 0); } else { Console.WriteLine("No subtitles matching ReleaseGroup found"); } if (subFiles.Count == 1) { Console.WriteLine("Best match found, renaming to match video filename."); } else { Console.WriteLine("Mutiple subtitles found, leaving file names unmodified."); } foreach (var subFile in subFiles) { var destFile = string.Empty; if (subFiles.Count == 1) { destFile = Path.Combine(targetFolder, Path.GetFileName(videoName + Path.GetExtension(subFile))); } else { destFile = Path.Combine(targetFolder, Path.GetFileName(subFile)); } File.Copy(subFile, destFile, true); Console.WriteLine("Copying sub {0} to {1}", Path.GetFileName(destFile), Path.GetDirectoryName(destFile)); } }
public IList<Sub> GetCandidateSubs(Video video, bool searchInComments, Dictionary<string, string> cache) { Console.WriteLine(); Console.WriteLine("Text used to seach subtitle is: {0}", video.GetSearchString()); Console.WriteLine("Release Group to match: {0}", video.ReleaseGroup); this.login(); var candidateSubs = new List<Sub>(); var subdivxClient = new CookieAwareWebClient(this.loginCookies); subdivxClient.Headers["User-Agent"] = "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))"; var page = 1; while (page > 0) { var url = this.GetUrl(video.GetSearchString(), page); string output; if (cache.ContainsKey(url)) { output = cache[url]; } else { output = subdivxClient.DownloadString(url); cache.Add(url, output); } var doc = new HtmlDocument(); doc.LoadHtml(output); var subsHtmlNodes = doc.DocumentNode.Descendants("div").Where(div => div.GetAttributeValue("id", string.Empty).Equals("buscador_detalle")); if (subsHtmlNodes.Count() == 0) { page = -1; } else { foreach (var subHtmlNode in subsHtmlNodes) { var subComments = string.Empty; if (searchInComments) { subComments = this.GetSubComments(subdivxClient, subHtmlNode); } var sub = new Sub(subHtmlNode, subComments); if (sub.Matches(video)) { candidateSubs.Add(sub); } } } page++; } candidateSubs.Sort(new Sub.SubComparer()); return candidateSubs; }
public void CalculateTest(double firstArgument, double secondArgument, double result, double accracy) { var testingFunction = new Sub(); var testResult = testingFunction.Calculate(firstArgument, secondArgument); Assert.AreEqual(result, testResult, accracy); }