text:
int_rules_3_1_5 = @theory begin

    #= ::Subsection::Closed:: =#
    #= 3.1.5*u*(a+b*log(c*x^n))^p =#
    @apply_utils Antiderivative((~(A') + ~(B') * log(~(c') * (~(d') + ~(e') * ~x) ^ ~(n'))) / sqrt(~a + ~(b') * log(~(c') * (~(d') + ~(e') * ~x) ^ ~(n'))), ~x) => (~B * (~d + ~e * ~x) * sqrt(~a + ~b * log(~c * (~d + ~e * ~x) ^ ~n))) / (~b * ~e) + ((2 * ~A * ~b - ~B * (2 * ~a + ~b * ~n)) / (2 * ~b)) * Antiderivative(1 / sqrt(~a + ~b * log(~c * (~d + ~e * ~x) ^ ~n)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~A, ~B, ~n], ~x)
    @apply_utils Antiderivative((~x) ^ ~(m') * (~d + ~(e') / ~x) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => Antiderivative((~e + ~d * ~x) ^ ~q * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~m, ~n, ~p], ~x) && (EqQ(~m, ~q) && IntegerQ(~q))
    @apply_utils Antiderivative((~x) ^ ~(m') * (~d + ~(e') * (~x) ^ ~(r')) ^ ~(q') * log(~(c') * (~x) ^ ~(n')), ~x) => With([u = IntHide((~x) ^ ~m * (~d + ~e * (~x) ^ ~r) ^ ~q, ~x)], Dist(log(~c * (~x) ^ ~n), u, ~x) - ~n * Antiderivative(SimplifyIntegrand(u / ~x, ~x), ~x)) <-- FreeQ([~c, ~d, ~e, ~n, ~r], ~x) && (IGtQ(~q, 0) && (IntegerQ(~m) && Not(EqQ(~q, 1) && EqQ(~m, -1))))
    @apply_utils Antiderivative((~x) ^ ~(m') * (~d + ~(e') * (~x) ^ ~(r')) ^ ~(q') * (~a + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => With([u = IntHide((~x) ^ ~m * (~d + ~e * (~x) ^ ~r) ^ ~q, ~x)], u * (~a + ~b * log(~c * (~x) ^ ~n)) - ~b * ~n * Antiderivative(SimplifyIntegrand(u / ~x, ~x), ~x)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~n, ~r], ~x) && (IGtQ(~q, 0) && (IntegerQ(~m) && Not(EqQ(~q, 1) && EqQ(~m, -1))))
    @apply_utils Antiderivative((~(f') * ~x) ^ ~(m') * (~d + ~(e') * (~x) ^ ~(r')) ^ ~q * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => ((~f * ~x) ^ (~m + 1) * (~d + ~e * (~x) ^ ~r) ^ (~q + 1) * (~a + ~b * log(~c * (~x) ^ ~n))) / (~d * ~f * (~m + 1)) - ((~b * ~n) / (~d * (~m + 1))) * Antiderivative((~f * ~x) ^ ~m * (~d + ~e * (~x) ^ ~r) ^ (~q + 1), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n, ~q, ~r], ~x) && (EqQ(~m + ~r * (~q + 1) + 1, 0) && NeQ(~m, -1))
    @apply_utils Antiderivative((~(f') * ~x) ^ ~(m') * (~d + ~(e') * (~x) ^ ~r) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~n)) ^ ~(p'), ~x) => ((~f) ^ ~m / ~n) * Subst(Antiderivative((~d + ~e * ~x) ^ ~q * (~a + ~b * log(~c * ~x)) ^ ~p, ~x), ~x, (~x) ^ ~n) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n, ~q, ~r], ~x) && (EqQ(~m, ~r - 1) && (IGtQ(~p, 0) && ((IntegerQ(~m) || GtQ(~f, 0)) && EqQ(~r, ~n))))
    @apply_utils Antiderivative(((~(f') * ~x) ^ ~(m') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p')) / (~d + ~(e') * (~x) ^ ~r), ~x) => ((~f) ^ ~m * log(1 + (~e * (~x) ^ ~r) / ~d) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p) / (~e * ~r) - ((~b * (~f) ^ ~m * ~n * ~p) / (~e * ~r)) * Antiderivative((log(1 + (~e * (~x) ^ ~r) / ~d) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p - 1)) / ~x, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n, ~r], ~x) && (EqQ(~m, ~r - 1) && (IGtQ(~p, 0) && ((IntegerQ(~m) || GtQ(~f, 0)) && NeQ(~r, ~n))))
    @apply_utils Antiderivative((~(f') * ~x) ^ ~(m') * (~d + ~(e') * (~x) ^ ~r) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => ((~f) ^ ~m * (~d + ~e * (~x) ^ ~r) ^ (~q + 1) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p) / (~e * ~r * (~q + 1)) - ((~b * (~f) ^ ~m * ~n * ~p) / (~e * ~r * (~q + 1))) * Antiderivative(((~d + ~e * (~x) ^ ~r) ^ (~q + 1) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p - 1)) / ~x, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n, ~q, ~r], ~x) && (EqQ(~m, ~r - 1) && (IGtQ(~p, 0) && ((IntegerQ(~m) || GtQ(~f, 0)) && (NeQ(~r, ~n) && NeQ(~q, -1)))))
    @apply_utils Antiderivative((~f * ~x) ^ ~(m') * (~d + ~(e') * (~x) ^ ~r) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => ((~f * ~x) ^ ~m / (~x) ^ ~m) * Antiderivative((~x) ^ ~m * (~d + ~e * (~x) ^ ~r) ^ ~q * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n, ~q, ~r], ~x) && (EqQ(~m, ~r - 1) && (IGtQ(~p, 0) && Not(IntegerQ(~m) || GtQ(~f, 0))))
    @apply_utils Antiderivative((~(f') * ~x) ^ ~(m') * (~d + ~(e') * ~x) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => ((~f * ~x) ^ ~m * (~d + ~e * ~x) ^ (~q + 1) * (~a + ~b * log(~c * (~x) ^ ~n))) / (~e * (~q + 1)) - (~f / (~e * (~q + 1))) * Antiderivative((~f * ~x) ^ (~m - 1) * (~d + ~e * ~x) ^ (~q + 1) * (~a * ~m + ~b * ~n + ~b * ~m * log(~c * (~x) ^ ~n)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n], ~x) && (ILtQ(~q, -1) && GtQ(~m, 0))
    @apply_utils Antiderivative((~(f') * ~x) ^ ~(m') * (~d + ~(e') * (~x) ^ 2) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => (-((~f * ~x) ^ (~m + 1)) * (~d + ~e * (~x) ^ 2) ^ (~q + 1) * (~a + ~b * log(~c * (~x) ^ ~n))) / (2 * ~d * ~f * (~q + 1)) + (1 / (2 * ~d * (~q + 1))) * Antiderivative((~f * ~x) ^ ~m * (~d + ~e * (~x) ^ 2) ^ (~q + 1) * (~a * (~m + 2 * ~q + 3) + ~b * ~n + ~b * (~m + 2 * ~q + 3) * log(~c * (~x) ^ ~n)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n], ~x) && (ILtQ(~q, -1) && ILtQ(~m, 0))
    @apply_utils Antiderivative((~x) ^ ~(m') * (~d + ~(e') * (~x) ^ 2) ^ ~q * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => (((~d) ^ IntPart(~q) * (~d + ~e * (~x) ^ 2) ^ FracPart(~q)) / (1 + (~e / ~d) * (~x) ^ 2) ^ FracPart(~q)) * Antiderivative((~x) ^ ~m * (1 + (~e / ~d) * (~x) ^ 2) ^ ~q * (~a + ~b * log(~c * (~x) ^ ~n)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~n], ~x) && (IntegerQ(~m / 2) && (IntegerQ(~q - 1 / 2) && Not(LtQ(~m + 2 * ~q, -2) || GtQ(~d, 0))))
    @apply_utils Antiderivative((~x) ^ ~(m') * (~d1 + ~(e1') * ~x) ^ ~q * (~d2 + ~(e2') * ~x) ^ ~q * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => (((~d1 + ~e1 * ~x) ^ ~q * (~d2 + ~e2 * ~x) ^ ~q) / (1 + ((~e1 * ~e2) / (~d1 * ~d2)) * (~x) ^ 2) ^ ~q) * Antiderivative((~x) ^ ~m * (1 + ((~e1 * ~e2) / (~d1 * ~d2)) * (~x) ^ 2) ^ ~q * (~a + ~b * log(~c * (~x) ^ ~n)), ~x) <-- FreeQ([~a, ~b, ~c, ~d1, ~e1, ~d2, ~e2, ~n], ~x) && (EqQ(~d2 * ~e1 + ~d1 * ~e2, 0) && (IntegerQ(~m) && IntegerQ(~q - 1 / 2)))
    @apply_utils Antiderivative((~(a') + ~(b') * log(~(c') * (~x) ^ ~n)) / (~x * (~d + ~(e') * (~x) ^ ~(r'))), ~x) => (1 / ~n) * Subst(Antiderivative((~a + ~b * log(~c * ~x)) / (~x * (~d + ~e * (~x) ^ (~r / ~n))), ~x), ~x, (~x) ^ ~n) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~n, ~r], ~x) && IntegerQ(~r / ~n)
    @apply_utils Antiderivative((~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p') / (~x * (~d + ~(e') * ~x)), ~x) => (1 / ~d) * Antiderivative((~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p / ~x, ~x) - (~e / ~d) * Antiderivative((~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p / (~d + ~e * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~n], ~x) && IGtQ(~p, 0)
    #= Antiderivative(((~a')+(~b')*log((~c')*(~x)^(~n')))^(~p')/((~x)*((~d)+(~e')*(~x)^(~r'))),~x) :=   (r*log(x)-log(1+(e*x^r)/d))*(a+b*log(c*x^n))^p/(d*r) - b*n*p/d*Antiderivative(log(x)*(a+b*log(c*x^n))^(p-1)/x,x) + b*n*p/(d*r)*Antiderivative(log(1+(e*x^r)/d)*(a+b*log(c*x^n))^(p-1)/x,x) <--  FreeQ([a,b,c,d,e,n,r],x) && IGtQ(p,0) =#
    @apply_utils Antiderivative((~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p') / (~x * (~d + ~(e') * (~x) ^ ~(r'))), ~x) => (-(log(1 + ~d / (~e * (~x) ^ ~r))) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p) / (~d * ~r) + ((~b * ~n * ~p) / (~d * ~r)) * Antiderivative((log(1 + ~d / (~e * (~x) ^ ~r)) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p - 1)) / ~x, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~n, ~r], ~x) && IGtQ(~p, 0)
    @apply_utils Antiderivative(((~d + ~(e') * ~x) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p')) / ~x, ~x) => ~d * Antiderivative(((~d + ~e * ~x) ^ (~q - 1) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p) / ~x, ~x) + ~e * Antiderivative((~d + ~e * ~x) ^ (~q - 1) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~n], ~x) && (IGtQ(~p, 0) && (GtQ(~q, 0) && IntegerQ(2 * ~q)))
    @apply_utils Antiderivative(((~d + ~(e') * ~x) ^ ~q * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p')) / ~x, ~x) => (1 / ~d) * Antiderivative(((~d + ~e * ~x) ^ (~q + 1) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p) / ~x, ~x) - (~e / ~d) * Antiderivative((~d + ~e * ~x) ^ ~q * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~n], ~x) && (IGtQ(~p, 0) && (LtQ(~q, -1) && IntegerQ(2 * ~q)))
    @apply_utils Antiderivative(((~d + ~(e') * (~x) ^ ~(r')) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n')))) / ~x, ~x) => With([u = IntHide((~d + ~e * (~x) ^ ~r) ^ ~q / ~x, ~x)], u * (~a + ~b * log(~c * (~x) ^ ~n)) - ~b * ~n * Antiderivative(Dist(1 / ~x, u, ~x), ~x)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~n, ~r], ~x) && IntegerQ(~q - 1 / 2)
    @apply_utils Antiderivative(((~d + ~(e') * (~x) ^ ~(r')) ^ ~q * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p')) / ~x, ~x) => (1 / ~d) * Antiderivative(((~d + ~e * (~x) ^ ~r) ^ (~q + 1) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p) / ~x, ~x) - (~e / ~d) * Antiderivative((~x) ^ (~r - 1) * (~d + ~e * (~x) ^ ~r) ^ ~q * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~n, ~r], ~x) && (IGtQ(~p, 0) && ILtQ(~q, -1))
    @apply_utils Antiderivative((~(f') * ~x) ^ ~(m') * (~d + ~(e') * (~x) ^ ~(r')) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => With([u = IntHide((~f * ~x) ^ ~m * (~d + ~e * (~x) ^ ~r) ^ ~q, ~x)], Dist(~a + ~b * log(~c * (~x) ^ ~n), u, ~x) - ~b * ~n * Antiderivative(SimplifyIntegrand(u / ~x, ~x), ~x) <-- (EqQ(~r, 1) || EqQ(~r, 2)) && (IntegerQ(~m) && IntegerQ(~q - 1 / 2)) || InverseFunctionFreeQ(u, ~x)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n, ~q, ~r], ~x) && (IntegerQ(2 * ~q) && (IntegerQ(~m) && IntegerQ(~r) || IGtQ(~q, 0)))
    @apply_utils Antiderivative((~(f') * ~x) ^ ~(m') * (~d + ~(e') * (~x) ^ ~(r')) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => With([u = ExpandIntegrand(~a + ~b * log(~c * (~x) ^ ~n), (~f * ~x) ^ ~m * (~d + ~e * (~x) ^ ~r) ^ ~q, ~x)], Antiderivative(u, ~x) <-- SumQ(u)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n, ~q, ~r], ~x) && (IntegerQ(~q) && (GtQ(~q, 0) || IntegerQ(~m) && IntegerQ(~r)))
    @apply_utils Antiderivative((~x) ^ ~(m') * (~d + ~(e') * (~x) ^ ~(r')) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~n)) ^ ~(p'), ~x) => (1 / ~n) * Subst(Antiderivative((~x) ^ (Simplify((~m + 1) / ~n) - 1) * (~d + ~e * (~x) ^ (~r / ~n)) ^ ~q * (~a + ~b * log(~c * ~x)) ^ ~p, ~x), ~x, (~x) ^ ~n) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~m, ~n, ~p, ~q, ~r], ~x) && (IntegerQ(~q) && (IntegerQ(~r / ~n) && (IntegerQ(Simplify((~m + 1) / ~n)) && (GtQ((~m + 1) / ~n, 0) || IGtQ(~p, 0)))))
    @apply_utils Antiderivative((~(f') * ~x) ^ ~(m') * (~d + ~(e') * (~x) ^ ~(r')) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => With([u = ExpandIntegrand((~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, (~f * ~x) ^ ~m * (~d + ~e * (~x) ^ ~r) ^ ~q, ~x)], Antiderivative(u, ~x) <-- SumQ(u)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n, ~p, ~q, ~r], ~x) && (IntegerQ(~q) && (GtQ(~q, 0) || IGtQ(~p, 0) && (IntegerQ(~m) && IntegerQ(~r))))
    @apply_utils Antiderivative((~(f') * ~x) ^ ~(m') * (~d + ~(e') * (~x) ^ ~(r')) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => Unintegrable((~f * ~x) ^ ~m * (~d + ~e * (~x) ^ ~r) ^ ~q * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n, ~p, ~q, ~r], ~x)
    @apply_utils Antiderivative((~(f') * ~x) ^ ~(m') * (~u) ^ ~(q') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => Antiderivative((~f * ~x) ^ ~m * ExpandToSum(~u, ~x) ^ ~q * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~f, ~m, ~n, ~p, ~q], ~x) && (BinomialQ(~u, ~x) && Not(BinomialMatchQ(~u, ~x)))
    @apply_utils Antiderivative(~Polyx * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => Antiderivative(ExpandIntegrand(~Polyx * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~n, ~p], ~x) && PolynomialQ(~Polyx, ~x)
    @apply_utils Antiderivative(~RFx * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => With([u = ExpandIntegrand((~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~RFx, ~x)], Antiderivative(u, ~x) <-- SumQ(u)) <-- FreeQ([~a, ~b, ~c, ~n], ~x) && (RationalFunctionQ(~RFx, ~x) && IGtQ(~p, 0))
    @apply_utils Antiderivative(~RFx * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => With([u = ExpandIntegrand(~RFx * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x)], Antiderivative(u, ~x) <-- SumQ(u)) <-- FreeQ([~a, ~b, ~c, ~n], ~x) && (RationalFunctionQ(~RFx, ~x) && IGtQ(~p, 0))
    @apply_utils Antiderivative(~AFx * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => Unintegrable(~AFx * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~n, ~p], ~x) && AlgebraicFunctionQ(~AFx, ~x, True)
    @apply_utils Antiderivative((~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p') * (~d + ~(e') * log(~(c') * (~x) ^ ~(n'))) ^ ~(q'), ~x) => Antiderivative(ExpandIntegrand((~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p * (~d + ~e * log(~c * (~x) ^ ~n)) ^ ~q, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~n], ~x) && (IntegerQ(~p) && IntegerQ(~q))
    @apply_utils Antiderivative((~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p') * (~(d') + ~(e') * log(~(f') * (~x) ^ ~(r'))), ~x) => With([u = IntHide((~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x)], Dist(~d + ~e * log(~f * (~x) ^ ~r), u, ~x) - ~e * ~r * Antiderivative(SimplifyIntegrand(u / ~x, ~x), ~x)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~n, ~p, ~r], ~x)
    @apply_utils Antiderivative((~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p') * (~(d') + ~(e') * log(~(f') * (~x) ^ ~(r'))) ^ ~(q'), ~x) => (~x * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p * (~d + ~e * log(~f * (~x) ^ ~r)) ^ ~q - ~e * ~q * ~r * Antiderivative((~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p * (~d + ~e * log(~f * (~x) ^ ~r)) ^ (~q - 1), ~x)) - ~b * ~n * ~p * Antiderivative((~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p - 1) * (~d + ~e * log(~f * (~x) ^ ~r)) ^ ~q, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~n, ~r], ~x) && (IGtQ(~p, 0) && IGtQ(~q, 0))
    @apply_utils Antiderivative((~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p') * (~(d') + ~(e') * log(~(f') * (~x) ^ ~(r'))) ^ ~(q'), ~x) => Unintegrable((~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p * (~d + ~e * log(~f * (~x) ^ ~r)) ^ ~q, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~n, ~p, ~q, ~r], ~x)
    @apply_utils Antiderivative((~(a') + ~(b') * log(~v)) ^ ~(p') * (~(c') + ~(d') * log(~v)) ^ ~(q'), ~x) => (1 / Coeff(~v, ~x, 1)) * Subst(Antiderivative((~a + ~b * log(~x)) ^ ~p * (~c + ~d * log(~x)) ^ ~q, ~x), ~x, ~v) <-- FreeQ([~a, ~b, ~c, ~d, ~p, ~q], ~x) && (LinearQ(~v, ~x) && NeQ(Coeff(~v, ~x, 0), 0))
    @apply_utils Antiderivative(((~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p') * (~(d') + ~(e') * log(~(c') * (~x) ^ ~(n'))) ^ ~(q')) / ~x, ~x) => (1 / ~n) * Subst(Antiderivative((~a + ~b * ~x) ^ ~p * (~d + ~e * ~x) ^ ~q, ~x), ~x, log(~c * (~x) ^ ~n)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~n, ~p, ~q], ~x)
    @apply_utils Antiderivative((~(g') * ~x) ^ ~(m') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p') * (~(d') + ~(e') * log(~(f') * (~x) ^ ~(r'))), ~x) => With([u = IntHide((~g * ~x) ^ ~m * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x)], Dist(~d + ~e * log(~f * (~x) ^ ~r), u, ~x) - ~e * ~r * Antiderivative(SimplifyIntegrand(u / ~x, ~x), ~x)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~m, ~n, ~p, ~r], ~x) && Not(EqQ(~p, 1) && (EqQ(~a, 0) && NeQ(~d, 0)))
    @apply_utils Antiderivative((~(g') * ~x) ^ ~(m') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p') * (~(d') + ~(e') * log(~(f') * (~x) ^ ~(r'))) ^ ~(q'), ~x) => (((~g * ~x) ^ (~m + 1) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p * (~d + ~e * log(~f * (~x) ^ ~r)) ^ ~q) / (~g * (~m + 1)) - ((~e * ~q * ~r) / (~m + 1)) * Antiderivative((~g * ~x) ^ ~m * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p * (~d + ~e * log(~f * (~x) ^ ~r)) ^ (~q - 1), ~x)) - ((~b * ~n * ~p) / (~m + 1)) * Antiderivative((~g * ~x) ^ ~m * (~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p - 1) * (~d + ~e * log(~f * (~x) ^ ~r)) ^ ~q, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~m, ~n, ~r], ~x) && (IGtQ(~p, 0) && (IGtQ(~q, 0) && NeQ(~m, -1)))
    @apply_utils Antiderivative((~(g') * ~x) ^ ~(m') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p') * (~(d') + ~(e') * log(~(f') * (~x) ^ ~(r'))) ^ ~(q'), ~x) => Unintegrable((~g * ~x) ^ ~m * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p * (~d + ~e * log(~f * (~x) ^ ~r)) ^ ~q, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~m, ~n, ~p, ~q, ~r], ~x)
    @apply_utils Antiderivative((~u) ^ ~(m') * (~(a') + ~(b') * log(~v)) ^ ~(p') * (~(c') + ~(d') * log(~v)) ^ ~(q'), ~x) => With([e = Coeff(~u, ~x, 0), f = Coeff(~u, ~x, 1), g = Coeff(~v, ~x, 0), h = Coeff(~v, ~x, 1)], (1 / h) * Subst(Antiderivative(((f * ~x) / h) ^ ~m * (~a + ~b * log(~x)) ^ ~p * (~c + ~d * log(~x)) ^ ~q, ~x), ~x, ~v) <-- EqQ(f * g - e * h, 0) && NeQ(g, 0)) <-- FreeQ([~a, ~b, ~c, ~d, ~m, ~p, ~q], ~x) && LinearQ([~u, ~v], ~x)
    @apply_utils Antiderivative(log(~(d') * (~e + ~(f') * (~x) ^ ~(m')) ^ ~(r')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => With([u = IntHide(log(~d * (~e + ~f * (~x) ^ ~m) ^ ~r), ~x)], Dist((~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, u, ~x) - ~b * ~n * ~p * Antiderivative(Dist((~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p - 1) / ~x, u, ~x), ~x)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~r, ~m, ~n], ~x) && (IGtQ(~p, 0) && (RationalQ(~m) && (EqQ(~p, 1) || (FractionQ(~m) && IntegerQ(1 / ~m) || EqQ(~r, 1) && (EqQ(~m, 1) && EqQ(~d * ~e, 1))))))
    @apply_utils Antiderivative(log(~(d') * (~e + ~(f') * (~x) ^ ~(m')) ^ ~(r')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => With([u = IntHide((~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x)], Dist(log(~d * (~e + ~f * (~x) ^ ~m) ^ ~r), u, ~x) - ~f * ~m * ~r * Antiderivative(Dist((~x) ^ (~m - 1) / (~e + ~f * (~x) ^ ~m), u, ~x), ~x)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~r, ~m, ~n], ~x) && (IGtQ(~p, 0) && IntegerQ(~m))
    @apply_utils Antiderivative(log(~(d') * (~e + ~(f') * (~x) ^ ~(m')) ^ ~(r')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => Unintegrable(log(~d * (~e + ~f * (~x) ^ ~m) ^ ~r) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~r, ~m, ~n, ~p], ~x)
    @apply_utils Antiderivative(log(~(d') * (~u) ^ ~(r')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => Antiderivative(log(~d * ExpandToSum(~u, ~x) ^ ~r) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~r, ~n, ~p], ~x) && (BinomialQ(~u, ~x) && Not(BinomialMatchQ(~u, ~x)))
    @apply_utils Antiderivative((log(~(d') * (~e + ~(f') * (~x) ^ ~(m'))) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p')) / ~x, ~x) => (-(PolyLog(2, -(~d) * ~f * (~x) ^ ~m)) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p) / ~m + ((~b * ~n * ~p) / ~m) * Antiderivative((PolyLog(2, -(~d) * ~f * (~x) ^ ~m) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p - 1)) / ~x, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n], ~x) && (IGtQ(~p, 0) && EqQ(~d * ~e, 1))
    @apply_utils Antiderivative((log(~(d') * (~e + ~(f') * (~x) ^ ~(m')) ^ ~(r')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p')) / ~x, ~x) => (log(~d * (~e + ~f * (~x) ^ ~m) ^ ~r) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p + 1)) / (~b * ~n * (~p + 1)) - ((~f * ~m * ~r) / (~b * ~n * (~p + 1))) * Antiderivative(((~x) ^ (~m - 1) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p + 1)) / (~e + ~f * (~x) ^ ~m), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~r, ~m, ~n], ~x) && (IGtQ(~p, 0) && NeQ(~d * ~e, 1))
    @apply_utils Antiderivative((~(g') * ~x) ^ ~(q') * log(~(d') * (~e + ~(f') * (~x) ^ ~(m')) ^ ~(r')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => With([u = IntHide((~g * ~x) ^ ~q * log(~d * (~e + ~f * (~x) ^ ~m) ^ ~r), ~x)], Dist(~a + ~b * log(~c * (~x) ^ ~n), u, ~x) - ~b * ~n * Antiderivative(Dist(1 / ~x, u, ~x), ~x)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~r, ~m, ~n, ~q], ~x) && ((IntegerQ((~q + 1) / ~m) || RationalQ(~m) && RationalQ(~q)) && NeQ(~q, -1))
    @apply_utils Antiderivative((~(g') * ~x) ^ ~(q') * log(~(d') * (~e + ~(f') * (~x) ^ ~(m'))) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => With([u = IntHide((~g * ~x) ^ ~q * log(~d * (~e + ~f * (~x) ^ ~m)), ~x)], Dist((~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, u, ~x) - ~b * ~n * ~p * Antiderivative(Dist((~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p - 1) / ~x, u, ~x), ~x)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~m, ~n, ~q], ~x) && (IGtQ(~p, 0) && (RationalQ(~m) && (RationalQ(~q) && (NeQ(~q, -1) && (EqQ(~p, 1) || (FractionQ(~m) && IntegerQ((~q + 1) / ~m) || IGtQ(~q, 0) && (IntegerQ((~q + 1) / ~m) && EqQ(~d * ~e, 1))))))))
    @apply_utils Antiderivative((~(g') * ~x) ^ ~(q') * log(~(d') * (~e + ~(f') * (~x) ^ ~(m')) ^ ~(r')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => With([u = IntHide((~g * ~x) ^ ~q * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x)], Dist(log(~d * (~e + ~f * (~x) ^ ~m) ^ ~r), u, ~x) - ~f * ~m * ~r * Antiderivative(Dist((~x) ^ (~m - 1) / (~e + ~f * (~x) ^ ~m), u, ~x), ~x)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~r, ~m, ~n, ~q], ~x) && (IGtQ(~p, 0) && (RationalQ(~m) && RationalQ(~q)))
    @apply_utils Antiderivative((~(g') * ~x) ^ ~(q') * log(~(d') * (~e + ~(f') * (~x) ^ ~(m')) ^ ~(r')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => Unintegrable((~g * ~x) ^ ~q * log(~d * (~e + ~f * (~x) ^ ~m) ^ ~r) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~r, ~m, ~n, ~p, ~q], ~x)
    @apply_utils Antiderivative((~(g') * ~x) ^ ~(q') * log(~(d') * (~u) ^ ~(r')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => Antiderivative((~g * ~x) ^ ~q * log(~d * ExpandToSum(~u, ~x) ^ ~r) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~g, ~r, ~n, ~p, ~q], ~x) && (BinomialQ(~u, ~x) && Not(BinomialMatchQ(~u, ~x)))
    @apply_utils Antiderivative(PolyLog(~k, ~(e') * (~x) ^ ~(q')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => (-(~b) * ~n * ~x * PolyLog(~k, ~e * (~x) ^ ~q) + ~x * PolyLog(~k, ~e * (~x) ^ ~q) * (~a + ~b * log(~c * (~x) ^ ~n)) + ~b * ~n * ~q * Antiderivative(PolyLog(~k - 1, ~e * (~x) ^ ~q), ~x)) - ~q * Antiderivative(PolyLog(~k - 1, ~e * (~x) ^ ~q) * (~a + ~b * log(~c * (~x) ^ ~n)), ~x) <-- FreeQ([~a, ~b, ~c, ~e, ~n, ~q], ~x) && IGtQ(~k, 0)
    @apply_utils Antiderivative(PolyLog(~k, ~(e') * (~x) ^ ~(q')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => Unintegrable(PolyLog(~k, ~e * (~x) ^ ~q) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~e, ~n, ~p, ~q], ~x)
    @apply_utils Antiderivative((PolyLog(~k, ~(e') * (~x) ^ ~(q')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p')) / ~x, ~x) => (PolyLog(~k + 1, ~e * (~x) ^ ~q) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p) / ~q - ((~b * ~n * ~p) / ~q) * Antiderivative((PolyLog(~k + 1, ~e * (~x) ^ ~q) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p - 1)) / ~x, ~x) <-- FreeQ([~a, ~b, ~c, ~e, ~k, ~n, ~q], ~x) && GtQ(~p, 0)
    @apply_utils Antiderivative((PolyLog(~k, ~(e') * (~x) ^ ~(q')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p')) / ~x, ~x) => (PolyLog(~k, ~e * (~x) ^ ~q) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p + 1)) / (~b * ~n * (~p + 1)) - (~q / (~b * ~n * (~p + 1))) * Antiderivative((PolyLog(~k - 1, ~e * (~x) ^ ~q) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ (~p + 1)) / ~x, ~x) <-- FreeQ([~a, ~b, ~c, ~e, ~k, ~n, ~q], ~x) && LtQ(~p, -1)
    @apply_utils Antiderivative((~(d') * ~x) ^ ~(m') * PolyLog(~k, ~(e') * (~x) ^ ~(q')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => ((-(~b) * ~n * (~d * ~x) ^ (~m + 1) * PolyLog(~k, ~e * (~x) ^ ~q)) / (~d * (~m + 1) ^ 2) + ((~d * ~x) ^ (~m + 1) * PolyLog(~k, ~e * (~x) ^ ~q) * (~a + ~b * log(~c * (~x) ^ ~n))) / (~d * (~m + 1)) + ((~b * ~n * ~q) / (~m + 1) ^ 2) * Antiderivative((~d * ~x) ^ ~m * PolyLog(~k - 1, ~e * (~x) ^ ~q), ~x)) - (~q / (~m + 1)) * Antiderivative((~d * ~x) ^ ~m * PolyLog(~k - 1, ~e * (~x) ^ ~q) * (~a + ~b * log(~c * (~x) ^ ~n)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~m, ~n, ~q], ~x) && IGtQ(~k, 0)
    @apply_utils Antiderivative((~(d') * ~x) ^ ~(m') * PolyLog(~k, ~(e') * (~x) ^ ~(q')) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ ~(p'), ~x) => Unintegrable((~d * ~x) ^ ~m * PolyLog(~k, ~e * (~x) ^ ~q) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~m, ~n, ~p, ~q], ~x)
    @apply_utils Antiderivative(~(Px') * (~F)(~(d') * (~(e') + ~(f') * ~x)) ^ ~(m') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => With([u = IntHide(~Px * (~F)(~d * (~e + ~f * ~x)) ^ ~m, ~x)], Dist(~a + ~b * log(~c * (~x) ^ ~n), u, ~x) - ~b * ~n * Antiderivative(Dist(1 / ~x, u, ~x), ~x)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~n], ~x) && (PolynomialQ(~Px, ~x) && (IGtQ(~m, 0) && MemberQ([asin, acos, asinh, acosh], ~F)))
    @apply_utils Antiderivative(~(Px') * (~F)(~(d') * (~(e') + ~(f') * ~x)) * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))), ~x) => With([u = IntHide(~Px * (~F)(~d * (~e + ~f * ~x)), ~x)], Dist(~a + ~b * log(~c * (~x) ^ ~n), u, ~x) - ~b * ~n * Antiderivative(Dist(1 / ~x, u, ~x), ~x)) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~n], ~x) && (PolynomialQ(~Px, ~x) && MemberQ([atan, acot, atanh, acoth], ~F))
end

max_stars_repo_path: src/rules/3 Logarithms/3.1.5 u (a+b log(c x^n))^p.jl


text:
# %% Scheduler tests
@testset "Standard Scheduler" begin
    N = 1000

    # by_id
    model = ABM(Agent0; scheduler = by_id)
    for i in 1:N
        add_agent!(model)
    end
    @test sort!(collect(keys(model.agents))) == 1:N
    @test model.scheduler(model) == 1:N

    # fastest
    Random.seed!(12)
    model = ABM(Agent0; scheduler = fastest)
    for i in 1:N
        add_agent!(model)
    end
    @test sort!(collect(model.scheduler(model))) == 1:N

    # random
    Random.seed!(12)
    model = ABM(Agent0; scheduler = random_activation)
    for i in 1:N
        add_agent!(model)
    end
    @test model.scheduler(model)[1:3] == [913, 522, 637] # reproducibility test

    # partial
    Random.seed!(12)
    model = ABM(Agent0; scheduler = partial_activation(0.1))
    for i in 1:N
        add_agent!(model)
    end

    a = model.scheduler(model)
    @test length(a) < N
    @test a[1] == 74 # reproducibility test

    # by property
    model = ABM(Agent2; scheduler = property_activation(:weight))
    for i in 1:N
        add_agent!(model, rand() / rand())
    end

    Random.seed!(12)
    a = model.scheduler(model)

    ids = collect(keys(model.agents))
    properties = [model.agents[id].weight for id in ids]

    @test ids[sortperm(properties)] == a
end

@testset "Union Types" begin
    @test Agents.union_types(Union{Agent0}) == (Agent0,)
    @test Agents.union_types(Union{Agent0,Agent1}) == (Agent0, Agent1)
    @test Agents.union_types(Union{Agent0,Agent1,Agent2,Agent3}) ==
          (Agent0, Agent1, Agent2, Agent3)
    #Union types are not order preserving
    @test Agents.union_types(Union{Agent1,Agent0}) == (Agent0, Agent1)
    @test Agents.union_types(Union{Agent1,Agent3,Agent2,Agent0}) ==
          (Agent0, Agent1, Agent2, Agent3)
end

# Mixed model
function init_mixed_model(; scheduler = fastest)
    model = ABM(Union{Agent0,Agent1,Agent2,Agent3}, scheduler = scheduler, warn = false)
    for id in 1:20
        choice = rand(0:3)
        if choice == 0
            a0 = Agent0(id)
            add_agent!(a0, model)
        elseif choice == 1
            a1 = Agent1(id, (0, 0))
            add_agent!(a1, model)
        elseif choice == 2
            a2 = Agent2(id, 5.0)
            add_agent!(a2, model)
        elseif choice == 3
            a3 = Agent3(id, (0, 0), 5.0)
            add_agent!(a3, model)
        end
    end
    return model
end

@testset "Mixed Scheduler" begin
    # Type shuffles
    model = init_mixed_model()
    @test sort!(collect(model.scheduler(model))) == 1:20

    Random.seed!(12)
    model = init_mixed_model(scheduler = by_type(false, false))
    @test [typeof(model[id]) for id in model.scheduler(model)] == [
        Agent0,
        Agent0,
        Agent0,
        Agent0,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
        Agent3,
        Agent3,
        Agent3,
    ]
    @test model.scheduler(model)[1:3] == [18, 7, 10]
    @test count(a -> a == Agent2, typeof(model[id]) for id in model.scheduler(model)) == 6

    Random.seed!(13)
    model = init_mixed_model(scheduler = by_type(true, false))
    @test [typeof(model[id]) for id in model.scheduler(model)] == [
        Agent3,
        Agent3,
        Agent3,
        Agent3,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent0,
        Agent0,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
    ]
    @test model.scheduler(model)[1:3] == [2, 16, 10]
    @test count(a -> a == Agent2, typeof(model[id]) for id in model.scheduler(model)) == 7

    # Offset union order and ids
    Random.seed!(833)
    model = ABM(Union{Agent0,Agent1}, scheduler = by_type(false, false), warn = false)
    for id in 1:3
        a1 = Agent1(id, (0, 0))
        add_agent!(a1, model)
    end
    for id in 4:6
        a0 = Agent0(id)
        add_agent!(a0, model)
    end
    @test [typeof(model[id]) for id in model.scheduler(model)] ==
          [Agent0, Agent0, Agent0, Agent1, Agent1, Agent1]

    Random.seed!(833)
    model = ABM(
        Union{Agent1,Agent0},
        scheduler = by_type((Agent1, Agent0), false),
        warn = false,
    )
    for id in 1:3
        a1 = Agent1(id, (0, 0))
        add_agent!(a1, model)
    end
    for id in 4:6
        a0 = Agent0(id)
        add_agent!(a0, model)
    end
    @test [typeof(model[id]) for id in model.scheduler(model)] ==
          [Agent1, Agent1, Agent1, Agent0, Agent0, Agent0]
    @test model.scheduler(model) == [2, 3, 1, 4, 5, 6]

    # Agent shuffles
    Random.seed!(12)
    # Same seed as before, should be shuffled.
    model = init_mixed_model(scheduler = by_type(false, true))
    @test [typeof(model[id]) for id in model.scheduler(model)] == [
        Agent0,
        Agent0,
        Agent0,
        Agent0,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
        Agent3,
        Agent3,
        Agent3,
    ]
    @test model.scheduler(model)[1:3] != [18, 7, 10]
    # Shoul still be grouped correctly.

    Random.seed!(13)
    # Shuffle both type and agents
    model = init_mixed_model(scheduler = by_type(true, true))
    # Type order expected to be out of order, but the same as above due to seed
    @test [typeof(model[id]) for id in model.scheduler(model)] == [
        Agent3,
        Agent3,
        Agent3,
        Agent3,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent1,
        Agent0,
        Agent0,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
        Agent2,
    ]
    # Agent order expected to be different
    @test model.scheduler(model)[1:3] != [7, 9, 14]

    Random.seed!(833)
    model =
        ABM(Union{Agent1,Agent0}, scheduler = by_type((Agent1, Agent0), true), warn = false)
    for id in 1:3
        a1 = Agent1(id, (0, 0))
        add_agent!(a1, model)
    end
    for id in 4:6
        a0 = Agent0(id)
        add_agent!(a0, model)
    end
    @test [typeof(model[id]) for id in model.scheduler(model)] ==
          [Agent1, Agent1, Agent1, Agent0, Agent0, Agent0]
    @test model.scheduler(model) == [3, 2, 1, 4, 6, 5]
end

ext: jl


text:
# heuristic container
type DiscoveryHeuristic <: Policy
    probing::Policy
    guess::Policy
end
function action(pomdp::CommunityAffiliationPOMDP, p::DiscoveryHeuristic, b::Belief, act=create_action(pomdp))
    if b.budget > 0
        return action(pomdp, p.probing, b)
    else
        return action(pomdp, p.guess, b)
    end
end

# probing heuristics
type ProbeHighestDegree <: Policy
    target_first::Bool
end
ProbeHighestDegree() = ProbeHighestDegree(false)
function action(pomdp::CommunityAffiliationPOMDP, p::ProbeHighestDegree, b::RevealedGraph, a::ProbeNode=ProbeNode())
    if p.target_first && !(pomdp.node in b.probed)
        a.node = pomdp.node
    else
        node_vector = collect(setdiff(b.revealed_nodes, b.probed))
        a.node = node_vector[indmax([degree(b,n) for n in node_vector])]
    end
    return a
end

# guessing heuristic
type GuessBasedOnNeighbors <: Policy
    rng::AbstractRNG
end
function action(pomdp::CommunityAffiliationPOMDP, p::GuessBasedOnNeighbors, b::RevealedGraph, a::GuessAffiliation=GuessAffiliation())
    # guess neighbors affiliation
    ns = neighbors(b, pomdp.node)
    labels = Array(Int, length(ns))
    guessed = zeros(Bool, length(ns))
    for i in 1:length(ns)
        if haskey(b.known_labels, ns[i])
            labels[i] = b.known_labels[ns[i]]
            guessed[i] = true
        else
            label_sums = zeros(Int, pomdp.true_network.n_comms)
            nns = neighbors(b, ns[i])
            for n in nns
                if haskey(b.known_labels, n)
                    label_sums[b.known_labels[n]] += 1
                end
            end
            maxcount = maximum(label_sums)
            if maxcount > 0
                guessed[i] = true
                cand = find(x->(x==maxcount), label_sums)
                labels[i] = cand[ceil(rand(p.rng)*length(cand))]
            end
        end
    end
    if any(guessed)
        bins,counts = hist(labels[guessed], 0:pomdp.true_network.n_comms)
        # assert bins == 1:pomdp.n_comms
        maxcount = maximum(counts)
        cand = find(x->(x==maxcount), counts)
        a.community = cand[ceil(rand(p.rng)*length(cand))]
    else
        a.community = ceil(rand(p.rng)*pomdp.true_network.n_comms)
    end
    return a
end


text:
# Compute densities of states

# IDOS (integrated density of states)
# N(ε) = sum_n f_n = sum_n f((εn-ε)/temperature)
# DOS (density of states)
# D(ε) = N'(ε)
# LDOS (local density of states)
# LD = sum_n f_n ψn

"""
Total density of states at energy ε
"""
function compute_dos(ε, basis, eigenvalues; smearing=basis.model.smearing,
                     temperature=basis.model.temperature)
    if (temperature == 0) || smearing isa Smearing.None
        error("compute_dos only supports finite temperature")
    end
    filled_occ = filled_occupation(basis.model)

    D = zeros(typeof(ε), basis.model.n_spin_components)
    for σ in 1:basis.model.n_spin_components, ik = krange_spin(basis, σ)
        for (iband, εnk) in enumerate(eigenvalues[ik])
            enred = (εnk - ε) / temperature
            D[σ] -= (filled_occ * basis.kweights[ik] / temperature
                     * Smearing.occupation_derivative(smearing, enred))
        end
    end
    D = mpi_sum(D, basis.comm_kpts)
end

"""
Local density of states, in real space
"""
function compute_ldos(ε, basis, eigenvalues, ψ; smearing=basis.model.smearing,
                      temperature=basis.model.temperature)
    if (temperature == 0) || smearing isa Smearing.None
        error("compute_ldos only supports finite temperature")
    end
    filled_occ = filled_occupation(basis.model)

    weights = deepcopy(eigenvalues)
    for (ik, εk) in enumerate(eigenvalues)
        for (iband, εnk) in enumerate(εk)
            enred = (εnk - ε) / temperature
            weights[ik][iband] = (-filled_occ / temperature
                                  * Smearing.occupation_derivative(smearing, enred))
        end
    end

    # Use compute_density routine to compute LDOS, using just the modified
    # weights (as "occupations") at each k-point. Note, that this automatically puts in the
    # required symmetrization with respect to kpoints and BZ symmetry
    compute_density(basis, ψ, weights)
end

"""
Plot the density of states over a reasonable range
"""
function plot_dos end


text:
@doc raw"""
    soft_threshold(X, γ)

Soft thresholding `X` with threshold `γ` using `sign(X) * max(abs(X) - γ, 0)`. Broadcasting is applied
when necessarily.

# Examples

`soft_threshold(X, 1/λ)` is the solution to the simplified lasso problem:

```math
    \min_d \lvert d \rvert + \frac{\lambda}{2} \lVert d - X \rVert^2_2
```

# References

[1] Goldstein, T., & Osher, S. (2009). The split Bregman method for L1-regularized problems. _SIAM journal on imaging sciences_, 2(2), 323-343.

[2] Wikipedia contributors. (2020, July 15). Lasso (statistics). In _Wikipedia, The Free Encyclopedia_. Retrieved 10:40, August 21, 2020, from https://en.wikipedia.org/w/index.php?title=Lasso_(statistics)&oldid=967820964

"""
soft_threshold(X, γ) = soft_threshold.(X, γ)
soft_threshold(x::T, γ::Number) where T <: Number = sign(x) * max(abs(x) - _maybe_promote(T, γ), zero(T))
# TODO: for cases that x is positve, max(x - γ, 0) is slightly faster

_maybe_promote(::Type{T}, x) where T = convert(T, x)
_maybe_promote(::Type{T1}, x::T2) where {T1 <: Union{Bool,Integer},T2} = promote_type(T1, T2)(x)

# optimized for memory
function mean2!(out::AbstractVector, m::AbstractMatrix)
    @assert length(out) == size(m, 1)
    fill!(out, zero(eltype(out)))
    @inbounds for i in axes(m, 1)
        rst = out[i]
        @simd for j in axes(m, 2)
            rst += m[i, j]
        end
        out[i] = rst / size(m, 2)
    end
    return out
end

# Copy from BlockMatching with extra `dist_buffer` input to reuse the memory
function multi_match(S::FullSearch, ref, frame, p::CartesianIndex, dist_buffer; num_patches)
    rₚ = S.patch_radius
    R_frame = CartesianIndices(frame)
    R_frame = first(R_frame) + rₚ : last(R_frame) - rₚ
    p in R_frame || throw(ArgumentError("Boundary unsupported now: pixel `p = $p` should be within $(first(R_frame)):$(last(R_frame))."))

    R_ref = CartesianIndices(ref)
    R_ref = first(R_ref) + rₚ : last(R_ref) - rₚ
    q_start = max(first(R_ref), p - S.search_radius)
    q_stop = min(last(R_ref), p + S.search_radius)
    candidates = q_start:S.search_stride:q_stop

    # For performance, we do not need to compare the dense patch to do block matching
    Δ = CartesianIndex(2, 2)
    patch_p = frame[p - rₚ:Δ:p + rₚ]
    @assert length(dist_buffer) >= length(candidates)
    dist = dist_buffer
    @inbounds for i in 1:length(candidates)
        q = candidates[i]
        patch_q = @view ref[q - rₚ:Δ:q + rₚ]
        dist[i] = S.f(patch_p, patch_q)
    end

    indices = partialsortperm(view(dist, 1:length(candidates)), 1:num_patches)
    candidates[indices]
end

# Threads helper

function with_blas_threads(f, num_threads)
    prev_num_threads = BLAS.get_num_threads()
    prev_num_threads = isnothing(prev_num_threads) ? 1 : prev_num_threads
    BLAS.set_num_threads(num_threads)
    retval = nothing
    try
        retval = f()
    catch err
        rethrow(err)
    finally
        BLAS.set_num_threads(prev_num_threads)
    end

    return retval
end


text:
@testset "Genus" begin
  Qx, x = FlintQQ["x"]
  K, a = NumberField(x - 1, "a", cached = false)
  OK = maximal_order(K)
  rlp = real_places(K)
  sig = Dict(rlp[1] => 2)

  p2 = prime_decomposition(OK, 2)[1][1]
  p3 = prime_decomposition(OK, 3)[1][1]
  p5 = prime_decomposition(OK, 5)[1][1]

  @test length(Hecke.local_genera_quadratic(K, p2, rank = 2, det_val = 0)) == 8
  @test length(Hecke.local_genera_quadratic(K, p2, rank = 2, det_val = 1)) == 8
  @test length(Hecke.local_genera_quadratic(K, p2, rank = 2, det_val = 2)) == 16
  @test length(Hecke.local_genera_quadratic(K, p2, rank = 2, det_val = 3)) == 24
  @test length(Hecke.local_genera_quadratic(K, p2, rank = 2, det_val = 4)) == 32

  @test length(Hecke.local_genera_quadratic(K, p3, rank = 5, det_val = 0)) == 2
  @test length(Hecke.local_genera_quadratic(K, p3, rank = 5, det_val = 1)) == 4
  @test length(Hecke.local_genera_quadratic(K, p3, rank = 5, det_val = 2)) == 8
  @test length(Hecke.local_genera_quadratic(K, p3, rank = 5, det_val = 3)) == 16
  @test length(Hecke.local_genera_quadratic(K, p3, rank = 5, det_val = 4)) == 28
  @test length(Hecke.local_genera_quadratic(K, p3, rank = 5, det_val = 5)) == 46
  @test length(Hecke.local_genera_quadratic(K, p3, rank = 5, det_val = 6)) == 72

  @test length(Hecke.local_genera_quadratic(K, p5, rank = 4, det_val = 2)) == 8
  @test length(Hecke.local_genera_quadratic(K, p5, rank = 4, det_val = 1)) == 4
  @test length(Hecke.local_genera_quadratic(K, p5, rank = 2, det_val = 0)) == 2
  @test length(Hecke.local_genera_quadratic(K, p5, rank = 2, det_val = 1)) == 4

  @test length(Hecke.genera_quadratic(K, rank = 2, signatures = sig, det = 5^2 * 8 * 9 * OK)) == 27
  @test length(Hecke.genera_quadratic(K, rank = 2, signatures = sig, det = 5 * 7 * 8 * 9 * OK)) == 36
  @test length(Hecke.genera_quadratic(K, rank = 2, signatures = sig, det = 2^5 * OK)) == 5
  @test length(Hecke.genera_quadratic(K, rank = 2, signatures = sig, det = 11 * 13^2 * OK)) == 6

  G1 = Hecke.local_genera_quadratic(K, p3, rank = 3, det_val = 1)[4]
  G1a = Hecke.local_genera_quadratic(K, p3, rank = 3, det_val = 1)[4]
  G1a.uniformizer = 4*G1.uniformizer
  @test G1 == G1a
  @test G1+G1a == G1+G1
  G2 = Hecke.local_genera_quadratic(K, p3, rank = 3, det_val = 1)[4]
  G2.uniformizer = -G2.uniformizer
  @test G2 != G1
  @test G2 != G1a

  # test representative and orthogonal_sum

  G = Hecke.local_genera_quadratic(K, p2, rank = 3, det_val = 4)
  for i in 1:10
    G1 = rand(G)
    G2 = rand(G)
    L1 = representative(G1)
    @test L1 in G1
    L2 = representative(G2)
    G3 = @inferred orthogonal_sum(G1, G2)
    L3, = orthogonal_sum(L1, L2)
    @test G3 == genus(L3, p2)
    @test genus(L1,p2) + genus(QuadLat,p2) == G1
  end
  @test sprint(show, G[1]) isa String
  @test sprint(show, "text/plain", G[1]) isa String

  G = Hecke.local_genera_quadratic(K, p2, rank = 3, det_val = 1)
  for i in 1:10
    G1 = rand(G)
    G2 = rand(G)
    L1 = representative(G1)
    L2 = representative(G2)
    G3 = @inferred orthogonal_sum(G1, G2)
    L3, = orthogonal_sum(L1, L2)
    @test G3 == genus(L3, p2)
  end

  G = Hecke.local_genera_quadratic(K, p2, rank = 5, det_val = 1)
  for i in 1:10
    G1 = rand(G)
    G2 = rand(G)
    L1 = representative(G1)
    @test L1 in G1
    L2 = representative(G2)
    G3 = @inferred orthogonal_sum(G1, G2)
    L3, = orthogonal_sum(L1, L2)
    @test G3 == genus(L3, p2)
  end

  G = Hecke.local_genera_quadratic(K, p3, rank = 5, det_val = 5)
  for i in 1:10
    G1 = rand(G)
    G2 = rand(G)
    L1 = representative(G1)
    L2 = representative(G2)
    G3 = @inferred orthogonal_sum(G1, G2)
    L3, = orthogonal_sum(L1, L2)
    @test G3 == genus(L3, p3)
    @test genus(L1,p3) + genus(QuadLat,p3) == G1
  end
  q = genus(QuadLat,p2)
  @test det(q) == 1
  @test rank(q) == 0
  @test hasse_invariant(q) == 1

  @test sprint(show, G[1]) isa String
  @test sprint(show, "text/plain", G[1]) isa String

  G = Hecke.local_genera_quadratic(K, p5, rank = 2, det_val = 1)
  for i in 1:10
    G1 = rand(G)
    G2 = rand(G)
    L1 = representative(G1)
    L2 = representative(G2)
    G3 = @inferred orthogonal_sum(G1, G2)
    L3, = orthogonal_sum(L1, L2)
    @test G3 == genus(L3, p5)
  end

  G = Hecke.genera_quadratic(K, rank = 3, signatures = sig, det = 2 * 9 * OK)
  for i in 1:10
    G1 = rand(G)
    G2 = rand(G)
    L1 = representative(G1)
    L2 = representative(G2)
    G3 = @inferred orthogonal_sum(G1, G2)
    L3, = orthogonal_sum(L1, L2)
    @test L3 in G3
  end

  Qx, x = PolynomialRing(FlintQQ, "x", cached = false)
  f = x - 1;
  K, a = number_field(f)
  D = matrix(K, 3, 3, [30, -15, 0, -15, 30, -15, 0, -15, 30]);
  gens = [[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [5//6, 2//3, 1//6], [5//6, 2//3, 1//6]]
  L = quadratic_lattice(K, gens, gram = D)
  p = prime_decomposition(maximal_order(K), 5)[1][1]
  fl, LL = Hecke.is_maximal_integral(L, p)
  @test !fl

  Qx, x = PolynomialRing(FlintQQ, "x", cached = false)
  f = x^2 - 2;
  K, a = number_field(f)
  p = prime_ideals_over(maximal_order(K),2)[1]
  D = matrix(K, 3, 3, [1//64, 0, 0, 0, 1//64, 0, 0, 0, 1//64]);
  gens = [[64, 0, 0], [248*a + 88, 0, 0], [32, 32, 0], [100*a + 136, 100*a + 136, 0], [32, 0, 32], [20*a + 136, 0, 20*a + 136]]
  L = quadratic_lattice(K, gens, gram = D)
  @test sprint(show, Hecke.JorDec(L, p)) isa String
  @test sprint(show,"text/plain" , Hecke.JorDec(L, p)) isa String
  @test sprint(show, genus(L, p)) isa String
  @test sprint(show, "text/plain", genus(L, p)) isa String

  R, x = PolynomialRing(QQ,:x)
  F,a = number_field(x^2-2,:a)
  OF = maximal_order(F)
  pl = real_places(F)
  p = prime_ideals_over(OF, 2)[1]
  p3 = prime_ideals_over(OF, 3)[1]

  # Test the computation of jordan decomposition
  G = Hecke.local_genera_quadratic(F, p, rank = 3, det_val = 2)
  for g in G
    g1 = genus(QuadLat, p, g.ranks, g.scales, g.weights, g.dets, g.normgens, g.witt)
    representative(g1) in G  # computes jordan decompositions
  end
  G = Hecke.local_genera_quadratic(F, p3, rank = 3, det_val = 2)
  for g in G
    g1 = genus(QuadLat, p3, g.uniformizer, g.ranks, g.scales, g.detclasses)
    representative(g1) in G  # computes jordan decompositions
  end

  sig = Dict([(pl[1],0),(pl[2],0)])
  for d in 1:(long_test ? 10 : 3)
    for G in Hecke.genera_quadratic(F,rank=2,det=d*OF,signatures=sig)
      @test representative(G) in G
    end
  end
  sig = Dict([(pl[1],3),(pl[2],2)])
  for d in 1:(long_test ? 10 : 3)
    for G in Hecke.genera_quadratic(F,rank=4,det=d*OF,signatures=sig)
      @test representative(G) in G
    end
  end

  R, x = PolynomialRing(QQ,:x)
  F,a = number_field(x^3+x+1,:a)
  OF = maximal_order(F)
  pl = real_places(F)
  sig = Dict([(pl[1],0)])
  for d in 1:(long_test ? 10 : 3)
    for G in Hecke.genera_quadratic(F,rank=2,det=d*OF,signatures=sig)
      @test representative(G) in G
    end
  end
  sig = Dict([(pl[1],3)])
  for d in 1:(long_test ? 10 : 3)
    for G in Hecke.genera_quadratic(F,rank=3,det=d*OF,signatures=sig)
      @test representative(G) in G
    end
  end
end


text:
const PRINT_COMPUTING = true

macro computing(ex, msgs...)
    msg_body = isempty(msgs) ? ex : msgs[1]
    msg = string(msg_body)
    if PRINT_COMPUTING
        return quote
            print("Computing " * $msg * "...")
            local time = @elapsed out = $(esc(ex))
            print("   Finished! (time: $(time)s)\n")
            out
        end
    end
    return esc(ex)
end

exponents_matrix(p) = reduce(hcat, exponent_vectors(p))

###############################################################################
#                             Array manipulations                             #
###############################################################################

anynonzero(A) = any((!iszero).(A))

function findfirstnonzero(A)
    return findfirst((!iszero), A)
end

function findpivotsof(W)
    # return findfirstnonzero.(eachrow(W)) ## it works just for matrices, code below is more generic.
    # return mapslices(findfirstnonzero, W, dims=collect(2:ndims(W)))
    return n -> findfirstnonzero.(eachslice(W, dims = n))
end

function nonzeroslicesof(A)
    # return n->vec(mapslices(anynonzero, M, dims=deleteat!(collect(1:ndims(M)),n)))
    return n -> anynonzero.(eachslice(A, dims = n))
end

function dropzeroslices(A)
    indices = nonzeroslicesof(A).(1:ndims(A))
    return A[indices...]
end

"""
$(SIGNATURES)

Given an array of rational numbers `A`, returns a multiple `λA` whose entries are all integers, where `λ=abs(lcm(denominator.(A)))` is the minimal integer with this property.
"""
function integermultiple end

function integermultiple!(A; dims)
    for a in eachslice(A; dims = dims)
        a .= integermultiple(a)
    end
    return Int.(A)
end

integermultiple(A; dims = nothing) =
    isnothing(dims) ? Int.(abs(lcm(denominator.(A))) .* A) : integermultiple!(copy(A); dims)

integermultiple(M::AbstractMatrix) = integermultiple(M, dims = 2)

# linearcombination(M) = sum(eachcol(M))
# linearcombination(A, range) = A * rand(range, size(A, 2), 1)

## Filtering real-positive elements from an array.
isrealof(rtol) = z -> abs(imag(z)) < rtol #
filter_real(A, rtol) = real.(filter(isrealof(rtol), A))
filter_positive(A, ispos_fun = _ispositive) = filter(ispos_fun, A)

function filter_realpositive(A, rtol::Real = 1e-7)
    if isempty(A)
        print("No filtering for empty arrays.\n")
        return A
    end
    # minimag, imin = findmin(abs.(imag.(out)))
    # print("Roots found!! Min image part: $(out[imin])\n")
    out = filter(_ispositive, filter_real(A, rtol))
    if isempty(out)
        print("No one is real and positive... Returning empty array.\n")
        return out
    end
    # print("Real positive found!!\n")
    return out
end

## TODO From Polymake matrices to Juila arrays
## Type T in @convert_to macro!!
# function convert_to_matrix(M::Polymake.Matrix, ::Type{T}=Int) where {T}
#     mat = Polymake.@convert_to Matrix{T} M
#     return T.(permutedims(Matrix(mat)))
# end

# function nonzero_minors(A, k)
#     row_indices = combinations(1:nrows(A), k)
#     col_indices = combinations(1:ncols(A), k)
#     mins = Vector{typeof((first(row_indices), first(col_indices)))}(undef, 0)
#     for ri in row_indices
#         for ci in col_indices
#             if !(iszero(det(A[ri, ci])))
#                 push!(mins, (ri, ci))
#             end
#         end
#     end
#     return mins
# end


text:
"""
    enum_vertices(bp::BilevelProblem, poly_lib)

Computes the extreme points of the dual polyhedron described
in `bp` using the `poly_lib` polyhedral solver (compliant with `Polyhedra`).
"""
enum_vertices(bp::BilevelProblem, poly_lib) = enum_vertices(bp.B, bp.H, bp.d, poly_lib)

"""
    enum_vertices(B, H, d, poly_lib)

Computes the extreme points of the dual polyhedron described
by `(B, H, d)` using the `poly_lib` polyhedral solver.
Returns a tuple `(V, F, k)` where:
- `V` is the vector of sub-problem results, each containing a vector of extremum points `(α, β)`
- `F` is a boolean indicating feasibility
- `k` is the first encountered infeasible sub-problem if relevant, 0 otherwise
"""
function enum_vertices(B, H, d, poly_lib)
    (ml, nl) = size(B)
    (mu, _) = size(H)
    m = JuMP.Model()
    # vertices contains for each sub-problem k a Vector of exremal points (α, β)
    vertices = Vector{Vector{Tuple{Vector{Float64}, Float64}}}(undef, mu)
    for k in 1:mu
        @variable(m, α[i = 1:ml] >= 0)
        @variable(m, β >= 0)
        @constraint(m, B' * α + β .* d .>= H[k,:])
        poly = Polyhedra.polyhedron(m, poly_lib)
        vk = Polyhedra.points(Polyhedra.vrep(poly))
        if isempty(vk) # no vertices == infeasible
            return (vertices, false, k)
        end
        vertices[k] = [(Float64.(v[1:ml]), Float64(v[end])) for v in vk]
    end
    return (vertices, true, 0)
end

function dual_polyhedron(B, d, H, k::Integer, xvar, vvar, A, G, q, b, δ::Real;
                         poly_lib::Polyhedra.Library, optimizer)
    x = JuMP.value.(xvar)
    v = JuMP.value.(vvar)
    nl = length(d)
    ml = size(B, 1)
    mu = size(H, 1)
    m = Model(optimizer)
    @variable(m, α[i=1:ml] >= 0)
    @variable(m, β >= 0)
    @constraint(m,
        cons[j=1:nl],
        sum(B[i,j] * α[i] for i in 1:ml) + d[j] * β ≥ H[k,j]
    )
    res = b - A * x
    @objective(m, Min, dot(α, res) + β * (dot(d, v) + δ))
    optimize!(m)
    # infeasible => no extreme point, the whole problem is infeasible
    if termination_status(m) == MOI.INFEASIBLE || termination_status(m) == MOI.INFEASIBLE_OR_UNBOUNDED
        return (:INFEASIBLE, nothing)
    end
    if JuMP.objective_value(m) <= q[k] - dot(G[k,:], x)
        return (:OPTIMAL, nothing)
    end
    points = Polyhedra.points(Polyhedra.vrep(Polyhedra.polyhedron(m, poly_lib)))
    vertices = map(points) do pvec
        alpha_vec = pvec[1:end-1]
        beta = pvec[end]
        (Float64.(alpha_vec), Float64(beta))
    end
    return (:VERTICES, vertices)
end


text:
module Vol

import LinearAlgebra

include("returns.jl")
include("ewma.jl")

end


text:
using Flux
using LinearAlgebra

abstract type AbstractLearningUpdate end
abstract type AbstractQLearning <: AbstractLearningUpdate end

struct QLearning{F} <: AbstractQLearning
    γ::Float32 # Discoount
    loss::F
end
QLearningHuberLoss(γ) = QLearning(Float32(γ), mean_huber_loss)

struct DoubleQLearning{F} <: AbstractQLearning
    γ::Float32
    loss::F
end
DoubleQLearningHuberLoss(γ) = DoubleQLearning(Float32(γ), mean_huber_loss)

include("loss.jl")

function update!(model,
                 lu::AbstractQLearning,
                 opt,
                 s_t,
                 a_t,
                 s_tp1,
                 r,
                 terminal,
                 target_model)

    local ℒ = 0.0f0
    ps = params(model)
    gs = gradient(ps) do
        ℒ = loss(lu, model, s_t, a_t, s_tp1, r, terminal, target_model)
    end
    Flux.Optimise.update!(opt, ps, gs)
    return UpdateState(ℒ, gs, ps, opt)
end

function update!(model,
                 lu::T,
                 opt,
                 s_t::Array{<:AbstractArray, 1},
                 a_t,
                 s_tp1::Array{<:AbstractArray, 1},
                 r,
                 terminal,
                 args...) where {T<:AbstractLearningUpdate}
    update!(model, lu, opt, cat(s_t...; dims=2), a_t, cat(s_tp1...; dims=2), r, terminal, args...)
end

# struct AuxTDLearning end

# struct AuxHordeQLearning{T<:AbstractQLearning} <: AbstractLearningUpdate
#     β::Float32
#     q_learning::T
#     td_learning::AuxHordeTDLearning
# end

# function update!(
#     model,
#     lu::AQL,
#     opt,
#     s_t::Array{<:AbstractFloat, 2},
#     a_t::Array{<:Integer, 1},
#     s_tp1::Array{<:AbstractFloat, 2},
#     r::Array{<:AbstractFloat, 1},
#     terminal,
#     target_model,
#     horde::RLCore.Horde) where {AQL<:AuxQLearning, H<:RLCore.Horde}

#     num_gvfs = length(horde)
#     ps = params(model)

#     ℒ = 0.0f0

#     gs = Flux.gradient(ps) do
#         ℒ_q = loss(lu.q_learning, (x)->model(x)[1:(end-num_gvfs), :], s_t, a_t, s_tp1, r, terminal, (x)->target_model(x)[1:(end-num_gvfs), :])
#         # @show ℒ_q
#         ℒ_td = loss(lu.td_learning, (x)->model(x)[(end-num_gvfs+1):end, :], s_t, a_t, s_tp1, r, terminal, (x)->target_model(x)[(end-num_gvfs+1):end, :], horde)
#         # @show ℒ_td
#         ℒ = ℒ_q  + lu.β*ℒ_td
#     end
#     Flux.Optimise.update!(opt, ps, gs)
#     return ℒ
# end

# function update!(
#     model,
#     lu::AuxQLearning,
#     opt,
#     s_t::Array{<:AbstractFloat, 2},
#     a_t::Array{<:Integer, 1},
#     s_tp1::Array{<:AbstractFloat, 2},
#     r::Array{<:AbstractFloat, 1},
#     terminal,
#     target_model,
#     horde::Nothing)
#     update!(model, lu.q_learning, opt, s_t, a_t, s_tp1, r, terminal, target_model)
# end


text:
cxx"""
#include <iostream>
#include "llvm/Support/raw_os_ostream.h"
using namespace llvm;
"""
function dumpLayout(d)
    ctx = pcpp"clang::ASTContext"(
        ccall((:getASTContext,libcxxffi),Ptr{Void},()))
    icxx"""
        raw_os_ostream OS(std::cout);
        $ctx->DumpRecordLayout(
            dyn_cast<clang::RecordDecl>($d),
            OS,
            false);
        OS.flush();
        (void) (std::cout << std::endl);
    """
end


text:
using Carrot
using Test
include("./bot/post_msg_tests.jl")
include("./forex/fetch_data_tests.jl")

@testset "launch" begin
    @test "batch bot" == Carrot.launch("batchBot")
    @test "forex predict" == Carrot.launch("forexPredict")
    @test "web" == Carrot.launch("web")
    @test "unknown" == Carrot.launch("balabala")
end

@testset "feature_mappings" begin
    @test Carrot.get_feature_mappings()["batchBot"] == 0
end


text:
#!/usr/bin/env julia

# CUDAdrv.jl version

using CUDAdrv

using Statistics
using Printf

const len = 1000
const ITERATIONS = 100

# TODO: api-trace shows some attribute fetches, where do they come from?

const dev = CuDevice(0)
const ctx = CuContext(dev)

const mod = CuModuleFile("cuda.ptx")
const fun = CuFunction(mod, "kernel_dummy")

function benchmark(gpu_buf)
    cudacall(fun, (CuPtr{Float32},), gpu_buf; threads=1)
    return
end

function main()
    cpu_time = Vector{Float64}(undef, ITERATIONS)
    gpu_time = Vector{Float64}(undef, ITERATIONS)

    gpu_buf = Mem.alloc(Mem.Device, len*sizeof(Float32))
    for i in 1:ITERATIONS
        i == ITERATIONS-4 && CUDAdrv.Profile.start()

        gpu_tic, gpu_toc = CuEvent(), CuEvent()

        cpu_tic = time_ns()
        record(gpu_tic)
        benchmark(gpu_buf)
        record(gpu_toc)
        synchronize(gpu_toc)
        cpu_toc = time_ns()

        cpu_time[i] = (cpu_toc-cpu_tic)/1000
        gpu_time[i] = CUDAdrv.elapsed(gpu_tic, gpu_toc)*1000000
    end
    CUDAdrv.Profile.stop()
    Mem.free(gpu_buf)

    popfirst!(cpu_time)
    popfirst!(gpu_time)

    @printf("CPU time: %.2f ± %.2f us\n", mean(cpu_time), std(cpu_time))
    @printf("GPU time: %.2f ± %.2f us\n", mean(gpu_time), std(gpu_time))

    destroy!(ctx)
end

main()


text:
using SPADL
using Test

@testset "SPADL.jl" begin
    # Write your tests here.
end


text:
# Run with
#   time julia --project=. make.jl && julia --project=. -e 'using LiveServer; serve(dir="build")'
# assuming you are in this `docs` directory (otherwise point the project argument here)

using Documenter, SphericalFunctions

DocMeta.setdocmeta!(SphericalFunctions, :DocTestSetup, :(using SphericalFunctions); recursive=true)

makedocs(
    sitename="SphericalFunctions.jl",
    modules = [SphericalFunctions],
    format = Documenter.HTML(
        prettyurls = !("local" in ARGS),  # Use clean URLs, unless built as a "local" build
        edit_link = "main",  # Link out to "main" branch on github
        canonical = "https://moble.github.io/SphericalFunctions.jl/stable/",
    ),
    pages = [
        "Introduction" => "index.md",
        "Primary functions" => "manual.md",
        "Utilities" => "utilities.md",
        "Notes" => map(
            s -> "notes/$(s)",
            sort(readdir(joinpath(@__DIR__, "src/notes")))
        ),
    ],
    #doctest = false
)

deploydocs(
    repo="github.com/moble/SphericalFunctions.jl.git",
    devbranch="main"
)


text:
# Very basic setup, useful for testing
using DFTK
using LinearAlgebra
using BenchmarkTools

a = 10.26  # Silicon lattice constant in Bohr
lattice = a / 2 * [[0 1 1.];
                   [1 0 1.];
                   [1 1 0.]]
Si = ElementPsp(:Si, psp=load_psp("hgh/lda/Si-q4"))
atoms = [Si => [ones(3)/8, -ones(3)/8]]

model = model_LDA(lattice, atoms)
kgrid = [1, 1, 1]  # k-point grid (Regular Monkhorst-Pack grid)
Ecut = 15          # kinetic energy cutoff in Hartree -- can increase to make G_vectors larger (larger solve time)
basis = PlaneWaveBasis(model, Ecut; kgrid=kgrid)

@time scfres = self_consistent_field(basis, tol=1e-8) # 75.068789 seconds (138.55 M allocations: 8.145 GiB, 4.59% gc time, 24.68% compilation time)

# TODO try to rewrite for Zygote
# e.g. translate loops to dense arrays or maps (?)

function kinetic_energy(lattice, basis, ψ, occ)
    recip_lattice = 2π * inv(lattice')
    E = zero(Float64)
    kinetic_energies = [[sum(abs2, recip_lattice * (G + kpt.coordinate)) / 2
                         for G in  G_vectors(kpt)]
                        for kpt in basis.kpoints]
    for (ik, k) in enumerate(basis.kpoints)
        for iband = 1:size(ψ[1], 2)
            ψnk = @views ψ[ik][:, iband]
            E += (basis.kweights[ik] * occ[ik][iband]
                  * real(dot(ψnk, kinetic_energies[ik] .* ψnk)))
        end
    end
    E
end
kinetic_energy(lattice) = kinetic_energy(lattice, basis, scfres.ψ, scfres.occupation)

@time E = kinetic_energy(lattice)
@btime kinetic_energy(lattice) # 648.802 μs (7590 allocations: 1.67 MiB)

# stress := diff E wrt lattice

#===#
# Check results and compile times on first call
stresses = Dict()

# works fine
using ForwardDiff
@time stresses[:ForwardDiff] = ForwardDiff.gradient(kinetic_energy, lattice) # 3.627630 seconds (5.99 M allocations: 363.981 MiB, 5.08% gc time, 98.69% compilation time)

# works but long compile time and gives ComplexF64 results
# hypothesis: slow compilation due to loop (and generator) unrolling
using Zygote
@time stresses[:Zygote] = Zygote.gradient(kinetic_energy, lattice) # 61.094425 seconds (63.31 M allocations: 3.715 GiB, 3.85% gc time, 67.43% compilation time)

# works fine
using ReverseDiff
@time stresses[:ReverseDiff] = ReverseDiff.gradient(kinetic_energy, lattice) # 5.409118 seconds (9.60 M allocations: 516.091 MiB, 14.61% gc time, 89.56% compilation time)

# sanity check
using FiniteDiff
@time stresses[:FiniteDiff] = FiniteDiff.finite_difference_gradient(kinetic_energy, lattice) # 2.606210 seconds (2.87 M allocations: 232.911 MiB, 19.92% gc time, 99.19% compilation time)

stresses
# Dict{Any, Any} with 4 entries:
#   :ForwardDiff => [0.206717 -0.207215 -0.207228; -0.198914 0.209309 -0.20982; -0.197421 -0.208313 0.207815]
#   :FiniteDiff  => [0.206717 -0.207215 -0.207228; -0.198914 0.209309 -0.20982; -0.197421 -0.208313 0.207815]
#   :Zygote      => (ComplexF64[0.206717+2.92541e-19im -0.207215-1.57175e-19im -0.207228-7.86273e-19im; -0.198914+1.08911e-19im 0.209309+4.47104e-20im -0.20982-5.38442e-19im; -0.197421-6.72652e-19im -0.2…
#   :ReverseDiff => [0.206717 -0.207215 -0.207228; -0.198914 0.209309 -0.20982; -0.197421 -0.208313 0.207815]

@btime ForwardDiff.gradient(kinetic_energy, lattice) #   3.152 ms (   7681 allocations:  11.00 MiB)
@btime Zygote.gradient(kinetic_energy, lattice)      #  99.395 ms ( 358600 allocations: 129.91 MiB)
@btime ReverseDiff.gradient(kinetic_energy, lattice) # 278.207 ms (4301696 allocations: 158.10 MiB)
@btime FiniteDiff.finite_difference_gradient(kinetic_energy, lattice) # 10.901 ms (136658 allocations: 30.14 MiB)

max_stars_repo_name: niklasschmitz/DifferentiableDFTK

max_issues_repo_name: niklasschmitz/DifferentiableDFTK

max_forks_repo_name: niklasschmitz/DifferentiableDFTK


text:
Random.seed!(123)
stable_rng = StableRNGs.StableRNG(123)

rowvec(y) = y
rowvec(y::Vector) = reshape(y, 1, length(y))

@test MLJFlux.MLJModelInterface.istransparent(Flux.ADAM(0.1))

@testset "nrows" begin
    Xmatrix = rand(stable_rng, 10, 3)
    X = MLJBase.table(Xmatrix)
    @test MLJFlux.nrows(X) == 10
    @test MLJFlux.nrows(Tables.columntable(X)) == 10
end

@testset "collate" begin
    # NeuralNetworRegressor:
    Xmatrix = broadcast(x->round(x, sigdigits=2), rand(stable_rng, 10, 3))
    # convert to a column table:
    X = MLJBase.table(Xmatrix)

    y = rand(stable_rng, 10)
    model = MLJFlux.NeuralNetworkRegressor()
    model.batch_size= 3
    @test MLJFlux.collate(model, X, y) ==
        ([Xmatrix'[:,1:3], Xmatrix'[:,4:6], Xmatrix'[:,7:9], Xmatrix'[:,10:10]],
         rowvec.([y[1:3], y[4:6], y[7:9], y[10:10]]))

    # NeuralNetworClassifier:
    y = categorical(['a', 'b', 'a', 'a', 'b', 'a', 'a', 'a', 'b', 'a'])
    model = MLJFlux.NeuralNetworkClassifier()
    model.batch_size = 3
    data = MLJFlux.collate(model, X, y)

    @test data == ([Xmatrix'[:,1:3], Xmatrix'[:,4:6],
                    Xmatrix'[:,7:9], Xmatrix'[:,10:10]],
                   rowvec.([[1 0 1; 0 1 0], [1 0 1; 0 1 0], [1 1 0; 0 0 1],
                            reshape([1; 0], (2,1))]))

    # MultitargetNeuralNetworRegressor:
    ymatrix = rand(stable_rng, 10, 2)
    y = MLJBase.table(ymatrix) # a rowaccess table
    model = MLJFlux.NeuralNetworkRegressor()
    model.batch_size= 3
    @test MLJFlux.collate(model, X, y) ==
        ([Xmatrix'[:,1:3], Xmatrix'[:,4:6], Xmatrix'[:,7:9], Xmatrix'[:,10:10]],
         rowvec.([ymatrix'[:,1:3], ymatrix'[:,4:6], ymatrix'[:,7:9],
                  ymatrix'[:,10:10]]))

    y = Tables.columntable(y) # try a columnaccess table
    @test MLJFlux.collate(model, X, y) ==
        ([Xmatrix'[:,1:3], Xmatrix'[:,4:6], Xmatrix'[:,7:9], Xmatrix'[:,10:10]],
         rowvec.([ymatrix'[:,1:3], ymatrix'[:,4:6],
                  ymatrix'[:,7:9], ymatrix'[:,10:10]]))

    # ImageClassifier
    Xmatrix = coerce(rand(stable_rng, 6, 6, 1, 10), GrayImage)
    y = categorical(['a', 'b', 'a', 'a', 'b', 'a', 'a', 'a', 'b', 'a'])
    model = MLJFlux.ImageClassifier(batch_size=2)

    data = MLJFlux.collate(model, Xmatrix, y)
    @test  first.(data) == (Float32.(cat(Xmatrix[1], Xmatrix[2], dims=4)),
                            rowvec.([1 0;0 1]))

    expected_y = [[1 0;0 1], [1 1;0 0], [0 1; 1 0], [1 1;0 0], [0 1; 1 0]]
    for i=1:5
        @test Int.(last(data)[i]) == expected_y[i]
    end

end

Xmatrix = rand(stable_rng, 100, 5)
X = MLJBase.table(Xmatrix)
y = Xmatrix[:, 1] + Xmatrix[:, 2] + Xmatrix[:, 3] +
    Xmatrix[:, 4] + Xmatrix[:, 5]

data = [(Xmatrix'[:,1:20], y[1:20]),
        (Xmatrix'[:,21:40], y[21:40]),
        (Xmatrix'[:,41:60], y[41:60]),
        (Xmatrix'[:,61:80], y[61:80]),
        (Xmatrix'[:, 81:100], y[81:100])]

data = ([Xmatrix'[:,1:20], Xmatrix'[:,21:40], Xmatrix'[:,41:60],
         Xmatrix'[:,61:80], Xmatrix'[:,81:100]],
            rowvec.([y[1:20], y[21:40], y[41:60], y[61:80], y[81:100]]))

# construct two chains with identical state, except one has
# dropout and the other does not:
chain_yes_drop = Flux.Chain(Flux.Dense(5, 15),
                            Flux.Dropout(0.2),
                            Flux.Dense(15, 8),
                            Flux.Dense(8, 1))

model = MLJFlux.NeuralNetworkRegressor() # any model will do here

chain_no_drop = deepcopy(chain_yes_drop)
chain_no_drop.layers[2].p = 1.0

test_input = rand(stable_rng, Float32, 5, 1)

# check both chains have same behaviour before training:
@test chain_yes_drop(test_input) == chain_no_drop(test_input)

epochs = 10

@testset_accelerated "fit! and dropout" accel begin

    move = MLJFlux.Mover(accel)

    Random.seed!(123)
    penalty = MLJFlux.Penalty(model)
    _chain_yes_drop, history = MLJFlux.fit!(model.loss,
                                            penalty,
                                            chain_yes_drop,
                                            Flux.Optimise.ADAM(0.001),
                                            epochs,
                                            0,
                                            data[1],
                                            data[2])
    println()

    Random.seed!(123)
    penalty = MLJFlux.Penalty(model)
    _chain_no_drop, history = MLJFlux.fit!(model.loss,
                                           penalty,
                                           chain_no_drop,
                                           Flux.Optimise.ADAM(0.001),
                                           epochs,
                                           0,
                                           data[1],
                                           data[2])

    # check chains have different behaviour after training:
    @test !(_chain_yes_drop(test_input) ≈
            _chain_no_drop(test_input))

    # check chain with dropout is deterministic outside of training
    # (if we do not differentiate):
    @test all(_chain_yes_drop(test_input) ==
              _chain_yes_drop(test_input) for i in 1:1000)

    @test length(history) == epochs + 1

end


text:
using Colors, CSV, DataFrames, PGFPlotsX
mmonth = CSV.File("data/estat_demo_mmonth.csv", missingstring=":") |> DataFrame
pop = CSV.File("data/estat_demo_pjan.csv", missingstring=":") |> DataFrame
pop = pop[(pop[:sex].=="T").&(pop[:age].=="TOTAL"), :]
pop_lo = stack(pop, 6:64)
mmonth_lo = stack(mmonth, 5:63)
mmonth_lo[:variable] = map(x->parse(Int, String(x)), mmonth_lo[:variable])
pop_lo[:variable] = map(x->parse(Int, String(x)), pop_lo[:variable])
pop_mmonth = join(pop_lo, mmonth_lo, on = [:geo, :variable], makeunique=true)
pop_mmonth[:rate] = pop_mmonth[:value_1]./pop_mmonth[:value]
swe_months = ["januari", "februari", "mars", "april", "maj", "juni", "juli",
    "augusti", "september", "oktober", "november", "december"]

function plot_geos_month(geos, month)
    monthlab = swe_months[parse(Int, month[2:end])]
    p = @pgf Axis({"yticklabel style"={}, ymin=0,
        "xticklabel style"={"font=\\tiny", "/pgf/number format/set thousands separator={}"},
        "yticklabel style"={"/pgf/number format/set thousands separator={}",
            "/pgf/number format/use comma"},
        "legend style"={"font=\\tiny"},
        legend_pos="south west", xlabel="år",  ylabel="döda/folkmängd",
        "xtick distance"=10,
        title="Döda $(monthlab)",
        xmajorgrids, ymajorgrids})
    plotcolors = distinguishable_colors(length(geos)+1, [RGB(1,1,1)])[2:end]
    for (i, geo) in enumerate(geos)
        plot_geo_month(geo, month, p, plotcolors[i])
    end
    p
end

function plot_geo_month(geo, month, p, plotcolor)
    pop_mmonth_sub = pop_mmonth[(pop_mmonth[:geo].==geo) .& (pop_mmonth[:month].==month), :]
    @pgf push!(p, PlotInc({"mark=x", color = plotcolor},
        Table([pop_mmonth_sub[:variable], pop_mmonth_sub[:rate]])),
        LegendEntry(geo))
end

max_stars_repo_name: klpn/static-dust

max_issues_repo_name: klpn/static-dust

max_forks_repo_name: klpn/static-dust


text:
using Revise
using Test
import AoC2019

@testset "computer.jl" begin
    # Write your own tests here.
    @test AoC2019.run_program([3,0,99]).data[0:2] == [1,0,99]
    @test AoC2019.run_program([3,9,8,9,10,9,4,9,99,-1,8]).output == [0]
    @test AoC2019.run_program([3,9,8,9,10,9,4,9,99,-1,8],input=[8]).output == [1]
    @test AoC2019.run_program([3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9]).output == [1]
    @test AoC2019.run_program([3,3,1105,-1,9,1101,0,0,12,4,12,99,1]).output == [1]
    @test AoC2019.run_program([104,1125899906842624,99]).output == [1125899906842624]
    @test AoC2019.run_program([1102,34915192,34915192,7,4,7,99,0]).output == [1219070632396864]
    @test AoC2019.run_program([109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99]).output == [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99]
    @test AoC2019.run_program([3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,
1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,
999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99]).output ==  [999]
    @test AoC2019.run_program([3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,
1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,
999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99], input=[8]).output ==  [1000]
    @test AoC2019.run_program([3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,
1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,
999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99], input=[9]).output ==  [1001]
end

max_stars_repo_name: buotex/aoc

max_issues_repo_name: buotex/aoc

max_forks_repo_name: buotex/aoc


text:
module FTensorKit
using GeometryBasics, LinearAlgebra

include("utils/Lattices.jl")
include("utils/PerspectiveMap.jl")
include("utils/SwapGates.jl")
include("eincode.jl")
include("FTN.jl")

end

max_stars_repo_name: qiyang-ustc/FTensorKit

max_issues_repo_name: qiyang-ustc/FTensorKit

max_forks_repo_name: qiyang-ustc/FTensorKit


text:
using Test
using JavaCall

import Dates
using Base.GC: gc

macro testasync(x)
    :( @test (@sync @async eval($x)).result ) |> esc
end
macro syncasync(x)
    :( (@sync @async eval($x)).result ) |> esc
end

JAVACALL_FORCE_ASYNC_INIT = get(ENV,"JAVACALL_FORCE_ASYNC_INIT","") ∈ ("1","yes")
JAVACALL_FORCE_ASYNC_TEST = get(ENV,"JAVACALL_FORCE_ASYNC_TEST","") ∈ ("1","yes")

@testset "initialization" begin
    if JavaCall.JULIA_COPY_STACKS || JAVACALL_FORCE_ASYNC_INIT
        @testasync JavaCall.init(["-Djava.class.path=$(@__DIR__)"])==nothing
    else
        @test JavaCall.init(["-Djava.class.path=$(@__DIR__)"])==nothing
    end
    # JavaCall.init(["-verbose:gc","-Djava.class.path=$(@__DIR__)"])
    # JavaCall.init()
end

System = @jimport java.lang.System
@info "Java Version: ", jcall(System, "getProperty", JString, (JString,), "java.version")

@testset "unsafe_strings_1" begin
    a=JString("how are you")
    @test a.ptr != C_NULL
    @test 11 == ccall(JavaCall.jnifunc.GetStringUTFLength, jint, (Ptr{JavaCall.JNIEnv}, Ptr{Nothing}),
                      JavaCall.penv, a.ptr)
    b = ccall(JavaCall.jnifunc.GetStringUTFChars, Ptr{UInt8},
              (Ptr{JavaCall.JNIEnv}, Ptr{Nothing}, Ptr{Nothing}), JavaCall.penv, a.ptr, C_NULL)
    @test unsafe_string(b) == "how are you"
end

T = @jimport Test

@testset "parameter_passing_1" begin
    @test 10 == jcall(T, "testShort", jshort, (jshort,), 10)
    @test 10 == jcall(T, "testInt", jint, (jint,), 10)
    @test 10 == jcall(T, "testLong", jlong, (jlong,), 10)
    @test typemax(jint) == jcall(T, "testInt", jint, (jint,), typemax(jint))
    @test typemax(jlong) == jcall(T, "testLong", jlong, (jlong,), typemax(jlong))
    @test "Hello Java"==jcall(T, "testString", JString, (JString,), "Hello Java")
    @test Float64(10.02) == jcall(T, "testDouble", jdouble, (jdouble,), 10.02) #Comparing exact float representations hence ==
    @test Float32(10.02) == jcall(T, "testFloat", jfloat, (jfloat,), 10.02)
    @test floatmax(jdouble) == jcall(T, "testDouble", jdouble, (jdouble,), floatmax(jdouble))
    @test floatmax(jfloat) == jcall(T, "testFloat", jfloat, (jfloat,), floatmax(jfloat))
    c=JString(C_NULL)
    @test isnull(c)
    @test "" == jcall(T, "testString", JString, (JString,), c)
end

@testset "static_method_call_1" begin
    jlm = @jimport "java.lang.Math"
    @test 1.0 ≈ jcall(jlm, "sin", jdouble, (jdouble,), pi/2)
    @test 1.0 ≈ jcall(jlm, "min", jdouble, (jdouble,jdouble), 1,2)
    @test 1 == jcall(jlm, "abs", jint, (jint,), -1)
end

@testset "static_method_call_async_1" begin
    jlm = @jimport "java.lang.Math"
    if JAVACALL_FORCE_ASYNC_TEST || JavaCall.JULIA_COPY_STACKS || Sys.iswindows()
        @testasync 1.0 ≈ jcall(jlm, "sin", jdouble, (jdouble,), pi/2)
        @testasync 1.0 ≈ jcall(jlm, "min", jdouble, (jdouble,jdouble), 1,2)
        @testasync 1 == jcall(jlm, "abs", jint, (jint,), -1)
    end
end

@testset "instance_methods_1" begin
    jnu = @jimport java.net.URL
    gurl = jnu((JString,), "https://en.wikipedia.org")
    @test "en.wikipedia.org"==jcall(gurl, "getHost", JString,())
    jni = @jimport java.net.URI
    guri=jcall(gurl, "toURI", jni,())
    @test typeof(guri)==jni

    h=jcall(guri, "hashCode", jint,())
    @test typeof(h)==jint
end

#Test NULL
@testset "null_1" begin
    H=@jimport java.util.HashMap
    a=jcall(T, "testNull", H, ())
    @test_throws ErrorException jcall(a, "toString", JString, ())
end

@testset "arrays_1" begin
    j_u_arrays = @jimport java.util.Arrays
    @test 3 == jcall(j_u_arrays, "binarySearch", jint, (Array{jint,1}, jint), [10,20,30,40,50,60], 40)
    @test 2 == jcall(j_u_arrays, "binarySearch", jint, (Array{JObject,1}, JObject), ["123","abc","uvw","xyz"], "uvw")

    a=jcall(j_u_arrays, "copyOf", Array{jint, 1}, (Array{jint, 1}, jint), [1,2,3], 3)
    @test typeof(a) == Array{jint, 1}
    @test a[1] == Int32(1)
    @test a[2] == Int32(2)
    @test a[3] == Int32(3)

    a=jcall(j_u_arrays, "copyOf", Array{JObject, 1}, (Array{JObject, 1}, jint), ["a","b","c"], 3)
    @test 3==length(a)
    @test "a"==unsafe_string(convert(JString, a[1]))
    @test "b"==unsafe_string(convert(JString, a[2]))
    @test "c"==unsafe_string(convert(JString, a[3]))

    @test jcall(T, "testDoubleArray", Array{jdouble,1}, ()) == [0.1, 0.2, 0.3]
    @test jcall(T, "testDoubleArray2D", Array{Array{jdouble, 1},1}, ()) == [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]
    @test jcall(T, "testDoubleArray2D", Array{jdouble,2}, ()) == [0.1 0.2 0.3; 0.4 0.5 0.6]
    @test size(jcall(T, "testStringArray2D", Array{JString,2}, ())) == (2,2)
end

@testset "dates_1" begin
    jd = @jimport(java.util.Date)(())
    jcal = @jimport(java.util.GregorianCalendar)(())
    jsd =  @jimport(java.sql.Date)((jlong,),round(jlong, time()))

    @test typeof(convert(Dates.DateTime, jd)) == Dates.DateTime
    @test typeof(convert(Dates.DateTime, jcal)) == Dates.DateTime
    @test typeof(convert(Dates.DateTime, jsd)) == Dates.DateTime
    nulldate = @jimport(java.util.Date)(C_NULL)
    @test Dates.year(convert(Dates.DateTime, nulldate)) == 1970
    nullcal = @jimport(java.util.GregorianCalendar)(C_NULL)
    @test Dates.year(convert(Dates.DateTime, nullcal)) == 1970

    @test Dates.year(convert(Dates.DateTime, nullcal)) == 1970
end

@testset "map_conversion_1" begin
    JHashMap = @jimport(java.util.HashMap)
    p = JHashMap(())
    a= Dict("a"=>"A", "b"=>"B")
    b=convert(@jimport(java.util.Map), JString, JString, a)
    @test jcall(b, "size", jint, ()) == 2
end

@testset "array_list_conversion_1" begin
    JArrayList = @jimport(java.util.ArrayList)
    p = JArrayList(())
    a = ["hello", " ", "world"]
    b = convert(@jimport(java.util.ArrayList), a, JString)
    @test jcall(b, "size", jint, ()) == 3
end

@testset "inner_classes_1" begin
    TestInner = @jimport(Test$TestInner)
    JTest = @jimport(Test)
    t=JTest(())
    inner = TestInner((JTest,), t)
    @test jcall(inner, "innerString", JString, ()) == "from inner"
    @test jfield(@jimport(java.lang.Math), "E", jdouble) == 2.718281828459045
    @test jfield(@jimport(java.lang.Math), "PI", jdouble) == 3.141592653589793
    @test jfield(@jimport(java.text.NumberFormat), "INTEGER_FIELD", jint) == 0
    Locale = @jimport java.util.Locale
    lc = jfield(@jimport(java.util.Locale), "CANADA", @jimport(java.util.Locale))
    #Instance field access
    #Disabled for now. Need to verify stability
    @test jfield(@jimport(java.util.logging.Logger), "GLOBAL_LOGGER_NAME", JString ) == "global"
    @test jcall(lc, "getCountry", JString, ()) == "CA"
    @test jfield(t, "integerField", jint) == 100
    @test jfield(t, "stringField", JString) == "A STRING"
end

# Test Memory allocation and de-allocatios
# the following loop fails with an OutOfMemoryException in the absence of de-allocation
# However, since Java and Julia memory are not linked, and manual gc() is required.
gc()
for i in 1:100000
    a=JString("A"^10000); #deleteref(a);
    if (i%10000 == 0); gc(); end
end

@testset "sinx_1" begin
    @test_throws UndefVarError jcall(jlm, "sinx", jdouble, (jdouble,), 1.0)
    @test_throws UndefVarError jcall(jlm, "sinx", jdouble, (jdouble,), 1.0)
end

@testset "method_lists_1" begin
    @test length(listmethods(JString("test"))) >= 72
    @test length(listmethods(JString("test"), "indexOf")) >= 3
    # the same for the type
    @test length(listmethods(JString)) >= 72
    @test length(listmethods(JString, "indexOf")) >= 3
    # the same for class
    @test length(listmethods(getclass(JString("test")))) >= 72
    @test length(listmethods(getclass(JString("test")), "indexOf")) >= 3
    m = listmethods(JString("test"), "indexOf")
    @test getname(getreturntype(m[1])) == "int"

    z = [getname.(t) for t in getparametertypes.(m)]
    @test findfirst(n->n==["int"], z) != nothing
    @test findfirst(n->n==["java.lang.String", "int"], z) != nothing
end

#Test for double free bug, #20
#Fix in #28. The following lines will segfault without the fix
@testset "double_free_1" begin
    JHashtable = @jimport java.util.Hashtable
    JProperties = @jimport java.util.Properties
    ta_20=Any[]
    for i=1:100; push!(ta_20, convert(JHashtable, JProperties((),))); end
    gc(); gc()
    for i=1:100; @test jcall(ta_20[i], "size", jint, ()) == 0; end
end

@testset "array_conversions_1" begin
    jobj = jcall(T, "testArrayAsObject", JObject, ())
    arr = convert(Array{Array{UInt8, 1}, 1}, jobj)
    @test ["Hello", "World"] == map(String, arr)
end

@testset "iterator_conversions_1" begin
    JArrayList = @jimport(java.util.ArrayList)
    a=JArrayList(())
    jcall(a, "add", jboolean, (JObject,), "abc")
    jcall(a, "add", jboolean, (JObject,), "cde")
    jcall(a, "add", jboolean, (JObject,), "efg")

    t=Array{Any, 1}()
    for i in JavaCall.iterator(a)
        push!(t, unsafe_string(i))
    end

    @test length(t) == 3
    @test t[1] == "abc"
    @test t[2] == "cde"
    @test t[3] == "efg"

    #Different iterator type - ListIterator
    t=Array{Any, 1}()
    for i in jcall(a, "listIterator", @jimport(java.util.ListIterator), ())
        push!(t, unsafe_string(i))
    end

    @test length(t) == 3
    @test t[1] == "abc"
    @test t[2] == "cde"
    @test t[3] == "efg"

    a=JArrayList(())
    t=Array{Any, 1}()
    for i in JavaCall.iterator(a)
        push!(t, unsafe_string(i))
    end
    @test length(t) == 0

    JStringClass = classforname("java.lang.String")
    @test isa(JStringClass, JavaObject{Symbol("java.lang.Class")})

    o = convert(JObject, "bla bla bla")
    @test isa(narrow(o), JString)
end

@testset "roottask_and_env_1" begin
    @test JavaCall.isroottask()
    @testasync ! JavaCall.isroottask()
    @test JavaCall.isgoodenv()
    if JAVACALL_FORCE_ASYNC_TEST || JavaCall.JULIA_COPY_STACKS || Sys.iswindows()
        @testasync JavaCall.isgoodenv()
    end
    if ! JavaCall.JULIA_COPY_STACKS && ! Sys.iswindows()
        @test_throws CompositeException @syncasync JavaCall.assertroottask_or_goodenv()
        @warn "Ran tests for root Task only." *
            " REPL and @async are not expected to work with JavaCall without JULIA_COPY_STACKS=1" *
            " on non-Windows systems."
            " Set JULIA_COPY_STACKS=1 in the environment to test @async function."
    end
end

# At the end, unload the JVM before exiting
JavaCall.destroy()


text:
using Test

include("enchantments.jl")

@testset "Determine if a card is present" begin
    @test has_card([2, 3, 4, 5], 3)
end

@testset "Find the position of a card" begin
    @test find_card([3], 3) == 1
    @test find_card([9, 7, 3, 2], 2) == 4
    @test find_card([8, 3, 9, 5], 8) == 1
    @test isnothing(find_card([5, 3, 1, 9], 2))
end

@testset "Determine if each card is even" begin
    @test !all_cards_even([1])
    @test !all_cards_even([2, 5])
    @test  all_cards_even([2, 4, 8, 6])
end

@testset "Check if the deck contains an odd-value card" begin
    @test !any_odd_cards([2, 4, 6])
    @test  any_odd_cards([2, 5])
    @test  any_odd_cards([1, 3, 5, 7])
end

@testset "Determine the position of the first card that is even" begin
    @test first_even_card_idx([2, 4, 1, 3]) == 1
    @test first_even_card_idx([1, 2]) == 2
    @test isnothing(first_even_card_idx([1, 3, 5]))
end

@testset "Get the first odd card from the deck" begin
    @test first_odd_card([2, 4, 1, 3]) == 1
    @test first_odd_card([1, 2]) == 1
    @test isnothing(first_odd_card([4, 2, 6]))
end


text:
### A Pluto.jl notebook ###
# v0.12.21

using Markdown
using InteractiveUtils

# ╔═╡ 064a4920-779b-11eb-0f3c-d72a8db494ba
using GMT, DataFrames, CSV

# ╔═╡ bef24730-779a-11eb-2898-236801295f32
md"# Choropleth example Covid rate of infection in Portugal
"

# ╔═╡ 0c3afa00-779b-11eb-2284-f5f77a1ed657
md"First, download the Portuguese district polygons shape file from this [Github repo](https://github.com/dssg-pt/covid19pt-data/tree/master/extra/mapas/concelhos)
Next load it with:
"

# ╔═╡ ea8cb480-779e-11eb-128a-034873e098bc
#Pt = gmtread("https://github.com/dssg-pt/covid19pt-data/blob/master/extra/mapas/concelhos/concelhos.shp");
Pt  = gmtread("C:\\programs\\compa_libs\\covid19pt\\extra\\mapas\\concelhos\\concelhos.shp");

# ╔═╡ 514155e0-77be-11eb-1357-a7f08aa8705f
md"
Download and load a CSV file from [same repo](https://github.com/dssg-pt/covid19pt-data/blob/master/data_concelhos_incidencia.csv) with rate of infection per district. Load it into a DataFrame to simplify data extraction.
"

# ╔═╡ fcdfb6f0-779e-11eb-3851-23b13e48f0da
#incidence = CSV.read("https://github.com/dssg-pt/covid19pt-data/blob/master/data_concelhos_incidencia.csv", DataFrame);
incidence = CSV.read("C:\\programs\\compa_libs\\covid19pt\\data_concelhos_incidencia.csv", DataFrame);

# ╔═╡ 7a3a5cd0-77a0-11eb-1697-21cc016a00c6
md"Get the rate of incidence in number of infected per 100_000 habitants for the last reported week."

# ╔═╡ 4c32c340-77a0-11eb-212d-158dae4cc702
r = collect(incidence[end, 2:end]);

# ╔═╡ 921da0a2-77a0-11eb-1f58-85feb4a2943d
md"But the damn polygon names above are all uppercase, Ghrrr. We will have to take care of that.
"

# ╔═╡ bd494360-77a0-11eb-04a8-53f52cf2988c
ids = names(incidence)[2:end];

# ╔═╡ ee946f30-77a0-11eb-3b1a-3bcc0ae50f90
md"
Because the multi-segment headers have several fields in a comma separated string and the one we care (the one that is common with the names in the **Pt** dataset) is in the seventh position we use argument **7**. Last argument, **2** means to convert all names in the **Pt** headers to upper case so we can compare them with the names in **ids**. The comparison is made inside the next call to the ``make\_zvals\_vec()`` function that takes care to return the numerical vector that we need in *plot's* **level** option
"

# ╔═╡ fd378900-77a0-11eb-304a-65d816ef0bb5
zvals = GMT.make_zvals_vec(Pt, ids, r, 7, 2);

# ╔═╡ 9364d130-77a1-11eb-2434-cba72ee71c9d
md"Create a Colormap to paint the polygons
"

# ╔═╡ a331c500-77a1-11eb-2428-ed715c229193
C = makecpt(range=(0,1500,10), inverse=true, cmap=:oleron, hinge=240, bg=:o);

# ╔═╡ 7b0a3db0-77a5-11eb-2d42-613993618852
md"Get the date for the data being represented to use in title
"

# ╔═╡ a6e0ed80-77a5-11eb-3555-154f927dd2c7
date = incidence[end,1];

# ╔═╡ bd8b6330-77a5-11eb-3bf8-6d35a73a8935
md"And finaly do the plot
"

# ╔═╡ c92caeb0-77a5-11eb-0e52-df880fa278b9
plot(Pt, level=zvals, cmap=C, close=true, fill="+z", pen=0.5, region=(-9.75,-5.9,36.9,42.1), proj=:Mercator, title="Infected / 100.000 habitants " * date)

# ╔═╡ 3e211d90-77ac-11eb-336a-61a8a2220e7a
colorbar!(pos=(anchor=:MR,length=(12,0.6), offset=(-2.4,-4)), color=C, axes=(annot=100,), show=true)

# ╔═╡ Cell order:
# ╟─bef24730-779a-11eb-2898-236801295f32
# ╠═064a4920-779b-11eb-0f3c-d72a8db494ba
# ╟─0c3afa00-779b-11eb-2284-f5f77a1ed657
# ╠═ea8cb480-779e-11eb-128a-034873e098bc
# ╟─514155e0-77be-11eb-1357-a7f08aa8705f
# ╠═fcdfb6f0-779e-11eb-3851-23b13e48f0da
# ╟─7a3a5cd0-77a0-11eb-1697-21cc016a00c6
# ╠═4c32c340-77a0-11eb-212d-158dae4cc702
# ╟─921da0a2-77a0-11eb-1f58-85feb4a2943d
# ╠═bd494360-77a0-11eb-04a8-53f52cf2988c
# ╟─ee946f30-77a0-11eb-3b1a-3bcc0ae50f90
# ╠═fd378900-77a0-11eb-304a-65d816ef0bb5
# ╟─9364d130-77a1-11eb-2434-cba72ee71c9d
# ╠═a331c500-77a1-11eb-2428-ed715c229193
# ╟─7b0a3db0-77a5-11eb-2d42-613993618852
# ╠═a6e0ed80-77a5-11eb-3555-154f927dd2c7
# ╟─bd8b6330-77a5-11eb-3bf8-6d35a73a8935
# ╠═c92caeb0-77a5-11eb-0e52-df880fa278b9
# ╠═3e211d90-77ac-11eb-336a-61a8a2220e7a


text:
module xija

import PyCall: PyObject, pyimport, PyNULL

pyxija = PyNULL()

function __init__()
    copy!(pyxija, pyimport("xija"))
end

struct XijaModel
    model::PyObject
    function XijaModel(model::PyObject)
        new(model)
    end
end

function XijaModel()
    new(model)
end

function make(model::XijaModel)
    model.model.make()
end

function calc(model::XijaModel)
    model.model.calc()
end

end