/// <summary> /// Allocates unmanaged memory. /// </summary> /// <param name="size">Number of bytes to allocate.</param> /// <param name="align">Allocation alignment in bytes.</param> /// <returns>Address of allocated memory.</returns> public static IntPtr Allocate(int size, int align) { // Lazily initialize container. if (Allocations == null) { Allocations = new List <AllocationItem>(); } // Allocate unaligned memory block. var unalignedAddress = Marshal.AllocHGlobal(size + align); // Get aligned address. var shift = (unalignedAddress.ToInt64() & (align - 1)); var alignedAddress = (shift != 0) ? new IntPtr(unalignedAddress.ToInt64() + align - shift) : unalignedAddress; // Register allocation. Allocations.Add(new AllocationItem { UnalignedAddress = unalignedAddress, AlignedAddress = alignedAddress }); // Return aligned address. return(alignedAddress); }
private bool GetNextFreeBlock(int size, out int offset) { if (size <= Size) { if (Allocations.Count == 0) { offset = 0; return(true); } else { for (int i = 0; i < Allocations.Count; ++i) { KeyValuePair <int, int> allocation = Allocations.ElementAt(i); int allocationEnd = allocation.Key + allocation.Value; // when there is a next element, used it as the limiter, if not use the // whole remaining space int memoryLeft = i + 1 < Allocations.Count ? Allocations.ElementAt(i + 1).Key - allocationEnd : Size - allocationEnd; if (memoryLeft >= size) { offset = allocationEnd; return(true); } } } } offset = 0; return(false); }
/// <summary> /// Frees unmanaged memory. /// </summary> /// <param name="allocation">Address of memory to deallocate.</param> public static void Deallocate(IntPtr allocation) { // Return early in case no allocations exist. if (!ContainsAllocations) { return; } // Free allocation. for (var i = 0; i < Allocations.Count; ++i) { if (Allocations[i].AlignedAddress != allocation) { continue; } Marshal.FreeHGlobal(Allocations[i].UnalignedAddress); Allocations.RemoveAt(i); break; } }
protected override async Task ModifyDraftForInsertAsync(JournalVoucherDTO draft) { TransactionDate = DateTime.Now; draft.Allocations = new List <AccountAllocation>(); Allocations.SetHost(draft.Allocations, AppArgs.MarketState.GLAccounts); draft.SerialNum = await AppArgs.Journals.GetNextSerialNum(); }
public void GenerateAllocations(List <CTFERecord> records) { Dictionary <string, int> types = new Dictionary <string, int>(); foreach (CTFERecord record in records) { BAllocation allocation = null; string type = record.Er.GetValue("_TypeName").ToString(); int index; if (!types.TryGetValue(type, out index)) { types[type] = index = types.Count; allocation = new BAllocation(); allocation.Type = type; Allocations.Add(allocation); } else { allocation = Allocations[index]; } allocation.Count++; ulong size = Convert.ToUInt64(record.Er.GetValue("_AllocationAmount64")); if (size == 0) { uint size32 = Convert.ToUInt32(record.Er.GetValue("_AllocationAmount")); allocation.Size += size32; } else { allocation.Size += size; } } }
public static bool PtrIsAllocated(IntPtr ptr) { lock (allocationsLock) { return(Allocations.Any(a => a == ptr)); } }
public override string ToString() { var sb = new StringBuilder(); sb.Append("Fitness: "); sb.AppendLine(Fitness.ToString()); sb.Append("Evaluated solutions: "); sb.AppendLine(EvaluatedSolutions.ToString()); for (int item = 0; item < numberOfItems; item++) { for (int day = 0; day < Allocations.GetLength(0); day++) { var shifts = new List <int>(); for (int slot = 0; slot < Allocations.GetLength(1); slot++) { if (Allocations[day, slot] == item) { shifts.Add(slot); } } sb.Append(shiftsToString(shifts)); if (day < Allocations.GetLength(0) - 1) { sb.Append(", "); } } sb.AppendLine(); } return(sb.ToString()); }
public string Solve(string url) { var filename = url.Substring(url.LastIndexOf('/') + 1); // everything after the last "/" is the filename using (var configurationWebClient = new WebClient( )) using (var configurationStream = configurationWebClient.OpenRead(url)) using (var configurationFile = new StreamReader(configurationStream)) { Configuration.TryParse(configurationFile, filename, out AT1Configuration, out var configurationErrors); } var cutoffTime = AT1Configuration.MaximumProgramDuration; // the max time a solution must take var bestAllocations = BestFirstSearch(cutoffTime); AT1Allocations = new Allocations(AT1Configuration); // convert List<Allocation> into Allocations object AT1Allocations.AddRange(bestAllocations); var taff = AT1Allocations.ToTaffString( AT1Configuration); // need to save as taff and back to Allocations to make some functions work Allocations.TryParse(taff, AT1Configuration, out AT1Allocations, out var errors2); return(taff); }
/// <summary> /// Called when the user clicks the Delete button. This will remove the /// given version (<seealso cref="SplitTrafficModel.VersionId"/>>) from the list of /// <seealso cref="Allocations"/> and adds the version to the the list /// of <seealso cref="_availableVersions"/>. /// </summary> private void OnDeleteCommand() { var selected = SelectedSplit; Allocations.Remove(selected); _availableVersions.Add(selected.VersionId); // Update the visual state. UpdateCommands(); }
/// <summary> /// Try to reserve a memory block in the pool /// </summary> /// <param name="size">Size of the wanted block</param> /// <param name="address">Address of the memory allocation</param> /// <returns>True when a block could be reserved, false if not</returns> public bool Reserve(int size, out IntPtr address) { if (GetNextFreeBlock(size, out int offset)) { Allocations.Add(offset, size); address = IntPtr.Add(Address, offset); return(true); } address = IntPtr.Zero; return(false); }
internal string GetFund(Transaction trade) { // Where(i => i.ParentOrderId == element.ParentOrderId).ToList(); var tradeAllocations = Allocations.Where(i => i.LpOrderId == trade.LpOrderId).ToList(); if (tradeAllocations.Count() > 0) { return(tradeAllocations[0].Fund); } return("Unknown"); }
public void EnumGetHashCodeInvocation() { var e = GetHashCode() % 2 == 0 ? ConsoleKey.Clear : ConsoleKey.Add; #if NETFRAMEWORK Allocations.AssertAllocates(() => e.GetHashCode()); Allocations.AssertAllocates(() => e.ToString()); Allocations.AssertAllocates(() => e.Equals(null)); #else Allocations.AssertNoAllocations(() => e.GetHashCode()); // optimized by runtime Allocations.AssertAllocates(() => e.ToString()); Allocations.AssertAllocates(() => e.Equals(null)); #endif }
public static Allocation ModelToDomain(Allocations model) { return(new Allocation { AllocationId = model.AllocationId, OrderId = model.OrderId, SecurityId = model.SecurityId, SecurityDesc = model.SecurityDesc, SecurityCcy = model.SecurityCcy, PortfolioCode = model.PortfolioCode, Quantity = model.Quantity, Price = model.Price, GamFundCode = model.GamFundCode }); }
private void generateAllocationsButton_Click(object sender, EventArgs e) { String CFFFileName = urlComboBox.Text; ClearGUI(); allocationsList = new List <string>(); totalcalls = 0; // Process allocations and configuration files. if (File.Exists(CFFFileName) || Uri.IsWellFormedUriString(CFFFileName, UriKind.Absolute)) { // Get both filenames. // Parse configuration file. using (WebClient configurationWebClient = new WebClient()) using (Stream configurationStream = configurationWebClient.OpenRead(CFFFileName)) using (StreamReader configurationFile = new StreamReader(configurationStream)) { Configuration.TryParse(configurationFile, CFFFileName, out AT1Configuration, out List <String> configurationErrors); } //This to to test for WCFlocal\\ LocalWCF.ServiceClient localwcf = new LocalWCF.ServiceClient(); /*allocationsList.Add(localwcf.GetData(AT1Configuration.FilePath));*/ // Remote wcf has been commented above. System.Threading.Tasks.Task.Run(() => Callremotewcf(AT1Configuration)); autoResetEvent.WaitOne(); //string allocation = FindOptimalAllocation(); if (allocationsList.Count() > 0) { foreach (var item in allocationsList) { Allocations.TryParse(item, AT1Configuration, out AT1Allocations, out List <String> errors); Console.WriteLine(item); } // Refesh GUI and Log errors. UpdateGUI(); AT1Allocations.LogFileErrors(AT1Allocations.FileErrorsTXT); AT1Allocations.LogFileErrors(AT1Configuration.FileErrorsTXT); } } }
public static global::System.IntPtr Malloc(ulong size, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0) { CallerInformation caller = new CallerInformation(memberName, fileName, lineNumber); IntPtr __ret = __Internal.JeMalloc(size); if (__ret != IntPtr.Zero) { Allocations.Add(__ret); //AllocationsDetails.Add(new Tuple<IntPtr, ulong, CallerInformation>(__ret, size, caller)); return(__ret); } else { throw new OutOfMemoryException($"Could not allocate {size} bytes for {GetCallerDetails(caller)}."); } }
public List <Allocations> GetAllAllocations(SearchFilters allocationsFilterData) { sqlhelper_obj = new SqlHelper(); List <Allocations> allocations_List = new List <Allocations>(); try { using (SqlConnection sqlconn_obj = new SqlConnection()) { sqlconn_obj.ConnectionString = sqlhelper_obj.GetConnectionSrting(); using (SqlCommand sqlcmd_details_obj = new SqlCommand("PARK_PROC_GetAllAllocations", sqlconn_obj)) { sqlcmd_details_obj.CommandType = CommandType.StoredProcedure; sqlcmd_details_obj.CommandTimeout = 0; sqlcmd_details_obj.Parameters.AddWithValue("@Company", allocationsFilterData.Company); sqlcmd_details_obj.Parameters.AddWithValue("@Location", allocationsFilterData.LocationID); sqlcmd_details_obj.Parameters.AddWithValue("@ParkingLot", allocationsFilterData.LocationParkingLotID); DataSet ds; using (SqlDataAdapter sql_dp = new SqlDataAdapter(sqlcmd_details_obj)) { ds = new DataSet(); sql_dp.Fill(ds); } DataTable dt_location = ds.Tables[0]; for (int i = 0; i < dt_location.Rows.Count; i++) { Allocations allocations_obj = new Allocations(); allocations_obj.EmpId = Convert.ToString(dt_location.Rows[i]["EmpID"]); allocations_obj.EmpName = Convert.ToString(dt_location.Rows[i]["EmpName"]); allocations_obj.Role = Convert.ToString(dt_location.Rows[i]["Role"]); allocations_obj.ReportsTo = Convert.ToString(dt_location.Rows[i]["ReportsTo"]); allocations_obj.Station = Convert.ToString(dt_location.Rows[i]["Station"]); allocations_obj.ParkingLot = Convert.ToString(dt_location.Rows[i]["ParkingLot"]); allocations_obj.LoginTime = Convert.ToString(dt_location.Rows[i]["LoginTime"]); allocations_List.Add(allocations_obj); } } } return(allocations_List); } catch (Exception ex) { throw ex; } }
public bool AllocationsFromString(string allocString) { try { string[] allocations = allocString.Split(','); foreach (string s in allocations) { string[] accountAndValue = s.Split('/'); Allocations.Add(new Allocation(accountAndValue[0], double.Parse(accountAndValue[1]))); } return(true); } catch (Exception) { return(false); } }
public void NullableEnumGetHashCodeInvocation() { ConsoleKey?e = GetHashCode() % 2 == 0 ? ConsoleKey.Clear : ConsoleKey.Add; object boxedComparand = ConsoleKey.Clear; #if NETFRAMEWORK Allocations.AssertAllocates(() => e.GetHashCode()); Allocations.AssertAllocates(() => e.ToString()); Allocations.AssertNoAllocations(() => e.Equals(null)); // shortcut Allocations.AssertAllocates(() => e.Equals(boxedComparand)); #else Allocations.AssertNoAllocations(() => e.GetHashCode()); // optimized by runtime Allocations.AssertAllocates(() => e.ToString()); Allocations.AssertNoAllocations(() => e.Equals(null)); // shortcut Allocations.AssertAllocates(() => e.Equals(boxedComparand)); #endif }
private string GetAccountNames(Func <AccountAllocation, bool> filter) { if (Allocations == null) { return(string.Empty); } if (!Allocations.Any()) { return(string.Empty); } var matches = Allocations.Where(filter); if (!matches.Any()) { return(string.Empty); } return(string.Join(L.f, matches.Select(_ => _.Account?.Name))); }
// Convert allocations to TAFF string public static string ToTaffString(this Allocations allocations, Configuration config) { var builder = new StringBuilder( ); builder.AppendLine($"CONFIG-FILE=\"{config.FilePath}\""); builder.AppendLine( ); builder.AppendLine( $"ALLOCATIONS-DATA={allocations.Count},{config.NumberOfTasks},{config.NumberOfProcessors}"); builder.AppendLine( ); foreach (var allocation in allocations) { builder.AppendLine(allocation.ToTaffString( )); builder.AppendLine( ); } return(builder.ToString( )); }
/// <summary> /// Free a memory block in the pool /// </summary> /// <param name="address">Allocation address</param> /// <returns>True, when the block has been found and freed, false if not</returns> public bool Free(IntPtr address, out int size) { int addressInt = address.ToInt32(); int baseAddressInt = Address.ToInt32(); if (addressInt >= baseAddressInt && addressInt < baseAddressInt + Size) { int relAddress = addressInt - baseAddressInt; size = Allocations[relAddress]; Allocations.Remove(relAddress); return(true); } size = 0; return(false); }
private void OnAddTrafficAllocationCommand() { var result = AddTrafficSplitWindow.PromptUser(_availableVersions); if (result != null) { var allocation = new SplitTrafficModel( versionId: result.Version, trafficAllocation: result.Allocation); // Remove the allocation from the list of available allocations to in future invocations the // user can only select the available ones. _availableVersions.Remove(allocation.VersionId); // Add the allocation to the list. Allocations.Add(allocation); // Update the visual state. UpdateCommands(); } }
private void OpenAllocationsFileToolStripMenuItem_Click(object sender, EventArgs e) { ClearGUI( ); // Process allocations and configuration files. if (openFileDialog1.ShowDialog( ) == DialogResult.OK) { // Get both filenames. var allocationsFileName = openFileDialog1.FileName; var configurationFileName = Allocations.ConfigurationFileName(allocationsFileName); // Parse configuration file. if (configurationFileName == null) { AT1Configuration = new Configuration( ); } else { using (var configurationWebClient = new WebClient( )) using (var configurationStream = configurationWebClient.OpenRead(configurationFileName)) using (var configurationFile = new StreamReader(configurationStream)) { Configuration.TryParse(configurationFile, configurationFileName, out AT1Configuration, out var configurationErrors); } } // Parse Allocations file. using (var allocationsFile = new StreamReader(allocationsFileName)) { Allocations.TryParse(allocationsFile, allocationsFileName, AT1Configuration, out AT1Allocations, out var allocationsErrors); } // Refesh GUI and Log errors. UpdateGUI( ); AT1Allocations.LogFileErrors(AT1Allocations.FileErrorsTXT); AT1Allocations.LogFileErrors(AT1Configuration.FileErrorsTXT); } }
public static bool Free(global::System.IntPtr ptr, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0) { bool ret = false; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (Allocations.TryTake(out ptr)) { __Internal.JeFree(ptr); ret = true; } else { ret = false; } } return(ret); }
public override int GetHashCode() => 31 *Allocations.GetHashCode() + Evictions.GetHashCode() + Idle.GetHashCode();
public void StructVirtualMethodWithoutOverride() { var st = new NoGetHashCodeOverride(); Allocations.AssertAllocates(() => st.GetHashCode()); }
public void RecordStructGetHashCodeInvocation() { var st = new RecordStruct(); Allocations.AssertNoAllocations(() => st.GetHashCode()); }
public void StructBaseGetHashCodeInvocation() { var st = new WithBaseGetHashCodeInvocation(); Allocations.AssertAllocates(() => st.GetHashCode()); }
public void NullableStructVirtualMethodWithOverride() { WithGetHashCodeOverride?st = new WithGetHashCodeOverride(); Allocations.AssertNoAllocations(() => st.GetHashCode()); }
/// <summary> /// Prüft, ob eine Aufzeichnung ergänzt werden kann. /// </summary> /// <param name="recording">Die neue Aufzeichnung.</param> /// <param name="time">Der Zeitraum der neuen Aufzeichnung.</param> /// <param name="minTime">Die Aufzeichnung darf auf keinen Fall vor diesem Zeitpunkt beginnen.</param> /// <returns>Gesetzt, wenn eine Aufzeichnung möglich war.</returns> /// <exception cref="ArgumentNullException">Es wurde keine Aufzeichnung übergeben.</exception> /// <exception cref="ArgumentOutOfRangeException">Die Startzeit liegt vor der Aktivierung des Gerätes.</exception> public bool Add(IRecordingDefinition recording, SuggestedPlannedTime time, DateTime minTime) { // Validate if (recording == null) { throw new ArgumentNullException("recording"); } // If the current resource can see the source we can do nothing at all var resource = Resource; if (!resource.CanAccess(recording.Source)) { return(false); } // If the recording is bound to dedicated sources but not use we should not process var allowedResources = recording.Resources; if (allowedResources != null) { if (allowedResources.Length > 0) { if (!allowedResources.Any(r => ReferenceEquals(r, resource))) { return(false); } } } // See if we have to cut it off and load the corresponding end of the recording var initialPlan = time.Planned; // Clip to minimum allowed if (time.Planned.Start < minTime) { // Not possible at all - should never ever be requested but better be safe if (time.Planned.End <= minTime) { return(false); } // Correct the parameters - end is calculated from start and duration time.Planned.Duration = time.Planned.End - minTime; time.Planned.Start = minTime; } // See if device could at least receive var sourceAllocation = Allocations.PrepareAllocation(recording.Source, time); if (sourceAllocation == null) { return(false); } // Add it - will clip the time accordingly sourceAllocation.Allocate(); // Time to check for encryption - technically it should not be possible to have a recording on a source which is for some time encypted and for some other time not but better be safe if (recording.Source.IsEncrypted) { // What to check for var counters = DecryptionCounters.Select(i => SchedulePlan.DecryptionCounters[i]).ToArray(); // Check all foreach (var counter in counters) { if (counter.PrepareAllocation(recording.Source, time) == null) { return(false); } } // Now reserve all - this may manipulate the time slice for the recording as well foreach (var counter in counters) { // Allocate again - we may only call the allocate immediatly after preparing var allocation = counter.PrepareAllocation(recording.Source, time); if (allocation == null) { throw new InvalidOperationException("PrepareAllocation"); } // Process allocation.Allocate(); } } // Remember recording m_Recordings.Add(new _RecordingItem(recording, time.Planned, time.Planned.Start > initialPlan.Start)); // Get cut time var delta = initialPlan.Duration - time.Planned.Duration; // Adjust cut time - this will be taken in account when checking weights to get the best plan TotalCut += delta; // Count failures if (delta.Ticks > 0) { CutRecordings += 1; } // We did it return(true); }