How can I manage all of my domains with minimal configuration?

Question:
This is a Canonical Question about DNS server administration.

I have one hundred or so domains. All of these domains need to be configured identically, but it seems like a huge waste of time to have to configure a new zone and/or zonefile for every one of these domains. There has to be a better way to automate this!
I think I'm on to something...if I create a zone called ., or use some other feature in my DNS software to always return a specific IP when an A record is requested, this seems to get me pretty close to my desired end result. My server is responding authoritatively to the requests and it's so much easier to manage!
This was working great until nameserver validation software started checking these domains. I figured out that I can make most of the errors go away by adding NS records, but my software won't let me put more than one SOA record in the same zone file.
How do I work around this multiple SOA record problem?
Answer: Unless I'm misunderstanding the question, I do this regularly with BIND, and it seems to be fine as long as each zone is absolutely identical.
On my primary nameserver, I have named.conf entries that point to the generic zonefile, eg
zone "example.com" {
        type master;
        file "primary/example.GENERIC";
};

zone "example.co.uk" {
        type master;
        file "primary/example.GENERIC";
};

and then a zonefile primary/example.GENERIC which says, eg
;; Start of Authority
@       IN      SOA     ns.teaparty.net. dns.gatekeeper.ltd.uk. (
                        2004091201      ; serial number YYYYMMDDNN
                        28800           ; refresh  8 hours
                        7200            ; retry    2 hours
                        864000          ; expire  10 days
                        3600 )          ; min ttl  1 day
;;
;;      Name Servers
                IN      NS      ns.teaparty.net.
                IN      NS      ns2.teaparty.net.

And I'm not aware of any problems with these zones at all.  I'm open to being told that I've misunderstood the question, or that my domains in fact don't work, but until then I think it works for me.
Note that you cannot pull the same trick on the secondary; each zone will require a different file to be stored in.  But since the contents of that file will be populated and kept up-to-date by zone xfers from the primary, this isn't a huge deal.
Answer: Short Answer
If you're looking for a "zero configuration" setup in BIND, it doesn't exist. Setting up a root zone (.) seems like a good idea, but it's not, and you need to find a solution that doesn't involve breaking DNS to suit your needs.
Long Answer
We've been getting variants of this question several times in the past year.
The answer is pretty simple here: you can't set up a single zone definition. Any software that lets you define or otherwise synthesize multiple SOA records in this context is broken software, and doing broken things is not on topic for ServerFault. You either need to choose DNS software that makes this management simpler for you, or you need to come up with a different strategy that does not involve this particular shortcut.
There are definitely some tricks you can use to make life easier...using BIND as an example, it's fairly commonplace to define multiple zones that all reference the same template zone file. This is perfectly legal and validation software will find nothing wrong with it: see MadHatter's answer. Most people pass over this solution because it's still "too much work" to add a zone declaration every time a new domain is acquired, but there is no "configure it once and walk away" option for this kind of hosting.
Newer versions of BIND support an option called allow-new-zones that will let you dynamically create zone definitions on the fly via the new rndc addzone functionality. You might want to take a look at this and see if it fits your needs.
Other than that the suggested solutions, your options are somewhat limited. Sometimes you're just stuck with doing the work if the software doesn't do things the way you want it to.
Answer: There are a number of shortcuts you can use to make your life easier:
If you use Bind or similar software that uses files to store the zone data: point your zones to the same file for example:
zone "example.net" {
    type master;
    file "/etc/bind/zone/default.zone";
};

zone "example.org" {
    type master;
    file "/etc/bind/zone/default.zone";
};

Because you can make use of certain DNS shorthands you can create a universal zone file:
$TTL 1h      ; default expiration time of all resource records without their own TTL value
@  IN  SOA   ns1.example.com. username.example.com. (
                               20140218131405 ; Serial number YYYYMMDDHHMMSS
                                        28800 ; Refresh     8 hours
                                         7200 ; Retry       2 hours
                                       604800 ; Expire      7 days
                                        86400 ; Minimum TTL 1 day )
@             IN  NS    ns1.example.com.      ; ns1.example.com is a primary nameserver
@             IN  NS    ns2.example.com.      ; ns2.example.com is a backup nameserver
@             IN  MX    10 mail.example.com.  ; mail.example.com is the mailserver
@             IN  MX    20 mail2.example.com. ; the secondary mailserver
@             IN  A     192.0.2.1             ; IPv4 address for the bare domain
              IN  AAAA  2001:db8:10::1        ; IPv6 address for the bare domain
www           IN  A     192.0.2.1             ; www.domain
              IN  AAAA  2001:db8:10::1        ; IPv6 address for www.domain - note by starting the line with a blank it becomes the continuation of the previous record and this IPv6 record applies to www
wwwtest       IN  CNAME www                   ; wwwtest is an alias for www

This makes use of the fact that the hostnames in zone files that don't end with
   a dot . are always expanded with the $ORIGIN which in turn is implicitly set to the zone name. And @ is short-hand for the $ORIGIN.

Rather than maintain individual zone files by hand, enable a method interact programmatically with your name servers.
I've used PowerDNS which allows for a RDMS as a back-end which fit in very well with the LAMP stack we were using at the time. Cloud Services like Amazon Route 53 also expose web-API's.
But even venerable Bind also supports dynamic Update which is a method for adding, replacing or deleting records in a master server by sending it a special form of DNS messages. The format and meaning of those messages is specified in RFC 2136.
Dynamic update is enabled by including an allow-update or an update-policy clause in the zone statement. For more info check the Bind Administrator Reference Manual.
Comment: The first half of your answer is dead on, but I'm not sure that DDNS applies here...it can't be used to add or remove zones, which defeats what most people in this scenario are trying to accomplish. (not having to touch named.conf for every zone add) The closest thing I know of in BIND land is the new `rndc addzone` option, but that's still kind of ugly since it ends up generating a config file with a hashed name in the working directory for every added zone.
Comment: In understand what you're trying to say, but a different interpretation is that the difficulty with many domains is in maintaining and duplicating work. Automating/scripting DNS is something which is not well documented.
Answer: When you say "domains need to be configured identically", do you mean they have to hold the same resource records? In that case, wouldn't a DNAME RR for all but one domain be a cleaner solution?
I cannot beat the trick by @MadHatter of importing the same template file while staying strictly within the scope of your question. I can only offer similar approach for LDAP backend (in my case, used with powerDNS): add the associatedDomain attributes for the relevant SOA and NS records, like so:
dn: dc=vanitydomains,ou=DNS,dc=myDIT
objectClass: dNSDomain2
objectClass: domainRelatedObject
dc: vanitydomains
associatedDomain: vanitydomain.ORG
associatedDomain: vanitydomain.NET
associatedDomain: vanitydomain.COM
associatedDomain: vanitydomain.INFO
sOARecord: NS1.example.com  sysadmin.example.com 2011100701 28800 1800 2592000 10800
dNameRecord: example.com
nSRecord: NS1.example.com
nSRecord: NS2.example.com

Comment: Sadly the DNAME technique misses the apex of the zone due to limitations of the RFCs. CNAME synthesis resulting from DNAME records are still subject to the same [constraints](http://serverfault.com/questions/613829/why-cant-a-cname-record-be-used-at-the-apex-of-a-domain) of non-synthetic CNAME records. Unlike MadHatter's solution, the result is very far from 100% identical RRsets.


React Native - Como atribuir valores a uma variável vetor usando Hooks como UseState

Question: const[VetImg,SetVetImg] = useState<any>([''])

quero atribuir valores nessa variável
ex:
VetImg[0] = 'teste.png'

eu sei que a variável é de estado e que tem que ser atribuída pelo SetVetImg porém eu quero informar a posição que será atribuída.
Answer: Não sei se está certo, mas veja se esse código resolve o problema:

import React, { useState, useEffect } from "react";

const App = () => {
    const [getVetImg, setVetImg] = useState([]);

    function addVetImg(value: string) {
        const vet = getVetImg; // talvez seja preciso usar this.getVetImg() ou this.getVetImg dependendo do contexto e ainda acrescentar o tipo da variavel, sendo const vet: string[] = getVetImg

        vet.push(value); // ou vet[0] = value;

        setVetImg(getVetImg => vet);
    }

    // desta forma, pode chamar addVetImg("teste.png"); em qualquer lugar onde for usar esse código
};
Comment: deu certo cara muito obrigado !!!!
Comment: de nada, é que agora estou usando mais React, mas já usei React Native e por isso que respondi.


Estimating the integral $\int_0^1 (1-t^2)^{-1/2} e^{-nt} \,dt$ for large $n$.

Question: I would like to find the asymptotic behavior of the integral
$$\int_0^1 (1-t^2)^{-1/2} e^{-nt} \,dt$$
for large $n$.  It seems reasonably obvious that the integral goes to zero.  At least it is bounded; the integral is between $0$ and
$$\int_0^1 (1-t^2)^{-1/2} \,dt = \pi/2.$$
I am just learning asymptotic methods and I'm having trouble even approaching this.  I thought that Laplace's method might be appropriate but only the case of $\int_{-\infty}^{\infty}$ is discussed in the books I have.
Full, detailed steps would be greatly appreciated.  My goal is to try to estimate a slightly more complicated integral.
Comment: FWIW, Wolfram Alpha gives an asymptotic expansion for large $n$: http://www.wolframalpha.com/input/?i=expansion+of+Integrate%5B%281-t%5E2%29%5E%28-1%2F2%29Exp%5B-nt%5D%2C+%7Bt%2C+0%2C+1%7D%5D+near+n%3Dinfinity
Comment: Have you tried using an expansion for $e^{-nt}$ in series and then switch the sum and the integral? If you have a formula for
$$
\int_0^1 \frac{t^k}{\sqrt{1-t^2}} \, dt
$$
perhaps it would become useful. It's just a suggestion at the moment because I'm tired and your question make me think of this.
Comment: Heh, funny you found the Beta function thing. Fancy. Are you sure of the divergence? I know nothing about beta functions beside their definition.
Comment: I still know nothing about those functions, so I just hope you had fun =) I am not very much into integrals, mostly those I can't handle. =P

But I see that I was out of context. Since you spoke of $-\infty$ to $\infty$ cases, perhaps an appropriate change of variable could be considered? Not at all a directed guess, just an idea. I have absolutely no reason or faith that this is the right direction though.
Comment: @Mariano, am I interpreting that correctly as $O(e^n n^{-3/2})$?  I think that may be a bit off, considering the integral is bounded between $0$ and $\pi/2$.
Comment: @Patrick, those integrals are Beta functions:

$$\int_0^1 (1-t^2)^{-1/2} t^k \,dt = \frac{1}{2}B\!\left(\frac{1}{2},\frac{k+1}{2}\right).$$

But I'm not sure you can switch the sum and the integral, mostly because the resulting series

$$\frac{\pi}{2}-\frac{n B(1/2,1)}{2}+\frac{n^2 B(1/2,3/2)}{4}-\frac{n^3 B(1/2,2)}{12} + \cdots$$

diverges as $n \to \infty$.
Comment: @Patrick: You're right, I spoke too soon.  According to WA, the series converges to

$$\frac{\pi}{2}(I_0(n)-L_0(n)+1),$$

where $I_0$ is the modified Bessel function of the first kind of order $0$, and $L_0$ is the modified Struvel function of order $0$ (that one's certainly new to me!).  The graph of this seems to indicate convergence as $n\to\infty$.

Link to WA: http://preview.tinyurl.com/6shhvc5
(I hope tinyurl isn't frowned upon here.)

However, estimating this by looking up the relevant expansions wouldn't help me learn about handling integrals, which was my goal for this question.
Answer: For large $n$ the integral is dominated at points where $\text{Re} t$ is smallest. In your case this is at $t=0$. Thus to get the correct asymptotic expansion (up to exponential accuracy), you need to expand the integrand around $t=0$:
$$\int_0^1 \!dt\,\frac{e^{-nt}}{\sqrt{1-t^2}} =
\int_0^1 \!dt\,e^{-nt} \left[ 1 + \frac{t^2}2 + O(t^4) \right].$$
Next step is to note that we introduce only exponential small errors (in $e^{-n}$) by extending the integral up to $t=\infty$. Thus, we have
$$\int_0^1 \!dt\,\frac{e^{-nt}}{\sqrt{1-t^2}} \sim
\int_0^\infty \!dt\,e^{-nt} \left[ 1 + \frac{t^2}2 + O(t^4)\right]=
n^{-1} + n^{-3} + O(n^{-5}). $$
This asymptotic expansion (because it only involves integer powers in $n$) you could as well have obtained by successive integrating (integrating $e^{-nt}$ and differentiating the rest).
Much more interesting is the asymptotic expansion for $n\to-\infty$...
Comment: @Antonio Vargas: for $n$ (very) large $e^{-nt_1} \gg e^{-n t_2}$ when $t_1<t_2$ (and this remains even true when multiplied by some algebraic function).
Comment: @AntonioVargas: this is exactly my statement. The other contributions are exponentially small. The contributions from $t\approx 0$ give $S_0=\sum_m a_m n^{-m}$ and the contribution from $t\approx 1$ give $S_1=e^{-n}\sum_m a_m n^{-m}$. For $n\to\infty$, $S_1 \ll S_0$ (exponents kill everything algebraic).
Comment: Fabian, thank you so much for your help :)
Comment: Thanks Fabian.  Could you go into detail on how to justify that the integral is dominated by small values of $t$?
Comment: I think the part I'm getting hung up on is how to estimate the contribution of the pole at t=1 and then conclude that it is negligible. For example, I tried showing that I may extend the integral to $\infty$ with small error, but I can only show that

$$\left|\int_{1+\delta}^{\infty} (1-t^2)^{-1/2} e^{-nt} \,dt \right| \leq \frac{1}{\sqrt{\delta}} \cdot \frac{1}{n e^n}$$

and hence that

$$\int_{1+\frac{1}{n}}^{\infty} (1-t^2)^{-1/2} e^{-nt} \,dt = O(n^{-1/2} e^{-n}).$$

Is this enough to conclude that the contribution of $\int_1^{\infty}$ is negligible?
Comment: @AntonioVargas: just to give a bit more information. For the asymptotic expansion of an integral, you have to check either saddle points inside the integration region AND the boundary terms (you cannot deform your integration contour away from the initial and final point).


What is the Oracle date formatting mask for time zones?

Question: I need to insert a date format from an outside source which includes the three letter code for time zone, but the TZD formatting mask does not seem to work...
insert into blah
    values (to_date('Thu, 18 Feb 2010 08:37:00 EST','Dy, DD Mon YYYY HH24:MI:SS TZD'));

ORA-01821: date format not recognized

If I remove the "TZD"...
insert into blah
    values (to_date('Thu, 18 Feb 2010 08:37:00','Dy, DD Mon YYYY HH24:MI:SS'));

1 row created.

What is the proper mask for such an insert statement in Oracle?
desc blah
 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 D                          DATE

Edit: I changed the table column from DATE type to TIMESTAMP type and got the same error.
Answer: Date columns don't have timezone as an option.  You'd have to create the column as data type TIMESTAMP WITH TIME ZONEorTIMESTAMP WITH LOCAL TIME ZONE, and besides, the TO_DATE function doesn't understand the TIME ZONE format mask you're applying.
SQL> CREATE TABLE T
  2  (DT DATE,
  3   TS TIMESTAMP,
  4   TSTZ TIMESTAMP WITH TIME ZONE,
  5   TSLTZ TIMESTAMP WITH LOCAL TIME ZONE);

Table created.

SQL> INSERT INTO T (TSLTZ) VALUES
  2  (to_timestamp_tz('Thu, 18 Feb 2010 08:37:00 EST','DY, DD Mon YYYY HH24:MI:SS TZD'))
  3  /

1 row created.

SQL> INSERT INTO T (TSTZ) VALUES
  2  (to_timestamp_tz('Thu, 18 Feb 2010 08:37:00 EST','DY, DD Mon YYYY HH24:MI:SS TZD'))
  3  /

1 row created.

Answer: If timezone is not relevant for you, just strip it from the string using SUBSTR function and insert as in your second example.


how do i pass props to next screen using Navigate

Question: <Navigate to={"/plans"} />;
I am using this to navigate to plans page but i want to send some data with it any idea how can I do it? new to programming
Answer: Pass data in route state on the Navigate component's state prop.
Navigate

declare function Navigate(props: NavigateProps): null;

interface NavigateProps {
  to: To;
  replace?: boolean;
  state?: State;
}

Usage:
<Navigate to={"/plans"} state={{ data }} />

And to access the route state on the target routed component use the useLocation hook access it.
const { state } = useLocation();

...

const { data } = state;

Answer: you can read here https://reactnavigation.org/docs/params. you can pass some props using navigate and route.
for example in screen 1
      <Button
        title="Go to Details"
        onPress={() => {
          navigation.navigate('Details', {
            itemId: 86,
            otherParam: 'anything you want here',
          });
        }}
      />

in screen 2
function DetailsScreen({ route, navigation }) {
  const { itemId, otherParam } = route.params;
  return (
  );
}

you can navigate using the name of screen
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

function MyStack() {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Home" component={HomeScreen} />
      <Stack.Screen name="Details" component={DetailsScreen} />
    </Stack.Navigator>
  );
}

Comment: OP appears to be using `react-router-dom`, not `react-navigation`. It's a completely different package.


User can add field value

Question: Can anyone give me some advice/tips on how to get this working? I have a content type called "reviews", and in that i have two fields, called "pros" and "cons". Both fields have values defined in the Drupal admin interface.
In the front-end of the site, users can add new reviews and select values from the field list, until here no problem, everything work, but now i need to allow users (the registered users) to add new values to the fields (pros & cons).
Beside that, the values submitted by the users that don't exists yet in the database, must be approved by the admin before shows on the front-end.
Any suggestions for resolving this 2 questions?
Thanks in advance for your help.
Answer: I will try and provide you a general direction which I think might serve you well:

Create a text field, with label something like this "Please add tags of your choice if you dont find adequate options".(purpose is explanatory from the label)
Create a content type, "Proposed Taxonomy Terms". Let it have only title and body field.
Now on saving a node of the content type in which we had the suggestion field, grab the value of the proposed taxonomy terms from it, create a node of type "Proposed taxonomy term" and clear the value of the field in the first content type.
Now the nodes in the content type "Proposed taxonomy Term" will be your basis which you need to set up such moderation. it will initially remain unpublished. Upon validation, write custom code, to grab the title on its save and create a taxonomy term in the vocabulary(which was used as term referance field in the first content type), and delete the node (or you may choose to keep it).

So next time when user tries to create the node of the first content type, they will have it as an option. this is a complex workflow. The logic parts you can do custom code better, employing drupal hooks or you may choose to use rules module (not sure it will serve the purpose exactly though).
Hope this long answer did not confuse you.
Comment: cool!, @neo how about keeping freetagging field on content type which is allowing to add more options and open the same vocab to other content type as select list? yes code will require to remove terms on the unpublished nodes from the select list on other content type and delete the tagged term if not having reference to other nodes except the node being deleted.
Comment: @arpitr Reasons I suggested this approach over freetagging mechanism:

1. Freetagging mechanism will be difficult to be moderated. It is meant for users to add terms without any moderation.Here the requirement is admin needs to approve the term before it is published.

2. Node publish (workflow setup) is more easily achievable than term creation workflow (not that sure about thisthough).

Can you mould youur approach to include this cases and provide a solution? I think, freetagging approach will face the above mentioned shortcomings
Comment: true, this is the reason I added codes will be needed to remove terms which are on unpublished nodes.we are still having node publish workflow, while having a check to have select list of taxonomies on other content type referenced node of which are publsihed
Comment: @Neo thanks for your answer, i am a little confused with your answer, can you give me your gtalk or skype so i can discuss this better with you since i don't have access yet to chat? Meanwhile let's see, i have the content type "reviews", in this i add a new text field...Then i create a new content type "proposed terms" with title and body and set it to unpublished by default? A didn't understood the next part, saving the node and creating a new node.

Thanks a lot.
Comment: Hi @Neo, i followed your tips in conjunction with arpitr tips and i think i have a workaround. When the user submits the reviews form (in the front-end), two nodes are created, one with the review and other with proposed terms. When i approve the proposed terms, they are moved to taxonomy term. Until here, i think its working well. Now my "problem", i need to do this, when i approve the "proposed terms" content type, i need the term to appear also in the "review" content type, any idea on how to do this? Thanks a lot again for both.

User can add field value


a macro to choose the object instantiation based on the amount of the arguments

Question: I'm trying to create a macro to choose the object instantiation based on the amount of the arguments. Macro must support zero to two arguments.
The desired result is selecting one of the following three, and pass 0 to 2 arguments if any:
    MyClass obj(hardcoded_arg); // Choose this one if no arguments passed to a macro
    MyClass obj(hardcoded_arg,arg1); // This one if a single argument passed
    MyClass obj(arg1,arg2); // This one if two arguments passed

Here is how I'm trying to achieve that:
    #define TYPE1(...)       MyClass obj(hardcoded_arg);
    #define TYPE2(arg1)      MyClass obj(hardcoded_arg,arg1);
    #define TYPE3(arg1,arg2) MyClass obj(arg1,arg2);

    #define EXPAND( x ) x
    #define GET_TYPE(DUMMY, _1 ,_2, NAME, ...) NAME
    #define INSTANTIATE(...) EXPAND(GET_TYPE(DUMMY ,##__VA_ARGS__, TYPE3, TYPE2, TYPE1))(__VA_ARGS__)

    INSTANTIATE()
    INSTANTIATE(1)
    INSTANTIATE(1,2)

I've tried using using a definition like
    #define VA_ARGS(...) , ##__VA_ARGS__
    #define INSTANTIATE(...) EXPAND(GET_TYPE(DUMMY VA_ARGS(__VA_ARGS__), TYPE3, TYPE2, TYPE1))(__VA_ARGS__)

but it also didn't resolve the case.
The solutions like INSTANTIATE(,) are lame.
Any advice is appreciated!
Comment: I dont understand why you need a macro at all. Why not just three constructors taking 0,1 or 2 parameters, respectively?
Comment: Because the hardcoded_arg is a "this" pointer of a calling object
Comment: then why dont you explicitly pass the pointer? Wouldnt that make the code easier to understand?
Comment: Yes, that is what the current code looks like. The MyClass behavior also depends on whether the calling method is const or not, so I was just trying to shorten the syntax with a macro. So now I'm just curious if such macro is possible at all.
Answer: How about overloaded factory functions? Like
MyClass create() { return MyClass(hardecoded_arg); }
MyClass create(type2 arg2) { return MyClass(hardcoded_arg, arg2); }
MyClass create(type1 arg1, type2 arg2) { return MyClass(arg1, arg2); }

Type-safe, and no need to play tricks with the preprocessor.
Comment: @user3348108 And have you measured that copying (which will most likely be [elided](http://en.cppreference.com/w/cpp/language/copy_elision) anyway in this simple case) is so harmful to your program? How about movement then? And a general tip: Don't do premature optimizations. First of all make your program readable and maintainable. Then measure and benchmark and profile your program. When (and *if*) you find bottlenecks, then carefully tune them.
Comment: Thank you for the answer dude! I forgot to say that the code is critical to the execution time and the idea is to make the code super fast.
Comment: The MyClass instance is forbidden to be copied
Comment: MyClass is an advanced thread-safety arbiter for a virtual file system (and that is why it can't be copied), so it is being instantiated really a lot. And that is why I am trying to place them on stack. Maybe the autopointers will make the stuff convenient then. Could you please explain your vision on moving here?
Comment: The reason I started with a macro is that it expands to different types on different build environment. So it's a legacy choice and I still hope to fix the macro.
Comment: A move constructor cannot be added because on some environments MyClass would be a library class which cannot be modified.
Comment: Anyway overloaded factory function is not an option because I still have to pass the "hardcoded" arguments - the "this" pointer and its cv-qualifier. The solution is supposed to fill them in automatically if omitted. The initial question is how to fix the macro, so your answer is unrelated.
Comment: @user3348108 Your question, as it is, is an example of [the XY problem](http://xyproblem.info/). You have a solution you want us to help you with, but we don't actually know the problem the solution is attempting to solve. There may be other ways of solving the problem, but we can't really tell since the question doesn't tell us the *actual* problem.
Comment: The question is very clear: how to make the macro expand in the expected way.
Comment: @user3348108, why do you keep getting distracted by false claims about speed and about the stack? You say *"And that is why I am trying to place them on stack"*, however a good compiler will directly construct your item in place, without any moving and without any copying
Answer: If constructors of MyClass are not explicit nor conflicting with an initializer_list constructor, you may use the following which doesn't call move/copy constructor:
MyClass make_MyClass() { return {hardcoded_arg}; }

template <typename T>
MyClass make_MyClass(T&& arg) { return {hardcoded_arg, std::forward<T>(arg)}; }

template <typename T1, typename T2>
MyClass make_MyClass(T1&& arg1, T2&& arg2)
{
    return {std::forward<T1>(arg1), std::forward<T2>(arg2)};
}

Demo
Comment: Thank you for the answer but it is unrelated to my question. I'm asking how to fix the macro. If the situation would be that trivial I would not as for help. Your solution can't handle the default argument values which are the 'this' pointer and boolean representing its cv-qualifier.
Comment: Which `this` pointer do you talk about ? I saw nothing related to that in your Question (to allow to update my answer accordantly if possible).


How can I prove transitivity of < in Peano Arithmetic

Question: I wish to prove
$$(\forall x)(\forall y)(\forall z)((x < y \land y < z) \rightarrow x < z)$$
only using the rules of Peano Arithmetic (PA) including the induction rule. I have seen other resources here:
Induction proof of transitivity
Prove by induction that P is transitive
but they do not answer my question and I am stuck on performing the induction given several free variables.
Comment: The first important question is: how have you defined $<$? Equally important, what kind of axioms are you using for Peano Arithmetic?
Comment: I am using the Robinson's Axioms as described here: http://web.mit.edu/24.242/www/Robinson'sArithmetic.pdf where Q11 defines <. Sorry - this should be been more specific
Comment: The system of Robinson's Axioms (Q) is not the same as Peano Arithmetic (PA). Most notably, Q does not include induction which makes it a lot weaker .... indeed, note that the reference you provided states how you can't even prove basic commutativity, associativity, or distribution laws in Q ...  and I don't see how you can prove transitivity in Q either. So ... are you using Q or are you using PA?
Answer: We start proving by Induction in the meta-theory:

$\forall z \ [(\text m < \text n ∧ \text n < z) → (\text m < z)]$.

Basis : $z=0$.
We assume $(\text m < \text n ∧ \text n < 0)$; from it : $(\text n < 0)$.
From (Ax.Q9) we get : $\lnot (\text n < 0)$. Using tautology : $\lnot p \to (p \to q)$ we conclude with :

$(\text m < 0)$.

Induction step : let assume $(\text m < \text n ∧ \text n < z) → (\text m < z)$.
Assume : $(\text m < \text n ∧ \text n < s(z))$. From it we get : $(\text n < s(z))$.
Using (Ax.Q10) we get : $(\text n < z) \lor (\text n = z)$.
Two cases : (a) $(\text n < z)$.
With $(\text m < \text n)$ and Induction Hyp we get : $(\text m < z)$.
(b) $(\text n = z)$. Again, using $(\text m < \text n)$ and axioms for equality we get : $(\text m < z)$.
From $(\text m < z)$ we get $(\text m < z) \lor (\text m = z)$.
Using (Ax.Q10) we get : $(\text m < s(z))$.
Thus, we conclude with :

$(\text m < \text n ∧ \text n < s(z)) \to (\text m < s(z))$.

In this way, we have proved by Induction :

$\forall z \ [(\text m < \text n ∧ \text n < z) \to (\text m < z)]$.

By Generalization, we have :

$\forall x \ \forall y \ \forall z \ [(x < y ∧ y < z) \to (x < z)]$.


how to open the last opened files in ISE at the starting

Question: i wanted to automatically open the last opend files in ISE with posh script,
so i tryed to save filepaths of these files like the following.
<code>
$action = {
$psISE.CurrentPowerShellTab.Files | select -ExpandProperty FullPath | ? { Test-Path $_ } |
Set-Content -Encoding String -Path$PSHOME\psISElastOpenedFiles.txt
Set-Content -Encoding String -Value "Now exiting..." -Path c:\exitingtest.log
}
Register-EngineEvent -SourceIdentifier Exit -SupportEvent -Action $action

</code>
when i close ISE, exitingtest.log is created and has "Now exiting...",
 but psISElastOpenedFiles.txt isn't created.
it seems that ISE closes all opening files before the exiting event is executed.
should i use Timer event?
Answer: Rather than saving on exit, save the MRU info when the CurrentTabs and Files objects raise the CollectionChanged event. This is the MRU ISE addon I'm using:
<code># Add to profile
if (test-path $env:TMP\ise_mru.txt)
{
    $global:recentFiles = gc $env:TMP\ise_mru.txt | ?{$_}
}

else
{
    $global:recentFiles = @()
}

function Update-MRU($newfile)
{
    $global:recentFiles = @($newfile) + ($global:recentFiles -ne $newfile) | Select-Object -First 10

    $psISE.PowerShellTabs | %{
        $pstab = $_
        @($pstab.AddOnsMenu.Submenus) | ?{$_.DisplayName -eq 'MRU'} | %{$pstab.AddOnsMenu.Submenus.Remove($_)}
        $menu = $pstab.AddOnsMenu.Submenus.Add("MRU", $null, $null)
        $global:recentFiles | ?{$_} | %{
            $null = $menu.Submenus.Add($_, [ScriptBlock]::Create("psEdit '$_'"), $null)
        }
    }
    $global:recentFiles | Out-File $env:TMP\ise_mru.txt
}

$null = Register-ObjectEvent -InputObject $psISE.PowerShellTabs -EventName CollectionChanged -Action {
    if ($eventArgs.Action -ne 'Add')
    {
        return
    }

    Register-ObjectEvent -InputObject $eventArgs.NewItems[0].Files -EventName CollectionChanged -Action {
        if ($eventArgs.Action -ne 'Add')
        {
            return
        }
        Update-MRU ($eventArgs.NewItems | ?{-not $_.IsUntitled}| %{$_.FullPath})
    }
}

$null = Register-ObjectEvent -InputObject $psISE.CurrentPowerShellTab.Files -EventName CollectionChanged -Action {
    if ($eventArgs.Action -ne 'Add')
    {
        return
    }
    Update-MRU ($eventArgs.NewItems | ?{-not $_.IsUntitled}| %{$_.FullPath})

}

Update-MRU
</code>
Answer: I tried to do this a few months ago and discovered that a race-condition prevents this from working 95% of the time. The tab collection in ISE's object model is generally disposed of before the powershell.exiting event is handled. Dumb, yes. Fixable, no.
-Oisin


Parâmetros nulos no controller ao enviar post via ajax

Question: Estou refatorando uma aplicação ASP.NET MVC escrita por outro desenvolvedor. Minha intenção é remover o uso de FormCollection.
Antes a assinatura do método do controller era a seguinte:
public ActionResult Salvar(FormCollection ParametroformCollection, FormCollection ParametroFormHidden, string ParametroView, string ParametroStrDirecao)

O envio dos formulários era feito via ajax, utilizando serializeArray()
Então criei dois models, um para cada formulário, porém no controller os objetos não são preenchidos, ficando nulos. Tentei serializar com serializeArray() e com serialize(). Não sei porque não está dando certo.
HTML dos Formulários
<form id="hiddenForms" method="POST">
    <input type="hidden" id="idhiddenFormPlaca" name="namehiddenFormPlaca" value="" />
    <input type="hidden" id="idhiddenFormFabricante" name="namehiddenFormFabricante" value="" />
    <input type="hidden" id="idhiddenFormAnoModelo" name="namehiddenFormAnoModelo" value="" />
    <input type="hidden" id="idhiddenFormOficina" name="namehiddenFormOficina" value="" />
    <input type="hidden" id="idhiddenFormCarrinho" name="namehiddenFormCarrinho" value="" />
    <input type="hidden" id="idhiddenFormAlteracao" name="namehiddenFormAlteracao" value="" />
</form>

<form id="containerForm" method="POST">
    <input type="text" id="idPlaca" name="namePlaca" value="@Model.strPlacaVeiculo" />

        <input type="radio" id="idRbCarros" name="optradio" value="Carros e Utilitários Pequenos">Carros

        <input type="radio" id="idRbMotos" name="optradio" value="Motos">Motos

        <input type="radio" id="idRbCaminhoes" name="optradio" value="Caminhões e Micro-Ônibus">Caminhões

</form>

Javascript do envio
function enviar() {
     var form = $("#containerForm").serialize();
     var formhidden = $("#hiddenForms").serialize();
     $.ajax({
                type: "POST",
                url: '@Url.Action("Salvar", "Home")',
                data: { ParametroformCollection: form, ParametroFormHidden: formhidden, ParametroView: "Placa", ParametroStrDirecao: ParametroDirecao },
                success: function (result) {

                }
     });
}

Controller
    [HttpPost]
    public ActionResult Salvar(PlacaForm ParametroformCollection, FormHidden ParametroFormHidden, string ParametroView, string ParametroStrDirecao)
    {
      ....
    }

Model
public class FormHidden
{
    public string namehiddenFormPlaca { get; set; }
    public string namehiddenFormFabricante { get; set; }
    public string namehiddenFormAnoModelo { get; set; }
    public string namehiddenFormOficina { get; set; }
    public string namehiddenFormCarrinho { get; set; }
    public string namehiddenFormAlteracao { get; set; }
}

public class PlacaForm
{
    public string namePlaca { get; set; }
}

Answer: Os form para funcionarem ficaram assim:
Observação: colocado nos campos do formulário, os seus valores.
<form id="hiddenForms" method="POST">
    <input type="hidden" id="idhiddenFormPlaca" name="namehiddenFormPlaca" value="0" />
    <input type="hidden" id="idhiddenFormFabricante" name="namehiddenFormFabricante" value="1" />
    <input type="hidden" id="idhiddenFormAnoModelo" name="namehiddenFormAnoModelo" value="2" />
    <input type="hidden" id="idhiddenFormOficina" name="namehiddenFormOficina" value="3" />
    <input type="hidden" id="idhiddenFormCarrinho" name="namehiddenFormCarrinho" value="4" />
    <input type="hidden" id="idhiddenFormAlteracao" name="namehiddenFormAlteracao" value="5" />
</form>

<form id="containerForm" method="POST">
    <input type="text" id="namePlaca" name="namePlaca" value="100" />

        <input type="radio" id="idRbCarros" name="optradio" value="Carros e Utilitários Pequenos">Carros

        <input type="radio" id="idRbMotos" name="optradio" value="Motos">Motos

        <input type="radio" id="idRbCaminhoes" name="optradio" value="Caminhões e Micro-Ônibus">Caminhões

    <button type="button" onclick="enviarData()">Enviar</button>
</form>

No código Javascript, deve enviar um item serializado com todas as informações, então, foi feita a junção dos dois form:
function enviarData() {

    var data = $("#hiddenForms").serialize();
    data = data + "&" + $("#containerForm").serialize();

    //console.log(data);

    $.ajax({
        type: "POST",
        url: '@Url.Action("Salvar", "Home")',
        data: data,
        success: function (data) {
            console.log(data);
        },
        "error": function (result) {
            var response = result.responseText;
            alert('Erro: ' + response);
        }
    });
}

No botão de envio, no evento onClick eu passei o nome da função enviarData();, e por fim no controller:
[HttpPost()]
public ActionResult Salvar(FormHidden formHidden, PlacaForm placaForm)
{
   //code ...
}

Comment: Deu certo não. Ainda os models ficaram nulos.
Comment: @Murilo dá uma olhada no seu Javascript e compare! o código acima é testado. olha na parte `$.ajax`!


Arduino, python, pyserial and socket

Question: I am trying to write a simple webserver on an Arduino to test a few things, but I couldn't find my Arduino with Ethernet on it.
"No worries" I thought, "I'll just write a socket server in python that acts as a proxy for the serial connection".
<code>import socket
import serial
host = ''
port = 8001
buffSize= 1024
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverSocket.bind((host, port))
serverSocket.listen(1)
ser = serial.Serial('COM3', 115200, timeout=None, dsrdtr =False,rtscts =False,xonxoff =False)
print "Listening..."
send = ""
while 1:
    conn, remoteAddr = serverSocket.accept()
    print "Connection...."
    data = conn.recv(buffSize)
    print "Recieved"
    ser.write("%s\n"%data)
    print "Sent"
    print "Attempting to get reply"
    while ser.inWaiting()>0:
            conn.send( ser.read())
    conn.close()
serverSocket.close()
</code>
However, whatever I try, it seems that the connection made by the browser resets randomly and I'd get multiple rows of data. And the script resets the Arduino each time it connects or disconnects from the serial port. I tried using RealTerm and I got a proper answer, but python and serialness is just a mess.
Can anyone help me?
Comment: The best design would be to put the whole thing into a single event loop, or reactor.
Answer: Use the tcp_serial_redirect.py script in the PySerial documentation. Is all you need.
Comment: Why was this downvoted?  I am looking into the serial redirect at this moment.  I'm still a noob, will probably update this comment later.

Arduino, python, pyserial and socket


Please help me refine this zero-inflated negative binomial model

Question: I have been working on a baseball model to predict success at the major league level using minor league statistics. After posting multiple threads on this site (1, 2, 3) and receiving valuable feedback, I have settled on a zero-inflated negative binomial model as being the best fit for my data.
For those who do not want to go back through old threads,  I will recap some of the story here. Also, for those who have read the old threads, some of the details regarding the variables I am using have changed.
In my model, the dependent variable, offensive career wins above replacement (oWAR), is a proxy for success at the MLB level and is measured as the sum of offensive contributions for every play the player is involved in over the course of his career (details here - http://www.fangraphs.com/library/misc/war/). The independent variables are z-scored minor league offensive variables for statistics that are thought to be important predictors of success at the major league level including age (players with more success at a younger age tend to be better prospects), strike out rate [SOPct], walk rate [BBPct] and adjusted production (a global measure of offensive production). Additionally, since position is an important determinant of whether a players makes the major leagues (those who play at easier positions will be required to perform at a higher offensive level in order to have the same value as a player at a more difficult position), I have included dummy variables to account for position. Note that I have not included the position dummy in the count portion of the model as the oWAR dependent variable has already been adjusted for the difficulty level of the position played by the player.
EDIT: I have added the paragraphs below in response to the following comments in the answer below:
"I see you do not include the same covariates in the Logit and the negative binomial process - why not? Ususally, each relevant predictor would be expected to influence both processes."
I think it would help if I explained the data generating process. A player plays in the minor leagues. At some point, when they have demonstrated enough skill at the minor league level (this is a combination of statistical success and observed traits that scouts believe will allow them to be successful at the major league level), a player is promoted to the major leagues. At this point, they have an opportunity to accrue oWAR. At this point, the first data-generating process  (captured by the logit model) ends. Now, a different data generating process takes over, whereby players accumulate oWAR depending on how they play at the major league level. Some players will not perform well and accumulate zero oWAR, the same as a player who did not make the majors. That is one of the reasons I think this model is appropriate. It is not necessarily easy to separate a player who accumulates zero because they aren't good enough to make the major leagues from a player who makes the major leagues but does not succeed at that level (and still ends his career with zero oWAR). I have not included the positional dummy in the count part of the model because the oWAR measure is already adjusted for the position played by the player whereas the minor league statistics are not. When I tried testing them in the model, they were, not surprisingly, not significant. I omitted the BB Pct statistic from the logit part of the model as it was not significant (p = 0.22)
"Since your data appears to be a panel (you observe players/teams repeatedly), you can think about more sophisticated stuff like fixed or random effects. "
In terms of how the data is sampled, a player can be in the dataset once (if they spend only a year at the level of the minor leagues) or multiple times if they take multiple years to advance. After reading up on fixed vs random effects model, I don't see how I can used a fixed model to predict out of sample players. However, I am sure that there are fixed effects (effects determined by the player that are not captured in the dependent variables) so I don't fully understand how to handle that issue.
END EDIT
After trying a linear, Box-Cox transformed and basic GLM model with generally poor results, I was directed to the zero-inflated negative binomial distribution set of models. After trying out different combination of variables and following the steps in this excellent step-by-step guide for regression models for count data in R, I settled on the following model (shown below).
Model

Furthermore, when I re-estimate the standard errors using sandwich standard errors, the model still appears to have appropriate independent variables.
Sandwich Standard Errors

At this point, I do not think I will find a better model type given the dataset I have. However, I am still left with some issues. The first issue may be a function of the dataset I am using. In most examples I have seen that discuss zero-inflated data, there are clearly more zeros than other values (hence, the name). However, the number of zeros still appears to be less than 50% of the total dependent variables and usually not even that high. In my dataset, approximately 87% of the dependent variables are zero i.e., it is hard to have success in major league baseball. I am guessing the model should technically be able to account for this scenario (albeit with less predictive value than a model with more non-zeros) but I am not sure how to check if that is the case. When I create a plot of fitted values and Pearson residuals, and a plot of fitted values and raw residuals, they appear as below:
Fitted vs Pearson residuals

Fitted vs raw residuals

Not knowing exactly what these plots look like in a good-fitting regression, I decided to take the sample data described here and examine the plots in an example where I know the fit has been deemed to be good.
Fitted vs Pearson residuals - Sample problem

Fitted vs raw residuals - Sample problem

Clearly, these plots do not look that similar to mine. I am not sure how much has to do with a) model misspecification b) the fact that my dependent variable has 87% zeros and c) the fact that this is a simple sample problem designed to perfectly fit this model whereas my data is messy, real world data. Any thoughts on this issue would be appreciated.
My second issue, which I am not sure if I should be tackling after or simultaneously with the first issue, has to do with the functional form specification. I don't know if my independent variables are in the right form. It has been suggested to me by a friend that I could try a) multiple fractional polynomials with loops or b) informally play around with adding polynomials of covariates, interactions, etc. My issue at this point is that I do not know how to implement point a in R and and I am not sure which forms to try for point b besides randomly choosing some. Once again, help on this separate (but related?) issue would be greatly appreciated.
If anyone has any questions, I will do my best to answer them. In my first post (1), I mentioned I could not provide the dataset but I have been given permission to do so if anyone wants to take a look.
Answer: The zero inflated model is designed to deal with overdispersed data - 87% zeros is usually considered overdispersed, but you can check if mean < variance after fitting a Poisson. A good way to see if you have dealt with overdispersion is to simply predict the share of $0,1,2,\ldots$ in your sample with your model. If you have overdispersed data, and only use negative binomial regression or Poisson, you will see that the predicted share in the sample and the actual share in the sample deviate a lot. This would be a sign that overdispersion is not dealt with adequately. But my guess is you're good - the additional logit process makes the model quite flexible.
You can think about including interaction terms as predictors (as you mentioned); some may make sense and improve your predictions, others might not. To decide which to include, you either have some prior knowledge that some interaction makes a difference (maybe age has a different influence depending on the position?). Or you choose you model by dividing your entire sample in half, use the first half to fit the model, predict the second half using the estimates, and compare predicted and actual outcomes. You should quickly see which models give better predictions. This method also helps you avoid overfitting (i.e., fitting your existing data so closely that even random noise is incorporated, which can hurt predictive power). In order not to fit too closely to your training data set, the "training" half and the "prediction" half should be selected randomly.
I see you do not include the same covariates in the Logit and the negative binomial process - why not? Ususally, each relevant predictor would be expected to influence both processes. EDIT: ok, just one thing. If your goal is prediction, you should probably not just look at significance, but also at the size of the coefficient. A large insignificant coefficient can change your predictions considerably (and thus you might want to keep it nonetheless), even though you would drop it if the goal were merely to explain the data.
Since your data appears to be a panel (you observe players/teams repeatedly), you can think about more sophisticated stuff like fixed or random effects. Fixed effects do not allow out of sample predictions (you can't predict outcomes for a player you don't have in your sample), but should predict very well within sample. Not sure if this even exists yet for the zero inflated negative binomial; here is a recent application of a fixed effects ZI-Poisson. I am no specialist on random effects. But both can improve predictions if your predictors don't predict very well, and much of the action is going on in the unobservables. EDIT: if you observe some players only once, and want to make out of sample predictions, then fixed effects is not a good idea.
Comment: I edited the question to address your comments.
Comment: Added two responses to your edits.
Comment: Thank you for the clarification. I will look into your point regarding keeping the coefficient.
Comment: The link on the application of fixed effects zero-inflated poisson is no longer active. Can you dig it up? I'm interested.
Comment: I think this was the paper: https://papers.ssrn.com/sol3/papers.cfm?abstract_id=1899582


Smallest digit sum for a specific number

Question: The task of mine is:
What is the smallest (non-iterated) digit sum of a positive and natural number that is divisible by $37$?
I have already done 80% of the task, I have proven that $1$ can't possibly be true. I also have proven that the digit sum $2$, that can be displayed as $2\times10^n$ such as $2;20;200$ etc., is impossible for a natural and positive number that is divisible by $37$. But the digit sum $2$ can be also made by two ones, like in $11$, $101$ or $100100$.
So my question is:
How can I prove, that $2$ is not a (non-iterated) digit sum of a positive and natural number that is divisible by $37$?
Comment: Please do not deface your question after you get an answer. That makes the answers impossible to understand and the entire post unhelpful for future users.
Comment: Powers of $10$ are either $1,10$ or $26$ $\pmod {37}$.  That tells us that two powers of $10$ can not add to a multiple of $37$.
Answer: Any number whose sum of digits adds up to $2$, and does not contain $2$ as a digit, must be of the form $10^x + 10^y$, where $x,y\in\mathbb Z^+$. This will be divisible by $37$ iff $$(10^x + 10^y)\equiv0 \pmod{37}\tag1$$
Observe that $10^3\equiv 1\pmod {37}$
As a result, for any $x\in\mathbb Z^+$, $$10^x\equiv10^{x\pmod3}\pmod{37}$$
Now, $x\pmod 3$ can only take values of $0,1,2$. We have that
$$10^0\equiv 1\pmod{37}$$
$$10^1\equiv 10\pmod{37}$$
$$10^2\equiv 26\pmod{37}$$
For there to exist $x,y$ to satisfy $(1)$, we need that their values $\pmod{37}$ add up to a value divisible by $37$. Clearly, using any pair out of $\{1,10,26\}$ does not give a sum divisible by $37$, so this is not possible.
However, observe that using three such powers works - we have $1+10+26=37\equiv 0\pmod{37}$. Thus, there exists a number with digit sum $3$, with three digits of value $1$, that is divisible by $37$. One can see that $111$ satisfies this.
Comment: @calculatormathematical Please stop suggesting edits to delete the answer.


Zooming and UIWebView

Question: I am having a problem with UIWebView. My application displays pdfs from local memory and displays them in a webView in fullscreen mode. By default, when the page loads, the content is apparently set to fit horizontally, which cuts off some of the bottom of the pdf. I would like it to initially show up vertically fit and horizontally centered. I have looked for an answer to this question for quit some time and can't seem to find anything.
Any ideas?
(Please do not suggest scalesPageToFit. Although it fixes many beginning problems, this is not one of them.)
Comment: I should clarify that this is really two questions: 1) How can I set the correct initial zoomFactor? and 2) how can I center the webView?
Comment: Is the pdf one page or multiple pages?
Comment: The way I am doing it now is a series of 1 page pdf files.
Answer: uiWebView.scrollView property has the ability to set zoom and also manage display of content
UIScollView class ref
Comment: Thanks. I set the content size and things worked out fairly well.

Zooming and UIWebView


Webform redirect to login before submit

Question: I am creating a webform for my users to submit it but i have one question.
How to redirect users to login before they submit a webform?
Comment: instead of [You must login to view this form.] need to be a redirection to the login page.
Answer: Take a look at the Login Redirect module. It should do what you are describing.
Answer: You need to use a custom implementation of hook_node_access so your users can see the node and then probably hook_form_alter to hide the form if not user_is_logged_in()

Webform redirect to login before submit


Issue with Responsive Design and .click() event listeners

Question: So what I have is a full HTML / CSS site that I did not design, I've just inherited it. The issue that I'm facing at the moment is that on one page in particular, when viewed on a phone / tablet, almost becomes too sensitive. What I mean by that is that it actually becomes very difficult to scroll around on the page due to the fact that there are many little "tiles" that are all wired to up for .click() listeners, which are being triggered by scrolling on the phones / tablets.
I am really looking for best practices or any ideas anyone might have as how to best handle this. After scouring google, I have been unsuccesful in finding anything of value to me.
A few ideas I had, but have yet to implement are to

Add a delay so that a person must actually tap and hold for a second or two before running the code in the click() event listener
With media queries, drastically reduce the size of the element that the click() listener is bound to

Anyways, here is a sample of the HTML and a screenshot of what the final product looks like when output to a browser
HTML -- There are many of these little  blocks in succession that stack with the responsive css

Shop and earn with

Macys

Screenshot
Answer: Start here: Understanding touch events to try migrating the on click events to on touch events to prevent this from happening.
Comment: The link you posted lead me to, http://gianlucaguarini.github.io/Tocca.js/ , which resolved my issue by using `.tap()` instead of `.click()` . Thank you!!


Is the following statement correct or incorrect?

Question: Is the following statement is true or False ?
let G be a finite group with a normal subgroup H such that $\frac{G}{H}$ has order $7$. then $G\cong H \times \frac {G}{H}$
im thinking that the statement will be true because if i take $G= Z_{14}$ and$ H= Z_7$ now $ Z_{14} =Z_7 \times Z_2$
which is satisfied the above statement . so from my point of view  this statment is true ..
Is its corrects ?...........
Answer: Hint: When is $\Bbb Z_{mn}$ not isomorphic to $\Bbb Z_m\times \Bbb Z_n$?
Comment: when gcd(m,n)$ \neq1$ but here  question is about normal subroup ...
Comment: @Stupid When the group is abelian, all subgroups are normal. Also, $\Bbb Z_m$ is (isomorphic to) a subgroup of $\Bbb Z_{mn}$, namely $\langle n\rangle$.
Comment: thanks arthur sir


Integrate $\int \frac{x^{4n-2}}{x^{4n}+x^{2n}+1} \, \mathrm dx$

Question: I want to evaluate the following indefinite integral with IBP and also with the limits $0$ to $\infty$. Once indefinite integral is calculated, it is easy to evaluate it within given limits.

$$I=\int \frac{x^{4n-2}}{x^{4n}+x^{2n}+1} \, \mathrm dx$$

So, I proceed through Partial fractions method.
$$I=\int \frac{x^{4n-2}}{x^{4n}+x^{2n}+1} \, \mathrm dx=\frac12
 \int \frac{x^{2n-2}+x^{n-2}}{x^{2n}+x^n+1} \, \mathrm dx+\frac12
\int \frac{x^{2n-2}-x^{n-2}}{x^{2n}-x^n+1} \, \mathrm dx$$
We can split it into $4$ integrals but I think that would make it a little messy.
Let $\space I=I_{1}+I_{2}$
$$I_1= \int \frac{1}{2x}\bigg(\frac{2x^{2n-1}+x^{n-1}-x^{2n-1}}{x^{2n}+x^{n}+1}\bigg)\mathrm dx$$
$$\implies I_1=\int \frac{1}{2nx}\bigg(\frac{2nx^{2n-1}+nx^{n-1}}{x^{2n}+x^n+1}-\frac{nx^{2n-1}}{x^{2n}+x^n+1}\bigg) \, \mathrm dx$$
After IBP, we get
$$I_1=\frac {1}{2n}\Bigg[\frac{1}{x}\ln(x^{2n}+x^n+1)+\int \frac {1}{x^2} \ln(x^{2n}+x^n+1) \, \mathrm dx\Bigg]-\frac12 \int \frac{x^{2n-2}}{x^{2n}+x^{n}+1} \, \mathrm dx$$
Let $x=\frac{1}{x}$ for above two integrals and we get
$$I_1 = \frac {1}{2nx} \ln(x^{2n}+x^n+1)+x\ln(x)-x-\frac{1}{2n}\int \ln(x^{2n} + x^{n}+1)\,\mathrm dx +\frac12 \int \frac{1}{x^{2n}+x^n+1} \, \mathrm dx$$
Same thing goes with $I_2$ and we are stuck with the
following integrals
$$\int \ln(x^{2n}\pm x^{n}+1)\,\mathrm dx \space and \int \frac{1}{x^{2n}\pm x^n+1} \, \mathrm dx$$

I don't think so that their anti-derivative can be expressed in terms of elementary functions. But I'm also interested in definite integrals of those functions i.e
$$\int_0^\infty \ln(x^{2n}+x^{n}+1)\mathrm dx \text{ and } \int_0^\infty \frac{1}{x^{2n}+x^n+1}\,\mathrm dx$$
Comment: This $\int_{0}^{\infty} \ln\left(x^{2n} + x^{n} +1\right) ~ dx$ diverges.
Comment: @Andrei I haven't tried that
Comment: Not sure if it will work, but have you tried to solve the original integral using residue theorem?
Answer: It is actually easier to evaluate the definite integral directly. For $m>1$
\begin{align}
I(m)=& \int_0^\infty \frac{1}{x^{2m}+x^m+1}dx\\
=& \>\frac1{2i\sin a }\int_0^\infty
\overset{t=xe^{i\frac am}}{\frac{e^{i a}}{x^m e^{i a}+1}} -\overset{t=xe^{-i\frac am}}{\frac{e^{-i a}}{x^m e^{-i a}+1} }\>dx\>\>\>\>\>\> (a=\frac\pi3 )\\
=& \>\frac{\sin\frac{(m-1)\pi}{3m}}{\sin\frac\pi3}\int_0^\infty \frac1{t^m+1}dt = \frac{2\pi\sin\frac{(m-1)\pi}{3m}}{\sqrt3 m \sin\frac\pi m}
\end{align}
where $\int_0^\infty \frac{dt}{t^m+1}= \frac\pi{m\sin\frac\pi m}$. Then
\begin{align}
\int_0^\infty \frac{x^{4n-2}}{x^{4n}+x^{2n}+1} dx
\overset{x\to\frac1x}
=\> \int_0^\infty \frac{1}{x^{4n}+x^{2n}+1} dx= I(2n)=\frac{\pi \cos\frac{(n+1)\pi}{6n} }{\sqrt3 n \sin\frac\pi {2n}}
\end{align}


How can I configure Terraform to update a GCP compute engine instance template without destroying and re-creating?

Question: I have a service deployed on GCP compute engine.  It consists of a compute engine instance template, instance group, instance group manager, and load balancer + associated forwarding rules etc.
We're forced into using compute engine rather than Cloud Run or some other serverless offering due to the need for docker-in-docker for the service in question.
The deployment is managed by terraform.  I have a config that looks something like this:
data "google_compute_image" "debian_image" {
  family  = "debian-11"
  project = "debian-cloud"
}

resource "google_compute_instance_template" "my_service_template" {
  name         = "my_service"
  machine_type = "n1-standard-1"

  disk {
    source_image = data.google_compute_image.debian_image.self_link
    auto_delete  = true
    boot         = true
  }
  ...
  metadata_startup_script = data.local_file.startup_script.content
  metadata = {
    MY_ENV_VAR = var.whatever
  }
}

resource "google_compute_region_instance_group_manager" "my_service_mig" {
  version {
    instance_template = google_compute_instance_template.my_service_template.id
    name              = "primary"
  }

  ...
}

resource "google_compute_region_backend_service" "my_service_backend" {
  ...

  backend {
    group = google_compute_region_instance_group_manager.my_service_mig.instance_group
  }
}

resource "google_compute_forwarding_rule" "my_service_frontend" {
  depends_on = [
    google_compute_region_instance_group_manager.my_service_mig,
  ]
  name = "my_service_ilb"

  backend_service       = google_compute_region_backend_service.my_service_backend.id

  ...
}

I'm running into issues where Terraform is unable to perform any kind of update to this service without running into conflicts.  It seems that instance templates are immutable in GCP, and doing anything like updating the startup script, adding an env var, or similar forces it to be deleted and re-created.
Terraform prints info like this in that situation:
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  ~ update in-place
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # module.connectors_compute_engine.google_compute_instance_template.airbyte_translation_instance1 must be replaced
-/+ resource "google_compute_instance_template" "my_service_template" {
      ~ id                      = "projects/project/..." -> (known after apply)
      ~ metadata                = { # forces replacement
          + "TEST"                             = "test"
            # (1 unchanged element hidden)
        }

The only solution I've found for getting out of this situation is to entirely delete the entire service and all associated entities from the load balancer down to the instance template and re-create them.
Is there some way to avoid this situation so that I'm able to change the instance template without having to manually update all the terraform config two times?  At this point I'm even fine if it ends up creating some downtime for the service in question rather than a full rolling update or something since that's what's happening now anyway.
Answer: I was triggered by this issue as well.
However, according to:
https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_instance_template#using-with-instance-group-manager

Instance Templates cannot be updated after creation with the Google
Cloud Platform API. In order to update an Instance Template, Terraform
will destroy the existing resource and create a replacement. In order
to effectively use an Instance Template resource with an Instance
Group Manager resource, it's recommended to specify
create_before_destroy in a lifecycle block. Either omit the Instance
Template name attribute, or specify a partial name with name_prefix.

I would also test and plan with this lifecycle meta argument as well:
+ lifecycle {
+   prevent_destroy = true
+ }
}

Or more realistically in your specific case, something like:
    resource "google_compute_instance_template" "my_service_template" {
      version {
        instance_template = google_compute_instance_template.my_service_template.id
        name              = "primary"
      }

+ lifecycle {
+   create_before_destroy = true
+ }
}

So terraform plan with either create_before_destroy or prevent_destroy = true before terraform apply on google_compute_instance_template to see results.
Ultimately, you can remove google_compute_instance_template.my_service_template.id from state file and import it back.
Some suggested workarounds in this thread:
terraform lifecycle prevent destroy
Comment: @Ameo: makes indeed sense! thanks for pointing it out. I adapted as suggested.
Comment: Hey, thanks very much for this answer!  This looks like it might just work... I'll try it out tomorrow and see how it goes
Comment: You're welcome. hope it worked out. Good luck!
Comment: @Ameo could you try out?
Comment: Hi yeah I forgot to post back.  Adding the lifecycle argument did fix the issue.  However, I set it to `create_before_destroy = true` rather than `prevent_destroy = true`.  I had to add it to the `google_compute_instance_template` rater than the `google_compute_region_instance_group_manager` which makes sense.

If you could update your answer with those details I will mark it as accepted. Tyvm again for your help!
Comment: Awesome, tyvm again for the help in getting this fixed - it's already had a big impact in making our deploys way easier to manage


Does the HERE API provide triangulation of GSM cell info?

Question: Currently testing out the HERE API for use in a GSM positioning application. It appears that no cell triangulation occurs but then why is it possible to pass several GSM data points into the API?
I have tried passing up to 7 GSM cell positions but the estimated location always ends up on one of the cells and not close to the actual position of the device.
<code>###############################################################################
# cell tower info for HERE API
###############################################################################
here_cell_0 = {"cid": 17078,
          "lac": 314,
          "mcc": 234,
          "mnc": 15,
          "rxlevel": -52,
          "nmr": [{"bsic": 18, "bcch": 25, "rxlevel": -52}]}

here_cell_1 = {"cid": 13491,
          "lac": 165,
          "mcc": 234,
          "mnc": 15,
          "rxlevel": -61,
          "nmr": [{"bsic": 27, "bcch": 33, "rxlevel": -61}]}

here_cell_2 = {"cid": 16191,
          "lac": 316,
          "mcc": 234,
          "mnc": 15,
          "rxlevel": -62,
          "nmr": [{"bsic": 38, "bcch": 26, "rxlevel": -62}]}

here_cell_3 = {"cid": 13492,
          "lac": 165,
          "mcc": 234,
          "mnc": 15,
          "rxlevel": -65,
          "nmr": [{"bsic": 8, "bcch": 30, "rxlevel": -65}]}

here_cell_4 = {"cid": 18119,
          "lac": 316,
          "mcc": 234,
          "mnc": 15,
          "rxlevel": -65,
          "nmr": [{"bsic": 35, "bcch": 36, "rxlevel": -65}]}

here_cell_5 = {"cid": 13564,

          "lac": 165,
          "mcc": 234,
          "mnc": 15,
          "rxlevel": -66,
          "nmr": [{"bsic": 37, "bcch": 29, "rxlevel": -66}]}

here_cell_6 = {"cid": 17079,
          "lac": 314,
          "mcc": 234,
          "mnc": 15,
          "rxlevel": -69,
          "nmr": [{"bsic": 41, "bcch": 37, "rxlevel": -69}]}

ALL_CELLS_HERE = [here_cell_0,here_cell_1,here_cell_2,here_cell_3,here_cell_4,here_cell_5,here_cell_6]

###############################################################################
# HERE API data
###############################################################################
# API KEY
APP_ID = ""
APP_CODE = ""
APP_ID_RESOURCE = "app_id=" + APP_ID
APP_CODE_RESOURCE = "app_code=" + APP_CODE

# position API
POS_BASE_URL = "https://pos.api.here.com/positioning/v1/locate"
POS_URL = POS_BASE_URL + "?" + APP_ID_RESOURCE + "&" + APP_CODE_RESOURCE

###############################################################################
# get positions of cells and estimated position
###############################################################################
CELL_COORDINATES = []

# get cell tower postions
for CELL in ALL_CELLS_HERE:
    POST_BODY = {"gsm": [CELL]}
    headers = {'Content-type': 'application/json'}
    r = requests.post(url = POS_URL, json = POST_BODY, headers=headers)
    if( r.status_code == 200):
        data = r.json()
        print(data)
        CELL_COORDINATES.append(data)
    else:
        print("Request failed, status code: " + str(r.status_code) )

# get estimated position HERE API
POST_BODY = {"gsm": ALL_CELLS_HERE}
headers = {'Content-type': 'application/json'}
r = requests.post(url = POS_URL, json = POST_BODY, headers=headers)
if( r.status_code == 200):
    ESTIMATED_COORDINATE_HERE_API = r.json()
    print(ESTIMATED_COORDINATE_HERE_API)
else:
    print("Request failed, status code: " + str(r.status_code) )

</code>
This is currently how i am calling the API.
Answer: I think you are listing neighboring cells wrong. They should be after main cell inside "nmr". If your serving (main) cell is 17078 format should be following:
<code>{
  "gsm": [{
  "mcc": 234,
  "mnc": 15,
  "lac": 314,
  "cid": 17078,
  "rxlevel": -52,
  "nmr": [
    {"bsic": 27, "bcch": 33, "rxlevel": -61,"lac":165,"cid":13491},
    {"bsic": 38, "bcch": 26, "rxlevel": -62,"lac":316,"cid":16191},
    {"bsic": 8, "bcch": 30, "rxlevel": -65,"lac":165,"cid":13492},
    {"bsic": 35, "bcch": 36, "rxlevel": -65,"lac":316,"cid":18119},
    {"bsic": 37, "bcch": 29, "rxlevel": -66,"lac":165,"cid":13564},
    {"bsic": 41, "bcch": 37, "rxlevel": -69,"lac":314,"cid":17079}
  ]
  }]
}
</code>
Format is listed here


Where do twig files find variables?

Question: for example for the file node.html.twig has a giant comment saying
* Available variables:
* - node: Full node entity.
 *   - id: The node ID.
 *   - bundle: The type of the node, for example, "page" or "article".
 *   - authorid: The user ID of the node author.
 *   - createdtime: Formatted creation date. Preprocess functions can
 *     reformat it by calling format_date() with the desired parameters on
 *     $variables['node']->getCreatedTime().
 * - label: The title of the node.
 * - content: All node items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.
 * - author_picture: The node author user entity, rendered using the "compact"
 *   view mode.
 * - metadata: Metadata for this node.
 * - date: Themed creation date field.
 * - author_name: Themed author name field.
 * - url: Direct URL of the current node.
 * - display_submitted: Whether submission information should be displayed.
 * - attributes: HTML attributes for the containing element.
 *   The attributes.class element may contain one or more of the following
 *   classes:
 *   - node: The current template type (also known as a "theming hook").
 *   - node--type-[type]: The current node type. For example, if the node is an
 *     "Article" it would result in "node--type-article". Note that the machine
 *     name will often be in a short form of the human readable label.
 *   - node--view-mode-[view_mode]: The View Mode of the node; for example, a
 *     teaser would result in: "node--view-mode-teaser", and
 *     full: "node--view-mode-full".
 *   The following are controlled through the node publishing options.
 *   - node--promoted: Appears on nodes promoted to the front page.
 *   - node--sticky: Appears on nodes ordered above other non-sticky nodes in
 *     teaser listings.
 *   - node--unpublished: Appears on unpublished nodes visible only to site
 *     admins.
 * - title_attributes: Same as attributes, except applied to the main title
 *   tag that appears in the template.
 * - content_attributes: Same as attributes, except applied to the main
 *   content tag that appears in the template.
 * - author_attributes: Same as attributes, except applied to the author of
 *   the node tag that appears in the template.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional output populated by modules, intended to be
 *   displayed after the main title tag that appears in the template.
 * - view_mode: View mode; for example, "teaser" or "full".
 * - teaser: Flag for the teaser state. Will be true if view_mode is 'teaser'.
 * - page: Flag for the full page state. Will be true if view_mode is 'full'.
 * - readmore: Flag for more state. Will be true if the teaser content of the
 *   node cannot hold the main body content.
 * - logged_in: Flag for authenticated user status. Will be true when the
 *   current user is a logged-in member.
 * - is_admin: Flag for admin user status. Will be true when the current user
 *   is an administrator.

Where would these come from?
When I write my own template file how do I know what variables are available in my new template file?
Answer: Variables can be added and manipulated in preprocess functions just as with .tpl.php files.
Twig has a dump() command that can allow you to see the available variables.
Answer: That's more or less just like in D7, just that it's a twig template in the end instead of PHPTemplate.
Initially, variables are defined in hook_theme(). Then someone calls a certain theme function and passes those arguments in, usually as part of a render array, something like:
$output = ['#theme' => 'item_list' => '#items' => [1, 2, 3]]

When that is rendered, then the preprocess functions are called which can process the initial variables and add more things. For node.html.twig, most of those things are added by template_preprocess_node().
More information: Theme system overview
Answer: You can see the variables available on your template:

  {% for key, value in _context  %}

{{ key }}

  {% endfor %}

Where do twig files find variables?


Android listview getting all items

Question: In android, is it possible to get all items inside the list view. Lets say the list view has multiple rows and only 2 rows are visible on the screen while the rest are accessible using the scroll bar. Each row has a radio button and a text view. Is there a way to get all textview of the rows whose radio button is selected and not just the ones visible on the screen.
Comment: You definitely can do that in your adapter implementation. Could you show us your ListView and Adapter codes ?
Comment: hey its not letting me post everything its more than the max lines. cna you give me an example of how i can do it in the adapter implementation? thank you
Comment: Try to post your in pastebin.com and upload the link here so that we can see your implementation.
Answer: Your answer may be:
for(int item = 0; item < m_listitem.count(); item ++){
            if(m_listitem[item].isSelected){
                View view = ListView.getChildAt(i);
                TextView textview = view.findViewById(your textView id);
                // do some thing
            }
        }

Comment: wouldnt the view.findviewbyid... get null if the row is not visible?
Comment: here is the link http://pastebin.com/iRvhUEud and the part i am concerned about starts at         tellOthers.setOnClickListener(new View.OnClickListener() {
Comment: @MushahidNawazKhan no, it is null if view is null  or id is not exits on view.
Comment: but the rows that are not visible would be null right? in that case when i select the radio button and click on submit, the rows afte the second one will be null right?
Comment: no, it is not null.
You can read docutments here
http://developer.android.com/reference/android/view/ViewGroup.html#getChildAt(int)
Comment: i am getting null when i run the code. i have almost the samethign as the one u posted. I read online some where that the rows that are not visible are null
Comment: U can see this link :).
http://stackoverflow.com/questions/24811536/android-listview-get-item-view-by-position
Comment: the link diddnt help :(
Answer: You can use custom list view to show your list items with checkbox & textview.
Answer: I happened to have a similar requirement where I had multiple EditText inside a ListView and only few of them were visible on the screen. I needed to get the values of all EditText and not just the ones visible on the screen.
Well if you are using a default Adapter, then the way it will work is it will recycle the old views to create new ones. So there is no way to preserve values of those Views which are not visible.
So the only workaround is to create your own Adapter, maybe something like the following, which will not recycle any views, but every time inflate new ones.
public class ListViewAdapter extends ArrayAdapter {

    public ListViewAdapter(Context context, ArrayList<Object> items) {
        super(context, 0, items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return LayoutInflater.from(getContext()).inflate(R.layout.your_layout_for_list_view_item, parent, false);
    }
}

After that, as in above answer Lãng Tử Bị Điên has mentioned, you can check in your java code, if your radio buttons are checked or not, and according to that, selected desired TextViews
for(int item = 0; item < m_listitem.count(); item ++){
        if(m_listitem[item].isSelected){
            View view = ListView.getChildAt(i);
            TextView textview = view.findViewById(your textView id);
            // do some thing
        }
    }

Hopefully this should do it.. It sure worked in my case!

Android listview getting all items


rtk query , How to assign data will received from request to variable is initialized with useState?

Question: How to assign data which received from request to variable is initialized with useState hook ?
** this is the define of the service which call request **

export const diligenceApi = createApi({
    reducerPath: 'diligenceApi',
    baseQuery: fetchBaseQuery({
        baseUrl: environment.apiUrl,
    }),
    tagTypes: ['Diligence'],
    endpoints: (builder) => ({
        updateCoverage: builder.mutation<DiligenceDTo[], { organizationName: string,              updateCoverageRequest: any }>({
            query: (arg) => {
                const { organizationName, updateCoverageRequest } = arg;
                return {
                    url: `${organizationName}/Charts/Coverage`,
                    method: "POST",
                    body: updateCoverageRequest,
                }
            },
            invalidatesTags: ['Diligence']
        }),
    })
})

export const { useUpdateCoverageMutation } = diligenceApi

** I want to assign data variable with data that's will received from the request after the request finish **
**like await it then **
const { dashboardFilter, organization } = useStateContext();
  const [data, setData] = useState<DiligenceDTo[]>();

  const [updateCoverage, { data: coverageData, isLoading, isSuccess, isError}] = useUpdateCoverageMutation();

  const getData =  async() => {
    await updateCoverage({ organizationName: organization?.name, updateCoverageRequest: dashboardFilter });

  }

  useEffect(() => {
    if (!organization?.name) return;
     getData();
  }, [dashboardFilter, organization]);

Comment: Did you try `setData`?
Comment: yes and didn't accept cause it may be infinite loop
Answer: useEffect(() => {
    if (!isSuccess) return;

    coverageData.then(({ data }) => setData(data));
}, [ coverageData, isSuccess]);


Localize multi platform projects - Consolidate string-files

Question: In our multi-platform projects, we have multiple localization files with different notation and file format (iOS .string, Android .xml, etc.).
Now we want to localize them in many languages, but in the different files, there are many equal strings. so anybody knows of a good way to consolidate these strings-files to one big localization file, hand this to the translation agency and then splut them back up into the different files?
Anybody knows a good approach?
Answer: I've worked on an iOS/Android project with 20 translations, and we used an Excel spreadsheet to keep track of all the translatable strings. The *.strings files for XCode and the *.xml files for Eclipse are then automagically generated using my custom VBA macro.
I've put an example Excel spreadsheet with VBA macro here:
http://members.home.nl/bas.de.reuver/files/multilanguage.zip
You can convert your existing .strings or .xml files to spreadsheet format (key value pairs, tab separated) with the tool below. Then you can send the spreadsheet to your translators, they fill in a column of translated values, send it back and you can simply generate your new translation files.
http://members.home.nl/bas.de.reuver/files/stringsconvert.html
EDIT in 2021
The homepage is offline now, but I've added the Excel/spreadsheet example on github:
https://github.com/BdR76/Manage-translations
Comment: Great solution but there is an error in the webpage converter: If I convert from Android to iOS the underscores in the keys get lost. i.e. an `This is my app` gets converted to `"app name" = "This is my app";`
Comment: This seems like a pretty nice solution. But if i open the excel file and run any of the macros, i get an error "Compile Error. Cant find project or library". Since i have no experience with VBA, do you have any advide on this?
Comment: Ah good point. If you get a compile error "User-defined type not defined" or something like that (the message probably changes between versions...), press ALT-F11 to go to the VBA editor, then from the menu select Tools -> References, and make sure the option "Microsoft Scripting Runtime" is checked.
Btw I've just now also updated the readme.txt in the zip.
Comment: I checked on this, but the Microsoft Scripting Runtime is checked. I am working on a mac, but i will try it on a windows machine tommorow. Maybe it will work there.
Comment: I just tried it on my windows machine and it works like a charm. Good work
Comment: Thanks :) btw when you first start adding translations, usually some texts are too long. So be aware that either the translators will have to do some re-phrasing and/or you'll have to make some layout changes in the app.
Comment: When converting from strings to xml, the spaces are replaced with underscores, because Eclipse can't handle spaces in xml key names. So, for symmetry, they were replaced back to spaces when converting from xml to strings. But okay, I've disabled that now.
Comment: FYI Microsoft Scripting Runtime is Windows only. This will not work on Mac.
Answer: Was in the same situation with my app about a month ago.
If you use SmoothLocalize for your localization (which I would recommend as they are really easy and super cheap), you don't have to pay for repeat strings on the 2nd order. So you would pay the full 4c/word for your iOS localization, then just paste in your order number for the Android localization and you don't have to pay to translate them again.
Also if they are EXACTLY the same, they will convert a .strings to a .xml for you so you would only have to do one order, just email them.
Comment: @Shudy There is a service called [Respresso](https://respresso.io?so). It let's you handle your mobile/web app localization (and other resources) on a web UI and creates all the platform specific formats after each change then sync them directly into your project during the next build. This allows you to give access to a translator and after they finish you only need to rebuild the project, no manual download/copy paste is needed. (As I know it will not merge duplicate values during import but it will match them by the keys.)
Comment: I arrived to this question and I was looking for options. This options is "deprecated". Company no longer offers this service.


Basis for topology on half open sets in R

Question: Hi I was trying to determine the basis of the topology on the following collection in R {[a,b), a <b}.
Here is what I tried : Knowing that the basis for a subspace topology is equal to the set of all intersections of {[a,b), a <b} with the basis of the topology it is a subspace to.
Now I also know that the basis for the euclidean topology on R is {(a,b), a <b}. Can I just take the intersection of {[a,b), a <b} and {(a,b), a <b} to get the basis? If so what does this equal? Or am I totally wrong?
Thanks in advance.
Comment: The collection $\{[a,b)\ |\ a<b\}$ is not a topology. But it already is a basis for some topology (more precisely: the topology generated by it). Also why you mention subspace topology and the euclidean topology? You don't have subspaces here, and the euclidean topology seems irrelevant.
Comment: My apologies you are ofc right. I misphrased my question.
Answer: If I understand your question correctly, we consider the subspace $C = [a, b) \subseteq \mathbb{R}$, where $a < b$. You can show that if $\mathcal{B}$ is a basis for the topology on $X$, and $A$ is a subspace of $X$, then the collection $\{ A \cap B | B \in \mathcal{B} \}$ is a basis for the topology on $A$. Thus, a basis for $C$ is the collection $\{ C \cap (x, y) | x, y \in \mathbb{R} \}$. You can verify that each element in this basis has one of two forms. The first is $[a, r)$, where $r \in C$. The other is $(l, r)$, where $l, r \in C$.
Comment: thx! sorry if my question wasn't that clear but you really helped me out :) !


Múltiplas turmas para um aluno

Question: Tenho uma aplicação de ensino nela tenho um model para Turmas (Room) e outro para Alunos (Student).
Na minha regra de negócios cada aluno pode ser matriculado em até 3 turmas.
Para isso eu simplesmente criei 3 colunas a mais no cadastro de alunos.

room_1 (integer)
room_2 (integer)
room_3 (integer)

E na criação coloco o id da turma de forma manual (form select) dentro de cada coluna.
Meu problema é que:

sei que não é e forma correta de criar esse relacionamento.
Estou tendo diversos problemas na hora de gerar relatório por que preciso dar diversas voltas para consultar os dados.
Answer: Primeiro é necessário fazer uma table N:N.
rails g model student_rooms student:references room:references

Agora, fazemos as migrações para criar as foreign_keys.
rails g migration AddStudentRoomToRooms student_room:references
rails g migration AddStudentRoomToStudents student_room:references
rails db:migrate

Nos models:
class StudentRoom
 belongs_to :student
 belongs_to :room
...

class Room
 has_many :student_rooms
 has_many :students, through: :student_rooms
...

class Student
  has_many :student_rooms, validates_length_of :rooms, maximum: 3
  has_many :rooms, through: :student_rooms
...

Uma Room possui muitos students e um Student possui muitas rooms. A table StudentRooms serve apenas para conectar as duas tables. O que impede que um Student tenha mais de 3 Rooms é a validates_length_of.

Múltiplas turmas para um aluno


Is the maximum link length function convex?

Question: Given $x_i$'s in $\mathbb{R}^2$ and $\mathcal{S}$ defined arbitrarily as a set of two $x_i$'s, i.e., $$\mathcal{S}=\{(x_1,x_4), (x_2, x_3), (x_3, x_6), (x_6,x_4), (x_4, x_7)\},$$
the function is defined by
$$f(x_1, x_2, \ldots, x_n)=\max_{(x,y) \in \mathcal{S}} \lVert x-y \rVert.$$
The physical meaning of $f$ is the maximum edge length in a tree, where the tree has $n$ vertices and $\lvert\mathcal{S}\rvert$ edges.
Is the function $f$ convex?
Answer: In general, if $f_\alpha$ are convex, then $f=\sup_\alpha f_\alpha$ is convex.
In the above case, the functions (indexed by $i,j$ rather than $\alpha$) are $(x_1,...,x_n) \to \|x_i-x_j\|$ which are convex.
That is, the function $f: (\mathbb{R}^2)^n \to \mathbb{R}$ is convex.
Comment: OMG, I also know the fact, as you said, that the supremum of a set of convex functions is again convex. However, I couldn't think of it rigorously and mathematically. Thanks to you, I wholly understood. God bless you!


Django is not finding images linked via CSS file when in production

Question: I have deployed a Django 2.2 project via Digital Ocean and it can be found at www.fancyfetish.co.uk
If you visit the site it looks awful, with a lot of images and styling missing. This is not the case when in development. When I use chrome dev tools to inspect the console there are 404 errors when retrieving images that have been called from the CSS file, along with a lot of CSS styling.
Find here a code snippet from my CSS file that is not being rendered at all:
.showcase {
  min-height: 40rem;
  position: relative;
  display: table;
  width: 100%;
  height: auto;
  padding-top: 15rem;
  padding-bottom: 10rem;
  background-image: url("/static/baseapp/img/fancy_fetish_showcase.png/");
  background-position: center 50px;
  background-repeat: no-repeat;
  background-size: cover;
 }

  .showcase h3 {
    font-family: 'Cinzel', serif;
  }

  .showcase h1 {
    font-family: 'Cinzel', serif;
  }

  .showcase a {
    font-family: 'Peddana', serif;
    font-size: 1.5rem;
  }

As shown in this section I clearly link the background-image back to the images folder. The particular images folder I am specifying is the one where all my static files go to when I use collectstatic.
The 404 error says:

http://fancyfetish.co.uk/static/baseapp/css/fancy_fetish_showcase.png

So it is trying to find the CSS image within the css file, however it is located in the img folder within static.
Here is the link in my django template:
<link rel="stylesheet" type="text/css" href="{% static 'baseapp/css/style.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'baseapp/css/bootstrap.css' %}">

Here is the directory:

Within apps is a cart application, a user application, a products application and a baseapp where I keep all static folders, and link back to all of them from the other apps, so I don't have static files in every single app.
My settings files look like this:

STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

STATICFILES_DIRS = [
    'apps/baseapp/static'
]

STATIC_URL = '/static/'

The main static directory in the directory image above is where collectstatic moves everything to, it looks like this:

The media file found within the main directory is where images uploaded via the database go, as shown here in one of my models:
class ToyProduct(models.Model):

    slug = models.SlugField(max_length=40)
    image = models.ImageField(upload_to='media')
    title = models.CharField(max_length=150)
    description = models.TextField()
    price = models.DecimalField(max_digits=5, decimal_places=2)
    stock_quantity = models.PositiveIntegerField()
    in_stock = models.BooleanField(default=True)
    category = models.CharField(choices=TOY_CATEGORY_CHOICES, max_length=2, default='FW')
    brand = models.CharField(choices=TOY_BRAND_CHOICES, max_length=2, default='NB')
    on_sale = models.BooleanField(default=False)

    def __str__(self):
        return self.title

I write my css in an SCSS file and Koala dev tool compiles to css which is then collected to the static folder.
I am pretty sure this is something very obvious and I am looking too far into it, or I have my static files in my settings wrong. Is anyone able to assist at all?
Most grateful regards!
Carlie
Comment: Which web server did you choose and have you configured it to serve static files? Django doesn't just serve the files in production the same way it does in development.
Comment: I am using Ubuntu through digital ocean, with nginx, and I assumed there was an issue with CSS only as other static files and my bootstrap.css files seem to have loaded fine
Comment: If I look at the 'style.css' files, the url is not as you show here. It's `background-image: url("fancy_fetish_showcase.png");`. urls in css files are always **relative to the location of the css file itself**. Change it to `url("../img/fancy_fetish_showcase.jpg")`.
Comment: Note that if `baseapp` is one of your Django apps, Django already looks for files inside the `baseapp/static/` directory so you don't need to add it to `STATICFILES_DIRS`, as explained [here](https://docs.djangoproject.com/en/stable/howto/static-files/#configuring-static-files)
Comment: Also note that media files are uploaded to `MEDIA_ROOT` (in your settings), so if `MEDIA_ROOT` is a folder called "media" somewhere, you shouldn't `upload_to='media'` since that would upload your files in __path/to/media/media__, ie. two times "media".
Comment: Finally, I would advise you to put "media" and "static" folders (`MEDIA_ROOT` and `STATIC_ROOT`) **outside of your project folder**, so one level higher up. That way, when you deploy your source code, you don't run the risk of overwriting media and static. Especially since both need to be accessible by nginx, whereas your source folder doesn't need to be accessible by nginx (only by django process) so you can tighten security.
Comment: I am really unsure why my CSS file on the server has the URL as url("fancy_fetish_showcase.png") as this is not what it written in the CSS file that I am uploading to the server. There may be an error in my SCSS rendering, thank you for pointing this out to me. I will also take a look at my file structures for security. Thank you!
Answer: url() in css files always uses a path relative to the location of the css file itself.
Your style.css file contains background-image: url("fancy_fetish_showcase.png"); so your browser is going to look for this file in the same folder as the css file (/static/baseapp/css).
You should replace this with url("../img/fancy_fetish_showcase.jpg") for it to look in /static/baseapp/img.
Answer: I discovered the issue, the server was accessing an old version of my css file through GIT. I recloned to repo and it updated to my latest working version of CSS and now all is working


Is SimpleNews Cron Neccessary?

Question: I'm running the latest stable version of SimpleNews 7.x.
I realise there is an option to disable sending via cron tasks and set a throttle. The description underneath this option advises it should only be used for testing purposes.
My SMTP server relays through Amazon SES. The SMTP server itself throttles email sending by default to 20 messages per connection.
So I'm wondering, is the cron task email sending really necessary if the messages just get queued up and throttled by my SMTP server anyway?
If I disable the cron sending are there any substantial problems I might encounter?
Answer: The throttle value you're mentioning is specific to cron jobs, not to a single send event. There's no easy way to throttle the number of mails delivered in a single send event.
In general, the main reason someone would want to use cron in this case is when your subscriber base is large enough that a single "Send" action will time out, due to the time taken to send the total number of emails exceeding your server's PHP maximum execution time directive.
Cron is utilised in this case to break up large subscriber bases into chunks your server can better manage.
In your case, you have a limitation of 20 outgoing mails imposed on you by your service provider. To ensure you can send mail to more than 20 people at a time, you will have to use cron to get around this limitation.
The throttle you refer to is the number of messages sent PER cron. Removing cron isn't advisable for a substantial list, as your server will connect to Amazon, attempt to deliver all the mails, of which only 20 would be accepted.
Without knowing the inner workings of Simplenews, one of two possible (and undesirable) scenarios would unfold:
1.) Any mail in excess of the first 20 would be ignored by Amazon, and sending would fail. Your site would ignore the errors, and of your entire "Send" event, 20 mails would go out.
2.) Simplenews might cache the remaining mails that Amazon doesn't accept in your DB. These would wait around to be sent at a later stage (next cron run), but because you're not running cron, Simplenews wouldn't be invoked during cron, and that queue would never be properly addressed. This would result in you sitting with a large number of unsent mails clogging up the Simplenews spool table.
Bottom line, disable cron at your peril. The second your subscriber base goes over 20, your newsletter sending process will start to give you issues.

Is SimpleNews Cron Neccessary?