private void createNewConstructors() { NameReference type_name = this.Name.CreateNameReference(null, this.InstanceOf, isLocal: true); if (!this.NestedFunctions.Any(it => it.IsNewConstructor())) { foreach (FunctionDefinition init_cons in this.NestedFunctions.Where(it => it.IsInitConstructor()).StoreReadOnly()) { //if (this.NestedFunctions.Any(it => it.IsNewConstructor() // && it.Name.Arity == init_cons.Name.Arity && it.NOT_USED_CounterpartParameters(init_cons))) //continue; const string local_this = "__this__"; var new_cons = FunctionDefinition.CreateHeapConstructor(init_cons.Modifier, init_cons.Parameters, type_name, Block.CreateStatement(new IExpression[] { VariableDeclaration.CreateStatement(local_this, null, Alloc.Create(type_name, useHeap: true)), FunctionCall.Create(NameReference.Create(NameReference.Create(local_this), NameFactory.InitConstructorName), init_cons.Parameters.Select(it => FunctionArgument.Create(it.Name.CreateNameReference())).ToArray()), Return.Create(NameReference.Create(local_this)) })); this.AddNode(new_cons); } } }
public void destroy() { Alloc.free(WaitSemaphores); Alloc.free(Swapchains); Alloc.free(ImageIndices); Alloc.free(Results); }
private ByteBuf AllocBuffer(int capacity) { if (_direct) { return(Alloc.DirectBuffer(capacity)); } return(Alloc.HeapBuffer(capacity)); }
// New Alloc, Push, read memory public static void Push(string msg) { if (check) { Alloc alloc = new Alloc(++count, 0, msg); mem.Push(alloc); alloc.mem = GC.GetTotalMemory(true); Console.WriteLine(string.Format("<{0}, {1}>, Start <{2}>", alloc.count, msg, alloc.mem)); } }
// New Alloc, Push, read memory public static void Push(string msg) { if(check) { Alloc alloc = new Alloc(++count, 0, msg); mem.Push(alloc); alloc.mem = GC.GetTotalMemory(true); Console.WriteLine(string.Format("<{0}, {1}>, Start <{2}>", alloc.count, msg, alloc.mem)); } }
internal byte *ProcessString(WCString pString) { if (!Initialized) { Initializer.Initialize(this); } if (Settings.SanityCheck && SanityChecks.IsBadCodePtr(pString)) { return(pString); } var String = pString; foreach (var Rld in Reloads) { var New = Rld.BeforeReload(String, true); if (New != null) { String = New; } } var Rst = ProcessString((string)String); if (Rst == null) { return(String); } var Output = (WCString)Rst; foreach (var Rld in Reloads) { var New = Rld.AfterReload(pString, Output, true); if (New != null) { Output = New; } } if (Settings.Overwrite && Output != null && ((string)Output) != null) { return((WCString)Alloc.Overwrite(Output.ToArray(), pString)); } if (Settings.HeapAlloc && Output != null && ((string)Output) != null) { return((WCString)Alloc.CreateHeap(Output.ToArray())); } return(Output); }
// Indicates whether the transform id assigned to an element has changed. It does not care who the owner is. static bool TransformIDHasChanged(Alloc before, Alloc after) { if (before.size == 0 && after.size == 0) { // Whatever start is, both are invalid allocations. return(false); } if (before.size != after.size || before.start != after.start) { return(true); } return(false); }
// Pop, del Alloc, read memory public static void Pop() { if (check) { end = GC.GetTotalMemory(true); Alloc alloc = (Alloc)mem.Pop(); long count = alloc.count; long start = alloc.mem; string msg = alloc.msg; // Log it Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "<{0}, {1}>, Start <{2}>, End <{3}>, Diff <{4}>", count, msg, start, end, end - start)); } }
/// <summary> /// 异步激活 /// </summary> /// <returns></returns> public override Task ActiveAsync() { var promise = new TaskCompletionSource(); Execute(() => { receivingByteBuf = Alloc.Buffer(this.ReceivingBufferSize); receivingSocketAsyncEventArgs.ByteBuf = receivingByteBuf; SetConnection(); //设置读取缓冲区,将状态设置为Activity之后就可以直接完成任务了 invoker.fireOnChannelActive(promise); TryReceiving(); }); return(promise.Task); }
public _SwapchainCreateInfoKHR(SwapchainCreateInfoKHR info) { SType = info.type; Next = info.next; Flags = info.flags; Surface = info.surface; MinImageCount = info.minImageCount; ImageFormat = info.imageFormat; ImageColorSpace = info.imageColorSpace; ImageExtent = info.imageExtent; ImageArrayLayers = info.imageArrayLayers; ImageUsage = info.imageUsage; ImageSharingMode = info.imageSharingMode; QueueFamilyIndexCount = (UInt32)(info.queueFamilyIndices?.Count ?? 0); QueueFamilyIndices = info.queueFamilyIndices != null?Alloc.alloc(info.queueFamilyIndices) : IntPtr.Zero; PreTransform = info.preTransform; CompositeAlpha = info.compositeAlpha; PresentMode = info.presentMode; Clipped = info.clipped; OldSwapchain = info.oldSwapchain; }
public void Begin(VisualElement ve, UIRenderDevice device) { Debug.Assert(ve.renderChainData.usesLegacyText && ve.renderChainData.textEntries.Count > 0); this.m_CurrentElement = ve; this.m_TextEntryIndex = 0; Alloc allocVerts = ve.renderChainData.data.allocVerts; NativeSlice <Vertex> slice = ve.renderChainData.data.allocPage.vertices.cpuData.Slice((int)allocVerts.start, (int)allocVerts.size); device.Update(ve.renderChainData.data, ve.renderChainData.data.allocVerts.size, out this.m_MeshDataVerts); RenderChainTextEntry renderChainTextEntry = ve.renderChainData.textEntries[0]; bool flag = ve.renderChainData.textEntries.Count > 1 || renderChainTextEntry.vertexCount != this.m_MeshDataVerts.Length; if (flag) { this.m_MeshDataVerts.CopyFrom(slice); } int firstVertex = renderChainTextEntry.firstVertex; this.m_XFormClipPages = slice[firstVertex].xformClipPages; this.m_IDsFlags = slice[firstVertex].idsFlags; this.m_OpacityPagesSettingsIndex = slice[firstVertex].opacityPageSVGSettingIndex; }
public void ShouldClear() { using var alloc = new Alloc(128); alloc.Size.ShouldBe(128); var ptr = (int *)alloc.AlignedPointer; for (var i = 0; i < alloc.Size / 4; i++) { ptr[i] = 0x5a5a5a5a; } Unsafe.ClearAlign16((void *)alloc.AlignedPointer, alloc.Size); for (var i = 0; i < alloc.Size / 4; i++) { ptr[i].ShouldBe(0); } Unsafe.ClearAlign16((void *)alloc.AlignedPointer, alloc.Size, 0x5aa5aa55); for (var i = 0; i < alloc.Size / 4; i++) { ptr[i].ShouldBe(0x5aa5aa55); } }
public _PresentInfoKHR(PresentInfoKHR info) { SType = info.type; Next = info.next; WaitSemaphoreCount = (UInt32)info.waitSemaphores.Count; SwapchainCount = (UInt32)info.swapchains.Count; WaitSemaphores = Alloc.alloc(info.waitSemaphores); Swapchains = Alloc.alloc(info.swapchains); ImageIndices = Alloc.alloc(info.indices); List <UInt32> res; if (info.results == null || info.results.Count == 0) { Results = IntPtr.Zero; } else { res = new List <UInt32>(info.results.Count); Results = Alloc.alloc(res); } }
public static AmiVar GetExtraData(string ticker, string name, int arraySize, Periodicity periodicity, Alloc alloc) { return(new AmiVar()); }
extern public static void Log4JSetAllocator(Alloc alloc, Free free);
public static extern IntPtr NewState( Alloc alloc, IntPtr baton );
public static extern IntPtr NewState(Alloc alloc, IntPtr baton);
public IMemory CreateAlloc(int size) { return(Alloc.Create(size)); }
public static AmiVar GetExtraData(string ticker, string name, int arraySize, Periodicity periodicity, Alloc alloc) { return new AmiVar(); }
public void destroy() { Alloc.free(QueueFamilyIndices); }
public static extern SshSessionHandle libssh2_session_init_ex( Alloc alloc, Free free, Realloc realloc, IntPtr context);
public override IEnumerable <Bar> Run(DateTime?startTime, DateTime?endTime) { //========== initialization ========== #if USE_CLENOWS_RANGE // matching Clenow's charts StartTime = DateTime.Parse("01/01/1999", CultureInfo.InvariantCulture); WarmupStartTime = StartTime - TimeSpan.FromDays(180); EndTime = DateTime.Parse("12/31/2014", CultureInfo.InvariantCulture); #else WarmupStartTime = Globals.WARMUP_START_TIME; StartTime = Globals.START_TIME; EndTime = Globals.END_TIME; #endif Deposit(IsChildAlgorithm ? 0.0 : Globals.INITIAL_CAPITAL); CommissionPerShare = Globals.COMMISSION; // Clenow is not considering commissions var all = AddDataSources(UNIVERSE.Constituents); var sp500 = AddDataSource(SP500); var benchmark = AddDataSource(BENCHMARK); //========== simulation loop ========== double?sp500Initial = null; // loop through all bars foreach (DateTime simTime in SimTimes) { if (!HasInstrument(benchmark)) { continue; } sp500Initial = sp500Initial ?? sp500.Instrument.Open[0]; // calculate indicators exactly once per bar // we are doing this on all available instruments, // as we don't know when they will become S&P500 constituents var indicators = Instruments .ToDictionary( i => i, i => new { regression = i.Close.LogRegression(MOM_PERIOD), maxMove = i.Close.SimpleMomentum(1).AbsValue().Highest(MOM_PERIOD), avg100 = i.Close.SMA(INSTR_TREND), atr20 = i.AverageTrueRange(ATR_PERIOD), });; // index filter: only buy any shares, while S&P-500 is trading above its 200-day moving average // NOTE: the 10-day SMA on the benchmark is _not_ mentioned in // the book. We added it here, to compensate for the // simplified re-balancing schedule. bool allowNewEntries = sp500.Instrument.Close.SMA(INDEX_FLT)[0] > sp500.Instrument.Close.SMA(INDEX_TREND)[0]; // determine current S&P 500 constituents var constituents = Instruments .Where(i => i.IsConstituent(UNIVERSE)) .ToList(); // trade once per week // this is a slight simplification from Clenow's suggestion to adjust positions // every week, and adjust position sizes only every other week if (IsTradingDay) { // rank by volatility-adjusted momentum and pick top 20% (top-100) var topRankedInstruments = constituents // FIXME: how exactly are we multiplying the regression slope with R2? .OrderByDescending(i => (Math.Exp(252.0 * indicators[i].regression.Slope[0]) - 1.0) * indicators[i].regression.R2[0]) //.OrderByDescending(i => indicators[i].regression.Slope[0] * indicators[i].regression.R2[0]) .Take((int)Math.Round(TOP_PCNT / 100.0 * constituents.Count)) .ToList(); // disqualify // - trading below 100-day moving average // - maximum move > 15% // FIXME: is maxMove > 1.0??? var availableInstruments = topRankedInstruments .Where(i => i.Close[0] > indicators[i].avg100[0] && indicators[i].maxMove[0] < MAX_MOVE / 100.0) .ToList(); // allocate capital until we run out of cash var weights = Instruments .ToDictionary( i => i, i => 0.0); double availableCapital = 1.0; int portfolioRisk = 0; foreach (var i in availableInstruments) { // Clenow does not limit the total portfolio risk if (portfolioRisk > RISK_TOTAL) { continue; } var currentWeight = NetAssetValue[0] > 0 ? i.Position * i.Close[0] / NetAssetValue[0] : 0.0; var newWeight = Math.Min(Math.Min(availableCapital, MAX_PER_STOCK / 100.0), RISK_PER_STOCK * 0.0001 / indicators[i].atr20[0] * i.Close[0]); var w = allowNewEntries ? newWeight : Math.Min(currentWeight, newWeight); weights[i] = w; availableCapital -= w; portfolioRisk += RISK_PER_STOCK; } // perform customized money-management ManageWeights(weights); // submit trades Alloc.LastUpdate = SimTime[0]; Alloc.Allocation.Clear(); foreach (var i in Instruments) { if (weights[i] > 0.005) { Alloc.Allocation[i] = weights[i]; } var targetShares = (int)Math.Round(NetAssetValue[0] * weights[i] / i.Close[0]); i.Trade(targetShares - i.Position, OrderType.openNextBar); } if (!IsOptimizing && (EndTime - SimTime[0]).TotalDays < 30) { string message = constituents .Where(i => weights[i] != 0.0) .Aggregate(string.Format("{0:MM/dd/yyyy}: ", SimTime[0]), (prev, i) => prev + string.Format("{0}={1:P2} ", i.Symbol, weights[i])); Output.WriteLine(message); } } else // if (IsTradingDay) { Alloc.AdjustForPriceChanges(this); } // create charts if (!IsOptimizing && TradingDays > 0) { _plotter.AddNavAndBenchmark(this, benchmark.Instrument); _plotter.AddStrategyHoldings(this, constituents); // plot strategy exposure _plotter.SelectChart("Strategy Exposure", "Date"); _plotter.SetX(SimTime[0]); _plotter.Plot("Stock Exposure", constituents.Sum(i => i.Position * i.Close[0]) / NetAssetValue[0]); _plotter.Plot("Number of Stocks", constituents.Where(i => i.Position != 0).Count()); if (Alloc.LastUpdate == SimTime[0]) { _plotter.AddTargetAllocationRow(Alloc); } #if true _plotter.SelectChart("Clenow-style Chart", "Date"); _plotter.SetX(SimTime[0]); _plotter.Plot(Name, NetAssetValue[0] / Globals.INITIAL_CAPITAL); _plotter.Plot(sp500.Instrument.Name, sp500.Instrument.Close[0] / sp500Initial); _plotter.Plot(sp500.Instrument.Name + " 200-day moving average", sp500.Instrument.Close.SMA(200)[0] / sp500Initial); _plotter.Plot("Cash", Cash / NetAssetValue[0]); #endif } if (IsDataSource) { var v = 10.0 * NetAssetValue[0] / Globals.INITIAL_CAPITAL; yield return(Bar.NewOHLC( this.GetType().Name, SimTime[0], v, v, v, v, 0)); } } //========== post processing ========== if (!IsOptimizing) { _plotter.AddAverageHoldings(this); _plotter.AddTargetAllocation(Alloc); _plotter.AddOrderLog(this); _plotter.AddPositionLog(this); _plotter.AddPnLHoldTime(this); _plotter.AddMfeMae(this); _plotter.AddParameters(this); } FitnessValue = this.CalcFitness(); }