What is the proper way to average a set of complex numbers in c++?

Question: I have inherited some C++ code that needs to average some complex numbers. Given a collection, it adds those values which pass a condition to an accumulator, then divides by the number of values added.
Using gcc (currently, gcc 8) I get template argument deduction/substitution failed if I use stand-alone operator/ but it works fine with std::complex::operator/=. Such a nuance seems fragile for follow-on maintainers.
So what is the proper way to get an average of complex numbers?
And is it reasonable that the language only partially supports division of complex numbers by integral types?
std::complex<double> A[32] = { /* initialization left to the reader */ };
int count = 0;

std::complex<double> sum;
for (auto i = 0; i < 32; ++i) {
   if ( i % 2 ) { // arbitrary condition, not important
      sum += A[i];
      ++count;
   }
}

auto avg = sum / count; // this is ambiguous
sum /= count;           // this is not

(representative error, for the curious)
main.cpp: In function 'int main()':
main.cpp:16:16: error: no match for 'operator/' (operand types are 'std::complex<double>' and 'int')
 auto avg = sum / count; // this is ambiguous
            ~~~~^~~~~~~
In file included from main.cpp:2:0:
/usr/include/c++/7/complex:434:5: note: candidate: template<class _Tp> std::complex<_Tp> std::operator/(const _Tp&, const std::complex<_Tp>&)
     operator/(const _Tp& __x, const complex<_Tp>& __y)
     ^~~~~~~~
/usr/include/c++/7/complex:434:5: note:   template argument deduction/substitution failed:
main.cpp:16:18: note:   mismatched types 'const std::complex<_Tp>' and 'int'
 auto avg = sum / count; // this is ambiguous
                  ^~~~~
In file included from main.cpp:2:0:
/usr/include/c++/7/complex:425:5: note: candidate: template<class _Tp> std::complex<_Tp> std::operator/(const std::complex<_Tp>&, const _Tp&)
     operator/(const complex<_Tp>& __x, const _Tp& __y)
     ^~~~~~~~
/usr/include/c++/7/complex:425:5: note:   template argument deduction/substitution failed:
main.cpp:16:18: note:   deduced conflicting types for parameter 'const _Tp' ('double' and 'int')
 auto avg = sum / count; // this is ambiguous
                  ^~~~~
In file included from main.cpp:2:0:
/usr/include/c++/7/complex:416:5: note: candidate: template<class _Tp> std::complex<_Tp> std::operator/(const std::complex<_Tp>&, const std::complex<_Tp>&)
     operator/(const complex<_Tp>& __x, const complex<_Tp>& __y)
     ^~~~~~~~
/usr/include/c++/7/complex:416:5: note:   template argument deduction/substitution failed:
main.cpp:16:18: note:   mismatched types 'const std::complex<_Tp>' and 'int'
 auto avg = sum / count; // this is ambiguous
                  ^~~~~

Comment: Have you tried `sum / double(count)`?
Comment: yes, I know I can do an explicit cast. And that is how I get around the error/ambiguity to keep going. I guess this is a more philosophical question than a pragmatic one
Comment: Opinion: Absolutely reasonable that the language only partially supports.  Your template is to the type double.  therefore doubles get special treatment relative to your template.  You are welcome to define the operation for other types as you see fit or even change the operation relative to doubles.
Comment: As converting an integer to floating point might lose accuracy, philosophically I'd expect support for division of a float by an integer. AFAIK, no processor actually supports division of a float by an integer, so I can see why C++ standard doesn't either.
Answer: Not sure what the most proper way to do division for it, but if you look through all the parameters operator/ and operator/= take, you would notice that:

operator/ takes in either std::complex<T> or T.

So if you have your original complex created with double, then it should only take in another value that is either double or complex<double>.
In fact, depends on the compiler you are using, clang straight up gave invalid operands to binary expression ('std::complex<double>' and 'int') error

operator/= takes in std::complex<T> or T, while also have specialization for float, double, and long double.

That means whatever passed to operator/= would have a change to be implicit converted to float, double, or long double, which int can do.
Comment: is this part of the mystical world of template type deduction, where implicit conversion does not apply? If I understand what you are saying, `operator/=` has an explicit specialization for `float` (for example) but `operator/` does not?
Comment: @Jwm That's exactly what I mean. Remember that `T` was deduced to `double` when you constructed `std::complex sum`.


How to Enable Ports 25 - 28 on a Cisco Catalyst 3750

Question: I am trying to enable ports 25 - 28 on my 28 port Catalyst 3750. These four ports are my fiber ports. I am using the following command to bring up that interface.
interface range Gi1/0/25 - 28
That works and it dumps me in the config-if-interface prompt. This is where I get stuck. I just want to enable these four ports and have them be in VLAN1 and On just like ports 1 - 24.
How do I do this?
Answer: First of all, do a show running-config interface GigabitEthernet 1/0/X and have a look at how those interfaces are actually configured.
Then do what is needed:

If they are in shutdown state, issue a no shutdown command.
If they are not in the right VLAN, issue a switchport access vlan X command.
If they are configured for something else than standard access (i.e. trunking), clear their configuration and reconfigure them.
Comment: Could also do "sh int status" for a quick view look at all interfaces. But Massimo hit the nail on the head with his answer.
Comment: This may be a silly question, but are they actually connected to something? The fact that they say "down" and not "administratively down" means they are enabled. The switch just doesn't see anything connected to them. Do you have SFP modules inserted? The output of `show int Gi1/0/25` (or 26-28) should have a line showing the media type, such as `media type is SX`, or `media type is Not Present` if there is no SFP module installed.
Comment: I issued a "no shutdown" to the interface range Gi1/0/25 - 28. Although when I back out to the non-enabled prompt and do a "show interface Gi1/0/25" the output states that Gigabit ethernet 1/0/25 is down, line protocol is down (not connected)".

Ports 25 - 28 are still not connected.
Comment: Agreed. "Line protocol is down" states clearly that the switch thinks there isn't anything connected to those interfaces, so you should have a look at cabling and at whatever is at the other end.
Answer: Do the ports require GBICs (and, if so, do you have GBICs installed)? Do you have cables attached to the ports? If you're using fibre, you MAY have to swap the connectors around (I don't think this is possible for SFP connectors, so you'd have to have a cross-over cable or a connector that allows you to connect RX on one cable to TX on the other).
Comment: You've got quite confused ideas, haven't you?
Comment: Not necessarily. Off-hand, I don't recall if ports 25-28 require GBICs or not (if they're GBIC ports, they'll just be slots in the chassis). I guess I could check it, but...

Missing cables happen, a lot, especially when different people deal with the physical install and configuration.

Fibres being the wrong way around is painfully common.
Answer: Have you tried:
- a show interface gi1/0/25 capabilities to see if the switch recognizes the SFP?
- checked that the SFP type works with the fiber type you are trying to use?
- The fiber path in properly patch and consistently the same type of fiber?
- The switch on the other end has a compatible SFP as well?
- some interfaces allow speed changes to be configured, you might check that the switches are configured the same on both sides.
I took a short LC and flipped the TX - RX, so that I can default the interface do a no shut, then plug in the tester to two interfaces on the same switch.  That will eliminate the other switch and the path if the link doesn't come up.
Answer: Did you make sure that the end device to those ports (25 - 28) are connected and powered up. Unless you power up the device connected to the port, it will say "not connected". Power up the device and try running sh int status again. Cheers


How to use Private Route using react-router?

Question: I want to make secure routes using authentication. I have defined the routes in App.jsx file. I am using "Route" to define which component to render.
In App.jsx
<Route
    path='/dashboard'
    exact={true}
    render={(props) => <Dashboard {...props} user={user}
    handleChildFunc={this.handleChildFunc}/>}
/>

The above code works without any issue. I want to make that secured like below.
<PrivateRoute
    path='/dashboard'
    exact={true}
    render={(props) => <Dashboard {...props} user={user}
    handleChildFunc={this.handleChildFunc}/>}
/>

In PrivateRoute.jsx
const PrivateRoute = ( props ) => {
  const user = "token from cookie"; // i will fetch token stored in cookie
  if(user !== null) {
    return <Route   />;
  }
  else {
    return <Redirect to="login" />
  }
}

If the token is present, render a component. Otherwise, redirect to /login.
Comment: I have made a [gist](https://gist.github.com/EduVencovsky/f8f6c275f42f7352571c92a59309e31d) for private routes, if you wanna check it out.
Comment: You are using . But in my case, the Route is defined like this :  }/>. How can i modify the code?  I am not using component={Component}. Because i want to pass props to the component.
Answer: You can have your PrivateRoute like,
<PrivateRoute
    path='/dashboard'
    exact={true}
    component={Dashboard}
    handleChildFunc={this.handleChildFunc}
/>

const PrivateRoute = ({ component: Component, handleChildFunc, ...rest }) => {
    const user = "token from cookie";
    return <Route {...rest} render={(props) => (
        user !== null
            ? <Component {...props} user={user} handleChildFunc={handleChildFunc}/>
            : <Redirect to='/login' />
        )}
    />
}

Comment: Thanks. It worked. I also found another way to do it.                                                                                const PrivateRoute = ( {path, exact, render} ) => {
    const user = null;
    if(user !== null)
    {
        return
    }
    else
    {
        return
    }
}
Answer: The accepted answer is good, but it does NOT solve the problem when we need our component to reflect changes in URL.
Say, your component has the following code:
export const Customer = (props) => {

   const history = useHistory();
   ...

}

And you change your URL:
const handleGoToPrev = () => {
    history.push(`/app/customer/${prevId}`);
}

The component will not reload!

An improved solution:
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import store from '../store/store';

export const PrivateRoute = ({ component: Component, ...rest }) => {

  let isLoggedIn = !!store.getState().data.user;

  return (
    <Route {...rest} render={props => isLoggedIn
      ? (
        <Component key={props.match.params.id || 'empty'} {...props} />
      ) : (
        <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
      )
    } />
  )
}

Usage:
<PrivateRoute exact path="/app/customer/:id" component={Customer} />

Comment: Wonderful solution for the dynamic url portion and in general.
Comment: You should link to specific answers rather than saying "the accepted answer". That can change.
Answer: Simply !
  export default function RouteComponent() {
  const user = useContext(UserContext);

  return (
    <Router>
      {user.islogin ? (

          <Switch>
            <Route exact path="/">
              <Home />
            </Route>
            <Route path="/NewActiv">
              <NewActiv />
            </Route>
          </Switch>

      ) : (
        <Switch>
          <Route exact path="/">
            <Login />
          </Route>
        </Switch>
      )}
    </Router>
  );
}
export default function RouteComponent() {
  const user = useContext(UserContext);

  return (
    <Router>
      {user.islogin ? (

          <Switch>
            <Route exact path="/">
              <Home />
            </Route>
            <Route path="/NewActiv">
              <NewActiv />
            </Route>
          </Switch>

      ) : (
        <Switch>
          <Route exact path="/">
            <Login />
          </Route>
        </Switch>
      )}
    </Router>
  );
}


Probability of distance between two points in an interval

Question: On interval [-2,4] we choose random numbers x and y.
a)What is the probability, that distance between x and y is greater then distance between y and number 4.

I did this: $$|y-x|>|4-y|$$$$\frac{x+4}{2}<y$$
I draw a line and 'paint' the surface above the line, in range [-2,4] for both x and y in the coordinate system. The areas's surface is 9, surface of the whole area between [-2,4] for both x and y is 36. So, the probability is:
$$\frac{9}{36} = \frac{1}{4}$$ which is a correct answer.
My question is: If I switch the above starting formula to $$|y-x|>|y-4|$$
I will get $$\frac{x+4}{2}>y$$
and the end result will be area under the graph. That would give me a wrong answer of $$\frac{3}{4}$$
How to approach this kind of problem?
Answer: Regardless of whether you use $|4-y|$ or $|y-4|$ you should get the same $x+4 < 2y$, so you did something wrong in between.
\begin{align}
|y-x| &> |y-4|\\
|y-x| &> 4-y & \text{you know $y \le 4$}\\
x > y + (4-y) & \text{ or } x < y - (4-y)\\
x &< 2y - 4 & \text{the first case is impossible}
\end{align}


Important composers in transitional eras

Question: I understand Beethoven (and Schubert) to be very important composers in the transition from the Classical Era to the Romantic, such that they could be considered the first Romantic composers.
Are there similar figures that can be pointed to at the start of the Baroque and Classical Eras? Are there individual pieces that are strongly representative of the change, comparable to Beethoven's 3rd and 5th symphonies?
Big names I am aware of, such as Mozart and Haydn or J.S. Bach and Handel seem to have been working in a time when their respective eras had already been established.
Comment: "Eras" are fairly arbitrary historical artefacts invented after the fact, but C P E Bach might float your boat. And early Haydn is not very similar to the "late" Haydn that usually figures in "classical" concerts, for example. And it has been said that Wagner added nothing to the "romantic" harmonic vocabulary that J S Bach hadn't written already. Historians often have tidy minds, compared with messy reality.
Comment: @alephzero I can appreciate what you're saying, I'm sure any tidy answer will necessarily be overly simplistic. That said, as someone who hasn't studied classical music, I can feel a difference from Beethoven's 1st and 2nd to the 3rd. I suppose I'm looking for an answer such as that. Do you have specific pieces by Haydn and CPE Bach in mind?
Comment: YES. Definitely second CPE Bach for the period between Baroque and Classical. Maybe check out the Probiestücke?
Answer: Linking between the renaissance and baroque periods you could say that Monteverdi was a pivotal figure, and also of importance, Giovanni Gabrieli.  Monteverdi's Vespers is a great example of mixing the old style with the new.
To usher in the classical via late baroque or rococo, I agree with the above comments about CPE Bach.  Not sure that I can single out a particular work to represent this transition.  His use of the Sturm und Drang style certainly paved the way for Haydn and Mozart.
Answer: Haydn: Baroque to Classical
Cage: Serialism to Aleatoric
Webern: Romantic to Serialism
Comment: Schönberg has a non-trivial romantic oeuvre and invented dodecaphony, so to me that seems the obvious choice. Why do you list Webern instead?
Comment: Is serialism on its own a period?
Comment: @ToddWilcox I would say yes due to all that stuff with Darmstadt and so on.  But I am Not sure if aleatoric is a period on its own.
Comment: Both Schönbergs and Weberns musical is totally in the tradition of romantic music. I list Webern, because he is later and composers from serialism referred to Webern mainly.
Answer: Kind of a longer thought about historicism in general:
As pointed out in the comments, "transitional" figures are typically chosen by historians after the fact.
There are however periods of music history where figures actually try hard to get away from the past. A good example would be the changes that happened from Medieval polyphony to what we now call the the styles of the Renaissance. The early Renaissance theorist Tinctoris even said that before the year 1430, there was hardly anything composed that was worth listening to!
There are also many figures that are so radically different for their time yet seemed to not have paved the way for development in their direction. An example of this is Carlo Gesualdo, whose harmony could be considered radically expressionistic for his time period. A great counterexample who did end up having an impact on harmony and history would be Monteverdi, who called himself a practitioner of a newer style for his day, the secunda practica as opposed to the prima practica of older composers like Palestrina. And of course there are composers who both span multiple periods, and are even responsible for their creation: Stravinsky being one of the most shining examples of this, early on being comparable to other early modernist composers (eg Bartok, Debussy), to his neo-classical phase, and finally his serial music phase.


centos7 apache cannot write to a file it owns

Question: I have installed httpd and php on a fresh centos7 and put some files into /var/www/html including an install script I wrote. This script needs to write to a config file in the /var/www/html directory. I created an empty config file and chowned it to apache:apache. However trying to fopen this file with write access always gives the error:
fopen(/var/www/html/config-local.php): failed to open stream: Permission denied
Doing research I read this quote: "in order to reach a file, ALL parent directories must be readable." So I checked and they are. /, /var, /var/www and /var/www/html are all readable by everyone.
So what's going on here? It appears that the apache user is some kind of specially restricted user since testing the same scenario with a standard user works fine.
Comment: "in order to reach a file, ALL parent directories must be readable" -- orthogonal to your problem, but this statement is incorrect.  All parent directories must be *executable* in order to reach a file.
Answer: It's likely an SELinux permissions issue. /var/log/audit/audit.log should be able to confirm.
SELinux context is probably system_u:object_r:httpd_sys_content_t:s0, but should be system_u:object_r:httpd_sys_rw_content_t:s0. This can be altered with chcon.

I'm also not sanguine about having a config file within the DocumentRoot of your webserver. I could be mistaken as you haven't provided enough detail, but that would be the case if you haven't altered the defaults.
Comment: i had just discovered that it was an SELinux problem:

`chcon -t httpd_sys_rw_content_t config-local.php`

re config file location - it's not an uncommon scenario to put it there. wordpress does that.
Comment: consider using `semanage` to update the fcontext definition or restorecond; which should be running, may eventually put it back to the incorrect context.  chcon changes can be easily reverted by moving files around or by restorecond.
Answer: Spent a lot of time looking for this answer but it's all in bits and pieces and no one every posts a solution (well most of the time) so here is my solution and it's used on various web control panels as well.
install and use MOD_RUID2
Install PHP with CLI (this is standard on newer versions)
In your HTTPD.CONF file in the virtual hosts, you'll add the following, replacing username with the user's login name, and usergroup with the user's group (These are usually the same)
<IfModule !mod_ruid2.c>
    SuexecUserGroup username usergroup
</IfModule>
<IfModule mod_ruid2.c>
    RMode config
    RUidGid username usergroup
    RGroups @none
</IfModule>

An example of a Virtual host conf is:
<VirtualHost *:443>
  DocumentRoot "/home/imtheuser/public_html"
  ServerName imtheuser.com
  <IfModule !mod_ruid2.c>
    SuexecUserGroup imtheuser imtheuser
  </IfModule>
  <IfModule mod_ruid2.c>
    RMode config
    RUidGid imtheuser imtheuser
    RGroups @none
  </IfModule>
  <Directory "/home/imtheuser/public_html">
    allow from all
    Options None
    Require all granted
  </Directory>
</VirtualHost>

This will allow apache/php to write to a directory owned by the user. It's much safer then setting your chmod to 0777.
Comment: How does this have any relevance to the question?


An item in IEnumerable does not equal an item in List

Question: I just can't figure out why the item in my filtered list is not found. I have simplified the example to show it. I have a class Item...
public class Item
{
    public Item(string name)
    {
        Name = name;
    }

    public string Name
    {
        get; set;
    }

    public override string ToString()
    {
        return Name;
    }
}

... and a class 'Items' which should filter the items and check if the first item is still in the list...
public class Items
{
    private IEnumerable<Item> _items;

    public Items(IEnumerable<Item> items)
    {
        _items = items;
    }

    public List<Item> Filter(string word)
    {
        var ret = new List<Item>(_items.Where(x => x.Name.Contains(word)));

        Console.WriteLine("found: " + ret.Contains(_items.First()));
        // found: false

        return ret;
    }
}

The executing code looks like this:
static void Main(string[] args)
{
    string[] itemNames = new string[] { "a", "b", "c" };

    Items list = new Items(itemNames.Select(x => new Item(x)));
    list.Filter("a");

    Console.ReadLine();
}

Now, if I execute the program, the Console.WriteLine outputs that the item is not found. But why?
If I change the first line in the constructor to
 _items = items.ToList()

then, it can find it. If I undo that line and call ToList() later in the Filter-method, it also cannot find the item?!
public class Items
{
    private IEnumerable<Item> _items;

    public Items(IEnumerable<Item> items)
    {
        _items = items;
    }

    public List<Item> FilteredItems
    {
        get; set;
    }

    public List<Item> Filter(string word)
    {
        var ret = new List<Item>(_items.Where(x => x.Name.Contains(word)));

        _items = _items.ToList();
        Console.WriteLine("found: " + ret.Contains(_items.First()));
        // found: false

        return ret;
    }
}

Why is there a difference where and when the lambda expression is executed and why isn't the item found any more? I don't get it!
Comment: you are initializing a new item every time when you call`x => new Item(x)));`. using `Select`
Comment: Thanks guys. It is so obvious, but I didnt see it. I should quit working for today :D
Answer: The reason is deferred execution.
You intialize the _items field to
itemNames.Select(x => new Item(x));

This is a query, not the answer to that query. This query is executed every time you iterate over _items.
So in this line of your Filter method:
var ret = new List<Item>(_items.Where(x => x.Name.Contains(word)));

the source array is enumerated and a new Item(x) created for each string. These items are stored in your list ret.
When you call Contains(_items.First()) after that, First() again executes the query in _items, creating new Item instances for each source string.
Since Item's Equals method is probably not overridden and performs a simple reference equality check, the first Item returned from the second iteration is a different instance of Item than the one in your list.
Answer: Let's remove extra code to see the problem:
var itemNames = new [] { "a", "b", "c" };
var items1 = itemNames.Select(x => new Item(x));
var surprise = items1.Contains(items1.First());   // False

The collection items1 appears not to contain its initial element! (demo)
Adding ToList() fixes the problem:
var items2 = itemNames.Select(x => new Item(x)).ToList();
var noSurprise = items2.Contains(items2.First()); // True

The reason why you see different results with and without ToList() is that (1) items1 is evaluated lazily, and (2) your Item class does not implement Equals/GetHashCode. Using ToList() makes default equality work; implementing custom equality check would fix the problem for multiple enumeration.
The main lesson from this exercise is that storing IEnumerable<T> that is passed to your constructor is dangerous. This is only one of the reasons; other reasons include multiple enumeration and possible modification of the sequence after your code has validated its input. You should call ToList or ToArray on sequences passed into constructors to avoid these problems:
public Items(IEnumerable<Item> items) {
    _items = items.ToList();
}

Answer: There are two problems in your code.
First problem is that you are initializing a new item every time. That is you don't store the actual items here when you write.
IEnumerable<Item> items = itemNames.Select(x => new Item(x));

The execution of Select is deferred. i.e every time you call .ToList() a new set of Items is created using itemNames as source.
Second problem is that you are comparing items by reference here.
Console.WriteLine("found: " + ret.Contains(_items.First()));

When you use ToList you store items in list and the references remains same so you will find item with reference.
When you don't use ToList the references are not same any more. because everytime a new Item is created. you cant find your item with different reference.


Stay on Remote S3 RemoteProvider

Question: I am trying to make snakemake read and write directly to S3. Does anyone know if it is possible to use S3RemoteProvider and have the parameter stay_on_remote=True? When I have this parameter set to True, it doesn't look like snakemake can find my inputs. I also tried to use the XRootD RemoteProvider, but it doesn't seem to be able to talk to S3. Is there another way to do this?
Thanks in advance for your help!
Answer: It is possible to set stay_on_remote=True on an S3RemoteProvider, but it is an uncommon usage with specific requirements.
The stay_on_remote=True parameter is intended for backends like XRootD where processing can be carried out remotely where the data resides: in such scenarios, a command is dispatched to the remote backend to perform some action on the data without moving the data around. This is a standard way of using XRootD systems.
In most cases, in order for Snakemake to run commands to act on S3-stored input, it is necessary to transfer the data to the machine executing the job, so stay_on_remote should be omitted or set to False. When it is False, Snakemake will automatically download the object, run the rule, and then delete the local copy of the object when no more jobs depend on it. If you do set stay_on_remote=True, that would leave the files on S3, causing any local commands to fail if they try to find or use the input--unless they can access s3 themselves.
The S3RemoteProvider allows stay_on_remote=True for the use case where you have the ability to run commands that accepts S3 pseudo-URLs for reading and writing (s3://bucket-name/full/key/value/to/data). This could either be a remote system, or something like samtools that accepts s3:// locations. If stay_on_remote=True, the protocol will be prepended to the file automatically if it is not specified, so for the S3 provider you don't need to explicitly include s3:// in the input file strings.
For example, stay_on_remote=True can be used with samtools like this:
from snakemake.remote.S3 import RemoteProvider as S3RemoteProvider
S3 = S3RemoteProvider()

rule all:
    input:
        S3.remote("1000genomes/phase1/data/NA12878/exome_alignment/NA12878.mapped.illumina.mosaik.CEU.exome.20110411.bam", stay_on_remote=True)
    output:
        "out.txt"
    run:
        # samtools accepts s3:// paths, which are given when stay_on_remote=True
        shell("samtools view {input} 20:1000-100000 > {output}")

In the above Snakefile, Snakemake substitutes the input, s3://1000genomes/phase1/[...], for {input}, and samtools can act on the S3 object directly.
If you include your Snakefile we can try to see if stay_on_remote would apply for what you're doing, or if there's a bug in the implementation.
Comment: Thanks! I think I will stick with the consistent option of just downloading and uploading the inputs/outputs.

Stay on Remote S3 RemoteProvider


Reuse include statements in Entity Framework Core

Question: I'm trying to make reusable includes and it currently works when I have specific concrete root entity. But let's say I have structure like this:
public class A
{
    public B NavigationB { get; set; }
}

public class B
{
    public C NavigationC { get; set; }
}

public class C
{

}

And my include extensions
public static class IncludeExtensions
{
    public static IQueryable MyIncludesB(this IQueryable query)
    {
        return query.Include(q => q.NavigationC);
    }

    public static IQueryable MyIncludesA(this IQueryable query)
    {
        return query.Include(q => q.NavigationB)
            .MyIncludesB(); // how can I implement this
    }
}

Basically everything is okay if I have single root e.g. A, but what if I want to do fetch using root B? The idea is to then include everything required for B, but when using A as root then include everything for A, and when including B, reuse MyIncludesB.
I'm not sure if this is possible because include is returning IIncludableQueryable, but if anyone has any suggestions, feel free to help!
Comment: You have to convert 'iqueryable' to 'iqueryable' to use the extension method. Does a implement b?
Comment: No, they have nothing in common, just a navigation property.
Comment: You could implement an interface, which contains the properties they have in common. and the method takes 'IQueryable'
Comment: I'm not sure if you've understood the question correctly, but they don't have anything common. I just want to reuse standalone include within another include chain so I don't have to always copy paste all includes from `MyIncludesB` inside `MyIncludesA`
Answer: I think there are numerous possibilities.
My first idea would be to encapsulate the property expression:
public static class IncludeExtensions
{
    public static Expression<Func> MyIncludeListB()
    {
        return q => q.NavigationC;
    }

    public static Expression<Func> MyIncludeListA()
    {
        return q => q.NavigationB;
    }

    public static IQueryable MyIncludesB(this IQueryable query)
    {
        return query.Include(MyIncludeListB());
    }

    public static IQueryable MyIncludesA(this IQueryable query)
    {
        return query.Include(MyIncludeListA()).ThenInclude(MyIncludeListB());
    }
}

As you can see you can pass Expression<Func> to the method Include
My second idea is to implement include with strings .Include(string):
public static class IncludeExtensions2
{
    public static IEnumerable<string> MyIncludeListB()
    {
        return "NavigationC".Split(";");
    }

    public static IEnumerable<string> MyIncludeListA()
    {
        return "NavigationB;NavigationB.NavigationC".Split(";");
    }

    public static IQueryable MyIncludesB(this IQueryable query)
    {
        foreach (var i in MyIncludeListB())
        {
            query = query.Include(i);
        }

        return query;
    }

    public static IQueryable MyIncludesA(this IQueryable query)
    {
        foreach (var i in MyIncludeListA())
        {
            query = query.Include(i);
        }

        return query;
    }
}

As you can see you can pass string to the method Include. You can pass the complete chain of navigation properties.
If you want to implement more than one navigation property you have to amend both code examples accordingly.
There are already some questions and answers like yours:
Easy: Entity Framework - Include Multiple Levels of Properties
Hard: Multiple Includes() in EF Core


Retorno assíncrono de algumas APIs

Question: Por que o retorno de algumas APIs são exatamente o resultado que queremos (por exemplo, um JSON) e algumas outras retornam um objeto cheio de funções e objetos?
Exemplo de API que retorna diretamente o resultado que quero:

function user(id) {
  const users = {
    1: {id: 1, name: 'Lucas'},
    2: {id: 2, name: 'João'}
  };
  return new Promise(resolve => {
    setTimeout(() => resolve(users[id]), 1000);
  });
}

async function exec() {
  console.log(await user(1))
}

exec()

Já outras me retornam um objeto que contem várias coisas como, por exemplo, body, bodyUsed, headers, ok, redirected, status, statusText, type, url e outros.
Como, por exemplo, a API do GitHub:

async function getUserGithub() {
  console.log(await fetch(`https://api.github.com/users/decarvalholucas`))
}
getUserGithub()

Por que é assim e qual a diferença delas pra isso acontecer?
Comment: Ambas funções retornam a mesma coisa: um objeto. 1) Você está retornando um objeto "simples" com as propriedades ID e o nome do usuário; 2) Você está retornando o objeto [Response](https://developer.mozilla.org/pt-BR/docs/Web/API/Response), que — para acessar um *json*, por exemplo — é necessário utilizar um dos métodos disponíveis.
Comment: Ta, beleza; Mas a forma como demonstrei ali, do github.. Ele retorna várias coisas "padrões", digo padrões porque a maioria das APIs que usamos retorna isso, ai sempre tempos que fazer outra requisição pra puxar o que de fatos queremos realmente, por EXEMPLO, teríamos que dar um await result.json(). Isso é um padrão? Sempre vai ser assim esse retorno das APIs?
Comment: O `fetch` retorna uma classe (Response), que possuem atributos (`ok`) e métodos `json` Na verdade isso vai depender da API que você está utilizando, caso utilize `FormData`, ela terá outros métodos etc.
Answer: TL;DR: Os métodos em questão não vêm da API, mas sim do objeto Response que é retornado como uma promessa pelo fetch. Para obter os dados do corpo da resposta, você deve usar métodos como o json ou text, disponíveis no protótipo do objeto da resposta (Response).

Você está a usar a API fetch, que retorna uma Promise que resolve em um objeto Response, que possui os métodos descritos na sua pergunta.
Portanto, não é a API do GitHub (ou nenhuma outra) que retorna os métodos descritos na pergunta, até porque isso não seria um JSON válido, uma vez que essa notação não é capaz de transferir dados como funções ou métodos.
Então, o código a seguir não retorna o JSON da sua API, mas sim um objeto Response:

async function resolveFetch(...params) {
  // O `await` resolve a `Promise` retornada pelo `fetch` no objeto `Response`.
  const responseObject = await fetch(...params);

  // Aqui, `responseObject` é um objeto `Response` (retornado pelo `fetch`)
  // como uma promessa que já se resolveu.
  // Esse objeto possui diversos métodos, como o `json`, `text`, e
  // propriedades como o `headers`, que te permitem converter o retorno da
  // API a um formato desejado (como o `json`) ou obter informações sobre
  // a resposta da requisição.
  return responseObject;
}

(async () => {
  const result = await resolveFetch('https://api.github.com/users/lffg');

  console.log(result instanceof window.Response); // true
})();

Desse modo, para obter o valor do corpo da resposta, você deve fazer uso de algum dos métodos a seguir, disponíveis no protótipo do objeto Response, que também foram listados aqui:

arrayBuffer(), que retorna uma promessa que resolve como um ArrayBuffer.
blob(), que retorna uma promessa que resolve como um blob.
formData(), que retorna uma promessa que resolve como um FormData.
json(), que retorna uma promessa que resolve com o resultado do parse do texto do corpo como JSON.
text(), que retorna uma promessa que resolve com um texto (USVString).

No seu caso, como você está lidando com APIs que retornam um JSON, é mais interessante trabalhar com o json para converter o corpo da resposta em um texto com o JSON "parseado".
Então, ficamos assim:

async function fetchJSON(...params) {
  // Aqui, `resolvedResponse` será um objeto `Response`, que veio da
  // resolução da promessa que o `fetch` retorna.
  const resolvedResponse = await fetch(...params);

  // Abaixo estamos usando o método `json`, presente no objeto `Response`
  // para obter o texto do corpo da resposta e já convertê-lo em JSON:
  const json = await resolvedResponse.json();

  // Podemos retornar o JSON.
  // Agora SIM! É o JSON retornado pela API! ;)
  return json;
}

(async () => {
  const json = await fetchJSON('https://api.github.com/users/lffg');

  console.log(json instanceof Response); // false

  // Notamos abaixo que agora sim se trata de um JSON.
  console.log(json.login); // "lffg"
})();

Podemos até transformar esse workflow em um simples diagrama:
Comment: Caraca que massa! Obrigado, Luiz. Mas ainda tenho uma dúvida. Pelo que vejo, eu tenho que fazer a "requisição principal" que é no endpoint da API, no caso: https://api.github.com/users/lffg, e, como eu preciso dos dados em json, eu novamente uso o await pra retornar o json em si, await response.json() Quando faço isso, eu novamente estou fazer outra requisição naquela API ou esse json ja está dentro do primeiro Response recebido? A pergunta é justamente por conta disso, terei que fazer 2 rquests a API pra obter de fato os dados que preciso?
Comment: Não. Somente o fetch faz a requisição. O json só é usado para "transformar" o corpo da resposta em JSON. :)
Comment: Ahh, agora faz sentido, perdão a "nubisse" hahaha, muito obrigado, Luiz! +50
Answer: Faltou tratar o recebimento:

async function getUserGithub() {
  await fetch(`https://api.github.com/users/decarvalholucas`).then(function(response) {
      response.json().then(function(data){
          console.log(data);
        });
    });
}
getUserGithub()

Retorno assíncrono de algumas APIs


validation question for webform validate

Question: I need to validate that a field does not contain only numbers. in other words it can have some numbers but must have some letters as well. Can someone help me with the regex to do that?
I am using webforms 7.x-3.18+3 and webforms validation 7.x 1.1
thanks
Answer: Here are the steps you'll need to follow:

Go to your webform
Select the "form validation" button.
under the "Add a validation rule" select "Regular expression, case-sensitive"
For the regex, you can use ^\d*$ and check the negate rule box below

OR

Go to your webform
Select the "form validation" button.
under the "Add a validation rule" select "Regular expression, case-sensitive"
For the regex, you can use [^\d]+
Comment: Thanks! the second option worked since I didnt have the negate rule box.


Count the words using 'for' PHP

Question: #My Question
There are information like below
yes
yes
yes
yes
no
no
yes
and I want to count how many "no" are in this list.
and I wrote code using PHP.
but it doesn't work and there are any error messages.
How can I solve this problem?
#My Code
<?php

$sum = 0;
for ($i = 0 ; $i <= 7 ; $i++){

$input = fgets(STDIN);
 if($input == "no"){
 $sum++;
  }
}

echo $sum;

?>

Comment: How is your yes and no are displayed - are in an array OR string etc etc ?
Comment: You are missing the `;` off the line `$input = fgets(STDIN)`, also `fgets()` will have a newline on the end, so use `trim()` to remove this ( `if(trim($input) == "no"){` ). You should also set `$sum` to 0 before the loop.
Comment: The "quotes" here are different from the "normal" quotes that are valid in PHP
Comment: yes and no are string.
Answer: You forgot to initialise $sum variable with a value before for loop.
Place this line above your for loop:
$sum = 0;

Answer: If your data is in an array then I hope the below code will help you
$data = array("yes","yes","yes","yes","no","no","yes");
$sum = 0;

foreach($data as $arr){
    if($arr == "no"){
        $sum++;
    }
}
echo $sum;

If your data is in a different format, let know and I'll modify this code accordingly.
Comment: Thank you for answering. I confirmed using `gettype` then it was a string.
Answer: There are a few assumptions to be made here, but I think the core thing which you are missing will be that the fgets(STDIN) would be returning a string, not an iteratable.
You can get the same functionality by doing:
<?php

$i = 0;
$sum = 0;
while(($data = fget('file')) !== false || $i <= 7){
   $i++;
   if($data == 'No'){
     $sum++;
   }
}

Count the words using ‘for’ PHP


Sub relatórios ficam um em cima do outro

Question: Olá!Minha aplicação tem que fazer um relatório com dois sub relatórios,um deles fica em cima do outro,q é o subrelatório de conhecimentos,alguem sabe pq?
Código relatório conhecimentos:
<?xml version="1.0" encoding="UTF-8"?>

<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="SubCo" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="842" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="b13071d7-55cd-4769-a1fc-d58cb7a3c9a6">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="Servidor Far"/>
    <parameter name="numeroDocumentoCobranca" class="java.lang.Double"/>
    <queryString>
        <![CDATA[SELECT numero_conhecimento,serie_conhecimento,data_emissao_conhecimento,valor_frete FROM ph161169_fatura_pagar WHERE numero_documento_cobranca = $P{numeroDocumentoCobranca}]]>
    </queryString>
    <field name="serie_conhecimento" class="java.lang.Double"/>
    <field name="numero_conhecimento" class="java.lang.Double"/>
    <field name="data_emissao_conhecimento" class="java.util.Date"/>
    <field name="valor_frete" class="java.lang.String"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="53" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="10" width="160" height="30" uuid="0d28e896-3ec6-47a2-9688-235b65e66ba3"/>
                <textElement>

                </textElement>
                <text><![CDATA[Notas Fiscais]]></text>
            </staticText>
        </band>
    </title>
    <columnHeader>
        <band height="40" splitType="Stretch">
            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.FreeLayout"/>
            <staticText>
                <reportElement x="0" y="0" width="142" height="40" uuid="33c16c28-f3ad-4372-a47d-9dd59cc01735">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <text><![CDATA[Série:]]></text>
            </staticText>
            <staticText>
                <reportElement x="142" y="0" width="140" height="40" uuid="b263fdf0-142a-493d-8db0-b546b2d40cf3">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <text><![CDATA[Número:]]></text>
            </staticText>
            <staticText>
                <reportElement x="282" y="0" width="140" height="40" uuid="c04244bd-420d-4b65-9734-a8bac3e17300">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <text><![CDATA[Data Emissão:]]></text>
            </staticText>
            <staticText>
                <reportElement x="562" y="0" width="140" height="40" uuid="d45efca9-5d54-4556-bab9-18036b2240d5">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <text><![CDATA[Valor frete:]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="51" splitType="Stretch">
            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.FreeLayout"/>
            <textField>
                <reportElement x="0" y="0" width="142" height="51" uuid="5fdaa9f0-9973-4668-b946-1c756439bdd0">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <textFieldExpression><![CDATA[$F{serie_conhecimento}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="142" y="0" width="140" height="51" uuid="092b57e7-2f7c-4686-8462-347c62839e8d">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <textFieldExpression><![CDATA[$F{numero_conhecimento}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="282" y="0" width="140" height="51" uuid="381c9f77-6a2e-4549-9dc2-5d14d9948210">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <textFieldExpression><![CDATA[$F{data_emissao_conhecimento}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="562" y="0" width="140" height="51" uuid="4bd6547a-72e2-4ee8-94ed-7d3104b9e818">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <textFieldExpression><![CDATA[$F{valor_frete}]]></textFieldExpression>
            </textField>
        </band>
    </detail>

        <band height="42" splitType="Stretch"/>

</jasperReport>

Código relatório principal:
<?xml version="1.0" encoding="UTF-8"?>

<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="SubCo" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="842" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="b13071d7-55cd-4769-a1fc-d58cb7a3c9a6">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="Servidor Far"/>
    <parameter name="numeroDocumentoCobranca" class="java.lang.Double"/>
    <queryString>
        <![CDATA[SELECT numero_conhecimento,serie_conhecimento,data_emissao_conhecimento,valor_frete FROM ph161169_fatura_pagar WHERE numero_documento_cobranca = $P{numeroDocumentoCobranca}]]>
    </queryString>
    <field name="serie_conhecimento" class="java.lang.Double"/>
    <field name="numero_conhecimento" class="java.lang.Double"/>
    <field name="data_emissao_conhecimento" class="java.util.Date"/>
    <field name="valor_frete" class="java.lang.String"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="53" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="10" width="160" height="30" uuid="0d28e896-3ec6-47a2-9688-235b65e66ba3"/>
                <textElement>

                </textElement>
                <text><![CDATA[Notas Fiscais]]></text>
            </staticText>
        </band>
    </title>
    <columnHeader>
        <band height="40" splitType="Stretch">
            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.FreeLayout"/>
            <staticText>
                <reportElement x="0" y="0" width="142" height="40" uuid="33c16c28-f3ad-4372-a47d-9dd59cc01735">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <text><![CDATA[Série:]]></text>
            </staticText>
            <staticText>
                <reportElement x="142" y="0" width="140" height="40" uuid="b263fdf0-142a-493d-8db0-b546b2d40cf3">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <text><![CDATA[Número:]]></text>
            </staticText>
            <staticText>
                <reportElement x="282" y="0" width="140" height="40" uuid="c04244bd-420d-4b65-9734-a8bac3e17300">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <text><![CDATA[Data Emissão:]]></text>
            </staticText>
            <staticText>
                <reportElement x="562" y="0" width="140" height="40" uuid="d45efca9-5d54-4556-bab9-18036b2240d5">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <text><![CDATA[Valor frete:]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="51" splitType="Stretch">
            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.FreeLayout"/>
            <textField>
                <reportElement x="0" y="0" width="142" height="51" uuid="5fdaa9f0-9973-4668-b946-1c756439bdd0">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <textFieldExpression><![CDATA[$F{serie_conhecimento}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="142" y="0" width="140" height="51" uuid="092b57e7-2f7c-4686-8462-347c62839e8d">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <textFieldExpression><![CDATA[$F{numero_conhecimento}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="282" y="0" width="140" height="51" uuid="381c9f77-6a2e-4549-9dc2-5d14d9948210">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <textFieldExpression><![CDATA[$F{data_emissao_conhecimento}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="562" y="0" width="140" height="51" uuid="4bd6547a-72e2-4ee8-94ed-7d3104b9e818">
                    <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="eb31812e-f740-4b5a-b134-42877ad91ba3"/>
                </reportElement>
                <textElement>

                </textElement>
                <textFieldExpression><![CDATA[$F{valor_frete}]]></textFieldExpression>
            </textField>
        </band>
    </detail>

        <band height="42" splitType="Stretch"/>

</jasperReport>

A pagina fica assim,todos os dados misturados.
Answer: Ola voce precisa marcar no posicionamento do subreport que esta em baixo como flow, para que ele possa flutuar livremente sem ficar por cima do primeiro subreport
Answer: Pode ser dois motivos, dentro do Jasper o subreport deve estar como float;
inserir a descrição da imagem aqui
Tambem deve se atender a tag "y", veja que neste exemplo tenho 3 subreports;
<band height="66" splitType="Stretch">
        <subreport>
            <reportElement positionType="Float" x="1" y="0" width="553" height="20" uuid="dcb4de43-b64f-4e50-a4b1-5ad31a1cd9a2"/>
            <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("carga.ordens")]]></dataSourceExpression>
            <subreportExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportExpression>
        </subreport>
        <subreport>
            <reportElement positionType="Float" x="1" y="20" width="553" height="20" uuid="dcb4de43-b64f-4e50-a4b1-5ad31a1cd9a2"/>
            <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("carga.ordens.itens")]]></dataSourceExpression>
            <subreportExpression><![CDATA[$P{SUBREPORT_DIR1}]]></subreportExpression>
        </subreport>
        <subreport>
            <reportElement positionType="Float" x="1" y="40" width="553" height="20" uuid="dcb4de43-b64f-4e50-a4b1-5ad31a1cd9a2"/>
            <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("carga.ordens.pedidos")]]></dataSourceExpression>
            <subreportExpression><![CDATA[$P{SUBREPORT_DIR2}]]></subreportExpression>
        </subreport>
    </band>


Como obter uma string de um json?

Question: Estou desenvolvendo uma aplicação e preciso salvar numa variável de tipo string o que vem no json do servidor.

 export class InicioPage {

  users : any[];
  vaga  : any[];
  nomes : boolean = true;
  elementType : 'url' | 'canvas' | 'img' = 'url';
  value; //= 'Código gerado';
  constructor(public navCtrl: NavController,
              private alertCtrl: AlertController,
              public service : ServiceProviderInicio,
              //public service1 : ServiceProvider

            ) {
    this.value = {};
  }

  ngOnInit() {
           this.getVaga();
           this.getDados();
     }

  /*  getDados() {
     //retorno de Dados
     this.service.getData()
           .subscribe(
                 data=> this.users = data
                 ,err=> console.log(err)
           );
     }*/

     getDados() {
     //retorno de Dados
     this.service.getData()
           .subscribe(
                 data=> this.users = data
                 ,err=> console.log(err)
           );
     }
}

Trecho que realiza requisição no banco de dados.

@Injectable()
export class ServiceProviderInicio {

      api : string = 'http://localhost:80/APIEST/inicio/';

  constructor(public http: Http) {}
      getData() {
            return this.http.get(this.api + 'apiRecuperaInicio.php').map(res=>res.json())
      }
}

E consulta no servidor.

<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html; charset=utf-8');
//recupera login usuario

$dns = "mysql:host=localhost;dbname=estacionamentobd";
$user = "root";
$pass = "";
//aqui

try {
    $con = new PDO($dns, $user, $pass);

    if(!$con){
        echo "Não foi possivel conectar com Banco de Dados!";
    }

    $query = $con->prepare("SELECT * FROM usuario");

        $query->execute();

        $out = "[";

        while($result = $query->fetch()){
            if ($out != "[") {
                $out .= ",";
            }
            $out .= '{"id_usuario": "'.$result["id_usuario"].'",';
            $out .= '"login": "'.$result["login"].'"}';
        }
        $out .= "]";
        echo $out;

} catch (Exception $e) {
    echo "Erro: ". $e->getMessage();
};
Comment: Em qual parte do código está sendo feita a requisição ? Teria como colocar na pergunta o código da requisição ? Pois vejo que você está chamando a função `getDados()` mas não a vejo no código.
Comment: Atualizei o post como pediu  Wellingthon. Obrigado
Answer: O que da pra fazer é getData().subscribe(res => this.value = JSON.stringify(res)).
Se foi o que eu entendi, seria isso :)

Como obter uma string de um json?


Função que retorna uma nova instância de uma classe

Question: Alguém sabe me explicar pq essa função não está retornando uma nova instância. Ela retorna um objeto monstro, exatamente como eu quero, mas quando o monstro morre, a nova instância que ele retorna volta exatamente como o monstro antigo que já foi morto.
<code>def new(self, name):
    monster = self._monsters.get(name) # Dicionário que contém todos os monstros
    instance = Monster(name=name) # Cria um novo monstro
    for attr in monster.__dict__:
        # Pega os atributos de um monstro existente o coloca na nova instância
        instance.__setattr__(attr, monster.__dict__[attr])
    return instance
</code>
Answer: olha  - o seu projeto todo - faz umas coisas estranhas pra manipular objetos - e o código não está todo aí, fui ver no github, por conta do contato que tivemos em outra pergunta - https://github.com/ThomasCaio/.RPG . E o problema é que seus monstros diferentes (com "names" diferentes, deveriam ser classes diferentes - você cria tudo como uma mesma classe,   usa instâncias para um tipo de monstro - e ainda usa um esquema de "caching" pra garantir que de fato só exista uma instância  "Monster" com o mesmo "name" de cada vez.
Como o código não está todo aqui (na questão), nem fiz a análise completa, mas provavelmente o problema que você está tendo provavelmetne está relacionado com esse approach.
(Colocar quase todo o código do projeto numa questão aqui também acho que não resolveria). Talvez até dê para achar o problema pontual aí, mas eu não achei - exceto que a chamada a MonsterFactory.add nesta linha https://github.com/ThomasCaio/.RPG/blob/9f6f38a7d10303b0bed7de434a3c279c266d57ae/rpg/units.py#L346 deveria pelo menos substituir o "monstro antigo" pelo "monstro novo".  Se você está tentando ter duas instâncias de um monstro com o mesmo "name", o problema está justamente aí,  o registro de monstros dentro do "MonsterFactory" mantém apenas um monstro de cada "name" - mas uma nova instância deveria vir com os atributos zerados normalmente.
Comment: Opa. Na verdade essa versão que tá no Github ela ainda retornava certinho a nova instância. O problema é que eu tô concertando essas coisas estranhas e tá bugando tudo. O Monster pode ter várias instâncias, só o objeto que manipula os monstros que eu deixei pra ter apenas uma instância, visto que nesse objeto estaria armazenado os monstros.
Comment: Ahh tá, achei. A classe Monster tem uma linha que adiciona o monstro no factory baseado no name e substitui o monstro antigo.


How does the Sidearm™ cricket ball thrower work?

Question: I have seen the videos where Graham Gooch is able to do easy throwdowns for batting practice - fast deliveries, slower ones, off-spinners, leg-spinners.
Can you tell me how and when the ball is released from the sidearm? Is the sidearm merely a cup holder for the ball and the ball is just flung at the batsman? (similar to a trebuchet probably?)
Or, does the sidearm clutch the ball and release it on a button press/release on the handle of the sidearm?
About Sidearm
Answer: It's essentially a cup with curved sides that provide a degree of grip to the ball.  The action of flicking the Sidearm at the batsman gives the ball enough momentum of it's own to break out of the cup and head to the batsman on it's own.  It's developed from a device used by dog owners to throw tennis balls.
Comment: No, I've seen a few around so this is just personal observation.  The cup is made of a reasonably strong plastic so I guess it would last a while but yes wear and tear would eventually reduce its effectiveness.
Comment: Do you have a source for this? And also does this mean that with wear and tear, the sidearm will get useless?


How to correctly place svg marker on google maps?

Question: I have a svg marker and want to place it on google maps via javascript api.
The problem is that marker is misaligned when I zoom out the map.
This is my svg path:

M20,13.8c0,5.5-4.4,9.3-10,14.2C4.4,23.1,0,19.3,0,13.8C0,8.4,4.5,4,10,4S20,8.4,20,13.8z

  new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(33.788303, -118.001511),
    icon: {
      path: "M20,13.8c0,5.5-4.4,9.3-10,14.2C4.4,23.1,0,19.3,0,13.8C0,8.4,4.5,4,10,4S20,8.4,20,13.8z",
      fillColor: '#1193c5',
      fillOpacity: 1,
      strokeWeight: 1,
      strokeColor: 'black'
    }
  });

From what I've already researched I need to set an anchor for the marker but I have no idea how to find anchor point for this svg path.
Here is a working example: https://jsbin.com/gonehocafu/edit?html,js,output
Answer: It is calculable if you know the size of the icon. The path origin for your icon is the upper left hand corner, to get to the middle of the bottom, set x equal to 1/2 the width of the icon, y equal the height of the icon.  For a SVG symbol:

anchor | Type:  Point
The position of the symbol relative to the marker or polyline. The coordinates of the symbol's path are translated left and up by the anchor's x and y coordinates respectively. By default, a symbol is anchored at (0, 0). The position is expressed in the same coordinate system as the symbol's path.

I usually use trial and error.  For your icon looks like what works is:
anchor: new google.maps.Point(10, 27)

proof of concept fiddle
code snippet:

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(33.788303, -118.001511),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(33.788303, -118.001511),
    icon: {
      path: "M20,13.8c0,5.5-4.4,9.3-10,14.2C4.4,23.1,0,19.3,0,13.8C0,8.4,4.5,4,10,4S20,8.4,20,13.8z",
      fillColor: '#1193c5',
      fillOpacity: 1,
      strokeWeight: 1,
      strokeColor: 'black',
      anchor: new google.maps.Point(10, 27)
    },
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}


How to change the user registration form markup

Question: I want to change the markup on the user registration form that reads

Spaces are allowed; punctuation is not allowed except for periods,
  hyphens, apostrophes, and underscores.

and

A valid e-mail address. All e-mails from the system will be sent to
  this address. The e-mail address is not made public and will only be
  used if you wish to receive a new password or wish to receive certain
  news or notifications by e-mail.

to something more friendly.
I don't think String Overrides works with the registration form so I guess I need a custom module - hook_form_alter perhaps?
Comment: Yes, `hook_form_alter()` is the right option
Comment: Thanks - but I am not sure how to target the markup?
Comment: Off the top of my head it'll be in something like `$form['account']['name']['#description']`, but if you install the Devel module and use `dpm($form);` in your alter hook, you should be able to find it easily. If not just update the question, it'll be something easily solved
Answer: You can do that by implementing hook_form_alter() in your custom module:
For ex:
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form') {
    //dpm($form);
    $form['account']['name']['#description'] = t('Your Custom Text');
  }
}

To add Markup you should look into theme_form_element.
Answer: The strings you want to change are the strings used for the #description properties of the name and mail form fields.
  // Only show name field on registration form or user can change own username.
  $form['account']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
    '#required' => TRUE,
    '#attributes' => array(
      'class' => array(
        'username',
      ),
    ),
    '#default_value' => !$register ? $account->name : '',
    '#access' => $register || $user->uid == $account->uid && user_access('change own username') || $admin,
    '#weight' => -10,
  );
  $form['account']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
    '#default_value' => !$register ? $account->mail : '',
  );

You could change those strings by using the String Overrides module (which works for every string passed to t(), as in this case), implementing hook_form_FORM_ID_alter() in a module, or implementing hook_form_alter().
In the first case, the module would replace every occurrence of the strings, while in the other two cases the strings would be replaced just in a specific form or when other conditions are verified. Since you seem to want to change those strings only when users register their account, I would use hook_form_FORM_ID_alter().
As there users who have the permission to change their own usernames, which means the username is not set when an account is created, I would use code similar to the following one.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  if ($form_id == 'user_register_form' || ($form_id == 'user_profile_form' && isset($form['#user_category']) && $form['#user_category'] == 'account')) {
    // The user is creating a new account or editing an existing account.
    if (isset($form_state['user']) && $form_state['user']->uid == $user->uid) {
      // The user is creating or editing their own account.
      $form['account']['name']['#description'] = t('Your new description for the name field');
      $form['account']['mail']['#description'] = t('Your new description for the mail field');
    }
  }
}

In this way, users who can edit accounts of other users (users with administrative permissions) would see the default description given from Drupal.
Answer: There is also the Better Login module which can speed things along for you.

Fancy login forms for Drupal :).
Styling Drupal login/password/registration forms are a mission most of
  the time because they form part of the theme... This module removes
  that issue, it is slightly inspired by the way Wordpress login forms
  work, and uses three page templates to change the style of the forms.
  It is very simple to use, just install the Better Login module and it
  starts working immediately.


Let $x$, $y$, and $z$ be real numbers such that $x^2 + y^2 + z^2 = 1.$ Find the maximum value of $9x+12y+8z.$

Question: Let $x$, $y$, and $z$ be real numbers such that $x^2 + y^2 + z^2 = 1.$ Find the maximum value of $9x+12y+8z.$

We aren't given anything other than what $x^2+y^2+z^2$ is.  How can I manipulate that equation into something useful?  I'm stuck.  Any solutions are highly appreciated.
Answer: By the Cauchy-Schwarz inequality
$$9x+12y+8z \color{red}\leq \sqrt{9^2+12^2+8^2}\sqrt{x^2+y^2+z^2} = \color{red}{17} $$
and equality is achieved at $(x,y,z)=\frac{1}{17}\left(9,12,8\right).$
Comment: Very nice. I was thinking of Lagrange multipliers, but yours is much better.


Do infinite state Markov chains have eigenvalues?

Question: A few days ago, I saw a post showing how the stationary distribution of an infinite-state Markov chain can be computed. Since for a finite-state Markov chain, we can solve its eigenvalue equation to get the stationary distribution (which is an eigenvector), I'm wondering if we can also solve for eigenvalues/eigenvectors for an infinite-state Markov chain. If so, how is it different from solving the eigenvalue equation from a finite-state case? If not, is there a way that we could assess the mixing time for an infinite-state Markov chain? (For a finite-state case, we can just calculate the spectral gap.)
Answer: You can't really do much with an infinite-state Markov chain in general, but in some cases you can express the eigenvalue equation as a recurrence and solve that.


Setting uploadReadAheadSize in IIS 8.5

Question: I'm trying to use the following command to set uploadReadAheadSize in IIS 8.5 on Windows Server 2012 R2:
appcmd.exe set config -section:system.webServer/serverRuntime/uploadReadAheadSize:"491521"  /commit:apphost

But I keep getting this error:
ERROR ( message:Can not set attribute "uploadReadAheadSize" to value "491521 "..
Reason: Not a valid unsigned integer . )

From this page the maximum should be 4GB so my integer is valid. (Admittedly this goes back to IIS 6.0 so not sure how relevant it is now.)
This page on the other hand suggests that the property may have been replaced/deprecated or something, but it's not clear from the error message or anything I can find on the Googles.
I'm no expert in IIS so there may be a simple/obvious answer to this, but I'd be grateful if anyone can share some more concrete info...
UPDATE: also posted in IIS forums
Answer:
Open IIS
Navigate under Default Web Site
Scroll down to Management and open Configuration Editor
Select following section (drop down at the top) system.webServer and expand it, then locate serverRuntime
you'll find there the current value of uploadReadAheadSize value, which you can change
Answer: Four years later... The clue was in the error message: "491521 " is not a valid unsigned integer. Note the space at the end of the integer before the quote marks.
Turns out the command I was running had a double space between the value and the /commit. Change to a single space and the command works fine.
Interestingly it's the same command I've been using for years and I've just confirmed it still works fine with the double space in Server 2008 R2!
Answer: How to set the maxAllowedContentLength to 500MB while running on IIS7?
Try this.  Looks like you need to set it below 4294967295(in bytes)
Comment: Don't post links to solutions, post the solution. Links go dead.
Comment: Vikrant, my integer is 491521. As I said, it should be below the limit already.
Comment: 4294967294 is invalid. Instead, 2147483647 (int.max) is accepted. Just shy of 2gb.
Answer: Try this:
appcmd.exe set config  -section:system.webServer/serverRuntime /uploadReadAheadSize:"491521" /commit:apphost

There must be a space after -section:system.webServer/serverRuntime and before /uploadReadAheadSize .
Answer: WebServer Run Time
POWERSHELL Command
Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST'  -filter "system.webServer/serverRuntime" -name "uploadReadAheadSize" -value 2147483647

uploadReadAheadSize Optional uint attribute.

Specifies the number of bytes that a Web server will read into a buffer and pass to an ISAPI extension or module. This occurs once per client request. The ISAPI extension or module receives any additional data directly from the client. The value must be between 0 and 2147483647.
The default value is 49152.

Setting uploadReadAheadSize in IIS 8.5


Checking a binary number is OK

Question: In connection with a problem I'm solving, I need to check if a binary number with $n$ digits is of a certain form. The number is OK if:

It is all $0$'s
The first digit is $1$ and the rest $0$'s
The first 2 digits are $1$'s and the rest $0$'s
The first 3 digits are $1$'s and the rest $0$'s
Etc

Is there a quick way to determine that a number is of this form? I.e. without having to check each digit, starting from the front?
Answer: A nonzero number is of the required form if and only if flipping the bits and adding $1$ results in a number with exactly one $1$ bit. Assuming that you are not using some antique computer, flipping the bits and adding $1$ is the same as negating the number.  Now there is a quick way of testing whether a number has exactly one $1$ bit.  Subtract $1$ and do a bitwise and with the original number.  The result is $0$ if and only if the original number had exactly one one bit.
The above operation (x &= x-1 in python) works because subtracting 1 replaces the rightmost $1$ by a $0$, the $0$s to it right by $1$1, and leaves all bits to the left unchanged.  Therefore, the operation zeroes the rightmost $1$ bit.
EDIT Actually, the operation works for $0$ also, so you don't even have to test a special case.  In python you just need
if x & (x-1) == 0: whatever

Just to clarify, in the above, $x$ is the negative of the number you started with.  In actual code, you'd probably use
if -x & (-x-1) == 0: whatever

Comment: Thanks! Exactly what I was looking for.
Comment: @Jens It was my pleasure.
Comment: This works if $n$ is the number of bits in the integer type of `x`. If $n=5$ (for example) this approach doesn't work on any ordinary computer. I suppose it can be modified to work for $n$ smaller than the word size, however.
Comment: If $n=5,$ instead of `-x` use `32-x`, because $32=2^5.$ In general the formula is $2^n-x.$
Answer: Do a binary search. Check if number formed by first $\lfloor \frac{n}{2} \rfloor$ digits is equal to 1s etc. If the number is lesser or greater you split and proceed. Stop if you cannot split any more -- number is not of required form. Complexity should be of the order of log(n).
Answer: Your numbers are of the form $2^{n-1}-2^k$ for some $k$ between $0$ and $n-1$.  The first is the $k=n-1$ case, the $n^{th}$ is the $k=0$ case.  You can just check if your number is equal to any of these.  Of course, that is $n$ checks, which is the same number as if you just check the bits.
Comment: Don't know why this was downvoted. I'm giving you a (+1) to compensate, not least because you answered my first question ever on MSE :)
Answer: An OK number is of the form $(2^m-1)2^n$.
Divide the number by two until you get a remainder. You now have $2^m-1$.
Add one. You now have $2^m$.
Divide by two until you get a remainder. You now have $1$.
If the final value is not one, your original number's not OK.
If you precede the original number with a $1$, this will work for the all zeros case as well.
Answer: A simpler way of putting it is that it is a string of $k; 0\le k$ ones followed by $m; 0 \le m$ zeros.
A number $x$ followed by $m$ zeros is $x*2^m$.
A number $x=$ a string of $k$ ones is $2^k -1$.
So you want numbers of the form $(2^k - 1)*2^m$.
Divide by two successively until you either get to $0$ or get to a point where you have a remainder.  If you get to $0$ it is of the form.  If you get a remainder then divide by subtract $1$ and divide by $0$ successively until you either get to $0$ or get to a point where you don't have a remainder.  If you get to $0$ it is of the form.  If you get to a point where you don't have a remainder it is not of the form.

Checking a binary number is OK


Maximum value of a function. I am not able to check double derivative.

Question: Can someone explain me how $\sin^p x \cos^q x$ attains maximum at $\tan^2 x = \frac pq$.
I am not able to check whether double derivative is positive or negative.

Question
Show that $$\sin^p\theta\cos^q\theta$$ attains a maximum when $$\theta=\tan^{-1}\sqrt{(p/q)}$$
Solution
Ley $y=\sin^p\theta\cos^q\theta$. For a maximum or minimum of $y$, we have $\frac{\text dy}{\text dx}=0$
\begin{align}p\sin^{p-1}\theta\cos^{q+1}\theta-q\sin^{p+1}\theta\cos^{q-1}\theta&=0\\
\sin^{p-1}\theta\cos^{q-1}\theta(p\cos^2\theta-q\sin^2\theta)&=0\end{align}
Therefore \begin{align}\sin\theta&=0\\
&\Downarrow\\
\theta&=0\\
\text{or } \cos\theta&=0\\
&\Downarrow\\
\theta&=\frac \pi 2\\
\text{or }\tan^2\theta&=\frac pq\\
&\Downarrow\\
\theta&=\tan^{-1}\sqrt{p/q}\end{align}
Now $y=0$ at $\theta=0$ and also at $\theta=\frac\pi2$
When $0<\theta<\frac\pi2$, $y$ is positive
Also, $\tan^{-1}\sqrt{p/q}$ is the only value of $\theta$ lying between $0$ and $\frac \pi2$ at which $\frac{\text d}{\text dx}=0$.
Hence $y$ is maximum when $$\theta=\tan^{-1}\sqrt{p/q}$$
This can be seen from the graph of $y$
Comment: Differential Calculus by Krishna Series from India.
Comment: Please don't post pictures containing your entire question. Pictures don't load on some devices, can take a long time to load on others, and are not searchable on the site. See [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for a tutorial on how to typset Maths on this site
Comment: That is a cool problem. What book is it from?
Answer: This is a nice application of logarithmic differentiation.
Consider $$f=\sin^p(x) \cos^q(x)\implies \log(f)=p \log(\sin(x))+q  \log(\cos(x))$$ Differentiate both sides $$\frac{f'}f=p \cot(x)-q \tan(x)=\frac{p-q \tan^2(x)}{\tan(x)}$$ and then the conditions for an extremum as already given in answers.
But, we need to check the second derivative : start with $$f'=f \left(\frac{f'}f \right)$$ and differentiate using the product rule $$f''=f'\left(\frac{f'}f\right)+f \left(\frac{f'}f \right)'$$ But, at the extremum $f'=0$ which reduces the problem to the sign of $$f \left(\frac{f'}f \right)'=-f\,(p \csc ^2(x)+q \sec ^2(x))$$
Edit
If you want to continue with some fun, using $$\sin(\tan^{-1}(t))=\frac{t}{\sqrt{t^2+1}}\qquad \cos(\tan^{-1}(t))=\frac{1}{\sqrt{t^2+1}}$$ and replacing $t$ by $\sqrt{\frac{p}{q}}$ the maximum value of $f$ is given by $$f_{max}=\sqrt{\frac{p^p \, q^q}{(p+q)^{(p+q)}}}$$
As said in comments, this works for any value of $p>0$, $q>0$, $p$ and $q$ being integers, rational or non rational numbers.
Considering the case where $p+q=k$, using again logarithmic differentiation we should find that $$\frac{f'_{max}}{f_{max}}=\frac 12 \log \left(\frac{p}{k-p}\right)$$ which is positive if $p>\frac k 2$ and negative otherwise.
Comment: This method is amazing. Thanks a lot.
Comment: Showed this solution to my instructor. He felt quite impressed. Thank you
Comment: @HoLyDeViL. and guess what ? It works even for non integer values of $p$ and/or $q$. Just for the fun, use Wolfram Alpha with $p=\pi$ and $q=e$. It works just like a charm ! Cheers.
Comment: Wow.That's cool. It's working.
Answer: Your picture shows a proof that $f'(x)=0$ at $x=x_0=\arctan\sqrt{p/q}$.
As $p$, $q\ge1$, $0<x_0<\pi/2$. Think of the graph of $f$ on $(0,\pi/2)$:
$f(0)=f(\pi/2)=0$ and $f(x)>0$ if $0<x<\pi/2$. Then $f$ certainly has
a maximum in the open interval $(0,\pi/2)$. But the calculation
in the picture shows the only turning point is at $x_0$. So $f$
has a maximum at $x_0$. You don't need to consider $f''(x_0)$.
Comment: Thanks a lot. Now I got it.
Comment: Did I miss something?  The original function didn't require `p` and `q` to be any particular value.  Does your approach work for, say ,  $p = -3 $ and $q = 0.256$  ?
Comment: I think p, q should be greater than one, Otherwise we don't end up values like 0,  π/2.
Answer: When you want to maximize $Sin^p x Cos^q x$ you can equally maximize $Sin^{2p} x Cos^{2q} x$ so ,suppose we need to maximize $$f=Sin^{2p} x Cos^{2q} x=\\
(Sin^2 x)^ (Cos^2x)^q $$
we know $$sin^2x+cos^2x=1 $$ so ,put down $cos^2x=1-sin^2x$ in $f$
$$f=(Sin^2 x)^p (Cos^2x)^q=(Sin^2 x)^p (1-in^2x)^q=X^pY^q$$with $$X+Y=1$$ now ,take f'
$$f=X^p(1-X)^q \to \\f'=pX^{p-1}(1-X)^{q}-qX^{p}(1-X)^{q-1}=0\\
X^{p-1}(1-X)^{q-1}(p(1-X)-qX)=0\\$$form here $$X=0,1,\frac{p}{p+q}$$
$0,1$ does not make maximum $f(0)=0,f(1)=0$ so $f(\frac{p}{p+q})$ is max,
when you return to begining ,you will see $$X=sin^2 x=\frac{p}{p+q}$$ so find $$cos^2x=1-X=1-\frac{p}{p+q}=\frac{q}{p+q}$$ and finally $$tan^2x=\frac{sin^2x}{cos^2x}=\frac{\frac{p}{p+q}}{\frac{q}{p+q}}=\frac{p}{q}$$
Comment: Wow. First question I have posted on this website. Great to see number methods followed by by all to solve this problem. Hmmm. It's fantastic.
Answer: You don't have to check the second derivate. What you use is:
$$y(0) = \sin^p(0)\cos^q(0) = 0$$
$$y(\pi/4) = \sin^p(\pi/4)\cos^q(pi/4) = 2^{-p/2-q/2} > 0$$
$$y(\pi/2) = \sin^p(\pi/2)\cos^q(pi/2) = 0$$
So you see that $y$ must have a maximum for some $c\in[0,\pi]$ and it has to be at least $2^{-(p+q)/2}>0$ so it's not at the end points which means that $y'(c) = 0$ and there's only one point where this holds so there must be the maximum.
Answer: For simplicity, I'll assume that both $p$ and $q$ are at least 1.  (Note that if $q = -1$ and $p = 1$, then your function is $\tan x$ and does not have a maximum!)
You first take the derivative,
$$ p\sin^{p-1} x\cos^{q+1}x - q\sin^{p+1}x\cos^{q-1}x = sin^{p-1}x\cos^{q-1}x(p\cos^{2}x - q\sin^{2}x).$$
Setting the last part equal to zero, we have that either
$\sin^{p-1}x = 0$, $\cos^{q-1}x = 0$ or $\tan^{2}x = \frac{p}{q}$.
It follows that the inputs that satisfy $\sin^{p-1}x = 0$ and $\cos^{q-1}x = 0$ do not yield a maximum.  (With this input, your output for the function would be zero and there are inputs that yield positive values.)
So we are left with $\tan^{2}x = \frac{p}{q}$.
Since we have the theorem that if an input is a local maximizer, it must be a critical point, and we ruled out the other cases, then the local maximizer must be a solution to the above equation.  (Note that it is possible that there are solutions to the above equation that are not maximizers.)
Finally, invoking the fact that your function is periodic allows us to say that the local maximizer is a global maximizer.
Answer: Let $f(x) = \sin^{p}(x) \, \cos^{q}(x)$ then
\begin{align}
f'(x) &= f(x) \, (-q \, \tan(x) + p \, \cot(x)) \\
&= -q \, \cot(x) \, f(x) \, \left( \tan^{2}(x) - \frac{p}{q} \right)
\end{align}
Now, the maximum of a function is defined by $f'(x) = 0$ then, seeking values other than $f(x) = 0$,
$$\tan^{2}(x) = \frac{p}{q}$$
or
$$x_{max} = \tan^{-1}\left(\sqrt{\frac{p}{q}}\right).$$


Django forms: How do I make it necessary to fill out one field but not possible to fill out both?

Question: I want to have an option to link to a file OR upload a file. Obviously you can't do both. How can I implement this?
Answer: Take a look at the Django docs about the clean function for cleaning and validating fields that depend on each other.
You can then, inside the clean, do a check for the values of the two fields.
Something along these lines:
from django import forms
from django.core.exceptions import ValidationError

class MyForm(forms.Form):

    field_1 = forms.CharField(required=False)

    field_2 = forms.CharField(required=False)

    def clean(self):

        # Get the field values submitted
        cleaned_data = super(MyForm, self).clean()
        field_1_data = cleaned_data.get('field_1')
        field_2_data = cleaned_data.get('field_2')

        # Check that only one field is filled out.
        if field_1_data and field_2_data:
            raise ValidationError('Only fill out one field please.', code='invalid')


Infinite matrix product

Question: Let
$$X=\left(\begin{array}{c} x_1 \\ x_2\\ \vdots \end{array}\right)$$
be an infinite real vector and
$$A=(a_{ij}), \ 0<i,j<\infty$$
be an infinite real matrix.
(1) For which $A$ can one define multiplication $AX$ on the space $\mathbb{R}^\infty$ of all infinite real vectors?
(2) What if we restrict $X$ to $Z=\{ X\in \mathbb{R}^\infty| x_n=0 \text{ for all but finitely many }n\}$
My answer is
(1) $A$ must be such that for all $i$, $a_{ij}=0$ for all but finitely many $j$.
(2) It is well defined for all $A=(a_{ij}), \ 0<i,j<\infty$
Is that correct?
Comment: In (1) - is with "all infinite real vectors" meant: any arbitrary vector X ? And why/for what purpose in this question A is a matrix and not only a row-vector?
Answer: Basically yes, you can define an infinite matrix-times-column product provided each matrix row is finitely supported, or (without restricting the matrix) when the column vector is finitely supported.
Of course with "can one define" questions, it will sometimes be possible to stretch the domain of application by restricting what one requires from a definition. In this case one could in principle allow some cases to be defined provided all the infinite sums that arise in the usual definition converge in some sense. I'm not sure how many useful properties the result would have; in any case it is not in the spirit of abstract (exact) algebra to let analysis thus penetrate into the basic definitions. (But of course, one can look at things like Hilbert spaces where such things can be done meaningfully.)

Infinite matrix product


Angular UI Bootstrap Typeahead directive creates a different DOM element for every instance

Question: I am trying to use the  Angular UI Bootstrap Typeahead directive in a few tables. These tables could have 0 to thousands of entries in them and when I attach the typeahead directive to each <input> in my table rows, it creates a DOM element for each one!
If I inspect the DOM after the page loads, I can see hundreds of  on the body of my HTML. The thing is, all of these typeaheads use the same source list to supply the typeahead with it's data, so techincally I should only need 1 typeahead element that is just re-used on each input in my tables.
Currently, I do not see a configuration attribute on the typeahead documentation that allows us to create 1 shared typeahead element.  Is there any way to easily get this functionality to work without altering the angular bootstrap javascript myself or without building the typeahead directive from scratch?
EDIT
To make things even worst, I have pagination on my tables and if you change between "pages" of the tables, the directive re-creates more  for every new instance of that page. Therefore, if the table starts out with 100 items per page out of 10 pages, if the user clicks on each page of the pagination at a time, they will end up with 1000  on the page.
Comment: So by changing it so we don't append the typeahead to the body, now it will not create more typeahead elements with each pagination page change, but there is still a unique typeahead for each row in the table and any given time.
Answer: Implement some kind of view/edit state transition on the cell that contains the typeahead directive.
Use something like an ng-if="row.isEditing" on the input with the typeahead directive. As-is, your table is going to create a DOM element for every row unless you tell it not to. When you click into the cell to edit, then change the edit mode state, and the DOM element for the typeahead will be loaded on-demand.
This plunker is (somewhat) like the approach I have in mind, but it implements a whole edit row instead: http://plnkr.co/edit/ivJQ0C
Notice in that example that the DOM element for the edit row does not exist until the condition of the ng-if is met.


Como especificar uma cor em HEXA no MSPaint?

Question: Boa tarde,
É possível especificar uma cor em HEXA no MSPaint? Como faço?
Grato.
Answer: O MS PAINT só aceitar RGB, você terá que converter de RGB para HEXA.
Comment: Muito obrigado!


What is this musical symbol?

Question:
First I thought it was a weird flat sign, but when I played the score it sounded odd. It looks a bit like a natural sign.
Here's the whole measure:
Comment: The notes partially look like handwritten. Is this the case? If so, could it be the writer's way to write a quarter rest?
Comment: They do look like natural signs, but it is hard to tell out of context. Would natural signs make sense there? Can you post a picture of the whole measure?
Comment: Who is the composer, and can you get in touch with them?
Comment: @CarlWitthoft definitely not. It's Bernard Herrmann
Comment: if it's a flat sign, I may have been confused by the shape the composer used in the bass line @Peter
Comment: OK, well,...  any chance of finding a published copy of the score?
Comment: @CarlWitthoft as far as I know it was never published
Answer: Looks like a handwritten natural sign to me.  The context doesn't suggest any other possibilities
Comment: Strangely, the first natural sign in the lower desk looks different.  But for handwritten, not to mention the resultant harmony,  flat sign is almost certainly wrong.
Comment: I don't think there are any other feasible options!+1. And Bernard knew a thing or two.
Comment: Yep, the only plausible possibility.
Comment: Yes.  I'm surprised there have been other opinions!

What is this musical symbol?


update datasource used for Amazon machine learning ML model

Question: I am using an amazon machine learning for creating ML models for my applications. I have created a datasource and also ML model corresponding to that datasource, however in my application new data always keeps getting added so I have to update the data file in s3 which in turn used by the datasource. So the question is how can I update the datasource corresponding to that data file without changing the datasource id and also how to update the ML model corresponding to that datasource without changing the ML model id?
I know that there are methods in Boto3 to update datasource or ML model however as far as I know it only updates the name of those objects.
Any help would be appreciated.
Answer: You cannot do that. Amazon ML datasources are immutable, save for the human-readable name attribute. Instead, when you have new data, create a new datasource that points at the same data file(s) in S3, and then train a new ML model using that datasource.
Comment: thanks for the response and yeah ultimately thats what i will have to do i guess


Views Load More: Showing X number of item initially

Question: I have a view which shows 6 items per page using Views Load More (Ajax). However what I would like to do is, on the very first page I would like to show 6 items and when clicked on Load More button it should show 3 items and so on. Is it possible?
Comment: that would be a nice feature, can't say I've come across anything that would let you do that though. If there's nothing out there already you could always write a custom pager plugin
Answer: Well you could use this workaround.
Have a view with the initial 3 (#1-3). Then add another view below it with an offset of 3, so it shows #4-6. Thus, it will load 3 rows at a time.
You could just show the views back to back on the page or you could use the Insert View module, and have it load the #1-3 view at the header of the 2nd view.


Javascript onload in sugarcrm

Question: I am currently customizing a SugarCRM instance. In one module I have created a few custom fields and a drop down menu. Based on the selection of the drop down menu I want to show or hide some of my fields. This works fine. My question is about the initial load of the page: In that case, all possible fields are displayed - not only the ones that should be displayed based on the default selection in the drop down menu.
My first instinct was to register the onload event and just hide whatever I don't need to see when the page is loaded. But I couldn't find anywhere to place it as I don't want to change /modules/... directly. I'd like to restrict my changes to /custom/modules...
Any ideas?
Answer: Here few ways to control dropdown visibility:

There is admin when you edit field there is formula and visibility functionality you can also try this.
Create custom edit view and add javascript code in display function of view.
custom/modules//views/view..php

.php');

    class View extends View {
        function View() {
            parent::View();
        }

        function display() {
          echo '';

          parent::display();
        }

    }
?>

Custom Javascript can be added to editviewdefs.php
<code>    'templateMeta' =>
    array (
   includes' => array (
               1 =>array ('file' => 'custom/modules/<ModuleName>/js/custom.js',),
    ),
),
</code>

Javascript onload in sugarcrm


Python relative/absolute import (again)

Question: This topic has been covered several times but I still can't get my package to work.
Here is the situation: I've got a package in which a logging module takes care of setting up the logging.
So clearly, mypackage.logging conflicts with Python logging from the standard library.
The directory' structure:
├── mypackage
│   ├── __init__.py
│   ├── logging.py
└── script.py

mypackage.__init__
import logging
from . import logging as _logging

logger = logging.getLogger(__name__)

def main():
    _logging.init_logging()
    logger.info("hello")

mypackage.logging
"""logging - Setup logging for mypackage."""

import copy
import logging
import logging.config

_DEFAULT_LOGGING_CONFIG_DICT = {
    'version': 1,

    'formatters': {
        'verbose': {
            'format': '%(asctime)s - %(name)s::%(levelname)s: %(message)s',
        },
        'simple': {
            'format': '-- %(message)s',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'level': 'DEBUG',
            'formatter': 'simple',
        },
        'file': {
            'class': 'logging.FileHandler',
            'filename': 'oprpred.log',
            'mode': 'w',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'oprpred': {
            'level': 'INFO',
        },
    },
    'root': {
        'level': 'INFO',
        'handlers': ['console', 'file'],
    },
}

def init_logging(verbose=False):
    """Initialize logging.

    Set the log level to debug if verbose mode is on.
    Capture warnings.
    """
    d = default_logging_dict()
    if verbose:
        d['root']['level'] = 'DEBUG'
        d['loggers']['oprpred']['level'] = 'DEBUG'
    logging.config.dictConfig(d)
    logging.captureWarnings(True)

def default_logging_dict():
    return copy.deepcopy(_DEFAULT_LOGGING_CONFIG_DICT)

script.py
import mypackage
mypackage.main()

Finally, this is the error message I'm getting:
$ python3 script.py                                                                                [11:09:01]
Traceback (most recent call last):
  File "script.py", line 4, in <module>
    mypackage.main()
  File "/Users/benoist/Desktop/test_logging/mypackage/__init__.py", line 8, in main
    _logging.init_logging()
AttributeError: module 'logging' has no attribute 'init_logging'

Final remark, I noticed that if in mypackage.__init.py__ I import mypackage.logging prior to the standard library logging, it works.
I don't want to do that since it is against Python PEP8 recommandations:

Imports should be grouped in the following order:

standard library imports
related third party imports
local application/library specific imports

Any help would be greatly appreciated.
Ben.
P.S. I'm using Python 3.5.1.
Comment: It should work if you import the standard logging module as `_logging` and your own logging module as `logging`. Generally, anything you import from your own package in `__init__.py` should be imported by its real name, and you shouldn't shadow those names with anything. I don't have a Python 3 installation I can test it on, though.
Answer: The way I deal with this specific issue of using a custom logging module is to import all the logging functions into my custom module.  Now you can also reimplement module level functions with customized versions as well.
For example:
"""logging - Setup logging for mypackage."""

import copy
from logging import *
import logging.config

_DEFAULT_LOGGING_CONFIG_DICT = { ... }

def init_logging(verbose=False):
    ...

def default_logging_dict():
    ...

Now you only need to import your custom module.
from . import logging

log = logging.getLogger()

An alternative to using from logging import * is to reimplement any commonly used functions from the built in logging module.
import copy
import logging

def getLogger(*args, **kwargs):
    logging.getLogger(*args, **kwargs)

If you need to reach logging function that you have not reimplemented you can call through to the builtin logging module, for example: logging.logging.addLevelName(...).
Comment: I guess this would work. Appears to me as a "dirty trick" since the `from logging import *` is quite insecure and is not recommended for this reason.
Comment: Another option is to just use `import logging`, then reimplement any functions that you will use often, in particular `getLogger()`.  You would still be able to reach any logging routines by calling through (`logging.logging.setLevel(...)`).
Comment: Thanks for your advice. I'm surprise no one else answered this question. If the solution your propose is the official good way to do this, I find it quite ugly honestly. I'm not used to ugly solutions with Python so I'm surprised!

Python relative/absolute import (again)