text:
Q: Why is the observable universe so big? The observable universe is approximately 13.7 billion years old. But yet it is 80 billion light years across. Isn't this a contradiction?

A: The universe is commonly defined as the totality of everything that exists, including all physical matter and energy, the planets, stars, galaxies, and the contents of intergalactic space.
No one knows if the universe is infinitely large, or even if ours is the only universe there is.
Although our view of the universe is limited, our imaginations are not. Astronomers have indirect evidence that the universe of galaxies extends far beyond the region we can see. But no one knows if the whole universe is infinitely large - large beyond limit.
According to the leading theories, other parts of the universe may look very different from our own - and may even have different laws of nature. We may never be able to find out for sure. But it is possible that clues to the answer lie in plain view, just waiting to be discovered!
I should note also the "80 billion light years across" it doesn't count as a contradiction. I don't know what your reference is but I believe that this concerns the region that we can see yet of this Universe.

A: You can travel as close to the speed of light as you want, but (assuming you're made from matter) you can't travel at the speed of light or faster.
So there's no reason why galaxies can't be receding from each other at 99.9999% the speed of light.  However, this isn't the whole story, as the expansion of spacetime can do funny things.  The universe isn't actually expanding as you'd expect from everyday life, as a explosion would, and there wasn't a "single point" that you can point to and say "that's where the big bang happened", it happened where you're sitting, and on the dark side of the moon, and just around the corner from Alpha Centauri...everywhere in fact.
Picture a graph - the point on the graph aren't moving away from each other (ie point A goes from (1,1) to (2,2) and point B goes from (5,5 to 7,7)) - instead, the whole graph, piece of paper and all, is being stretched.
This stretching is allowed to happen faster than the speed of light, as no matter actually has to change coordinates for it to happen.
In relation to the title of your question, the best answer is to ask "compared to what?".

A: This question implicitly refers to the visible universe, but we should state that explicitly, as otherwise the question doesn't make any sense.
It may seem like we shouldn't be able to see more than 13.7 billion light-years (13.7 giga-light-years, or glyrs) away, but that reasoning omits the expansion of spacetime according to General Relativity. A photon emitted from somewhere near the beginning of the Universe would have traveled nearly 13.7 glyrs if you had measured each light-year just as the photon crossed it, but since those light-years that you measured have expanded since the photon passed through, that distance now adds up to about 80 glyrs.

A: The radius of the observable universe is about 46 billion light years, which is considerably greater than its age of about 14 billion years. Since the radius of the observable universe is defined by the greatest distance from which light would have had time to reach us since the Big Bang, you might think that it would lie at a distance of only 14 billion light years, since $x=ct$ for motion at a constant velocity $c$. However, a relation like $x=ct$ is only valid in special relativity. When we write down such a relation, we imagine a Cartesian coordinate system $(t,x,y,z)$, which in Newtonian mechanics would be associated with a particular observer's frame of reference. In general relativity, the counterpart of this would be a Minkowski coordinate frame, but such frames only exist locally. It is not possible to make a single frame of reference that encompasses both our galaxy and a cosmologically distant galaxy. General relativity is able to describe cosmology using cosmological models, and this description is successful in matching up with observations to a high level of precision. In particular, no objects are observed whose apparent ages are inconsistent with their distances from us.
One way of describing this difference between special relativity's $x=ct$ and the actual distance-time relationship is that we can think of the space between the galaxies as expanding. In this verbal description, we can imagine that as a ray of light travels from galaxy A to galaxy B, extra space is being created in between A and B, so that by the time the light arrives, the distance is greater than $ct$.
None of this has anything to do with inflation. Inflation makes certain testable predictions about cosmological observations (e.g., it predicts that the universe is spatially flat), but it's irrelevant for understanding why the radius of the observable universe has the size it does in comparison to the age of the universe. Inflation may not even be correct. If inflation turns out never to have happened, it will have no effect on this particular question.
It turns out that we can get a surprisingly good estimate of the size of the observable universe using a simplified FRW cosmological model consisting only of dust, i.e., nonrelativistic matter. The approximation is good because the universe has spent most of its history dominated by matter, with only a very short period early on that was radiation-dominated, and another fairly recent era that is dominated by the cosmological constant. In accord with the current observational data, we make a second approximation, which is that the universe is spatially flat. In a spatially flat FRW model, the $r-t$ part of the metric is of the form $ds^2=dt^2-a^2dr^2$, where the scale function $a$ depends on time. For a photon, $ds=0$, and we can then show that the proper distance traversed by a photon since shortly after the Big Bang is given by $L=a \int dt/a$. For a matter-dominated solution, $a$ is proportional to $t^{2/3}$, and we find $L=3t$. This is quite close to the $L/t$ ratio of about 3.3 given by the most realistic models. It also makes sense that the result is somewhat greater than 3, because the universe has now entered an era in which its expansion is accelerating. In the future, $L/t$ will become greater and greater.

A: This is not a contraction.  Special Relativity does not say that nothing can travel faster than the speed of light.  Rather, it says that no regular matter can travel faster than the speed of light.  Therefore, instead of thinking galaxies move away from each other, think that the space between them is increasing.  That would mean that the space itself can beat the speed of light.

A: Briefly...
Consider a photon emitted 13.8 Gly ago (Gly = billion light years). As it travels through space, not only its getting farther away from its source due to traveling at the speed of light $c$, but photons distance also increases as the universe grows.

Technically...
To get technical, the expansion of the universe is captured by the scale factor $a(t)$ which is governed by the Friedmann's equation:
$$\frac{(a'(t)/a(t))^2}{H_ 0^2}=\frac{\Omega _{\text{R0}}}{a(t)^4}+\frac{\Omega _{\text{M0}}}{a(t)^3}+\frac{\Omega _{\text{$\kappa $0}}}{a(t)^2}+\Omega _{\text{$\Lambda
$0}}$$
where
the Hubble constant $H_0 = 67.8 \frac{\text{km}/\text{s}}{\text{Mpc}} = 0.0693 /\text{Gyr}$,
the present value of the radiation density $\Omega _{\text{R0}} = 0.0000905$,
the present value of the matter density
$\Omega _{\text{M0}} = 0.308$ (which mainly consist of dark matter) ,
the present value of the curvature density $\Omega _{\text{$\kappa $0}} = 1 - (\Omega _{\text{R0}} + \Omega _{\text{M0}} + \Omega _{\text{$\Lambda
$0}}) = 1$,
and the present value of the cosmological constant $\Omega _{\text{$\Lambda $0}} = 0.692$. These values are from the Plank Collaboration 2015. This equation can only be solve numerically. The following figure shows scale factor as a function of time:

In cosmology, the amount of distance a photon can travel in a given time is known as the comoving distance or the comoving horizon denoted by $\eta$:
$$\eta = \int_{0}^{t}\frac{c dt}{a(t)}$$
which again has to be evaluated numerically. By numerically integrating from 13.799 Gyr ago until the present time, a particle horizon of 43.5 Glyr is obtained which is the radios of the observable universe. One should take this value with a grain of salt since it is highly sensitive to $H_0$.

Biologically...
I would like to focus on "Why the observable universe is so big?" from different perspective. Alternatively we can ask why the observable universe is 13.8 Gyr old! This is not such an odd question to ask if we state it as the following: "Why are we, as observers, happen to look at the universe 13.8 Gyr after the big bang?" Given that intelligent life on earth took ~3.5 Gyr to rise and the conditions of the universe were too harsh to permit evolution of life during the first ~10 Gyrs, one could expect that most pockets of intelligent observers would form and study the universe ~15 Gyr after the big bang. However, it is very surprising to find ourselves at the dawn of formation of life given that life would flourish for many giga-years to come.

A: Yes this does sound like it might be a contradiction but in fact it isn't. It's because the universe has been expanding rapidly in every direction since the big bang and our observations are limited by the speed of light.
For example if we observe a distant quasar that appears to be 10 billion light years away, the light from the quasar is 10 billion years old (which is why quasars are known for being some of the most ancient phenomena in the universe). In the time it took for that light to reach us the universe has been expanding. In fact the expansion has been accelerating all that while so the distance between us and that quasar is at this present time considerably larger than 10 billion light years.
If we had a means to observe distant objects as they appear right at this instance, not only would we have a type of time machine but we might observe the universe to be 80 billion light years across, although I cannot vouch for the accuracy of the 80 billion light year figure given on the wikipedia page.
Astronomers and physicists also struggle with the question of "what is it that the universe expanding into". Is it expanding into empty space and if so is there anything that lies out there beyond our universe at some vast distance? If so, the universe may be infinite.
Or does the universe fold back in on itself on some higher dimensional plain i.e. if we had a hypothetical means to travel faster that the rate of the expansion of the universe and travelled in a straight line, would we eventually end up back in the same spot? In this scenario the universe would have a theoretical boundary at any one time.

A: The question asks about opposite edges of the observable universe, but it's a special case of a more general question:

How can two objects that move away from a common point for a time $Δt$ end up more than $2cΔt$ apart?

You don't need to understand general relativity to understand the answer to this question, since it can happen even in special relativity. For the rest of my answer I'll assume a basic familiarity with special relativity.
Alice and Bob zero their stopwatches at a common place and time, then move away from each other for 1 second as measured by the stopwatches (or as measured by saying "one potato"). How far apart are they at the end? That is, what is the spacetime interval between the two events of the stopwatches reading 1 second?
It's easy to show* that if they both move inertially, then the interval at the end is $\sqrt{2(γ{-}1)}$ light seconds, where $γ$ is the gamma factor of their relative speed. Since $γ$ can be arbitrarily large, so can the distance. It exceeds 2 light seconds when $γ>3$ ($v \gtrsim 0.94c)$, and it exceeds any finite value for a large enough (sublight) relative speed.
In Minkowski spacetime, the triangle inequality only holds when all three sides of the triangle are spacelike. In other cases, the length of the third side isn't constrained at all by the lengths of the other two. Our thought-experiment is the case where two of the sides are timelike and the third is spacelike. The case where all three sides are timelike is the twin paradox: the stay-at-home twin can be arbitrarily old when the traveling twin returns from their two-second jaunt.
We can make this look a little more like a cosmology by introducing Carol, Ted, etc. who also move inertially away from the same point (which we'll dub the big bang) for 1 proper second. They move at different speeds, but we'll require that the relative speeds of nearest neighbors be similar to each other (this is the homogeneity assumption in cosmology). Also, instead of measuring the straight-line spacetime interval between the most distant movers, we'll measure the intervals between nearest neighbors and add them up.
If you plot the worldlines of all the movers, the points where their stopwatches read 1 second will lie on a hyperbola with the equation $t^2-x^2 = 1\,\text{s}^2$ in inertial coordinates.** The distances we measure are polygonal approximations to distances along this hyperbola. You might think that these distances would be longer than the straight-line distances; actually, they're shorter, because as usual everything is backwards in spacetime. But they aren't enough shorter to change the fundamental conclusion that arbitrarily long distances are possible. You can always make a larger distance by increasing the relative speed of adjacent movers, or by adding more of them at the extremes.
This toy model is more than just an analogy. If you start with the ΛCDM model that describes the real world (post-inflation) and take all of the densities continuously to zero in an appropriate way, it continuously morphs into this toy model. In every intermediate model, sufficiently distant objects are farther apart than $2c$ times the cosmological time since the big bang, and there's no point in the process of taking the limit at which the reason for that changes. The spacetime of the real world is curved, but the nonzero curvature isn't the reason that this counterintuitive behavior is possible. The real reason is the mixed metric signature of spacetime.

Aside from the failure of the triangle inequality, another reason people find this so confusing is probably the heavy emphasis on Cartesian (inertial) coordinate systems when teaching special relativity. Einstein had a good reason in 1905 to construct this type of coordinate system: he was trying to make a connection to the traditional Newtonian picture of space and time for the benefit of his audience which still believed in that picture. Today, 115 years later, no one believes in that picture, but we still teach it. There's so much drilling of Cartesian coordinates and related formulas (time dilation, length contraction, etc.) that people get the idea that this is how the universe really works. In truth, the universe doesn't care about our coordinate systems. The closest thing in the real world to a universal network of synchronized clocks is the expanding galaxies, and they don't follow a Cartesian grid, but a kind of polar grid (albeit on a curved manifold). If you define "distance" and "time" by reference to a Cartesian grid, then you can't get more than $Δx=2cΔt$ away; but if you define them by reference to the polar grid that actually (after a fashion) exists, then you can – even in the limit where spacetime is flat.

* Pick units where 1 second = 1 light second = 1, and inertial coordinates where the starting point is $x=t=0$, Alice doesn't move, and Bob moves on the x axis. Then Alice's final position is $(x,t)=(0,1)$ and Bob's is $(x,t)=(γβ,γ)$, and the distance between them is $\sqrt{(γβ-0)^2-(γ-1)^2}$ = $\sqrt{2γ-2}$.
** If you add more spatial dimensions, it's a hyperboloid, which in Minkowski space is a surface of constant negative curvature. This model is a zero-density limit of the FLRW cosmology, and this is why space is negatively curved in that limit, and not flat as you might expect: the FLRW coordinates are analogous to polar coordinates and "space" is a sphere of constant radius (cosmological time). In a Euclidean space it would have constant positive curvature; in Minkowski spacetime everything is backwards.


text:
Q: Running an IRC bot on Heroku I've got my bot up and running, and I would like it to run on Heroku to keep it persistently connected to our IRC-channel. This is the content of my procfile:
web: coffee marvin.coffee

(The bot's name is marvin).
And this is marvin.coffee
irc = require 'irc'
config = require('./config').config

client = new irc.Client(config.server, config.nick, config.options)

# IRC-listeners

I'm never creating any HTTP server, and I was hoping that it was possible to simply run this coffeescript on Heroku in order for my bot to run, but I get the following error:
 Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

The bot is launched, and joins the channel, but immediately leaves due to the fact that Heroku kills the process due to this error.
Any help would be greatly appreciated :-)

A: Does it work if you change web: coffee marvin.coffee to bot: coffee marvin.coffee in your Procfile?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Labels on Rects in Vega Stacked Bar Chart In the old vega-label documentation there is reference to a labeled stacked bar chart example. The example spec doesn't work in the online Vega editor, throwing an error that a.map is not a function.
I am trying to do almost exactly what is referenced in the above example: create a vertically-stacked bar chart where each segment is labeled with its value. I have seen a few examples of this in Vega-Lite with layers, but how can it be achieved in Vega?
I've attempted to recreate the above spec using a group containing the rect mark and the text mark, but I'm not getting it right. I also see how to display the value as a tooltip on hover, but I'd like it displayed in the rectangle of each segment of the bar itself.
Ideally I would end up with a chart like this:

Here's the spec I've been working with:
{
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "description": "A basic stacked bar chart example.",
  "width": 294,
  "height": 200,
  "padding": 5,
  "autosize": {"type": "fit-x", "contains": "padding"},

  "data": [
    {
      "name": "categories",
      "values": [
        {"y": 5, "c": 0, "name": "other"},
        {"y": 7, "c": 1, "name": "corn"},
        {"y": 22, "c": 2, "name": "pasture/hay"},
        {"y": 31, "c": 3, "name": "developed"},
        {"y": 35, "c": 4, "name": "forest"}
      ],
      "transform": [
        {
          "type": "stack",
          "field": "y"
        }
      ]
    }
  ],

  "scales": [
    {
      "name": "y",
      "type": "linear",
      "range": "height",
      "nice": true, "zero": true,
      "domain": {"data": "categories", "field": "y1"}
    },
    {
      "name": "color",
      "type": "ordinal",
      "range": "category",
      "domain": {"data": "categories", "field": "c"}
    }
  ],

  "axes": [
  ],

  "marks": [
    {
      "name": "categoriesBars",
      "type": "group",
      "from": {"data": "categories"},
      "zindex": 1,
      "marks": [
        {
          "type": "rect",
          "from": {"data": "categories"},
          "encode": {
            "enter": {
              "x": {"value": 0},
              "width": {"value": 294},
              "y": {"scale": "y", "field": "y0"},
              "y2": {"scale": "y", "field": "y1"},
              "fill": {"scale": "color", "field": "c"}
            },
            "update": {
              "fillOpacity": {"value": 1}
            },
            "hover": {
              "fillOpacity": {"value": 0.5}
            }
          }
        },
        {
          "type": "text",
          "encode": {
            "enter": {
              "y": {"field": {"parent": "y"}},
              "x": {"value": 130},
              "fill": [
                {"test": "contrast('white', datum.fill) > contrast('black', datum.fill)", "value": "white"},
                {"value": "black"}
              ],
              "align": {"value": "center"},
              "baseline": {"value": "middle"},
              "text": {"field": {"parent": "name"}}
            }
          }
        }
      ]
    }
  ]
}

A: Is this what you're after?

{
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "description": "A basic stacked bar chart example.",
  "width": 294,
  "height": 200,
  "padding": 5,
  "autosize": {"type": "fit-x", "contains": "padding"},
  "data": [
    {
      "name": "categories",
      "values": [
        {"y": 5, "c": 0, "name": "other"},
        {"y": 7, "c": 1, "name": "corn"},
        {"y": 22, "c": 2, "name": "pasture/hay"},
        {"y": 31, "c": 3, "name": "developed"},
        {"y": 35, "c": 4, "name": "forest"}
      ],
      "transform": [{"type": "stack", "field": "y"}]
    }
  ],
  "scales": [
    {
      "name": "y",
      "type": "linear",
      "range": "height",
      "nice": true,
      "zero": true,
      "domain": {"data": "categories", "field": "y1"}
    },
    {
      "name": "color",
      "type": "ordinal",
      "range": {"scheme": "pastel2"},
      "domain": {"data": "categories", "field": "c"}
    }
  ],
  "axes": [],
  "marks": [
    {
      "name": "i",
      "type": "rect",
      "from": {"data": "categories"},
      "encode": {
        "enter": {
          "x": {"value": 0},
          "width": {"value": 294},
          "y": {"scale": "y", "field": "y0"},
          "y2": {"scale": "y", "field": "y1"},
          "fill": {"scale": "color", "field": "c"}
        },
        "update": {"fillOpacity": {"value": 1}},
        "hover": {"fillOpacity": {"value": 0.5}}
      }
    },
    {
      "type": "text",
      "from": {"data": "i"},
      "encode": {
        "update": {
          "y": {"field": "y"},
          "dy": {"signal": "(datum.y2 - datum.y)/2"},
          "x": {"signal": "width/2"},
          "fill": [
            {
              "test": "contrast('white', datum.fill) > contrast('black', datum.fill)",
              "value": "white"
            },
            {"value": "black"}
          ],
          "align": {"value": "center"},
          "baseline": {"value": "middle"},
          "text": {"field": "datum.name"}
        }
      }
    }
  ]
}


text:
Q: How to compute for the mean and sd I need help on 4b please

*'Warpbreaks' is a built-in dataset in R. Load it using the function data(warpbreaks). It consists of the number of warp breaks per loom, where a loom corresponds to a fixed length of yarn. It has three variables namely, breaks, wool, and tension.
b.    For the 'AM.warpbreaks' dataset, compute for the mean and the standard deviation of the breaks variable for those observations with breaks value not exceeding 30.
data(warpbreaks)
warpbreaks <- data.frame(warpbreaks)
AM.warpbreaks <- subset(warpbreaks, wool=="A" & tension=="M")

mean(AM.warpbreaks<=30)
sd(AM.warpbreaks<=30)

This is what I understood this problem and typed the code as in the last two lines. However, I wasn't able to run the last two lines while the first 3 lines ran successfully. Can anybody tell me what is the error here?
Thanks! :)

A: Another way to go about it:
This way you aren't generating a bunch of datasets and then working on remembering which is which. This is more a personal thing though.
data(warpbreaks)
mean(AM.warpbreaks[which(AM.warpbreaks$breaks<=30),"breaks"])
sd(AM.warpbreaks[which(AM.warpbreaks$breaks<=30),"breaks"])

A: There are two problems with your code.  The first is that you are comparing to 30, but you're looking at the entire data frame, rather than just the "breaks" column.
AM.warpbreaks$breaks <= 30

is an expression that refers to the breaks being less than thirty.
But mean(AM.warpbreaks$breaks <= 30) will not give the answer you want either, because R will evaluate the inner expression as a vector of boolean TRUE/FALSE values indicating whether that break is less than 30.
Generally, you just want to take another subset for an analysis like this.
AM.lt.30 <- subset(AM.warpbreaks, breaks <= 30)
mean(AM.lt.30$breaks)
sd(AM.lt.30$breaks)


text:
Q: How to sync the line to line flow of two methods in testng parallel execution? I have two methods as shown below.
I'm executing the suite using testng.xml by keeping thread-count="2" parallel="methods" so that all @Test methods will be executed parallelly.
 @Test
 //this method will be executed in firefox
 public void method1(){
     WebDriver driver=new FirefoxDriver();
     driver.get("https://google.co.in");
     line2;
     line3;
 }

  @Test
 //this method will be executed other window of firefox
 public void method2(){
     WebDriver driver=new FirefoxDriver();
     driver.get("https:gmail.com");  //has to be executed only after the opening of google in method1
     line2;  //has to be executed after the line2 of method1
     line3;  //has to be executed after the line3 of method1
 }

Two methods will run parallelly without depending on each other. But as per my requirement (mentioned in the code comments) is it possible to make the execution of method2 to depend on the execution of method1?

A: Add the below dependsOnMethods in @Test
@Test(dependsOnMethods = { "method1" })
public void method2(){
       .....
}


text:
Q: Laravel API Authentication - Passport Token I'm building an API using Laravel. For authentication and security I am using Passport: https://laravel.com/docs/5.7/passport
I followed all the steps in the documentation. I am working with several profiles that pass through authentication, and I came across a problem, the token used by a middleware can be applied in other middleware.
In my config / auth.php file it looks like this:
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'user' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],

    'producer' => [
        'driver' => 'passport',
        'provider' => 'producers',
    ],

    'coordinator' => [
        'driver' => 'passport',
        'provider' => 'coordinators',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    'producers' => [
        'driver' => 'eloquent',
        'model' => App\Producer::class,
     ],

     'coordinators' => [
        'driver' => 'eloquent',
        'model' => App\Coordinator::class,
     ],
],

The Coordinator model looks like this:
class Coordinator extends Authenticatable{

use HasApiTokens, Notifiable;

protected $table = 'coordinators';
protected $guard = 'coordinator';

protected $fillable = [
    'coordinator_name', 'email', 'password', 'cpf_cnpj', 'phone'
];

protected $hidden = [
    'password',
];

public function events(){
    return $this->belongsToMany('App\Event')->using('App\EventCoordinator');
}}

And the Model Producer looks like this:
class Producer extends Authenticatable{
use HasApiTokens, Notifiable;

protected $guard = 'producer';

protected $fillable = [
    'name', 'email', 'password', 'cpf_cnpj', 'phone', 'street', 'neighborhood', 'city', 'state', 'number', 'zipcode', 'complement'
];

protected $table = 'producers';

protected $hidden = [
    'password',
];

public function events(){
    return $this->hasMany('App\Event');
}}

On the routes I'm using the middleware set in auth.php
Route::middleware('auth:producer')->group(function() {
    Route::get('events', 'ProducerController@events');
});

Route::middleware('auth:coordinator')->group(function() {
    Route::get('events', 'CoordinatorController@events');
});

And finally the events method in the CoordinatorController looks like this:
public function events(){
    try{
        if(Auth::guard('coordinator')->check()){
            $events = Auth::user()->events;

            return response()->json(['events' => $events], 200);
        }else{
            return response()->json(['error' => ['message' => 'Usuário não autenticado.']], 421);
        }
    }catch(\Exception $err){
        return response()->json(['error' => ['code' => $err->getCode(), 'message' => $err->getMessage()]], 400);
    }
}

and in ProducerController:
public function events(){
    try{
        try{
        if(Auth::guard('producer')->check()){
            $events = Auth::user()->events;

            return response()->json(['events' => $events], 200);
        }else{
            return response()->json(['error' => ['message' => 'Usuário não autenticado.']], 421);
        }
    }catch(\Exception $err){
        return response()->json(['error' => ['code' => $err->getCode(), 'message' => $err->getMessage()]], 400);
    }
}

I am using Postman for testing, and when I use the Producer token to access the Coordinator method it works even though using different middleware in the route. Can anyone help? Something is missing?

A: as far as I know, passport didn't support MultiAuth
you can use widely available 3rd party multiauth support for laravel, like this package.


text:
Q: Is the rows of matrix $\{\{1,2,2\}, \{−1,2,1\}, \{0,8,6\}\}$ a basis of $\mathbb{R}^3$ Is the rows of matrix  $\{\{1,2,2\}, \{−1,2,1\}, \{0,8,6\}\}$ a basis of $\mathbb{R}^3$?
The answer given to me for this is "no, it is not".
But can anyone tell me why? I solved it through row reduction but I don't understand why it is not a basis of $\mathbb{R}^3$.

A: I assume the $3$ vectors from your matrix are $(1,2,2)$, $(-1,2,1)$ and $(0,8,6)$. If so, they are not linearly independent, since $2$ times the first plus $2$ times the second gives the third one. In particular,
$$\begin{equation}\begin{aligned}
2 \times (1,2,2) + 2 \times (-1,2,1) & = (2,4,4) + (-2,4,2) \\
& = (0,8,6)
\end{aligned}\end{equation}\tag{1}\label{eq1A}$$
Thus, they cannot cannot be a basis for $R^3$ as that requires $3$ linearly independent vectors.

A: octave:1> rref([1, 2,2; -1, 2, 1; 0, 8, 6])
ans =

   1.00000   0.00000   0.50000
   0.00000   1.00000   0.75000
   0.00000   0.00000   0.00000

Since you mention row reduction, I have included the RREF. Row reduction doesn't change the dimension. As you can see, there are only two linearly independent rows but the dimension of $\mathbb{R}^3$ is $3$. Hence it can't be a basis.


text:
Q: Laravel 5.2 can't set offset $request->page I'm having trouble creating a custom pagination.
If I do this, it does not work:
$page = json_decode($request->page);
// $page = 5;
$offset = $page * $limit - $limit;

$query->offset($offset);
$query->limit($limit);

If i do this, it works:
// $page = json_decode($request->page);
$page = 5;
$offset = $page * $limit - $limit;

$query->offset($offset);
$query->limit($limit);

When I var_dump, I can see both $page values are int.
What am I missing?


text:
Q: I'm creating an RSS reader and having trouble with feedburner feeds I'm using the Google Feed API to get feeds and the results contain an link field which is great however a feedburner feed returns something to the effect of google.feedproxy.blahblahblah and I need the actual url for the html.  The google.feedproxy url will redirect.  Is there a way using Javascript for me to get the url that is being redirected to?  Or even just a more elegant way of getting the html url?
Any help is appreciated.

A: Grab the text in <feedburner:origLink>.  it's available in most of the feedburner feeds.

A: Make sure your Accept header is limited to the RSS and Atom MIME types. If by HTML URL, you mean the site for the feed, look for a <link rel="alternate"/> in the feed itself, as its href is the relevant site.


text:
Q: tolower function of the corpus package throws an error I trying to do some text mining using twitter data. I do the following:
#connect to twitter API
setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_secret)

#set radius and amount of requests
N=200  # tweets to request from each query
S=200  # radius in miles

lats=c(38.9,40.7)
lons=c(-77,-74)

roger=do.call(rbind,lapply(1:length(lats), function(i) searchTwitter('Roger+Federer',
                                                                  lang="en",n=N,resultType="recent",
                                                                  geocode=paste(lats[i],lons[i],paste0(S,"mi"),sep=","))))

This all works fine but when I want to use the tolower function of the corpus package like this:
data=as.data.frame(cbind(tweet=rogertext))
corpus=Corpus(VectorSource(data$tweet))
corpus=tm_map(corpus,tolower)

It trows this error:
> corpus=tm_map(corpus,tolower)
Error in FUN(X[[i]], ...) :
invalid input 'RT @Federerism: Roger Federer reaches  5 million followers   on twitter  Love You Roger í ½í¸˜ í ½í¸ í ½í¸˜ í ½í¸ #Roger #Federer #   Federerism #Maestro https:/…' in 'utf8towcs'

Any thought on what goes wrong?

A: base::tolower chokes on special characters. This is often a problem when mining tweets. You could try catching errors or just use stringi's tolower pendant:
# tw <- searchTwitter('Roger Federer reaches  5 million followers   on twitter  Love You Roger', n=1)
download.file("https://www.dropbox.com/s/33ilhcu2v82nwuq/twitter_tolower.rda?dl=1", tf <- tempfile(fileext = ".rda"), mode="wb")
load(tf)

tw[[1]]$getText()
# [1] "RT @Federerism: Roger Federer reaches  5 million followers on twitter  Love You Roger \xed��\xed�\u0098 \xed��\xed�\u008d \xed��\xed�\u0098 \xed��\xed�\u008d #Roger #Federer # Federerism #Maestro https:/…"

## Does not work:
tolower(tw[[1]]$getText())
# Error in tolower(tw[[1]]$getText()) :
#   invalid input 'RT @Federerism: Roger Federer reaches  5 million followers on twitter  Love You Roger í ½í¸˜ í ½í¸ í ½í¸˜ í ½í¸ #Roger #Federer # Federerism #Maestro https:/…' in 'utf8towcs'

## Works:
stringi::stri_trans_tolower(tw[[1]]$getText())
# [1] "rt @federerism: roger federer reaches  5 million followers on twitter  love you roger \xed��\xed�\u0098 \xed��\xed�\u008d \xed��\xed�\u0098 \xed��\xed�\u008d #roger #federer # federerism #maestro https:/…"

## Works, too:
library(tm)
corp <- Corpus(VectorSource(tw[[1]]$getText()))
corp <- tm_map(corp, content_transformer(stringi::stri_trans_tolower))
content(corp[[1]])
# [1] "rt @federerism: roger federer reaches  5 million followers on twitter  love you roger \xed��\xed�\u0098 \xed��\xed�\u008d \xed��\xed�\u0098 \xed��\xed�\u008d #roger #federer # federerism #maestro https:/…"

A: Try the following:
corpus <- tm_map(corpus, content_transformer(tolower))

There has been a change of syntax in the tm package a few years ago. Hope this solves the problem.


text:
Q: progress dialog getting error in android i have asynctask class and i try to send http request.i also use progress dialog but i can't show progress dialog.i have error
this is a my source
private class SendAccesssTokenToServer extends
        AsyncTask<String, Void, String> {
    ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(getActivity());

        pDialog.setCancelable(false);
        pDialog.show();
        pDialog.setContentView(R.layout.custom_progressdialog);
    }

    @Override
    protected String doInBackground(String... params) {
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (pDialog != null) {
            pDialog.dismiss();

            pDialog = null;
        }

        Log.e("Result issss", result + "res");

    }
}

this is a my logical error

how i can solve my problem ? if anyone knows solution please help me
thanks

A: You have placed the code wrongly. Check for the right code below:
private class SendAccesssTokenToServer extends
    AsyncTask<String, Void, String> {
ProgressDialog pDialog;

@Override
protected void onPreExecute() {
    super.onPreExecute();

    pDialog = new ProgressDialog(getActivity());
    pDialog.setContentView(R.layout.custom_progressdialog);
    pDialog.setCancelable(false);
    pDialog.show();

}

@Override
protected String doInBackground(String... params) {
    return null;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);

    if (pDialog != null) {
        pDialog.dismiss();
    }

 }
}

A: @Override
protected void onPreExecute()
{

    super.onPreExecute();

    pDialog = new ProgressDialog(LoginActivity.this);

    pDialog.setMessage("Loading car. Please wait...");

    pDialog.setIndeterminate(false);

    pDialog.setCancelable(false);

    pDialog.show();
}

protected void onPostExecute(String file_url)
{
     // dismiss the dialog after getting values

     pDialog.dismiss();

}

A: @Override
protected void onPreExecute() {
    super.onPreExecute();

    pDialog = new ProgressDialog(getActivity());

    pDialog.setCancelable(false);
    pDialog.show();
    pDialog.setContentView(R.layout.custom_progressdialog);
}

First you show the progressDialog then assign another layout without dissmiss the previous progressDialog. Thas why you get that error.
Just change the code like this :-
@Override
protected void onPreExecute() {
    super.onPreExecute();

    pDialog = new ProgressDialog(getActivity());
    pDialog.setContentView(R.layout.custom_progressdialog);
    pDialog.setCancelable(false);
    pDialog.show();

}

Hope this will help you :)


text:
Q: Windows 8.1, moving files between drives with overwrite I have 2 file backup drives that are not in sync. In order to make sure that I have a complete copy, I would like to move all the files from drive 1 to drive 2 and overwrite them. That way, drive 2 will be a merge of both drives' contents. I can then copy all the files back to emptied drive 1.
When doing this in Windows Explorer (Win 8.1), I'm getting an error that says that I don't have enough space. That's actually not the case because there's a big overlap in those two drives.
How can I execute the move that I have just described without having to deal with such an error?
Thnaks.

A: I would use a sync program to sync the 2 files - e.g. the free version of Allway Sync or any other.


text:
Q: object recognition performance not good I am trying to do object recognition using algorithms such as SURF, FERN, FREAK in opencv 2.4.2.
I am using the programs from opencv samples without modifications - find_obj.cpp, find_obj_ferns.cpp, freak_demo.cpp
I tried changing the parameters for the algorithms which didn't help.
I have my training images, test images and the result of FREAK recognition here
As you can see the result is pretty bad.

*

*No feature descriptors is detected for one of the training image - image here

*Feature descriptors are detected outside the object boundary for the other - image here
I have a few questions:

*

*Why does these algorithms work with grayscale images ? It is apparent that for my above training images, the object can be detected easily if RGB is included. Is there any technique that takes this into account.

*Is there any other way to improve performance. I tried fiddling with feature parameters which didn't work well.

A: First thing i observed in your image is, object is plane and no texture differences are there...I mean all the feature detectors you used are for finding corners which are view invariant, it means those are the keypoints in an image which are having unique neighborhood and good magnitude of x and y derivatives. I have uploaded my analysis...see the figures
How to know what I am saying is correct?
Just go to the descriptor values of a keypoint you find over your object and see the values, you will see most of them are zeros...Because a descriptor is the description of variation of the edges around a corner point in a specific direction (see surf documentation for more details).
The object you are trying to detect is looking like a mobile phone, so you just reverse the object or mobile and repeat the experiment and you will surely get good results...Because on front side generally objects have more texture like switches, logos etc..
Here is a result I uploaded,


text:
Q: Touch Bar, how to add a scrollable list of buttons? I'd like to show a scrollable list of buttons in my app's Touch Bar, similar to how Safari shows favourites when typing an address.
A scroll view doesn't seem to be one of the standard TouchBar controls. Which controls do you use for this?

A: NSScrollView is actually supported on the TouchBar (https://developer.apple.com/reference/appkit/nstouchbar#2587738).
NSScrubber is intended to be a picker of items, similar to a segmented control but with the added benefit of a scrollable list. NSScrubber also manages it's own highlighted state and will eat up touch events.
You can get a horizontal scrollable list of NSButtons by popping them into a scroll view. Here's a quick example using constraints to create an NSCustomTouchBarItem:
  NSScrollView *scrollView = [[NSScrollView alloc] initWithFrame:CGRectMake(0, 0, 400, 30)];

  NSMutableDictionary *constraintViews = [NSMutableDictionary dictionary];
  NSView *documentView = [[NSView alloc] initWithFrame:NSZeroRect];

  NSString *layoutFormat = @"H:|-8-";
  NSSize size = NSMakeSize(8, 30);

  for (int i = 0; i <= 8; i++) {
    NSString *objectName = [NSString stringWithFormat:@"button%@",@(i)];
    NSButton *button = [NSButton buttonWithTitle:objectName
                                          target:nil
                                          action:nil];
    button.translatesAutoresizingMaskIntoConstraints = NO;
    [documentView addSubview:button];

    // Constraint information
    layoutFormat = [layoutFormat stringByAppendingString:[NSString stringWithFormat:@"[%@]-8-", objectName]];
    [constraintViews setObject:button forKey:objectName];
    size.width += 8 + button.intrinsicContentSize.width;
  }

  layoutFormat = [layoutFormat stringByAppendingString:[NSString stringWithFormat:@"|"]];

  NSArray *hConstraints = [NSLayoutConstraint constraintsWithVisualFormat:layoutFormat
                                                                  options:NSLayoutFormatAlignAllCenterY
                                                                  metrics:nil
                                                                    views:constraintViews];

  [documentView setFrame:NSMakeRect(0, 0, size.width, size.height)];
  [NSLayoutConstraint activateConstraints:hConstraints];
  scrollView.documentView = documentView;

  NSCustomTouchBarItem *item = [[NSCustomTouchBarItem alloc] initWithIdentifier:@"com.TouchBar.scrollButtons"];
  item.view = scrollView;

A: As you probably know, you add NSTouchBarItems to a TouchBar instance in order to add items to a Touch Bar.
In order to add a scrollable list, create an instance of NSScrubber. Once that's set up, you'll need to add that NSScrubber to a custom instance of NSCustomTouchBarItem, most likely to the view property. Then, you can add that item to the Touch Bar. Be sure to read the linked documentation.

A: I just translated the code from Santiago Gil to Swift 4.
let scrollView = NSScrollView(frame: CGRect(x: 0, y: 0, width: 400, height: 30))
var constraintViews: Dictionary<String, Any> = [:]
let documentView = NSView(frame: NSZeroRect)

var layoutFormat: String = "H:|-8-"
var size = NSSize(width: 8, height: 30)

for i in 0...8 {
    let objectName: String = "button\(i)"
    let button: NSButton = NSButton(title: objectName, target: nil, action: nil)
    button.translatesAutoresizingMaskIntoConstraints = false

    documentView.addSubview(button)

    // Constraint Information

    layoutFormat += "[\(objectName)]-8-"
    constraintViews[objectName] = button
    size.width += 8 + button.intrinsicContentSize.width

}

layoutFormat += "|"

let hConstraints: Array<NSLayoutConstraint> = NSLayoutConstraint.constraints(withVisualFormat: layoutFormat, options: .alignAllCenterY, metrics: nil, views: constraintViews)

documentView.frame = NSRect(x: 0, y: 0, width: size.width, height: size.height)
NSLayoutConstraint.activate(hConstraints)

scrollView.documentView = documentView

let item = NSCustomTouchBarItem(identifier: .controlScrubber)

item.view = scrollView

Hopefully this helps someone ;-)


text:
Q: How to compare two Persian date via Linq-to-Entities? I have a table as follow in oracle 11g:
Persons Table:
|ID      |FirstName|LastName|PersianBirthDate|
|1       |FName1   |LName1  |"1362/01/01"    |
|2       |FName2   |LName2  |"1359/05/01"    |
|3       |FName3   |LName3  |"1350/04/11"    |
|4       |FName4   |LName4  |"1355/02/10"    |
|5       |FName5   |LName1  |"1365/12/25"    |

When i want to get rows that their PersianDateBirthDate are less than "1362/01/01" like as below:
|ID      |FirstName|LastName|PersianBirthDate|
|2       |FName2   |LName2  |"1359/05/01"    |
|3       |FName3   |LName3  |"1350/04/11"    |
|4       |FName4   |LName4  |"1355/02/10"    |

I use following code in EntityFramework (code-first):
using (var db = new MyContext())
{
  return (db.Persons
            .Where(x=>
                      PersianDateTime.Parse(x.PersianBirthDate).ToDateTime()
                      < PersianDateTime.Parse("1362/01/01").ToDateTime())
            .ToList();
}

But the following exception occurs:
LINQ to Entities does not recognize the method 'System.DateTime ToDateTime()' method, and this method cannot be translated into a store expression.

I can't use db.persons.AsEnumerable().
Note: The datatype of PersianBirthDate is char(10) and
PersianDateTime library convert Persian Date to Gregorian Date.

A: According to @KristoferA comment, we can use code below:
db.Persons
  .Where(x => x.PersianBirthDate.CompareTo("1362/01/01") < 0).ToList();

And then the following SQL is sent to DB:
 SELECT
[Extent1].[ID] AS [ID],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
[Extent1].[PersianBirthDate] AS [PersianBirthDate]
FROM [dbo].[Persons] AS [Extent1]
WHERE [Extent1].[PersianBirthDate] < N'1362/01/01'

But I think, We can improve this solution.

A: This should work:
p.Where(x => ((int)x.PersianBirthDate.Substring(0,4)) < year) ||
             (((int)x.PersianBirthDate.Substring(0,4)) = year) && ((int)x.PersianBirthDate.Substring(5,2) < month)) ||
             (((int)x.PersianBirthDate.Substring(0,4)) = year) && ((int)x.PersianBirthDate.Substring(5,2) = month)  && ((int)x.PersianBirthDate.Substring(8,2) <= day)


text:
Q: Can I do this with data.table without using the merge() function? I work with very huge datasets and I'm trying to speed up my R code.
Here is an example of data :
dt <- data.table(id = c(100,101,102,103, 104), sex = c("m","f","m","m","f"),
value = c(32,14,32,03,03))

data look like this :
    id sex value
1: 100   m    32
2: 101   f    14
3: 102   m    32
4: 103   m     3
5: 104   f     3

The final output I want :
   value f.value m.value f   m
1:     3    1       1    1   1
2:    14    1       NA   1   NA
3:    32    NA      2    NA  2

The code I currently use :
dt_u <- unique(dt, by = c("id", "sex", "value"))
dt_u <- dt_u[, .(n = .N), keyby = .(value, sex)]
dt_u <- dcast(dt_u, value ~ sex, value.var = "n")
dt_t <- dt[, .(n = .N), keyby = .(value, sex)]
dt_t <- dcast(dt_t, value ~ sex, value.var = "n")
dt <- merge(dt_t, dt_u, by = "value", all = TRUE)

The code is working great, the problem is that the merging of dt_u and dt_t can take a lot of time on 10GB + data. So my question is : Is it possible to get the same final output without having to "split" the data and then merging it?
Also I would like the answer to be in data.table if possible,
thank you.
EDIT : example and explaination. The ID represent a person, this person can go to the same location (value) more than one time. For this example you can say that each value represent a different city.
IE:
dt <- data.table(value = c(21,21,21,21,21,40,1,22,1,1,22, 22, 49,
49,21,21,1,1,1), id =
c(1000716624,1000722724,1000716624,1000746824,1001012024,
1002067324,1002743624,1002743645, 1002743636,
1002743423,1000716624,1000722724, 1000722724,1001012024,
1000716624,1000716624,1002743624,1002743624,1002743624), sex = c("f", "m",
"m", "m", "f", "f", "m", "f", "f", "m", "f", "m", "m", "f","f","f", "m",
"m", "m"))

Output :
 value   places_women   places_men  number_women   number_men
1:     1            1          5            1          2
2:    21            4          3            2          3
3:    22            2          1            2          1
4:    40            1         NA            1         NA
5:    49            1          1            1          1

A: This works for the second example (based on reverse engineering the desired output):
> dcast(dt, value ~ sex, value.var=list("value", "id"), fun=list(length, uniqueN), fill=NA)
   value value.1_length_f value.1_length_m id_uniqueN_f id_uniqueN_m
1:     1                1                5            1            2
2:    21                4                3            2            3
3:    22                2                1            2            1
4:    40                1               NA            1           NA
5:    49                1                1            1            1

A more explicit description of what calculations are supposed to be in each column (and maybe more natural column names in the example) would help if this doesn't work for the full problem.

A: library(data.table)

dt <- data.table(id = c(100,101,102,103, 104), sex = c("m","f","m","m","f"),
                 value = c(32,14,32,03,03))

dcast(unique(unique(dt,
                    by = c("id", "sex", "value"))[ ,

            count := .N, by = list(value,sex)][,
        id:=NULL]),
value ~ sex, value.var = "count")

#>    value  f  m
#> 1:     3  1  1
#> 2:    14  1 NA
#> 3:    32 NA  2

Created on 2019-05-29 by the reprex package (v0.3.0)


text:
Q: When inherited, will the require https be included? Defined:
#if !DEBUG
        [RequireHttps]
#endif
[Authorize(Roles="Admin")]
public class AdminAuthorizeController : Controller { }

Used:
public class GlobalCrudController : AdminAuthorizeController

Will this ensure that the GlobalCrudController will have the [RequireHttps] markup when not in DEBUG mode?

A: Yes, has this parameter. Attributes are inherited in C# in this case. A conditional compilation statement like the one you have used is pretty simple. It will include the code if the statement is true, otherwise it will not.

A: Yes, because this attrib is already applied to RequireHttpsAttribute:
[AttributeUsage(AttributeTargets.Class, Inherited=true)]

A: Yes, RequireHttps attribute has inherited property "true".
Your condition does not influence on the inheritance.
But you can write your own attribute to avoid this inheritance like in this example - https://stackoverflow.com/a/747208/775779


text:
Q: jacoco as surefire argLine - The command line is too long I'm running Jacoco as an agent to surefire
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.18.1</version>
    <configuration>
        <argLine>${jacoco.agent.argLine}</argLine>
    </configuration>
</plugin>

I'm configuring Jacoco with a large list of exclusions (constants and my deprecated classes) for my build-breaker.
<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.7.5.201505241946</version>
    <configuration>
        <excludes>
            <exclude>*/*Test</exclude>
            <exclude>*/*Constants*</exclude>
            <exclude>${jacoco.exclusions.list}</exclude>
        </excludes>
    </configuration>

What I'm getting is that when I go to run the tests I get the error:

 T E S T S
-------------------------------------------------------
The command line is too long.

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

Is there another way to pass the exclusions list to Jacoco than on the agent parameter arglist on the command line? (Looking at the code it doesn't look like it)
My question is: How to pass the list of exclusions to the Jacoco agent running in surefire other than on the command line?

A: As of today JaCoCo Java Agent doesn't allow reading of options from files.
However you can specify agent via environment variable JAVA_TOOL_OPTIONS, which supposed to have bigger size limit than command line.
Also JaCoCo in offline mode (without agent) allows to provide configuration via file jacoco-agent.properties.


text:
Q: Static dropdown list showing ID value instead of text on index view How can i show the value i mean the text instead of the ID value of static dropdownlist in razor view here is the code
<td>
    @Html.DisplayFor(modelItem => item.Program_duration_Years)
</td>

and here it is in create view
@Html.DropDownListFor(model=>model.Program_duration_Years, new List<SelectListItem>
{
    new SelectListItem{ Text="Select Duration", Value = "0" },
    new SelectListItem{ Text="One year", Value = "1" },
    new SelectListItem{ Text="Two Year", Value = "2" },
     new SelectListItem{ Text="Three year", Value = "3" },
    new SelectListItem{ Text="Four Year", Value = "4" },
     new SelectListItem{ Text="Five year", Value = "5" },
 }, new { @class = "form-control", @id = "ddlduration" })
 @Html.ValidationMessageFor(model => model.program_type, "", new { @class = "text-danger" })


text:
Q: Hiding GET variables with sockets I have a script where i send a GET request to a page. Im trying to figureout how to surpress the output, here is the code itself:
use  IO::Socket;
my $domain = 'yahoo.com';

$socket=IO::Socket::INET->new(
                                Proto => 'tcp',
                                PeerAddr => $domain,
                                PeerPort => '80',
                                ) or return $!;
print $socket "GET /index.php HTTP/1.0\r\n";
print $socket "Host: ", $domain, "\r\n";
print $socket "Connection: close", "\r\n";
print $socket "User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)", "\r\n";
print $socket "Accept: text/html, application/xhtml+xml, */*", "\r\n\r\n";

print while <$socket>;

Here is the output.
HTTP/1.0 200 OK
Server: nginx/1.4.7
Content-Type: text/html
X-Powered-By: PHP/5.4.27-1~dotdeb.0
Set-Cookie: PHPSESSID=k2bviiurukqdju1l26j4fat0q0; path=/
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Date: Sun, 18 May 2014 19:53:20 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
X-Page-Speed: 119_1_jt
X-XSS-Protection: 1; mode=block
Alternate-Protocol: 80:quic

Apache works!

As you can see it shows the full page headers at the top, i just want the page output.
How could i suppress the output of the server headers? And just keep the page data.

A: If you are just trying to make web requests, it is almost always better to just use an http library.
For this particular case, however, the following should also suffice. It simply prints everything after the first line with only \r\n, because that is the delimiter used to separate the headers from content in the http protocol.
# The following line has been replaced with the loop
# print while <$socket>;

$seennl = 0;
while (<$socket>) {
    if ($seennl) {
        print;
    }
    elsif ($_ eq "\r\n"){
        $seennl=1;
    }
}

A: The HTTP standard specifies that the headers and the contents are separated by an empty line. Therefore, you can just discard everything until the first empty line:
my $print = 0;
while (<$socket>) {
    chomp;
    if ($print) {
        print $_, "\n";
    }
    elsif ($_ eq '') {
        $print = 1;
    }
}

It would be easier, and you would handle special cases better, if you used a module such as LWP::UserAgent:
use LWA::UserAgent;
use HTTP::Request;
my $req = HTTP::Request->new( GET => 'http://yahoo.com/index.php' );
my $ua  = LWP::UserAgent->new;
my $res = $ua->request($req);
if ($res->is_success) {
    print $res->content, "\n";
}

A: I would definitely recommend that you heavier weight module like LWP or Mojo::UserAgent instead of recreating the wheel.  There's a helpful 8 minute video introduction to the latter in Mojocast Episode 5.
However, because the spec for HTTP is to separate the header by a blank line, you can just do an initial read in paragraph mode to skip the header:
# Skip Header
{
    local $/ = "";
    <$socket>;
}

print while (<$socket>);


text:
Q: Реализация шорткодов в PHP Как можно реализовать шорткоды (например, если ввести {name} то автоматически вставляется имя пользователя).
Может есть какие-то библиотеки или примеры? И как в целом это можно реализовать?

A: По разному. Самый простой вариант, если я вас правильно понял — «Использование массивов с числовыми индексами в качестве аргументов функции preg_replace()».
<?php

$string = 'Hello, {name}. Welcome to {country}';

$patterns = [];
$patterns[0] = '/{name}/';
$patterns[1] = '/{country}/';

$replacements = [];
$replacements[0] = 'Nick';
$replacements[1] = 'Russia';

echo preg_replace($patterns, $replacements, $string);

?>

https://eval.in/842803


text:
Q: How to sort two columns at once using sorted() I have a .csv file which holds two columns which I want to sort.
I want to sort the first column alphabetically and the second one by highest number to lowest.
I used sortedColumn = sorted(csv_opener,key=operator.itemgetter(0)) to sort the first column alphabetically but I also want to do the same thing for the second column. How would I go about doing that?

A: You can sort by two aspects by having the key callable return a tuple.
I'm assuming that the second column is a string convertable to an integer:
sortedColumn = sorted(csv_opener, key=lambda row: (row[0], -int(row[1])))

By returning negative values from row[1] you can sort from highest-to-lowest, while the main sort is done or row[0] in alphabetical order.
So for the sample rows:
Alpha, 10
Beta, 30
Alpha, 42
Gamma, 81
Beta, 10

the sorted output gives you:
Alpha, 42
Alpha, 10
Beta, 30
Beta, 10
Gamma, 81

sorting first alphabetically on the first column, and then for equal values in the first column, the rows are sorted in descending order on the second column.

A: Martijn Pieters already provided a perfect answer, but I think it is worth checking out Pandas DataFrame for dealing with CSV data in case you have not considered it.
You can use pandas.read_csv() to read the CSV input as a DataFrame and then use DataFrame.sort_values() to sort it any way you want.
To add an example, let's first generate some random sample data
from faker import Factory
from random import randint, choice
import pandas

fake = Factory.create()
names = [fake.name() for i in range(5)]
nums = [randint(1, 50) for i in range(5)]
data = []
for i in range(10):
    data.append((choice(names), choice(nums)))

df = pandas.DataFrame.from_records(data, columns=("Names", "Nums"))

Resulting in, for example
    Names                   Nums
0   Jeffry Wintheiser       25
1   Dr. Corine Sporer PhD   25
2   Jeffry Wintheiser       17
3   Emmett Reilly           17
4   Jeffry Wintheiser       17
5   Emmett Reilly           33
6   Jeffry Wintheiser       33
7   Lilah Purdy             17
8   Emmett Reilly           22
9   Miss Julie Wisoky       25

Then you can use the sort_values as follows
df.sort_values(["Names", "Nums"], ascending=[True, False])

Resulting in
    Names                   Nums
1   Dr. Corine Sporer PhD   25
5   Emmett Reilly           33
8   Emmett Reilly           22
3   Emmett Reilly           17
6   Jeffry Wintheiser       33
0   Jeffry Wintheiser       25
2   Jeffry Wintheiser       17
4   Jeffry Wintheiser       17
7   Lilah Purdy             17
9   Miss Julie Wisoky       25


text:
Q: Django string index out of range Very confused. I have a variable that has 32 items in it, and I'm trying to do a for loop but it's saying "Caught IndexError while rendering: string index out of range"
Any ideas? The variable definitely isn't empty.
{% if photos %}

        {% for photo in photos %}

        {% endfor %}

{% else %}
    No photos found.
{% endif %}

A: I believe the problem might be with the photo.images part of the value.  Is images an array or collection in the photo object?  If it is an array, the images.low_resolution is  trying to access the image in the array at the index value of low_resolution which is probably not what you want (or maybe it is???).  You might need to add some logic to loop over the photo.images rather than trying to access it the way you are now.
See this answer for other info:  How to access array elements in a Django template?


text:
Q: Voltage/Amperage load rating I'm a newbie when it comes to electricity, and this has been bugging me since like 9th grade when I first learned about V/I/R/P combinations, and to this day I still can't wrap my head around the concept.
I understand about the mathematical formulas, but what I'm having trouble with is the meaning of V/I when it comes to wiring things.  I'm thinking of starting a small project wiring up a solar panel to computer fans just to learn about this.

*

*Solar panel is rated at DC 6V/1W

*Fans are rated at DC 12V/160mA

What do these rating mean?

*

*Does this mean that the fans can only operate if the source voltage is 12V?

*What if the source is under-voltage like 6V? Will the fans not power on at all?

*What if the source is over-voltage like 120V? Will the fans start catching fire?

*What if the source is just slightly over/under like 13V or 4V?

If my solar panel is rated at 6V/1W (~160mA max), and I connect four fans in parallel, which means each fan will receive ~40mA, does this mean that the fan will not spin? Or will the fans spin at 1/4th of the speed?
Lastly, if my solar panel is only 6V, and fans are operatable at 12V, does this mean that I have to connect two solar panel serially?  Can I put a resistor between the panel and fans to increase it to 12V?

A: How a device will respond to the wrong voltage will depend much on the type of device. A resistor for instance getting half the voltage will dissipate 1/4 the power, and that's it. For motors like the fan it's different. A slightly lower voltage, like 10 V, will probably not be a problem, but at 6 V it may not start. Same here: it only get 1/4 of the required power, and that may be insufficient to get it going. But it may run if you would hand-start it.
120 V will kill it. Final. It's 100 times the rated power and it will burn, possible burst open with a small explosion and some smoke.
A slightly higher voltage than rated for won't do too much harm, but I would avoid it, again for the same reason: power is proportional to voltage squared, so 10 % higher voltage will give 20 % higher power, and since much of the load is resistive it will get hotter.
If your solar panel can supply 160 mA, and you would connect four 160 mA loads in parallel to it it would get overloaded and the output voltage would sag.

For small load changes the graph shows that the voltage won't vary very much, but at 4\$\times\$ overload you'll be in the higher part of the graph where the voltage will decrease quickly with increasing current. The fans would get too little voltage and due to the limited current won't spin.
If you need 12 V and have 6 V solar panels then placing two of them in series is indeed the right thing to do.


text:
Q: Parsing Wordpress XML iOS / Objective-C I am trying to create an iOS app which (besides a few other things) needs to load in the content of a Wordpress-Page
When I use the getPosts feature from Wordpress's XML-RPC feature, I get the following returned:
<?xml version="1.0" encoding="UTF-8"?>
<methodResponse>
  <params>
    <param>
      <value>
      <array><data>
  <value><struct>
  <member><name>post_id</name><value><string>23</string></value></member>
  <member><name>post_title</name><value><string>Post1Post1</string></value></member>
  <member><name>post_date</name><value><dateTime.iso8601>20140211T14:26:39</dateTime.iso8601></value></member>
  <member><name>post_date_gmt</name><value><dateTime.iso8601>20140211T12:26:39</dateTime.iso8601></value></member>
  <member><name>post_modified</name><value><dateTime.iso8601>20140217T22:32:45</dateTime.iso8601></value></member>
  <member><name>post_modified_gmt</name><value><dateTime.iso8601>20140217T20:32:45</dateTime.iso8601></value></member>
  <member><name>post_status</name><value><string>publish</string></value></member>
  <member><name>post_type</name><value><string>post</string></value></member>
  <member><name>post_name</name><value><string>im-notfall</string></value></member>
  <member><name>post_author</name><value><string>1</string></value></member>
  <member><name>post_password</name><value><string></string></value></member>
  <member><name>post_excerpt</name><value><string></string></value></member>
  <member><name>post_content</name><value><string>Post1Post1</string></value></member>
  <member><name>post_parent</name><value><string>0</string></value></member>
  <member><name>post_mime_type</name><value><string></string></value></member>
  <member><name>link</name><value><string>http://example.com/ExampleProjekt/?p=23</string></value></member>
  <member><name>guid</name><value><string>http://example.com/ExampleProjekt/?p=23</string></value></member>
  <member><name>menu_order</name><value><int>5</int></value></member>
  <member><name>comment_status</name><value><string>closed</string></value></member>
  <member><name>ping_status</name><value><string>open</string></value></member>
  <member><name>sticky</name><value><boolean>0</boolean></value></member>
  <member><name>post_thumbnail</name><value><array><data>
</data></array></value></member>
  <member><name>post_format</name><value><string>standard</string></value></member>
  <member><name>terms</name><value><array><data>
  <value><struct>
  <member><name>term_id</name><value><string>1</string></value></member>
  <member><name>name</name><value><string>Allgemein</string></value></member>
  <member><name>slug</name><value><string>allgemein</string></value></member>
  <member><name>term_group</name><value><string>0</string></value></member>
  <member><name>term_taxonomy_id</name><value><string>1</string></value></member>
  <member><name>taxonomy</name><value><string>category</string></value></member>
  <member><name>description</name><value><string></string></value></member>
  <member><name>parent</name><value><string>0</string></value></member>
  <member><name>count</name><value><int>3</int></value></member>
</struct></value>
</data></array></value></member>
  <member><name>custom_fields</name><value><array><data>
</data></array></value></member>
</struct></value>
  <value><struct>
  <member><name>post_id</name><value><string>9</string></value></member>
  <member><name>post_title</name><value><string>Post2Post2</string></value></member>
  <member><name>post_date</name><value><dateTime.iso8601>20140206T13:16:56</dateTime.iso8601></value></member>
  <member><name>post_date_gmt</name><value><dateTime.iso8601>20140206T11:16:56</dateTime.iso8601></value></member>
  <member><name>post_modified</name><value><dateTime.iso8601>20140217T22:33:01</dateTime.iso8601></value></member>
  <member><name>post_modified_gmt</name><value><dateTime.iso8601>20140217T20:33:01</dateTime.iso8601></value></member>
  <member><name>post_status</name><value><string>publish</string></value></member>
  <member><name>post_type</name><value><string>post</string></value></member>
  <member><name>post_name</name><value><string>neuer-erster-beitrag</string></value></member>
  <member><name>post_author</name><value><string>1</string></value></member>
  <member><name>post_password</name><value><string></string></value></member>
  <member><name>post_excerpt</name><value><string></string></value></member>
  <member><name>post_content</name><value><string>Post2Post2</string></value></member>
  <member><name>post_parent</name><value><string>0</string></value></member>
  <member><name>post_mime_type</name><value><string></string></value></member>
  <member><name>link</name><value><string>http://example.com/ExampleProjekt/?p=9</string></value></member>
  <member><name>guid</name><value><string>http://example.com/ExampleProjekt/?p=9</string></value></member>
  <member><name>menu_order</name><value><int>3</int></value></member>
  <member><name>comment_status</name><value><string>closed</string></value></member>
  <member><name>ping_status</name><value><string>open</string></value></member>
  <member><name>sticky</name><value><boolean>0</boolean></value></member>
  <member><name>post_thumbnail</name><value><array><data>
</data></array></value></member>
  <member><name>post_format</name><value><string>standard</string></value></member>
  <member><name>terms</name><value><array><data>
  <value><struct>
  <member><name>term_id</name><value><string>1</string></value></member>
  <member><name>name</name><value><string>Allgemein</string></value></member>
  <member><name>slug</name><value><string>allgemein</string></value></member>
  <member><name>term_group</name><value><string>0</string></value></member>
  <member><name>term_taxonomy_id</name><value><string>1</string></value></member>
  <member><name>taxonomy</name><value><string>category</string></value></member>
  <member><name>description</name><value><string></string></value></member>
  <member><name>parent</name><value><string>0</string></value></member>
  <member><name>count</name><value><int>3</int></value></member>
</struct></value>
</data></array></value></member>
  <member><name>custom_fields</name><value><array><data>
</data></array></value></member>
</struct></value>
  <value><struct>
  <member><name>post_id</name><value><string>5</string></value></member>
  <member><name>post_title</name><value><string>Post3Post3</string></value></member>
  <member><name>post_date</name><value><dateTime.iso8601>20131217T17:32:09</dateTime.iso8601></value></member>
  <member><name>post_date_gmt</name><value><dateTime.iso8601>20131217T15:32:09</dateTime.iso8601></value></member>
  <member><name>post_modified</name><value><dateTime.iso8601>20140217T22:33:18</dateTime.iso8601></value></member>
  <member><name>post_modified_gmt</name><value><dateTime.iso8601>20140217T20:33:18</dateTime.iso8601></value></member>
  <member><name>post_status</name><value><string>publish</string></value></member>
  <member><name>post_type</name><value><string>post</string></value></member>
  <member><name>post_name</name><value><string>test-beitrag-2</string></value></member>
  <member><name>post_author</name><value><string>1</string></value></member>
  <member><name>post_password</name><value><string></string></value></member>
  <member><name>post_excerpt</name><value><string></string></value></member>
  <member><name>post_content</name><value><string>Post3Post3</string></value></member>
  <member><name>post_parent</name><value><string>0</string></value></member>
  <member><name>post_mime_type</name><value><string></string></value></member>
  <member><name>link</name><value><string>http://example.com/ExampleProjekt/?p=5</string></value></member>
  <member><name>guid</name><value><string>http://example.com/ExampleProjekt/?p=5</string></value></member>
  <member><name>menu_order</name><value><int>4</int></value></member>
  <member><name>comment_status</name><value><string>closed</string></value></member>
  <member><name>ping_status</name><value><string>open</string></value></member>
  <member><name>sticky</name><value><boolean>0</boolean></value></member>
  <member><name>post_thumbnail</name><value><array><data>
</data></array></value></member>
  <member><name>post_format</name><value><string>standard</string></value></member>
  <member><name>terms</name><value><array><data>
  <value><struct>
  <member><name>term_id</name><value><string>1</string></value></member>
  <member><name>name</name><value><string>Allgemein</string></value></member>
  <member><name>slug</name><value><string>allgemein</string></value></member>
  <member><name>term_group</name><value><string>0</string></value></member>
  <member><name>term_taxonomy_id</name><value><string>1</string></value></member>
  <member><name>taxonomy</name><value><string>category</string></value></member>
  <member><name>description</name><value><string></string></value></member>
  <member><name>parent</name><value><string>0</string></value></member>
  <member><name>count</name><value><int>3</int></value></member>
</struct></value>
</data></array></value></member>
  <member><name>custom_fields</name><value><array><data>
</data></array></value></member>
</struct></value>
</data></array>
      </value>
    </param>
  </params>
</methodResponse>

Specifically I would need the following fields:

*

*post_id

*post_title

*post_motified

*post_content

*menu_order

I've tried a few options to achieve this.
One was using Gdata, which has been recommended in another post, but the example is for a simpler xml, and I can't seem to get it to work for me.
    NSArray *tempPosts = [XMLdoc nodesForXPath:@"//methodResponse/params/param/value/array/data/value/struct/member" error:nil];

I also tried using the WPXMLRPC framework  -> https://github.com/wordpress-mobile/wpxmlrpc
Using this code:
WPXMLRPCDecoder *decodedWPXML = [[WPXMLRPCDecoder alloc] initWithData:XMLcontent];
if ([decodedWPXML isFault]) {
    NSLog(@"XML-RPC error %ld: %@", (long)[decodedWPXML faultCode], [decodedWPXML faultString]);
} else {
    NSLog(@"XML-RPC response: %@", [decodedWPXML object]);
}

I manage to receive an object, which I can output via NSLog(@"%@", object);
But I fail to further process any data I receive that way.
I am (maybe obvious for some) very new to objective-c.
I have also looked at the official wordpress for iOS app, but I wasn't able to make use of any code.
Any help would be appreciated, I don't mind using any different frameworks/technologies, etc. if they help getting to my solution.

A: I am happy with Wordpress JSON plugin, it's free. You can easily fine tune your requests to specific pages and post types, it's well documented. What you get back from your site is always a structure of dictionaries and arrays in JSON (better then XML ;). Good way to examine the JSON structure is a JSON viewer.
Some sample code to get started.
- (void)loadNewsForPage:(NSUInteger)page
{

    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.mywordpresssite.com/api/get_posts/?page=%lu", (unsigned long)page]]
            completionHandler:^(NSData *data,
                                NSURLResponse *response,
                                NSError *error) {

                // handle response
                NSError *jsonError = nil;
                id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];

                if (!jsonError) {
                    if ([jsonObject isKindOfClass:[NSDictionary class]]) {

                        // fill datastore
                        [self newsIntoDataStore:(NSDictionary *)jsonObject forPage:page];
                    }
                    else {
                        NSLog(@"returned jsonObject is not a dictionary!");
                    }
                } else {
                    NSLog(@"jsonError, news: %@", jsonError);
                }

            }] resume];
}

- (void)newsIntoDataStore:(NSDictionary *)news forPage:(NSUInteger)page
{
    if ([[news objectForKey:@"status"] isEqualToString:@"ok"]) {

        self.newsPages = [[news objectForKey:@"pages"] integerValue];
        NSArray *posts = [news objectForKey:@"posts"];

        if (posts.count > 0) {
            // store individual posts

            for (NSDictionary *post in posts) {

                // determine post slug
                NSArray *categoriesArray = [post objectForKey:@"categories"];
                NSString *postSlug = nil;
                NSString *desiredSlug = @"news";

                if (categoriesArray.count > 0) {
                    for (NSDictionary *category in categoriesArray) {
                        if ([[category objectForKey:@"slug"] isEqualToString:desiredSlug]) {
                            postSlug = desiredSlug;
                        }
                    }
                }

                    NSString *title = [post objectForKey:@"title"];

                    NSDate *dateFromAPI = [self.dateFormatterFromAPI dateFromString:[post objectForKey:@"date"]];
                    NSString *date = [self.dateFormatterForCell stringFromDate:dateFromAPI];

                    NSString *imageURLStringOrg = [[[post objectForKey:@"thumbnail_images"] objectForKey:@"full"] objectForKey:@"url"];
                    NSString *imageURLStringConverted = [imageURLStringOrg stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

                    NSAttributedString *attributedContentString = [[NSAttributedString alloc] initWithData:[[post objectForKey:@"excerpt"] dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil];
                    NSString *content = [attributedContentString string];

                    NSString *url = [post objectForKey:@"url"];

                    if (title && date && imageURLStringConverted && content && url) {

                        NSDictionary *postDictionary = @{@"title" : title, @"date" : date, @"imageURL" : imageURLStringConverted, @"content" : content, @"url" : url};

                        [self.newsArray addObject:postDictionary];

                    } else {
                        NSLog(@"some post item empty, skipping this post: %lu", (unsigned long)[posts indexOfObject:post]);
                    }
                }

            }

            dispatch_async(dispatch_get_main_queue(), ^{

                if (self.pageLoaded < self.newsPages) {
                    [self loadNewsForPage:self.pageLoaded + 1];
                } else {

                    [self.delegate newsFetchingCompleted];
                }
            });

        } else {
            NSLog(@"no objects in the array");
        }
    } else {
        NSLog(@"returned status NOT OK");
    }
}

A: GDataXMLDocument *XMLdoc = [[GDataXMLDocument alloc] initWithData:XMLcontent options:0 error:nil];
NSArray *XMLofPosts = [XMLdoc  nodesForXPath:@"//methodResponse/params/param/value/array/data/value/struct/member" error:nil];

gives me an array of all post members that i can iterate via
for(GDataXMLElement *postMember in XMLofPosts){ ... }

Thansk for the help.
I've opened a new post for a more detailed question on the subject, since I found it's pretty much a different question, since it's on GDataXML more than getting the Wordpress XML
GDataXML nodesForXPath on Node contains items of entire GDataXMLDocument


text:
Q: I getting undefined using JSON in jQuery why? Im learning some JSON, Im trying to list some data about dogs from twitter...but I can't really present the data...I believe that the error is inside map-method...something I'm missing...thanks for yr help

U almost there!!

A: Change obj.text to $(obj).text();

A: I found the problem.....the reason why I was just presenting a list (li- li)
 with undefined items was cuz I forgot to add results from the JSON-object like so:
info.results If u do a console.log on the publish-method. This obj. has many other properties insid and we want to target the index of this obj right?, and presente in a list...:)


text:
Q: returning object attributes in get request in a better way Learning the basics of Flask development and it just seems as though I am missing something in order to return all of the attributes of an object.
@app.route("/teams/<int:idtofind>", methods=['GET'])
def findbyID(idtofind=None):
    for i in teamlist:
        if i.id == idtofind:
            return i.__dict__

I expect to either return a dictionary of the values, which this code does, but I feel as thought the dict is suboptimal.
{
    "abbrev": "CLE",
    "city": "Cleveland",
    "full_name": "Cleveland Cavaliers",
    "id": 2,
    "name": "Cavaliers"
}

A: In case if you wanted only the attributes of the dictionary object.
@app.route('/teams/<int:idtofind>', methods=['GET'])
def findbyID(idtofind=None):
  global teamlist
  for i in teamlist:
    if i.id == idtofind:
      return ', '.join(i.__dict__.keys())
  return ''


text:
Q: How to return a value depending on whether an Optional value is present or not? I use Optional in a controller
@GetMapping(value = "/address/{id}")
public ResponseEntity<Addresses> getAddressById(@PathVariable("id") Integer id) {

    Optional<Address> address = addressService.getAddressById(id);
    return new ResponseEntity(address.get(), address.isPresent() ? HttpStatus.OK : HttpStatus.NOT_FOUND);
}

Actually, if there is no value, i get
java.util.NoSuchElementException: No value present
    at java.util.Optional.get(Optional.java:135) ~[na:1.8.0_131]

not sure if it's a good way to manage thing.
is there any good pratice

A: Try this:
return address.isPresent()
    ? new ResponseEntity(address.get(), HttpStatus.OK)
    : new ResponseEntity(HttpStatus.NOT_FOUND);

With your current code, you are calling address.get() regardless of whether or not a value is present.
Note that for a more informative NOT_FOUND response (response code 404), you probably should still include a body in the response (which my suggested code does not do). From the HTTP spec (RFC 7231) section on 4xx response codes:

Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.

According to RFC 2119, the key word "SHOULD" means:

that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.

A: You're missing the fluent quality of Optionals. Think of them like a Stream:
  @GetMapping(value = "/address/{id}")
  public ResponseEntity<Address> getAddressById(@PathVariable("id") Integer id) {
    return addressService.getAddressById(id)
        .map(ResponseEntity::ok)
        .orElse(new ResponseEntity<Address>(NOT_FOUND));
  }


text:
Q: What is the relationship between spin network spacetime and tensor network (entanglement) spacetime? In 1971, Sir Roger Penrose, suggested a combinatorial construction of spacetime using the angular momentum of particles. This work led to and introduced the idea of spin networks which are representations of particle interactions where vertices represent events in spacetime and edges represent the worldlines of resultant particles. In such a way one can use these diagrams to illustrate the information held in a system.
In 2010, Mark Van Raamsdonk, wrote an essay outlining how spacetime can be built from quantum entanglement building off of the ideas of Malcadena and Susskind which have now come to be known as the ER = EPR conjecture. Brian Swingle provided a mathematical framework to present these ideas in the form of Tensor Networks, typically used in Many-Body physics, where AdS/CFT has been found to be ubiquitous.
What is so different between these two approaches? Or what, if any, are the relationships between the two bodies of work?
Can one reduce the work of Van Raamsdonk to that of Penrose?


text:
Q: Show that $\tfrac{(-1)^{n}}{\cos(n)+n^{\tfrac{3}{4}}}=\tfrac{(-1)^{n}}{n^{\tfrac{3}{4}}}+\mathcal{O}\left( \tfrac{1}{n^{\tfrac{3}{2}}}\right) $
I would like to show that :
  $$\dfrac{(-1)^{n}}{\cos(n)+n^{\tfrac{3}{4}}}=\dfrac{(-1)^{n}}{n^{\tfrac{3}{4}}}+\mathcal{O}\left( \dfrac{1}{n^{\tfrac{3}{2}}}\right) $$
  by starting from the left side and get the right side

My Proof:

Note that :
  $$\left(1+x\right)^{\alpha}=1+\mathcal{O}\left( x\right) \quad x \to 0$$
  $$\left|\left(\dfrac{\cos(n)}{n^{\tfrac{3}{4}}}  \right)\right|\leq \left(\dfrac{1}{n^{\tfrac{3}{4}}}  \right) \underset{ \overset { n \rightarrow +\infty } {} } {\longrightarrow }0 $$

\begin{align*}
\dfrac{(-1)^{n}}{\cos(n)+n^{\tfrac{3}{4}}}&=\dfrac{(-1)^{n}}{n^{\tfrac{3}{4}}}\left(1+\dfrac{\cos(n)}{n^{\tfrac{3}{4}}} \right)^{-1} \\
&= \dfrac{(-1)^{n}}{n^{\tfrac{3}{4}}}\left(1+\mathcal{O}\left(\dfrac{\cos(n)}{n^{\tfrac{3}{4}}}  \right) \right)\\
&=\dfrac{(-1)^{n}}{n^{\tfrac{3}{4}}}+\mathcal{O}\left( \dfrac{\cos(n)}{n^{\tfrac{3}{2}}}\right) \\
&=\dfrac{(-1)^{n}}{n^{\tfrac{3}{4}}}+\mathcal{O}\left( \dfrac{1}{n^{\tfrac{3}{2}}}\right)
\end{align*}
since
$$\left|\dfrac{\left( \dfrac{\cos(n)}{n^{\tfrac{3}{2}}}\right) }{\left( \dfrac{1}{n^{\tfrac{3}{2}}}\right) }\right| \leq 1 \implies \mathcal{O}\left( \dfrac{\cos(n)}{n^{\tfrac{3}{2}}}\right) =\mathcal{O}\left( \dfrac{1}{n^{\tfrac{3}{2}}}\right) $$

*

*Is my proof correct


text:
Q: Hardcoded things in migrations Could you tell me why Django hardcodes the business logic into migrations?
We can formulate the question the other way. Let's have a look at valitadors and upload_to. These all is hardcoded into migrations.
But if we show SQL that a migration produces, no validators or upload_to will be there.
So, why are they hardcoded? Validators and upload_to are already mentioned in models. DRY principle is violated.
Any change in the code ruins migrations. For example renaming of upload_to will result in the project's blowing up.
Validators and upload_to are just examples. There are more things of the kind. Anyway, they don't influence the database. So, why do we need them in migrations?
Could you comment?


text:
Q: How does multithreading utilizes multiple cores? So recently I've learned some basic knowledge about multithreading. What I've understood is that thread is a lightweight process that runs under processes by sharing memory, while one process is running under one CPU core.
Yet by this perspective I couldn't understand some saying that threads utilizes multiple cores and make the whole program executes more effective. From what I've known, threads created by one process should run only under that specific process, which means that it should only run under that very one CPU core. If we want to utilize multiple cores, we should actually use multiprocess to run parallelly. Most of what I've researched is only about the conclusion, i.e multithreading utilizes multiple cores, but none of them explains my question. Did I think anything wrong? Thanks!

A: Your confusion lies here:

[...] while one process is running under one CPU core.
[...] threads created by one process should run only under that specific process, which means that it should only run under that very one CPU core.

This is not true. I think what the various explanations you have read meant that any process have at least one thread (where a 'thread' is a sequence of instructions ran by a CPU core).
If you have a multithreaded program, the process will have several threads (sequences of instructions ran by a CPU core) that can run concurrently on different CPU cores.
There are many processes executing on your computer at any given time. The Operating System (OS) is the program that allocates the hardware resources (CPU cores) to all these processes and decides which process can use which cores for what amount of time before another process gets to use the CPU. Whether or not a process gets to use multiple cores is not entirely up to the process. More confusing still, multithreaded programs can use more threads than there are cores on the computer's CPU. In that case you can be certain that all your threads do not run in parallel.
One more thing:

[...] threads utilizes multiple cores and make the whole program executes more effective

I am going to sound very pedantic, but it is more complicated than that. It depends on what you mean by "effective". Are we talking about total computation time, energy consumption ..?
A sequential (1 thread) program may be very effective in terms of power consumption but taking a very long time to compute. If you are able to use multiple threads, you may be able to reduce that computation time but it will probably incur new costs (synchronization between threads, additional protection mechanisms against concurrent accesses ...).
Also, multithreading cannot help for certain tasks that fall outside of the CPU realm. For example, unless you have some very specific hardware support, reading a file from the hard-drive with 2 or more concurrent threads cannot be parallelized efficiently.


text:
Q: MVVM Passing data between two views / view models I have two Pages:

*

*Page 1

*Page 2

and two ViewModels with the same properties:

*

*ViewModel1
Properties:

*

*FirstName1

*LastName1

*ViewModel2
Properties:

*

*FirstName2

*LastName2

Now I want to pass data(properties) between ViewModel1 to ViewModel2, and retrive this data on the Page 2.
How do I achieve this?

A: You could take a look at MVVMLight's Messenger. Here's is a tutorial that could guide you on your way. Basically, the idea is to use a messenger that's independent from your Views/ViewModels to send messages from/to them. Your Views/ViewModels register and send specific messages that contain properties values you want to pass along.

A: You can either go with a parent ViewModel that both viewmodels inherit from or an Event Aggregator.  Here is a simple one using Reactive Extensions.

A: Your page could be constructed like so:
public class Page2 {

  public ViewModel1 VM1;

  public Page2() {
    VM1 = new ViewModel1(new ViewModel2());
  }
}

Your ViewModel1 could look like so, with pass-through properties:
public class ViewModel1 : Person {

  private ViewModel2 _vm2;

  public ViewModel1(ViewModel2 vm2) {
    _vm2 = vm2;
  }

  public override string FirstName {
    get { return _vm2.FirstName; }
  }

  public override string LastName {
    get { return _vm2.LastName; }
  }
}

We assume your ViewModel2 has some business logic or something
public class ViewModel2 : Person {
  //Etc
}

Both inherit from the same base class:
public abstract class Person {
  public abstract string FirstName { get; }
  public abstract string LastName { get; }
}


text:
Q: Nao consigo utilizar as Pseudo-classes no css Olá.
Estou tentando colocar um estilo nos links do meu site, mas quando abro o site não aplica as alterações que coloquei através do css.
Utilizei o seguinte código

Já pesquisei em alguns lugares, mas nenhum informa o meu prblema.

A: Bem vindo ao Stackoverflow!
Utilizei exatamente o mesmo css que você disponibilizou e esta funcionando normalmente.
A unica diferença é um ; que estava faltando na linha 7 em color: #315e8a

body {
  font-family: "K2D", sans-serif;
}

a:link, a:active, a:visited {
  color: #315e8a;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}
Teste

A: Não testei o código, mas tem um ponto e vírgula (;) faltando na linha 7. Tente isso e provavelmente vai funcionar.


text:
Q: General case of Gronwall's inequality In my ODE class, the statement below is said to be true.

$F(t,x)<G(t,x) \quad \forall (t,x)\in[a,b]\times\mathbb{R}$
$f'(t)=F(t,f(t))\quad g'(t)=G(t,g(t))\quad f(a)=g(a)=c$
$\Rightarrow f(t)\leq g(t)\quad \forall t\in [a,b] $

I have seen another vision with stronger assumptions. But I wonder if it's sufficient with only the pairwise inequality. (For simplicity, let's assume $F,G$ is continuous and Lipschitz continuous in x, but not always monotonic.)

A: Consider the difference $h(t) = g(t) - f(t)$. Then
$$
 h(a) = c - c = 0, \quad h'(a) = G(a, c) - F(a, c) > 0
$$
so that $h$ is strictly positive on an interval $(0, \delta]$.
Now assume that $h(t_1) <0$ for some $t_1 \in (0, b]$. Then $h$ must be zero somewhere between $\delta$ and $t_1$ and we can define
$$
 t_0 = \max \{ t \in [0, t_1] \mid h(t) = 0 \} \, .
$$
Then $h(t_0) = 0$ and $h(t) \le 0$ for all $t \in [t_0, t_1]$, so that $h'(t_0) \le 0$. On the other hand, $f(t_0) = g(t_0) =: d$, and
$$
 h'(t_0) = G(t_0, d)) - F(t_0, d) > 0
$$
gives a contradiction.


text:
Q: List of procedures in scheme In scheme, I would like to be able to have a list of procedures that I could use on lists of numbers via map.
For example, say I have the procedure
(define (overten? x) (> x 10))

Why does this work when called with (foo '(1 2 11 12) '()) ?
(define (foo lst proc)
    (map overten? lst)
)

But this gives an error called with (foo '(1 2 11 12) '(overten?)) ?
(define (foo lst proc)
    (map (car proc) lst)
)

With the error being
The object overten? is not applicable.

A: Because '(overten?) is a list containing a symbol. Only if you evaluated overten? you would get back the procedure. You need to write (list overten?) so that arguments to list are evaluated (unlike quote).
See Why does Scheme have both list and quote?

A: '(overten?) is not a list with procedures. It's a list with a symbol that has nothing to do with procedures bound to that name in any scope
You need to think evaluation:
overten?
; ==> {procedure overten? blabla}
;     (a implementation dependent representation of a procedure object
'overten
; ==> overten?
;     (just a symbol with name "overten?", nothing to do with the procedure object above)
(list overten? 'overten?)
; ==> ({procedure overten? blabla} overten)
      a list where the first element is a procedure and the second a symbol with name "overten?"

(define another-name-quoted 'overten?)
; ==> undefined
; 'overten? evaluated to a symbol, them bound to another-name-quoted
(define another-name overten?)
; ==> undefined
; overten? evaluated to a procedure, then bound to another-name

The procedure overten? is not more overten? than it is another-name.
Here is an example where we use lists of procedures. It's an implementation of the compose procedure:
(define (my-compose . procs)
  (let* ((rprocs (if (zero? (length procs))
                     (list values)
                     (reverse procs)))
         (proc-init (car rprocs))
         (proc-list (cdr rprocs)))
    (lambda args
      (foldl (lambda (proc acc)
               (proc acc))
             (apply proc-init args)
             proc-list))))

(define sum-square-sub1-sqrt
  (my-compose inexact->exact
              floor
              sqrt
              sub1
              (lambda (x) (* x x))
              +))

(sum-square-sub1-sqrt 1 2 3) ; 5


text:
Q: Looping up to a different number and start looping again ( Awk/Bash) Looping over the whole column sum using can be done in the below txt file this:
101     10
101     10
101     10.10
101     13
101     10
101     10
102     10.140
102     10
102     10
102     0.90
102     10
103     10
104     10
111     11
111     11
111     5.485e+12
111     11

 awk '{sum+=$2;} END{print sum;}' file1.txt > sum_a.txt

Now I would like to do something different.   For example, I would like to sum the second columns upto when the first column numbers are same and start over again. Can it be done using seen[$1]?
awk '{ seen[$1] += $2 } END { for (i in seen) print i, seen[i] }' file1.txt

where $1 being treated as the index value.
I couldn't make it run using seen[$1]. Or Any other nice way to do the looping?
The result would be like this:
101     63.10
101     63.10
101     63.10
101     63.10
101     63.10
101     63.10
102     40. 90

and so on... up to the whole column.

A: $ awk 'NR==FNR{sum[$1]+=$2; next} {print $1, sum[$1]}' file file
101 63.1
101 63.1
101 63.1
101 63.1
101 63.1
101 63.1
102 41.04
102 41.04
102 41.04
102 41.04
102 41.04
103 10
104 10
111 5485000000033
111 5485000000033
111 5485000000033
111 5485000000033

A: If just want to use only one input file using awk:
 $ awk -v c=1 '{ a[$1]+=$2;b[c]=$1;c+=1} END { for( i=1;i<=NR;i++ ){key=b[i]; print key" "a[key]} }' file1.txt
101 63.1
101 63.1
101 63.1
101 63.1
101 63.1
101 63.1
102 41.04
102 41.04
102 41.04
102 41.04
102 41.04
103 10
104 10
111 5485000000033
111 5485000000033
111 5485000000033
111 5485000000033


text:
Q: Apex 5.1 interactive grid hiding toolbar buttons Is it possible to allow add and save actions but hiding the "add row" and 'edit" buttons in the grid toolbar? When I tried unchecking those buttons I was not longer able to add data to the grid progrmmatically. How can I allow adding multiple rows programmatically and having "save" button but hiding "add row" and "edit"?

A: Try to add this css to your page:
#myStaticIgId button[data-action="selection-add-row"], #myStaticIgId div[data-action="edit"] {
    display: none !important;
}


text:
Q: How to use dynamic to normal model? I want to convert dynamic incoming data to normal model and use it. How can I do?
Click problem image
I get an error on the ConvertedModel conversion.

A: Your model variable isn't a JSON string so you can't deserialise it. It's a dynamic object - it's a type in C#. If the data has the same structure as your model you could just cast it to that type.
But this shouldn't be necessary anyway - why not just use the model type in the method signature directly? It's unclear why you have set it up this way.
If you write it like this then ASP.NET will automatically attempt to deserialise the incoming data directly to your model type:
public AjaxResponse AddFavourite(YourModelClass model) {

A: If you want to convert a dynamic data to a normal model,it is possible,but you need to pass data to tell which model you want to convert.You can refer to this:
Here is a demo worked:
 public class A {
     public string userid { get; set; }
     public string symbol { get; set; }
    }
    public class B
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
    public class C
    {
        public string Id { get; set; }
        public string Email { get; set; }
    }

Controller:
public IActionResult DynamicModel([FromBody]dynamic d,string modelName) {
            var model = new Object();
            switch (modelName)
            {
                case "A":
                    model = JsonConvert.DeserializeObject<A>(d.ToString());
                    break;
                case "B":
                    model = JsonConvert.DeserializeObject<B>(d.ToString());
                    break;
                case "C":
                    model = JsonConvert.DeserializeObject<C>(d.ToString());
                    break;
                default:
                    break;
            }
            return Ok(model);
        }

result:

A: you can use
string strJSON = JsonConvert.SerilzeObject();
var model = JsonConvert.Deserialize(strJSON);