text:
Q: className effect not showing reactjs I'm using react zoom pan pinch library, and want to give height:"100%" to TransformWrapper and TransformComponent, i can do it from chrome inspect just fine, but when trying to add className or straight style={{height:"100%"}} it wont show it, any idea ?
code to try:
https://codesandbox.io/s/withered-violet-uumcx0?file=/src/App.tsx
code:

import React from "react";
import { makeStyles } from "@material-ui/core";

import "./styles.css";

import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch";
const useStyles = makeStyles({
  wrapper: {
    height: "100%",
    backgroundColor: "red"
  }
});
export default function App() {
  const classes = useStyles();

  return (

        <TransformWrapper
          className={classes.wrapper}
          limitToBounds={true}
          alignmentAnimation={{ sizeX: 0, sizeY: 0 }}
          centerZoomedOut={true}
        >
          {({ zoomIn, zoomOut, resetTransform }: any) => (
            <React.Fragment>

                  <button onClick={zoomIn}>+</button>
                  <button onClick={zoomOut}>-</button>
                  <button onClick={resetTransform}>x</button>

                <TransformComponent>

                </TransformComponent>

            </React.Fragment>
          )}
        </TransformWrapper>

  );
}

A: It looks like the TransformWrapper and TransformComponent components from the react-zoom-pan-pinch library don't accept a className or style prop.
According to the documentation you should use wrapperClass, wrapperStyle, contentClass or contentStyle for TransformComponent.

A: i hope this will help you
first, add the style from makeStyle into the wrapperClass props in your TransformComponent
<TransformComponent wrapperClass={classes.wrapper}>

in your makeStyle, you can navigate your target container inside the component TransformComponent in to like this:
const useStyles = makeStyles({
  wrapper: {
    height: "calc(100% - 21px)", // 21 is the height of tools
    "&> div": {
      height: "100%",
      backgroundColor: "blue !important"
    }
  }
});

here is the complete code in codesandbox

A: You can do it with pure css.
Add this to your parent div:
style={{
         display: "flex",
         flexDirection: "column",
         border: "1px solid black",
         height: "300px"
       }}

And those two classes to css:
.react-transform-wrapper,
.react-transform-component {
  height: 100% !important;
}

And it will work.
Check it here CODESANDBOX
UPDATED
As you can find in the docs, you can do it by adding wrapperClass and  contentClass as follows:
<TransformComponent wrapperClass="full-height" contentClass="full-height">

where full-height is as follows
.full-height {
  height: 100% !important;
}


text:
Q: How to make login as other user in API using laravel passport? I am using laravel passport for API authentication. and I want to log in as different users with different roles from superadmin. So how can I achieve this? Please give your suggestions.
   public function masqueradeNotary($profileId)
   {
     $userId = decodeC($profileId);
     $notaryUser = $this->adminService->getUser($userId);

     if($userId){

        //logout from current login user
        $user = auth()->user()->token();
        $user->revoke();

        //login as notary user
        $userRoles = $notaryUser->roles()->get();

        // $scopes = [];
        // if ($userRoles) {
        //     $scopes = Arr::pluck($userRoles,'code');
        // }

        if(Auth::login($notaryUser)){
            \Log::info("auth user");
            \Log::info(auth()->user());
            // $token = $user->createToken($user->email . '-' . now(), $scopes);
        }
      }
   }

A: Welcome to stackoverflow.
Well, you should look at spatie's package, it might make your life easier.
You can apply roles on the registration if you create two different registration functions. In the front-end, you have to somehow make the user decide and pass that value (a checkbox would be ideal).

A: I got the solution. there is no need to check auth login just log out the current user and revoke the access token and create a token for the user directly.
$token = $user->createToken($user->email . '-' . now(), $scopes);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replicate this P-value given $r$ and $n$? I am using http://www.socscistatistics.com/pvalues/pearsondistribution.aspx as my reference here.
$r = 0.0789$
$n = 15$
The $P$-value is $0.779858$. I have tried to replicate it without success. Is this something where I need $t = r\frac{\sqrt{n-2}}{\sqrt{1-r^2}} = 0.285367618996$ somehow? How do I compute $P$?

A: From the formula you provided, we know that
$$
r\frac{\sqrt{n-2}}{\sqrt{1-r^2}}
$$
is T distributed with $n-2$ degrees of freedom. So then if we use R we have:
> pt(0.285367618996, 13, lower.tail=F) # one tailed
[1] 0.3899292
> 2*pt(0.285367618996, 13, lower.tail=F) # two tailed
[1] 0.7798585

which is the answer provided on the website.


text:
Q: undefined method unpack for nil:NilClass when rendering JSON I'm working on a Rails 5 API application and Im having trouble when trying to render json. Take that simple controller:
module Api
  module V1
    class UsersController < ApplicationController
      def sign_up
        @user = User.new user_params
        if @user.save
          render json: {status: :ok, user: @user.to_json }
        else
          render json: { status: :error, errors: @user.errors }, status: :unprocessable_entity
        end
      end
    end
  end
end

When I test this request with a simple spec:
RSpec.describe Api::V1::UsersController, type: :controller do

  context 'As an unregistered user' do
    context 'signing up with valid params' do
      let(:valid_params) do
        { name: 'Test User', email: 'test@test.com', password: '123456789', password_confirmation: '123456789' }
      end

      it 'returns a 200 status' do
        post :sign_up, params: { user: valid_params }
        expect(response.status).to eq 200
      end
    end
  end
end

I get an error thrown at me:
Failures:

  1) Api::V1::UsersController As an unregistered user signing up with valid status returns a 200 status
     Failure/Error: render json: {status: :ok, user: @user.to_json }

     NoMethodError:
       undefined method `unpack' for nil:NilClass
     # ./app/controllers/api/v1/users_controller.rb:10:in `sign_up'
     # ./spec/controllers/api/v1/users_controller_spec.rb:15:in `block (4 levels) in <top (required)>'

I'm not using any gems that alter rendering yet so I'm really lost of what might be the problem. Thanks in advance.


text:
Q: Difference between quartz2d on iphone and mac There is difference between quartz2d on iphone and mac? where can i find a list of that? Every  book i founded in amazon is dedicate to programming quartz on mac.

A: As far as the low-level drawing goes, the two platforms are almost identical.  One issue that you'll encounter is that many of those guides were written before Leopard was released, so they don't take into account Core Animation layer backing for views, which is present everywhere on the iPhone.
You don't have access to some of the text drawing systems on the iPhone that you do on the Mac.
Another key difference between the two platforms is the coordinate space for Quartz drawing.  Standard Quartz on the Mac has the lower left corner be (0,0), where the backing layers for UIViews have a flipped geometry with the upper left corner being (0,0).  I provide a little more detail in this answer.


text:
Q: Why does a 'www.' URL-prefix affect whether cURL can grab webpage content? Here's my setup:
$url1 = "www.gyngen.dk";
$url2 = "gyngen.dk";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 20);
$result = curl_exec($curl);
curl_close($curl);

Using $url1 will result in an empty string and $url2 will work as intended. But why my fellow stackoverflowians, is cURL so delicate when it comes to the presence of 'www.' , when it (in my experience) doesn't matter when using URLs in my browser (firefox).
Thanks in advance!

A: cURL does not follows redirects and going to www.gyngen.dk would redirect you to gyngen.dk using redirect. And since there is no redirect cURL receives empty web content.

A: http://www.gyngen.dk redirects to http://gyngen.dk.
Your browser follows the redirect transparently.
PHP/cURL, with your settings, does not. This question explains how to change that.

A: The www. and bare domains are two separate domains. Web browsers will sometimes try and obscure this difference for people who do not know any better, and if a page is not found at one of the addresses, it will sometimes try the other. In reality, the domains are distinctly their own, and curl does not make any attempt to hide this.


text:
Q: Extra information in a IID random variable? So here's the original question:

$n$ players enter a room and a red or blue hat is placed on each
  person's head. The color of each hat is determined by [an independent]
  coin toss. No communication of any sort is allowed, except for an
  initial strategy session before the game begins. Once they have had a
  chance to look at the other hats [but not their own], the players must
  simultaneously guess the color of their own hats or pass. The puzzle
  is to find a group strategy that maximizes the probability that at
  least one person guesses correctly and no-one guesses incorrectly.

Now the solution for $n=3$, I could somehow solve (winning probability = 0.75):

Say Red/Blue if you see 2 Blue/Red (in that order), pass otherwise

Although I do not know how to generalize this result to $n$, my issue with any arbitrary $n$ is this.
Looking at it from the perspective of say any one player Bob. Bob has 2 jobs, decide whether he will pass or not based on what the others' hats are, and the guess (again based on the hats of the rest).
Both of these steps require basing his decision on the hats of the rest. So why does any decision based on the information from independent variables affect the chances of his being right when he does guess?
Irrespective of what the other hats are, from Bob's point of view, whenever he does choose to guess (based on information which is in no way related to the color of his own hat), it will always be a 50% chance that he is right. And this reasoning can be extended to every other player, so that from their own perspective, all the guesses are in fact only 50% valid. How does the winning probability be any higher than 0.5?
Isn't basing your prediction about the next outcome on a sequence of IID previous outcomes very similar to the Gambler's fallacy? I am significantly confused, since I did solve the $n=3$ case somehow.
PS: I hear that this is somewhat a famous puzzle. Any link to a solution for the general case?

A: I'm not solving the general problem, just answering about this apparent paradox about independent variables influencing the probability.
You are right that for each person separately, the chance to get it right or wrong in repeated executions of this procedure is the same. But this game is about $n$ players playing the game simultaneously, and the information those players have is highly correlated: Player $A$ and player $B$ see the absolute same hats from all the other $n-2$ players, the only difference is in hat $A$, that player $B$ sees, and hat $B$, that player $A$ sees.
So a pre-discussed strategy, while not allowing each person to guess their own hat color with more than 50% probability, by allowing passes allows the 'good' outcome defined in the problem to succeed with probability > 0.5.
As another argument, assume that players could not pass, each one had to state the color of their hat. It would seem that the probability that everyone guesses correctly would now plunge down to almost 0 for big $n$, right? Not correct, with a prediscussed strategy the probability that everyone guesses correctly can be made 0.5. Everybody simply assumes that the number of overall red hats among all players is even, then states their own hat color based on what they can see to make the assumption true.
First to note is that with this strategy, all players simultaneously get it right or get it wrong. That's due to the highly correlated information they get to make their decision. Second to note is that using binomial coefficients, the number of red hats being even is happening in exactly half of the $2^n$ cases, so the probabiliy of being right is 0.5.
It should be clear that allowing passes might increase the probability, as you've shown for $n=3$.


text:
Q: A regular curve on regular surface in $ \mathbb R^3 $ being of constant tangent length I was given this in diff. geometry on which I am stuck:

Let $ S \subset \mathbb R^3 $ be a regular orientable surface in $ \mathbb R^3 $ such that on it we define the regular curve $ \gamma : I \to S $ a regular curve on the surface S and we define the following positive basis for $ \mathbb R^3 $ as $ \{ T(t) = \gamma ' (t) \space \space ; \space \space N(t) = N(\gamma(t)) \space \space ; \space \space V(t) = N(t) \times T(t)  \} $ and we are to show there exists smooth functions on the curve a,b,c such that:
$ T' = aV+bN $
$ V' = -aT+cN $
$ N' = -bT-cV $

I know the approach is that all three basis elements are smooth and therefore differentiable and the vectors $ T' ; V' ; N' $ are in $\mathbb R^3 $ and therefore are linear combinations of the given basis and therefore I can write for the first one $ T' = aV+bN+dT $ taking inner product with the tangent T and using orthogonality we obtain $ \langle {T', T} \rangle = d \langle {T, T} \rangle $ and because of regularity I know the tangent never vanishes therefore for $ d=0 $ as desired I need to have $ \langle {T', T} \rangle = 0 $ which is equivalent to saying $ ||T|| = const $ which I am not sure if it holds with the given data I was given as I know I forgot nothing and typed it as it was given to me and you see where my block comes from, I certainly appreciate any helper's opinion on this, thanks

A: Review how the Frenet frame works. Any time you have a smoothly-varying orthonormal basis $e_1,e_2,e_3$ at each point of the curve, you're going to have $e_i'$ orthogonal to $e_i$ (by the argument you gave) and $\langle e_i',e_j\rangle  = -\langle e_j',e_i\rangle$ (by the same argument).


text:
Q: DB and web server on separate providers machines I am moving my servers so I am going to have my web application running for a month with database on different provider servers. Servers geographical distance is small (the same city).

*

*DB server  - PDO MySql

*Web server - Zend PHP

Will I have problems with communication between these web and db server? What are major things to pay attention to?

A: You should probably account for more latency, it will mostly depend on the quality of the connection in between the servers but it could still be pretty reasonable.
You will have to set an account up on the remote database host which can actually login from your ip address, and probably whitelist your server's ip in general on that server to prevent others from connecting.
The rest won't change much, just the usual:
-use prepared statements
-validate the input
-don't trust your users
-etc
Apart from that, I'd be considering taking a more regular look at the logs to make sure that everything runs smoothly and that you make regular backups just in case you need to set up an emergency server if something goes wrong.


text:
Q: Leverage Browser Cache asp.net I tried to check the speed of my website using
https://developers.google.com/speed/
It says to Leverage Browser Cache.
I tried doing this by placing the following code in web.config file
<staticContent>
<clientCache cacheControlMode="UseExpires" httpExpires="Tue, 19 Jan 2038 03:14:07 GMT" />
</staticContent>

And I rechecked again. But it is showing the same again!
Does the above code sole the problem actually??
I'm using IIS 7.5 and .NET Framework 4.0 for my website.

A: I don't think it makes any difference but I got it working with UTC time format:
<staticContent>
  <clientCache httpExpires="Sun, 26 Oct 2014 00:00:00 UTC" cacheControlMode="UseExpires" />
</staticContent>


text:
Q: Как преобразовать "обводку" в контур Всех приветствую. Я загрузил себе пример one line drawing (рисунок, написанный непрерывной линией, как если бы рисовали, не отрывая карандаша от бумаги) На одном сайте сконвертировал его в svg. Открыв в inkspace файл, я увидел следующую картину.
На этом скриншоте вы можете видеть один из сегментов всего рисунка. Так как у контура есть ширина онлайн-конвертер решил обвести контур первоначального изображения. То есть точки path находятся как справа от линии так и слева.
У меня есть python скрипт, который аппроксимирует path ломаной. А из-за этой обводки ломаная сначала аппроксимирует линию, а затем ещё аппроксимирует её в обратном направлении.
Как я могу избавиться от обводки? Например, как-то оставить только точки слева от контура или только справа. (Сначала в голову пришла идея просто всю ломаную разделить пополам, однако это не сработало так как аппроксимация неравномерная)
Или для моей задачи (конвертировать one line изображение в svg с линией без этой "обводки") есть более подходящее средство, чем онлайн-конвертер?
Вариант, удалять вручную все точки, прошу не рассматривать)
Спасибо за помощь
Изначальное изображение


text:
Q: One UIViewController or Two for portrait / landscape views I am looking for some clarification with regards to view controllers and views. Should one view controller be used exclusively to control one view?
Basically, my portrait view is going to be a 4x3 grid of buttons (within a scrollview). When i rotate the view to landscape, i am going to want maybe a 6x4 grid.
Obviously the functionality for handling the buttons' clicks etc will be the same in either orientation, so it would seem a lot of effort to duplicate this for landscape.
How should i get the view controller to use the correct view xib?
Should i have two seperate xibs? I have tried every combination of autoresize masks and not having much luck.
I'm not sure of the correct way to go.
Thanks.

A: i do not think that the above one answered the question of joec. joec want to know, if it is bad or good to have 2 nibs (i.e. landscape.nib and portrait.nib) and manage the views in that 2 nibs with 1 uiviewcontroller.
my understanding of the mvc design pattern is, that a ViewController really SHOULD manage different views. but when i look at the internet, in cause of cocoa touch, often people says that it is BAD (whatever this means) when a UIViewController switches his view-property at runtime. thats confusing to me. why should a viewcontroller not be able to switch views ? why should i build some strange "master"-viewcontroller, which manages 2 other viewcontrollers, and everyone of this manages his own view. in case of landscape and portrait abstraction (or i.e. iphone-gui and ipad-gui abstraction) the code in the gui-business-layer (the event-code etc. in the viewcontroller) is exactly the same for different views. the style of the views is not. so that should one of the benefits of a mvc-implementation.
sorry, but that seems not logical for me, apple.
any thoughts ?
edit says:
it seems that apple provides some strange sort of workaround to solve this problem (hate me, but for me it is nothing more than that, because i see no really straight-forward design implementation for managing and handling views in the UIViewController class):
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/BasicViewControllers/BasicViewControllers.html%23//apple_ref/doc/uid/TP40007457-CH101-SW26
i found this link in the following stack overflow thread:
Want to use muliple nibs for different iphone interface orientations
thanks to Michal for that one.

A: You can also try to change your views and subviews sizes etc.
Take a look here Madhup expained It before.  Changing UIView on orientation change


text:
Q: Memory order in shared pointer destructor I'm trying to figure out the most relaxed (and correct) memory order for shared pointer destructor. What I have in mind for now is as follows:
~shared_ptr() {
   if (p) {
     if (p->cnt.fetch_sub(1, std::memory_order_release) == 1) {
       p->cnt.load(std::memory_order_acquire);
       delete p;
     }
   }
 }

Basically, I'm thinking that all previous fetch_sub() should happen-before delete p;, and by p->cnt.load(std::memory_order_acquire);, I construct a release sequence that ensures this.
I'm new to C++ memory model, and not quite confident. Is my above reasoning correct, and the memory order I specified correct and most relaxed?

A: In theory, you may have the most efficient code, since there is no more synchronization than necessary.
But in practice, there are almost no CPU that provides instruction that would map perfectly to acquire/release memory order (maybe future ARMv8.3-A will). So you will have to check for each target the generated code.
For example on a x86_64 fetch_sub(std::memory_order_acq_rel) and fetch_sub(std::memory_order_release) will result in the exact same instruction.
So while in theory your code looks like optimal, in practice, you get a code that is less optimal than if you had opted to a simpler approach:
std::atomic<int> cnt;
int* p;
void optimal_in_therory() {
     if (cnt.fetch_sub(1, std::memory_order_release) == 1) {
       cnt.load(std::memory_order_acquire);
       delete p;
   }
}
void optimal_in_practice_on_x86_64() {
     if (cnt.fetch_sub(1, std::memory_order_acq_rel) == 1) {
       delete p;
   }
}

Assembly:
optimal_in_therory():
  lock sub DWORD PTR cnt[rip], 1
  je .L4
  rep ret
.L4:
  mov eax, DWORD PTR cnt[rip]  ;Unnecessary extra load
  mov rdi, QWORD PTR p[rip]
  mov esi, 4
  jmp operator delete(void*, unsigned long)
optimal_in_practice_on_x86_64():
  lock sub DWORD PTR cnt[rip], 1
  je .L7
  rep ret
.L7:
  mov rdi, QWORD PTR p[rip]
  mov esi, 4
  jmp operator delete(void*, unsigned long)

One day I will live in Theory, because in Theory every thing goes well -Pierre Desproges

Why does the compiler keep this extra-load?
According to the standard optimizers are allowed to elide redundant load performed on non volatile atomics. For example if in your code you added three extra-loads:
cnt.load(std::memory_order_acquire);
cnt.load(std::memory_order_acquire);
cnt.load(std::memory_order_acquire);

With GCC or Clang the three loads would appear in the assembly:
mov eax, DWORD PTR cnt[rip]
mov eax, DWORD PTR cnt[rip]
mov eax, DWORD PTR cnt[rip]

This is a realy bad pessimization. My opinion is that it is kept as-is because of an historical confusion between "volatility" and "atomicity". While almost all programmers know that a volatile does not have the properties of an atomic variable, many code are still written with the idea that an atomic has the propertie of a volatile: "an atomic access is an observable behaviour". According to the standard it is not (an explicit example note about this fact in the standard). This is a recurring question on SO.
So your code is realy the optimal code in theory, and it is pessimized because compilers optimize code as if atomics were also volatiles.
The work around could be to replace the load by an atomic_thread_fence as proposed by Kieth in its comment. I am not an hardware expert but I imagine that such a fence could cause more memory "synchronization" than necessary (or at least in theory ;)).
Why I believe your code is the optimal in theory?
The last shared_ptr of a single object must call the destructor of that object without itself causing a data race. The desctructor may access the value the object, so the desctructor call must happen after the "invalidation" of the pointer to the object.
So delete p; must "happen after" the destructor call of all others shared pointers that were sharing the same pointed object.
In the standard happens before is defined by the following paragraph:
[intro.races]/9:

An evaluation A inter-thread happens before an evaluation B if:

*

*A synchronizes with B, or [...]

*

*any combination with "sequenced before" and it is a transitive rule.

[intro.races]/10:

An evaluation A happens before an evaluation B (or, equivalently, B happens after A) if:

*

*A is sequenced before B, or

*A inter-thread happens before B.

So there must be a "synchronize with" relation between the fetch_sub that is sequenced before delete p and the other fetch_sub.
According to [atomics.order]/2:

An atomic operation A that performs a release operation on an atomic object M synchronizes with an atomic operation B that performs an acquire operation on M and takes its value from any side effect in the release sequence headed by A.

So delete p must be sequenced after an acquire operation which load a value which is in the release sequence of all the other fetch_sub.
According to [expr.races]/5 the last fetch_sub (in the modification order of cnt) will belong to the release sequence of all the other release fetch_sub because a fetch_sub is a read-modify-write operation, as is fetch_add (supposing no other operations happen on cnt).
So delete p will happen after all the other fetch_sub, and it is only before delete p is called that a "synchronization" will be produced. Precisely not more that what is necessary.


text:
Q: One SQL query instead of many Suppose I have a MySQL table with just 2 columns:
id
invited_by_id

and I want to know for
each id how many times it appears in invited_by_id column.
How to make this using only one query?

A: A simple GROUP BY on the invited_by_id column is all you need, since it holds the same id values as the id column:
SELECT invited_by_id, COUNT(*) AS invited_count FROM table GROUP BY invited_by_id

A: select id1.id, (count*)
from id as id1
inner join id as id2 on id1.id = id2.invited_by_id
group by id1.id

A: select invited_by_id, count(*) from table group by invited_by_id

A: SELECT m.id
     , grp.cnt
FROM
    ( SELECT DISTINCT id
      FROM mytable
    ) AS m
  LEFT JOIN
      ( SELECT invited_by_id
             , COUNT(*) AS cnt
        FROM mytable
        GROUP BY invited_by_id
      ) AS grp
    ON grp.invited_by_id = m.id


text:
Q: Configuring Google Domains, EC2, and Nginx I'm running into a big problem when trying to configure a domain name through Google Domains to point to my EC2 (Ubuntu Server) instance.
I set up nginx as a reverse proxy to serve a Django app. I also configured and associated an elastic IP with the EC2 instance. When I visit the elastic IP (34.XXX.XXX.28), I get to the app just fine. This tells me that everything is configured properly within the EC2 instance (nginx, Django app, etc...).
The problem is when I visit my domain name at www.mydomain.com, I get this page:

Welcome to nginx!
If you see this page, the nginx web server is successfully installed
  and working. Further configuration is required.
For online documentation and support please refer to nginx.org.
  Commercial support is available at nginx.com.
Thank you for using nginx.

I'm confused why directly visiting the elastic IP works, but visiting through the domain name (www.mydomain.com) would lead to the default nginx page. Could someone please point me in the right direction?
Here is some context:

*

*This is my Google Domains config

*These are my elastic IP and EC2 security inbound rules config

*My nginx is configured to listen to port 80. Here is my config:

upstream djangoapp {
    server unix:/var/www/run/djangoapp.sock;
}

server {

    listen 80;
    server_name 34.XXX.XXX.28;

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_pass http://djangoapp ;
    }

    location /static/ {
        alias /var/www/djangoapp/static/;
        autoindex on;
    }
}

A: Nginx can listen for multiple websites on the same IP address, both http and https. Right now you have it listening for requests to a specific IP, not the domain name. The solution is to specify the domain(s) you want it to listen to - for example
server_name example.com www.example.com;

You should typically only listen on one domain. Subdomains should be forwarded to the main domain, though whether www or the root domain is what you consider "main" is entirely up to you.
# Main server
server {
  listen 80;
  server_name example.com;
  // Locations etc
}

server {
  listen       80;
  server_name  www.example.com;
  return 301   https://example.com$request_uri;
}

You can also any given server block the 'default server'. This could be the main server block for your site, or it could be another to prevent your server responding by IP. You might not want to respond to IPs because the internet is continually scanned
server {
  listen      80 default_server;
  server_name 1.2.3.4 example.com;
}

This is a default server that rejects traffic to your IP that isn't handled by a specific server block
server {
  listen      80 default_server;
  server_name _; # Wildcard, any domain is served
  return      444; # This means "go away", effectively
}

A: When you are using public IP of your site, it is escaping the DNS. You are viewing 100% correct things, no caching mechanism of DNS is in between. It is mot possible to say without precise details of error log, full config. But Nginx config is wrong like others pointed and obviously Nginx has documentation. Example config given on official docs. You'll see they said about similar format like the other answers, comments here.
Only we can say to :

*

*set the TTL of DNS to very low like 30 seconds during debug

*and set server_name www.your-domain-name.com; from nginx.

*Then check DNS propagation

*access via Tor browser to check. May be you are seeing cached page.

After correcting, run nginx -t config test and then restart nginx to take effect.

A: Nginx is listening on IP address. You need to add your domain name in "server_name" directive. Then reload the nginx and it should work fine.


text:
Q: How to go from .SD syntax to for set syntax with data.table? From the foo.in data.table, and thanks to the help that I was able to receive here, I manage to get what I wanted : foo.out.
set.seed(123)
foo.in <- data.table(id = rep(LETTERS[1:10], each = 10),
                  code = sample(c(111, 222, 333, 444), 100, replace = TRUE),
                  cof = rep(runif(10, 1, 10), each = 10),
                  x1 = sample(0:1, 100, replace = TRUE),
                  x2 = sample(0:1, 100, replace = TRUE),
                  x3 = sample(0:1, 100, replace = TRUE),
                  x4 = sample(0:1, 100, replace = TRUE),
                  x5 = sample(0:1, 100, replace = TRUE),
                  x6 = sample(0:1, 100, replace = TRUE))

foo.out <- foo.in[, lapply(.SD, function(x) uniqueN(code[x==1]) * cof),
                    .SDcols = grep("^x\\d+$", names(foo.in)),
                     by = .(id, cof)]

It works fine, but with a very large data.table I would like to test another syntax with for and set.
By documenting myself, I understood that depending on the case, it could be faster than using .SD.
Even if it turns out not, it's a good exercice to learn and run my own benchmarks.
But I can't do it with this syntax...
My attempt :
cols <- paste0("x", c(1:6))
for (c in cols) { set(foo.in, j = c, value = ...) }

Thanks !!


text:
Q: Do I need the left table indexed for efficiency when left merging with another indexed DataFrame? I want to do a left merge to join two pandas DataFrame:
merged_df = left_df.merge(right_df, how='left', left_on='id', right_index=True)

left_df is not indexed, it only has an id, but right_df is indexed.
I have not indexed left_df since it changes continuously, but for the merge would it be faster if the left DataFrame is also indexed? In my case the merge is done very frequently and until now the left DataFrames has up to 60k rows and the right up to 1000.
I have not checked pandas' merge code, but since in the left merge it keeps all rows of the left DataFrame I am not sure if indexing it would increase this merge's speed.

A: Let's just test it with fake data:
import pandas as pd
import numpy as np

# df1: 60k rows, not indexed
df1 = pd.DataFrame(data = {'a': np.random.randint(0, 100, 60_000),
                           'b': np.random.randint(0, 100, 60_000)})
# df2: 1k rows, indexed
df2 = pd.DataFrame(data = {'c': np.random.randint(0, 100, 1000)},
                   index =  np.random.randint(0, 100, 1000))

Joins Performances
%timeit pd.merge(df1, df2, left_on='a', right_index=True, how='left')
55.4 ms ± 6.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit pd.merge(df1.set_index('a'), df2, left_index=True, right_index=True,
how='left')
49.8 ms ± 3.13 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

This already shows a better performance when joining on index. However I am also setting the index in the join, which just need to be done once if you have multiple joins. Let's see time split between the two operations:
%time df1.set_index('a', inplace=True)
Wall time: 936 µs

%timeit pd.merge(df1, df2, left_index=True, right_index=True, how='left')
48 ms ± 3.13 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


text:
Q: Start ERROR: E is not a recognized option Crate Version : 2.1.5
OS : Windows
I have an error when starting whith crate.bat:
PS D:\Dev\Crate\crate-2.1.5\bin> .\crate.bat
starts CrateDB

Option          Description
-C <KeyValuePair>     Configure a setting
-V, --version         Prints CrateDB version information and exits
-d, --daemonize       Starts CrateDB in the background
-h, --help            show help
-p, --pidfile <Path>  Creates a pid file in the specified path on start
-q, --quiet           Turns off standard ouput/error streams logging in console
-s, --silent          show minimal output
-v, --verbose         show verbose output
**ERROR: E is not a recognized option**

Java path is : "C:\Program Files\Java\jdk1.8.0_131\bin\java"  -Xms256m
  -Xmx1g -Xss256k -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+DisableExplicitGC -Djna.nosys=true -Dfile.encoding=UTF-8 -Dlog4j.shutdownHookEnabled=false -Dlog4j2.disable.jmx=true -Dlog4j.skipJansi=true -Dio.netty.noUnsafe=true -Dio.netty.noKeySetOptimization=true -Dio.netty.recycler.maxCapacityPerThread=0  -cp "D:\Dev\Crate\crate-2.1.5/lib/;D:\Dev\Crate\crate-2.1.5/lib/enterprise/;D:\Dev\Crate\crate-2.1.5/lib/sigar/*"
  "io.crate.bootstrap.CrateDB" -Epath.home="D:\Dev\Crate\crate-2.1.5" -V

Do you have the same problem?
An idea of where the error might come from?
Thanks

A: This will be fixed in the upcoming release of 2.1 - Thanks. https://github.com/crate/crate/issues/6129

A: Work around in the meantime:
In crate.bat, replace
set CRATE_PARAMS=-Epath.home="%CRATE_HOME%"

by
set CRATE_PARAMS=-Cpath.home="%CRATE_HOME%"

and remove:
    ) else if "!param:~0,2!" equ "-C" (
        set param=!param:-C=-E!

source: https://github.com/crate/crate/pull/6142


text:
Q: Live Charts WPF need to always show hardcoded steps in X axis I'm trying to do something that I believe should be easy.
I want to show the values 1 through 30, evenly spaced, because I do a run of data that represents 30 minutes of data. Sometimes there are 500 data points, but sometimes there are thousands (I can easily determine the number of points though).
Basically, my code for the Xaxis looks like this, but it is not doing what I want. Below the code is a screenshot of what is happening, and below that is a screenshot of what I want.
        cartChart.AxisX.Add(new Axis
        {
            // TODO fix this to acutally show real time
            Title = "Minutes",
            //Labels= { "1", "2", "4", "6", "8", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30" },
            Separator = new LiveCharts.Wpf.Separator
            {
                Step = listOfChartValues[i].Count / 30 > 0 ? listOfChartValues[i].Count / 30 : 1, // this is making the assumtion that data arrivals follow uniform distribution
                IsEnabled = false
            }
        });

Current Bug chart (trying to put a minute label for every data point)

Need only 30 minute labels (maybe my algorithm to calculate step needs adjusting, currently I divide total number of data points by 30)

I looked at these two posts, but this is a different issue
LiveChart doesn't show all Labels on x-axis WPF
Force all axis labels to show

A: The issues, is that live chart produces for each point labels, and the numbers of labels need to be the number of the points. There are two solutions for the problem.
First You change the ChartValues<double> to ChartValues<ObservablePoint>
chart.Series = new LiveCharts.SeriesCollection()
{
    new LineSeries()
    {
        Title = "Some series",
        Values = new ChartValues<ObservablePoint>
        {
            new ObservablePoint(1,5),
            new ObservablePoint(1.5,7.6),
            new ObservablePoint(2,21),
            new ObservablePoint(5,25),
            new ObservablePoint(10,30),
            new ObservablePoint(17,30),
            new ObservablePoint(19.6,30),
            new ObservablePoint(30,40),

        }
    }
};
chart.AxisX = new LiveCharts.Wpf.AxesCollection()
{
    new LiveCharts.Wpf.Axis()
    {
        Title= "Minutes",
        Separator = new LiveCharts.Wpf.Separator()
        {
            Step = 1.0,
            IsEnabled = false
        }

    }
};

See that in the obserablepoint you specify X and Y. Point could have different distance between each other (irregular intervals)
The second solution could be that you got label array define in following way, so you make labels array as big as your count of points but you declare it that you got only 30 items, rest of them are empty.
chart.AxisX.First().Labels = new List<string>() { "1", "","2","","","3",.... "30" };

A: This was the solution to the problem, but Kaspar's answer was educational and helped me arrive at this solution. Therefore, I accepted his answer since he deserves the credit.
The way I solved this problem was to do the following: While creating the charts I would bind to the listOfLableValues; after creating the charts I would edit add to this list as shown in the bottom loop of my code:
private List<string> listOfLableValues = new List<string>();

//... other WPF code
// loop through all charts and to create them
       SeriesCollection = new SeriesCollection
       {
            new StepLineSeries
            {
                Values = listOfChartValues[i],
                PointGeometry = null,
                // Fill = Brushes.Transparent
             },
       };
//... other Livecharts code

        int lableCount = 1;
        for (int i = 0; i < listOfChartValues.Count; i++)
        {
            listOfChartValues[i].AddRange(de.ListOfListPlottedAmpData[i]);

            if (0 == i % (listOfChartValues[i].Count / 30))
                listOfLableValues.Add(lableCount++.ToString());
            else
                listOfLableValues.Add("");
        }


text:
Q: How to make multiple subdirectories in Eclipse from existing code I am using Windows 10 and Eclipse Mars edition 32 bit. Programming in C
I am trying to learn C from a Lynda.com course C Essential Training. The course provides a zipped directory with many .c and files and a few others like .h files as you can see below.

However in the video he managed to get each .c file and related source code into its own directory structure.

I've tried numerous type of imports and I also used a batch file to put each .c file in its own folder and tried importing that. I was able to get the Eclipse IDE project window to look like the instructors, but as soon as I tried to compile individual .c programs the project kept looking in the primary workspace folder which for me is C:\Source\Testing\workspace and error'd out.
Is there an import option to create this type of subdirectory structure automatically? I want to go through the tutorial and build and execute each .c file individually. However what I have had to do is put the .c file into a single folder build it and run it one at a time. I then have to delete the source and debug folder and start over for each lesson. There must be a better way.

A: Eclipse workspace is streigh connected to FS.
This means that your workspace in Eclipse is a folder on your hard disk or where it is stored.
What you can simply do is to create a new folder using right-click-popup-menu within Eclipse Project Explorer and then copy/move files into the new folder.
Or you can create a new folder into your workspace directory and copy/move file inside, then you must refresh Eclipse workspace.


text:
Q: RabbitMQ + OAuth => MQTT login failed for user I'm having trouble configuring RabbitMQ to use JWT for client access (for exemple with Paho to access MQTT)
I have use this recomended plugin rabbitmq_auth_backend_oauth2
I'm generating my JWT access_token using Keycloak
Sample :
{
    "exp": 1617886910,
    "iat": 1617872510,
    "jti": "e720xxxxxxad0",
    "iss": "https://xxxxxxxxxxx",
    "aud": [
        "kanban",
        "rabbitmq",
        "account"
    ],
    "sub": "ec27xxxxxxx92fc",
    "typ": "Bearer",
    "azp": "kanban",
    "session_state": "1bcxxxxxxx5e",
    "acr": "1",
    "allowed-origins": [
        ""
    ],
    "realm_access": {
        "roles": [
            "offline_access",
            "uma_authorization"
        ]
    },
    "scope": "email kanban.read:*/* kanban.write:*/* profile kanban.configure:*/*",
    "email_verified": false,
    "plant": "*",
    "name": "xxx xx",
    "preferred_username": "xxxx",
    "given_name": "xxxxx",
    "rabbitmq": ["kanban.read:*/*", "kanban.write:*/*"],
    "family_name": "xx",
    "email": "xxxxxxxxx"
}

And for rabbitmq config:
Dockefile
RUN rabbitmq-plugins enable rabbitmq_mqtt
RUN rabbitmq-plugins enable rabbitmq_web_mqtt
RUN rabbitmq-plugins enable rabbitmq_management
RUN rabbitmq-plugins enable rabbitmq_auth_backend_oauth2
COPY ./rabbitmq/advanced.config /etc/rabbitmq/advanced.config
COPY ./rabbitmq/rabbitmq.conf /etc/rabbitmq/rabbitmq.conf
EXPOSE 1883

advanced.config
[
  {rabbit, [
    {auth_backends, [rabbit_auth_backend_oauth2, rabbit_auth_backend_internal]},
    {auth_mechanisms, ['PLAIN','AMQPPLAIN','EXTERNAL']}
  ]},
  {rabbitmq_auth_backend_oauth2, [
    {resource_server_id, <<"kanban">>},
    {key_config, [
      {default_key, <<"YoC-uSkB0wTmh39078PuzmobULDLk-1aQqDZWV4fgYc">>},
      {additional_rabbitmq_scopes, <<"rabbitmq">>},
      {jwks_url, <<"https://XXXXX/auth/realms/XXXXX/protocol/openid-connect/certs">>},
      {signing_key,
          #{<<"YoC-uSkB0wTmh39078PuzmobULDLk-1aQqDZWV4fgYc">> => {pem, <<"-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArXL0WnwckscW5XeCofcG65Fhdy/FJhvvuQkFOUu2erzPfI1Tq35yijikcAG4Qp+nnpUaKXw6juWXdRwebAEuX6ZsCZ5T75dJlXErov3jqOb47U5V0g2B2nNWOzeNGLsPDBOVw3e1iG6zIZtVUlJBM7hkAQuKj6w9R4mu5JEisGCw3onjrF97/E1oOvTw3v+tDYxwWqyLpFi5crjam3lzx4VxN8zwLCx1Q3x2a3jeMLlt0iL9F/+axrHZg45CrMq0MOsWJ3vJQh7WfKjW6hFlyDE4y/nxHds+v/nmzJC5ahEAFHixq7+0VhL0K+tSDmQjxG8gBfyaPsQsPCLC4Zzv/wIDAQAB
-----END PUBLIC KEY-----">>}
         }
     }]
    }
  ]}
].

When I test using Paho, providing my JWT on PASSWORD field (and user empty or anythign else), I have the error.
What I have tried :

*

*Check if advanced.config is loaded by providing stupid key => generate parse error

*Check authbackend is loaded => displayed in log at startup

*Check with different username or empty in my paho script

*Check with/without signing key field in advanced.config

*Check with or without << >> around JKWS => nothing happend

What can cause the error or what is missconfigured in my configfiles ?


text:
Q: Download file php I have a Codeigniter function which puts some data in a file to be downloaded.
$data= "test";

header('Content-Disposition: attachment; filename=test.file');

echo $data;

However, the content includes the HTML for that view in which I click on to activate the function as well. How do I remove the content for the HTML inside the file?

A: Create a separate controller/view just for the file.

A: Create a method in a controller
sample code:
  public function download_file($name)
    {
        $data = file_get_contents(FCPATH . 'storage' . DIRECTORY_SEPARATOR. $name); // Read the file's contents

        force_download($name, $data);
        redirect('index/index');
    }

Call the above method from view page


text:
Q: Undefined array variable $attacks_list = array();

function f1()
{
    $sql = "SELECT * FROM user_pokemon_db WHERE user_id = '".$id."' AND pkmn_id = '".$pkmn_id."' " or die(mysql_error());
    $res = mysql_query($sql);
    $$attacks_list = mysql_result($res,0,"attacks");
    $attacks_list = unserialize($attacks_list);
    print_r($attacks_list);
 }

I have already declared the array globally..!But still its not able to identify it!
Is there any other way to declare it globally?

A: If you wish to use a global within a function, you must declare it to be global at function level too, e.g.
$attacks_list = array();

function f1()
{
    global $attacks_list; // <-- ADDED
    $sql = "SELECT * FROM user_pokemon_db WHERE user_id = '".$id."' AND pkmn_id = '".$pkmn_id."' " or die(mysql_error());
    $res = mysql_query($sql);
    $$attacks_list = mysql_result($res,0,"attacks");
    $attacks_list = unserialize($attacks_list);
    print_r($attacks_list);
 }

Have a look at the php.net article on variable scope for more information too: http://www.php.net/manual/en/language.variables.scope.php


text:
Q: Misunderstanding of notation of tangent maps Im getting mad with the notation related to tangent bundles and so. Im following the book Analysis II of Amann and Escher, where the main discussed issue appear in page 270.

Some definitions: let $M\subset\Bbb R^n$ a submanifold of dimension $m$, then $$\begin{align}T_pM:=\{&(v)_p\in T_p\Bbb R^n:\\&\quad\exists\epsilon>0\exists\gamma\in C^1((-\epsilon,\epsilon),\Bbb R^n)\text{ such that }{\rm im}(\gamma)\subset M,\gamma(0)=p,\dot\gamma(0)=v\}\tag1\end{align}$$
where $T_p\Bbb R^n:=\{(p,v):v\in\Bbb R^n\}$ and $(v)_p:=(p,v)$. And for some differentiable $f:M\to Y$ is defined
$$T_pf:T_pM\to T_{f(p)}Y,\quad (p,v)\mapsto (f(p),\partial f(p)v)\tag2$$
Also is described a chain rule for tangent maps that reads
$$T_p(f\circ g)=T_{g(p)}f\circ T_p g\tag3$$
Suppose $\varphi$ is a chart of $M$ around $p$, thus is defined as in $(2)$, that is
$$T_p\varphi:T_pM\to T_{\varphi(p)}V$$
for some $V\subset\Bbb R^m$.

My confusion starts from the representation of $(T_p\varphi)v$ (for some $v\in T_pM$). It is written as
$$(T_p\varphi)v=\sum_{k=1}^m v_ke_k\tag4$$
where it is not clear if $e_1,e_2,\ldots,e_m$ is a basis of $\Bbb R^m$ or a basis of $T_{\varphi(p)}\Bbb R^m$ (I know that both spaces are essentially the same thing anyway).
The definition of differential of a map $f\in C^1(M,\Bbb R)$ is defined as
$$d_p f:={\rm pr_2}\circ T_p f\tag5$$
where ${\rm pr_2}$ is the canonical projection of the second coordinate. But here again appear my confusion with the notation of $(T_p\varphi)v$ when is stated that
$$(d_p f)v=\partial (f\circ\varphi^{-1})(x_0)(T_p\varphi)v\tag6$$
where $x_0:=\varphi(p)$. From all the above definitions I can follow the algebraic manipulations of $(6)$ but anyway it seems meaningless, observe that $(T_p\varphi)v\in T_{\varphi(p)}V\subset T_{\varphi(p)}\Bbb R^m$, however the domain of $\partial (f\circ \varphi^{-1})(x_0)$ is not $T_{\varphi(p)}V$!!!
I must assume that here the authors are using some trivial isomorphism between $T_{\varphi(p)}V$ and $V$?

A: Since $T_p\mathbb{R}^n$ is canonically isomorphic to $\mathbb{R}^n$ via the map
$$\begin{align}
T_p\mathbb{R}^n &\to \mathbb{R}^n \\
(p,v) &\mapsto v
\end{align}$$
most authors do not bother distinguishing them. In fact, some even define $T_p\mathbb{R}^n$ to be equal to $\mathbb{R}^n$. Similarly, if $V$ is an open subset of $\mathbb{R}^n$, then the inclusion map $V \hookrightarrow \mathbb{R}^n$ induces an isomorphism $T_pV \cong T_p\mathbb{R}^n$ and hence an isomorphism $T_pV \cong \mathbb{R}^n$ for any $p \in V$. Thus $T_pV$ and $\mathbb{R}^n$ can be (and in practice, are) treated as if they were equal.

it is not clear if $e_1,e_2,…,e_m$ is a basis of $\mathbb{R}^m$ or a basis of $T_{\varphi(p)}\mathbb{R}^m$

It is a basis of $T_{\varphi(p)}V$, which is canonically identified with $T_{\varphi(p)}\mathbb{R}^n \cong \mathbb{R}^n$.

however the domain of $\partial(f\circ\varphi^{−1})(x_0)$ is not $T_{φ(p)}V$

Again, this is not a problem because $T_{\varphi(p)}V$ is, for all intents and purposes, equal to $\mathbb{R}^n$.


text:
Q: Hacer una query en Laravel con una tabla pivote Hola buenos días estoy intentando hacer una query entre tres tablas con una de ellas es la pivote. Se trata que tengo una tabla para guardar las viviendas, otra para guardar los servicios que puede tener las viviendas y por último una pivote que almacena la id de la vivienda y la id del servicio que tiene.
La idea es mostrar todos los servicio en una iteración y lo que si tenga la vivienda ponerles un check verde y si no lo tiene poner una x en rojo.
Mis tablas son las siguientes:
Vivienda

id
name
slug

1
Reformado con plaza de garaje incluida
v-849-reformado-con-plaza-de-garaje-incluida

2
Reformado con ascensor
v-850-reformado-con-ascensor

Servicio

servicio_id
name

1
Ascensor

2
Armarios empotrados

vivienda_servicio

vivienda_vivienda_id
servicio_servicio_id

1
2

1
1

Bien, supongo que se puede hacer con relaciones, pero no es algo que se me de muy bien, entonces estoy haciendolo así:
Controlador
$servicios = ViviendaServicio::
        join('servicio', 'vivienda_servicio.servicio_servicio_id', '=', 'servicio.servicio_id')
        ->where('vivienda_servicio.vivienda_vivienda_id', $propiedad->id)
        ->select('vivienda_servicio.*', 'servicio.nombre', 'servicio.servicio_id')->get();
 //////
$serviciosSeleccionados = ViviendaServicio::where('vivienda_servicio.vivienda_vivienda_id', $propiedad->id)->pluck('servicio_servicio_id');
//////
$todosServicios = Servicio::whereNotIn('servicio_id', $serviciosSeleccionados)->get();

Luego en mi vista los itero así:

      @foreach ($servicios as $item)

             {{ $item->nombre }}

       @endforeach
       @foreach ($todosServicios as $item2)

               {{ $item2->nombre }}

        @endforeach

Esto está funcionando, pero el problema es que me saca primero los que si tiene y luego los que no y yo quiero que me los saque todos con el mismo orden siempre y ponga el check en los que si y la cruz en los que no. ¿Eso es posible?
Pongo como consulto en mi controlador la vivienda que estoy viendo.
$propiedad = Vivienda::with('etiqueta')
             ->with('poblacion')
             ->with('elDistrito')
             ->with('galeria')
             ->where('slug', $slug)->first();

En respuesta a Jonathan Orta:
Esto es lo que recibo con un dd($serviciosSeleccionados);
  0 => 1
    1 => 2
    2 => 3
    3 => 4
    4 => 8
    5 => 19
    6 => 20
    7 => 21
    8 => 26
  ]

A: Puedes modificar un array de todos los servicios utilizando los que ya existen
$propiedad = Vivienda::with('etiqueta')
             ->with('poblacion')
             ->with('elDistrito')
             ->with('galeria')
             ->where('slug', $slug)->first();

//Obtienes los id de los servicios que tiene
$serviciosSeleccionados = ViviendaServicio::where('vivienda_vivienda_id', $propiedad->id)->get()->pluck('servicio_servicio_id');

//Al utilizar map, indicas cuales tiene, añadiendo una propiedad que puede ser 'tiene' que va a tener un valor true o false dependiendo si el servicio esta incluido en los servicios de la vivienda
$servicios = Servicio::orderBy('nombre')->get()->map(function ($servicio) use ($serviciosSeleccionados) {
    $servicio->tiene = in_array($servicio->id, $serviciosSeleccionados);
    return $servicio;
});

// En la vista, recorres todos los servicios y la propiedad 'tiene' te permite saber si existe o no
@foreach ($servicios as $item)

             {{ $item->nombre }}

                tiene ? 'siTiene' : 'noTiene' }}">

       @endforeach


text:
Q: C# Password validation limit for multiple user login I am attempting to set a login attempt limit. The code allows me to log in to each user, recognizes and invalid attempt, and records the first attempt. BUT it doesn't add up the attempts and then execute the limitation. I originally had the login types as "else if" statements but it would only approve the last login type. Here is my code. Any hints would be greatly appreciated.
        private void buttonLogin_Click(object sender, EventArgs e)
        {
            MyDB db = new MyDB();
            int attempt = 1;

            if (attempt < 4)
            {

                MySqlDataAdapter adapter = new MySqlDataAdapter();
                DataTable table = new DataTable();
                MySqlCommand command = new MySqlCommand("SELECT * FROM `users` WHERE `username` = @usn AND `password` = @pas", db.getConnection);

                command.Parameters.Add("@usn", MySqlDbType.VarChar).Value = textUsername.Text;
                command.Parameters.Add("@pas", MySqlDbType.VarChar).Value = textBoxPass.Text;

                adapter.SelectCommand = command;

                adapter.Fill(table);

                if (table.Rows.Count > 0)
                {

                    switch (table.Rows[0]["type"] as string)
                    {
                        case "student":
                            {
                                this.Hide();
                                new StudentMain().Show();
                                break;
                            }
                        case "faculty":
                            {
                                this.Hide();
                                new FacultyMain().Show();
                                break;
                            }
                        case "admin":
                            {
                                this.Hide();
                                new AdminMain().Show();
                                break;
                            }
                    }
                }
                else
                {
                    MessageBox.Show("Invalid Username or Password", "Attempt: " + attempt, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            else if (attempt == 4)
            {
                MessageBox.Show("Login attempts exceeded.");
                textUsername.Enabled = false;
                textBoxPassword.Enabled = false;
                this.Close();
            }

            attempt++;
        }
    }
}

A: It's because you keep resetting your login attempts each time you click the login button.
Changes this:
private void buttonLogin_Click(object sender, EventArgs e)
{
    ...

    int attempt = 1;

    ...
}

To this:
int attempt = 1;

private void buttonLogin_Click(object sender, EventArgs e)
{
    ...
}

A: you can write click button function like this logic
public int Attempts = 0;
private void Button_Click(object sender, EventArgs e)
{
     bool passwordIsTrue = false;

     Attempts++;

     if (Attempts >= 4)
     {
         MessageBox.Show("Maximum attempts (3)");
         return;
     }

     if (passwordIsTrue == false)
     {
         Attempts++;
     }
     else
     {
         Attempts = 0;
     }
}

A: Just keep your counter outside the function so when the limit is reached you don´t even have to call the function.


text:
Q: AngularJS adding Headers in http.put request I am new to angularJs, right now I want to use $http.put to update an Json file at a remote repository.
but everytime I try, I get the following error
XMLHttpRequest cannot load http://blabla&action=update.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'localhost:9080' is therefore not allowed access.

So it doesn't work. now I did my part of search on Stack and google. a lot of people are saying I should add headers. I don't know how to add headers correctly and I have no idea how to verify if the headers are correctly added.
Can someone help me? The following is my code.
$http.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
$http.defaults.headers.post['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT';
$http.defaults.headers.post['Access-Control-Allow-Credential'] = 'true';
$scope.update = function(key,value){
    $scope.myData[key] = value;
    $http.put('http://blabla&action=update', $scope.myData)
    .success(function (data, status) {
        alert('success');
    })

the code above is still giving me the same error, from my research online, the headers are suppose to solve this problem... but it didn't. I don't know what I did wrong. thanks guys!

A: You can pass a config object to the $http.put method like this:
$http({
        method: 'PUT',
        url: 'http://blabla&action=update',
        data: $scope.myData,
        headers: {
            "Access-Control-Allow-Origin": "self",
            <other headers here>
        }
    })
    .success(function (data, status) {
    alert('success');
});

And you can verify the headers with the request within developer tools if you use Chrome or IE and FireBug if you use Firefox.
More info on Angular Docs.

A: Your main issue is that the headers need to be set on the server.  Your error:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'localhost:9080' is therefore not allowed access. is the key to all of this.
You are requesting from localhost:9080 to somewhere like foo.com/api.  That endpoint needs to return an Access-Control-Allow-Origin: localhost:9080 header to your application.


text:
Q: Translating column-wise JSON data from Excel into a hierarchical structure with python Overall goal
My overall goal is to translate input from an Excel file into a text file (a Stata .do file) to perform a set of data harmonisation tasks that have roughly the same structure but require individual treatment due to the idiosyncratic nature of the data (national surveys). The harmonisation will be performed by different people and Excel ensures people use the same structure. My strategy is to read the Excel file in JSON structure, use this structure write to the do file.
Task I request help with
The problem I am trying to solve now is how to go from the column structure of the JSON as it reads from Excel to a hierarchical structure. The Excel file I would like users to have has a structure of Blocks and Tasks within the Blocks, with specific commands (of one or more lines) needed to carry out the tasks. The image below is an example of the Excel document:

The ultimate goal is to produce a text file like this:
* A

* A1
Command for A1

* A2
Command for A2 (1)
Command for A2 (2)

* B

* B1
Command for B1 (1)
Command for B1 (2)
Command for B1 (3)

*B2
Command for B2 (1)
Command for B2 (2)

I use Python to read this in using the following code:
path = "Some Path/test.xlsx"
import pandas
import json

x = pandas.read_excel(path, sheet_name='Sheet')
json_str = x.to_json()

This yields, as said, a column structure of JSON, which looks like this:

What I am struggling with is to translate this into the hierarchical structure the code naturally has. My desired output would be a JSON object of this form:

If there is a smarter way to achieve the overall goal, I am happy to learn of it, but I thought this translation is a necessary step to structure the information.
Here is the code to produce the JSON objects for reproducibility
# Column-wise object
'{"Block":{"0":"* A","1":null,"2":null,"3":null,"4":null,"5":null,"6":"* B","7":null,"8":null,"9":null,"10":null,"11":null},"Task":{"0":"* A1","1":null,"2":null,"3":"* A2","4":null,"5":null,"6":"* B1","7":null,"8":null,"9":null,"10":"*B2","11":null},"Code":{"0":"Command for A1","1":null,"2":null,"3":"Command for A2 (1)","4":"Command for A2 (2)","5":null,"6":"Command for B1 (1)","7":"Command for B1 (2)","8":"Command for B1 (3)","9":null,"10":"Command for B2 (1)","11":"Command for B2 (2)"}}'

# Hierarchical object
'{"* A": {"* A1": ["Command for A1"], "* A2": ["Command for A2 (1)", "Command for A2 (2)"] }, "* B" : {"* B1" : ["Command for B1 (1)", "Command for B1 (2)", "Command for B1 (3)"], "* B2" : ["Command for B2 (1)", "Command for B2 (2)"]}}'

A: You can do it like this:
import pandas as pd
import json
from collections import defaultdict

path = "Some Path/test.xlsx"
df = pd.read_excel(path,
                   engine='openpyxl',
                   # header=None, names=['Block', 'Task', 'Code']  # only if your file has no headers
                   )

df.dropna(inplace=True, axis=0, how='all')
df.fillna(method='ffill', inplace=True, axis=0)
df = df.set_index(['Block', 'Task'])

nested_dict = defaultdict(lambda : defaultdict(list))

for keys, value in df.Code.iteritems():
    nested_dict[keys[0]][keys[1]].append(value)

json_str = json.dumps(nested_dict, indent=4, sort_keys=True)
print(json_str)

Output:
{
    "* A": {
        "* A1": [
            "Command for A1"
        ],
        "* A2": [
            "Command for A2 (1)",
            "Command for A2 (2)"
        ]
    },
    "* B": {
        "* B1": [
            "Command for B1 (1)",
            "Command for B1 (2)",
            "Command for B1 (3)"
        ],
        "* B2": [
            "Command for B2 (1)",
            "Command for B2 (2)"
        ]
    }
}


text:
Q: My CSS isn't being applied to elements with IDs I am trying to have a background box behind my text and I cant get it to work. I have done this before and it worked fine, but I can't see where I have gone wrong this time. I have checked to make sure I have linked the CSS to the HTML correctly by changing the background-color, which worked.
HTML:

<link rel="shortcut icon" type="image/x-icon" href="SiteIcon.ico">
<title>Navigation</title>
<link rel="stylesheet" href="CSS/style for SubNav.css">

Navigation

The Online World

Animation

Creating an app

Mini Game

Gallery

Be Creative

About me

CSS:
body {
    color: black;
    background-color: black;
    margin: 0;
}

#1{
    width: 7%;
    margin: 50px auto 50px auto;
    padding: 2%;
    background-color: white;
    box-shadow: 0px 0px 1px rgba(0,0,0,.90);
    position: relative;
}

A: The problem is not with the HTML / element ID - browsers have supported the "lenient" ID for a long time, which is why it is part of HTML5. While the HTML4 specification is different, if this was a major breaking change it wouldn't be in HTML5 - 'nough said.
The real issue the CSS selector, not the element ID. A CSS selector that begins with a number must have the number escaped.
That is, #1 is an invalid CSS selector while #\31 is valid - and matches elements with id=1.
This is a CSS parsing rule, for backwards compatibility now, and not an HTML or ID restriction. See CSS character escape sequences for gritties on escaping "odd" CSS selectors. Or see the w3c token/lexing train tracks. (For example, the selector to match id=1hello is #\31 hello, with the space - good grief!)
The corrected selector can be verified with this fiddle:

Hello world!

#\31 {
   color: blue;
   font-size: 30px;
}

That being said, I avoid element IDs that are not trivial CSS selectors to avoid this extra work.

A: Element IDs can't start with numbers. As soon as you change that, everything is good: http://jsfiddle.net/gr5956br/

body {
color: black;
background-color: black;
margin: 0;
}

#a1{
width: 7%;
margin: 50px auto 50px auto;
padding: 2%;
background-color: white;
box-shadow: 0px 0px 1px rgba(0,0,0,.90);
position: relative;
}

Navigation

The Online World

Animation

Creating an app

Mini Game

Gallery

Be Creative

About me

Your original version with numbers (just so you can see that's the issue):

body {
color: black;
background-color: black;
margin: 0;
}

#1{
width: 7%;
margin: 50px auto 50px auto;
padding: 2%;
background-color: white;
box-shadow: 0px 0px 1px rgba(0,0,0,.90);
position: relative;
}

Navigation

The Online World

Animation

Creating an app

Mini Game

Gallery

Be Creative

About me

A: While ids can technically be numbers (in HTML5), it's got weird support in browsers because of backwards compatibility with the HTML4 spec.
ids should start with a letter for compatibility.

The Online World

and
#a1{
    width: 7%;
    margin: 50px auto 50px auto;
    padding: 2%;
    background-color: white;
    box-shadow: 0px 0px 1px rgba(0,0,0,.90);
    position: relative;
}

works as expected.

A: Do you mean something like this?
HTML

Navigation

The Online World

Animation

Creating an app

Mini Game

Gallery

Be Creative

About me

</body

CSS
   body {
color: black;
background-color: black;
margin: 0;
}

#One{
width: 7%;
margin: 50px auto 50px auto;
padding: 2%;
background-color: white;
box-shadow: 0px 0px 1px rgba(0,0,0,.90);
position: relative;
}

You shouldnt use numerical numbers for ID's. Replace with characters and you will be fine.
Fiddle

A: You can also style the div's for less markup. And then style each link as needed. http://codepen.io/dfrierson2/pen/RNoWZe
body {
color: #fff;
background-color: pink;
margin: 0;
}

div {

  width: 7%;
  background: #fff;
}

#1{
width: 7%;
margin: 50px auto 50px auto;
padding: 2%;
background-color: white;
box-shadow: 0px 0px 1px rgba(0,0,0,.90);
position: relative;
}

<link rel="shortcut icon" type="image/x-icon" href="SiteIcon.ico">
<title>Navigation</title>
<link rel="stylesheet" href="CSS/style for SubNav.css">

Navigation

The Online World

Animation

Creating an app

Mini Game

Gallery

Be Creative

About me


text:
Q: (Date).ToString does not use specified delimiter Why does the ToString() method return the date with '-' rather than the '/' specified.
PS 11:59  C:\src\t
>((Get-ChildItem 'u.txt').LastWriteTime).ToString('yyyy/MM/dd')
2019-08-09

A: / is the format specifier for a date separator, which for your culture evidently is -.
As that documentation section notes...

To change the date separator for a particular date and time string, specify the separator character within a literal string delimiter.

...which you would do like this...
((Get-ChildItem 'u.txt').LastWriteTime).ToString('yyyy''/''MM''/''dd')

...or this...
((Get-ChildItem 'u.txt').LastWriteTime).ToString("yyyy'/'MM'/'dd")

You can also escape the / character to get the same result...
((Get-ChildItem 'u.txt').LastWriteTime).ToString('yyyy\/MM\/dd')


text:
Q: Replacing key value in array of objects I'm working on a project that is a basic message app. basically i have created an array of objects that allows me to see pre built messages. Then i should be able to click a clear all button and clear all of the messages that are being displayed by looping through the array of objects. this is what i have so far in my messageData.js
const messages = [
  {
    id: 'message1',
    message: 'Hello everyone! Welcome to hell',
    userId: 'user1',
  },
  {
    id: 'message2',
    message: 'Yall are weirdos!',
    userId: 'user3',
  },
  {
    id: 'message3',
    message: 'Hey! I think everyone is awesome!',
    userId: 'user2',
  },
  {
    id: 'message4',
    message: 'Thanks for saying that my friend.',
    userId: 'user4',
  },
  {
    id: 'message5',
    message: 'Hey buddy, what is up?',
    userId: 'user4',
  },
];

const getMessages = () => messages;

and what i want to do is basically on click allow the messages key value to be changed to an empty string onclick so that i get rid of the displayed messages without getting rid of the object so that i can later push new messages into these key values.
I started to write this but i seem to be missing something..
const clearBtnFunction = () => {
  messages.splice(1, '');
};

i'll be calling the event listener on my main.js file so i'm not super worried about that part yet. I just want to know the proper syntax for replacing the key value in the array if thats possible.

A: const clearBtnFunction = () => {
  messages.foreach( ( message ) => {
      message.message = "";
  });
};

or with a for loop
const clearBtnFunction = () => {
  for( let i =0; i < messages.length; i++) {
      messages[i].message = "";
  }
};

A: Here is what i opted for. I placed this function, not in the messagesData.js but in the messages.js where i'm building the domstring
const clearBtnFunction = (e) => {
 e.preventDefault();
 const messages = message.getMessages();
 messages.splice(0, messages.length);
 messageBuilder(messages);
};


text:
Q: Generalized Poisson regression using glmmTMB I'm modelling a discrete (and naturally bounded) underdispersed variable $Y$ taking values in $0, 1,..., k$ and the aim is to estimate the conditional probabilities $P(Y ≤ y \ | \ X)$ under the model for a given predicted value y and predictors $X$. A Generalized Poisson regression handles underdispersion by estimating dispersion parameters and can be fitted using glmmTMB::glmmTMB(..., family = "genpois") from which the estimated means and dispersion parameters can be extracted. I'm unable to find the parameterization used in the package and thus a formula for the conditional Generalized Poisson density given the two model parameters - which is necessary to compute $P(Y ≤ y \ | \ X)$.
Any other general suggestions on how to model underdispersed count data while obtaining the conditional distribution is also appreciated.


text:
Q: How do I tailor my query to get a specific title? I have a query in my app.js file that renders into my list page list.ejs  found at http://localhost:4100/list. As the name may suggest, the list page displays a list of ALL the transactions stored in the database, though I would be more interested in only displaying all the transactions strictly within the county of Nairobi.
Find below the contents of my app.js file:
app.get('/list', (req,res)=> {

let countyName;
countyName = transModel.findOne({ transCounty : /Nairobi/i, })
                                    .limit(5)
                                    .select({ transCounty:1})
                                    .exec( (err, result)=> {

                                    if (err) throw err;
                                           console.log('>> ' +result);
                                           return result;
                                        });

console.log ('countyName: ' +countyName);

transModel.find( (err, docs)=> {
if (!err)
    {
        res.render('list',  {data : docs, countyName: countyName});
    }
else
    {
//          res.status(status).send(body);
    }

 })

});

In the terminal, the code above yeilds:
countyName: undefined
>> { _id: 609f7ed8fe1fd8b3193b0b77, transCounty: 'Nairobi' }

My list.ejs looks like this:

 Transactions

 Name of County: <%= countyName %>

         _id
         Transaction Amount
         Transaction County
         Transaction Industry

    <% data.forEach(function(entry) {%>

         <%=entry._id%>
         <%=entry.transAmount%>
         <%=entry.transCounty%>
         <%=entry.transIndustry%>

    <%});%>

The above list.ejs file, though correctly renders a table with the desired content from the database isn't able to pick the name of the County.  Kindly help me figure out how I can achieve this.
Find below an image of the rendered list.ejs:

Kindly note Name of county is undefined.
How do I formulate my query be able to yield all transactions within only Nairobi, and also display the name of the county in the ejs file.
Looking forward to your help.

A: You should wait for the promise to resolve before using its value:
countyName = await transModel.findOne({
        transCounty: /Nairobi/i,
    })
    .limit(5)
    .select({
        transCounty: 1
    })
    .exec();


text:
Q: How to save statistics value output from Python nested loop for I have program to compute statistical values from several file datasets. I have created program using nested loop for. The output is nicely printed on screen but can't saved in on file.
import numpy as np
from scipy.stats.stats import pearsonr

list = ['01', '02','03','04','05','06','07','08','09','10']
month='NOV2016'

for date in list:

    path='D:/Match-Nov2016/24-match-ground-imsra-0.25/'
    data=np.loadtxt(path+'3DIMG_'+date+month+'_DAILY.dat')
    lats=data[:,0]
    lons=data[:,1]
    ground=data[:,2]
    model=data[:,5]

    bias=np.mean(model-ground)
    rms=np.sqrt(np.mean((ground-model)**2))
    std=np.std(ground-model)
    corr=pearsonr(ground,model)
    corr=corr[0]

    bias=np.round(bias,2)
    rms=np.round(rms,2)
    std=np.round(std,2)
    corr=np.round(corr,2)

    stat=np.zeros((np.size(bias),4))

    stat[:,0]=np.reshape(bias,(np.size(bias)))
    stat[:,1]=np.reshape(rms,(np.size(rms)))
    stat[:,2]=np.reshape(std,(np.size(std)))
    stat[:,3]=np.reshape(corr,(np.size(corr)))

    print stat
    np.savetxt('result.dat',stat,fmt='%9.2f')

RESULT:
The result shown on screen is as follows:
[[ 12.27  25.48  22.33   0.26]]
[[ 18.39  26.47  19.04   0.3 ]]
[[ 22.96  33.12  23.87   0.38]]
[[ 14.31  38.9   36.17   0.08]]
[[ 19.73  26.75  18.07   0.46]]
[[ -3.53  24.77  24.51   0.  ]]
[[  9.68  21.91  19.66  -0.11]]
[[  4.94  17.96  17.27   0.02]]
[[  3.76  15.88  15.43   0.5 ]]
[[  2.07  18.1   17.98   0.31]]

However, the result printed on output file "result.dat" is only the last line.
     2.07     18.10     17.98      0.31

I could not figure out whats the problem with that!..

A: Finally I managed to found something simple to solve to question above.
import numpy as np
from scipy.stats.stats import pearsonr

#############################################################################
list = ['01', '02','03','04','05','06','07','08','09','10']

month='NOV2016'

data2=[]
data3=[]
data4=[]
data5=[]
for date in list:

    path='D:/MASTER/PLOT-MATCH/Match-Nov2016/24-match-ground-imsra-0.25/'
    data=np.loadtxt(path+'3DIMG_'+date+month+'_DAILY.dat')
    lats=data[:,0]
    lons=data[:,1]
    ground=data[:,2]
    model=data[:,5]

    bias=np.mean(model-ground)
    rms=np.sqrt(np.mean((ground-model)**2))
    std=np.std(ground-model)
    corr=pearsonr(ground,model)
    corr=corr[0]

    data2.append(bias)
    data3.append(rms)
    data4.append(std)
    data5.append(corr)

print data2
print data3
print data4
print data5

#######################################################################

##SAVE FILE OPTION 2

stat=np.zeros((10,4))

stat[:,0]=data2
stat[:,1]=data3
stat[:,2]=data4
stat[:,3]=data5

print stat
np.savetxt('TEST-NEW2.dat',stat,fmt='%9.2f')
###############################################################

Define the new output list name as data2,data3, data4 and data5 and append the value on it and you can call and saved the values on text in numpy.


text:
Q: The css file does not work on localhost when using bootstrap When I change the index.php file to index.html, it runs main.css file on local. But when I run it with php, it does not see main.css. Bootstrap sees the css files.
Note:The index.html code works when I run on local. There is no problem with the code.
Edit:The problem is not in PHP
<!DOCTYPE HTML>

<title>Hi</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/main.css">

<button type="button" class="btn btn-primary btn-outline-danger">Danger</button>

main.css:
.btn-primary{
  font-size: 20px;
  padding: 15px 60px;
  background-color: #fed136;
  text-transform: uppercase;
}

A: This is not really a PHP problem. This is happening because Bootstrap is overwriting your main CSS. In fact, using the main CSS, give your button an ID name and change it to the main cass. I think this will work
bootstrap default css  btn-primary

use css
.class_name.btn-primary{
  font-size: 20px;
  padding: 15px 60px;
  background-color: #fed136;
  text-transform: uppercase;
}

A: Please do not overwrite the bootstrap classes,instead use custom class say .btnDelete.
.btnDelete{
   font-size: 20px;
  padding: 15px 60px;
  background-color: #fed136;
  text-transform: uppercase;
}

And also remove asterisk btn-primary.Bootstrap uses snake case notation for naming classes.why don't you use camelCase notation in order to distinguish between user-defined classes and bootstrap classes.

A: It is actually not a PHP problem. It is happening because Bootstrap is overwriting your main CSS. To actually use main CSS give your button a id name then change it in main.css. I think that will work. ;-)


text:
Q: Fisher information $I(\sigma^2)$ and Cramer-Rao of estimator $S^2$
Let $X_1,...,X_n$ be a random sample with $X_1\sim N(\mu,\sigma^2)$. Compute $I(\sigma^2)$ and verify the Cramer-Rao theorem for the estimator $S^2$

Since $f_{\mu, \sigma^2} = \frac{1}{\sqrt{2\pi} \sigma} \exp({-\frac{(x-\mu)^2}{2\sigma^2}})$, we have:
$$f(X|\sigma^2) = \prod_{k=1}^n\frac{1}{\sqrt{2\pi} \sigma} \exp({-\frac{(X_k-\mu)^2}{2\sigma^2}}) = (\frac{1}{\sqrt{2\pi} \sigma})^n \exp({-\frac{\sum_{k=1}^n (X_k-\mu)^2}{2\sigma^2}})$$
\begin{align*}
&\log(L(X|\sigma^2)) =-n\log(\sqrt{2\pi}\sigma)-\frac{\sum_{k=1}^n (X_k - \mu)^2}{2\sigma^2} \\
&\frac{\partial}{\partial \sigma^2}\log(L(X|\sigma^2)) = -\frac{n}{2\sigma^2}+\frac{\sum_{k=1}^n (X_k - \mu)^2}{2\sigma^4} \\
&I(\sigma) = \mathbb{E}((\frac{\partial}{\partial \sigma^2}\log(L(X|\sigma^2)))^2) = \frac{n^2}{4\sigma^4} -\frac{n^2}{2\sigma^4} +\frac{n^2}{4\sigma^4} = 0
\end{align*}
I'm pretty sure it shouldn't be $0$. Where is my mistake?
And for the second part I probably have to use $S^2 = \frac{1}{n-1}\sum^n_{k=1}(X_k-\bar{X})$ and check if $Var(S^2) \geq \frac{1}{I(\sigma)}$?

A: The mistake is in the last line:
$$\mathbb{E}\left[\left(\frac{\sum_{k=1}^n (X_k - \mu)^2}{2\sigma^4}\right)^2\right]=\mathbb{E}\left[\left(\frac{\chi_n^2}{2\sigma^2}\right)^2\right]=\frac{n(n+2)}{4\sigma^4}\neq\frac{n^2}{4\sigma^4}.$$


text:
Q: An erroneous successful parsing in a recursive descent parser I have the following code. It's a recursive descent parser with backtracking.
/*\              /*\
|*|--------------|*|
|*| Grammar:     |*|
|*| A -> ( A ) B |*|
|*|   | [ A ] B  |*|
|*|   | n B      |*|
|*|   | B        |*|
|*|              |*|
|*| B -> + C B   |*|
|*|   | e        |*|
|*|              |*|
|*| C -> ( C ) D |*|
|*|   | [ C ] D  |*|
|*|   | n D      |*|
|*|   | D        |*|
|*|              |*|
|*| D -> * E D   |*|
|*|   | e        |*|
|*|              |*|
|*| E -> n       |*|
|*|              |*|
|*| e represents |*|
|*| epsilon      |*|
|*|--------------|*|
\*/            /*\*/

#include <stdbool.h>
#include <stdio.h>

char *next;

int terminal(char token)
{
    return (*next++ == token);
}

int A();
int B();
int C();
int D();
int E()
{
    printf("In E()\n");
    char *temp = next;
    return (next = temp, terminal('n'));
}

int A1()
{
    printf("In A1()\n");
    return terminal('(') && A() && terminal(')') && B();
}

int A2()
{
    printf("In A2()\n");
    return terminal('[') && A() && terminal(']') && B();
}

int A3()
{
    printf("In A3()\n");
    return terminal('n') && B();
}

int A4()
{
    printf("In A4()\n");
    return B();
}

int A()
{
    printf("In A()\n");
    char *temp = next;
    return  (next = temp, A1()) ||
            (next = temp, A2()) ||
            (next = temp, A3()) ||
            (next = temp, A4());
}

int B1()
{
    printf("In B1()\n");
    return terminal('+') && C() && B();
}

int B2()
{
    printf("In B2()\n");
    return true;
}

int B()
{
    printf("In B()\n");
    char *temp = next;
    return  (next = temp, B1()) ||
            (next = temp, B2());
}

int C1()
{
    printf("In C1()\n");
    return terminal('(') && C() && terminal(')') && D();
}

int C2()
{
    printf("In C2()\n");
    return terminal('[') && C() && terminal(']') && D();
}

int C3()
{
    printf("In C3()\n");
    return terminal('n') && D();
}

int C4()
{
    printf("In C4()\n");
    return D();
}

int C()
{
    printf("In C()\n");
    char *temp = next;
    return  (next = temp, C1()) ||
            (next = temp, C2()) ||
            (next = temp, C3()) ||
            (next = temp, C4());
}

int D1()
{
    printf("In D1()\n");
    return terminal('*') && E() && D();
}

// D2 and B2 are the same functions

int D()
{
    printf("In D()\n");
    char *temp = next;
    return  (next = temp, D1()) ||
            (next = temp, B2());
}

int main(void)
{
    char str[1000];
    printf("INPUT a string to be parsed : ");
    scanf("%s", &str);
    next = &str[0];
    (*next == '\0' || A() == 1) ? printf("Parsed Successfully\n") : printf("Parsed Unsuccessfully\n");
    //(A() == 1) ? printf("Parsed Successfully\n") : printf("Parsed Unsuccessfully\n");
    printf("\n");
}

The string 3 = 3 gets parsed successfully by the program. The program is tripping up on the epsilon transition base on the console output. How can I fix it?
Here is the console output:
INPUT a string to be parsed : 3 = 3
In A()
In A1()
In A2()
In A3()
In A4()
In B()
In B1()
In B2()
Parsed Successfully

--------------------------------
Process exited after 2.888 seconds with return value 0
Press any key to continue . . .


text:
Q: Association between aspects/types Based on my previous question, I want to specify a part of it which I strongly believe can be a good guide to solve my problem, since the answer to the whole question is probably composed of many parts.
When I define an "association" in an "aspect" (or a type) in Alfresco Content Model, what is actually the "target class"? Could it be another aspect? When I want to associate two aspects as two tables in a regular Database, how this can be done? How can I define the properties in the second aspect? Could someone provide an example of associating two aspects? If the purpose of the association is not that which serves my above requirement, then what does it actually serves?

A: When you define an association, its target should be a node type. So node1 is associated to node2 somehow. That node is a valid node (aspect is just a set of properties/assocs over that node2).
Aspect is not a node type, it is merely a few more properties. You can add aspects to types, you can even define mandatory-aspects in type definition. But I think you want to associate node to node.
Now, you want to define an aspect that would be a table in another database? As in, not Alfresco? I believe the proper use case here should be that those tables get a dedicated type, not an aspect.
See what you can read from here and ask more questions on this.
In the mean time, it would help if you clarify a bit what is it that you want to do exactly?


text:
Q: Which green spectral line(s) are emitted in a Thomson tube? Related: What is meant by boiling off electrons in a heater coil?
In the Thomson tube we used in our class to produce an electron beam, the lab manual stated that the tube was filled with a low pressure argon gas. When the electrons collided with the argon gas, electrons in the gas molecules were excited and when they de-excite, green light is emitted. However, when one looks at the atomic spectra of argon, there are two green lines, as shown below.

Is one able to distinguished between these two green lines in this experiment or am I actually seeing both of these lines? I assume that because the Thomson tube sends in a range of electron velocities, that maybe its both green lines that I am seeing. However, I don't know for sure.

A: This is at best only a partial answer since I don't know for sure, but I would guess the tube contains a mixture of some gas (possibly argon) with a small amount of mercury vapour.
Effectively what you have is a gas discharge lamp, though I'd guess it's at a lower pressure than the usual gas discharge lamps because you don't want excessive electron scattering. These don't give you a single line, but rather you get a whole series of lines and the overall colour depends on which lines are strongest and contribute most to the light. Most gases tend to give blue/violet discharges - I'd guess your picture is of an argon discharge, and you can see that it's violet not green. I believe that adding a small amount of mercury vapour gives a blue/green light, which is why I suspect it's an argon/mercury mixture.
To be honest I'm not sure about this, and a quick Google didn't help much. Maybe it will give you somewhere to start from if you want to try following this up yourself.


text:
Q: How to truncate text in Django template loop I am spitting out some values with a for loop and want to make sure that it only displays X characters.  I'm relatively new to Django.
For example:

    by
    {% for author in book.volumeInfo.authors %}
      {% if not forloop.first %}&{% endif %}
      {{author}}
    {% endfor %}

Would produce a list of book authors, e.g.:

by Lennart Berggren & Jonathan M. Borwein & Peter B. Borwein

and I'd only like 30 characters, since sometimes the list of authors can be long.
I understand that I can use truncatechars (new in Django 1.4) to do this on a single value like {{author|truncatechars:9}}, but I'm wondering if there is an elegant way to apply to the for loop, or the resulting text from the for loop.  Please let me know if this isn't clear.
EDIT
truncatechars does not seem to work properly when used in a {% filter %}.  All it produces is "...".  I'll test some more, could be a bug.   truncatewords works well, and I may be more suitable for this situation anyhow.

        by
        {% filter truncatechars:30 %}
          {% for author in book.volumeInfo.authors %}
          {% if not forloop.first %}&{% endif %}
            {{author}}
          {% endfor %}
        {% endfilter %}

A: {% filter %}

A: Use a custom filter (doc here)
@register.filter
def queryset_as_list(queryset, attr=None):
    query_list = []
    for param in queryset:
        query_list.append(getattr(param, attr) if attr else str(param))

    return query_list

@register.filter
def str_list(list):
    return ', '.join(list)

I use a filter to convert a queryset to a list and another filter to convert a list to a string and finally use truncatechars filter of django to show only 50 characters in the template like this
{{ book.volumeInfo.authors|queryset_as_list|str_list|truncatechars:50 }}


text:
Q: build folder missing in Finder on Mac after npm build After running npm run-script build the build folder is not visible in Mac Finder.
But the folder is there, as seen via Terminal window ls command.
How can I get the folder to display in finder?

A: *

*The build folder might be hidden. You can try pressing cmd + shift + . in Finder to turn on showing hidden folders.

*You might have opened Finder in the wrong folder.  Try running open . in the terminal where you ran ls in.  That will open Finder in the correct folder.


text:
Q: Compare-Object (diff) unexpected results when importing CliXML I am currently reading a powershell book (powershell in a month of lunches), and there is one sample in the book which is not behaving as expected.
The intention: before executing these command, i have an instance of notepad++ running. I save the response of "Get-Processes note". This should only return an entry for notepad++. Then i start notepad twice, and then save the output of the same command again. When i do & diff of those 2 results, i expect to see notepad, twice.
First, i'll give a sample that -does- work as intended.
PS C:\WINDOWS\system32> $ref = gps *note*
PS C:\WINDOWS\system32> notepad
PS C:\WINDOWS\system32> notepad
PS C:\WINDOWS\system32> $cmp = gps *note*
PS C:\WINDOWS\system32> diff -ref $ref -diff $cmp

InputObject                          SideIndicator
-----------                          -------------
System.Diagnostics.Process (notepad) =>
System.Diagnostics.Process (notepad) =>

Great! This is the expected result.
The sample below should yield the same result, but it doesnt:
PS C:\WINDOWS\system32> cd \temp
PS C:\temp> cd \temp
PS C:\temp> gps *note* | Export-Clixml ref.xml
PS C:\temp> notepad
PS C:\temp> notepad
PS C:\temp> gps *note* | Export-Clixml cmp.xml
PS C:\temp> diff -ref (Import-Clixml ref.xml) -diff (Import-Clixml cmp.xml)

InputObject                            SideIndicator
-----------                            -------------
System.Diagnostics.Process (notepad)   =>
System.Diagnostics.Process (notepad++) =>

This time, i get one entry mentioning notepad, and one mentioning notepad++?
How does that make sense? Can anyone clarify?
FYI: i am not executing this as a script, i am executing these command one by one.

A: This isn't a full answer, but comments are too short to add the details:
I can repro the issue locally, but I think it's related to comparing PSCustomObjects rather than specifically to do with notepad / notepad++ processes and Export-Clixml and Import-Clixml. It just happens that Import-Clixml returns PSCustomObjects...
For example:
PS> $x = new-object PSCustomObject -Property @{"Name" = "aaa"}
PS> $y = @( (new-object PSCustomObject -Property @{"Name" = "bbb"}), (new-object PsCustomObject -Property @{"Name" = "aaa"}) )
PS> diff $x $y

InputObject SideIndicator
----------- -------------
@{Name=aaa} =>


text:
Q: white lines on heat map made by ggplot2 Look at the following picture, I tried to get a heat plot with ggplot2, but there is a white vertical line on it. What happens? Anybody gives me an hint?
Besides, there is a white line on each side of plot, why couldn't the heat plot fill the whole part while the contour fill the whole part?

A: Lucky! I've sovled the problem with setting an ultra-small left or right margin.


text:
Q: Why are some JSON attributes omitted? I have a JSON object that I'm working with. It's the result of an HTTP GET request.
The expected results are the following:
{
  "name": {
    "type": "string"
  },
  "authors": {
    "collection": "users",
    "via": "IDPid"
  },
  "id": {
    "type": "integer",
    "autoIncrement": true,
    "primaryKey": true,
    "unique": true
  }
}

The actual results are the following (The authors attribute is omitted):
{
  "name": {
    "type": "string"
  },
  "id": {
    "type": "integer",
    "autoIncrement": true,
    "primaryKey": true,
    "unique": true
  }
}

Why did it take out the authors attribute?
However, when I debug this in Chrome, though the authors attributes is still omitted, I am able to execute console.log(response.authors) and it reads it fine.
Also, when I go to the Network tab on Chrome dev tools to see the response of the HTTP request, it shows the missing attribute in the response body just fine.

A: I found out the problem. It was because console.log doesn't run right away. It runs after some time. I had other code that modified the object, but console.log ran after that code for some reason, even though I wrote it before.


text:
Q: General solution to a PDE
Consider the equation $u_{xx}+2u_{xy}+u_{yy}=0.$ Write the equation in the coordinates $s=x$ and $t=x-y$ and find the general solution of the equation.

We have that $x=s$ and $y=s-t,$ thus $u(x,y)=u(s,s-t)=v(s,t)$. Now I know I must compute partial derivatives of $x$ and $y$ by using the chain rule to find a general solution, but I am not sure how to apply it here?

A: $s=x$ and $t=x-y$  hense   $s_x=1$ ; $s_y=0$ ; $t_x=1$ ; $t_y=-1$
$$u_x=v_s s_x+v_t t_x=v_s+v_t$$
$$u_{xx}=(v_{ss} s_x+v_{st} t_x)+(v_{ts} s_x+v_{tt} t_x)=v_{ss}+v_{st}+v_{ts}+v_{tt}=v_{ss}+2v_{st}+v_{tt}$$
$$u_{xy}=(v_{ss} s_y+v_{st} t_y)+(v_{ts} s_y+v_{tt} t_y)=-v_{st}-v_{tt}$$
$$u_y=v_s s_y+v_t t_y=-v_t$$
$$u_{yy}=-v_{ts} s_y-v_{tt} t_y=v_{tt}$$
$$u_{xx}+2u_{xy}+u_{yy}=v_{ss}+2v_{st}+v_{tt}+2(-v_{st}-v_{tt})+v_{tt}=v_{ss}$$
$$v_{ss}=0$$
There is no difficulty to continue...


text:
Q: Complex variable algebra mishap One question on a problem set was the following:

Show that $x^2 - y^2 = 1$ can be rewritten as $z^2 + \bar{z}^2 = 2$. (With $z = x + iy$)

So I started working from the first expression based on the algebraic definition of $Re$ and $Im$ to see where it would lead me:
$$
\begin{align}
x^2 - y^2 & = Re(z)^2 - Im(z)^2\\
& = (\frac{z + \bar{z}}{2})^2 - (\frac{z - \bar{z}}{2})^2\\
& = \frac{1}{4}(z^2 - z^2 + 2z\bar{z} + 2z\bar{z} + \bar{z}^2 - \bar{z}^2)\\
& = \frac{1}{4}(4z\bar{z}) \\
& = z\bar{z}
\end{align}
$$
Okay, so this is progress I suppose, but if we look more closely we actually see that this is wrong:
$$
z\bar{z} = (x + iy)(x - iy) = x^2 + y^2
$$
... What the heck? How did that happen, we started with $x^2 + y^2$ and ended up with $x^2 + y^2$. What happened here? What is it that I'm missing that's causing this to happen.
EDIT: I also knew from the beginning that $x^2 - y^2 = z^2$, but the question asked me to solve it in terms of $Re$ and $Im$, so that's what I tried to do.

A: Note that $\operatorname{Im}(z) = \dfrac{1}{2\color{red}{i}}(z - \bar{z})$ so
$$\operatorname{Re}(z)^2 - \operatorname{Im(z)}^2 = \left(\frac{z + \bar{z}}{2}\right)^2 - \left(\frac{z - \bar{z}}{2i}\right)^2 = \left(\frac{z + \bar{z}}{2}\right)^2 + \left(\frac{z - \bar{z}}{2}\right)^2.$$


text:
Q: jqXHR.statusText is returned always "BAD REQUEST" I am having a service orientedwebsite that all its html is generated by wcf services . I am having my services deployed live . but the problem is in wcf code I always return the request as bad request , but I make my action in the statustext , like success error etc... so the problem that the services isnt working 100% time fine , sometimes they return the statusText as supposed , sometimes they return BAD REQUEST , which makes a mess in my application. Is there any iis setting or something that I must write to make sure that it returns statusText as supposed? this is my code for changing it in WCF:
//Set the http status code
currentContext.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest;
//set the msg
currentContext.OutgoingResponse.StatusDescription = "Success";

I am using jQuery 1.4.2 and WCF 4.0

A: Some platforms do not accept custom status description texts - that depends on the browser, the OS, and likely some other factor (I know that Safari on Macs don't). Just don't do that. The HTTP RFC specifies what each status code means (so those platforms may take advantage of that and skip parsing the rest of the first line of the response header). If you really need to convey some additional information, try using some custom response header:
currentContext.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
currentContext.OutgoingResponse.Headers["X-Status"] = "Success";