text:
Q: $\lfloor\frac12+\frac1{2^2}+\frac1{2^3}+\cdots\rfloor\;$ vs $\;\lim_{n\to\infty}\lfloor\frac12+\frac1{2^2}+\cdots+\frac1{2^n}\rfloor$ Is there any difference between answers of $[1]$ and $[2]$?
$$\Bigg\lfloor\frac12+\frac1{2^2}+\frac1{2^3}+\cdots\Bigg\rfloor \tag*{$\space.....[1]$}$$
$$
\lim _{n \rightarrow \infty} \Bigg\lfloor\frac{1}{2}+\frac{1}{2^{2}}+\frac{1}{2^{3}}+\cdots+\frac{1}{2^{n}}\Bigg\rfloor \tag*{$ \space.....[2] $}$$
If yes then please do explain that why I can't write $[2]$ as $[1]$ even if $n$ tends to $\infty$ in $[2]$
(Notice the use of the 'floor' function indicated by the type of brackets.)
NOTE- PLEASE don't unnecessarily edit $[1]$ and $[2]$. It is exactly  as it should be.

A: The problem here is that we cannot simply exchange the limit and the function because the floor function is not continuous over $\mathbb R$.
Indeed we know that continuous functions map convergent sequences to convergent sequences. Therefore in that case we have:
$$\lim\limits_{n\to \infty}f(a_n) = f(\lim\limits_{n\to\infty}a_n)$$
As @Jmoravitz remarked this does not have to hold for functions that fail to be continuous, e.g. in our case $f: \mathbb R \to \mathbb N$, defined by $f(x)=\lfloor x \rfloor$. Indeed by direct computation we recognise the geometric series:
$$\left\lfloor\lim_{n \to \infty } \sum_{i=1}^n \frac{1}{2^i}\right\rfloor= \left\lfloor\sum_{i=1}^\infty \frac{1}{2^i} \right\rfloor= \left\lfloor\frac{1}{1-0.5}-1 \right\rfloor=1.$$
However, if we first floor the finite sum, we see that $0<\sum_{i=1}^n \frac{1}{2^i}< 1$ for all $n \in \mathbb N$. This is why we find:
$$\lim_{n \to \infty } \left\lfloor \sum_{i=1}^n \frac{1}{2^i} \right\rfloor= \lim_{n \to \infty } 0=0.$$
We see that we cannot simply exchange the limit and "applying the function".

A: The difference the difference between $\lim\limits_{n\to \infty} f(g(n))$ and $f(\lim\limits_{n\to \infty}g(n))$.
In $\lim _{n \rightarrow \infty} \Bigg\lfloor\frac{1}{2}+\frac{1}{(2)^{2}}+\frac{1}{(2)^{3}}+\cdots+\frac{1}{(2)^{n}}\Bigg\rfloor \tag*{$ \space.....[2] $}$ you take a sum, floor it, then take the limits of the floors.
In $\Bigg\lfloor\frac{1}{2}+\frac{1}{(2)^{2}}+\frac{1}{(2)^{3}}+\frac{1}{(2)^{4}}+...\infty\Bigg\rfloor \tag*{$ \space.....[1] $}$  which can is defined as, and can be written as, $\Bigg\lfloor\lim\limits_{n\to \infty}(\frac{1}{2}+\frac{1}{(2)^{2}}+\frac{1}{(2)^{3}}+\frac{1}{(2)^{4}}+...\frac{1}{(2)^{n}})\Bigg\rfloor \tag*{$ \space.....[1] $}$ you take a sum, find its limit and then floor it in the end.
Different things.
.......
$\lim _{n \rightarrow \infty} \Bigg\lfloor\frac{1}{2}+\frac{1}{(2)^{2}}+\frac{1}{(2)^{3}}+\cdots+\frac{1}{(2)^{n}}\Bigg\rfloor \tag*{$ \space.....[2] $}=0$
Why?  Because $0< \frac{1}{2}+\frac{1}{(2)^{2}}+\frac{1}{(2)^{3}}+\cdots+\frac{1}{(2)^{n}} < 1 $ for all $n$.  So  $\Bigg\lfloor\frac{1}{2}+\frac{1}{(2)^{2}}+\frac{1}{(2)^{3}}+\cdots+\frac{1}{(2)^{n}}\Bigg\rfloor \tag*{$ \space.....[2] $}=0$ for all $n$. So $\lim _{n \rightarrow \infty} \Bigg\lfloor\frac{1}{2}+\frac{1}{(2)^{2}}+\frac{1}{(2)^{3}}+\cdots+\frac{1}{(2)^{n}}\Bigg\rfloor \tag*{$ \space.....[2] $}=\lim_{n\to \infty} 0 = 0$.
But $\Bigg\lfloor\frac{1}{2}+\frac{1}{(2)^{2}}+\frac{1}{(2)^{3}}+\frac{1}{(2)^{4}}+...\infty\Bigg\rfloor \tag*{$ \space.....[1] $}$$=\Bigg\lfloor\lim\limits_{n\to \infty}(\frac{1}{2}+\frac{1}{(2)^{2}}+\frac{1}{(2)^{3}}+\frac{1}{(2)^{4}}+...\frac{1}{(2)^{n}})\Bigg\rfloor \tag*{$ \space.....[1] $}=1$
Why?
Because $\lim\limits_{n\to \infty}\frac{1}{2}+\frac{1}{(2)^{2}}+\frac{1}{(2)^{3}}+\frac{1}{(2)^{4}}+...\frac{1}{(2)^{n}}= \lim\limits_{n\to \infty} 1- \frac 1{2^{n}} = 1$.  So $\Bigg\lfloor\lim\limits_{n\to \infty}(\frac{1}{2}+\frac{1}{(2)^{2}}+\frac{1}{(2)^{3}}+\frac{1}{(2)^{4}}+...\frac{1}{(2)^{n}})\Bigg\rfloor \tag*{$ \space.....[1] $}= \Bigg\lfloor 1 \Bigg\rfloor = 1$


text:
Q: Add a click event to the bar chart of chartjs Is it possible to identify the exact segment that is clicked on in a bar chart? I've three "bars" in the chart. When I click on a particular bar, I'm calling the getBarsAtEvent() to see which particular portion of the bar is called. But getBarsAtEvent() is returning an array of all the data points in that bar. I need to know which exact portion is clicked. Is there anyway to achieve this?

A: Try using the event parameter.  Every function called by your webpage has an event object as the last parameter.
You can read more about the event object here
I suspect you would use something like event.target to get the specific node you clicked on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: using skewness to segment volume my knowledge in statistics is minuscule, sorry. I have a large volume of measured amplitudes. In the absence of a signal, the noise is assumed to have a normal distribution. When a signal is present with higher amplitude than the surrounding noise, the shape of the distribution is more tailed on the positive side. I was thinking of using skewness for detection of signal. But the area of higher amplitude (cells in the volume) is rather small compared to the volume itself. So, we are talking of in magnitude of hundreds of cells from a total of some thousands. If the skewness is zero for a normal distribution, how can I extract those cells in my volume which contribute to the non-zero skewness. If say, my skewness value is 0.5, is there a way to drop all cells and keep only those which raised the skewness value. Perhaps I sound unclear but that just shows how little I understand of the topic.
Thanks in advance.

A: It seems to me that the problem might best be modeled as a mixture model: we have a Gaussian background
B ~ N(0, sigma)
and a signal, about which the poster has not specified a particular model.
If we can assume that the signal also takes the form of one (or possible a mixture of several) Gaussian(s), then Gaussian mixture modelling with the EM algorithm may be a good way to solve it (see Wikipedia).
A good paper in the context of segmentation is this here:
http://www.fil.ion.ucl.ac.uk/~karl/Unified%20segmentation.pdf
If we cannot make such an assumption, I would use a robust regression method to estimate the parameters of the Gaussian noise, where the signal is treated as an outlier, e.g. Least trimmed squares (again see Wikipedia).
The outlier cells can then be found via (Bonferroni-corrected) hypothesis testing, as described e.g. in this paper:
http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2900857/


text:
Q: How much water could be stored? We have two water storage tanks--- Tank A and Tank B --- on the roof of the upper storey of our two-storey house.
The tanks are cylindrical in shape.
Each of the two tanks have a circular opening at the top.
Tank A has a capacity of about 500 gallons, whereas Tank B has a capacity of about 300 gallons.
The two tanks are placed on the same horizontal surface and are connected through an iron pipe.
The water is drawn up with the help of an electric motor and pumped into one of the tanks through a pipe via the opening at the top.
With this arrangement, how much water could be stored?
And how can we achieve the maximum storage capacity of 800 gallons, without changing the position of the tanks?
Exactly which area of mathematics do such problems properly belong?
And, how to tackle such problems?


text:
Q: How to create a stopwatch I'm learning Android and since I'm a beginner I thought it could be appropriate to make some kind of stopwatch as my first app. I also need one since I want to measure my long walks.
I have done the part with the buttons and all that stuff, now I'm not sure how to get this time thing to get hours, minutes and seconds to update the textView?
I also wonder how I should do to get calls to a method, like each, 30 minutes?
Preciate some guidance and hints! Thanks!

A: Just create a thread for that task the same as we did here:
http://www.itcuties.com/android/how-to-create-android-splash-screen/
Let's modify our code a little bit :)
public class MainActivity extends Activity {

    private static String TAG = MainActivity.class.getName();
    private static long SLEEP_TIME = 1; // Sleep for some time

    private TextView hoursText;
    private TextView minutesText;
    private TextView secondsText;

    // TODO: time attributes

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        hoursText = (TextView) findViewById(R.id.hoursView);
        minutesText = (TextView) findViewById(R.id.minutesView);
        secondsText = (TextView) findViewById(R.id.secondsView);

        // TODO: Get start time here

        // Start timer and launch main activity
        ClockUpdater clockUpdater = new ClockUpdater();
        clockUpdater.start();
    }

    private class ClockUpdater extends Thread {
        @Override
        /**
         * Sleep for some time and than start new activity.
         */
        public void run() {
            try {
                // Sleeping
                while (true) {
                    Thread.sleep(SLEEP_TIME * 1000);
                    // TODO: Get current time here

                    // current time - start time ...

                    // Set new values
                    hoursText.setText("10"); // don't know if you walk this long
                                                // :)
                    minutesText.setText("10");
                    secondsText.setText("10");
                }

            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }

        }
    }
}


text:
Q: member function pointer and callbacks Hi
I am trying to pass a callback which is a member function.  I  understand that a function pointer and a member function pointer are different and have tried to create a wrapper and use a static cast and the void pointer.  Unfortunately I am missing something as my code produces an error at compile
Error   16  error C2664: 'dSpaceCollide' : cannot convert parameter 3 from 'int (__cdecl *)(void *,void *,dGeomID,dGeomID)' to 'dNearCallback (__cdecl *)'

My code.....
class ODEPhysics

header file
void NearCallback (void* data, dGeomID o1, dGeomID o2);
static int StaticNearCallback(void* data, void* userPtr, dGeomID o1, dGeomID o2);

.cpp file
void ODEPhysics::NearCallback (void* data, dGeomID o1, dGeomID o2){.........}

void ODEPhysics::StaticNearCallback(void* data , void* userPtr, dGeomID o1, dGeomID o2)
{
      static_cast<ODEPhysics*>(userPtr)->NearCallback( data, o1,  o2);

}

dSpaceCollide (Space, 0, &ODEPhysics::StaticNearCallback);

If anyone could clarify what I am doing wrong and why it would be greatly appreciated.
Fred

A: The problem is most likely, from what you show, that dSpaceCollide just wants a
typedef void (*dNearCallback)(void*,dGeomID,dGeomID)

callback, that is, a function with a single void* user-data pointer and the two dGeomIDs as parameters. The void* is whatever data you passed to the dSpaceCollide then.
Assuming dSpaceCollide is defined something like this:
void dSpaceCollide(CSpace s, void* user_data, dNearCallback cb){
  // somewhere inside the code it will call your callback:
  cb(user_data, some_other, params);
  // ...
}

You can then change the callbacks to this:
void NearCallback(dGeomID o1, dGeomID o2);
static void StaticNearCallback(void* data, dGeomID o1, dGeomID o2){
  ODEPhysics* self = static_cast<ODEPhysics*>(data);
  self->NearCallback(o1, o2);
}

No more need for the void* data pointer in the member function, as that data is only relevant for the static callback:
// assuming you call this inside of your ODEPhysics class
dSpaceCollide(Space, this, &ODEPhysics::StaticNearCallback);
// pass this as user_data

A: I'm going to guess here, and assume typedef void dNearCallback(void *data, dGeomID o1, dGeomID o2). That is to say, there's no void* userPtr passed to your callback. The type system catches this when you try to use StaticNearCallback, which does expect a void* userPtr.
Underlying this problem might be a more fundamental misunderstanding. Why does your StaticNearCallback have two untyped void* pointers? What are you doing with void* data in NearCallback? Remember, C++ methods have a (typed) this pointer, so you rarely need an untyped void* data.

A: Have a look at boost::function (and maybe boost::bind). They can often make your life a lot easier.


text:
Q: PostgreSQL: speed up SELECT query in table with millions of rows I have a table with > 4.5 million rows and my SELECT query is far too slow for my needs.
The table is created with:
CREATE TABLE all_legs (
                carrier TEXT,
                dep_hub TEXT,
                arr_hub TEXT,
                dep_dt TIMESTAMP WITH TIME ZONE,
                arr_dt TIMESTAMP WITH TIME ZONE,
                price_ct INTEGER,
                ... 5 more cols ...,
                PRIMARY KEY (carrier, dep_hub, arr_hub, dep_dt, arr_dt, ...3 other cols...)
                )

When I want to SELECT all rows for a certain date, the query is too slow; it takes between 12sec and 20 seconds. My aim is that it takes max 1 sec. I expect the query to return between 0.1% and 1% of the rows contained in the table.
The query is quite simple:
SELECT * FROM all_legs WHERE dep_dt::date = '2017-08-15' ORDER BY price_ct ASC

EXPLAIN ANALYZE returns:
Sort  (cost=197154.69..197212.14 rows=22982 width=696) (actual time=14857.300..14890.565 rows=31074 loops=1)
  Sort Key: price_ct
  Sort Method: external merge  Disk: 5256kB
  ->  Seq Scan on all_legs  (cost=0.00..188419.85 rows=22982 width=696) (actual time=196.738..14581.143 rows=31074 loops=1)
        Filter: ((dep_dt)::date = '2017-08-15'::date)
        Rows Removed by Filter: 4565249
Planning time: 0.572 ms
Execution time: 14908.274 ms

Note: I learned yesterday about this command, so I am still not able to fully understand all that is returned.
I have tried using index-only scans, as suggested here, by running the command: CREATE index idx_all_legs on all_legs(dep_dt); but I did not notice any difference in running time. I also tried creating the index for all columns, as I want all columns return.
Another thought was sorting all rows by dep_dt, so then the search of all rows fulfilling the condition should be much faster as they would not be scattered. Unfortunately, I don't know how to implement this.
Is there a way to make it as fast as I am aiming to?

Solution
As suggested in the Laurenz' answer, by adding an index CREATE INDEX IF NOT EXISTS idx_dep_dt_price ON all_legs(dep_dt, price_ct); and adapting the condition in the SELECT to WHERE dep_dt >= '2017-08-15 00:00:00' AND dep_dt < '2017-08-16 00:00:00' has reduced the running time to 1/4. Even if it is a very good improvement, that means running times between 2 and 6 seconds.
Any additional idea to reduce the running time even further would be appreciated.

A: The index does not help because you use
WHERE dept_dt::date=constant

This seems fine to a beginner, but to the database, it looks like:
WHERE convert_timestamp_to_date(dep_ts)=constant

With convert_timestamp_to_date() being an arbitrary function (I just came up with the name, don't look it up in the docs). In order to use the index on dep_ts, the DB would have to reverse the function convert_timestamp_to_date into something like convert_date_to_timestamp_range (because a date corresponds to a range of timestamps, not just one timestamp), and then rewrite the WHERE as Laurenz did.
Since there are many such functions, the database developers didn't bother to maintain a huge table of how to invert them. Also it would only help for special cases. For example, if you specified a date range in your WHERE instead of a "=constant" then it would be yet another special case. It's your job to handle this ;)
Also, an index on (dep_dt,price_ct) won't speed up the sort as the first column is a timestamp, so the rows are not ordered in the index the way you want. You'd need an index on (dept_dt::date, price_ct) to eliminate the sort.
Now, which index to create? This depends...
If you also use timestamp range queries like "WHERE dep_dt BETWEEN ... AND ..." then the index on dep_dt needs to be the original timestamp type. In this case, creating another index on the same column, but converted to date, would be unnecessary (all indexes have to be updated on writes, so unnecessary indexes slow down inserts/updates). However, if you use the index on (dep_ts::date,price_ct) lots and lots of times and eliminating the sort is really important for you, then it may make sense. It's a tradeoff.

A: *

*The very first you should change here is to remove composite primary key and use plain one-column one instead of this.
This is because if you're going to use some columns index, it works the best with something like one column integer index which is here like a spine and allows your index to fetch fast rows you need to. When you have such big index like in your example, the planner may say that it will be faster for him to scan through whole table.

*Even if your index would be good enough to be used by planner, it may be dropped by ordering. I say that 'may be' as - as many things in sql - it depends on your actuall data in table, analyses, and so on.
I'm not sure about Postgres but you may want to try to build another index on column used in order by or even to try composite index for (dep_dt, price_ct). Also you may try to put dep_dt to order by list to give a compiler a hint.

*Do you need all from this table? Using * vs id (for example) can also have a impact here.

*How unique values you have in dep_dt column? Sometimes planner can say that it may be more effective in making scan through whole table than by index because there is many non-unique values here.
In summary, SQL querying is art of experimenting, as it all depends on current data (as planner is using statistics build by analyzer to guess optimal query plan). So it may even happen that when you have tuned query to table with thousand of rows, it may stop working when you reach millions.

A: The index won't help.
Two solutions:

*

*You chould either change the query to:
WHERE dep_dt >= '2017-08-15 00:00:00' AND dep_dt < '2017-08-16 00:00:00'

Then the index can be used.

*Create an index on an expression:
CREATE INDEX ON all_legs(((dep_dt AT TIME ZONE 'UTC')::date));

(or a different time zone) and change the query to
WHERE (dep_dt AT TIME ZONE 'UTC')::date = '2017-08-16'

The AT TIME ZONE is necessary because otherwise the result of the cast would depend on your current TimeZone setting.
The first solution is simpler, but the second has the advantage that you can add price_ct to the index like this:
CREATE INDEX ON all_legs(((dep_dt AT TIME ZONE 'UTC')::date), price_ct);

Then you don't need a sort any more, and your query will be as fast as it can theoretically get.


text: Q: Horizontally scaling a MongoDB database for a flask API and providing user based access control I'm trying to create a Database structure for a flask REST API in MongoDB using MongoEngine. The requirement is to make a horizontally scaled Database cluster - one Db per user. The user should be able to access only his/her own database. Every time a user is to be added to the system that user should only be able to access his assigned database. What is the more efficient way to do so? What are the best practices for doing this?


text:
Q: MY CPUs At 100% If I Run Anything Even after OS Re-install It's a Dell Inspiron 2016 I5 quad core CPU w/ 8 gigs of ram. I don't think it should be obsolete already. The CPUs are always at 100 esp with any kind of website with a lot going on like FB or youtube. I just re-installed the OS for the 3rd time in a few weeks trying to resolve this problem. Unbuntu 20.04. It came with Windows 10, but had the same issue, and took 20 minutes to boot. It worked better with 18.04 for a few years.
Is this a hardware issue? Is it just time to get a new PC? OR is there soemthing I can do?
I'm getting a gaming PC after this, I'm done with laptops, nothing but headaches and you can't upgrade them if the hardware is faulty or obsolete.


text:
Q: In Stencil with Jest, how to test object property on components using template? I have a stencil component that looks something like this:
    export class MyBadge {
      @Prop() skin: string = 'primary';
      render(){
        return (
        <span class={`skin-${this.skin}`} />
      )

I want to write a unit test that checks that the rendered component applies the given skin property.
I have a test that compares the rendered component to my expected html, using expect(page.root).toEqualHtml(´´). This test works! However, when I try to modify the prop, using template, it fails to run the test.
    import { newSpecPage } from '@stencil/core/testing';
    import { MyBadge } from './my-badge'
    it('should have "secondary" skin', async () => {
     const page = newSpecPage({
            components: [MyBadge],
            template: () => (`
              <my-badge skin=secondary></my-badge>
              `),
          });
          expect(page.root).toEqualHtml(`

          ...
          `);
        });

This gives the error expect toEqualHtml() value is "null" and the test fails
I have also tried including the bellow html under the it, but that fails too.
html: `<my-badge></my-badge>`,

Removing the template option makes the test work, however it then does not see the updated prop.
I wanted to use the template option based on this answer:
https://github.com/ionic-team/stencil/issues/1923
I've also tried a few different syntaxes, I'm not clear on how to wrap the template string.
I've been looking around for documentation on this but I can't seem to find what I'm looking for. Any help would be appreciated!
Edit: Cleaned up the code based on suggestions from @Simon Hänisch

A: Your template is returning a string, not JSX. You basically get a document with <badge skin=secondary></badge> as a string in it, not an actual badge element.
BTW badge is not a valid custom element name, it needs to have a dash (-) in its name. There are also syntax errors in your example code, like your component should
return (
  <span class={`skin-${this.skin}`} />
)

(back ticks for the class string were missing and the tag wasn't closed)
Assuming that all this is just mistakes when writing this question and you actually have a line with newSpecPage in your code (that's also missing here), here's what you need to do:

*

*Change the extension of your spec test file to .tsx.

*Add import { h } from '@stencil/core';.

*Write some actual JSX as the return value of your template.

import { h } from '@stencil/core';
import { newSpecPage } from '@stencil/core/testing';
import { MyBadge } from './my-badge';

it('should have "secondary" skin', async () => {
  const page = newSpecPage({
    components: [MyBadge],
    template: () => <my-badge skin="secondary" />,
  });

  expect(page.root).toEqualHtml('');
});

You can't use both options template and html at the same time (or at least it doesn't make sense, I'm not sure which one will take precedence), because they are different ways of setting the content for the page. If you use template, you can directly use JSX syntax to bind any kind of value to props etc. If you use html, it has to be a string with the html content of your page, and in that case you can only bind string values to props.
If you wanted to use html in your example instead, it would need to be
const page = newSpecPage({
  components: [MyBadge],
  html: `<my-badge skin="secondary"></my-badge>`,
});

I don't think you can use the self-closing syntax in this case because it's not valid for custom elements, see this answer.


text:
Q: Trying to install Perl module (Math::Random) and unable to find pathway use/bin/make which does not exist Trying to install Math::Random using sudo cpan
Writing Makefile for Math::Random
Writing MYMETA.yml and MYMETA.json
  GROMMEL/Math-Random-0.72.tar.gz
  /usr/local/Cellar/perl/5.34.0/bin/perl Makefile.PL -- OK
Running make for G/GR/GROMMEL/Math-Random-0.72.tar.gz
  GROMMEL/Math-Random-0.72.tar.gz
  /use/bin/make -- NOT OK

The path /use/... does not exist, and make is located in usr/bin/make
Have tried reinstalling cpan, perl via brew, and reinstalling make
I'm using perl v5.34.0
Has anyone got any suggestions of what else I could try? Any thoughts much appreciated! Thank you

A: You don't say what Linux version you're on but you need to install make and probably some of the development tools


text:
Q: Partial order on power sets Let's say $A = {1, 2, 3, 4}$
How can I show that $⊆$ is a partial order on $P(A)$?
Would I still have to show that it's reflexive/anti-symmetric/transitive?
I'm just confused on how to apply partial orders on power sets.

A: $$\forall B \in P(A), B \subseteq B$$
Hence it is reflexive.
$$\forall B, C \in P(A), B \subseteq C \wedge C \subseteq B \implies B=C.$$
Hence it is antisymmetry.
$$\forall B, C, D \in P(A), B \subseteq C \wedge C \subseteq D \implies B \subseteq D.$$
Hence it is transitive.


text:
Q: Prove that $[0,1]^k$ in $\mathbb{R}^d$ has strict Hausdorff dimension $k$ I am trying to prove that the set
$$[0,1]^k=\{(x_1,...,x_k,0,...,0):x_i\in[0,1]\}\subset\mathbb{R}^d$$
has strict Hausdorff dimension $k$. I have a hint: prove that there is a constant $C\in\mathbb{R}$ such that for every $E\in\mathbb{R}^k$ satisfies $\lambda_k^*(E)\leq C\operatorname{diam}(E)^k$.
Above, $\lambda_k^*$ is the Lebesgue outer measure on $\mathbb{R}^k$. Shouldn't it be the Hausdorff measure instead? Is there any explicit inequality relating the Lebesgue outer measure and Hausdorff outer measure?
I think that once I prove the hint I can take $E=[0,1]^k$ but then I'll just get $1\leq C$, right? Any suggestions on how to start would be helpful!

A: Let $Q_k = [0,1] \times \cdots [0,1] \subset \mathbb R^k$ be the unit $k$-cube. The function $$f : Q_k \to [0,1]^k$$ given by $$f(x_1,\ldots,x_k) = (x_1,\ldots,x_k,0,\ldots,0)$$ is an isometry, and thus preserves Hausdorff measure. The $k$-Hausdorff measure of $Q_k$ is its Lebesgue measure, which is just $1$.


text:
Q: create file and save to it using memorystream How can i create a file and write to it using the memory stream?
I need to use the memorystream to prevent other threads from trying to access the file.
The data i'm trying to save to a file is html.
How can this be done?

A: (Presuming you mean how to copy a file's content to a memory stream)
If you are using framework 4:
var memoryStream = new MemoryStream();

using var fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
fileStream.CopyTo(memoryStream);

A: Here are code to create file
byte[] data = System.Text.Encoding.ASCII.GetBytes("This is a sample string");
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Write(data, 0, data.Length);
ms.Close();


text:
Q: How to send POST request in Xamarin? I've built my backend in rails.
My email address is "sample@zmail.com" and it's already registered. The password is "28902890" here
After giving the following command in terminal
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST https://auth-agdit.herokuapp.com/api/v1/sessions -d "{\"user\":{\"email\":\"sample@zmail\",\"password\":\"28902890\"}}"

I get this response from my backend,
{"success":true,"info":"Logged in :) ","data":{"authentication_token":"iexGFwJ6HwERQZ3wJ4NG"}}

Now I need to get this data from my Android app.
I can get json by using WebClient().downloadString() method for simple json where authentication is not needed and the request method is GET.
Now I need to get the output Json for POST method.
How can I accomplish that?

A: There are several methods of doing this. You could use the Xamarin component called RestSharp. This will provide you with easy methods of interfacing with your backend.
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", 123); // replaces matching token in request.Resource

// add parameters for all properties on an object
request.AddObject(object);

// execute the request
RestResponse response = client.Execute(request);

If you do want to simply use the WebClient class provided by the BCL you can use the WebClient.UploadString(string, string) method like so:
using (WebClient client = new WebClient())
{
  string json = "{\"user\":{\"email\":\"sample@zmail\",\"password\":\"28902890\"}}";
  client.UploadString("https://example.com/api/v1/sessions, json);
}

If you need more control over the request (such as setting accept headers, etc.) then you can use HttpRequest, see this question for an example of that.

A: This is how I did it:
  WebClient wc = new WebClient();
        string baseSiteString = wc.DownloadString("https://auth-agdit.herokuapp.com");
        string csrfToken = Regex.Match(baseSiteString, "<meta name=\"csrf-token\" content=\"(.*?)\" />").Groups[1].Value;
        string cookie = wc.ResponseHeaders[HttpResponseHeader.SetCookie];
        Console.WriteLine("CSRF Token: {0}", csrfToken);
        Console.WriteLine("Cookie: {0}", cookie);

        wc.Headers.Add(HttpRequestHeader.Cookie, cookie);
        wc.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
        wc.Headers.Add(HttpRequestHeader.Accept, "application/json, text/javascript, */*; q=0.01");
        wc.Headers.Add("X-CSRF-Token", csrfToken);
        wc.Headers.Add("X-Requested-With", "XMLHttpRequest");

        string dataString = @"{""user"":{""email"":""email_here"",""password"":""password_here""}}";
     //   string dataString = @"{""user"":{""email"":"""+uEmail+@""",""password"":"""+uPassword+@"""}}";
        byte[] dataBytes = Encoding.UTF8.GetBytes(dataString);
        byte[] responseBytes = wc.UploadData(new Uri("https://auth-agdit.herokuapp.com/api/v1/sessions.json"), "POST", dataBytes);
        string responseString = Encoding.UTF8.GetString(responseBytes);
        Console.WriteLine(responseString);

A: Try with this code:
Uri address = new Uri("http://example.com/insert.php");
NameValueCollection nameValueCollection = new NameValueCollection();
nameValueCollection["Name"] = "string-input";

var webClient = new WebClient();
webClient.UploadValuesAsync(address, "POST", nameValueCollection);


text:
Q: calculate neighbors with NetworkX (error: The node 0 is not in the graph.) I have a sample dataframe with a column for 'to', a column for 'from' and several columns for features relating to either the 'to' or 'from' colum.
I used G = nx.from_pandas_edgelist(df, source='to', target='from',edge_attr=True) to convert the dataframe to a NetworkX graph. I used edge_attr=True because I would like to keep the features for future analysis.
I want to calculate the number of neighbours for each point, so I used neighbours = nx.all_neighbors(G,0) however, I get the error 'The node 0 is not in the graph.'
I'm not sure what I'm doing wrong.
import pandas as pd
import networkx as nx

df = pd.DataFrame({'to':[78,18,94,55,68,57,78,8],
                   'from':[18,78,35,14,57,68,57,17],
                   'to_Attribute_1':[18,78,35,14,57,68,57,17],
                   'to_Attribute_2':[18,78,35,14,57,68,57,17],
                   'from_Attribute_1':[18,78,35,14,57,68,57,17],
                   'from_Attribute_2':[18,78,35,14,57,68,57,17],
                  })
G = nx.from_pandas_edgelist(df, source='to', target='from',edge_attr=True)
[e for e in G.edges]

neighbours = nx.all_neighbors(G,0)

A: You should loop over the graph's nodes:

neighbours = {n: len(list(nx.all_neighbors(G, n))) for n in G.nodes}

Output (node -> number of neighbors):
{78: 2, 18: 1, 94: 1, 35: 1, 55: 1, 14: 1, 68: 1, 57: 2, 8: 1, 17: 1}


text:
Q: double type Functor definition refused why is this functor definition refused ?
data Second a b = Ok a b | Ko a b deriving (Show)

instance Functor (Second x) where
  fmap f (Ok a b ) = Ok (f a) b
  fmap f (Ko a b ) = Ko a (f b)

I get a lot of errors:
GHCi, version 8.0.1

main.hs:4:22: error:
    • Couldn't match type 'b' with 'x'
      'b' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a b. (a -> b) -> Second x a -> Second x b
        at main.hs:4:3
      'x' is a rigid type variable bound by
        the instance declaration at main.hs:3:10
      Expected type: Second x b
        Actual type: Second b a
    • In the expression: Ok (f a) b
      In an equation for 'fmap': fmap f (Ok a b) = Ok (f a) b
      In the instance declaration for 'Functor (Second x)'
    • Relevant bindings include
        a :: x (bound at main.hs:4:14)
        f :: a -> b (bound at main.hs:4:8)
        fmap :: (a -> b) -> Second x a -> Second x b (bound at main.hs:4:3)
main.hs:4:28: error:
    • Couldn't match expected type 'a' with actual type 'x'
      'x' is a rigid type variable bound by
        the instance declaration at main.hs:3:10
      'a' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a b. (a -> b) -> Second x a -> Second x b
        at main.hs:4:3
    • In the first argument of 'f', namely 'a'
      In the first argument of 'Ok', namely '(f a)'
      In the expression: Ok (f a) b
    • Relevant bindings include
        b :: a (bound at main.hs:4:16)
        a :: x (bound at main.hs:4:14)
        f :: a -> b (bound at main.hs:4:8)
        fmap :: (a -> b) -> Second x a -> Second x b (bound at main.hs:4:3)

What does this all mean? Please help.

A: If you unpack the definition of Functor you'll see that Second's first parameter is kept the same, while its second parameter is up for transformation.
class Functor f where
  fmap :: (s -> t) -> f s -> f t

(where I've renamed type variables a and b to s and t, respectively, because you also have value variables a and b.)
That class gives us, in your specific instance
instance Functor (Second x) where
  -- fmap :: (s -> t) -> (Second x) s -> (Second x) t
  --    i.e. (s -> t) -> Second x s   -> Second x t

Now, when you implement fmap, you have to make sure that the users of fmap can choose any x, s and t they want. So you must make no assumptions about them: they stand for arbitrary, possibly different types. That's what the error messages mean when they talk about "rigid" type variables: your code is not allowed to choose specific types for them, so that its users can. The compiler is complaining that you are promising a very polymorphic function, but delivering a less polymorphic function which typechecks only when x=s=t.
That is, when you write
  fmap f (Ok a b) = Ok (f a) b

you have
f :: s -> t
Ok a b :: Second x s
a :: x
b :: s

and you are returning
Ok (f a) b :: Second x t

which would need
f a :: x   -- clearly not true, as f :: s -> t
b :: t     -- clearly not true, as b :: s

where f a needs
a :: s     -- clearly not true, as a :: x

So, yes, lots of errors.
A Functor instance lets you transform data in positions corresponding to the type's last parameter, i.e., the b in
data Second a b = Ok a b | Ko a b deriving (Show)

so your
  fmap f (Ko a b ) = Ko a (f b)

is just fine, but your
  fmap f (Ok a b ) = Ok (f a) b

hits the usage of a different parameter and is not ok.
  fmap f (Ok a b ) = Ok a (f b)

would work. As would changing the data declaration to
data Second a b = Ok b a | Ko a b deriving (Show)

and leaving your instance as it is.
Either fix works, but don't do both "just to be on the safe side"!


text:
Q: Query page in wordpress by slug/ID I want to show my page content using id or slug. I managed to do this in some other WP theme but for some reason its not working this time...
I want to show title, excerpt and featured image
This is my code:

<?php echo the_title() ?>

                            <?php the_excerpt(); ?>
                            <?php
                                if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
                                    the_post_thumbnail( 'full', array( 'class' => 'center-block img-responsive')); // show featured image
                                }
                            ?>
                                <?php
                                    query_posts("page_id=222");
                                    while ( have_posts() ) : the_post()
                                ?>
                            <?php //the_content() ?>
                                <?php
                                    endwhile;
                                    wp_reset_query();
                            ?>

A: You don't say what is failing, but the order of your code doesn't seem right. the_title() and the_excerpt() are normally inside the loop. Like this:
  <?php
  query_posts("page_id=222");
  while ( have_posts() ) : the_post()
  ?>

<?php echo the_title() ?>

      <?php the_excerpt(); ?>
      <?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
              the_post_thumbnail( 'full', array( 'class' => 'center-block img-responsive')); // show featured image
            }
      ?>
      <?php //the_content() ?>
  <?php
  endwhile;
  wp_reset_query();

A: Using WP_Query instead of query_posts will give you more control about the scope:
<?php
  $page = new WP_Query("page_id=374");
  while ( $page->have_posts() ) : $page->the_post();
     the_content();
  endwhile;
?>


text:
Q: How to test Subscription in AWS AppSync Console? I have written the following subscription and mutation code in the App Sync Console:
subscription SubscribeToCreateDoctor {

  subscribeToCreateDoctor {
       id
       name
  }

}

mutation CreateDoctor {

      createDoctor(
        input: {
          name: "sanju",
          registrationNo: "some value",
          speciality: "some value",
          profilePic: "some value",
          placeOfResidence: "some value",
          medicalCenter: "some value",
          direction: "some value",
          municipality: "some value",
          isAvailable: "No",
        }) {
         id
         name

       }
}

In the schema, I have defined both the mutation and subscription:
type Subscription {

    subscribeToCreateDoctor: Doctor
        @aws_subscribe(mutations: ["createDoctor"])
}

type Mutation {

    createDoctor(input: CreateDoctorInput!): Doctor

}

When I test the CreateDoctor mutation in the App Sync console, I get the following response:
{
  "data": {
    "createDoctor": {
      "id": "5845c994-2389-4df9-8a3e-e13dc24b0153",
      "name": "Sanju"
    }
  }
}

However, I don't see any logs getting printed for the subscription in AWS App Sync console. The same if I test in the React Native Client app, the subscription event is triggered.
As per AWS docs it possible to test subscription in App Sync console:
https://docs.aws.amazon.com/appsync/latest/devguide/test-debug-resolvers.html

AWS AppSync lets you log errors and full request details using Amazon
CloudWatch. Additionally, you can use the AWS AppSync console to test
GraphQL queries, mutations, and subscriptions and live stream log data
for each request back into the query editor to debug in real time. For
subscriptions, the logs display connection-time information.

Did anyone successfully tested subscriptions in AWS Sync Console?

A: It won't work because you try to test mutation and subscription in the same console.
Just open two different consoles. One for mutation and another one for subscription.First, start subscription in the first console.Whenever mutation in the second console start, subscription will get invoked in the first console.


text:
Q: MySQL Getting last 5 entries for each id in a SELECT - WHERE IN statement I would like to select last 5 entries for each of the id in a SELECT - WHERE IN statement.
//How to get last 5 entries for each id
SELECT * FROM table1
WHERE id IN (111,222,333,.....)
ORDER BY date DESC
LIMIT 5

EDIT: Example of how data structure
id  date    name
111 7-Nov   Anna
111 8-Nov   Belle
111 9-Nov   Mary
111 10-Nov  John
111 11-Nov  Robert
111 12-Nov  Gary
111 13-Nov  Rick
222 8-Apr   Sarah
222 9-Apr   Lee
222 10-Apr  Margaret
222 11-Apr  Lisa
222 12-Apr  Will
222 13-Apr  Alex
222 14-Apr  Kelly
222 15-Apr  Lucas

Desired results
id  date    name
111 13-Nov  Rick
111 12-Nov  Gary
111 11-Nov  Robert
111 10-Nov  John
111 9-Nov   Mary
222 15-Apr  Lucas
222 14-Apr  Kelly
222 13-Apr  Alex
222 12-Apr  Will
222 11-Apr  Lisa

I am not sure this can be done in mysql. I have tried looking at some answers posted and I can't find the answers.

A: It just pseudo code, but I think it works. try this

SELECT
id,
SUBSTRING_INDEX(GROUP_CONCAT( some_column_1 ORDER BY date DESC),',',5)
SUBSTRING_INDEX(GROUP_CONCAT( some_column_2 ORDER BY date DESC),',',5)
....
FROM table WHERE id IN (111,222,333,.....) GROUP BY id;

it look not like you want. I just showing how use GROUP_CONCAT and SUBSTRING_INDEX function, you apply this, you can find answer.

A: this doesn't make much sense, but if your mysql-version supports it, you can do it with a subquery:
SELECT * FROM `table1`
WHERE `id` IN (SELECT `id` FROM `table1` ORDER BY `date` DESC LIMIT 5)


text:
Q: Windows 7 Failing Ping on IPv6 in DHCP Setup I have set up a test ISC DHCP server that is not connected to an internet with DHCP and DHCPv6. I also have a Cisco 3750G with IPv6 enabled. I have firewalls off on both machines.
My Windows 7 machine will get both an IPv4 and an IPv6 address:
Ethernet adapter Wired Network Connection:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Intel(R) 82566MM Gigabit Network Connection
   Physical Address. . . . . . . . . : 00-0B-97-DD-18-4E
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes
   IPv6 Address. . . . . . . . . . . : 2001:6::afb(Preferred)
   Link-local IPv6 Address . . . . . : fe80::900c:ec5b:cfd0:8470%11(Preferred)
   IPv4 Address. . . . . . . . . . . : 10.99.1.101(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.0.0
   Default Gateway . . . . . . . . . :
   DHCP Server . . . . . . . . . . . : 10.99.1.10
   DHCPv6 IAID . . . . . . . . . . . : 234883991
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-13-99-C3-BE-00-0B-97-DD-18-4E

   DNS Servers . . . . . . . . . . . : 2001:6::10
                                       10.99.1.10
   NetBIOS over Tcpip. . . . . . . . : Enabled

Pinging on IPv4 works fine both ways. I can ping using IPv6 from the DHCP server to my windows machine, but if I try to ping from the Windows machine, to elsewhere, it gives me this:
C:\Users\Brad>ping 2001:8::10

Pinging 2001:8::10 with 32 bytes of data:
PING: transmit failed. General failure.
PING: transmit failed. General failure.

Ping statistics for 2001:8::10
    Packets: Sent = 2, Received = 0, Lost = 2 (100% loss)

I read that I need to have a default router set (doesn't really make sense as I'm not leaving the network), but I can't find the option to set it. option routers expects an IPv4 address.
Any ideas on what I'm doing wrong?
Edit: More Info
/etc/dhcpd6.conf
#Some defines
# These made no difference, but I saw them elsewhere:
#option dhcp6.softwire code 54 = ip6-address;
#option dhcp6.defroute code 123 = ip6-address;
#option dhcp6.defgateway code 99 = ip6-address;

ping-check false;
ddns-update-style none;
authoritative;
default-lease-time 900;
min-lease-time 900;
max-lease-time 900;

shared-network "pool 1" {
  subnet6  2001:6::/64 {
    range6 2001:6::11 2001:6::fff;
    #prefix6 2001:6::1:0:0:0:0 2001:6::ffff:0:0:0:0 / 64;
    option dhcp6.name-servers 2001:6::10;
    option dhcp6.defgateway 2001:6::1;
  }
}

Windows 7 Routing Table (It's only giving me /128 for the IPv6 address)
IPv6 Route Table
===========================================================================
Active Routes:
 If Metric Network Destination      Gateway
  1    306 ::1/128                  On-link
 11    266 2001:6::afb/128          On-link
 33    276 fe80::/64                On-link
 14    281 fe80::/64                On-link
 11    266 fe80::/64                On-link
 14    281 fe80::39e6:c23:1fc4:b71b/128
                                    On-link
 11    266 fe80::900c:ec5b:cfd0:8470/128
                                    On-link
 33    276 fe80::b933:ca7f:14:f58d/128
                                    On-link
  1    306 ff00::/8                 On-link
 33    276 ff00::/8                 On-link
 14    281 ff00::/8                 On-link
 11    266 ff00::/8                 On-link
===========================================================================
Persistent Routes:
  None

A: You can't set the router through DHCPv6 (One of the many shortcomings I've found in it). You have to use the router advertisement protocol.
You have the prefix commented out in the configuration file you posted. DHCPv6 will need that or else the client has to guess, Windows defaults to 128.
Here is a pretty simple example with all the common options for ISC DHCPv6.


text:
Q: Load resource file based upon path the user control I need assistance reading all the resources from a resource file. I am working with visual studio 2010 c# .net 4.0.
I have a user control eg ~/MyFolder/MyControl.ascx. which has local resource files associated with it
I pass the above value ie. path the control, to another of my classes where I want to load the applicable resource file based on the current language.
Is this possible and if so how might i achieve this?
Thanks.

A: One way is it to use embedded resources:
Assembly _assembly = Assembly.GetExecutingAssembly();
_assembly.GetManifestResourceStream("Project.UI.Assets.Logo.png");

This blog post might give you more insight:
http://www.attilan.com/2006/08/accessing-embedded-resources-using.html


text:
Q: What's the fastest way to read from System.in in Java? I am reading bunch of integers separated by space or newlines from the standard in using Scanner(System.in).
Is there any faster way of doing this in Java?

A:
Is there any faster way of doing this in Java?

Yes. Scanner is fairly slow (at least according to my experience).
If you don't need to validate the input, I suggest you just wrap the stream in a BufferedInputStream and use something like String.split / Integer.parseInt.

A small comparison:
Reading 17 megabytes (4233600 numbers) using this code
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
    sum += scanner.nextInt();

took on my machine 3.3 seconds. while this snippet
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = bi.readLine()) != null)
    for (String numStr: line.split("\\s"))
        sum += Integer.parseInt(numStr);

took 0.7 seconds.
By messing up the code further (iterating over line with String.indexOf / String.substring) you can get it down to about 0.1 seconds quite easily, but I think I've answered your question and I don't want to turn this into some code golf.

A: I created a small InputReader class which works just like Java's Scanner but outperforms it in speed by many magnitudes, in fact, it outperforms the BufferedReader as well. Here is a bar graph which shows the performance of the InputReader class I have created reading different types of data from standard input:

Here are two different ways of finding the sum of all the numbers coming from System.in using the InputReader class:
int sum = 0;
InputReader in = new InputReader(System.in);

// Approach #1
try {

    // Read all strings and then parse them to integers (this is much slower than the next method).
    String strNum = null;
    while( (strNum = in.nextString()) != null )
        sum += Integer.parseInt(strNum);

} catch (IOException e) { }

// Approach #2
try {

    // Read all the integers in the stream and stop once an IOException is thrown
    while( true ) sum += in.nextInt();

} catch (IOException e) { }

A: If you asking from competitive programming point of view, where if the submission is not fast enough, it will be TLE.
Then you can check the following method to retrieve String from System.in.
I have taken from one of the best coder in java(competitive sites)
private String ns()
{
    int b = skip();
    StringBuilder sb = new StringBuilder();
    while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
        sb.appendCodePoint(b);
        b = readByte();
    }
    return sb.toString();
}`

A: You can read from System.in in a digit by digit way. Look at this answer: https://stackoverflow.com/a/2698772/3307066.
I copy the code here (barely modified). Basically, it reads integers, separated by anything that is not a digit. (Credits to the original author.)
private static int readInt() throws IOException {
    int ret = 0;
    boolean dig = false;
    for (int c = 0; (c = System.in.read()) != -1; ) {
        if (c >= '0' && c <= '9') {
            dig = true;
            ret = ret * 10 + c - '0';
        } else if (dig) break;
    }
    return ret;
}

In my problem, this code was approx. 2 times faster than using StringTokenizer, which was already faster than String.split(" ").
(The problem involved reading 1 million integers of up to 1 million each.)

A: StringTokenizer is a much faster way of reading string input separated by tokens.
Check below example to read a string of integers separated by space and store in arraylist,
String str = input.readLine(); //read string of integers using BufferedReader e.g. "1 2 3 4"
List<Integer> list = new ArrayList<>();
StringTokenizer st = new StringTokenizer(str, " ");
while (st.hasMoreTokens()) {
    list.add(Integer.parseInt(st.nextToken()));
}

A: In programming perspective this customized Scan and Print class is way better than Java inbuilt Scanner and BufferedReader classes.
import java.io.InputStream;
import java.util.InputMismatchException;
import java.io.IOException;

public class Scan
{

private byte[] buf = new byte[1024];

private int total;
private int index;
private InputStream in;

public Scan()
{
    in = System.in;
}

public int scan() throws IOException
{

    if(total < 0)
        throw new InputMismatchException();

    if(index >= total)
    {
        index = 0;
        total = in.read(buf);
        if(total <= 0)
            return -1;
    }

    return buf[index++];
}

public int scanInt() throws IOException
{

    int integer = 0;

    int n = scan();

    while(isWhiteSpace(n))   /*  remove starting white spaces   */
        n = scan();

    int neg = 1;
    if(n == '-')
    {
        neg = -1;
        n = scan();
    }

    while(!isWhiteSpace(n))
    {

        if(n >= '0' && n <= '9')
        {
            integer *= 10;
            integer += n-'0';
            n = scan();
        }
        else
            throw new InputMismatchException();
    }

    return neg*integer;
}

public String scanString()throws IOException
{
    StringBuilder sb = new StringBuilder();

    int n = scan();

    while(isWhiteSpace(n))
        n = scan();

    while(!isWhiteSpace(n))
    {
        sb.append((char)n);
        n = scan();
    }

    return sb.toString();
}

public double scanDouble()throws IOException
{
    double doub=0;
    int n=scan();
    while(isWhiteSpace(n))
    n=scan();
    int neg=1;
    if(n=='-')
    {
        neg=-1;
        n=scan();
    }
    while(!isWhiteSpace(n)&& n != '.')
    {
        if(n>='0'&&n<='9')
        {
            doub*=10;
            doub+=n-'0';
            n=scan();
        }
        else throw new InputMismatchException();
    }
    if(n=='.')
    {
        n=scan();
        double temp=1;
        while(!isWhiteSpace(n))
        {
            if(n>='0'&&n<='9')
            {
                temp/=10;
                doub+=(n-'0')*temp;
                n=scan();
            }
            else throw new InputMismatchException();
        }
    }
    return doub*neg;
}

public boolean isWhiteSpace(int n)
{
    if(n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
        return true;

    return false;
}

public void close()throws IOException
{
    in.close();
}
}

And the customized Print class can be as follows
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class Print
{
private BufferedWriter bw;

public Print()
{
    this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}

public void print(Object object)throws IOException
{
    bw.append("" + object);
}

public void println(Object object)throws IOException
{
    print(object);
    bw.append("\n");
}

public void close()throws IOException
{
    bw.close();
}

}

A:
You can use BufferedReader for reading data

BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
  int t = Integer.parseInt(inp.readLine());
  while(t-->0){
    int n = Integer.parseInt(inp.readLine());
    int[] arr = new int[n];
    String line = inp.readLine();
    String[] str = line.trim().split("\\s+");
    for(int i=0;i<n;i++){
      arr[i] = Integer.parseInt(str[i]);
    }

And for printing use StringBuffer

    StringBuffer sb = new StringBuffer();
    for(int i=0;i<n;i++){
              sb.append(arr[i]+" ");
            }
    System.out.println(sb);

A: Here is the full version fast reader and writer. I also used Buffering.
import java.io.*;
import java.util.*;

public class FastReader {
    private static StringTokenizer st;
    private static BufferedReader in;
    private static PrintWriter pw;

    public static void main(String[] args) throws IOException {

        in = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        st = new StringTokenizer("");

        pw.close();
    }

    private static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }
    private static long nextLong() throws IOException {
        return Long.parseLong(next());
    }
    private static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
    private static String next() throws IOException {
        while(!st.hasMoreElements() || st == null){
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }
}

A: Reading from disk, again and again, makes the Scanner slow. I like to use the combination of BufferedReader and Scanner to get the best of both worlds. i.e. speed of BufferredReader and rich and easy API of the scanner.
Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in)));


text:
Q: What format gpsd uses for feeding? I need to replay collected gps data by gpsd for testing. I know that I can feed gpsd by tcp, for example: gpsd -N tcp://127.0.0.1:6000, but I can't find right format for feeding. What the format should I use?

A: If you want to replay the GPS data for testing, you can use gpsfake tool from the gpsd suite: https://gpsd.gitlab.io/gpsd/gpsfake.html
Regarding the log format that it can use
Logfiles for the use with gpsfake can be retrieved using gpspipe, gpscat, or cgps from the gpsd distribution, or any other application which is able to create a compatible output.

So I would record the log from a real GNSS receiver with
gpspipe -R > gps.log
and later use gpsfake to replay it during testing without GNSS receiver.
edit: The gpspipe -R command will save a NMEA log if the receiver outputs NMEA messages. It can be later used for testing with gpsfake or other tool. Of course you can kill gpsd and just directly listen to the serial port to record the NMEA.


text:
Q: extjs 4 ajax request json error decode while querying for plain text These code:
        Ext.Ajax.request({
        url: 'modules/tags.cfc?method=getHtml',
        success: function(response, opts) {
            //var obj = response.responseText;
            console.dir(response, opts);
            //this.html=obj;
        },
        failure: function(response, opts) {
           // console.log('server-side failure with status code ' + response.status);
        }
    },this);

Is throwing this error:

[E] Ext.JSON.decode(): You're trying to decode an invalid JSON String:

    ihooolog @ ext-all-dev.js:12297Ext.Error.Ext.extend.statics.raise @ ext-all-dev.js:11394Ext.JSON.me.decode @ ext-all-dev.js:11800MIS.Methods.AjaxTrigger @ MIS.Methods.js?{ts '2015-08-06 19:33:54'}:45fire @ ext-all-dev.js:16019continueFireEvent @ ext-all-dev.js:17883fireEventArgs @ ext-all-dev.js:17854fireEvent @ ext-all-dev.js:17831Ext.define.onComplete @ ext-all-dev.js:48201Ext.define.onStateChange @ ext-all-dev.js:48148(anonymous function) @ ext-all-dev.js:3332

When I return a simple string "ihooo" from the server. I can't figure out why he is trying to decode JSON, I don't see where...
The response headers are:

HTTP/1.1 200 OK
  Transfer-Encoding: chunked
  Content-Type: text/html; charset=UTF-8
  Server: Microsoft-IIS/7.5
  X-Powered-By: ASP.NET
  Date: Thu, 06 Aug 2015 17:37:35 GMT

And the response itself if realy just a simple text.
The component & function (tags.cfc):
<cfcomponent extends="base" output="false">
<cffunction name="getHtml" access="remote" returnformat="plain" returntype="String">
    <cfreturn "ihooo">
</cffunction>

Any help/clue would be gratly appreciated!
Thanks!

A: Isn't it caused by console.dir, which is trying to output the property of a javascript object?
Try:
Ext.Ajax.request({
    url: 'modules/tags.cfc?method=getHtml',
    success: function(response, opts) {
        var obj = response.responseText;
        console.dir(obj);
    },
    failure: function(response, opts) {
       // console.log('server-side failure with status code ' + response.status);
    }
},this);

A:
When I return a simple string "ihooo" from the server. I can't figure
  out why he is trying to decode JSON, I don't see where

Read the error message. It is telling that there is a call to Ext.JSON.decode in your MIS.Methods.js file at line 45.
Just don't do it on simple strings "ihooo" :)


text:
Q: PHP Session is null when accessed in a different script I'm setting a session like so:
// ---- Start the session
session_start();
.
.
.
.

$tokenMap = $_SESSION["tokenMap"];
$date = new DateTime();
$created = $date->getTimestamp();
$accessToken = uniqid();
if (!isset($tokenMap))
  $tokenMap = array($accessToken=>array("username"=>$username, "created"=>$created));
else {
  // ---- Unset any values that already exist
  foreach($tokenMap as $t => $user) {
    if ($user["username"] === $username) {
      unset($tokenMap[$t]);
      break;
    }
  $tokenMap[$accessToken] = array("username"=>$username, "created"=>$created);
}
echo $_SESSION["tokenMap"]; // returns correct values

However, when I access it in a different script, $_SESSION is empty:
// ---- Start the session
session_start();

echo json_encode($_SESSION); // []

Is there something I'm missing or misunderstanding about PHP sessions?

A: To make your session available you can create a table and save & update your session data when ever you need.


text:
Q: $.getJSON() to $.ajax() I would like to ask how could I convert the following $.getJSON() to $.ajax() please.
I have a set of arrays from var googleApi like this:
Array [Object, Object, Object, Object, Object]

// if stringified
[{"id":"0","name":"user1","type":"mf","message":"bonjour user1"},
{"id":"1","name":"user2","type":"ff","message":"hello user2"},
{"id":"2","name":"user3","type":"mm","message":"konnichiwa user3"},
{"id":"3","name":"user4","type":"mf","message":"ni hao user4"},
{"id":"4","name":"user5","type":"ff","message":"high 5! user5"}]}

I would like to ask how could I identify if the value of a declared variable (eg. content with the value of user1) is the same as a value within the list of name keys in the array?
Below is my attempt and you might find my full code in $.getJSON() here:
$.getJSON():
var googleApi = 'https://api.com/url_here';

$.getJSON(googleApi, function(json){

    console.log(JSON.stringify(json));
    var item = json.result.find(function(e){

    return e.name == content;

    }) || json.result[0];
    console.log("PRINT ID: " + item.id);

    var name = item.name || content;
    $('#nameText').text(name);
    console.log("Name: " + name);
});

Below is my attempt on $.ajax() but I got an error of "TypeError: data.result is undefined";I have also tried using $(this) to replace data.result but without luck... it would be very nice if someone could identify what have I done wrong please:
var googleApi = "https://sheetsu.com/apis/v1.0/f924526c";
var googleKey = "0123456789";
var googleSecret = "987654321";

var data = [];
$.ajax({
    url: googleApi,
    headers: {
    "Authorization": "Basic " + btoa(googleKey + ":" + googleSecret)
    },
    data: JSON.stringify(data),
    dataType: 'json',
    type: 'GET',

    success: function(data) {

        console.log(data);

        var item = data.result.find(function(e){

            return e.name == content;

        }) || data.result[0];
        console.log("PRINT ID: " + item.id);

        var name = item.name || content;
        $('#nameText').text(name);
        console.log("Name: " + name);
});

Merci beaucoup :))) x

A:
...how could I identify if the value of a declared
  variable ... is the same as a value
  within the list of name keys in the array?

As per your provided response object you could iterate through it and check the values against your variable content:
var content = "user1";

$.each(response, function(i, v) {
   if (v.name == content) {
      console.log(v.name);
   }
});

Example Fiddle

As for the second part of your question:

but I got an error of "TypeError: data.result is undefined";

The reason you may be getting your error is because find is expecting a jQuery object, you have received a JSON object back from your endpoint, so using dot notation as above will should work as well:
success: function(data) {
    $.each(data, function(i, v) {
        if (v.name == content) {
            console.log(v.name);
        }
    });

}

You can see the answer to this question for a bunch of awesome information on how to access / proccess objects.
Also note your success callback in your code above is not closed, which will create errors.

A:         function getID(name){

            $.each(data,function(key,value){    //value = object.value (name)

                $.each(value,function(key1,value1){     //value1 = user name (actual names in array)

                    if(value1 == content){
                        console.log(value.id);

                        var name = value.name;
                        $('#nameText').text(name);
                        console.log("Name: " + name);

                        return;
                        }
                    });

                });
            }

        getID(data);
        return false;


text:
Q: Оптимальный способ передачи данных из BD в массив Python Имеется большой набор данных, хранящийся в отдельном файле в виде dataclass c несколькими параметрами, требуется передать этот набор данных в массив иного проекта в виде ссылки или похожем.
Грубо говоря получить что-то вроде:
a = [(href = 'BD.py')]
Заранее благодарю.


text:
Q: Indention error in jade This is my jade template. When I try to test following jade code @http://jade-lang.com/ it shows indention error
html(ng-app='testApp2', lang='en')
  head(ng-app = testApp2)
        script(src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.15/angular.min.js')
    title!= title
  body(ng-controller = 'mainController as vm')
      script(type='text/javascript', src='/assets/js/app.js')
     {{ vm.massage }}
     ul
     li(ng-repeat='person in vm.person')
     {{person.name}}

After I run the app following error shows
Jade:8
    6|       script(type='text/javascript', src='/assets/js/app.js')
    7|      {{ vm.massage }}
  > 8|      ul
    9|      li(ng-repeat='person in vm.person')
    10|      {{person.name}}

unexpected token "indent"

A: Your li should lie inside ul
  html(ng-app='testApp2', lang='en')
     head(ng-app = testApp2)
         script(src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.15/angular.min.js')
         script(type='text/javascript', src='/assets/js/app.js')
         title!= title
     body(ng-controller = 'mainController as vm')

       {{ vm.massage }}
       ul
          li(ng-repeat='person in vm.person')
          {{person.name}}

now my code looks like this
html(ng-app='testApp2', lang='en')
  head(ng-app = testApp2)
        script(src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.15/angular.min.js')
    title!= title
  body(ng-controller = 'mainController as vm')
      script(type='text/javascript', src='/assets/js/app.js')

ul
     li(ng-repeat='person in vm.person'){{person.name}}


text:
Q: XSLT test on xsl:template I've a xml file
<?xml version="1.0" encoding="UTF-8"?>
<CategoriesList>
  <Category ID="1" >
    <Name ID="1395687" Value="Libelle1" langid="1"/>
    <Name ID="1395689" Value="" langid="3"/>
  </Category>
  <Category ID="2" >
    <Name ID="1395687" Value="" langid="1"/>
    <Name ID="1395689" Value="Libelle2" langid="3"/>
  </Category>
</CategoriesList>

I try to do a smart filter with XSLT file
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output  method="xml" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="CategoriesList">
    <xsl:apply-templates select="Category"/>
</xsl:template>

<xsl:template match="Category">
    <xsl:element name="Category">
        <xsl:attribute name="ID">
            <xsl:value-of select="@ID"/>
        </xsl:attribute>
        <xsl:apply-templates select="Name"/>
    </xsl:element>
</xsl:template>

<xsl:template match="Name[@langid=3]">
    <xsl:attribute name="Name">
        <xsl:value-of select="@Value"/>
    </xsl:attribute>
</xsl:template>

I can filter to take only Name node with langid=3
But I want :
if Name node with langid=3 is empty take Name node with langid=1
if Name node with langid=3 is not empty take Name node with langid=3
I saw

Please, can you help me

A: If "empty" means that the Value attribute is empty, try something like:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/CategoriesList">
    <xsl:copy>
        <xsl:apply-templates select="Category"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Category">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:attribute name="Name">
            <xsl:choose>
                <xsl:when test="Name[@langid=3][string(@Value)]">
                    <xsl:value-of select="Name[@langid=3]/@Value"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="Name[@langid=1]/@Value"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:attribute>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Applied to your input example, the result is:
<?xml version="1.0" encoding="UTF-8"?>
<CategoriesList>
  <Category ID="1" Name="Libelle1"/>
  <Category ID="2" Name="Libelle2"/>
</CategoriesList>

Note that we are assuming that langid is unique within each category.


text: Q: POST request forbidden I am using django-rest-framework. I have a few APIs which I use to GET data. When I am testing a new API to post information, I am getting a 403 forbidden while making the request as vanilla xhr object, as well as using jQuery. The same API is working properly from Postman and django-rest-framework API interface as well. What can be the reason for this?


text:
Q: Meaningless characters before every build output in Sublime Text Every time I use a build a file (any type of file – C++, python...), there's these funky characters that appear before the build output. Here's a screenshot, on the left, the console looks normal, on the right I cancelled a build to see whether it happened during or before the build. It's always the same characters.

Any idea what might be causing this? I reinstalled Sublime from scratch (keeping my Packages and User Packages directories) and it's still happening. I'm running 3083 by the way.


text:
Q: How to populate a column based on values from multiple columns in python? I have a data frame where I am trying to populate a column based on the values in the other columns. There should only be one Sxx per row, but it could be in a different column in each row. So in row 1, S11 could be in column 4, but in row 2 S15 could be in column 5. What I want to do is to take all of the Sxx values and put them in one column at the end. Any help here would be much appreciated!
Here is an example of the data frame. If you look at the second to last and last row, that is emblematic of what I am trying to solve for.
    Entity1 Entity2 Entity3 Entity4 Entity5 Entity6 Entity7 Entity8 Entity9 School
0   C12 CAD G01 S09 None    None    None    None    None    NaN
1   C12 CAD G01 S09 None    None    None    None    None    NaN
2   C12 CAD G01 S09 None    None    None    None    None    NaN
3   C12 CAD G01 S09 None    None    None    None    None    NaN
4   C12 CAD G01 S09 None    None    None    None    None    NaN
... ... ... ... ... ... ... ... ... ... ...
322976  C07 CAD G01 S09 None    None    None    None    None    NaN
322977  C13 CAD G01 S06 None    None    None    None    None    NaN
322978  C13 CAD G01 S06 None    None    None    None    None    NaN
322979  C13 CAD G01 S06 None    None    None    None    None    NaN
322980  CAD G01 S14 W04 None    None    None    None    None    NaN
322981 rows × 10 columns

A: Here is one way of doing it, probably not the most optimal, using regex. It assumes there is always one Sxx at each row. Assuming your DataFrame is data_df:
import pandas as pd
import re

last_col = list()
for index, row in data_df.iterrows():
    for cell in row.to_list():
        if re.match('S[0-9]+', cell):
            last_col.append(cell)
            break

data_df['last_col'] = last_col

A: Find the locations of Sxx's with the apply(lambda match) then propagate those to the last column with ffill(axis=1) then add that last column ( .iloc[:,-1:] ) to the DF.
df['Last_S_Col'] = \
    df[df.apply(lambda x: x.str.match('S[0-9]{2}'), axis=1)].ffill(axis=1).iloc[:,-1:]

df:
  Entity1 Entity2 Entity3 Entity4 Entity5 Entity6 Entity7 Entity8 Entity9  \
0     C12     CAD     S12     G01    None    None    None    None    None
1     C12     CAD     G01     S09    None    None    None    None    None
2     C12     CAD     G01     S09    None    None    None    None    None
3     C12     S14     G01     CAD    None    None    None    None    None
4     S01     CAD     G01     C12    None    None    None    None    None

   School Last_S_Col
0     NaN        S12
1     NaN        S09
2     NaN        S09
3     NaN        S14
4     NaN        S01


text:
Q: How to get Angular service by name programmatically I have a string that contains the name of a service I need to inject into in one of my controllers programmatically.
function Ctrl() {
    var serviceName = '$myService';
    var service = ???
}

I am assuming it should be pretty easy to do something similar to:
function Ctrl($injector) {
    var serviceName = '$myService';
    var service = $injector.inject(serviceName);
}

I know I don't have the syntax correct but can someone give me the correct syntax?

A: You can get a service like this:
var myService = $injector.get('MyServiceName');


text:
Q: When to Know If Vectors are Implemented Vertically Or Horizontally Within a Matrix This is my first time asking a question on stack exchange so please bear with me.
Sometimes I see vectors in matrices in row form i.e. for simultaneous equations but when checking for linear independence the vectors are inserted as columns. I know that this is because aV1 + aV2 + aV3 = 0 where a is a scalar multiple of the vectors so I am adding the x1 from each vector, the x2 accordingly etc... But how do I know if given a co-efficient matrix, whether they are implemented in a row or column format or in other words if they are vertical or horizontal within the matrix?

A: This is one of the challenges of linear algebra, so you're asking a good question. Of course, given a question you want to solve, you can always set it up so that either way works, but I agree that it is more natural one way than the other.
You already pointed out that when you think of a system of equations $A\vec x = \vec b$, we treat $\vec x$ and $\vec b$ as column vectors and the coefficients of each equation become the row vectors of $A$. On the other hand, the columns of $A$ still have a meaning: The vectors $\vec b$ for which this system of equations is consistent (i.e., has a solution) are precisely the column space (span of the columns) of $A$.
Indeed, solving for $\vec x$ in $A\vec x=\vec b$ tells you the coefficients of the respective column vectors that gives you the linear combination $\vec b$: If $\vec a_j$ are the columns of $A$, then the equation $A\vec x=\vec b$ can be rewritten as $\sum x_j\vec a_j = \vec b$. This then leads naturally to the question of linear dependence/independence to which you already alluded.
Suppose I hand you vectors $\vec v_1,\dots,\vec v_m\in \Bbb R^n$ and ask you to find the orthogonal complement of the subspace they span; that is, I want you to find all vectors $\vec x\in\Bbb R^n$ so that $\vec v_i\cdot\vec x=0$ for all $i=1,\dots,m$. Well, then, if you put the $\vec v_i$ in as the rows of a $m\times n$ matrix $A$, you're looking for the nullspace of $A$ (i.e., all solutions of $A\vec x=\vec 0$). But you could put them in as the columns of an $n\times m$ matrix and find the so-called left nullspace (i.e., all solutions of $\vec x{}^\top\!\!A = \vec 0{}
^\top$).
Here's one for you. Suppose I give you two planes in $\Bbb R^3$, one spanned by $(1,1,0)$ and $(0,1,-1)$, and the other spanned by $(1,0,1)$ and $(2,-1,1)$. Can you find all the vectors that are in both planes?


text:
Q: Customer org corrupted: Public class deleted in 1.2 magically gets deprecated in 1.1.1 patch We pushed patch 1.1.1 of our managed app to a customer production org which worked fine in their sandbox for the last weeks. After the installation our customers faces compile-time type errors as Apex classes could not be found during runtime.

Variable does not exist:...

or

Invalid type: ....

Indeed a handful of public classes were missing on which the code relied on. In the Sandbox with the exact same version those classes existed!
The the patch DE org those classes were marked with this strange deprecation warning which we have never seen before:

This Apex class is deprecated

Strange as we thought you can only annotate global classes to be @deprecated.

So it appears that the deletion of Apex classes in a later release changes the behaviour of classes already uploaded as a patch release month before. Customer orgs which had this patch installed before the deletion of the classes were lucky and those who installed it later are...doomed.
We currently see no way to cure this problem. Anyone out there that experience similar strange behaviour in his apps.
As a side note: Salesforce.com activated the "Delete Packaged Components" and "Push Upgrade" feature for this ISV app recently. We also had the feeling that Salesforce.com with Winter '15 changed the behavior of class deletion. See this Why can I not reuse the name of Apex classes deleted in previous releases?

A: This was indeed a Platform bug which only seemed to happen in our ISV product.
In the past we did the following: remove a class from the org, upload a new package and then later undelete the class from the "View Deleted Components" page.
This was possible until the Winter '15 upgrade. Conerning to Saelsforce the first delete of that class left a max_version flag on this file of the kind "Deprecated in release x.Y". With Winter '15 this flag started to become meaning an classes that very illegally undeleted after a release got deprecated and unusable in already delivered releases.
Salesforce.com Support was now able to change those max version flags in all relevant classes and we could reuse them.


text:
Q: DatabaseReference Generic Search with an Array of Strings There's an attribute "categories" that I'm storing in my firebaseDB, and it is and array of strings, exemple:

categories: "diabetes, açúcar sanguíneo, diabético"

And I need to create a search for this categorie that is similliar to an sql query like: ... categories is like '%word%';. So the search word could be either "diabetes", " açúcar sanguíneo" , "diabético", "açúcar"...
I tried with startWith, or endWith


text:
Q: Access function in class A from non related class B using object of class A
Possible Duplicate:
Call function of class ONE from class TWO without extend?

why this does not work?
    class A {
        function one() {
            echo "Class A";
        }
    }

    class B {
        function two() {
            echo "Class B";
            $a->one();
        }
    }

    $a = new A;
    $b = new B;

    $b->two();

A: $a is not accessable in Class B in your example. Please read Variable Scope
Try:
class A {
    public function one() {
        echo "Class A";
    }
}

class B {
    public function two() {
        echo "Class B";
        $a = new A;
        $a->one();
    }
}

$b = new B;
$b->two();

A: This does not work because $a is not a global variable.
It should work if you declare $a as global in class B beforehand.
class B {
        function two() {
            global $a;
            echo "Class B";
            $a->one();
        }
    }

A: As mentioned, this is a variable scope problem. The scope of B::two() does not include the variable $a which has been declared in the global namespace.
The best thing to do is pass $a to B as a dependency. There would be several ways to do this...
For single use in B::two()
public function two(A $a)
{
    echo 'Class B';
    $a->one();
}

Then
$b->two($a);

As a property of B
class B
{
    private $a;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function two()
    {
        echo 'Class B';
        $this->a->one();
    }
}

then
$b = new B($a);
$b->two();


text:
Q: Copy Files Using Python I'm trying to copy files from my current directory to a newly created folder in my current directory. The folder name is the exact date and time the script runs using the time module. I'm trying to use the shutil module because that's what everyone seems to say is the best for copying files from one place to another, but I keep getting a permission error. I've pasted the code and the error below. Any suggestions? Thanks in advance.
import os
import time
from shutil import copyfile

oldir = os.getcwd()
print(oldir)
timestr = time.strftime("%Y%m%d-%H%M%S")
print('timestr: {}'.format(timestr))
newdir = os.path.join(oldir + "\\" + timestr)
print(newdir)

for filename in os.listdir(os.getcwd()):
    if filename.startswith("green"):
        print (filename)
        copyfile(oldir, newdir)

error:
Traceback (most recent call last):
  File "\\directory\directory\Testing1.py", line 16, in <module>
    copyfile(oldir, newdir)
  File "C:\Python36-32\lib\shutil.py", line 120, in copyfile
    with open(src, 'rb') as fsrc:
PermissionError: [Errno 13] Permission denied: '\\\\directory\\directory'

A: You need to first create the directory and then when you make the copy, use the entire path to both the start file and then end file
import os
import time
from shutil import copyfile

oldir = os.getcwd()
print(oldir)
timestr = time.strftime("%Y%m%d-%H%M%S")
print('timestr: {}'.format(timestr))
newdir = os.path.join(oldir + "\\" + timestr)
print(newdir)

if not os.path.exists(newdir):
    os.makedirs(newdir)

for filename in os.listdir(os.getcwd()):
    if filename.startswith("green"):
        print (filename)
        copyfile(oldir+"\\"+filename, newdir + "\\" + filename)


text:
Q: Vector equation of a plane from normal vector and a point (quick way) For example: the plane passing through the point $B(1,1,1)$ with a normal vector of  $(2i-j+2k)$
I know I can set up the Cartesian equation of the line, then find $2$ additional points on the plane by plugging random $x$'s and $y$'s into the Cartesian equation. Then setting up the vector equation by doing the standard method with three points.
However, is there any way to go straight to the vector equation without first having to set up the Cartesian equation and find three points?

A: For the vector equation let find two vectors orthogonal to $\vec n=(2,-1,2)$ as for example

*

*$\vec v_1=(1,2,0)$

*$\vec v_2=(0,2,1)$

then the parametric equation of the plane through the origin is given by
$$t\vec v_1+s\vec v_2$$
then find $k$ such that $$t\vec v_1+s\vec v_2+k\vec n$$
passes through $B(1,1,1)\implies k=\frac13$ then the plane equation in parametric form is
$$t\vec v_1+s\vec v_2+\frac13\vec n$$

A: Yes, there is: if $\vec n$ is a normal vector, and $80$ a point on the straight line, the equation, vectorially, is written as
$$\overrightarrow{M_0M}\cdot\vec n=0\quad\text{or }\;\overrightarrow{OM}\cdot\vec n=\overrightarrow{OM_0}\cdot\vec n,$$
i.e. with the present coordinates
$$2x-y+2z=2\cdot 1-1+2\cdot 1=3.$$


text:
Q: Manual Flow Facebook Login Error: Please try closing and re-opening your browser I'm building an app in Go and allowing users to log in using Facebook. I've followed the instruction as carefully as I can, but after I redirect users to Facebook I am getting an error page that says: "Sorry, something went wrong: Please try closing and re-opening your browser window." and that's all.
If I refresh the URL that displayed at the top of the error message, it successfully redirects to my app, provides a code and I'm able to exchange the code for a token.
The only thing that's broken is that instead of a smooth user flow where I redirect a user to Facebook and they get sent back, the user is stuck on the error page unless they think to refresh.
I've seen a bunch of posts saying that Facebook is very sensitive to the state parameter, but I'm using a vanilla alphanumeric (no special chars) and after refresh I get it back successfully.
The URL I'm seeing in FB while it is displaying the error looks like this:
https://www.facebook.com/dialog/oauth?client_id=<myAppId>&redirect_uri=https%3A%2F%2F<hostname>%2Ffbcallback&response_type=code&scope=public_profile&state=<18 character string>

I've checked that the URI is connected to the app profile in the Facebook developer page. Any clues? I don't know what this error means.
One discovery - if I try my flow in an incognito window where I'm not currently logged in to Facebook, everything works perfectly. If I then try to log into my app again, that's when I see the error. I'm not setting any cookies in my app, but it seems like there's some connection here.


text:
Q: Apply cql to cassandra on bare metal during application deployment to kubernetes cluster Our customer has a running cassandra cluster (not in a container).
We are currently trying to find a way to apply cql scripts in an automated way during rollout of our application that is deployed in a kubernetes cluster.
Our application is a quarkus application.
Has anyone a hint for me how to handle this in a proper way?


text:
Q: Adding Multiple Dict Value against a Single Key I am doing following:
>>> l = []
>>> l
[]
>>> l
[]
>>> d = {}
>>> d['Title'] = {'Age':4}
>>> d
{'Title': {'Age': 4}}
>>> l.append(d)
>>> l
[{'Title': {'Age': 4}}]
>>> d['Title'] = {}
>>> d['Title'] = {'Age':21}
>>> l.append(d)
>>> l
[{'Title': {'Age': 21}}, {'Title': {'Age': 21}}]

Instead of showing Age 4 and 21 it repeats the last value. Where am I doing wrong?

A: You reused the same dictionary object you already added to l. If you meant to add a new dictionary, create a new object:
l = []
d = {'Title': {'Age': 4}}
l.append(d)
d = {'Title': {'Age': 21}}
l.append(d)

where I used a dictionary literal to create the whole structure in one go.
Alternatively, create a copy of d to add to l:
l.append(d.copy())

which creates a shallow copy of d.
Python lists hold references, not copies.

A: d is just a reference. So when you change d and append it l again, you have effectively added the same object twice to l. You can either:

*

*Use a different dictionary variable the second time.

*Use del before you re-use d. Like this:
In [58]: d = {}
In [59]: l = []
In [60]: d['Title'] = {'Age':4}
In [61]: l.append(d)
In [62]: del d
In [63]: d = {}
In [64]: d['Title'] = {'Age':21}
In [65]: l.append(d)
In [66]: l
Out[66]: [{'Title': {'Age': 4}}, {'Title': {'Age': 21}}]

*Use copy
In [72]: d = {}
In [73]: l = []
In [74]: d['Title'] = {'Age':4}
In [75]: l.append(d.copy())
In [76]: d['Title'] = {'Age':21}
In [77]: l.append(d)
In [78]: l
Out[78]: [{'Title': {'Age': 4}}, {'Title': {'Age': 21}}]

A: if you check id of these objects they are all the same:
>>> l
[{'Title': {'Age': 4}}]
>>> id(l[0])
139978373813960
>>> id(d)
139978373813960
>>> d['Title'] = {}
>>> id(d)
139978373813960
>>> d['Title'] = {'Age':21}
>>> id(d)
139978373813960
>>> l.append(d)
>>> id(l[0])
139978373813960
>>> id(l[1])
139978373813960

A: With all these good answers, my one cent: id() is useful in this case to show that you have two incidence of the same dictionary in your list, rather than two different dictionaries:
In [13]: id.__doc__
Out[13]: "id(object) -> integer\n\nReturn the identity of an object.  This is guaranteed to be unique among\nsimultaneously existing objects.  (Hint: it's the object's memory address.)"

In [14]: l = []

In [15]: d={}

In [16]: d['Title'] = {'Age':4}

In [17]: l.append(d)

In [18]: d['Title'] = {}

In [19]: d['Title'] = {'Age':21}

In [20]: l.append(d)

In [21]: map(id, l)
Out[21]: [4386697552, 4386697552] #identical


text:
Q: Trigger Laravel 5.4 reset password programatically from controller I need to use Laravel's out-of-the-box reset password functionality through another function in my API controller.

A: Use the ResetPasswords trait in your controller.
class ApiController extends Controller
{
    use \Illuminate\Foundation\Auth\ResetsPasswords;

    public function doSomething(Request $request) {
        ...
        $this->broker()->sendResetLink(['email' => 'youremail@yourdomain.com']);
    }
}


text:
Q: How to find min , max on array and how to change color text for min green color and max red color using angular I have the JSON like below but I have a lot of data:
items: [
{
itemId: "22222",
category: 'A',
total: 100
},
{
itemId: "666666",
category: 'A',
total: 80
},
{
itemId: "555",
category: 'B',
total: 50
}
....
...
{
itemId: "555",
category: 'B',
total: 2
}
]
I create on .scss
   &.is-green {
      color: green;
    }
    &.is-red {
      color: red;
    }

I want to use it something like that:

{{item.category}}

       {{item.total}}

From this data I want to find min total and change color to green.
I want to find also max total and change color red.
Please, have you any idea how to make this?

A: So, this question has two parts, right ?
The first one is sorting
and the second one is changing the first and last items green and red.
For Sorting, you can use this
items = items.sort((fstItem, secItem)=> fstItem.total > secItem.total ? 1 :
fstItem.total < secItem.total -1 : 0 );

for second thing, you can use in html with first and last index from *ngFor

{{item.category}}

   {{item.total}}


text:
Q: unable to design vertical menu with image I am working on my college project, for which I have to add vertical menu bar in my project. I have searched a lot on Google, but could not find a code for creating a vertical menu with images. Can you please tell me how I can create this type of menu?
I want to create my menu like this:

i am trying like this , but text is getting placed at the bottom. i want it in middle.

Home

A: The basic idea is that you can vertical align the text and the image using display: inline-block and vertical-align: middle.

Roadster

Roadster

http://jsfiddle.net/YVp8E/11/http://jsfiddle.net/YVp8E/11/show
.nav {
   width: 25em;
}
.nav li {
  display: block;
}
.nav li a {
    color: #686868;
    display: block;
    padding: 10px 0;
}
.nav li {
    background: url(https://cdn2.iconfinder.com/data/icons/ios-7-icons/50/forward-128.png) no-repeat 100% 50%;

}
.nav li {
    border-top: 1px solid #ccc;
}
.nav li:first-child {
    border-top: none;
}
.nav span {
  display: inline-block;
  vertical-align: middle;
}
.nav .image {
  padding-left: 60px;
}

A: you can use :after pseudo element to achieve desire effect. Check the Demo.

Boxter

Cayman

911

/--Here is the CSS----*/
ul{margin:0; padding:0; list-style-type:none;}
li a
{
  display:block;
  border-bottom:1px solid grey;
  padding:25px 0;

}
li{ position:relative;}

li a:after
{
  content:">";
  position:absolute;
  right:20px;
  top:30px;
  vertical-align:middle;
}
li:nth-child(1):after
{
content:" ";
position:absolute;
right:50px;
top:0;
background:url("http://lorempixel.com/70/70") 0 20px no-repeat;
width:70px;
height:70px;
vertical-align:middle;
}
li:nth-child(2):after
{
content:" ";
position:absolute;
right:50px;
top:0;
background:url("http://placehold.it/70x70") 5px 20px no-repeat;
width:70px;
height:70px;
vertical-align:middle;
}