-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Helper.cs
63 lines (55 loc) · 1.91 KB
/
Helper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright (C) 2016 Maxim Gumin, The MIT License (MIT)
using System.Linq;
using System.Xml.Linq;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
static class Helper
{
public static int Random(this double[] weights, double r)
{
double sum = 0;
for (int i = 0; i < weights.Length; i++) sum += weights[i];
double threshold = r * sum;
double partialSum = 0;
for (int i = 0; i < weights.Length; i++)
{
partialSum += weights[i];
if (partialSum >= threshold) return i;
}
return 0;
}
public static long ToPower(this int a, int n)
{
long product = 1;
for (int i = 0; i < n; i++) product *= a;
return product;
}
public static T Get<T>(this XElement xelem, string attribute, T defaultT = default)
{
XAttribute a = xelem.Attribute(attribute);
return a == null ? defaultT : (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(a.Value);
}
public static IEnumerable<XElement> Elements(this XElement xelement, params string[] names) => xelement.Elements().Where(e => names.Any(n => n == e.Name));
}
static class BitmapHelper
{
public static (int[], int, int) LoadBitmap(string filename)
{
using var image = Image.Load<Bgra32>(filename);
int width = image.Width, height = image.Height;
int[] result = new int[width * height];
image.CopyPixelDataTo(MemoryMarshal.Cast<int, Bgra32>(result));
return (result, width, height);
}
unsafe public static void SaveBitmap(int[] data, int width, int height, string filename)
{
fixed (int* pData = data)
{
using var image = Image.WrapMemory<Bgra32>(pData, width, height);
image.SaveAsPng(filename);
}
}
}