Here are the examples of the csharp api System.Math.Ceiling(decimal) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
127 Examples
19
Source : IBssMapKeyResolverProviderTest.cs
with MIT License
from 1996v
with MIT License
from 1996v
private static ulong[] ConvertULong(byte[] bin)
{
int ul = (int)Math.Ceiling((decimal)bin.Length / 8);
ulong[] u = new ulong[ul];
Unsafe.CopyBlock(ref Unsafe.As<ulong, byte>(ref u[0]), ref bin[0], (uint)bin.Length);
for (int i = 0; i < u.Length; i++)
{
u[i] = BssomBinaryPrimitives.ReadUInt64LittleEndian(ref Unsafe.As<ulong, byte>(ref u[i]));
}
return u;
}
19
Source : IBssMapKeyResolverProviderTest.cs
with MIT License
from 1996v
with MIT License
from 1996v
private static ulong[] ConvertRaw(byte[] bin)
{
int ul = (int)Math.Ceiling((decimal)bin.Length / 8);
ulong[] u = new ulong[ul];
Unsafe.CopyBlock(ref Unsafe.As<ulong, byte>(ref u[0]), ref bin[0], (uint)bin.Length);
return u;
}
19
Source : SeatCollectionExtensions.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
internal static int CentroidIndex(this int rowSize)
{
return (int) Math.Ceiling((decimal) rowSize / 2);
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long UpdateTest(int count)
{
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Employee emp = new Employee()
{
EmployeeId = i,
EmployeeName = "Update Employee " + i,
Location = "Location " + i,
Department = "Department " + i,
Designation = "Designation " + i,
DOB = new DateTime(1978, (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 12m), (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 25m)),
CTC = i * 1000m
};
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = @"UPDATE Employee SET EmployeeName=@EmployeeName,
Location=@Location, Department=@Department,
Designation=@Designation, DOB=@DOB, CTC=@CTC
WHERE EmployeeId=@EmployeeId";
cmd.Parameters.AddWithValue("EmployeeId", emp.EmployeeId);
cmd.Parameters.AddWithValue("EmployeeName", emp.EmployeeName);
cmd.Parameters.AddWithValue("Location", emp.Location);
cmd.Parameters.AddWithValue("Department", emp.Department);
cmd.Parameters.AddWithValue("Designation", emp.Designation);
cmd.Parameters.AddWithValue("DOB", emp.DOB);
cmd.Parameters.AddWithValue("CTC", emp.CTC);
cmd.ExecuteNonQuery();
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long UpdateTest(int count)
{
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Employee emp = new Employee()
{
EmployeeId = i,
EmployeeName = "Update Employee " + i,
Location = "Location " + i,
Department = "Department " + i,
Designation = "Designation " + i,
DOB = new DateTime(1978, (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 12m), (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 25m)),
CTC = i * 1000m
};
Repository<Employee> repository = new Repository<Employee>(con);
repository.Update(emp);
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long InsertTest(int count)
{
PerformanceTest.TruncateTable();
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Employee emp = new Employee()
{
EmployeeId = i,
EmployeeName = "Employee " + i,
Location = "Location " + i,
Department = "Department " + i,
Designation = "Designation " + i,
DOB = new DateTime(1978, (int)Math.Ceiling(( Convert.ToDecimal(i) / Convert.ToDecimal(count))*12m), (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 25m)),
CTC = i * 1000m
};
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = @"INSERT INTO Employee (EmployeeId, EmployeeName, Location, Department, Designation, DOB, CTC)
VALUES(@EmployeeId, @EmployeeName, @Location, @Department, @Designation, @DOB, @CTC)";
cmd.Parameters.AddWithValue("EmployeeId", emp.EmployeeId);
cmd.Parameters.AddWithValue("EmployeeName", emp.EmployeeName);
cmd.Parameters.AddWithValue("Location", emp.Location);
cmd.Parameters.AddWithValue("Department", emp.Department);
cmd.Parameters.AddWithValue("Designation", emp.Designation);
cmd.Parameters.AddWithValue("DOB", emp.DOB);
cmd.Parameters.AddWithValue("CTC", emp.CTC);
cmd.ExecuteNonQuery();
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long UpdateTest(int count)
{
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Employee emp = new Employee()
{
EmployeeId = i,
EmployeeName = "Update Employee " + i,
Location = "Location " + i,
Department = "Department " + i,
Designation = "Designation " + i,
DOB = new DateTime(1978, (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 12m), (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 25m)),
CTC = i * 1000m
};
con.Execute(@"UPDATE Employee SET EmployeeName = @EmployeeName,
Location = @Location, Department = @Department,
Designation = @Designation, DOB = @DOB, CTC = @CTC
WHERE EmployeeId = @EmployeeId", emp);
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long InsertTest(int count)
{
PerformanceTest.TruncateTable();
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Employee emp = new Employee()
{
EmployeeId = i,
EmployeeName = "Employee " + i,
Location = "Location " + i,
Department = "Department " + i,
Designation = "Designation " + i,
DOB = new DateTime(1978, (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 12m), (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 25m)),
CTC = i * 1000m
};
Repository<Employee> repository = new Repository<Employee>(con);
repository.Add(emp);
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long InsertTest(int count)
{
PerformanceTest.TruncateTable();
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Employee emp = new Employee()
{
EmployeeId = i,
EmployeeName = "Employee " + i,
Location = "Location " + i,
Department = "Department " + i,
Designation = "Designation " + i,
DOB = new DateTime(1978, (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 12m), (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 25m)),
CTC = i * 1000m
};
con.Execute(@"INSERT Employee(EmployeeId, EmployeeName, Location, Department, Designation, DOB, CTC)
VALUES(@EmployeeId, @EmployeeName, @Location, @Department, @Designation, @DOB, @CTC)", emp);
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : MathFilters.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static int Ceil(object value)
{
return value == null
? 0
: Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(value)));
}
19
Source : RoundingSettings.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public decimal Round(decimal value)
{
var isNegative = (RoundingConventionMethod != null && RoundingConventionMethod != RoundingConvention.Normal) && value < 0;
if (RoundingConventionMethod != null && isNegative)
value = Math.Abs(value); // its very importend to have a positive number when using floor/Ceiling
switch (RoundingConventionMethod)
{
case null:
case RoundingConvention.Normal:
value = Math.Round(value, this.RowDecimalRoundTotal);
break;
case RoundingConvention.RoundUpp:
{
var adjustment = (decimal)Math.Pow(10, RowDecimalRoundTotal);
value = (Math.Ceiling(value * adjustment) / adjustment);
}
break;
case RoundingConvention.RoundDown:
{
var adjustment = (decimal)Math.Pow(10, RowDecimalRoundTotal);
value = (Math.Floor(value * adjustment) / adjustment);
}
break;
case RoundingConvention.None:
{
var adjustment = (decimal)Math.Pow(10, RowDecimalRoundTotal);
value = (Math.Truncate(value * adjustment) / adjustment);
}
break;
}
if (isNegative)
value = -value;
return value;
}
19
Source : TorrentInfo.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
public int GetBlockCount(int pieceIndex)
{
pieceIndex.MustBeGreaterThanOrEqualTo(0);
pieceIndex.MustBeLessThan(this.PiecesCount);
return (int)Math.Ceiling((decimal)this.GetPieceLength(pieceIndex) / (decimal)this.BlockLength);
}
19
Source : DecimalExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static decimal Ceiling(this decimal d)
{
return Math.Ceiling(d);
}
19
Source : BlazorGrid.razor.g.cs
with MIT License
from AnkitSharma-007
with MIT License
from AnkitSharma-007
protected override async Task OnInitAsync()
{
pagerSize = 5;
curPage = 1;
ItemList = Items.Skip((curPage - 1) * PageSize).Take(PageSize);
totalPages = (int)Math.Ceiling(Items.Count() / (decimal)PageSize);
SetPagerSize("forward");
}
19
Source : BlazorGrid.g.i.cs
with MIT License
from AnkitSharma-007
with MIT License
from AnkitSharma-007
protected override async Task OnInitAsync()
{
pagerSize = 5;
curPage = 1;
ItemList = Items.Skip((curPage - 1) * PageSize).Take(PageSize);
totalPages = (int)Math.Ceiling(Items.Count() / (decimal)PageSize);
SetPagerSize("forward");
}
19
Source : MathImplementation.cs
with MIT License
from apexsharp
with MIT License
from apexsharp
public decimal ceil(decimal decimalValue) => Ceiling(decimalValue);
19
Source : TimeHelper.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public static int SecondToMinute(int Second)
{
decimal mm = (decimal)((decimal)Second / (decimal)60);
return Convert.ToInt32(Math.Ceiling(mm));
}
19
Source : LinuxMachineInfo.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public ComputerInfo GetDiskSize()
{
ComputerInfo computer=null;
try
{
computer = new ComputerInfo();
var diskcon = Directory.GetLogicalDrives();
long total = 0;
long free = 0;
foreach (string diskname in diskcon)
{
try
{
DriveInfo di = new DriveInfo(diskname);
if (di.IsReady)
{
total += di.TotalSize;
free += di.AvailableFreeSpace;
computer.DiskCount++;
}
}
catch
{
}
}
computer.DiskCount = diskcon.Length;
computer.RAMTotal = CommHelper.ToGB(total, 1000);
computer.RAMFree = CommHelper.ToGB(free, 1000);
computer.RAMUsed = CommHelper.ToGB(total - free, 1000);
computer.UsedRate = (100 - Math.Ceiling((decimal)free * 100 / total)).ToString() + "%";
}catch(Exception ex)
{
LoggerHelper.Exception(ex);
}
return computer;
}
19
Source : WindowsMachineInfo.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public ComputerInfo GetDiskSize()
{
ComputerInfo computer;
try
{
computer = new ComputerInfo();
var diskcon = Directory.GetLogicalDrives();
long total = 0;
long free = 0;
foreach (string diskname in diskcon)
{
try
{
DriveInfo di = new DriveInfo(diskname);
if (di.IsReady)
{
total += di.TotalSize;
free += di.AvailableFreeSpace;
computer.DiskCount++;
}
}
catch
{
}
}
computer.RAMTotal = CommHelper.ToGB(total, 1000);
computer.RAMFree =CommHelper.ToGB(free, 1000);
computer.RAMUsed = CommHelper.ToGB(total-free, 1000);
computer.UsedRate = (100 - Math.Ceiling((decimal)free * 100 / total)).ToString()+"%";
}
finally
{
}
return computer;
}
19
Source : Startup.cs
with MIT License
from ArchaicQuest
with MIT License
from ArchaicQuest
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IDataBase db, ICache cache)
{
if (env.EnvironmentName == "dev")
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Play/Error");
}
_db = db;
_cache = cache;
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseCors("client");
app.UseMiddleware<JwtMiddleware>();
// Forward headers for Ngnix
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<GameHub>("/Hubs/game");
});
_hubContext = app.ApplicationServices.GetService<IHubContext<GameHub>>();
app.StartLoops();
var watch = System.Diagnostics.Stopwatch.StartNew();
var rooms = _db.GetList<Room>(DataBase.Collections.Room);
foreach (var room in rooms)
{
AddSkillsToMobs(room);
MapMobRoomId(room);
_cache.AddRoom($"{room.AreaId}{room.Coords.X}{room.Coords.Y}{room.Coords.Z}", room);
_cache.AddOriginalRoom($"{room.AreaId}{room.Coords.X}{room.Coords.Y}{room.Coords.Z}", JsonConvert.DeserializeObject<Room>(JsonConvert.SerializeObject(room)));
}
if (!_db.DoesCollectionExist(DataBase.Collections.Alignment))
{
foreach (var data in new Alignment().SeedData())
{
_db.Save(data, DataBase.Collections.Alignment);
}
}
if (!_db.DoesCollectionExist(DataBase.Collections.Skill))
{
foreach (var data in new SeedCoreSkills().SeedData())
{
_db.Save(data, DataBase.Collections.Skill);
}
}
else
{
var currentSkills = _db.GetList<Skill>(DataBase.Collections.Skill);
foreach (var data in new SeedCoreSkills().SeedData())
{
if (currentSkills.FirstOrDefault(x => x.Name == data.Name) == null)
{
_db.Save(data, DataBase.Collections.Skill);
}
}
}
if (!_db.DoesCollectionExist(DataBase.Collections.AttackType))
{
foreach (var data in new AttackTypes().SeedData())
{
_db.Save(data, DataBase.Collections.AttackType);
}
}
if (!_db.DoesCollectionExist(DataBase.Collections.Race))
{
foreach (var data in new Race().SeedData())
{
_db.Save(data, DataBase.Collections.Race);
}
}
if (!_db.DoesCollectionExist(DataBase.Collections.Status))
{
foreach (var data in new CharacterStatus().SeedData())
{
_db.Save(data, DataBase.Collections.Status);
}
}
if (!_db.DoesCollectionExist(DataBase.Collections.Clreplaced))
{
foreach (var data in new Clreplaced().SeedData())
{
_db.Save(data, DataBase.Collections.Clreplaced);
}
}
var clreplacedes = _db.GetList<Clreplaced>(DataBase.Collections.Clreplaced);
foreach (var pcClreplaced in clreplacedes)
{
_cache.AddClreplaced(pcClreplaced.Name, pcClreplaced);
}
if (!_db.DoesCollectionExist(DataBase.Collections.Config))
{
_db.Save(new Config(), DataBase.Collections.Config);
}
var config = _db.GetById<Config>(1, DataBase.Collections.Config);
_cache.SetConfig(config);
//add skills
var skills = _db.GetList<Skill>(DataBase.Collections.Skill);
foreach (var skill in skills)
{
_cache.AddSkill(skill.Id, skill);
}
var quests = _db.GetList<Quest>(DataBase.Collections.Quests);
foreach (var quest in quests)
{
_cache.AddQuest(quest.Id, quest);
}
var areas = _db.GetList<Area>(DataBase.Collections.Area);
//foreach (var area in areas)
//{
// var roomList = rooms.FindAll(x => x.AreaId == area.Id);
// _cache.AddMap(area.Id, Map.DrawMap(roomList));
//}
foreach (var area in areas)
{
var roomList = rooms.FindAll(x => x.AreaId == area.Id);
var areaByZIndex = roomList.FindAll(x => x.Coords.Z != 0).Distinct();
foreach (var zarea in areaByZIndex)
{
var roomsByZ = new List<Room>();
foreach (var room in roomList.FindAll(x => x.Coords.Z == zarea.Coords.Z))
{
roomsByZ.Add(room);
}
_cache.AddMap($"{area.Id}{zarea.Coords.Z}", Map.DrawMap(roomsByZ));
}
var rooms0index = roomList.FindAll(x => x.Coords.Z == 0);
_cache.AddMap($"{area.Id}0", Map.DrawMap(rooms0index));
}
var socials = new SocialSeedData().SeedData();
foreach (var social in socials)
{
_cache.AddSocial(social.Key, social.Value);
}
if (!_db.DoesCollectionExist(DataBase.Collections.Socials))
{
foreach (var social in socials)
{
_db.Save(social, DataBase.Collections.Socials);
}
}
if (!_db.DoesCollectionExist(DataBase.Collections.Items)) {
foreach (var itemSeed in new ItemSeed().SeedData())
{
_db.Save(itemSeed, DataBase.Collections.Items);
}
}
else
{
var hasMoney = _db.GetList<Item>(DataBase.Collections.Items)
.FirstOrDefault(x => x.ItemType == Item.ItemTypes.Money);
if (hasMoney == null)
{
foreach (var itemSeed in new ItemSeed().SeedData())
{
_db.Save(itemSeed, DataBase.Collections.Items);
}
}
}
if (!_db.DoesCollectionExist(DataBase.Collections.Help))
{
foreach (var seed in new HelpSeed().SeedData())
{
_db.Save(seed, DataBase.Collections.Help);
}
}
else
{
var helpList = _db.GetList<Help>(DataBase.Collections.Help);
foreach (var seed in new HelpSeed().SeedData())
{
if (helpList.FirstOrDefault(x => x.replacedle.Equals(seed.replacedle)) != null)
{
continue;
}
_db.Save(seed, DataBase.Collections.Help);
}
}
var helpFiles = _db.GetList<Help>(DataBase.Collections.Help);
foreach (var helpFile in helpFiles)
{
_cache.AddHelp(helpFile.Id, helpFile);
}
var craftingRecipes = _db.GetList<CraftingRecipes>(DataBase.Collections.CraftingRecipes);
foreach (var craftingRecipe in craftingRecipes)
{
_cache.AddCraftingRecipes(craftingRecipe.Id, craftingRecipe);
}
if (!_db.DoesCollectionExist(DataBase.Collections.Users))
{
var admin = new AdminUser() {Username = "Admin", Preplacedword = "admin", Role = "Admin", CanEdit = true, CanDelete = true};
_db.Save(admin, DataBase.Collections.Users);
}
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine($"Start up completed in {elapsedMs}");
GameLogic.Core.Helpers.PostToDiscord($"Start up completed in {Math.Ceiling((decimal)elapsedMs / 1000)} seconds", "event", _cache.GetConfig());
}
19
Source : eliteSlider.cs
with MIT License
from arqueror
with MIT License
from arqueror
private void eliteSliderTouched(object eventSender, SKTouchEventArgs eventArgs)
{
switch (eventArgs.ActionType)
{
case SKTouchAction.Pressed:
{
float givenDistance = SKPoint.Distance(this.sliderThumbPoint, eventArgs.Location);
if (givenDistance <= this.sliderThumbSize)
{
this.sliderThumbPointCanMove = true;
this.sliderThumbSizeUpdated = this.sliderThumbSize + 8;
this.InvalidateSurface();
}
}
break;
case SKTouchAction.Released:
{
if (this.sliderThumbPointCanMove)
{
this.sliderThumbSizeUpdated = this.sliderThumbSize;
this.InvalidateSurface();
}
this.sliderThumbPointCanMove = false;
}
break;
case SKTouchAction.Moved:
{
if (this.sliderThumbPointCanMove)
{
if (eventArgs.Location.X <= this.sliderThumbSize
|| eventArgs.Location.X >= this.canvasWidth - this.sliderThumbSize)
return;
int thumbOffset = (int)(eventArgs.Location.X - this.sliderThumbSize - 10);
int barWidth = this.sliderBarWidth - this.sliderThumbSize - 10;
decimal onePixelInPercent = 100m / barWidth;
decimal pixelInPercent = onePixelInPercent * thumbOffset;
decimal sliderPercent = Math.Ceiling(pixelInPercent);
this.OnValueChanged((int)sliderPercent);
this.sliderThumbPointUpdated = new SKPoint(eventArgs.Location.X, this.sliderThumbPoint.Y);
this.sliderThumbPointHasUpdated = true;
this.InvalidateSurface();
}
}
break;
}
eventArgs.Handled = true;
}
19
Source : Utility.cs
with MIT License
from Ashesh3
with MIT License
from Ashesh3
public static string CutFilePath(string path, int maxLength)
{
if (string.IsNullOrEmpty(path))
return "/null";
if (maxLength < 10)
return path;
var fileName = Path.GetFileNameWithoutExtension(path);
var fileExt = Path.GetExtension(path);
var fileDir = Path.GetDirectoryName(path);
var _maxLen = maxLength - fileExt.Count() - 6;
var _maxDirLen = (fileDir.Length > 4) ? (int)Math.Ceiling(_maxLen - (_maxLen * 0.35)) : fileDir.Length;
var _maxFileLen = (fileName.Length > 3) ? _maxLen - _maxDirLen : fileName.Length;
var _isDirOk = _maxDirLen + 3 < fileDir.Length;
var _isFileOk = _maxFileLen + 3 < fileName.Length;
var _dirPart1 = (_isDirOk) ? new string(fileDir.Take((int)Math.Ceiling(_maxDirLen / 2m)).ToArray()) : fileDir;
var _dirPart2 = (_isDirOk) ? new string(fileDir.Reverse().Take((int)Math.Ceiling(_maxDirLen / 2m)).Reverse().ToArray()) : "";
var _filePart1 = (_isFileOk) ? new string(fileName.Take((int)Math.Ceiling(_maxFileLen / 2m)).ToArray()) : fileName;
var _filePart2 = (_isFileOk) ? new string(fileName.Reverse().Take((int)Math.Ceiling(_maxFileLen / 2m)).Reverse().ToArray()) : "";
var _dir = (_isDirOk) ? $"{_dirPart1}...{_dirPart2}" : _dirPart1;
var _file = $"{((_isFileOk) ? $"{_filePart1}...{_filePart2}" : _filePart1)}{fileExt}";
return Path.Combine(_dir, _file);
}
19
Source : ImageLoader.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik
with BSD 3-Clause "New" or "Revised" License
from b4rtik
private static byte[] GetPayloadFromImage(Stream imgfile, int payloadlength)
{
Bitmap g = new Bitmap(imgfile);
int width = g.Size.Width;
int rows = (int)Math.Ceiling((decimal)payloadlength / width);
int array = (rows * width);
byte[] o = new byte[array];
int lrows = rows;
int lwidth = width;
int lpayload = payloadlength;
for (int i = 0; i < lrows; i++)
{
for (int x = 0; x < lwidth; x++)
{
Color pcolor = g.GetPixel(x, i);
o[i * width + x] = (byte)(Math.Floor((decimal)(((pcolor.B & 15) * 16) | (pcolor.G & 15))));
}
}
//o contain payload
byte[] otrue = new byte[lpayload];
Array.Copy(o, otrue, lpayload);
return otrue;
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik
with BSD 3-Clause "New" or "Revised" License
from b4rtik
private static void Executereplacedembly(string imgfile, int payloadlength)
{
Bitmap g = new Bitmap(imgfile);
int width = g.Size.Width;
int rows = (int)Math.Ceiling((decimal)payloadlength / width);
int array = (rows * width);
byte[] o = new byte[array];
int lrows = rows;
int lwidth = width;
int lpayload = payloadlength;
for (int i = 0; i < lrows; i++)
{
for (int x = 0; x < lwidth; x++)
{
Color pcolor = g.GetPixel(x, i);
o[i * width + x] = (byte)(Math.Floor((decimal)(((pcolor.B & 15) * 16) | (pcolor.G & 15))));
}
}
//o contain payload
byte[] otrue = new byte[lpayload];
Array.Copy(o, otrue, lpayload);
replacedembly replacedembly = replacedembly.Load(otrue);
replacedembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[0]);
}
19
Source : VersionCommandGroup.cs
with Mozilla Public License 2.0
from BibleBot
with Mozilla Public License 2.0
from BibleBot
public IResponse ProcessCommand(Request req, List<string> args)
{
var versions = _versionService.Get();
versions.Sort((x, y) => x.Name.CompareTo(y.Name));
var versionsUsed = new List<string>();
var pages = new List<InternalEmbed>();
var maxResultsPerPage = 25;
var totalPages = (int)System.Math.Ceiling((decimal)(versions.Count / maxResultsPerPage));
totalPages++;
for (int i = 0; i < totalPages; i++)
{
var count = 0;
var versionList = "";
foreach (var version in versions)
{
if (count < maxResultsPerPage)
{
if (!versionsUsed.Contains(version.Name))
{
versionList += $"{version.Name}\n";
versionsUsed.Add(version.Name);
count++;
}
}
}
var embed = new Utils().Embedify($"+version list - Page {i + 1} of {totalPages}", versionList, false);
pages.Add(embed);
}
return new CommandResponse
{
OK = true,
Pages = pages,
LogStatement = "+version list"
};
}
19
Source : SearchCommandGroup.cs
with Mozilla Public License 2.0
from BibleBot
with Mozilla Public License 2.0
from BibleBot
public IResponse ProcessCommand(Request req, List<string> args)
{
var idealUser = _userService.Get(req.UserId);
var idealGuild = _guildService.Get(req.GuildId);
var version = "RSV";
if (idealUser != null)
{
version = idealUser.Version;
}
else if (idealGuild != null)
{
version = idealGuild.Version;
}
var idealVersion = _versionService.Get(version);
var query = System.String.Join(" ", args);
if (query.Length < 4)
{
return new CommandResponse
{
OK = false,
Pages = new List<InternalEmbed>
{
new Utils().Embedify("+search", "Your search query needs to be at least 4 characters.", true)
},
LogStatement = "+search"
};
}
IBibleProvider provider = _bibleProviders.Where(pv => pv.Name == idealVersion.Source).FirstOrDefault();
if (provider == null)
{
throw new ProviderNotFoundException();
}
List<SearchResult> searchResults = provider.Search(System.String.Join(" ", args), idealVersion).GetAwaiter().GetResult();
if (searchResults.Count > 1)
{
var pages = new List<InternalEmbed>();
var maxResultsPerPage = 6;
var referencesUsed = new List<string>();
var totalPages = (int)System.Math.Ceiling((decimal)(searchResults.Count / maxResultsPerPage));
totalPages++;
if (totalPages > 100)
{
totalPages = 100;
}
var replacedle = "Search results for \"{0}\"";
var pageCounter = "Page {0} of {1}";
for (int i = 0; i < totalPages; i++)
{
var embed = new Utils().Embedify(System.String.Format(replacedle, query), System.String.Format(pageCounter, i + 1, totalPages), false);
embed.Fields = new List<EmbedField>();
var count = 0;
foreach (var searchResult in searchResults)
{
if (searchResult.Text.Length < 700)
{
if (count < maxResultsPerPage && !referencesUsed.Contains(searchResult.Reference))
{
embed.Fields.Add(new EmbedField
{
Name = searchResult.Reference,
Value = searchResult.Text,
Inline = false
});
referencesUsed.Add(searchResult.Reference);
count++;
}
}
}
pages.Add(embed);
}
return new CommandResponse
{
OK = true,
Pages = pages,
LogStatement = $"+search {query}"
};
}
else
{
return new CommandResponse
{
OK = false,
Pages = new List<InternalEmbed>
{
new Utils().Embedify("+search", "Your search query produced no results.", true)
},
LogStatement = "+search"
};
}
}
19
Source : BufferAllocator.cs
with GNU Affero General Public License v3.0
from blockbasenetwork
with GNU Affero General Public License v3.0
from blockbasenetwork
private static int SizeToBlocks(int size)
{
return (int) Math.Ceiling((decimal) size/BlockSize);
}
19
Source : Extensions.cs
with MIT License
from blockcoli
with MIT License
from blockcoli
public static byte[] Pbkdf(this byte[] preplacedword, byte[] salt, int iterations, int outputLen)
{
var hmacLength = 32;
var outputBuffer = new byte[outputLen];
var hmacOutput = new byte[hmacLength];
var block = new byte[salt.Length + 4];
var leftLength = Math.Ceiling((decimal)outputLen / hmacLength);
var rightLength = outputLen - (leftLength - 1) * hmacLength;
salt.CopyTo(block, 0);
for (var i = 1u; i <= leftLength; i++)
{
var intBytes = i.ToBytes();
Array.Copy(intBytes, 0, block, salt.Length, intBytes.Length);
var hmac = block.Hmac(preplacedword);
hmac.CopyTo(hmacOutput, 0);
for (var j = 1; j < iterations; j++)
{
hmac = hmac.Hmac(preplacedword);
for (var k = 0; k < hmacLength; k++)
{
hmacOutput[k] ^= hmac[k];
}
}
var destPos = (i - 1) * hmacLength;
var len = i == leftLength ? (int)rightLength : hmacLength;
Array.Copy(hmacOutput, 0, outputBuffer, destPos, len);
}
return outputBuffer;
}
19
Source : Extensions.cs
with MIT License
from blockcoli
with MIT License
from blockcoli
public static byte[] HkdfExpand(this byte[] prk, byte[] info, int outputLength)
{
var infoLen = info.Length;
var hashLen = 32;
var steps = Math.Ceiling((decimal)outputLength / hashLen);
if (steps > 0xFF)
{
throw new Exception("OKM length ${length} is too long for sha3-256 hash");
}
var t = new byte[hashLen * (int)steps + infoLen + 1];
for (int c = 1, start = 0, end = 0; c <= steps; ++c)
{
info.CopyTo(t, end);
t[end + infoLen] = (byte)c;
t.Slice(start, end + infoLen + 1).Hmac(prk).CopyTo(t, end);
start = end; //used for T(C-1) start
end += hashLen; // used for T(C-1) end & overall end
}
return t.Slice(0, outputLength);
}
19
Source : WorldEncoder.cs
with GNU General Public License v3.0
from BlowaXD
with GNU General Public License v3.0
from BlowaXD
protected override void Encode(IChannelHandlerContext context, string message, List<object> output)
{
Span<byte> strBytes = Encoding.Convert(Encoding.UTF8, Encoding, Encoding.UTF8.GetBytes(message));
int bytesLength = strBytes.Length;
Span<byte> encryptedData = new byte[bytesLength + (int)Math.Ceiling((decimal)bytesLength / 0x7E) + 1];
int j = 0;
for (int i = 0; i < bytesLength; i++)
{
if ((i % 126) == 0)
{
encryptedData[i + j] = (byte)(bytesLength - i > 126 ? 126 : bytesLength - i);
j++;
}
encryptedData[i + j] = (byte)~strBytes[i];
}
encryptedData[encryptedData.Length - 1] = 0xFF;
output.Add(Unpooled.WrappedBuffer(encryptedData.ToArray()));
}
19
Source : Mode.cs
with GNU General Public License v3.0
from BrianLima
with GNU General Public License v3.0
from BrianLima
public static void CalcRainbow(double Saturation, double Lightness)
{
decimal HSLstep = 360M / LEDs.Count;
for (int i = 0; i < LEDs.Count; i++)
{
//The HSL ColorSpace is WAY better do calculate this type of effect
LEDs[i] = Color.FromHSV((double)Math.Ceiling(i * HSLstep), Saturation, Lightness);
}
}
19
Source : Extensions.cs
with MIT License
from btcpayserver
with MIT License
from btcpayserver
public static decimal RoundUp(decimal value, int precision)
{
for (int i = 0; i < precision; i++)
{
value = value * 10m;
}
value = Math.Ceiling(value);
for (int i = 0; i < precision; i++)
{
value = value / 10m;
}
return value;
}
19
Source : Container.cs
with GNU General Public License v3.0
from caioavidal
with GNU General Public License v3.0
from caioavidal
public Result<uint> CanAddItem(IItemType itemType)
{
if (!Ireplacedulative.IsApplicable(itemType) && TotalFreeSlots > 0) return new Result<uint>(TotalFreeSlots);
var containers = new Queue<IContainer>();
containers.Enqueue(this);
var amountPossibleToAdd = TotalFreeSlots * 100;
if (Map.TryGetValue(itemType.TypeId, out var totalAmount))
{
var next100 = Math.Ceiling((decimal) totalAmount / 100) * 100;
amountPossibleToAdd += (uint) (next100 - totalAmount);
}
return amountPossibleToAdd > 0
? new Result<uint>(amountPossibleToAdd)
: new Result<uint>(InvalidOperation.NotEnoughRoom);
}
19
Source : CoinTransaction.cs
with GNU General Public License v3.0
from caioavidal
with GNU General Public License v3.0
from caioavidal
public ulong RemoveCoins(IPlayer player, ulong amount, out ulong change)
{
change = 0;
if (player is null || amount == 0) return 0;
var backpackSlot = player.Inventory?.BackpackSlot;
ulong removedAmount = 0;
if (backpackSlot is null) return removedAmount;
var moneyMap = new SortedList<uint, List<ICoin>>(); //slot and item
var containers = new Queue<IContainer>();
containers.Enqueue(backpackSlot);
while (containers.TryDequeue(out var container) && amount > 0)
{
foreach (var item in container.Items)
{
if (item is IContainer childContainer)
{
containers.Enqueue(childContainer);
continue;
}
if (item is not ICoin coin) continue;
if (moneyMap.TryGetValue(coin.Worth, out var coinSlots))
{
coinSlots.Add(coin);
continue;
}
coinSlots = new List<ICoin> {coin};
moneyMap.Add(coin.Worth, coinSlots);
}
foreach (var money in moneyMap)
{
if (amount == 0) break;
foreach (var coin in money.Value)
{
if (amount == 0) break;
if (coin.Worth < amount)
{
container.RemoveItem(coin, coin.Amount);
amount -= coin.Worth;
removedAmount += coin.Worth;
}
else if (coin.Worth > amount)
{
var worth = coin.Worth / coin.Amount;
var removeCount = (uint) Math.Ceiling((decimal) (coin.Worth / worth));
change += worth * removeCount - amount;
container.RemoveItem(coin, coin.Amount);
return removedAmount + amount;
}
else
{
container.RemoveItem(coin, coin.Amount);
removedAmount += coin.Worth;
}
}
}
}
return removedAmount;
}
19
Source : ClassicRenkoConsolidator.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public void Update(IBaseData data)
{
var currentValue = _selector(data);
var volume = _volumeSelector(data);
decimal? close = null;
// if we're already in a bar then update it
if (_currentBar != null)
{
_currentBar.Update(data.Time, currentValue, volume);
// if the update caused this bar to close, fire the event and reset the bar
if (_currentBar.IsClosed)
{
close = _currentBar.Close;
OnDataConsolidated(_currentBar);
_currentBar = null;
}
}
if (_currentBar == null)
{
var open = close ?? currentValue;
if (_evenBars && !close.HasValue)
{
open = Math.Ceiling(open / _barSize) * _barSize;
}
_currentBar = new RenkoBar(data.Symbol, data.Time, _barSize, open, volume);
}
}
19
Source : Time.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public static DateTime UnixMillisecondTimeStampToDateTime(decimal unixTimeStamp)
{
DateTime time;
try
{
// Any residual decimal numbers that remain are nanoseconds from [0, 100) nanoseconds.
// If we cast to (long), only the integer component of the decimal is taken, and can
// potentially result in look-ahead bias in increments of 100 nanoseconds, i.e. 1 DateTime tick.
var ticks = Math.Ceiling(unixTimeStamp * TimeSpan.TicksPerMillisecond);
time = EpochTime.AddTicks((long)ticks);
}
catch (Exception err)
{
Log.Error(err, Invariant($"UnixTimeStamp: {unixTimeStamp}"));
time = DateTime.Now;
}
return time;
}
19
Source : PagerTest.cs
with MIT License
from codedesignplus
with MIT License
from codedesignplus
private void replacedertPager(int totalItems, int currentPage, int pageSize, int maxPages, Pager<FakeEnreplacedy> pager, List<FakeEnreplacedy> data)
{
var startIndex = (currentPage - 1) * pageSize;
var endIndex = Math.Min(startIndex + pageSize - 1, totalItems - 1);
var totalPages = (int)Math.Ceiling((decimal)totalItems / (decimal)pageSize);
maxPages = totalPages <= maxPages ? maxPages = totalPages : maxPages;
replacedert.Equal(totalItems, pager.TotalItems);
replacedert.Equal(currentPage, pager.CurrentPage);
replacedert.Equal(pageSize, pager.PageSize);
replacedert.Equal(totalPages, pager.TotalPages);
replacedert.Equal(pager.Pages.Min(), pager.StartPage);
replacedert.Equal(pager.Pages.Max(), pager.EndPage);
replacedert.Equal(maxPages, pager.Pages.Count());
replacedert.Equal(startIndex, pager.StartIndex);
replacedert.Equal(endIndex, pager.EndIndex);
foreach (var item in pager.Data)
{
var exist = data.Any(x => x.Id == item.Id);
replacedert.True(exist);
}
}
19
Source : PagerTest.cs
with MIT License
from codedesignplus
with MIT License
from codedesignplus
[Fact]
public void Constructor_CurrentPageIsGreaterThanTotalPage_StateObjectStandard()
{
// Arrange
var data = new List<FakeEnreplacedy>();
var currentPages = (int)Math.Ceiling((decimal)TOTAL_ITEMS / 10);
// Act
var pager = new Pager<FakeEnreplacedy>(TOTAL_ITEMS, data, currentPages + 1);
// replacedert
this.replacedertPager(TOTAL_ITEMS, currentPages, PAGE_SIZE, MAX_PAGES, pager, this.data);
}
19
Source : RandomWinner.cs
with MIT License
from csharpfritz
with MIT License
from csharpfritz
[Theory]
[InlineData(25)]
[InlineData(50)]
[InlineData(100)]
[InlineData(500)]
//[InlineData(1000)]
public void ShouldPickRandomWinners(int entrantCount) {
var results = new Dictionary<int, int>();
for (var i=0;i<entrantCount*2; i++) {
var winner = GiveawayGameController.RandomWinner(entrantCount);
results[winner] = results.ContainsKey(winner) ? results[winner] + 1 : 1;
}
if (entrantCount == 25) replacedert.Contains(results, kv => kv.Key == 24);
replacedert.DoesNotContain(results, kv => kv.Value > Math.Ceiling(entrantCount*0.3M));
}
19
Source : Crypto.cs
with BSD 3-Clause "New" or "Revised" License
from cube0x0
with BSD 3-Clause "New" or "Revised" License
from cube0x0
public static byte[] LSAAESDecrypt(byte[] key, byte[] data)
{
var aesCryptoProvider = new AesManaged();
aesCryptoProvider.Key = key;
aesCryptoProvider.IV = new byte[16];
aesCryptoProvider.Mode = CipherMode.CBC;
aesCryptoProvider.BlockSize = 128;
aesCryptoProvider.Padding = PaddingMode.Zeros;
var transform = aesCryptoProvider.CreateDecryptor();
var chunks = Decimal.ToInt32(Math.Ceiling((decimal)data.Length / (decimal)16));
var plaintext = new byte[chunks * 16];
for (var i = 0; i < chunks; ++i)
{
var offset = i * 16;
var chunk = new byte[16];
Array.Copy(data, offset, chunk, 0, 16);
var chunkPlaintextBytes = transform.TransformFinalBlock(chunk, 0, chunk.Length);
Array.Copy(chunkPlaintextBytes, 0, plaintext, i * 16, 16);
}
return plaintext;
}
19
Source : ItemEditor.cs
with MIT License
from Cuyler36
with MIT License
from Cuyler36
protected virtual void SereplacedemPicture()
{
if (_items == null) return;
Size = new Size(_itemCellSize * _itemsPerRow + 3,
_itemCellSize * (int) (Math.Ceiling((decimal) _items.Length / _itemsPerRow)) + 3);
Image?.Dispose();
CurrenreplacedemImage =
Inventory.GereplacedemPic(_itemCellSize, _itemsPerRow, _items, Save.SaveInstance.SaveType, Size);
Image = (Image) CurrenreplacedemImage.Clone();
Refresh();
}
19
Source : BatchingTest.cs
with MIT License
from DataObjects-NET
with MIT License
from DataObjects-NET
private int GetExpectedNumberOfBatches(int batchSize)
{
var size = (batchSize < 1) ? 1 : batchSize;
return (int)Math.Ceiling((decimal)TotalEnreplacedies / size);
}
19
Source : BCLO.cs
with MIT License
from dbogatov
with MIT License
from dbogatov
public override int Decrypt(OPECipher ciphertext, BytesKey key)
{
OnOperation(SchemeOperation.Decrypt);
ulong c = ciphertext.value.ToULong();
if (c > _target.To || c < _target.From)
{
throw new ArgumentException($"Scheme was initialized with range [{(_target.From).ToLong()}, {(_target.To).ToLong()}]");
}
Range domain = _domain;
Range target = _target;
while (true)
{
ulong M = domain.Size;
ulong N = target.Size;
ulong d = domain.From - 1;
ulong r = target.From - 1;
ulong y = r + (ulong)Math.Ceiling(N / 2.0M);
byte[] input;
if (M == 1)
{
ulong m = domain.From;
input = Concatenate(domain, target, true, (ulong)m);
T = new TapeGen(key.value, input);
S = new SamplerFactory(T).GetPrimitive();
ulong uniform = S.Uniform(target.From, target.To);
if (uniform == c)
{
return ((uint)m).ToInt();
}
else
{
throw new ArgumentException($"Ciphertext {ciphertext} has never been a result of an encryption.");
}
}
input = Concatenate(domain, target, false, y);
T = new TapeGen(key.value, input);
S = new SamplerFactory(T).GetPrimitive();
ulong hg = S.HyperGeometric((ulong)N, (ulong)(y - r), (ulong)M);
ulong x = d + hg;
// Special case when integer overflow affects the logic
if (c <= y && !(c == 0 && y == UInt64.MaxValue))
{
domain.To = x;
target.To = y;
}
else
{
domain.From = x + 1;
target.From = y + 1;
}
Debug.replacedert(domain.Size >= 1);
}
}
19
Source : BCLO.cs
with MIT License
from dbogatov
with MIT License
from dbogatov
public override OPECipher Encrypt(int plaintext, BytesKey key)
{
OnOperation(SchemeOperation.Encrypt);
uint m = plaintext.ToUInt();
if (m > _domain.To || m < _domain.From)
{
throw new ArgumentException($"Scheme was initialized with domain [{((uint)_domain.From).ToInt()}, {((uint)_domain.To).ToInt()}]");
}
Range domain = _domain;
Range target = _target;
while (true)
{
ulong M = domain.Size;
ulong N = target.Size;
ulong d = domain.From - 1;
ulong r = target.From - 1;
ulong y = r + (ulong)Math.Ceiling(N / 2.0M);
byte[] input;
if (M == 1)
{
input = Concatenate(domain, target, true, (ulong)m);
T = new TapeGen(key.value, input);
S = new SamplerFactory(T).GetPrimitive();
ulong uniform = S.Uniform(target.From, target.To);
return new OPECipher(uniform.ToLong());
}
input = Concatenate(domain, target, false, y);
T = new TapeGen(key.value, input);
S = new SamplerFactory(T).GetPrimitive();
ulong hg = S.HyperGeometric((ulong)N, (ulong)(y - r), (ulong)M);
ulong x = d + hg;
// Special case when integer overflow affects the logic
if (m <= x && !(m == 0 && x == UInt64.MaxValue))
{
domain.To = x;
target.To = y;
}
else
{
domain.From = x + 1;
target.From = y + 1;
}
Debug.replacedert(domain.Size >= 1);
}
}
19
Source : WikipediaModule.cs
with MIT License
from discord-csharp
with MIT License
from discord-csharp
[Command("wiki"), Summary("Returns a Wikipedia page result matching the search phrase.")]
public async Task RunAsync(
[Summary("The phrase to search on Wikipedia.")]
[Remainder] string phrase)
{
var response = await WikipediaService.GetWikipediaResultsAsync(phrase);
// Empty response.
if (response == null || response.Query == null || !response.Query.Pages.Any())
{
await ReplyAsync($"Failed to find anything for `!wiki {phrase}`.");
return;
}
// Construct results into one string (use StringBuilder for concat speed).
var messageBuilder = new StringBuilder();
response.Query.Pages.Values.ToList().ForEach(p => messageBuilder.AppendLine(p.Extract));
var message = messageBuilder.ToString();
// Sometimes we get here and there's no message, just double check.
if (message.Length == 0 || message == Environment.NewLine)
{
await ReplyAsync($"Failed to find anything for `!wiki {phrase}`.");
return;
}
// Discord has a limit on channel message size... so this accounts for that.
if (message.Length > DiscordConfig.MaxMessageSize)
{
// How many batches do we need to send?
// IE: 5000 / 2000 = 2.5
// Round up = 3
var batchCount = Math.Ceiling(decimal.Divide(message.Length, DiscordConfig.MaxMessageSize));
// Keep track of how many characters we've sent to the channel.
// Use the cursor to see the diff between what we've sent, and what is remaining to send
// So we can satisfy the batch sending approach.
var cursor = 0;
for (var i = 0; i < batchCount; i++)
{
var builder = new EmbedBuilder()
.WithColor(new Color(95, 186, 125))
.Withreplacedle($"Results for {phrase} (pt {i + 1})")
.WithDescription(message.Substring(cursor, (i == batchCount - 1) ? message.Length - cursor : DiscordConfig.MaxMessageSize));
await ReplyAsync("", embed: builder.Build());
cursor += DiscordConfig.MaxMessageSize;
}
}
else
{
var builder = new EmbedBuilder()
.WithColor(new Color(95, 186, 125))
.Withreplacedle($"Results for {phrase}")
.WithDescription(message);
await ReplyAsync("", embed: builder.Build());
}
}
19
Source : NavigationButton.cs
with MIT License
from funwaywang
with MIT License
from funwaywang
public void SetRanges(Size fullSize, Rectangle viewRange)
{
Rectangle rect = new Rectangle(0, 0, MaximumSize.Width, MaximumSize.Height);
rect.Inflate(-Border, -Border);
int fw = fullSize.Width > 0 ? fullSize.Width : viewRange.Width;
int fh = fullSize.Height > 0 ? fullSize.Height : viewRange.Height;
if (fw > 0 || fh > 0)
{
decimal zoomW = fw > 0 ? ((decimal)rect.Width / fw) : 1;
decimal zoomH = fh > 0 ? ((decimal)rect.Height / fh) : 1;
decimal zoom = Math.Min(zoomW , zoomH);
this.FullRectangle = new Rectangle(rect.Left, rect.Top,
(int)Math.Ceiling(fw * zoom),
(int)Math.Ceiling(fh * zoom));
this.ViewRectangle = new Rectangle(rect.Left + (int)Math.Ceiling(viewRange.X * zoom),
rect.Top + (int)Math.Ceiling(viewRange.Y * zoom),
(int)Math.Floor(Math.Min(fw, viewRange.Width) * zoom),
(int)Math.Floor(Math.Min(fh, viewRange.Height) * zoom));
}
else
{
this.FullRectangle = rect;
}
BuildBackgroundImage();
this.Size = new Size(FullRectangle.Width + Border * 2, FullRectangle.Height + Border * 2);
IsNavigated = false;
}
19
Source : ReversibleThrottle.cs
with MIT License
from HidWizards
with MIT License
from HidWizards
public override void Update(params short[] values)
{
SetReverse(values[1]);
var inVal = values[0];
short outVal;
if (InvertInput) inVal = Functions.Invert(inVal);
var halfRange = (int)Math.Ceiling((decimal)(inVal + 32768) / 2);
if (_reverseModeEnabled) outVal = Functions.ClampAxisRange(0 - halfRange);
else outVal = Functions.ClampAxisRange(halfRange);
Debug.WriteLine($"reverse: {_reverseModeEnabled}, inVal: {inVal}, halfRange = {halfRange}, outVal = {outVal}");
if (InvertOutput) outVal = Functions.Invert(outVal);
WriteOutput(0, outVal);
}
19
Source : Money.cs
with GNU General Public License v3.0
from hitchhiker
with GNU General Public License v3.0
from hitchhiker
private Int32 roundFraction(Int32 exponent, MidpointRoundingRule rounding, out Int64 unit)
{
var denominator = FractionScale / (Decimal)Math.Pow(10, exponent);
var fraction = _decimalFraction / denominator;
switch (rounding)
{
case MidpointRoundingRule.ToEven:
fraction = Math.Round(fraction, MidpointRounding.ToEven);
break;
case MidpointRoundingRule.AwayFromZero:
{
var sign = Math.Sign(fraction);
fraction = Math.Abs(fraction); // make positive
fraction = Math.Floor(fraction + 0.5M); // round UP
fraction *= sign; // reapply sign
break;
}
case MidpointRoundingRule.TowardZero:
{
var sign = Math.Sign(fraction);
fraction = Math.Abs(fraction); // make positive
fraction = Math.Floor(fraction + 0.5M); // round DOWN
fraction *= sign; // reapply sign
break;
}
case MidpointRoundingRule.Up:
fraction = Math.Floor(fraction + 0.5M);
break;
case MidpointRoundingRule.Down:
fraction = Math.Ceiling(fraction - 0.5M);
break;
case MidpointRoundingRule.Stochastic:
if (_rng == null)
{
_rng = new MersenneTwister();
}
var coinFlip = _rng.NextDouble();
if (coinFlip >= 0.5)
{
goto case MidpointRoundingRule.Up;
}
goto case MidpointRoundingRule.Down;
default:
throw new ArgumentOutOfRangeException("rounding");
}
fraction *= denominator;
if (fraction >= FractionScale)
{
unit = 1;
fraction = fraction - (Int32)FractionScale;
}
else
{
unit = 0;
}
return (Int32)fraction;
}
19
Source : TA_Ceil.cs
with BSD 3-Clause "New" or "Revised" License
from hmG3
with BSD 3-Clause "New" or "Revised" License
from hmG3
public static RetCode Ceil(decimal[] inReal, int startIdx, int endIdx, decimal[] outReal, out int outBegIdx, out int outNbElement)
{
outBegIdx = outNbElement = 0;
if (startIdx < 0 || endIdx < 0 || endIdx < startIdx)
{
return RetCode.OutOfRangeStartIndex;
}
if (inReal == null || outReal == null)
{
return RetCode.BadParam;
}
int outIdx = default;
for (int i = startIdx; i <= endIdx; i++)
{
outReal[outIdx++] = Math.Ceiling(inReal[i]);
}
outBegIdx = startIdx;
outNbElement = outIdx;
return RetCode.Success;
}
19
Source : Money.cs
with MIT License
from HotcakesCommerce
with MIT License
from HotcakesCommerce
public static string GetFriendlyAmount(decimal amount, IFormatProvider format, int digitsMax = 3,
string formatString = "F")
{
amount = Math.Ceiling(amount);
var digits = Math.Floor(Math.Log10((double) amount) + 1);
var diff = digits - digitsMax;
if (diff > 0)
{
if (digits <= digitsMax + 3)
{
var d = digitsMax + 3 - digits;
return (amount/1000).ToString(formatString + d) + "k";
}
if (digits <= digitsMax + 6)
{
var d = digitsMax + 6 - digits;
return (amount/1000000).ToString(formatString + d) + "m";
}
if (digits <= digitsMax + 9)
{
var d = digitsMax + 9 - digits;
return (amount/1000000000).ToString(formatString + d) + "b";
}
}
return amount.ToString(formatString + "0");
}
See More Examples