How can I use types so that generic operations are inlined (or "open coded") in sbcl?

Question: SBCL compiler optimizations are based on the idea that if a type is declared, then "open coding" allows generic operations to be replaced with specific ones.
For example
(defun add (a b)
    (declare (type fixnum a b))
    (+ a b))

Will allow the generic + to be replaced with a single instruction for fixnum.
However, I have found that in practice, this seems to rarely be possible because:

In order for a function to be specialized/optimized it must be inlinable. The declaration must be marked explicitly with a (declaim (inline ...)), so the author of a function must anticipate that others might want to inline it. (In theory the compiler could generate multiple versions, but this doesn't seem to be the case.)
Most standard functions do not appear inlineable.

For example, one would expect that the following declaration is sufficient for open coding to take place:
(defun max-integers (array)
    (declare (optimize (speed 3) (space 0) (safety 0)))
    (declare (inline reduce))
    (declare (type (simple-array fixnum (*)) array))
    (reduce (lambda (a b) (if (> b a) b a)) array))

However, the assembly shows it's making a function call to the generic reduce:
; Size: 22 bytes. Origin: #x1001BC8109
; 09:       488B15B0FFFFFF   MOV RDX, [RIP-80]                ; no-arg-parsing entry point
                                                              ; #<FUNCTION (LAMBDA
                                                              ;                # ..)>
; 10:       B904000000       MOV ECX, 4
; 15:       FF7508           PUSH QWORD PTR [RBP+8]
; 18:       B8781C3220       MOV EAX, #x20321C78              ; #<FDEFN REDUCE>
; 1D:       FFE0             JMP RAX

The conclusion seems to be that the compiler cannot actually do much type optimization, as each usage of reduce, map, etc is a barrier to type propagation, and they are building blocks of everything else.
How can I overcome this and take advantage of optimizations by declaring types?
I really want to avoid writing type specific versions of each function or "macroifying" what should be a function.
Comment: `(reduce #'> array)` doesn't make sense, because `#'>` returns `t` or `nil` which are not valid inputs for `#'>`.
Comment: @Svante silly me! Let me write it correctly and update the question.
Comment: @Svante I have made the correction.
Comment: There's not really much you can do to force optimizations. All you can do is declare types as much as possible, and hope that the compiler is able to use them. Some compilers are better at this than others.
Comment: @Barmar sure, I understand that CL doesn't specify how types will be used, but I am focusing on SBCL. It clearly has a lot of infrastructure built for doing optimization, my question is how I use that effectively. `reduce` is just one example to illustrate what appears to be limitations of the larger system. If there are weird reasons why my example doesn't work, but other practices will, I would be interested.
Answer: I think one answer is that if you want to write FORTRAN-style array-bashing code, write FORTRAN-style array-bashing code.  In particular using things like reduce is probably not the way to do this.
For instance if you change your function to the perfectly readable
(defun max-integers/loop (array)
  (declare (optimize (speed 3) (space 0) (safety 0))
           (type (simple-array fixnum (*)) array))
  (loop for i of-type fixnum across array
        maximizing i))

Then SBCL does a far, far better job of optimising it.

It's worth pointing out another confusion in your question:  You say that for something like
(defun add (a b)
  (declare (type fixnum a b))
  (+ a b))

SBCL will optimize + to the machine instruction.  No, it won't.  The reason it won't is because the fixnum type is not closed under addition: consider what (add most-positive-fixnum 1) should do.  If you want to generate very fast code for integers you need to make sure that your integer types are small enough that the compiler can be sure that the operations you're doing on them remain machine integers (or, if you want to live dangerously, cover your code with (the fixnum ...) and set safety to 0 when compiling, which seems to allow the compiler to just return the wrong answer for addition in the way people usually expect computers to do).
Comment: @JustinMeiners: you almost certainly won't need to declare the system functions inline: the compiler will do that.  The useful declaration would `notinline` in fact, if you wanted to be able to see the function call.
Comment: Thanks. In the mean time I found and tested this sample: https://bugs.launchpad.net/sbcl/+bug/756926 in which `replace` is inlined as I would have expected. So it looks like there are reasonable transforms for many system functions, and as you said, map/reduce is probably just not a good fit for this. The key thing I want to verify is that the pattern of declaring generic functions as inlineable, and then ensuring types are declared by the caller will allow optimization to take place, which appears to be true.
Answer: You can't force the implementation to open-code functions that weren't declared INLINE when they were defind -- it simply hasn't saved the information needed.
However, the overhead of calling REDUCE is probably negligible compared to the actual processing. So what you can do is declare the types of a and b, to optimize the callback function.
(reduce (lambda (a b) (declare (type fixnum a b)) (if (> b a) b a)) array)

I guess you were hoping that if it open-coded reduce it would automatically propagate this type from the declaration of array, so you wouldn't need to do this.
Comment: Yes, precisely I had hoped that would be propogated. Is there any guidance either for the CL standard, or the SBCL implementation itself that specifies which functions are inlinable?
Comment: Sorry, no. Optimizations are left entirely to "quality of implementation". Implementations are allowed to ignore INLINE completely. All these declarations are just considered to be hints that the implementation can use if it wants to.
Comment: I don't know SBCL-specific optimizations.
Comment: Thanks for your help, perhaps this is an SBCL mailing list question. Yeah I don't imagine the call to reduce is expensive, but there are all sorts of iteration and lookup optimizations that are being left off the table, because it cannot "see" that it is a simple array.


Algebraic closure for $\mathbb{Q}$ or $\mathbb{F}_p$ without Choice?

Question: I know the usual proof of the existence of an algebraic closure for any field using Zorn's Lemma. The answer to this previous question makes it clear that in general, some nonconstructive axiom (not necessarily the full AC) is needed to guarantee an algebraic closure. My question is if we can avoid any of this in the cases of $\mathbb{Q}$ and $\mathbb{F}_p$.

Can algebraic closures for $\mathbb{Q}$ and $\mathbb{F}_p$ be constructed in ZF?

Intuitively, it seems plausible to me that they can. There are two places I see a need for an AC-typed axiom in the construction of an algebraic closure: one is to create some order (i.e. bijection with $\mathbb{N}$) for the set of polynomials whose roots I need to adjoin; two is to handle what happens when I start adjoining roots and the polynomials start factoring into smaller factors. (Which factor do I approach first?) It seems to me that $\mathbb{Q}$ and $\mathbb{F}_p$ both have structure that could be used cleverly to resolve both of these points without recourse to AC. However, I don't see the path clearly.
Comment: What is interesting is that we cannot prove *uniqueness*. For example, it is consistent (in a choice-free setting) that there is an *uncountable* algebraic closure of ${\mathbb Q}$. Of course, the subfield of ${\mathbb C}$ of algebraic numbers is countable, so this gives us two non-isomorphic algebraic closures of ${\mathbb Q}$.
Comment: $\mathbb{C}$ can be constructed in ZF, and by Separation the set of all elements of $\mathbb{C}$ that are algebraic is a set, hence an object in ZF.
Comment: The alg. closure of finite fields is an increasing countable union of finite fields, so it is constructible with very little power.
Comment: @Henning: It is a somewhat subtle issue: In abstract, a field extension of a field $K$ is not a superset $K(\alpha)$ of $K$, but rather a set $K(\alpha)$ together with an embedding of $K$ into $K(\alpha)$. And we can be in a situation in which there is no coherent way of putting all these embeddings together in an ordered way that allows us to recognize that we only have countably many objects present. Recall that a countable union of countable sets needs not be countable if we do not have a uniform way of enumerating all the countable sets "simultaneously."
Comment: @Henning: I think it comes down to the fact that algebraic closures only have a weak universal property: if $K$ is a field and $\overline{K}$ is an algebraic closure, _under the axiom of choice_, for any other field $L$ containing all roots of $K$, there is _at least_ one homomorphism $\overline{K} \to L$. In general there will be $\textrm{Gal}(\overline{K} / K)$ many. In the absence of choice, there may not even be any homomorphism $\overline{K} \to L$.
Comment: @Andres: Interesting. The mechanism that prevents such an uncountable closure from being cut down to countable, I suppose, would be that we need choice in order to distinguish globally between different roots of the same polynomial?
Comment: @Andres: I don't really follow you here; I think you're shooting down a different argument from the one I was imagining. The one I imagined was that if $L$ is a closure of $\mathbb Q$, then every element $x\in L$ can be finitely described by a tree of a polynomial that $x$ is a root in, a polynomials that its coefficients are roots in, and so on until we hit rationals at some finite height. The trouble is then that such a tree is only a unique description if each node says _which_ of the polynomial's root it encodes. And that takes the tree outside the realm of finite descriptions.
Comment: @Henning: Actually, every element in an algebraic closure of $K$ is necessarily algebraic over $K$. But even in the presence of the axiom of choice, the only way to name the roots of a polynomial is to, well, take an algebraic closure... The most obvious way to construct a homomorphism between two algebraic closures is to use Zorn's lemma and construct it on all the finite subextensions.
Comment: Thank you everyone for all these answers and all this conversation! I will accept an answer after I have time to thoroughly digest everything.
Answer: For any finite or countable field $K$, you can well-order $K$ even without AC, and then you don't actually need any further choice to construct a closure for it.
Namely, since $K$ can be well-ordered, you can well-order all monic polynomials over $K$ and adjoin roots for the irreducible ones one by one by transfinite induction up to $\omega_1$. Each time we adjoin elements, we can well-order the new elements and stick them at the end of the well-ordering of the ones we already have. If we order the polynomials primarily by "maximal coefficient" rather than by degree, the new polynomials that become possible after each extension will always come after the ones we already know.
By the time we reach $\omega_1$, there cannot be any more polynomials that need to have roots adjoined. Namely, every polynomial we can form at that point will have had each of its coefficients added at a time when there were only countably many polynomials in our list of polynomials to process, so this polynomial will have been processed at some step before $\omega_1$.
Edit to add: In fact, as Zhen Lin points out, one only has to adjoin roots for polynomials with coefficients in $K$. For $K=\mathbb Q$ that is shown in this question, but the arguments there appear to work in general. This is easy enough to do for any well-orderable $K$, not just countable ones.
Comment: @ZhenLin: Sure, but so what? If the polynomial we're looking at factors (in the extension so far), we don't need to choose a particular factorization; we just skip it. At the end, no polynomial of degree more than one can be irreducible, because if so it must have been irreducible the whole time, and therefore also when we processed it. [On the other hand, this may mean that we do have to adjoin roots to polynomials with coefficients outside $K$, because we may not have added enough roots the first time we consider a polynomial. The rest will come around when we consider its new factors].
Comment: Sorry to be picky, but: "For any finite or countable field K, you can (by definition) well-order K" This is certainly true; moreover I would say that is clearly true; but I don't see how it is true "by definition".
Comment: @Asaf: it's not a key point by any means, but again, having an action into a countable ordinal is not the *definition* of well-ordered...although I can well believe that to a set-theorist this is a silly distinction to make.  Anyway, no biggie...
Comment: How do you know that your transfinite process stops? It's probably easier to prove that any field $L$ that purportedly contains the roots of all polynomials over $K$ must also contain an algebraic closure of $K$, so that you can stop your construction after one iteration.
Comment: @Zhen: I've tried to expand the argument. Yes, the argument you sketch would be simpler, but it is not immediately clear to me that it can be carried out for arbitrary $K$. Perhaps just a stupid oversight on my part?
Comment: @Zhen (later): Indeed -- it turns out that I've offered proof of this that seems to generalize directly from $\mathbb Q$. Much easier that way.
Comment: Actually, I think the well-orderability of the set of monic irreducible polynomials is a red herring. If $p$ is irreducible over $K$ and $L$ is a (finite) extension of $K$, there's no reason to believe that $p$ is irreducible over $L$. That means at each step we have to re-factorise our polynomials...
Comment: There's also no reason to assume that $p$ factoring over $L$ implies $p$ _splits_ over $L$. For example, take $p(x) = x^3 - 2$ over $\mathbb{Q}$. After adding one root of $p$, $p$ factors into a linear part and a quadratic part. So you must add _all_ the roots at each step.
Comment: @Zhen: No, because the quadratic part will be considered at some later step when we get to polynomials with coefficients not in the original $K$. That's what I tried to say in the square-bracketed addendum above.
Comment: Anyway, since we're carrying around a well-ordering of the field extension we're working in at any point, we _can_ add all roots at once if we like to -- whenever we need to factor anything, just choose the lexicographically first factoring.
Comment: @Pete: You're right, that is rather more of a strech on paper than it was in my head. My train of thought was something like: Any finite or countable K is by definition in bijective correspondence with an ordinal and can therefore be well-ordered.
Comment: @Pete: The definition of countable is to have an injection into $\omega$... so the fact that countable sets can be well ordered is indeed "by definition".
Comment: @Pete: I guess you're right. I often think about well orderable as "can be injected into an ordinal", so by that definition countable implies well orderable.
Comment: Thanks for this answer, Henning. Before accepting I want to make sure I understand all the details. Where do the well-orders on the extensions come from? Is there somehow a canonical well-order on a finite extension of a field that's been well-ordered?
Comment: @Ben: The well-orders of the extensions come from the fact that each time you add a solution to _one_ polynomial you add at most countably many new elements to the field, which can all be described as polynomials of the new root you're adjoining. Since there's a definable way to well-order polynomials, you can describe a well-ordering of each extension without needing to make arbitrary choices.
Comment: Hmmm, I think I see. You're saying, say the field at some stage is $K$ and I adjoin $\alpha$. The set of polynomials in $\alpha$ gets a well-order (say lexicographic or something) from the well-order on $K$; this set of polynomials includes all elements of $K(\alpha)$ (actually, multiple times) so it induces a well-order on $K(\alpha)$ e.g. by taking the lowest-degree polynomial representing a given element and finding its place in the well-order on polynomials?
Comment: @Ben: Yes, exactly. (Or just the representing polynomial that comes first in the well-order of polynomials).
Comment: Am I missing something that you don't need transfinite recursion up to $ω_1$? You do not need to care about the elements you have added, because by the tower law every algebraic extension of any algebraic extension is an algebraic extension of the base field. So it suffices to have a well-ordering of the field to obtain its algebraic closure without transfinite induction.
Answer: Actually, according to this FOM post, Wilfrid Hodges [1975, Läuchli's algebraic closure of $\mathbb{Q}$] proved that ZF is not enough to prove the existence of a unique algebraic closure of $\mathbb{Q}$, where he takes algebraic closure to mean an algebraically closed field containing (an isomorphic copy of) $\mathbb{Q}$ and no other strictly smaller algebraically closed subextension.
On the other hand, in the same post, Stephen Simpson asserts that every countable field $K$ admits a unique (up to non-unique isomorphism) countable algebraic closure, in the sense of a countable algebraically closed field containing (an isomorphic copy of) $K$ whose elements are all algebraic over (the copy of) $K$.
As far as I can tell, the construction given by Henning Mahkolm below should work to construct an algebraic closure of $\mathbb{Q}$, and so should Arturo Magidin's suggestion (modulo proving that $\mathbb{C}$ has all roots of all polynomials over $\mathbb{Q}$). Here is the required fact to pass from one to the other:
Proposition. Let $L$ be a field extension of $K$. If every polynomial over $K$ splits over $L$, then there is a unique subextension $\overline{K}$ such that

$\overline{K}$ is an algebraically closed field.
$\overline{K}$ is minimal with respect to this property.

Proof. Let $\overline{K} = \{ x \in L : x \text{ is algebraic over } K \} $. Clearly, if we can show (1), (2) will follow by construction: any algebraically closed subextension of $L$ must contain $\overline{K}$ as a subset.
By the usual dimension arguments – which I believe are allowed since we only need to work with finite-dimensional vector spaces over $K$ – it can be shown that $\overline{K}$ is a subfield of $K$: the key point is that if $K'$ is a finite extension of $K$ and $K''$ is a finite extension of $K'$, then $K''$ is a finite extension of $K$, and if $x$ is algebraic over $K'$ then $K'(x)$ is finite over $K'$, so $x$ is algebraic over $K$ itself.
Now, consider an arbitrary polynomial $p$ over $\overline{K}$. Since $p$ only has finitely many coefficients, it is in fact a polynomial over some subfield $K'$ which is a finite extension of $K$. So it is enough to show that, for any finite subextension $K'$, every polynomial $p$ over $K'$ splits over $\overline{K}$. But $K'$ is finite over $K$, so every root of $p$ must be algebraic over $K$, and every polynomial over $K$ splits over $\overline{K}$ by hypothesis, so $p$ must split over $\overline{K}$ as well, and hence, over $\overline{K}$. So $\overline{K}$ is indeed algebraically closed.

Regardless, a few of the things we want algebraic closures for can be done by hand in the absence of choice. For example:
Lemma. Let $K$ be a field, and let $K \hookrightarrow L$ and $K \hookrightarrow L'$ be any two finite extensions. Then, there is a finite extension $K \hookrightarrow M$ containing isomorphic copies of $L$ and $L'$ as subextensions.
Proof. Let $A = L \otimes_K L'$. This is a finite-dimensional $K$-algebra. As such, it has a finite upper bound on lengths of strictly ascending chains of ideals, and therefore contains a maximal ideal $\mathfrak{m}$. (Note: this is much stronger than the usual ascending chain condition, and the ascending chain condition is not enough to prove the existence of maximal ideal! See [Hodges, 1973, Six impossible rings].) It is easy to check that the field $M = A / \mathfrak{m}$ has the desired properties.
Lemma. Let $K$ be a field, and let $p$ be a polynomial over $K$. Then, there is an extension $K \hookrightarrow L$ which splits $p$.
Proof. By the preceding lemma, if we can do this for irreducible polynomials, then we can do this for all polynomials. We may assume $p$ is irreducible of degree at least 2. Observe that $K' = K[x] / (p)$ is a field, and $p$ factors over $K'$ into polynomials of strictly lower degree. The result follows by induction on the degree of $p$.
So as long as we are content to only work with finitely many polynomials at any time, things should be fine...
Comment: Lauchli was great. In his Ph.D. he practically showed that all the algebra we know relies on the axiom of choice (vector spaces, etc. etc.) he worked with Specker's approach to Quine's Atoms which is cumbersome in ZF compared to ZFA+Jech-Sochor (or directly forcing symmetric extensions). It's a good thing, though. It allows me to write my M.Sc. thesis and refurbish some of his work!
Answer: Even if the axiom of choice does not hold in the universe itself, many of its uses can be replaced de-facto by well orders (which allow effectively choosing elements). This allows showing existence of a minimal algebraically closed field, but it is not enough to show its uniqueness.
Much like Henning said, if a field is countable (like the rationals, or finite fields) then we can effectively order the polynomials then go through the list and add the needed roots. In the general case this won't really work because we don't have a way of choosing a lot of polynomials at once. As Zhen Lin notes in his answer, it was shown that such algebraic closure need not be unique up to isomorphism.
Let me digress for a moment (it's gonna be worth it in a paragraph or two) and talk about weak choice principles. I give a division of three kinds of weak choice principles. There are "choices family principles" (we can choose from certain families of nonempty sets) sort of choice principles like The Axiom of Countable Choice; there are topological principles (like the Ultrafilter lemma and its equivalents); and there are other weird principles (Small Violations of Choice, KWP's, etc etc.).
These are often independent of one another, for example the first Cohen model shows that choice for certain families fail strongly (we cannot choose from a countable family of infinite sets) while the ultrafilter lemma holds.
Interestingly enough, the existence and uniqueness of an algebraic closure follow from the ultrafilter lemma (equiv. Boolean prime ideal theorem; Compactness theorem; etc.) and not from well orders and choice related principles. So while we can use well orders to effectively choose how to add the roots to the polynomials, we can do it in a "less constructive" way by using the ultrafilter lemma instead - even if the field cannot be well ordered. It is not known (as far as I know) whether or not existence implies uniqueness; or the ultrafilter lemma. It is known that uniqueness does not imply neither of them though.
Comment: "It is known that uniqueness does not imply neither of them though."
Do you mean "either"? Don't mean to nag. Just not sure if I heard that right. Also, if you did mean "either", I'd like to take a look at a paper, if you could direct me to one.
Answer: I believe we can generalize a bit: every well-orderable field $K$ has a well-orderable algebraic closure. (and any two are isomorphic)
First, choose a well-ordering $<$ on $K$. Also, choose a well-ordering of the polynomials over $K$ (e.g. a lexicographic order). The $\alpha$-th polynomial is $f_\alpha$.
Using transfinite recursion, construct a family $L_\alpha$ of algebraic extension fields of $K$, and well-orderings $<_\alpha$ on $L_\alpha$ such that, for any $\alpha < \beta$:

$L_\alpha$ is a subfield of $L_\beta$
If $x \in L_\alpha$ and $y \in L_\beta \setminus L_\alpha$, then $x < y$.

The base case will be $L_0 = K$ and $<_0 = <$. At each $\alpha > 0$, perform the following:

$E = \cup_{\beta < \alpha} L_\beta$ is an algebraic extension of $K$
$<_E = \cup_{\beta < \alpha} <_\beta$ is a well-ordering on $E$
Construct $L_\alpha$, a splitting field of $f_\alpha$ over $E$
Modify $L_\alpha$ so that $L \subseteq L_\alpha$.
Construct a well-ordering $<_\alpha$ on $L_\alpha$ (e.g. lexicographical, as a finite-dimensional $E$-vector space)
Modify $<_\alpha$ so that $E$ is an initial segment of $L_\alpha$

The main thing to make this work, I think, is to verify making the splitting field is constructive -- e.g. note that we have a canonical choice of well-ordering on polynomials over $E$, and thus a canonical way to choose factor of $f_\alpha$ each time we need to do so.
Comment: Also you are using *some* choice: The union of well-ordered sets is well-ordered. The union of countably many *pairs* (which are finite and surely well orderable) need not be well-orderable.
Comment: But... $\mathbb Q$ is well-orderable and can have two *non-isomorphic* algebraic closures... (regardless to their cardinality!)
Comment: @Asaf: But is it not true that all *well-orderable* algebraic closures are isomorphic? I don't follow your argument as to why I'm using something beyond just ZF.
Comment: Yes, but not all the algebraic closures of a well-orderable field are themselves well-orderable.
Comment: That's why I was only talking about the well-orderable ones.


Creating Item category type throw "6000: A business validation error has occurred while processing your request" error

Question: I am using v3-php-sdk, creating items non category type works well.
The problem is when the item is use to be category eg.
Array
(
    [Name] => Item
    [FullyQualifiedName] => Item
    [Type] => Category
)

Then if I call
Item::create($arrayItem)

It generated object like this.
QuickBooksOnline\API\Data\IPPItem Object
        (
            [Name] => Item
            [Sku] =>
            [Description] =>
            [Active] =>
            [SubItem] =>
            [ParentRef] =>
            [Level] =>
            [FullyQualifiedName] => Item
            [Taxable] =>
            [SalesTaxIncluded] =>
            [PercentBased] =>
            [UnitPrice] =>
            [RatePercent] =>
            [Type] => QuickBooksOnline\API\Data\IPPCustomFieldTypeEnum Object
                (
                    [value] => Category
                )

            [PaymentMethodRef] =>
            [UOMSetRef] =>
            [IncomeAccountRef] =>
            [PurchaseDesc] =>
            [PurchaseTaxIncluded] =>
            [PurchaseCost] =>
            [ExpenseAccountRef] =>
            [COGSAccountRef] =>
            [AssetAccountRef] =>
            [PrefVendorRef] =>
            [AvgCost] =>
            [TrackQtyOnHand] =>
            [QtyOnHand] =>
            [QtyOnPurchaseOrder] =>
            [QtyOnSalesOrder] =>
            [ReorderPoint] =>
            [ManPartNum] =>
            [DepositToAccountRef] =>
            [SalesTaxCodeRef] =>
            [PurchaseTaxCodeRef] =>
            [InvStartDate] =>
            [BuildPoint] =>
            [PrintGroupedItems] =>
            [SpecialItem] =>
            [SpecialItemType] =>
            [ItemGroupDetail] =>
            [ItemAssemblyDetail] =>
            [AbatementRate] =>
            [ReverseChargeRate] =>
            [ServiceType] =>
            [ItemCategoryType] =>
            [ItemEx] =>
            [Id] =>
            [SyncToken] =>
            [MetaData] =>
            [CustomField] =>
            [AttachableRef] =>
            [domain] =>
            [status] =>
            [sparse] =>
        )

However, it always throw error for this object, on my research they are saying that we should not pass 0 or negative number for eg. unitprice or other fields but if that's the case the sdk is the one generated this object and I just provide the data I have.
Any idea regarding this?
Answer: "For Sandbox, category is not enabled by default. You will need to go to this link to enable it on Sandbox: https://sandbox.qbo.intuit.com/app/categorymigration
Try create a free-trial production company, everything should be working correctly"
As per Hao_Lu (Intuit Developer Group)
Click this link for more info.
Answer: That's because [UnitPrice] => is empty. You will need to pass in some positive value if that's the error message you are getting
Array
(
    [Name] => Item
    [FullyQualifiedName] => Item
    [Type] => Category
    [UnitPrice] => 1
)

Comment: Yeh but for creating category it doesn't need to have any UnitPrice.
Refer here https://developer.intuit.com/docs/api/accounting/item;
CATEGORY REQUEST BODY
SAMPLE REQUEST
{
  "Name": "Trees",
  "Type":"Category"
}


iframe jquery dialog in parent window

Question: I have a page with an iframe that appears in a jQuery dialog.
Inside the iframe it loads a page and there is a button on that page which shows an alert via a jQuery dialog. At the moment the dialog appears and sits over the iframe, however how can I display this dialog to appear outside of the iframe and be at the upper most layer? i.e. covers the parent screen.
main page

iframe page is loaded dynamically and on that page there is a function
$('#alertclick').click(function() {
    var alert_dialog = $('
' + alertinfo + '
');
    alert_dialog.dialog({ width: 400, height: 300, resizable: false });
});

Answer: If you put the div in the parent page, you can call a function within the parent page to show the dialog from inside the iframe. For example, placing this within the iframe:
parent.functionName();
Will call the function functionName within the initial page, from the iframe.

iframe jquery dialog in parent window


I have a cluster of computers, how do I setup ntpd so they all have nearly the same clock?

Question: I have 4 computers, one is considered the master (direct connection to the Internet) and the others are considered slaves (for those the master adds one extra hop to any external communication.)
At this time, all computers are setup to have time synchronized through external time servers (a.k.a. 0.north-america.pool.ntp.org). Is that the way you would do it too?
I am wondering whether setting up the ntpd of each slave to accept clock adjustments from the master instead of external sources could be better?
Comment: Do you really care if their clocks differ by a few milliseconds?
Comment: Me personally? Not really. However, systems like Cassandra and timed network messages need to have clocks that are as close as possible to avoid inconsistencies.
Answer: Typically, you'd set an ntp server up on a single machine on your network, possibly your router or gateway.  That machine would call out to ntp servers over the Internet and make sure its time is accurate.  You will want to provide a few ntp servers in your region.  It will also provide time information to your LAN.  There are many tutorials on how to get this done properly for a LAN-only setup.
The other machines on your LAN would then make ntp requests to the ntp server on your LAN.  Your LAN ntp server will be the only machine they would query.
This would be the best method of making sure the machines on your LAN have near-matching times, as well as ensuring the LAN doesn't get get out of sync with the rest of the world.


Can't install packages after changing to KDE on Ubuntu 16.04

Question: After installing KDE on Ubuntu 16.04 I can't use unity anymore and when trying to download new software with apt-get I get error messages.
The following packages have unmet dependencies:
kde-telepathy-minimal : Depends: kde-config-telepathy-accounts (>=15.04.0) but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

When I try sudo apt-get -f install i get another error message.
0 upgraded, 1 newly installed, 0 to remove and 46 not upgraded.
2 not fully installed or removed.
Need to get 0 B/137 kB of archives.
After this operation, 825 kB of additional disk space will be used.
Do you want to continue? [J/n] j
(Reading database ... 445397 files and directories currently installed.)
Preparing to unpack .../kde-config-telepathy-accounts_4%3a15.12.3-0ubuntu1_amd64.deb ...
Unpacking kde-config-telepathy-accounts (4:15.12.3-0ubuntu1) ...
dpkg: error processing archive /var/cache/apt/archives/kde-config-telepathy-accounts_4%3a15.12.3-0ubuntu1_amd64.deb (--unpack):
trying to overwrite '/usr/share/accounts/services/google-im.service', which is also in package account-plugin-google 0.12+16.04.20160126-0ubuntu1
Processing triggers for libc-bin (2.23-0ubuntu7) ...
Errors were encountered while processing:
/var/cache/apt/archives/kde-config-telepathy-accounts_4%3a15.12.3-0ubuntu1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

I'm pretty sure i messed something up along the way and I read online that I will have to delete the damaged package but I don't really know how to do that without bricking my system.
Comment: Follow the David Xia's answer there. You basically need to use `sudo apt-get install -f -o Dpkg::Options::="--force-overwrite"`
Comment: Although this is a duplicate answer, I would like to comment one thing, `--force-overwrite`  will be my last option. Better go for [Avinash's answer](https://askubuntu.com/a/433510/146791).
Answer: What it says: Installing kde-config-telepathy-accounts tries to (over)write the file /usr/share/accounts/services/google-im.service, which also are in the package account-plugin-google .. this is a conflict between unity / gnome and KDE packages.
You can remove account-plugin-google (sudo apt remove account-plugin-google) or just remove the file (sudo rm /usr/share/accounts/services/google-im.service) and hope that the two packages can exist together ..
And in either case, rerun sudo apt-get -f install


Kubernetes run pod as root

Question: I am trying to deploy the Hashicorp Vault Helm chart, and I get the following issue: Error: container's runAsUser breaks non-root policy is there a way to run Vault as non root? or is there a way to only allow that service to run as root without changing the whole policy?
Comment: Based on [this code](https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kuberuntime/security_context.go#L87-L92) the only way you can see this error is when `runAsUser: 0` and `runAsNonRoot: true`. Is it what's happening in your case?
Comment: how do i change that?
Comment: Is it what's happening in your case? You should see it in pod object. Run `kubectl get pod  -oyaml`. Hashicorp Vault helm chart [by default runs as user 100](https://github.com/hashicorp/vault-helm/blob/master/templates/server-statefulset.yaml#L48). Did you change any defaults?
Comment: I left everything as default here is the user part of the pod:
fsGroup: 1000
    runAsGroup: 1000
    runAsNonRoot: true
    runAsUser: 100
Comment: In such case there shouldn't be any problems. Can you provide detailed step-by-step description how I can replicate your issue?
Comment: I found the issue, it was in the same namspace as my Azure Dev Spaces and there was a conflict there, moved to a new namespace and it was fixed
Answer: found the issue, it was in the same namespace as my Azure Dev Spaces and there was a conflict there, moved to a new namespace and it was fixed
Answer: The test container that's the base of the Helm Chart currently works with the directory in /root. So you must run the Chart with root or you will have to change the Chart completely.
FROM alpine:latest
WORKDIR /root

ENV BATS_VERSION "1.1.0"

# base packages
RUN apk update && apk add --no-cache --virtual .build-deps \
    ca-certificates \
    curl \
    tar \
    bash \
    openssl \
    python \
    py-pip \
    git \
    jq

Comment: is there a way to only run that container as root and leave policy for all the other containers?
Comment: You're free to make how many changes/customizations you need, but in this case, it's not recommended by Hashicorp.
Comment: I mean in the K8s side, because right now it doesn't let me deploy it getting this error " Error: container's runAsUser breaks non-root policy" is there a way to do kind of an exception for this chart?

Kubernetes run pod as root


How can I provide garbage collection for an interpreted language implemented in C?

Question: If I were to implement a garbage collected interpreted language in C, how can I go about providing precise (i.e. not conservative) garbage collection without writing my own garbage collector? Are there libraries available for this? If so, which ones? I understand that I would have to maintain certain invariants on my end for any objects tracked by the garbage collector.
Comment: Based on your implementation, count references to dynamic objects. Once they reach zero - discard.
Comment: You might like to take a look at some examples, like the Lua reference-impementation. It uses a tracing GC.
Comment: @EugeneSh. That doesn't work for circular references, for example. I'm looking for more of a conventional mark and sweep GC.
Comment: I don't think you will get any good answer, since it is totally based on the interpreter you are implementing. Maybe using an existing one and modifying only the syntax part will help.
Comment: @EugeneSh. Are you saying that every interpreter implements its own GC? I was really hoping for some kind of portable library.
Comment: Well ,since you are implementing your own interpreter, you might want to use some kind of virtual memory model, or even virtual machine to run the code. Well, this is what I would do in this case. So this is totally up to you how you manage the memory.
Comment: @EugeneSh. I'm totally ok with something like that, as long as the virtual machine can be run from C, and not the other way around. For example, can C start a JVM instance and allocate memory through it?
Comment: @Matt, no I was talking about specific virtual machine implemented to run the custom language.
Comment: @EugeneSh. Ok, but is there a library that would do that for me? I don't want to have to implement my own VM.
Comment: Why do you dislike conservative GCs like Boehm's GC?
Comment: Is your implementation free software (e.g. on github)? If yes, give the link
Comment: @BasileStarynkevitch: I want to provide a guarantee that there will not be any memory leaks (except of course those caused by client code). So far this is just a personal project and I have not plans to distribute it (yet).
Answer: If you want a precise GC (not a conservative one, like Boehm's GC, which performs quite well in practice) you should track local pointer (to GC-ed data) variables, or else invoke the GC only with a nearly empty call stack when you are sure there are no  such local variables (btw, the GCC compiler has such a mark&sweep garbage collector - with marking routines generated by some specialized gengtype C++ code generator; that GGC is invoked only between passes). Of course you should also track global (including static, or thread local) pointer (to GC-ed data) variables also.
Alternatively, have some bytecode virtual machine (like OCaml or NekoVM have), then the local GC-ed variables are those in the stacks and/or registers of your bytecode VM, and you trigger your GC at specific and carefully chosen points of your VM interpreter. (See this explanation of Ocaml GC).
You should read more about Garbage Collection techniques, see the GC handbook.
If your GC is copying generational, you need to implement write barriers (to handle mutation of old data pointing to new zone). You could use my old Qish GC (which I don't maintain much anymore), or Ravenbrook's MPS, or write your own generational copying GC (this is not that hard in theory, but debugging GCs is a nightmare in practice, so it is a lot of work).
You probably want to use some macro tricks (like my Qish does) to help keeping your local variables. See the Living in harmony with the garbage collector section of Ocaml documentation as an example (or look inside Qish).
Notice that a generational copying GC is not friendly to handle in manually written C code (because you need to explicitly keep local pointers, and because you need a write barrier to remember when an old value is modified to have a pointer to the new generation). If you want to do that, your C code should be in A-normal form (you cannot code x=f(g(y),z); but you need to code temp=g(y); x=f(temp,z); and add temp as a local variable, assuming that x, y, z are local GC-ed variables and that both f and g return a GC-ed pointer). In practice it is much easier to generate the C code. See my MELT domain specific language (to extend and customize GCC) as an example.
If your language is genuinely multithreaded (several mutator threads allocating in parallel), then coding a GC becomes quite tricky. It might take several months of work (and is probably a nightmare to debug).
Actually, I would today recommend using Boehm's GC (notice that it is multithread friendly). A naive mark&sweep handcoded GC would probably not be faster than Boehm's GC. And you won't be able (and I don't recommend) to use GGC, the garbage collector internal to GCC (which, IMNSHO, is not very good; it was a dirty hack design many years ago).
BTW, you might consider customizing -e.g. with MELT- the GCC compiler (by adding some application specific __attribute__  or #pragma) to help your GC. With some work, you could generate some of the marking routines, etc. However, that approach might be quite painful (I really don't know). Notice that MELT (free software, GPLv3+) contains a copying generational GC whose old generation is the GGC heap, so you could at least look inside the code of melt-runtime.cc
PS. I also recommend Queinnec's book: Lisp In Small Pieces; it has some interesting material about GC and their connection to programming languages, and it is a great book to read when you are implementing an interpreter. Scott's book on Programming Languages Pragmatics is also worth reading.
Comment: Look into Ravenbrook's MPS. It probably is very suited to your needs
Comment: Wow, I didn't know GCC came with a GC (and it's called GGC... too many acronyms!). That seems like it's exactly the sort of thing I was looking for, thanks!
Comment: The GGC is only internal to the GCC compiler. It does not matter to you (except as an example of GC, which I don't like much because I feel that GGC is not a very good GC implementation)
Comment: @Oh, that's disappointing. But it seems like it may be possible to use it if I link with the GCC source code. I guess borrowing an existing implementation from an open source project is probably the best way to get what I want. But thanks for all the other tips, too!
Answer: For C programs, there are 2 options: the Boehm GC which replaces malloc (it is a conservative GC, so perhaps not exactly what you're looking for but it's either that or...), or write your own.
But writing your own isn't that hard. Do the mark-sweep algorithm. The root set for marking will be your symbol table. And you'll need another table or linked-list to track all of the allocated memory that can be freed. When you sweep through the list of allocations, free anything without a mark.
The actual coding will of course be more complicated because you have to iterate through these two kinds of data structures, but the algorithm itself is very simple. You can do it.

A few years ago, I found myself on the same search and these were (and AFAIK still are) the results. Writing your own is tremendously rewarding and worthwhile.
In practice, a great many other issues will arise as Basile's answer touches upon.
If the garbage collector is called from deep in the call-stack (by an allocation routine that needs more memory, perhaps), then care must be taken about any allocations whose handles are still held in local variables of C functions in the call stack, and not saved-out to their symbol-table or database locations. In my postscript interpreter I dealt with this by using a temporary stack which all allocators pushed to. This stack was cleared by the main loop after all subroutines had returned, and it was considered part of the root set during marking. In my APL interpreter, I call the GC everytime around the mainloop. For the little programs in little languages, the speed issues are less vital than the more-dreaded memory leakage, at least among the circles which have influenced me.
Comment: The question is about a *precise* GC, not a conservative one.
Comment: Thanks @BasileStarynkevitch, I've added a note that it's not exactly the same.
Comment: BTW, your answer is not exactly correct. My answer contain pointers to existing software which might be reused or inspirational.
Comment: My goal was to illustrate a simplified but complete algorithm. I do like your answer. Is mine missing something?
Comment: Well, a manually written mark&sweep GC has not much advantage over Boehm's GC.
Comment: @BasileStarynkevitch: It has the advantage of being precise rather than conservative.
Answer: When implementing such a language, your interpreter needs to keep track of all objects in the program it's running, including knowledge of their types and what part of the data is a reference to other data. Then it's trivial for you to walk all the data and implement whatever sort of garbage collector you like. No bogus hacks like trying to determine where the C implementation's "heap"/"stack"/etc. are located or guessing at what might be a pointer is needed, because you're dealing exactly with the data whose structure you know.
Comment: Obviously I can take the time and implement my own less-than-mediocre GC. I want to know whether there are existing solutions to this problem. And of course I know that I will have to provide some sort of information about where the pointers are.
Comment: As far as I know, asking for library suggestions is off-topic on SO, but I'm not aware of anything you can just plug in anyway.


How do you solve the liebard riddle about the wind farm?

Question: When you find and talk to the treasure hunter in the wind farm, he gives you a riddle.

I tried interacting with every single windmill in the place and nothing happened except one of them burned down.  What gives?
Answer: I'm Willy, the creator of Ramble Planet. I wouldn't take anything he says too seriously. Mostly it's just a bunch of misdirection.
However, the Liebard is important for something. His position on the surface rotates based on the minutes on the game's timer. If you manage to talk to him while he is in The Isles, he will give you a PART.
Comment: I was wondering why he kept moving around.  What does your time have to be at to catch him on the isles?


No. of finite group (nonidentity)elements $x$ satisfying $x^5=e$ is a multiple of $4$

Question:
In a finite group $G$ with $e:=\text{id}_G$, show that the number of nonidentity elements that satisfy the equation $x^5=e$ is a multiple of 4.

This is number $50$, Ch.$2$ from Gallian's text. I have seen two repeats of this question on MSE (Show that number of solutions satisfying $x^5=e$ is a multiple of 4?, In a finite group, show that the number of nonidentity elements that satisfy the equation $x^5=e$ is a multiple of 4.) but I still have questions about the question and my proof.
My first question:
Do we have to assume that $x^5=e$ for some $x\in G$ in the first place? My thinking is that this is a yes since in general a finite group may not have such an $x$.
Proof of claim:
Suppose some $x\in G$,$\space$$x\neq e$ satisfies the condition $x^5=e$. Then note that $x^2\in G$ and $$(x^2)^5=(x^5)^2=e^2=e$$ so $x^2$ satisfies the condition. Similarly $x^3\in G$ and $x^4\in G$. Observe that $$(x^3)^5=(x^5)^3=e^3=e$$ $$(x^4)^5=(x^5)^4=e^4=e$$ so that $x^3$ and $x^4$ also satisfy the condition. Once we verify that $x,x^2,x^3,x^4$ are distinct and that $x^i\neq e$ for $1\leq i \leq 4$ we will have proved the claim since for every $x$ that is a solution, so is $x^2$,$x^3$, and $x^4$. Thus solutions come in multiples of $4$.
Note that we don't consider elements like $x^6$ or $x^7$ as solutions because $x^6=x$ and $x^7=x^2$ i.e. for $n>5$, $x^n=x^i$ where $i\in\{1,2,3,4,5\}$. So, considering powers of elements modulo $5$ is enough.
To show each $x^i$ is distinct, we assume the contrary. That is, assume $$x^i=x^j$$ for some distinct $i,j\in\{1,2,3,4\}$. Thus if we take $i$ to always be the greater of the two, $$x^i=x^j\iff x^{i-j}=e$$ so $$i-j=1,2\text{ or } 3$$
Note it is impossible $i-j=1$ by the assumption that $x\neq e$. If $i-j=2$ or $i-j=3$, then $$x^2=e\text{ and } x^3=e\implies x^3=x^2\cdot x=e\cdot x=x = e$$
but the latter shows $x=e$ if $x^3=e$ and $x^2=e$; this is a contradiciton. Thus it must be false that $x^i=x^j$ for some distinct $i,j\in\{1,2,3,4,5\}$.
In proving the above, we saw that the $x^2=e=x^3$ leads to a contradiction, so to show the last claim, namely that $x^i\neq e$, we show that $x^4\neq e$. Again assume that indeed $x^4=e$. Then $$x^4=e=x^5\iff e=x\therefore\text{ contradiction }$$ $\blacksquare$
My second question:
Is the above proof correct? By removing the condition that the group be finite, how could this change the conclusion about the number of solutions? I never really utilized that $G$ was finite above (maybe tacitly? I don't know) so I'm pretty stumped on this one.
Comment: For your first point, you do not have to assume that $x^5 = e$ for some $x\neq e$, since if this doesn't hold, the number of such elements is 0 and 4 does divide 0. For why you assume finiteness, note that the infinite product of $\mathbb{Z}_5$ with itself has an $infinite$ number of such elements, and so the claim that 4 divides this number does not make sense. Basically, the finiteness of the group guarantees the finiteness of the set under consideration. Proof looks good!
Comment: You still need to show that no two sets of four elements you make in this way have an element in common (hint: if you think in terms of subgroups and Lagrange's thm, this is an easy observation)
Comment: Almost.  The intersection should either be empty or equal to $\{x,x^2,x^3,x^4\}$  The easiest way, absent lagrange's theorem, is to first assume $y=x^i$ and show you get the whole set again.  Then assume $y$ isn't one of the powers of $x$ but $x^i=y^j$ and reach a contradiction.
Comment: It is not correct for me. For example if you consider x such that $x^2=e$, then you have that it satisfies your condition but $x^3=x$
Comment: @Federico If $\exists x$ s.t. $x^2=e$ then $x=x^{-1}$ so $x^5=x\cdot x\cdot x\cdot x\cdot x=x\cdot x^{-1}\cdot x\cdot x^{-1}\cdot x=e\cdot e \cdot x=x$. So that $x$ wouldn't satisfy the condition, right?
Comment: @BrianMoehring I saw something like that from James in the first answer I linked... although by chapter 2, Gallian has only developed uniqueness of identity and inverse, cancellation, and the 'shoe-socks' property. To show what you're proposing, take $x$ and $y$ as solutions. Then we have to show $\{x,x^2,x^3,x^4\}\cap\{y,y^2,y^3,y^4\}=\emptyset$?
Comment: Okay @BrianMoehring, I will try that. Thank you!
Answer: In general, if $p$ is an odd prime and $G$ a finite group, then $\#\{ g \in G: g^p=1\} \equiv 1$ mod $(p-1)$. Observe that the set includes the identity element. Proof (sketch): on the set $S=\{ g \in G: g^p=1\}$ define an equivalence relation: $g \sim h$ if and only if $\langle g \rangle =\langle h \rangle$. Then $S$ partitions in $\{1\}$ and equivalence classes of order $p-1$ (namely $\langle g \rangle -\{1\}$ for each non-identity $g \in S$).
Answer: Let $G$ be a finite group with identity $e$. Let $x\in G$ such that $x^5=e$. Then as you obtained there are four other elements that follows same relation. Your proof is correct, but you make this so cumbersome. By the way I am giving a general idea to you, for any $x\in G$ such that $x^k=e$  the number of non-identity elements of $G$ satisfy the equation $x^k=e$ is a multiple of $\phi(k)$, where $\phi$ is Euler function.
You make see this in an easy way, using the formula,
$$\circ(x^r)=\frac{\circ(x)}{gcd(r,\circ(x))}$$
Comment: Why am I getting this (-1)? Can anyone explain?


Bathroom Sink Clog

Question: I've had an ongoing battle with my bathroom sink. A little over a year ago, I successfully cleared a clog using a liquid drain cleaner but noticed some leaks at the juncture of the J-bend, and so I replaced the plumbing under the sink (p-trap and slip nuts). Fast forward one year, and the clog is back with a vengeance. I dismantled the P-trap and cleaned out what I assume was some minor soap slime, but there was no clog, suggesting that the clog is somewhere in the wall. I again used a liquid drain cleaner and again successfully cleared the clog - or so I thought. Two days later the drain was again clogged, and this time the water is draining much more slowly. I tried using a liquid drain cleaner a third time, but this time the clog isn't moving. Before I spend money on either an auger or plumber, I have a couple of questions:

Is it possible that this clog has something to do with the way I installed the P-trap? For example, does the P-trap have to be pitched in a particular manner? It seems unlikely that this is the problem, given that I went nearly a year without any problems after installing the P-trap.
I live in condo complex and I've had yearly problems with backflow in my bathtub as well, which has required snaking. It turns out that my bathtub drain forms a tee with my neighbor's before connecting with the main line, and plumbers have suggested that my neighbor's thick black hair may be the culprit (based on the hair captured by the auger). Do bathroom sinks typically form tees with neighboring sinks in large condominium complexes, or are they usually on separate lines?

Any suggestions as to how to proceed with this clog would be appreciated. I assume a drain auger is the next step.
Comment: I would also check around the popup drain plug.
Comment: Hi Duston, I've removed the pop-up drain plug and the clog is still intact. I've also used a wooden rod to clean the tailpiece running between the drain opening and the P-trap and flushed it with water, and it appears to be clear.
Comment: Is the availability of a drain snake/auger the issue?  You can get a small one for pretty cheap.
Comment: Availability is not necessarily a problem. My local Home Depot rents augers, but I was trying to start with a cheaper, more conservative approach before spending money on an auger or plumber. It seems that it's cheaper to purchase an auger and, considering the numerous plumbing issues I've encountered, it might save me some money in the long run.
Comment: There is no way that an improperly installed P-trap can cause a clog further downstream (although it can cause other problems). So you can cross that off the list of things to worry about.
Comment: Good to know. Thanks Mike!
Answer: I agree that it's probably not the P trap.
It's pretty common for condo/apartments to share main drains. Has your neighbor had problems too? Liquid drain cleaners will work for only so long and then usually an auger or snake is needed. You can pick up a inexpensive snake at your home store and try that out. It could definitely solve your problem. If not, you have to consider the possibility of tree roots breaking into the pipes. If you have a condo association they might foot the bill if more than one unit has the problem... Good luck.
Comment: Thanks very much for your suggestion, Jack. Two days after I called a plumber to clear my bathtub drain due to backflow last year, I heard a plumber snaking out my neighbor's bathtub drain and I ran over and spoke to the plumber. He told me that he was able to get some hair out of the line, though he said it was further than 15 feet down. So, yes, my neighbor has had problems. The HOA paid to have a plumber snake the bathtub drain last week, as I was again experiencing backflow, but the plumber would not snake the bathroom sink drain, since the work order listed only the bathtub drain.
Comment: think about buying a snake and running it down your sink drain. Remove  the trap so you don't have to feed the snake down the sink pipe and through the trap.
Comment: Thanks Jack! I purchased a drain auger. I'll remove the P-trap and feed the auger directly into the wall. I appreciate your help.

Bathroom Sink Clog


optimizely server side experiments tracking the events

Question: I'm performing a server side experiment where our results are A/B tested on a small fraction of users before launching to everyone.We use optimizely sdk library for java .we have experiment setup in optimizely ui and we call activate method for that experiment and user id to get the variations .since this the server side setup , we don't see the metrics like products added ,add to cart being tracked in optimizely ui . How to get those metrics logged in optimizely ui? Any suggestions will be helpful.
Comment: we are using Optimizely library com.optimizely.ab. we are calling the Optimizely activate method like this in our code.
 Variation variation = optimizely.activate(experiment, userId);                                     we dont specifically track the events as its server side experiments.
Comment: Are you able to share what code you are using to activate an experiment and send metrics?
Answer: You need to specifically call Optimizely.track at the point where you have add to cart or purchase events. If those events are recorded server side, you could record it when the call is made to the server to update the cart. If the events are only persisted on the webpage, you would use the Optimizely JavaScript SDK to fire the track event in the browser when the user hits "add to cart". The two SDKs would use the same project ID since you are running the experiment across server side and client side.
https://docs.developers.optimizely.com/full-stack/docs/track-events


What kind of timer is most suitable for MIDI timing?

Question: I am writing a simple MIDI app for my own use, in C# and .NET 4.x.
I assume that commercial DAWs (on the Windows platform that is) use Windows Multimedia Timers for timing the playback of MIDI data. But I can't verify this, since commercial stuff is closed-source.
I'm hoping someone has knowledge in this area, and can tell me if my assumption is right. Or, are these DAWs using timers I'm not aware of? I want to make sure there isn't anything more suitable that I've overlooked.
Comment: Audio, in general, requires accurate timing. Choosing a platform with unpredictable performance characteristics, like .NET, is questionable.
Comment: @IInspectable Good point and I'm aware of it - I may port what I've done so far to C++/Native WinApi if early tests demonstrate issues. But the question around what timer to use still stands in either case.
Comment: It is my understanding that MIDI requires millisecond accuracy. I doubt that any commercial DAW delegates that sort of accuracy to standard system timers.
Comment: You don't need a driver to spin in a loop until a high precision timer (like `rdtsc`) reaches its target time. If I were to implement a DAW on Windows without dedicated MIDI hardware I'd probably use a system timer to land at a time point prior to the target time, and then actively spin for higher accuracy.
Comment: @IInspectable Indeed, that's my suspicion too, but DAWs like Reaper don't appear to install any special system-level drivers that I thought would be necessary for precision timing. So the mystery remains - if not existing system timers, what timers are DAWs using for MIDI playback (not to be confused with digital audio or video, which is quite different)
Comment: As I pointed out, you don't need a timer to implement accurate timing. Requesting the current (high precision) time in a loop is sufficiently accurate for nanosecond timings. Also, you often don't need to install a driver to communicate with a device. The system already has drivers for standard protocols like USB that clients can use to control custom hardware without the need to install a kernel driver.
Comment: @IInspectable But, using a timer is key in achieving low CPU usage. Even intelligent "targeted" spinning would drive a CPU core to 100% during periods of dense MIDI. Looking at Reaper and Cakewalk CPU usage, I see no evidence of spinning - very low CPU usage even in dense MIDI tracks.
Comment: If you want to know how existing DAW systems are implemented, you're going to have to reverse engineer their respective implementations, assuming this is legal in your jurisdiction. As a preliminary step you can inspect their import tables and see if/whether they import system-provided timer interfaces. Though I doubt you'd be able to see a timer/active spinning hybrid implementation sketched out in a previous comment by looking at the CPU consumption in Task Manager.
Comment: @IInspectable I'm sorry - I think we both got off track here. I'm hoping that someone with experience in coding DAWs or MIDI apps actually knows the answer to my question and will share it with us. So I will give it some time and see if we get an answer, fingers crossed :-)
Comment: Windows doesn't provide any timers with millisecond accuracy. A software system that requires millisecond accuracy isn't going to be using any of Windows' timers. That is essentially the answer to your question.
Comment: Yes, timeBeginPeriod() and timeSetEvent() gives you a timer accurate to 1 millisecond.  Plenty good enough for human ears.
Comment: @han `timeBeginPeriod` isn't guaranteed to allow for a resolution down to 1ms. And resolution is not the same thing as accuracy. Besides, 1ms is **far** from the timing requirements of MIDI 2.0. This is used in professional music production. Being good enough for human ears doesn't quite cut it.
Answer: Although I have not had the privilege of coding for commercial DAW projects specifically, I do have experience in coding for scenarios where the accurate timing of events is important, including MIDI processing/routing.
Your assumption is correct. Well-coded MIDI sequencers use the Windows Multimedia Timer to schedule the sending of MIDI messages to MIDI devices.
Microsoft's Multimedia Timer Reference actually mentions MIDI sequencing as an example use:

These timer services are useful for applications that demand high-resolution timing. For example, a MIDI sequencer requires a high-resolution timer because it must maintain the pace of MIDI events within a resolution of 1 millisecond.

How to use the timer is for another topic, I won't get into that here. But I'd like to point out a few things:

All modern hardware supports a timer resolution of 1 millisecond, it's basically a given, but you should still call timeGetDevCaps to make sure before calling timeBeginPeriod.

Using the multimedia timer, at 1 millisecond resolution, will have the effect of quantizing your MIDI messages to a 1 millisecond grid +/- some variance/jitter. In the vast majority of cases this is a non-issue because that is still a sufficiently fine resolution to provide reasonably nuanced timing, so far as musical timing goes anyway. If you absolutely need sub-millisecond timing, you will have to do as @iinspectable suggests - use the timer to get "close" and then spin to precisely time the sending of your MIDI messages. However, this approach comes at a cost. I don't know what your intentions are for the app, but should you have several simultaneous MIDI tracks playing, each with continuous controllers and pitch bend, you'll find your app spinning all the time and you'll peg a CPU core to 100% which is just plain bad.

Do look into Windows' Multimedia Class Scheduler Service to get prioritized access to CPU resources for your MIDI playback thread.

Don't be discouraged by comments from @iinspectable. You can absolutely do high-performance MIDI sequencing using C#/.NET. Your only concern needs to be that of the garbage collector unpredicatably pausing your app. You can always code in a way that minimizes GC (e.g. use structs not classes, don't create/destroy anything during playback). Also consider using GC.TryStartNoGCRegion to, for example, prevent GC pauses during playback.
Comment: Thank you for such a thorough answer and the useful tips. Much appreciated!


SELECT RECORDS INTO ARRAY

Question: I'm neubie with PHP. I need to build some Web Service so, I have problems.. please help me.
I have this code, I have to put in array the Select's records and the return in JSON.
The CODE...
 function redeem() {
 // Check for required parameters
if (isset($_POST["id_cliente"]) && isset($_POST["id_sucursal"])) {
    // Put parameters into local variables
    $cliente = $_POST["id_cliente"];
    $sucursal = $_POST["id_sucursal"];
    $stmt = $this->db->prepare('SELECT id_arbitro FROM arbitro WHERE id_cliente =? AND id_sucursal =?') or die(mysqli_error($this->db));
    $stmt->bind_param("ii", $cliente, $sucursal);
    $stmt->execute();
    //$stmt->bind_result($id_arbitro);
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
      $cuantos = count($result);
    echo "$cuantos";

    $registros = 0;
    /*while ($stmt->fetch()) {
        $registros ++;
        // Return unlock code, encoded with JSON
        $result = array("id_arbitro" => $stmt,);
        echo "$id_arbitro !";
    }
    */
    $stmt->close();
    if ($registros < 0) {
        sendResponse(400,"No existen arbitros con los parámetros recibidos");
        return false;
    }

    //echo json_encode($result);
    sendResponse(200, "FIN");
    //printf("ERROR %s",$registros);
    return true;
}
sendResponse(400, 'Invalid request');
return false;

}
Comment: So which part are you having trouble with? We can't see the syntax of the class `$this->db` points to, but you essentially need to iterate the results, put them into an array, and json_encode(); it
Comment: Hi Helion. SELECT instruccion it's fine works .. If I uncomment the WHILE instuction, I can get value in $registros variable, but I can't put the records in the array ... $result = array("id_arbitro" => $stmt,);, when I tried to get de count array's items I only have gotten one record count($result), that it's my trouble
Comment: I've answered based on this information.
Answer: To encode the results of your query, use something like that
$statement=$pdo->prepare("SELECT * FROM table");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);

Comment: how can I check that $results has all my records, with count($results) ? ... becouse last doesen't work
Comment: Yes, you should be able to do sizeof($results) or count($result).
If you wan to return the count in your json, just do:

return json_encode(array('Result'=>$results, 'count' => sizeof($results));
Answer: Based on your comment, you're having trouble understanding how to put them all into an array.
First, make sure that whatever you use for database calls doesn't already have a fetchAll style function that could do this for you.
If you still need to do, you need to define an array first and then add to it:
$results = array();
while ($record = $stmt->fetch()) {
    $registros ++;
    $results[] = $record;
}
print json_encode($results);

The syntax might vary slightly for your database class but this gives you an idea.
Comment: I've provided an example of a loop but you need to look at the documentation for the database access classes you're using.
Comment: I work with Mysql ..  $this->db = new mysqli('localhost', 'futchoco', 'Futcho19', 'futchoco_futsoft');

SELECT RECORDS INTO ARRAY


What to use instead DbEntityValidationException in EF Core?

Question: With EF I used DbEntityValidationException catch branch (along with others)
catch (DbEntityValidationException exception)
{
    // any statements here...
    throw;
}

Now using .NET Core 3.17 with EF Core 3.17 and apparently there is no DbEntityValidationException and also reviewed EF Core 3.17 sources, and no traces of that exception type. (Note, I am not only talking about where it is defined, I mean it is not thrown any places in the EF Core 3.17 sources)
Question
How to migrate the code above to EF Core 3.17?
Comment: [DbUpdateException](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbupdateexception?view=efcore-3.1) is likely what you're after.
Comment: thx, going to examine
Comment: Note that DbUpdateException does not have collection of exceptions(probably intentionally)
Answer: When you look at the documentation for DbEntityValidationException, you can see the versions it applies to are only:  4.3.1, 5.0.0, 6.2.0.
Now if you look at the docs for SaveChanges (assuming that's what you're calling inside your try block, you can see that it now only throws DpUpdateException and DbUpdateConcurrencyException.  So I think what you probably want is the below, since that should catch any exception while saving to the db.  I'd think validation would be included in that.
catch (DbUpdateException exception)
{
    // any statements here...
    throw;
}

Answer: Model validation on save is gone from EF core. This is a quote from EF developers:

Validation happens on the client, then again in the action to protect against malicious requests. Most validation also happens in the database too (nullability of columns, max length of data, etc.). Obviously not all apps go that far, but validating during SaveChanges is usually just front loading an exception you would get from the database and adding overhead to do that.

Said that, if you deem you need it one more, your objects could implement IValidatableObject and that interface could be used by overriding SaveChanges:
public override int SaveChanges() {
    var validationErrors = ChangeTracker
        .Entries<IValidatableObject>()
        .SelectMany(e => e.Entity.Validate(null))
        .Where(r => r != ValidationResult.Success);

    if (validationErrors.Any()) {
       // Possibly throw an exception here
    }

   return base.SaveChanges();
}

See also: https://long2know.com/2016/07/porting-ef6-to-ef7-or-ef-core/


Rotate line around center

Question: I have to use a propriertary graphics-engine for drawing a line. I can rotate the whole drawing by its origin point (P1). What I want, is to rotate it around its center point(M). So basically that it looks like the green line (L_correct instead of L_wrong).
I think, it should be possible to correct it, by moving it from P1 to P2. But I cannot figure out what formula could be used, to determine the distance. It must probably involve the angle, with and height... Can anyone give me a hint?
Answer: Trick is, to move the entire object so that the point about which you want to rotate is at the center. Then rotate and after that counter move it so that the point is were it was.
In fact this is not so much of a trick, as such, nearly all graphics engines work this way. It is just abstracted away in many cases. Most often you will see it done in matrix notation like this:
$$ T^{-1} R T $$
Where T is to transformation from world to pivot and R is the rotation matrix. Since it can be easily packaged this way you end up with a function called rotate about the pivot point. This is usually the reason why drawing API's allow for a transformation matrix.

Image 1: Rotate about a pivot point, image source available for investigation. Sub images in RTL reading order: Original, inverse transform, inverse and rotate, inverse rotate and move back.
Answer: I am a bit unsure if my calculations are correct, but on my scribbling paper it seemed to work out.
P1 and P2 lie on a circle around M.
This allows us to measure the distance of the two points by just taking the radius (which is half the line length) of the circle and constructing two rectangular triangles. The accepted answer here provides a sketch for this construction.
So given your rotation angle is $\gamma$ and the line is $l$ long it follows:
$x = 2* sin(\frac{\gamma}{2}) * \frac{l}{2}$
The lines M to P1 and M to P2 form a isosceles triangle with the third side being the line segment between P1 and P2.
The angle at point M is known to be the rotation angle $\gamma$ so the remaining two angles in this triangle are given by
$\alpha = \frac{180 - \gamma}{2}$
And therefore the angle between the wrong line and the needed translation vector is just
$\beta = \alpha + \gamma$
So now you rotate a unit vector that starts along the wrong line.
You rotate it around P1 for $\beta$ and scale it to length x.
This yields the translation vector from P1 to P2. The rotation of the line should indeed be correct.
Comment: Though in general it is far easier to just use the construction joojaa explained in his answer.

Rotate line around center


How to free pointer's space in memory?

Question: I have question about pointers in C. Each pointer has 4 bytes in memory (address). When I call malloc() it only allocates memory and put it's address to the pointer, also free() only frees the memory that pointer is pointing to. But how can I delete pointer (4 bytes) in memory that I no longer need ? Isn't there a memory leak ?
Answer: The pointer itself is a regular variable, which means that when it goes out of scope those 4 bytes allocated for it will automatically be freed, just like any other variable you might have declared on that same scope.
Comment: @quarry Doesn't matter if it's a pointer or an int. Just imagine if it's an int and see if it makes sense.s an int and see if it makes sense.
Comment: @quarry If that pointer allocate's memory and then you return it, you are actually returning the memory address of the newly allocated space, and not the memory address of the variable pointer. Does this make any sense to you?
Comment: @quarry: `main()` is a function just like any other, so variables declared in it have local scope.
Comment: @ninjalj The question was "what happens when you allocate memory for a pointer and then *return* the pointer as the return of function". Humm, I see you edited your comment. Ok.
Answer: The pointer variable itself typically has automatic storage duration, i.e. it's on the stack, so the memory occupied by it will be reclaimed and reused once the variable goes out of scope.
Comment: It could also have global scope
Comment: @Steve: Yes, of course, thanks. In that case it would have static storage duration, i.e. the memory is allocated at load time and freed at termination time.
Answer: Typically the pointer will be held in a stack variable. Or traced back through heap allocated pointers to a stack variable. The stack is statically allocated and freed when the process terminates. Thus nothing is leaked.
Answer: A pointer is just a normal variable, and has the same lifetime a normal variable would have in its place. I it's a local non-static variable, its lifetime ends when it goes out of scope. If it's a variable with static storage duration, its lifetime ends when the program ends. If it's located on dynamically allocated memory, its lifetime ends when that memory is freed, and for the future C1x standard, if it's a thread-local variable, its lifetime ends when the thread ends.
Answer: in an nut shell..you can not free up a pointer location or memory by any code or command..for you might be wanting to make a perfect program of codes..with acute memory consumption..i get it ..but you cant..
thanks..

How to free pointer's space in memory?


Binding Pushpins in ObservableCollection to Bing Maps Control WP7

Question: I'm working on a Windows Phone 7 Project (Mango) and am trying to bind Pushpins to my silverlight Bing Maps control using an ObservableCollection, but it wont work. I've been sat here for the last 5 hours, scouring the internet and other questions on stackoverflow and have implemented some answers but can't find one which works :(
I would be very grateful for any ideas as to why its not working. I'm pretty sure its to do with my XAML as my ObservableCollection is populated correctly (checked at runtime using breakpoints) with valid Locations. For the moment my ObservableCollection is only populated with two locations, however I will be looking to increase this number when I start using the Bing RouteService.
Here is the code:
public partial class MapView : PhoneApplicationPage
{
    private readonly CredentialsProvider bingMapsCredentials = new ApplicationIdCredentialsProvider(App.BingMapsKey);
    private GeoCoordinate geoDestination;
    private GeoCoordinate geoCurrentLocation;
    public ObservableCollection<PushpinModel> PushpinCollection { get; set; }

    public MapView()
    {
        InitializeComponent();

        geoDestination = new GeoCoordinate(54.975556, -1.621667);
        geoCurrentLocation = new GeoCoordinate(53.463056, -2.291389);

        CreatePushpins();
    }

    private void CreatePushpins()
    {
        PushpinModel currentLocationModel = new PushpinModel();
        PushpinModel destinationLocationModel = new PushpinModel();

        currentLocationModel.Location = geoCurrentLocation;
        destinationLocationModel.Location = geoDestination;

        PushpinCollection = new ObservableCollection<PushpinModel>();
        PushpinCollection.Add(currentLocationModel);
        PushpinCollection.Add(destinationLocationModel);
    }

Below is the PushpinModel Class:
using System.Device.Location;

namespace NavigationApp
{
    public class PushpinModel
    {
       public GeoCoordinate Location { get; set; }
    }
}

And below is the offending XAML (I think!):
<phone:PhoneApplicationPage
    x:Class="NavigationApp.MapView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:NavigationApp"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True"
    xmlns:my="clr-namespace:Microsoft.Phone.Controls.Maps;assembly=Microsoft.Phone.Controls.Maps">
    <phone:PhoneApplicationPage.Resources>
        <local:PushpinModel x:Key="PushpinModel" />
        <DataTemplate x:Key="LogoTemplate">
            <my:Pushpin Location="{Binding Location}" Background="#FFB6DE2E" />
        </DataTemplate>
    </phone:PhoneApplicationPage.Resources>

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="0"/>
            <RowDefinition Height="768*"/>
        </Grid.RowDefinitions>

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"></StackPanel>

        <Grid x:Name="ContentPanel" Grid.Row="1">
            <my:Map Height="520" HorizontalAlignment="Left" Margin="6,6,0,0" Name="map1" VerticalAlignment="Top" Width="468" ZoomBarVisibility="Collapsed" ZoomLevel="1" CredentialsProvider="{Binding bingMapsCredentials}" >
                <my:MapItemsControl Name="Pushpinsss" ItemTemplate="{StaticResource LogoTemplate}" ItemsSource="{Binding PushpinCollection}" >
                 </my:MapItemsControl>
            </my:Map>
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>

If you need anymore Code/Info then just let me know :)
Thanks
Ryan
Solution
Changed ObservableCollection to:
        private ObservableCollection<PushpinModel> PushpinCollection;
    public ObservableCollection<PushpinModel> pushpinCollection
    {
        get
        {
            return PushpinCollection;
        }
    }

And XAML is now:
 <my:MapItemsControl Name="Pushpinsss" ItemTemplate="{StaticResource LogoTemplate}" ItemsSource="{Binding pushpinCollection}" >

Answer: From your code it seams you forgot to set the DataContext. You can do this with:
public MapView()
{
    InitializeComponent();

    geoDestination = new GeoCoordinate(54.975556, -1.621667);
    geoCurrentLocation = new GeoCoordinate(53.463056, -2.291389);

    CreatePushpins();
    DataContext = this;
}

By the why, you can only bind to properties. So this won't work:
private readonly CredentialsProvider bingMapsCredentials =
    new ApplicationIdCredentialsProvider(App.BingMapsKey);

XAML:
<my:Map ...  CredentialsProvider="{Binding bingMapsCredentials}" ... />

Use a wrapper propery instead:
private readonly CredentialsProvider bingMapsCredentials =
    new ApplicationIdCredentialsProvider(App.BingMapsKey);

public CredentialsProvider BingMapsCredentials
{
     get { return bingMapsCredentials; }
}

XAML:
<my:Map ...  CredentialsProvider="{Binding BingMapsCredentials}" ... />

There is a good overview about DataBinding on MSDN (it's about WPF but the most part also applies for WP7)
Comment: Thanks very much for the speedy reply, the Bing map credentials was actually working fine, however I've taken on board what you've said about the wrapper property and have implemented that for my ObservableCollection and also set the data context and it works brilliantly!!!

See the "Solution" section of the original post for the modified XAML and C#


ICE servers URL

Question: Why there is no :// in the URL of the ICE servers?
stun:stun.example.com
turn:turn.example.com

Is the following valid too?
stun://stun.example.com
turn://turn.example.com

Answer: The definitions say these URLs are not valid with slashes:
https://www.rfc-editor.org/rfc/rfc7064
https://www.rfc-editor.org/rfc/rfc7065
The "why" is hard to answer, you would have to crawl the IETF mailing list archives for that rationale.

ICE servers URL


Android crashes trying to build fragments

Question: I have an Android app and it has been recently crashing building some Fragments. This doesn't happen always, just occasionally.
This is the typical crash log:
Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mycompany.myapp./com.mycompany.myapp..ui.activities.MainActivity}: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.mycompany.myapp..l.a.a1: could not find Fragment constructor
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3534)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3689)
       at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
       at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
       at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2239)
       at android.os.Handler.dispatchMessage(Handler.java:107)
       at android.os.Looper.loop(Looper.java:227)
       at android.app.ActivityThread.main(ActivityThread.java:7822)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1026)

So far I was building the fragments this way:
    String fragmentName = MyFragment.class.getName()
    Fragment fr = Fragment.instantiate(this, fragmentName);
    final FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.frame_content, fr, fragmentName);
    ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
    ft.commit();
    fm.executePendingTransactions();

And this crash never happened until a couple of months ago. I don't know if I changed something or it's related to Android version (I'm compiling with SDK 29).
Trying to solve the problem I changed the way I build the fragments to use FragmentFactory:
    String fragmentName = MyFragment.class.getName()
    final FragmentManager fm = getSupportFragmentManager();
    FragmentFactory ff = fm.getFragmentFactory();
    Fragment fr = ff.instantiate(getClassLoader(), fragmentName);
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.frame_content, fr, fragmentName);
    ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
    ft.commit();
    fm.executePendingTransactions();

But the crash is still happening.
Taking into account the log it seems like the fragment class name is obfuscate or something like that and Android is not able to deobfuscate it.
In case it's important I have this gradle configuration:
buildTypes {
    release {
        minifyEnabled true
        firebaseCrashlytics {
            mappingFileUploadEnabled true
        }
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

And my Proguard-rules.pro file includes this:
-keepattributes SourceFile,LineNumberTable        # Keep file names and line numbers.
-keep public class * extends java.lang.Exception  # Optional: Keep custom exceptions.

Answer: Don't initiate your Fragments with the "instantiate" function, to fix the error look at this answer https://stackoverflow.com/a/62931666/5313283


Why do I have to be outside the package's folder to properly execute the class file?

Question: (Note: I know I am not using standard naming conventions here. The names are simply for the purpose of simplicity.)
I have a file called 'PackageTest.java'. It's sole purpose is to print a line to the console saying, "This works!". It belongs to a package named main. In my console I execute the command:
javac -d . PackageTest.java

This creates a new directory (folder) called main, which contains the class file named 'PackageTest.main'. I am CD'd into it's parent directory, and I execute the following command:
java main.PackageTest

And the console then reads:
This works!

So the file executed. That's good. Now I CD into the 'main' folder. I execute the command:
java main.PackageTest

Only to get the result:
Error: Could not find or load main class main.PackageTest
Caused by: java.lang.ClassNotFoundException: main.PackageTest

So I try this command:
java PackageTest

And now I get this error:
Error: Could not find or load main class PackageTest
Caused by: java.lang.NoClassDefFoundError: main/PackageTest (wrong name:
PackageTest)

Why do I have to be outside of the directory to allow the file to execute?
Answer: The package (and folder) are semantically meaningful. You can specify the classpath, if you use an absolute path you can move anywhere in your tree and still run the code. It's also possible to use a relative path. Like,
java -cp .. main.PackageTest


Force g++ to look for Boost in one location ignoring other settings

Question: I am trying to compile graph-tool from source on Ubuntu 16.04 but have the problem that it fails to pick up the correct boost libraries. I am trying to compile it against anaconda python so have to provide additional flags to ./configure. I try to run the following:
./configure CXX="g++-5" CXXFLAGS="-std=gnu++14 -Wno-unused-local-typedefs" CPPFLAGS="-I/home/pmj27/anaconda2/lib" PYTHON="/home/pmj27/anaconda2/bin/python2.7" CAIROMM_LIBS="-L/home/pmj27/anaconda2/include/cairomm-1.0/cairomm" --enable-openmp

This however fails with the following error message being displayed in the terminal window
checking for boostlib >= 1.54.0... configure: We could not detect the boost libraries (version 1.54 or higher). If you have a staged boost library (still not installed) please specify $BOOST_ROOT in your environment and do not give a PATH to --with-boost option.  If you are sure you have boost installed, then check your version number looking in <boost/version.hpp>. See http://randspringer.de/boost for more documentation.
checking whether the Boost::Python library is available... no
configure: error: No usable boost::python found

despite the fact that libboost_python.so resides in /home/pmj27/anaconda2/lib.
Looking at config.log the error message seems to be:
configure:19187: g++-5 -c -fopenmp -O3 -fvisibility=default -fvisibility-inlines-hidden -Wno-deprecated -ftemplate-depth-250  -DNDEBUG -Wall -Wextra -ftemplate-backtrace-limit=0 -std=gnu++14 -Wno-unused-local-typedefs -I/home/pmj27/anaconda2/lib -I/usr/include conftest.cpp >&5
conftest.cpp:35:33: fatal error: /usr/local/include/boost/version.hpp: Permission denied
compilation terminated.

So what seems to be happening is that it first looks in /usr/local/include/boost, which is the wrong location, and then fails. How do I stop it from doing that? (I presume this is the reason why graph-tool won't compile.)
I have also tried
./configure CXX="g++-5" CXXFLAGS="-std=gnu++14 -Wno-unused-local-typedefs -I/home/pmj27/anaconda2/lib" PYTHON="/home/pmj27/anaconda2/bin/python2.7" CAIROMM_LIBS="-L/home/pmj27/anaconda2/include/cairomm-1.0/cairomm" --enable-openmp

But that still fails with the same error message though now /home/pmj27/anaconda2/lib seems to appear before /usr/local/include/boost:
configure:19104: checking for boostlib >= 1.54.0
configure:19187: g++-5 -c -fopenmp -O3 -fvisibility=default -fvisibility-inlines-hidden -Wno-deprecated -ftemplate-depth-250  -DNDEBUG -Wall -Wextra -ftemplate-backtrace-limit=0 -std=gnu++14 -Wno-unused-local-typedefs -I/home/pmj27/anaconda2/lib  -I/usr/include conftest.cpp >&5
conftest.cpp:35:33: fatal error: /usr/local/include/boost/version.hpp: Permission denied
compilation terminated.

Comment: The fact that you get "permission denied" when reading something in /usr/local means you have installed it with the wrong permissions.
Comment: True, and I can overcome that with using `sudo`. I was trying to prevent using those boost libraries as I need to use the anaconda ones in order to prevent c++ signature mismatches when running `graph-tool`.
Comment: You are not overcoming it, you are probably causing the problem in the first place by using sudo (e.g. running as root) when you should not have to. Using sudo like this is bad form, and a bad idea. Part of the problems you are experiencing is a consequence of this.
Answer: First of all: "We could not detect the boost libraries" does not mean that it fails to find a shared library of Boost::Python. It means that it fails to find the boost itself, that is: all its header files.
In view of this I have to question this:
-I/home/pmj27/anaconda2/lib

Does it contain boost header files in there? Because you are describing that an .so file resides there instead.
Once you deal with the boost include issue, you might need a different set of flags pointing to the .so library. It may depend on how you want to deploy it, but something along this line:
-L/home/pmj27/anaconda2/lib -lboost_python -Wl,-rpath=/home/pmj27/anaconda2/lib

but that is future. Focus on getting the proper header files of boost first!
Comment: The header files seem to reside in `/home/pmj27/anaconda2/include/boost` as far as I can tell (it containts a bunch of `.hpp` files).
Comment: Then you need `-I/home/pmj27/anaconda2/include` instead.


How to refer to an object's "Owner" in Ruby?

Question: "Owner" is probably not the right term for this but I don't know what is so it's making the search very difficult.
I'm making a card game, and each player can have multiple hands of cards.
I have a "Player," "Hand," and "Card" classes.
player1 = Player.new
hand1 = Hand.new # => A new hand of two random cards

player1.hands.push(hand1)

#Now player1 has one hand with two cards in it.

Is there an attribute or method I can call on hand1 that will refer to its "owner", player1?
I'm expecting something like
hand1.owner

=> #<Player:0x007fb6ae05b448
# @behavior=:human,
# @hands=[#<Hand:0x007fb6ad8653b0 @cards=[{:A,:spades},{:Q,:hearts}]>],
# @money=800,
# @name="Dougie Jones">

Comment: I know this may be just an example, but if you need to query hands to determine their player, I'd say you've modeled something wrong.
Comment: I am going to have to agree with @MarkThomas on this one. Why does the `Hand` need to know its `Player`? Let's assume we are playing "Go Fish"... You would ask the `Player` about a `Card` in their `Hand` not ask the `Hand` about the `Player`. A `Hand` should only know about the `Card`s and a `Player` should know about the `Hand` and through the `Hand` know about the `Card`s
Comment: It's a blackjack game and sometimes you need to split a hand into two hands, up to a total of four. I found it easier to have each hand "play" itself and have all player and AI decisions take place in the Hand class. I didn't run into trouble until I realized that doubling and splitting required the hand to know whether its player had enough money. I probably would structure it differently now, especially since I still have a lot of gameplay methods in the Player class anyway...
Answer: No, there is no way. An object doesn't know where you keep it. You may keep it in many different places, who is going to be the owner then? You need to set relationships manually or consider changing design.
Consider this:
class Player
  attr_accessor :hands

  def initialize
    @hands = []
  end

  def add_hand(hand)
    hand.player = self
    @hands << hand
  end
end

class Hand
  attr_accessor :player
end

player = Player.new
hand = Hand.new
player.add_hand(hand)
puts hand.player #=> #<Player:0x000000017b2978>

Comment: Yes! Thank you! Adding the .player attribute to from the Player class' new_hand method is so much simpler than the workaround I found, which was to pass the player's unique identifier into the new_hand method as an additional parameter, and then turning it into an attribute within the Hand class' initializer. Thanks!
Answer: You can cross-reference objects with attributes. (every Hand object can reference a specific Player object)
For example, you can add an attribute to your Hand model:
class Hand
  attr_accessor :player
end

Then when you create a new Hand, you can set the player:
player1 = Player.new
hand1 = Hand.new
hand1.player = player1

This is essentially how ActiveRecord associations work.
Comment: A year later I'm looking over my post history and see your comment. Man, I was completely not at all ready to hear about ActiveRecord stuff back then. I'd definitely approach this problem differently now!


for-loop: necessity of pointer variable as condition in if-statement

Question: I dont understand why the condition of if-statement needs to be a pointer. I assumed a normal variable call will not give any complaints.
Was trying to learn about std::vector::erase from cppreference, got intrigued about the example there (https://en.cppreference.com/w/cpp/container/vector/erase)
#include <vector>
#include <iostream>

int main( )
{
    std::vector<int> c{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    for (auto &i : c) {
        std::cout << i << " ";
    }
    std::cout << '\n';
    // Erase all even numbers (C++11 and later)
    for (auto it = c.begin(); it != c.end(); ) {
        if (*it % 2 == 0) {
            it = c.erase(it); // THE LINE ABOVE THIS
        } else {
            ++it;
        }
    }
    for (auto &i : c) {
        std::cout << i << " ";
    }
    std::cout << '\n';
}

Output
0 1 2 3 4 5 6 7 8 9
1 3 5 7 9

Hope anyone could share an explanation or direct me to an available resource.
Comment: Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)
Comment: Its not a pointer.  It is de-referencing the  iterator to get the value stored in that location in the vector.
Comment: That's not a range loop.
Answer: In the classical loop:
auto it = c.begin() - it is an iterator. To access what it refers to you need to dereference it, which you do with *it. The * there does not mean pointer, it means dereference (technically, on iterators, it's a call to operator*).
See also https://en.cppreference.com/w/cpp/iterator
In the range based loop:
for (auto &i : c) - here you get back a reference to the element in the container directly. No iterators involved.
Comment: Technically `operator*` which on iterators means something different.
Comment: @tadman - Right. Good point. Answer updated.
Answer:
Ranged based for-loop: necessity of pointer variable as condition in
  if-statement

I think that the confusion is that you are incorrectly considering the ordinary for-loop
for (auto it = c.begin(); it != c.end(); )

as the ranged for-loop.
In your program the range-based for loop is used only to output the vector.
for (auto &i : c) {
    std::cout << i << " ";
}

Iterators behave as pointers. That is for them for example there are defined operator * and operator ++.
Consider a similar program that deals with an array. Of course you can not remove elements from an array but you can move "removed" elements to the end of the array.
Here is a demonstrative program.
#include <iostream>

int main()
{
    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    const size_t N = sizeof( a ) / sizeof( *a );

    for ( const int *p = a; p != a + N; ++p )
    {
        std::cout << *p << ' ';
    }
    std::cout << '\n';

    int *q = a;

    for ( const int *p = a; p != a + N; ++p )
    {
        if ( not ( *p % 2 == 0  ) )
        {
            if ( p != q ) *q = *p;
            ++q;
        }
    }

    for ( const int *p = a; p != q; ++p )
    {
        std::cout << *p << ' ';
    }
    std::cout << '\n';

    return 0;
}

Its output is
0 1 2 3 4 5 6 7 8 9
1 3 5 7 9

As you can see in this if statement
if ( not ( *p % 2 == 0  ) )

you have to dereference the pointer to get the value pointed to by the pointer.
Now rewrite the program the following way using generic functions std::begin, std::cbegin, and std::cend.
#include <iostream>
#include <iterator>

int main()
{
    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    for ( auto p = std::cbegin( a ); p != std::cend( a ); ++p )
    {
        std::cout << *p << ' ';
    }
    std::cout << '\n';

    auto q = std::begin( a );

    for ( auto p = std::cbegin( a ); p != std::end( a ); ++p )
    {
        if ( not ( *p % 2 == 0  ) )
        {
            if ( p != q ) *q = *p;
            ++q;
        }
    }

    for (  auto p = std::begin( a ); p != q; ++p )
    {
        std::cout << *p << ' ';
    }
    std::cout << '\n';

    return 0;
}

Now the pointers look like iterators and nothing was changed in the if statement
if ( not ( *p % 2 == 0  ) )

Comment: thank you Vlad, the demo really got me thinking about whats referencing / dereferencing / pointing what, so array (a) became 1, 3, 5, 7, 9, 5, 6, 7, 8, 9. and pointer/iterator q is at '5'