text:
Q: POST requests with Python module I am attempting to access a web-service that is under development and execute a POST request via Python script.  I have tested the url and parameters with Postman, and it works correctly.
My script:
import requests
import json
import jsonpickle

f = open('C:\Users\Administrator\Desktop\myla311.json', 'r')

data = jsonpickle.encode(f)

url = "url"
headers = {'Content-type': 'raw', 'Accept': '/'}

response = requests.post(url, json=data, headers=headers)
f.close()

print response.text

print response

My output:
C:\Python27\ArcGIS10.2\python.exe C:/Python27/ArcGIS10.2/websocket-client-0.23.0/websocket-client-0.23.0/examples/MYLAJSONtesting.py
com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class com.kahuna.request.wrapper.ServiceRequestWrapper] from String value ('null'); no single-String constructor/factory method
 at [Source: org.apache.camel.converter.stream.InputStreamCache@264330f4; line: 1, column: 1]
  at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
  at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:757)
  at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:277)
  at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:289)
  at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1137)
  at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:139)
  at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:126)
  at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3051)
  at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2192)
  at org.apache.camel.component.jackson.JacksonDataFormat.unmarshal(JacksonDataFormat.java:128)
  at org.apache.camel.processor.UnmarshalProcessor.process(UnmarshalProcessor.java:67)
  at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:72)
  at org.apache.camel.processor.interceptor.TraceInterceptor.process(TraceInterceptor.java:163)
  at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
  at org.apache.camel.processor.Pipeline.process(Pipeline.java:118)
  at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
  at org.apache.camel.processor.TryProcessor.process(TryProcessor.java:111)
  at org.apache.camel.processor.TryProcessor.process(TryProcessor.java:82)
  at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:72)
  at org.apache.camel.processor.interceptor.TraceInterceptor.process(TraceInterceptor.java:163)
  at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
  at org.apache.camel.processor.Pipeline.process(Pipeline.java:118)
  at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
  at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
  at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:105)
  at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:87)
  at org.apache.camel.component.restlet.RestletConsumer$1.handle(RestletConsumer.java:55)
  at org.apache.camel.component.restlet.MethodBasedRouter.handle(MethodBasedRouter.java:54)
  at org.restlet.routing.Filter.doHandle(Filter.java:159)
  at org.restlet.routing.Filter.handle(Filter.java:206)
  at org.restlet.routing.Router.doHandle(Router.java:431)
  at org.restlet.routing.Router.handle(Router.java:648)
  at org.restlet.routing.Filter.doHandle(Filter.java:159)
  at org.restlet.routing.Filter.handle(Filter.java:206)
  at org.restlet.routing.Router.doHandle(Router.java:431)
  at org.restlet.routing.Router.handle(Router.java:648)
  at org.restlet.routing.Filter.doHandle(Filter.java:159)
  at org.restlet.engine.application.StatusFilter.doHandle(StatusFilter.java:155)
  at org.restlet.routing.Filter.handle(Filter.java:206)
  at org.restlet.routing.Filter.doHandle(Filter.java:159)
  at org.restlet.routing.Filter.handle(Filter.java:206)
  at org.restlet.engine.CompositeHelper.handle(CompositeHelper.java:211)
  at org.restlet.Component.handle(Component.java:406)
  at org.restlet.Server.handle(Server.java:516)
  at org.restlet.engine.connector.ServerHelper.handle(ServerHelper.java:72)
  at org.restlet.engine.adapter.HttpServerHelper.handle(HttpServerHelper.java:152)
  at org.restlet.ext.servlet.ServerServlet.service(ServerServlet.java:1118)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
  at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
  at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
  at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:301)
  at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
  at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:60)
  at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:119)
  at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:324)
  at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:460)
  at oracle.security.jps.ee.http.JpsAbsFilter.runJaasMode(JpsAbsFilter.java:103)
  at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:171)
  at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71)
  at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:60)
  at oracle.security.wls.filter.SSOSessionSynchronizationFilter.doFilter(SSOSessionSynchronizationFilter.java:292)
  at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:60)
  at oracle.dms.servlet.DMSServletFilter.doFilter(DMSServletFilter.java:163)
  at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:60)
  at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3748)
  at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3714)
  at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
  at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
  at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2283)
  at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2182)
  at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1491)
  at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
  at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
<Response [500]>**

JSON file:
{
    "MetaData": {},
    "RequestSpecificDetail": {
        "ParentSRNumberForLink": ""
    },
    "SRData": {
        "Anonymous": "Y",
        "Assignee": "",
        "CreatedByUserLogin": "",
        "CustomerAccessNumber": "",
        "LADWPAccountNo": "",
        "Language": "English",
        "ListOfLa311GisLayer": {},
        "ListOfLa311ServiceRequestNotes": {
            "La311ServiceRequestNotes": [
                {
                    "Comment": "hxhdudi",
                    "CommentType": "Feedback",
                    "FeedbackSRType": "Weed Abatement for Pvt Parcels",
                    "IsSrNoAvailable": "N"
                },
                {
                    "Comment": "",
                    "CommentType": "External",
                    "CreatedByUser": "",
                    "IsSrNoAvailable": "N"
                }
            ]
        },
        "LoginUser": "",
        "MobilOS": "Android",
        "NewContactEmail": "",
        "NewContactFirstName": "",
        "NewContactLastName": "",
        "NewContactPhone": "",
        "Owner": "Other",
        "ParentSRNumber": "",
        "Priority": "Normal",
        "SRCommunityPoliceStation": "RAMPART",
        "SRType": "Feedback",
        "ServiceDate": "01/22/2015",
        "Source": "Mobile App",
        "Status": "Open",
        "UpdatedByUserLogin": ""
    }
}

Expected output:
{"status":{"code":311,"message":"Service Request Successfully Submited","cause":""},"Response":{"PrimaryRowId":"1-3GZFZ","ListOfServiceRequest":{"ServiceRequest":[{"SRNumber":"1-5831279"}]}}}

EDIT: After changing json=data to data= data I received
{"status":{"code":1007,"message":"Service Request Does Not Submitted.","cause":"java.lang.NullPointerException"}}
<Response [200]>

Process finished with exit code 0

A: data = jsonpickle.encode(f) The doc says you have to pass Python objects to this function. I'm not sure, perhaps this may help;
data = jsonpickle.encode( jsonpickle.decode(f.read()) )
Here I tried to convert json string to Python objects and back to json. You can try passing as data = f.read().

A: You're accessing a web service written in Java using the Restlet library. I think Ryan O'Donnell is correct about your usage of the requests.post call and the need for a content-type.
See the following example from the requests documentation:
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

You should probably add an accept header:
'Accept': 'application/json'

Finally, rather than using open and close on a file, it's cleaner and safer to use a with block. Your code might look something like this:
with open('C:\Users\Administrator\Desktop\myla311.json', 'r') as f:
    payload = f.read()

headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
r = requests.post(url, data=payload, headers=headers)

I'm not sure what your use of jsonpickle is doing, but there's no need to decode and re-encode your payload. It's already JSON and that's what you want to send.


text:
Q: SQL: reverse groupby : EDIT Is there a build in function in sql, to reverse the order in which the groupby works? I try to groupby a certain key but i would like to have the last inserted record returned and not the first inserted record.
Changing the order with orderby does not affect this behaviour.
Thanx in advance!
EDIT:
this is the sample data:
id|value
-----
1 | A
2 | B
3 | B
4 | C

as return i want
1 | A
3 | B
4 | C

not
1 | A
2 | B
4 | C

when using group by id don't get the result i want.

A: Question here is how are you identifying last inserted row. Based on your example, it looks like based on id. If id is auto generated, or a sequence then you can definitely do this.
select max(id),value
from your_table
group by value

Ideally in a table design, people uses a date column which holds the time a particular record was inserted, so it is easy to order by that.

A: Use Max() as your aggregate function for your id:
SELECT max(id), value FROM <table> GROUP BY value;

This will return:
1 | A
3 | B
4 | C

As for eloquent, I've not used it but I think it would look like:
$myData = DB::table('yourtable')
                 ->select('value', DB::raw('max(id) as maxid'))
                 ->groupBy('value')
                 ->get();

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the Axiom of Choice and Axiom of Determinacy? Would someone please explain:

*

*What does the Axiom of Choice mean, intuitively?

*What does the Axiom of Determinancy mean, intuitively, and how does it contradict the Axiom of Choice?

as simple words as possible?
From what I've gathered from the Wikipedia page, my understanding is that the Axiom of Choice pretty much lets you make a completely random decision, i.e. equal probability for everything. I don't, however, understand what they're talking about regarding the sets of sets (is it more than what I just described?), and I further don't understand the Axiom of Determinancy.
Info on those would be appreciated. :)

A: I have nothing technical to add to Asaf's answer (he's the one who works on the axiom of choice, after all :-), but something from the perspective of someone who wondered for a long time what the axiom of choice is all about and realized in the end that this confusion arose from a deep misunderstanding of the point of axiomatic set theory. If you already have some (philosophical or pre-philosophical) notion of what it means for mathematical objects like sets to "exist", it happens easily that you read statements about the "existence" of a set (which abound in axiomatic set theory, including Asaf's answer) in the light of that pre-existing notion. That naturally tends to lead to reactions such as: "Whaddaya mean, there might not be a choice function? Here's the set of sets, there's the set of their elements, you agree that both of these exist and that their Cartesian product exists, how can you say there might not be a subset of that product containing exactly one pair for each set relating it to one of its elements? It's right there, that's what the Cartesian product is all about!"
The point is that axiomatic set theory intentionally forgets about all such intuitions of what sorts of sets "there are" and deals only with formal statements about the existence of sets that can be deduced from the axioms and/or that hold in certain models (which often bear little resemblance to what you intuitively think of as "the sets that there are or should be"). If you read that "a choice function might not exist", don't interpret this as telling you something you can or can't do or imagine with infinite sets; it simply means that the existence of a choice function cannot be proved from the axioms, or that there is no choice function in the particular model being discussed.
If you stick to this advice, the axiom of choice becomes a lot less mysterious than it may seem. It's actually quite easy to imagine that there are models of certain axioms that don't contain sets that one thinks "should exist" -- after all, they're just models and axioms. If you don't use the axiom of infinity, you can't deduce from the remaining axioms that there's an infinite set, and you can find a model that doesn't contain any infinite sets -- that has nothing to do with whether infinite sets "really exist" in a philosophical sense of the word (if there is one :-).
Related to this is that it's important to clearly distinguish "internal" and "external" statements -- axiomatic set theory is always concerned with a certain universe of sets, and we can always talk about this "from the outside" and talk about sets that "don't exist" inside the universe under consideration. This would obviously not be possible if all statements about "existence" referred to "the actual universe of sets" (whatever that might be) and not to some particular one.
After all this, one might wonder why bother with axiomatic set theory if it's just a formal game with axioms and models. The reason for this is that our intuition about sets can prove quite unreliable, as evidenced by the paradoxes that pop up everywhere in what's now called "naive set theory". We can say something like "the set of all sets that don't contain themselves", and think that we've said something meaningful, whereas in fact we've said something utterly meaningless, since there can be no such thing. Now that doesn't mean that you can't form the collection of all sets that don't contain themselves and think about it, just like you can form the Cartesian product as the collection of all pairs and think about it and come to the obvious conclusion that it contains a choice function; the paradox arises only if you then insist on calling that collection a "set". So axiomatic set theory, in a sense, allows us to define formally and without many of the pitfalls of "naive set theory" what sort of things we want to call a "set" in a given context -- that's no reason to doubt the existence of other collections, or not to call these collections "sets" in a different context (if that happens to be consistent).

A: This is only half an answer, since I don't know much about the axiom of determinacy and so cannot explain how it conflicts with the axiom of choice. However, I hope that the exposition below is useful in answering your first question.

Axiom of choice. Let $\{ X_i : i \in I \}$ be a set, with each $X_i$ a non-empty set. Let $X = \bigcup_{i \in I} X_i$, the union of all of them. Then, there is a function $f : I \to X$ such that $f(i) \in X_i$ for each $i$ in $I$.
Intuitively, this is saying that if you give me any collection of non-empty sets, I can 'choose' an element from each one. This is obviously true in the case where you only give me finitely many sets. But what if you give me infinitely many? Obviously I can choose an element for an arbitrarily large number of them, given enough time, but it is not at all obvious that I can, in one fell swoop, choose an element from all of them at once. If I can, that must be because I can describe, in a finitistic way, a choice procedure which does so: this is exactly what $f : I \to X$ is in the above axiom, and for this reason it is called a choice function.
The way I have described the problem perhaps predisposes you to believe that the axiom of choice is not true. How could it be that there is a choice procedure for any arbitrary problem? The axiom of choice is non-constructive and merely asserts the existence of choice functions. But most mathematicians believe that the axiom of choice is true, because it is convenient. Indeed, the axiom of choice is equivalent to many other statements, some more obviously 'correct' or 'wrong' than others. A famous joke, apparently due to Jerry Bona, references this:

The Axiom of Choice is obviously true, the well-ordering principle obviously false, and who can tell about Zorn's lemma?

I'll start with some of the less set-theoretic ones, to show how it connects with 'real' mathematics.
Equivalent 1. Every non-trivial vector space has at least one basis.
Like the axiom of choice, this seems entirely reasonable in finite settings: for example, a finite-dimensional vector space obviously has a basis (but how would we know it's finite dimensional otherwise?), and similarly, given a finite collection of non-empty sets, it is obviously possible to pick one element from each set.
Equivalent 2. (Krull's theorem) Every non-trivial ring (with identity) has a maximal ideal. This is proven from the axiom of choice using Zorn's lemma.
Equivalent 3. Every surjective function has a right inverse, that is, if $p : X \to Y$ is a surjective function, then there is a function $f : Y \to X$ such that $f(p(y)) = y$ for all $y$ in $Y$. [The function $p$ is surjective just if for every $y$ in $Y$, there is an $x$ in $X$ such that $p(x) = y$.]
It's not hard to see intuitively that this is equivalent to the axiom of choice: after all, what's happening here is that $p$ is partitioning $Y$ into subsets indexed by $X$, and to construct $f$ one needs to pick from each subset one element; conversely, assuming that this is true, given a choice problem, we can reformulate it so as to obtain a solution using this $f$: for convenience, assume that $X_i$ and $X_j$ have no common elements when $i \ne j$, take $X$ as in the axiom, and set $Y = I$, and let $p : X \to I$ be the function which sends $x$ to $i$ if $x \in X_i$. Then any right inverse $f$ is obviously a choice function.
Just to show why this sort of thing might be a little suspect, let's make a tiny tweak to the conditions. Suppose instead that $X$ and $Y$ are topological spaces, and that $p$ is continuous. Then by no means is it guaranteed that there is a continuous right inverse $f$. For example: let $X$ be the real line and $Y$ be the circle. It's obvious that you can wrap $X$ around $Y$ in a continuous way—so there is such a continuous surjective function $p$. But there's no way to take a circle and transform it into a line continuously, so there isn't any continuous right inverse $f$.
Equivalent 4. (Well-ordering principle) Every non-empty set admits a well-ordering. [A well-ordering is an ordering such that every non-empty subset has a unique minimal element.]
Its equivalence with the axiom of choice is also intuitive: if every non-empty set has a well-ordering, then I can just give $I$ a well-ordering, and work through each $X_i$ in order, giving each one a well-ordering and picking a minimal element; conversely, given the axiom of choice, we can just 'choose' a well-ordering.
Equivalent 5. Given any two sets $X$ and $Y$, there is either an injection $X \to Y$, or an injection $Y \to X$, or a bijection between the two sets. This basically says that any two cardinal numbers can be compared. [An injection is a function such that different points in the domain get sent to different points in the image, that is, a function $f : X \to Y$ is injective just if $f(x) = f(x')$ implies $x = x'$. A bijection is a function which is both injective and surjective.]
Equivalent 6. Given a family of non-empty sets $\{ X_i : i \in I \}$, their cartesian product $\prod_{i \in I} X_i$ is non-empty. This is really just a reformulation of the axiom of choice, since an element of the cartesian product is precisely a choice function. [The cartesian product of a finite number of sets can be thought of as a set of ordered lists: for example, $X_1 \times X_2$ is the set of pairs $(x_1, x_2)$ where $x_1 \in X_1$ and $x_2 \in X_2$. But such a pair is obviously the same thing as a function from $\{ 1, 2 \}$ to $X_1 \cup X_2$, so that is how we define the cartesian product in the infinite case.]
Equivalent 7. (Tychonoff's theorem) Given a family of (non-empty) compact topological spaces, their cartesian product, equipped with the product topology, is (non-empty and) compact. This is a somewhat advanced bit of mathematics, but I state it here since it is related to the previous example.
Equivalent 8. (Zorn's lemma) Every partially-ordered set with the property that every chain has an upper bound in fact has a maximal element. [A partially-ordered set is a set with a binary relation $\le$ such that $x \le x$ ($\le$ is reflexive); $x \le y$ and $y \le z$ implies $x \le z$ ($\le$ is transitive); and $x \le y$ and $y \le x$ implies $x = y$ ($\le$ is antisymmetric). A chain is a subset which has the additional property that for all $x$ and $y$ in the subset, either $x \le y$ or $y \le x$. A chain $C$ in a partially-ordered set $X$ has an upper bound if there is an element $u$ in $X$ such that $x \le u$ for every $x$ in $C$. A maximal element is an element $m$ such that there do not exist any elements $x$ such that $m \le x$.]

There are also various results which are known to be invalid without the axiom of choice. In other words, these are statements implied by the axiom of choice but which do not themselves imply the axiom of choice, unlike the equivalents listed above. Some of these results are 'useful', and others are unpleasant and run counter to intuition.
Consequence 1. Any two bases of a vector space have the same cardinality—in other words, the dimension of a vector space is well-defined and does not depend on the basis. It can be shown (assuming the consistency of certain logical theories) that there is a universe of Zermelo–Fraenkel set theory where the axiom of choice is false (or, for short, 'a universe without AC') and in which there is a vector space which have two bases which have different cardinalities.
Consequence 2. Every field has an algebraic closure. [A field $K$ is algebraically closed if every polynomial with coefficients in $K$ also has a root in $K$. The field of complex numbers $\mathbb{C}$ is algebraically closed, for example. An algebraic closure of a field $F$ is a field $K$ which is algebraically closed and contains $F$ as a subfield.] As above, there is a universe without AC which has a field with no algebraic closure.
Consequence 3. Every countable union of countable sets is again countable. [A set $X$ is countable if there is an injection $X \to \mathbb{N}$, where $\mathbb{N}$ is the set of natural numbers.] There is a universe without AC in which the real numbers is a countable union of countable sets, but it can be shown that in any universe which obeys ZF, the real numbers must be uncountable.
Consequence 4. A function is sequentially continuous at a point if and only if it is also continuous at that point. [A function $f$ is sequentially continuous just if for every sequence of points $(x_n)$ converging to $x$, $f(x_n)$ converges to $f(x)$. By continuous here we mean the usual $\epsilon$-$\delta$ definition.] But there is a universe without AC in which there is a function of the real numbers which is sequentially continuous at a point but not continuous there.
Consequence 5. (Vitali set) There is a non-Lebesgue-measurable subset of the real line. [Informally, there is a subset of the real line for which does not admit a meaningful definition of 'total length' compatible with the intuitive notion that the unit interval $[0, 1]$ has length $1$.] There is a universe without AC in which every subset of Euclidean space is measurable.
Consequence 6. (Banach–Tarski theorem) There is a partition of the ball into finitely many pieces such that by rigid motions, these pieces can be reassembled into two balls of the same volume as the original. These pieces are, of course, not measurable, so do not exist in the universe mentioned above.

But is the axiom of choice true? That's not really a meaningful question. At best we can only ask whether Zermelo–Fraenkel set theory together with the axiom of choice (or ZFC for short) is logically consistent or not. Unfortunately, the answer to this question is as yet unknown, and quite possibly can never be known. (Gödel's incompleteness theorem is a precise form of the latter claim: it shows that the logical consistency of ZFC cannot be proven from the axioms of ZFC alone.) Personally, I advocate for pluralism in mathematics, so I don't see this as much of a problem. If it turns out that Zermelo–Fraenkel set theory with the axiom of choice is consistent and the Zermelo–Fraenkel set theory with some negation of the axiom of choice (e.g. the axiom of determinacy) is consistent, this is all the better, because it adds to the richness of mathematics. It's also a defence against the extremely unlikely event that someone does demonstrate that ZFC is inconsistent, though I suspect most mathematicians would just move on as if nothing ever happened...

A: I'm late to the party but I just read the following explanation of the Axiom of Choice and thought it was good, so I'm adding it. (Quoted from Just / Weese, p. 118):

(A9)Axiom of Choice: For every family $x$ of non-empty pairwise disjoint sets there exists a set $z$ such that $|z \cap y|=1$ for each $y \in x$.
The Axion of Choice generalises the familiar process of choosing representatives. If $x$ is the family of congressional districts, then the Congress of the United States is an example of a set $z$as in (A9). Note that congressional districts are non-empty and disjoint.
What makes the Axiom of Choice so special that we even mention it specifically in the name of our theory ZFC? Its non-constructive character. The axiom assures us that there will be a Congress after the next Election Day but it does not specify who will be elected. Otherwise, there would be no point in holding elections in the first place. The latter option has always been preferred by dictators who evidently do not have much confidence in the Axiom of Choice and prefer legislatures composed of loyal supporters.
Now suppose for the sake of argument that you seized dictatorial power of the United Sets of the Universe. You need to stay on good terms with your archrival, the Former Solid Intersection who keeps meddling in your internal affairs with evil propaganda about human rights, democracy and similar nuisances. In order to keep up appearances you need some sort of congress. So you start looking at the list of congressional districts and make your choices. But there is a problem: The United Sets of the Universe have infinitely many congressional districts. While you are busy picking your best congress, your enemies may be plotting your overturn. You better get quickly done with this congress-choosing business. In other words, you must make infinitely many choices in a finite amount of time without having the option of describing all these choices by a single formula. The Axiom of Choice says that you can somehow do this, but it does not give you much control over the outcome of the selection process.

A: The axiom of choice is an axiom of set theory, and it is used when implicitly assuming that the universe consists of sets, and sets alone. That is - everything is a set.
For example, $0=\emptyset$ and $1=\{\emptyset\}$. Since everything is a set, consider a set $X$ and all its elements are non-empty sets themselves. Formally $\forall y(y\in X\rightarrow \exists z(z\in y))$.
The axiom of choice asserts the existence of a function whose domain is $X$ and its range is $\{z\mid\exists y(y\in X\land z\in y)\}$ (often denoted $\bigcup X$). The function has a very special property, namely $f(y)\in y$. It chooses someone from every element of $X$.
Some examples (which do not require the axiom of choice) are, $X=\mathcal P(\mathbb N)\setminus\{\emptyset\}$ that is all the non-empty subsets of natural numbers.
We can have $f(A)=\min A$, that is the least element of $A$ is returned. We can require something slightly more peculiar $f(A) = \min\{a\in A\mid a\text{ is even}\}$ if such $a$ exists, or $\min A$ otherwise.
These are two examples which do not require the axiom of choice since we are able to specify in a uniform formula who do we want to pick from every $A$.
A useful equivalence of the axiom of choice is Zorn's lemma. This lemma is somewhat complicated, but it asserts that if $(A,<)$ is a partially ordered set, and every linearly ordered subset of $A$ has an upper bound, then there exists a maximal element.
To elaborate on that, if $A$ is a non-empty set, and $<$ defines a partial order on $A$, if every $C\subseteq A$ which has the property $\forall a\forall b(a<b\lor b<a\lor a=b)$ has some $x\in A$ such that $\forall a(a\in C\rightarrow a<x)$ then there exists a maximal element - some $x\in A$ for which the property $\forall a(a\neq x\rightarrow a<x)$ is true.
Zorn's lemma is very useful in algebra, and used in the proof that every field has an algebraic closure; every vector space has a basis; and every ideal can be extended to a maximal ideal (and many many many other uses).
The proof uses heavily the axiom of choice (not surprisingly, since the two are equivalent) and in a nutshell we take one element, then $\{a_0\}$ is linearly ordered, therefore if $a_0$ is not maximal in $A$ we can extend it. That is the set $\{b\in A\mid a<b\land a\neq b\}$ is non-empty, and we can choose from it. We choose from non-empty subsets of $A$ until we either "find" a maximal element, or derive contradiction to one property or another.
I use "find" because many times the maximal element is one we cannot describe nicely by a sentence (and in fact without the axiom of choice there are vector spaces without basis, fields without algebraic closures and so on).

To understand the axiom of determinacy first we need to understand what there is to be determined.
Take $A\subseteq\mathbb N^\mathbb N$, that is a set of infinite sequences of natural numbers.
Now we play a game, I will be Player I (P-I) and you will be Player I (P-II). I will choose some $n\in\mathbb N$, and then you will choose another. The game is infinitely long and will have another round for every finite number of rounds.
Note that in the $n$-th round we have $x_n$ and $y_n$ (I chose $x$'s and you choose $y$'s). This defines a sequence:
$$a_n =\begin{cases}x_k & n=2k\\ y_k & n=2k+1\end{cases}$$
We say that I win the game if $\langle a_0,a_1\ldots\rangle\in A$, otherwise you win the game. If there is a strategy assuring victory for either one of us then we say that the game is determined. This is to say there is a function from $\mathbb N$ to $\mathbb N$ that given the current state of the game will give me a possible tail segment which assures one of the player's victory. (Note that there are usually a lot of possible strategies).
For example $A$ will be all the sequences which are constants $a_n=k$ for some $k$. Clearly you have a winning strategy. Whatever I chose at first, choose something else and I have no chance of winning.
Another example is $A$ will be the set of sequences that $a_n$ is even whenever $n$ is even ($a_n=n$, for example). All I have to do is choose even numbers in my turn, and I cannot lose.
The Axiom of determinacy asserts: Every game is determined. That is, if we play this sort of game then regardless to which set of sequences we have chosen, one of us can win.
The conflict with the axiom of choice is a bit technical for this post (and the part about determinacy could surely be phrased better by someone else), the idea is as such. If we assume the axiom of determinacy, then every game is determined. We will define $A$ by a transfinite induction. Since at each step during the game the collection of winning strategies is non-empty. We simply choose such winning strategy and ensure that it will not work by adding a sequence to $A$, repeating the process "enough" times we ensured that no strategy exists to determine the winner after any finite number of turns. This contradicts the assumption that every game is determined.
Determinacy is somewhat of a technical axiom, and while it was very natural to postulate this axiom in some parts of set theory (namely descriptive set theory), the mainstream mathematics has been made very comfortable with the axiom of choice, and as Theo points out in the comments some pathologies which we are used to are gone when assuming the axiom of determinacy.
This makes the axiom of choice more common in modern mathematics than determinacy. Things can change, though... things can change.

Added:
To understand the need for the axiom of choice, we return to Bertrand Russell's wonderful analogy. Given infinitely many pairs of shoes, you can always choose one from each pair, but to choose a sock from infinitely many pairs of socks you need the axiom of choice.
What does that mean? Well, given shoes you can easily say "Pick all the left shoes", and regardless of how many pairs are given in each pair there is exactly one left shoe. This defines a function which chooses an element of each pair. On the other hand socks are indistinguishable and you cannot say which one is the left and which one is the right.
What does that mean indistinguishable? Well, given one pair of socks $\{a,b\}$ we can always say "Oh, this is $a$ and this is $b$", even if our assignment of $a$ was arbitrary. Every time we are given three pairs of socks we can ad-hoc assign each pair as $a_i, b_i$ and pick the ones we assigned as $a_i$. However if there are infinitely many pairs of socks, can we always make such assignment? Well, only if we assume the axiom of choice holds.
The point is that a pair of socks has two elements in it. These are always distinct and we can always examine the pair by itself and distinguish between the two socks. We can always distinguish between three, four and five socks at once; as well ten or fifteen pairs of socks. We simply assign each collection of socks with different names to be able and temporarily tell which sock is which, then we can choose the names we would like.
Mathematically speaking if we are given a finite collection of non-empty sets, if we do not actually care about the choice of elements, as long as we choose exactly one from each set, it is always doable. First we need to understand that "not caring" means that we only require $f(A)\in A$ which is of course doable since $A$ is non-empty. However, in mathematics it is not enough to claim things, one has to prove them as well. In this case, we can simply write the following statment (assuming $A_1,\ldots, A_n$ are our non-empty sets):
$$\exists x_1\ldots\exists x_n(x_1\in A_1\land x_2\in A_2\land\ldots\land x_n\in A_n\bigwedge f(A_1)=x_1\land f(A_2)=x_2\land\ldots\land f(A_n)=x_n)$$
That is to describe exactly (I am somewhat cheating here, I did not describe it exactly, but I gave a close enough approximation) how $f$ looks like, it is the function (however a function may be defined set theoretically) that after fixing $x_i\in A_i$ simply returns $x_i$ as the choice from $A_i$. Since this is a finite collection of pairs we can describe this sort of choice.
If we have one pair then this sentence is very short, as we keep on adding pairs we will write longer and longer sentences. If we finally have infinitely many pairs then we cannot write this sort of sentence. We need to find a different formulation. This is where the ability to uniformly distinguish some unique element in each $A_i$ comes to help. Suppose $\varphi(x)$ is the property of being a left shoe. Let $B=\{B_n\mid n\in\mathbb N\}$ be a collection of infinitely many pairs of shoes. If we want to choose from each pair, we can simply do it as such:
$$\forall X(X\in B\rightarrow \varphi(f(X)))$$
Since there exists exactly one element, $a$ in every $X$ for which $\varphi(a)$ is true (i.e. there is exactly one left shoe in each pair of shoes) this implies the function $f$ is nicely defined, in a finite (and even short) sentence.
Now we return to the socks. There is no property $\varphi(x)$ such that in every pair of socks there is exactly one sock for which $\varphi$ is true. This means that we cannot write a very nice sentence as above, to choose one sock from each pair!
This is the (with a capital "the") key of the issue here. In a finite collection you can always distinguish every element from every other element. When looking at an infinite collection you may not be able to have this luxury.
What does that mean mathematically? It means that you may not be able to write a finite sentence to help you choose from infinitely many pairs without the axiom of choice - which asserts this sort of choice exists (it may not be computable or even definable except for knowing it exists somewhere in your universe, and therefore you can take an arbitrary one and use it for a while).


text:
Q: C++ Steady Clock Returning 0 time elapsed, sometimes? I'm trying to use steady clock to benchmark parts of my code and I'm pulling some hair out here. It seems that sometimes it returns the difference between 2 times, and sometimes it just returns 0.
I have the following code. This is not real code in my prog but illustrates the problem
typedef std::chrono::steady_clock::time_point clock_point;

for ( int i = 0; i < 2; i++ ) {

    clock_point start_overall = std::chrono::steady_clock::now();

    for ( int j = 0; j < 10000000; j++ ) {
        int q = 4;
    }

    clock_point end_phase_1 = std::chrono::steady_clock::now();

    std::cout << "DIFF=" << std::chrono::duration_cast<std::chrono::microseconds>( end_phase_1 - start_overall ).count() << "\n";

}

This gives me the following output from running the prog 4 times:
DIFF=15622
DIFF=0

DIFF=12968
DIFF=13001

DIFF=12966
DIFF=13997

DIFF=0
DIFF=0

Very frustrating!! i need some consistent times here. And Its not like the time needed to loop 10,000,000 times is completely irrelevant. In my actual program, there's much more going on in the loop and it takes significantly longer, but i still sometimes get 0 vals for time differences.
Whats going on? How can I fix this so i get reliable time differences? Thanks
EDIT: Ok because the explanation I'm getting is that the compiler is simplifying out the loop because nothing actually happens in it, I'm going to show you the actual code in the actual loop that runs, between the 2 clock points
    // need to reset some variables with each situation
    // these are global vars so can access throughout (ewww)
    this_sit_phase_1_complete = dataVars.phase_1_complete;
    this_sit_on_the_play = dataVars.on_the_play;
    this_sit_start_drawing_cards = dataVars.start_drawing_cards;
    this_sit_current_turn = dataVars.current_turn;
    this_sit_max_turn = dataVars.max_turn;

    // note: do i want a separate split count for each scenario?
    // mmm yeah.. THIS IS WHAT I SHOULD DO INSTEAD OF GLOBAL VARS....
    dataVars.scen_active_index = i;

    // point to the split count we want to use
    // dataVars.use_scen_split_count = &dataVars.scen_phase_1and2_split_counts[i];
    dataVars.split_count[i] += 1;

    // PHASE 1:
    // if we're on the play, we execute first turn without drawing a card
    // just a single split to start in a single que
    // phase 1 won't be complete until we draw a card tho
    // create the all_splits_phase_1 for each situation
    all_splits_que all_splits_phase_1;

    // SPLIT STRUCT
    // create the first split in the scenario
    split_struct first_split_struct;
    // set vars to track splits
    first_split_struct.split_id = dataVars.split_count[i];
    // first_split_struct.split_trail = std::to_string(dataVars.split_count[i]);
    // set remaining vars
    first_split_struct.cards_in_hand_numbs = dataVars.scen_hand_card_numbs[i];
    first_split_struct.cards_in_deck_numbs = dataVars.scen_initial_decks[i];
    first_split_struct.cards_bf_numbs = dataVars.scen_bf_card_numbs[i];
    first_split_struct.played_a_land = false;

    // store the split struct as the initial split
    all_splits_phase_1 = { first_split_struct };

    // if we're on the play, execute first turn without
    // drawing any cards
    if ( this_sit_on_the_play ) {

        // execute the turn on the play before drawing anything
        execute_turn(all_splits_phase_1);

        // move to next turn
        this_sit_current_turn += 1;
    }

    // ok so now, regardless of if we were on the play or not, we have to draw
    // a card for every remaining card in each split, and then execute a turn
    // once these splits are done, we can convert over to phase 2
    do_draw_every_card( all_splits_phase_1 );

    // execute another turn after drawing one of everything,
    // we wont actually draw anything within the turn
    execute_turn( all_splits_phase_1 );

    // next turn
    this_sit_current_turn += 1;

    clock_point end_phase_1 = std::chrono::steady_clock::now();
    benchmarker[dataVars.scen_active_index].phase_1_t = std::chrono::duration_cast<std::chrono::microseconds>( end_phase_1 - start_overall ).count();

There is LOTS happening here, lots and lots, the compiler would never simplify out this block. And yet I'm getting 0's as i explained.

A: Out of OPs code:
    for ( int j = 0; j < 10000000; j++ ) {
        int q = 4;
    }

This is a repeated assignment to a local variable which isn't used anywhere.
I strongly assume that the compiler is clever enough to recognize that there is no side-effect caused by the loop. Hence it doesn't emit any code for the loop – for proper (and legal) optimization.
To check this, I completed OPs code snippet to the following MCVE:
#include <chrono>
#include <iostream>

typedef std::chrono::steady_clock::time_point clock_point;

int main()
{
for ( int i = 0; i < 2; i++ ) {

    clock_point start_overall = std::chrono::steady_clock::now();

    for ( int j = 0; j < 10000000; j++ ) {
        int q = 4;
    }

    clock_point end_phase_1 = std::chrono::steady_clock::now();

    std::cout << "DIFF=" << std::chrono::duration_cast<std::chrono::microseconds>( end_phase_1 - start_overall ).count() << "\n";

}
}

and compiled with -O2 -Wall -std=c++17 on CompilerExplorer:

Live Demo on CompilerExplorer
Please, note that the lines for the loop are not colored.
The reason is (as I assumed): there is no code emitted for the for-loop.
So, OP measures two consecutive calls of std::chrono::steady_clock::now(); which may (or may not) appear in a sub-clock-tick time. Thus, it looks if no time has been passed between these calls.

To prevent such optimizations, the code has to contain something which causes side-effects that the compiler cannot foresee during compile time. Input/output operations are an option. So, the loop could contain an assignment from a variable determined by input and assign results to a container determined for output.
Marking variables as volatile could be an option as well because it forces the compiler to assign the variable in any case even if it cannot "see" side-effects.

A: I ran your code. In debug I see the correct difference. In release it's 0-es. Optimized assignment is my assumption. Try in debug, or flag int q to volatile int q


text:
Q: Using Basic Authentication and Forms authentication on same site Can anyone tell me, if it is possible to use both basic and forms authentication on my site without the 2 interfering with each other?
I have a new site that I want only certain people to see for approval purposes.
The site has a members area that uses Forms authentication and now when anyone enters the site after passing basic authentication they are being directed to the forms authentication page, even though they should be viewing a page that isn't protected by forms authentication.
I need a situation whereby anyone who clears basic authentication can then view the whole site excluding the members area of the site where they will need to log in via forms authentication.

A: It sounds like you just haven't configured forms authentication for just the particular members area, but have it configured for everything.
Look at the authorization element and the location element (if you want to control the settings in the main Web.config, instead of creating a Web.config for the member's area).
See also ASP.NET Forms Authentication and a "No Authentication" subfolder (except you want the reverse).

A: One option is to write your own basic authentication filter attribute and protect the action that just require basic authentication with the custom attribute . The controller action which requires forms authentication should be protected with the normal [Authorize] attribute. Please refer the following example :-
http://www.ryadel.com/en/http-basic-authentication-asp-net-mvc-using-custom-actionfilter/
I had a similar issue in the past but was more along the lines of providing basic authentication for REST calls and form authentication when someone access the mvc site. We ended up creating our own authentication filter


text:
Q: 12.10 consumes too much battery I have trouble with battery life on ubuntu 12.10
Before I installed ubuntu 12.10, ı was user of ubuntu 12.04 LTS.
My computer is HP Probook 4530s. On 12.10 my battery life is less than 1.5 hours but on 12.04 my battery life is 2.30 - 3.00 hours.
Actually, İt sounds me crazy because sometimes i had to use my laptop portable without ac power.
Could anyone suggest anything about my problem?

A: General tips:

*Install jupiter. More info: Does Jupiter really improve battery power? To me this is a great battery saver since when changing from AC to battery it actually tells the kernel to set parameters to power saving. The deb installer can be found here: http://sourceforge.net/projects/jupiter/files/

*Try another desktop like Cinnamon . You can install this next to the normal Unity 3D. Unity and Compiz seem to be a bit power hungry.

*Install powertop and see what is causing wake up calls. The less you have the better
sudo apt-get install powertop
sudo powertop

This AU topic: How to analysis the output of powertop to increase battery lifetime got me this link to a powertop benchmark topic. Conclusion: "For best power consumption, we should have some pm-utils power.d scripts to put the following device controllers into a low power state: webcam, audio, DRAM, ethernet, wifi, bluetooth, SATA link, and your card slot (MMC/SD)"
Important  If you want to test for wakeups, you need to close EVERYTHING except the base desktop (clean boot recommended), open a terminal, unplug, and start powertop as root. Wait 10, 15 minutes and check the result.

*Check for programs that you never use. If you never use bluetooth disable it from starting (boot up manager).

*Check the lesswatts.org website for general pointers. Though some of these seem to be already active in 12.10. For instance: VM writeback is set to 60.000 (weird thing: powertop claims it is bad).

*Check power management for less aggressive options. Dim the display. Spin down the hard drive when possible.

*... and of course check websites like Ask Ubuntu, Phoronix or OMG! Ubuntu! for tips.


text:
Q: Not able to format resulting number into decimal form Why would this not show #total as a decimal?
 The value of the inputs in class="total" are a function result that stores the value in 2 decimal format.  The function to display the row totals works fine but when I use the below code to total the rows when the qty field changes, the mat is correct and the change takes place correctly, but it in an int style not a currency format (2 decimal places).  I have tried toPrecision as well with no change.
$('[name^=qty]').change(function(){
    var sum = 0;
    $('input.total').each(function() {
        sum += $(this).val();
    });

    $('#total').val(sum).toFixed(2);
    });

Here is the code that totals each row
function Tot(x,price,y) {
var total = CurrencyFormatted(x*price);
var v = document.getElementById(y);
v.setAttribute('value',total);}

All of these functions run just fine, totaling correctly and updating as expected, with exception to the decimal places in the grand total field.
Below is the html that I am using for each row and then the total
<td>$<input id="t1" disabled="disabled" size="8" value="0.00" class="total" />
...
<input disabled="disabled" id="total" name="total" size="8" value="0.00" />

There is nothing in the css that would change the format of the number either in the class or the table structure.  I am at a complete loss, but hopefully someone will see something I don't.  Thank you in advance.

A: $('input.total').each(function() {
    sum += parseFloat( $(this).val() );
});

$('#total').val( sum.toFixed(2) );

EDIT, since i was busy i didn't explain my answer, Greg Pettit did, so here's the explanation
You were trying to chain toFixed() to something that's not a number. Also, you weren't converting your retrieved values to floats. JS may have handled the latter, but better to run it through parseFloat as per sample

A: You can use the parseFloat function to do it:
parseFloat(value).toFixed(2);

for more examples:
JQuery Type examples

A: val returns a String object, not a number. you'll need to call parseFloat or cast to Number before calling toFixed(2)


text:
Q: Pandas: return multiple column values based on searching the multiple row values Assume I have a dataframe in Pandas:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': '0 1 2 3 4 5 6 7'.split(),
                   'D': '0 2 4 6 8 10 12 14'.split()})

The dataframe df looks like
      A      B  C   D
 0  foo    one  0   0
 1  bar    one  1   2
 2  foo    two  2   4
 3  bar  three  3   6
 4  foo    two  4   8
 5  bar    two  5  10
 6  foo    one  6  12
 7  foo  three  7  14

Note that the type of numbers in C and D columns is string.
I'm thinking about two conditions:
(1) Consecutive search
I want to return the D values when I'm searching C=2:5. If I use df.loc[df['C'] == '2:5', "D"], it returns an error. How can I do this part?
(2) Discrete search
I'd like to return the D values when I'm searching C=0,3,6. Again, if I use df.loc[df['C'] == '0,3,6', "D"], it returns an error. What should I write this code?

A: Consecutive Search:
The consecutive search method for a range of numerical strings can be taken care of by the isin() and zfill() method. The zfill method in the below code creates a list containing the range of the numbers:
df.D.loc[df.C.isin([str(i).zfill(1) for i in range(2,6)])]

Discrete Search
The discrete searching can be done by using the isin() method:
df.D.loc[(df.C.isin(['0','3','6'])]


text:
Q: change icon of a dialog i am recently editing an open source project in visual c++ 2010 , i don't know much about vc++ ,(i have only 5 days of experience in c++), with my little knowledge i am changing some user interface of the project
there is only one icon in my project ,the apps shows the main icon as  icon , at the same time i want to make that icon to be on the title of a dialog also (the dialog will be shown when a button in main form is clicked),
the dialog is already in the  resources/dialogs but i want to change the icon of it ;

A: You need to find the dialog procedure of the dialog you're interested in, and in the WM_INITDIALOG message handler (you need to add it if it's not already present) use WM_SETICON to set the icon:
// hIcon is your icon handle
SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon);


text:
Q: Import-PFXCertificate: The specified network password is not correct I've got some pretty simple code I'm trying to troubleshoot. The environment is an Azure Windows Server 2012 machine, and I'm logged in as a domain admin running a Powershell console with Administrator privileges.
I'm just trying to Import-PFXCertificate from a known location but it will not accept the network password.
Here's the code.
$SecurePWD = ConvertTo-SecureString -String 'iW@nt2die' -AsPlainText -Force
Import-PFXCertificate -Password $SecurePWD -CertStoreLocation "Cert:\LocalMachine\Root" -FilePath "C:\Certs\TestCert.pfx"

When I run this beautiful block of code, with the password being absolutely correct (I tested by logging in using the password), it greets me with this error:
Import-PFXCertificate : The specified network password is not correct.

WHYYYY.
I've tried escaping out the @, but that doesn't do anything. I've tried crying, but the computer is completely unmoved by my tears.

A: Per documentation for Import-PfxCertificate, the -Password parameter is for the password of the certificate and not the user to login with.

-Password - Specifies the password for the imported PFX file in the form of a secure string.

A: I know this post is a little older, but as I saw that some people commented recently, i wanted to share our solution.
We had a similar problem when we tried to replace our SSL certificate by a new one.
We experienced the same error message but while using the method Get-PfxData, not Import-Pfx but I think it's the same issue.
The problem was that our new Pfx-Password contained a dollar sign $ which is reserved in Powershell to be variable. After escaping the dollar sign with a quote (`) it worked.
So if the password was XyZaBc$DeF we needed to use XyZaBc`$DeF.
That solved the problem in our case.


text:
Q: Copy Sheet with protections and change new Duplicate's name to a date I have a template sheet for group data entry. Most of the sheet is free entry, but there are title rows that I don't want edited so I have them protected. We have one of these tabs for each day of the month and a new Sheet for each month.
I want to copy the template 30-31 times depending on the month and have the title of the sheet be the corresponding date (MM.dd.yy ie: 11.02.20). I have the Date set in A2 (ie: 11/01/2020).
So far I tried combining a protections and a date change, but I keep getting variable errors and then sometimes it double creates sheets (like 11.06.20 and then stops).
This is the code I've tried (and edited and moved around a few times).
function duplicateSheetWithProtections() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();
  var dateCell = "A2";
  sheet = ss.getSheetByName('Template.01.20');
  sheet2 = sheet.copyTo(ss).setName('11..20');
  var N = 30;
  var startDate = new Date(s.getRange(dateCell).getValue());
  var day = startDate.getDate();
  var month = startDate.getMonth();
  var year = startDate.getFullYear();
  for (var i = 0; i < N; i++) {
    var asn = s.copyTo(ss);
    var thisSheetDate = new Date(year, month, day+(i+1));
    asn.getRange(dateCell).setValue(thisSheetDate);
    asn.setName(Utilities.formatDate(thisSheetDate, "GMT-08:00", "MM.dd.yy"));
  var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  for (var i = 0; i < protections.length; i++) {
    var p = protections[i];
    var rangeNotation = p.getRange().getA1Notation();
    var p2 = sheet2.getRange(rangeNotation).protect();
    p2.setDescription(p.getDescription());
    p2.setWarningOnly(p.isWarningOnly());
    if (!p.isWarningOnly()) {
      p2.removeEditors(p2.getEditors());
      p2.addEditors(p.getEditors());
      // p2.setDomainEdit(p.canDomainEdit());
   }
  }
 }
}

Any help would be greatly appreciated.
Also, new to this and if you couldn't tell, kind of a noob. So any references to help grow would be awesome. Thanks!

A: Issue:
You are using the same variable (i) for two different for loops, one nested inside the other. This is messing up with your dates, causing the error you're getting.
Solution:
Change the variable name of the inner loop (for example, to j):
  for (var j = 0; j < protections.length; j++) {
    var p = protections[j];

Further issues:

*

*You are setting protections to sheet2, which corresponds to the copied sheet with name 11..20, but not to the rest of sheets (actually, I'm not sure what's the point of making this copy, so I'd just delete the line sheet2 = sheet.copyTo(ss).setName('11..20');). In order to set the protections to each copied sheet, you should use asn instead:

var p2 = asn.getRange(rangeNotation).protect();

*

*Since you want to copy the file named Template.01.20, there is no point in getting the active sheet and storing it in s. I'd just change the mentions of s to sheet (and remove the line var s = ss.getActiveSheet();, since it's not needed):

var startDate = new Date(sheet.getRange(dateCell).getValue());
// ...
var asn = sheet.copyTo(ss);

*

*Since the number of sheets to copy depends on how many days the month has, I'd suggest you to dynamically find that number. You can do that using the following function, for example (credits to Juan Mendes):

function getDaysInMonth(year, month, day) {
  var date = new Date(year, month, day);
  var days = [];
  while (date.getMonth() === month) {
    days.push(new Date(date));
    date.setDate(date.getDate() + 1);
  }
  return days;
}

Which you could then call in your main function:
  var dates = getDaysInMonth(year, month, day + 1);
  for (var i = 0; i < dates.length; i++) {
    var asn = sheet.copyTo(ss);
    var thisSheetDate = dates[i];

Code sample:
Therefore, your code could be something like this instead:
function duplicateSheetWithProtections() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dateCell = "A2";
  var sheet = ss.getSheetByName('Template.01.20');
  var startDate = new Date(sheet.getRange(dateCell).getValue());
  var day = startDate.getDate();
  var month = startDate.getMonth();
  var year = startDate.getFullYear();
  var dates = getDaysInMonth(year, month, day + 1);
  for (var i = 0; i < dates.length; i++) {
    var asn = sheet.copyTo(ss);
    var thisSheetDate = dates[i];
    asn.getRange(dateCell).setValue(thisSheetDate);
    asn.setName(Utilities.formatDate(thisSheetDate, "GMT-08:00", "MM.dd.yy"));
    var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
    for (var j = 0; j < protections.length; j++) {
      var p = protections[j];
      var rangeNotation = p.getRange().getA1Notation();
      var p2 = asn.getRange(rangeNotation).protect();
      p2.setDescription(p.getDescription());
      p2.setWarningOnly(p.isWarningOnly());
      if (!p.isWarningOnly()) {
        p2.removeEditors(p2.getEditors());
        p2.addEditors(p.getEditors());
      }
    }
  }
}

function getDaysInMonth(year, month, day) {
  var date = new Date(year, month, day);
  var days = [];
  while (date.getMonth() === month) {
    days.push(new Date(date));
    date.setDate(date.getDate() + 1);
  }
  return days;
}


text:
Q: CodeCollab GUI issues I am trying to upload code to Code Collaborator via the GUI. When I enter the server url, username and password and select ClearCase as the SCM, I get the following error: Error: rational cm api for clearcase remote client not found. Has anyone encountered this before? What have you done to solve this?

A: URL means that you are communicating with a CCRC server (a ClearCase Remote Client server) in order to review code stored in ClearCase.
The CodeCollaborator (v7.0.7027) user guide does mention:

Support for ClearCase Remote Client (CCRC)
CodeCollaborator integration with CCRC uses the Rational Change Management Server API.
  When running the CodeCollaborator client installer, there is an edit field allowing you to
  select the location of the Rational CM API jar files on your system. The required files are:

*

*remote_core.jar

*stpcc.jar

*stpcmmn.jar

*stpwvcm.jar
These files are installed by the ClearCase Remote Client under the Rational Shared
  Resource Directory.
  The directory should look similar to one of the following:

C:\Program Files\IBM\IMShared\plugins\com.ibm.rational.teamapi_7.1.2.v201105310712
# or
/opt/eclipse/plugins/com.ibm.rational.teamapi_7.1.2.v201105310712

Find the location of the files on your system and select or enter it during install so the CodeCollaborator installer can make them available to the CodeCollaborator client.
  The installer will copy them to the following subdirectory under the CodeCollaborator client installation directory:

ui/plugins/com.smartbear.collaborator_7.0.xxxx/libs

If using the RPM installer, you will have to manually copy these files to the correct
  subdirectory.

So make sure you have those files present on the system, and copied on the CodeBear client installation directory.


text:
Q: CMake cyclic dependency of external and internal static library I have a framework/code generator with a static library libA.a which contains symbols which are defined by the generated code (libB). So essentially, I imagine the dependency graph is circular, since the generated code uses API from libA:
libB -> libA -> libB

libB I am building, and then using to create an executable
set(LIBA libA.a)

add_library(libB "${libb_sources}")

target_link_libraries(libB libA)

add_executable(execAB ${MAIN_SRC})
target_link_libraries(execAB libB)

The issue I have is that during linking, libA symbols defined in libB are not getting resolved. Relatively normal circular dependency, but including an external library not built during our build.
/usr/local/lib/libara_vsomeipbinding.a(vsomeip_proxy_factory.cc.o): In function `ara::com::internal::vsomeip::runtime::VSomeIPProxyFactoryImpl::AvailabilityHandler(unsigned short, unsigned short, bool)':
vsomeip_proxy_factory.cc:(.text+0x7ff): undefined reference to `ara::com::internal::vsomeip::runtime::VSomeIPServiceMapping::GetMappingForVSomeIPServiceId(unsigned short)'

What I have tried so far:

*

*making libB an OBJECT library resolves the issue, but I have the requirement to make it a static library, to keep in line with other parts of the project, so that is not a solution

*defining an intermediate static library libC, with libB being a OBJECT library -> does not help because the situation is essentially unchanged, I guess.

*having a intermediate library libC, and defining the dependencies multiple times to have them appear multiple times in the linker command line. Didn't work, they only appeared once.

*defining a circular dependency between libB and libC, in the hope that dependencies also get doubled. No, only those two appear twice on the command line.

Other issues:

*

*gcc-only solutions like --start-group/--end-group is also not an option because we target both Visual Studio and gcc

*I don't want to add libA as dependency of execAB if possible, the dependency should be encapsulated in some (static if possible) library target

How do I get the linker to link libA and libB as group/ twice so all symbols get properly resolved?

More detailed information:
I am building a framework on top of the ARA reference implementation of adaptive AUTOSAR. In AUTOSAR, services / service interfaces are defined in XML files, ARA has a code generator which reads these and generates code for these services / for their communication, which my framework uses. During my cmake build, the ARAgen generator runs to generate the code.
There is, of course, a static part of the ARA API, this is libA. In the generated portion of the code, which is part of libB, there is, for example, ara::com::internal::vsomeip::runtime::VSomeIPServiceMapping::GetMappingForVSomeIPServiceId(unsigned short), which according to the name I would say maps numeric IDs to the specific (generated) Services. This is used by the static ARA part to map from service id to service object/class.
On the other hand, the static ARA library of course contains code that the generated part uses (base classes and such, I guess).


text:
Q: jeditable callback has empty values
Possible Duplicate:
jeditable callback has empty values //OR// How to display edited text after clicking save button?

In my code I found value and settings are empty in callback function...
can anyone help why is that so?
$(".edit_area").editable('/cgi-bin/mycgiscript.cgi', {
event       : 'dblclick',       //or dblclick
type        : 'textarea',
rows        : 2,
cols        : 30,
cancel      : 'Cancel',
submit      : 'Save',
indicator   : '<img src="images/indicator.gif">',
placeholder : 'Double Click to enter text',
tooltip     : 'Double Click to edit...',
name        : 'name',
id      : 'id',
callback    : function(value, settings) {
console.log('value='+value);
console.log('settings='+settings);
console.log('callback executed='+value);
return(value);
}
});

I used callback, because after 'SAVE'ing the edited text. The edited text is not displayed on the HTML page. It is properly being saved in the backend database. I have re run the ajax call which displays the updated information from the backend server...
editable is attached to the div in the html table which is being generated from an ajax call. if it helps...


text:
Q: Authorize User in Spring/Jersey I'm working in a Spring/Jersey setup and trying to figure out how to authorize a user to access only resources that belong to them.  I've seen numerous examples of how to secure an endpoint using authorization or broad role-based security, but I haven't seen anything that makes sure the user submitting the request is submitting it for his/her own stuff.
For clarity, suppose I have a GET /account/1 endpoint.  I want only the user with ID 1 to be able to access that account information and only once he/she is authenticated.  I've got the latter part taken care of using OAuth, but I can't figure out the former part.
How could I go about doing this?

A: By default, Spring Security's SecurityContext is a thread local. So you can access it anywhere from the request thread, using the SecurityContextHolder. From the SecurityContext you can obtain the UserDetails, which will have the user name.
So because the Jersey request processing occurs in the same request thread, you should be able to access this information. From a Jersey component you can use whatever service you want to obtain you actual user domain objects and just check for the same user. For example you can have something like
@Path("/accounts")
public class AccountsResource {

    @Inject
    private UserService userService;

    @GET
    @Path("/{id}")
    @Produces("application/json")
    public User get(@PathParam("id") Long id) {
        User user = userService.getUser(id);
        // if user == null throw 404

        UserDetails userDetails
                = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();

        if (!userDetails.getUsername().equals(user.getUsername())) {
            throw new ForbiddenException();
        }

        return user;
    }
}

If you have a lot of endpoints like this, and you want to keep it DRY, you can use a Jersey filter to handle the access control process.
@Provider
@AccessFiltered
@Priority(Priorities.AUTHORIZATION)
public class UserAccessFilter implements ContainerRequestFilter {

    @Inject
    private UserService userService;

    @Override
    public void filter(ContainerRequestContext requestContext) {
        List<String> params = requestContext.getUriInfo().getPathParameters().get("id");
        Long id = Long.parseLong(params.get(0));
        User user = userService.getUser(id);
        // if user == null throw 404

        UserDetails userDetails
                = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();

        if (!userDetails.getUsername().equals(user.getUsername())) {
            throw new ForbiddenException();
        }
    }
}

Now with the Name Binding Annotation @AccessFiltered
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface AccessFiltered {
}

We can just filter the methods we annotated
@GET
@Path("/{id}")
@AccessFiltered
@Produces("application/json")
public User get(@PathParam("id") Long id) {
}

Now suppose we want access to that User, and we don't want to have to hit the DB again to retrieve it in our resource method. It's possible to put the User we obtained inside the filter, into the request context (a full example here)
public class UserAccessFilter implements ContainerRequestFilter {

    public static final String USER_FILTER_PROPERTY = "UserAccessFilter.User";

    @Override
    public void filter(ContainerRequestContext requestContext) {
        ...
        User user = userService.getUser(id);
        ...
        requestContext.setProperty(USER_FILTER_PROPERTY, user);
    }
}

Then we can just inject the User into our resource method
@GET
@Path("/{id}")
@AccessFiltered
@Produces("application/json")
public User get(@Context User user) {
    return user;
}

There's one more step to configure this (i.e. the Factory - see the previous link). You could also create a custom annotation for injecting the user, but that gets a bit more complicated.
I'm sure this type of access control could be implemented using Spring Security's ACL feature, but for me being a Jersey user, this way is more intuitive for me.


text:
Q: Retrofit how to use colon in url? I am developing an Android app using Google Photo API.
I am trying to upload an image file into the Google Photo Server using below API.
https://developers.google.com/photos/library/reference/rest/v1/mediaItems/batchCreate
According to the document, I should use below URL to upload an image file.
POST https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate

So I write the code using the retrofit.
@Headers("Content-type: application/json")
@POST("mediaItems:batchCreate") // The point is here
fun batchCreate(@Header("Authorization") authorization: String, @Body batchCreateRequest: BatchCreateRequest): Observable<BatchCreateResponse>

When I run it, IllegalArgumentException occurred.
java.lang.IllegalArgumentException: Malformed URL. Base: https://photoslibrary.googleapis.com/v1/, Relative: mediaItems:batchCreate
What can I do solve this problem?

A: Try using @POST("./mediaItems:batchCreate") instead of @POST("mediaItems:batchCreate")


text:
Q: I want to POST/PATCH Map> and also ImageFile using Dio in flutter I want to send this JSON file to API -
 {
            "speciality": [7,2]
        }

My Workings:
    class Doctor {
          dynamic specialities;

          Doctor({
            this.specialities,
          });

          Map<String,dynamic>toJson()=>{
            "speciality": List<dynamic>.from(specialities.map((x) => x)),
         };
        }

So when I used http.patch it worked fine (code below). My question is how to do the same thing using Dio package because I am working with MuiltipartFile.
response = await http.patch(
      Uri.encodeFull(fullUrl),
      body: jsonEncode(doctor.toJson()),//jsonEncode(data),
      headers: {
       'Content-type' : 'application/json',
       'Accept' : 'application/json',
       'Authorization' : 'Token $token',
     },
    );

I tried using Dio code(below), I got no error in the console but it is not patching successfully.
updateDoctorInformation(Doctor doctor,token) async{
    Dio dio = new Dio();
            var formData = FormData();
            formData = FormData.fromMap(doctor.toJson());

            Response response = await dio.patch(
                      Uri.encodeFull(fullUrl),
                      data: formData,
                      options: Options(
                        followRedirects: false,
                        validateStatus: (status) {
                          return status < 500;
                        },
                        headers: {
                          'Content-type' : 'multipart/form-data',
                          'Accept' : '*/*',
                          'Authorization' : 'Token $token',
                        },
                      )).catchError((onError){
                    print(onError.toString());
                  }).whenComplete(() => print("completed"));
                  print(response.data);
                  return response;
}

I Need the Dio code correction. Thanks in advance.

A: I found a way that is adding separately.
if(doctor.specialities !=null){
        for(int i=0;i<doctor.specialities.length;i++){
          formData.fields.add(
              MapEntry("speciality",doctor.specialities[i].toString())
          );
        }
      }

Still, I am seeking for a better solution like using toJson above


text:
Q: Android Firebase How to wait for image upload before registering to database? I am new to android development and I have an issue.
I have a fragment in which a user can post an announcement and should be able to upload a photo(optional).
When the form is full and the "Post announcement" button is pressed, I trigger the method to save the information to the database.
The only problem I am facing is retrieving the Uri of the newly uploaded photo.
This is the code which extracts the information.
public Map<String, Object> appendDataFromAnnouncementForm(){
    String title = titleLineEdit.getText().toString();
    String category = categoryLineEdit.getText().toString();
    String description = descriptionLineEdit.getText().toString();
    String date = dateLineEdit.getText().toString();
    String time = timeLineEdit.getText().toString();
    String location = locationLineEdit.getText().toString();

    //Image upload to firebase + getting the Uri

    if(localPhotoUri != null){
        uploadImageToFirebase(generatePhotoName(localPhotoUri), localPhotoUri);
    }

    Map<String, Object> newAnnouncement = new HashMap<>();

    //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    if(uploadedImageUri != null) // <- this is always null
    {newAnnouncement.put("imageUri", uploadedImageUri.toString());}
    //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

    newAnnouncement.put("title", title);
    newAnnouncement.put("category", category);
    newAnnouncement.put("description", description);
    newAnnouncement.put("date", date);
    newAnnouncement.put("time", time);
    newAnnouncement.put("location", location);

    return newAnnouncement;
}

Below I am posting the code which uploads the photo to Firebase Storage. Since
private void uploadImageToFirebase(String photoName, Uri localContentUri) {
    imagesStorageReferance = myStorageReference.child("images/" + photoName);
    imagesStorageReferance.putFile(localContentUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            //getUploadedImageUri(referenceToImageFolder);
            imagesStorageReferance.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    Log.d(TAG, "onSuccess: The download url of the photo is "
                            + uri.toString());
                    uploadedImageUri = uri; /// <- I want to retrieve this
                }
            });

        }
    })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d(TAG, "onFailure: Failed uploading the photo to the database " + e.getMessage());
                }
            });
}

From what I have read on the Internet, this is an synchronization problem(basically, the app registers the information to the database before my photo is uploaded). There are many solutions which I have tried, but I can't really figure it out one to work on my case...
I would be very grateful if you could provide me some explanation on what I should do in order to fix this. How can I wait the photo to be uploaded ?

A: Since firebase works asynchronously, the code continues to execute regardless of whether firebase has finished the upload process or not. In your case, the time to run the code following firebase is faster than the upload time to firebase to eventually assign uploadedImageUri = uri; which explains why you are getting a null value for uploadedImageUri present directly after the call for upload.
For this matter, I would suggest you to register to database inside uploadImageToFirebase function after uploadedImageUri = uri; to ensure that uploadedImageUri is never null and always fetched before database registration.
private void uploadImageToFirebase(String photoName, Uri localContentUri) {
    imagesStorageReferance = myStorageReference.child("images/" + photoName);
    imagesStorageReferance.putFile(localContentUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            //getUploadedImageUri(referenceToImageFolder);
            imagesStorageReferance.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    Log.d(TAG, "onSuccess: The download url of the photo is "
                            + uri.toString());
                    uploadedImageUri = uri;
    String title = titleLineEdit.getText().toString();
    String category = categoryLineEdit.getText().toString();
    String description = descriptionLineEdit.getText().toString();
    String date = dateLineEdit.getText().toString();
    String time = timeLineEdit.getText().toString();
    String location = locationLineEdit.getText().toString();

    Map<String, Object> newAnnouncement = new HashMap<>();

    newAnnouncement.put("imageUri", uploadedImageUri.toString());

    newAnnouncement.put("title", title);
    newAnnouncement.put("category", category);
    newAnnouncement.put("description", description);
    newAnnouncement.put("date", date);
    newAnnouncement.put("time", time);
    newAnnouncement.put("location", location);

//UPLOAD newAnouncement TO FIREBASE HERE...
                }
            });

        }
    })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d(TAG, "onFailure: Failed uploading the photo to the database " + e.getMessage());
                }
            });
}

A: I am sharing the code from my project:
Assign this globally:
StorageTask uploadTask;
String myUrl = "";

and this is code:
private void uploadImage()
{
    if (imageUri != null)
    {
        final StorageReference reference = storageReference.child(System.currentTimeMillis()+"."+getExtension(imageUri));
        uploadTask = reference.putFile(imageUri);
        uploadTask.continueWithTask(new Continuation() {
            @Override
            public Object then(@NonNull Task task) throws Exception {
                if (!task.isComplete())
                {
                    throw task.getException();
                }
                return reference.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful())
                {
                    Uri downloadUri = task.getResult();
                    myUrl = downloadUri.toString();

                    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Categories")
                            .child(randomKey);

                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("categoryId", randomKey);
                    hashMap.put("categoryImage", myUrl);
                    hashMap.put("categoryName", editText.getText().toString());

                    databaseReference.setValue(hashMap);

                    save.setVisibility(View.VISIBLE);
                    startActivity(new Intent(AddCategoryActivity.this, CategoriesActivity.class));
                }
                else
                {
                    save.setVisibility(View.VISIBLE);
                    Toast.makeText(AddCategoryActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                save.setVisibility(View.VISIBLE);
                Toast.makeText(AddCategoryActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    else
    {
        save.setVisibility(View.VISIBLE);
        Toast.makeText(this, "No Image Selected", Toast.LENGTH_SHORT).show();
    }
}