get attribute object without using isolated scope angularjs custom directive

Question: let say that I have this custom directive

    <select ng-model="selectBox">
         <option value="test">test</option>
    </select>

    <my-directive select="selectBox"></my-directive>

myApp.directive('myDirective', function () {
    return {
        restrict:'EA',
        function (scope, element, attr) {
           var atrib = scope.$eval(attr.select)

           console.log(atrib);
    }
   }
});

whenever I execute the console.log command it returned with undefined value. I heard about isolated scope. But for this environment I don't want to use isolated scope..
the question is how can I achieve these ?
UPDATE
I update the question based on @dfsq answer but it still got nothing
UPDATE
apparently if I wrapped the attr.select using scope.$eval and change the attribute from {{}} which is object wrapping I use string only it will work! thank you so much for your answer guys!
Comment: Please see my new answer.
Answer: Not sure how you even get any console log output. It's not possible with the way you are defining your directive. You are using directive as an element, however its definition states it to be used as an attribute. Change it to this:
myApp.directive('myDirective', function() {
    return {
        restrict: 'E',
        link: function(scope, element, attr) {
            var atrib = attr.select;
            console.log(atrib);
        }
    }
});

Again, you need to declare resrict property as E "element". If you omit it (happens if you just provide a link function) it's A "attribute" be default.
Comment: Yes, you have to use `$eval` if you don't want to use isolated scope. Otherwise the solution would be cleaner, as provided by @Artyom Pranovich.
Comment: yap I update the codes but it still gives me nothing, could you give me another answer based on my question ? @dfsq
Comment: It gets you nothing, because `$scope.selectBox` is undefined. You want your directive to console.log every time you update a `selectBox` model?
Comment: @user3860691 Glad to help. Feel free to accept the answer if helped you.
Answer: If you want to see new value in your console after every option change in select, you can do it by the following way.

    <select ng-model="selectBox" ng-options="item for item in items"></select>
    <my-directive select="{{selectBox}}"></my-directive>

JS code:
myApp.directive('myDirective', function () {
    return {
        restrict:'E',
        scope: {
            select: '@select'
        },
        link: function (scope, element, attr) {
           scope.$watch('select', function(newValue){
               console.log(attr.select); //changed every time after a new select
           });
    }
   }
});

function MyCtrl($scope) {
    $scope.items = ['test1', 'test2', 'test3'];
    $scope.selectBox = $scope.items[0]; //default select's value
}

I've attached JSFiddle example for you.
Comment: thanks a lot for your response, but I solved it using scope.$eval(attr) ! @artyom
Comment: This is a proper way to handle it. However for some reason OP doesn't want to use isolated scope.
Comment: @user3860691 I'm not sure, that using of '$eval' in this case is a good idea. Just enough to use a '$watch'
Comment: Yes, $watch is enough if you use `select: '@select'`.
Comment: well now that you mentioned it I'm wondering what is the difference between $watch and $eval ? @ArtyomPranovich
Comment: Interestin question. I don't think $watch evaluates expression directly. Need to look at implementation though.
Comment: @user3860691, $eval don't evaluate JavaScript code, it evaluate AngularJS expressions between {{ }} braces. If you don't use the $eval function in the 'dfsq' plunker, so attr.select returns just the name of model: it will be 'selectBox' (because you don't evaluate angular expression).
Comment: @user3860691 about $watch you should to look through this post: http://stackoverflow.com/questions/15112584/using-scope-watch-and-scope-apply


Finite pushforward commute with taking cohomology

Question: Let $f: X \to Y$ be a finite morphism of schemes. How one can show that $f_*H^i(G) \cong H^i(f_* G)$ for any $G \in D(X)$ and any $i \in \mathbb{Z}$? In english, $G$ is a complex of quasi-coherent sheaves on $X$, $H^i$ means taking cohomology of this complex (but not hypercohomology!)
Answer: Since $f$ is finite, $f_*$ is exact. (This is more or less exercise III.8.2 in Hartshorne -- namely $R^1f_* = 0$. More generally, this property is true for affine morphisms.)
Taking (co)homology of a complex commutes with exact functors since cohomology is computed using kernels and cokernels (which exact functors preserve).
Comment: Subtle point that many people forget: $f_*$ is only exact on $\operatorname{Qcoh}(X)$. Thus, you need to have a resolution by injective *quasicoherent* sheaves (or, by Hartshorne Cor III.8.3 and Prop III.1.2A, by flasque quasicoherent sheaves). See [this answer](http://mathoverflow.net/a/27330/82179) for background and elimination of Noetherian hypotheses.


Solving a simple second order ODE with initial condition

Question: Okay i've been at it for far too long now. It comes from a bigger question from working with a PDE. I did seperation of variables and now I am stuck near the end of the problem. Here is the ODE in question
$$ \Phi''(y)= \lambda^2\cdot\Phi(y)$$ with the following initial condition
$$ \Phi'(H)=0$$ where $H$ is a positive number. Also I know $\displaystyle \lambda = \frac{n\pi}{L} >0$. There is another condition but I dont think it can help
$$ \Phi(0) = \begin{cases} 0  & x > L/2  \\ 1 & x < L/2 \end{cases}$$
sorry, i dont know how to do cases in latex and yes, that is an $x$ in the initial condition. Like i said this is a bigger problem that has both x and y.
The solution should be $$\Phi(y) = B \cdot \cosh{(\lambda(H-y))}$$
I've tried going through the following general solutions
$$\Phi(y) = Ae^{\lambda y} + B e^{-\lambda y}$$ and
$$\Phi(y) = A \sinh{\lambda y} + B \cosh{\lambda y}$$
but no luck that way :(
Answer: The forms $Ae^{\lambda y} + Be^{-\lambda y}$ and $D \cosh(\lambda(C - y))$ are really different ways of writing the same thing. For
$$Ae^{\lambda y} + Be^{-\lambda y} = \sqrt{AB} ( \sqrt{A \over B} e^{\lambda y} + \sqrt{B \over A} e^{-\lambda y})$$
$$ = \sqrt{AB} ({ e^{\lambda y + {1 \over 2}\ln({A \over B})} + e^{-\lambda y - {1 \over 2}\ln({A \over B})}})$$
Letting $C = -{1 \over 2\lambda}\ln{A \over B}$, this becomes
$$\sqrt{AB} ( e^{\lambda y - \lambda C}+ e^{-\lambda y + \lambda C})$$
$$=2\sqrt{AB} \cosh(\lambda(y - C)) = 2\sqrt{AB} \cosh(\lambda(C - y)) $$
Thus letting $D = 2\sqrt{AB}$ you get the other form. Plug in your initial condition to show $C = H$.
Comment: thankyou. is there another way to do this?
Comment: you could just keep the solution in the form $Ae^{\lambda y} + Be^{-\lambda y}$. Your initial condition will give $A$ in terms of $B$ so your solutions will be $B \times$ function, which will also be correct although written a different way.
Comment: Do you have a A in terms of B so I can compare my answer? I got $A = B e^{H\lambda}$
Comment: I think it's $A = Be^{-2H\lambda}$.
Answer: It is probably easiest just to remember as a general fact that
$$f(x)=\begin{cases}A\cosh(\lambda(x-H)) & A, H\in\mathbb R\\
A\sinh(\lambda(x-H)) & A, H\in\mathbb R\\
e^{\lambda(x-H)} & H\in\mathbb R\\
e^{-\lambda(x-H)} & H\in\mathbb R\end{cases}$$
are a complete set of solutions to $f''=\lambda^2f$ in general. To remember that they are solutions, just note that since the ODE does not mention the independent variable we can slide any known solution to the left and right. Proving them complete is slightly more involved -- one strategy would be to show that together they cover all possible pairs of $f(0), f'(0)$, by case analysis on their logarithmic derivatives.
Then, since you're already given a $H$ such that $f'(H)=0$ you can immediately see that it must be of the form $A\cosh(x-H)$ for some $A$, since the other forms have no stationary points. Finding $A$ such that your condition for $\Phi(0)$ holds is then a simple matter of scaling.
Comment: What does it mean by " since the ODE does not mention the independent variable we can slide any known solution to the left and right."
Also, what does it mean by saying the other forms have no stationary points
Comment: The ODE is $\frac{d^2y}{dx^2}=\lambda^2 y$, and it doesn't mention $x$, only _differences_ in $x$. So if you add or subtract a constant from all $x$s (thereby moving its graph to the left or right), it cannot make a solution into a nonsolution or vice versa. -- A stationary point of a function $f$ is an $x$ such that $f'(x)=0$ There are clearly no such points for $\sinh$ or the pure exponential forms.
Comment: Thankyou. To be honest I still dont understand the "differences" part but I'll do some more research on my own now that I know what it is. Also would $x=0$ be considered a stationary point or are zeros not considered a stationary point.
Comment: The differences point is simply that $x\mapsto f(x)$ is a solution if and only of $x\mapsto f(x+c)$ is a solution. $x=0$ is a [stationary point](http://en.wikipedia.org/wiki/Stationary_point) if and only if $f'(0)=0$. It's not a deep concept -- I could just as well have said "... since $f'(x)$ is always nonzero for the other forms".
Comment: Also what does it mean by having $A, H \in \mathbb{R}$
Comment: Also in my usual cases when I solve by seperation of variables I usually get a nice answer such as $f(y) = A cosh(\lambda y)$ Is there scaling there too (just the scaling is 0?). Also is there a wiki article I can read to find out more about the solutions?
Comment: The $A,H\in\mathbb R$ are just an attempt to indicate that that each choice of $A$ and $H$ will give rise to a different solution. -- In $f(y)=A\cosh(\lambda y)$, the $A$ is a scaling factor. (Are you confusing scaling with translation?)


Getting Empty response while fetching JSON data

Question: When I try to fetch JSON data from a website I can see the data in my browser but when i try to do the same through programing i get empty response http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1 this is the url i am trying to fetch i get empty response in my App where as just changing the value in the url string from 1113 to 1416 the JSON data is properly seen.
 Below is my code
protected Void doInBackground(Void... params) {
String matchesUrl = "http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1"
            data = new ArrayList<ListGroup>();
            HttpHandler sh = new HttpHandler();
            String jsonStr = sh.makeServiceCall(matchesUrl);
            Log.e(TAG, "Response from url: " + jsonStr);
            if (jsonStr != null||jsonStr !="") {
                data = jsonExtractor.extractJson(jsonStr);
            }else{
                Log.e(TAG, "Response from url: null");
            }
            return null;
        }

HttpHandler class:
public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

Response from URL:http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1 inside the app
E/FootBallMainFragment: Json Data is downloading
06-06 16:06:03.420 23817-24720/com.dotsyndicate.al_islah I/System.out: *** url=http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1
06-06 16:06:03.420 23817-24720/com.dotsyndicate.al_islah I/System.out: [CDS]rx timeout:0
06-06 16:06:03.421 23817-24720/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest>>
06-06 16:06:03.421 23817-24720/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest<<
06-06 16:06:03.851 23817-24720/com.dotsyndicate.al_islah E/FootBallMainFragment: Response from url:
06-06 16:06:03.870 23817-23817/com.dotsyndicate.al_islah D/ColorDrawable: Color = -1118482, canvas = android.view.GLES20RecordingCanvas@4422f0f, mTintMode = SRC_IN, mTint = null, ColorDrawable = android.graphics.drawable.ColorDrawable@36589616
06-06 16:06:03.871 23817-23817/com.dotsyndicate.al_islah D/ColorDrawable: Color = -13619152, canvas = android.view.GLES20RecordingCanvas@c76cb97, mTintMode = SRC_IN, mTint = null, ColorDrawable = android.graphics.drawable.ColorDrawable@17401d0b

Response from URL:http://dotsyndicate.com/unionsports/procedure.php?gc=fb1416&getMatches=1 inside the app
E/FootBallMainFragment: Json Data is downloading
06-06 16:04:55.988 23817-24044/com.dotsyndicate.al_islah I/System.out: *** url=http://dotsyndicate.com/unionsports/procedure.php?gc=fb17&getMatches=1
06-06 16:04:55.994 23817-24044/com.dotsyndicate.al_islah I/System.out: [CDS]rx timeout:0
06-06 16:04:55.996 23817-24044/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest>>
06-06 16:04:55.999 23817-24044/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest<<
06-06 16:04:56.386 23817-24044/com.dotsyndicate.al_islah E/FootBallMainFragment: Response from url: {"2017-06-08":{"11|2:1|4:1|0":"REAL MADRID|ZERU|23:30|0|0","12|6:2|8:2|0":"AL AHLY|JUVENTUS|23:55|0|0"},"2017-06-07":{"9|1:1|3:1|0":"ATHLETICO|JEMTEM|23:30|0|0","10|5:2|7:2|0":"PREDATORS|JB|23:55|0|0"},"2017-06-06":{"8|6:2|7:2|0":"AL AHLY|JB|23:55|0|0","7|2:1|3:1|0":"REAL MADRID|JEMTEM|23:30|0|0"},"2017-06-01":{"6|8:2|5:2|0":"JUVENTUS|PREDATORS|23:55|0|0","5|4:1|1:1|0":"ZERU|ATHLETICO|23:30|0|0"},"2017-05-31":{"4|7:2|8:2|0":"JB|JUVENTUS|23:55|0|0","3|3:1|4:1|0":"JEMTEM|ZERU|23:30|0|0"},"2017-05-30":{"2|5:2|6:2|0":"PREDATORS|AL AHLY|23:55|0|0","1|1:1|2:1|0":"ATHLETICO|REAL MADRID|23:30|0|0"}}

Its bit confusing as both the url are responding correctly but only one works inside the App. Can't figure out why is it so
Comment: let me tell you something, that json is awful, you should ask for a better formatted json response to make your life easier.
Comment: It is just a 2D array encode in json format never the less  the only problem is am unable to figure out why my app doesnot recognize response from the first url @JonathanAste
Answer:
I think Problem is in reading data at below statement.

while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }

you are appending '\n' in every line...i didn't understand the use of this, you should try after removing .append('\n') from here.
Comment: No changes, still gets response from url empty
Answer: Finally figured out the problem.
Issue is from the server side. At the time requesting from the user using HttpURLConnection, it sends null useragent and thats the reason server is not responding correctly.
just by adding custom useragent after initializing HttpURLConnection solves the issue.
conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.71");


Taylor series $\frac{z^2+z}{(z-1)^2}$ at $z=-1$

Question: Taylor series expansion for $\frac{z^2+z}{(z-1)^2}$ at $z=-1$.
Also find its radius of convergence.
One way is to expand with the general formula and calculate derivative of all orders but that is very tedious. Is there a way to find the series without calculating every term?
Here's the answer from WA if it helps:
$-\frac14(z + 1) + \frac1{16} (z + 1)^3 + \frac1{16} (z + 1)^4 +\frac3{64} (z + 1)^5 + \frac1{32} (z + 1)^6 + O((z + 1)^7)
$
Comment: Perhaps [this](https://www.wolframalpha.com/input/?i=taylor+series+(z2%2Bz)%2F((z%E2%88%921)%5E2)+about+z%3D%E2%88%921) will be helpful.
Comment: Yes, it gave an answer to check if we did right but how to find the series without WA?
Answer: Note that\begin{align}\frac{x^2+x}{(x-1)^2}&=\frac{x^2+x-2}{(x-1)^2}+\frac2{(x-1)^2}\\&=\frac{(x-1)(x+2)}{(x-1)^2}+2\left(\frac1{1-x}\right)'\\&=1-3\frac1{1-x}+2\left(\frac1{1-x}\right)'.\end{align}Now, compute the Taylor series of $\frac3{1-x}$ and of its derivative centered around $-1$. For that, use the fact that $1-x=2-(x+1)$.
Answer: Hint:
Set $u=z+1$, i.e. $z=u-1$, and rewrite the fraction:
$$ \frac{z^2+z}{(z-1)^2}=\frac{u^2-u}{(u-2)^2}=1+\frac{3u-4}{(u-2)^2}= 1+\frac14\frac{3u-4}{(\frac u 2-1)^2}= 1+\frac14\frac{6(\frac u2-1)-1}{(\frac u 2-1)^2}, $$
so, setting $t=\frac u2$, we ultimately obtain
\begin{align}
\frac{z^2+z}{(z-1)^2}&=1+\frac32\frac{(\frac u2-1)}{(\frac u 2-1)^2}-\frac 14\frac1{(\frac u 2-1)^2}
= 1-\frac32\frac{1}{1-t}-\frac14\frac1{(1-t)^2} \\[1ex]
&= 1-\frac32\frac{1}{1-t}+\frac14\biggl(\frac1{1-t}\biggr)^{\negmedspace\prime}.
\end{align}
Now expand with the standard formula, and replace $t$ with $\;\frac12(z+1)$.
Answer: The brute force strategy is pretty straight-forward: Find the series for $\frac1{z-1} = \frac{1}{(z+1)-2}$, square it, and finally multiply by $z^2 + z = (z+1)^2 - (z+1)$.
For simplicity, I will set $x = z+1$ and expand about $x = 0$ so I can actually see what's going on.
So, without further ado:
$$
\frac{1}{x-2} = -\frac12\cdot\frac{1}{1-\frac x2} = -\frac12\left(1+\frac12 x +\frac14x^2 + \frac18x^3 + \cdots \right)
$$
Squaring this yields
$$
\frac{1}{(x-2)^2} = \frac14\left(1 + \frac 22x + \frac34x^2 + \frac48x^3 + \cdots\right)
$$
(where I've kept the fractions unsimplified to make the pattern stand out more).
Finally, we multiply this by $x^2 - x$ to get
$$
\frac{x^2 - x}{(x-2)^2} = -\frac14x + \frac14\left(1 - \frac 22\right)x^2 + \frac14\left(\frac22 - \frac34\right)x^3 + \frac14\left(\frac34 - \frac48\right)x^4 + \cdots
$$
Reinserting $x = z+1$ gives the result you're after.
Edit: I just realized I haven't addressed the second part of the question: the radius of convergence. The radius of convergence is equal to the distance to the nearest singularity of the function. That happens at $z=1$, obviously, so the radius of convergence is $2$.


Como simplificar a chamada de tradução no i18n?

Question: Veja este exemplo abaixo de uma tradução faltando:
{
  "errors": [
    "Email translation missing: pt-BR.activerecord.errors.models.artemis/user.attributes.email.taken"
  ]
}

Para resolver essa tradução devo seguir exatamente a estrutura gerada acima:
activerecord:
  errors:
    models:
      artemis/user:
        attributes:
          cpf:
            taken: 'Aqui vem a tradução'

Minha duvida está se existe uma forma mais automatizada e simples para simplificar essa tradução? Veja abaixo:
errors:
  messages:
    cpf: 'Aqui vem a tradução'

Sei que posso colocar a frente da validação algo como message: I18n.t('errors.messages.cpf'), mas ter que fazer essa inserção em toda validação iria deixar o código bem poluído.
Answer: Como o ActiveRecord é quem valida ele já tem sua hierarquia de chamada no arquivo do I18n, ou seja deve-se seguir sua convenção, como você já demonstrou em sua pergunta. Para mudar esse comportamento você teria que sobrescrever isso no ActiveRecord.
Answer: Exatamente como o Luiz comentou, esta regra de nomenclatura é convenção do Rails.
Existe uma forma, que seria criar um validate no model chamando uma função, e adicionar um erro "customizado" pro erro acontecido.
Ex:
validates_presence_of :email, :message => "mensagem de erro com outra tradução"

Ou também, daria para criar um validade no model, da seguinte forma:
class MeuModel < ActiveRecord::Base
   validate :email

   def parent_released
     errors.add(:email, "mensagem de erro com outra tradução") if
     deu_erro?
   end
end

Como solução para facilitar o gerenciamento de traduções, existe uma ferramenta chamada "Localeapp", https://www.localeapp.com...
Com esta GEM https://github.com/Locale/localeapp voce consegue baixar as traduções criadas facilmente para o seu projeto.
Espero que ajude! Abraço!
Answer: Você pode colocar este arquivo: https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/pt-BR.yml na pasta config/locales/
Depois adicionar esta linha no arquivo config/application.rb:
config.i18n.default_locale = :'pt-BR'


How do I post data onto a website with Postman?

Question: For my internship I am required to create a database that gathers data from Shopify API and UpKeep API and display information about a customer.
We use Postman to GET data from these sources. However I need some direction when it comes to displaying the data on the localhost. We'll be using Next.JS AND tailwind CSS. Now I know nothing about these in particular.
I am really worried and have begun doing tutorials, but everything is so new to me and I don't want to end up wasting time just researching... Does anyone have any guides online that can give me some guidance for this process?
Answer: Postman is more the tool for testing in your scenario I believe. Postman can be used to call the APIs to send and receive data.  However, Postman is basically just doing that.  To show the data on a website, you need to do the same calls you are doing with Postman, via the code on the website and display the results.
If you are using Next, then follow there tutorials.
With the basic application built, you likely then need to follow the API routes to call the external source, retrieve data and display it.
Comment: Thank you so much. I really thought Postman was a way to display the data haha


Give Role Permission to 1 Admin Configuration area?

Question: Is there a simple way to give access to 1 panel of options within Administration Configuration? I made a custom module with settings under /admin/config/mymodule and it shows up as a block with links in the admin config area.
But I cant see how to easily say Role X can access that -- without giving global access admin configuration in Permissions, which lets them see everything there :(.
My example hook_menu is:
function predeparture_menu() {
  $items = array();
  $items['admin/config/eap-predeparture'] = array(
    'title' => 'Manage Site',
    'description' => 'upload the valid predeparture csv file from this page.',
    'position' => 'left',
    'weight' => -100,
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('administer site configuration'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
  );
  // Need at least one child item before your section will appear.
  $items['admin/config/eap-predeparture/list'] = array(
    'title' => 'Student Predeparture List',
    'description' => 'Upload, Revise or Rebuild the student perm list to administer access to the predeparture survey.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('predeparture_csv_admin_form'),
    'access arguments' => array('administer site configuration'),
    'weight' => 10,
  );
  $items['admin/config/eap-predeparture/incomplete'] = array(
    'title' => 'Not Yet Completed Orientation Report',
    'description' => 'These students have not completed the Predeparture survey based on those in the CSV file.',
    'page callback' => 'predeparture_incomplete_listing',
    'access arguments' => array('administer site configuration'),
    'weight' => 20,
  );
  return $items;
}

Answer: you can write your own "access callback" function returning TRUE just if the current user have the role you choose. Something like this:
function predeparture_menu() {
  $items = array();
  $items['admin/config/eap-predeparture'] = array(
    'title' => 'Manage Site',
    'description' => 'upload the valid predeparture csv file from this page.',
    'position' => 'left',
    'weight' => -100,
    'page callback' => 'system_admin_menu_block_page',
    'access callback' => 'my_access_callback',
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
  );

function my_access_callback() {
  global $user;
  return in_array('the role', $user->roles);
}

Answer: Create your own permission in your module
function predeparture_permission() {
  return array(
    'administer my module' => array(
      'title' => t('Administer my module'),
      'description' => t('Perform administration tasks for my module.'),
    ),
  );
}

Then your menu item should have
'access arguments' => array('administer my module')

And check this permission for the role you want in the permissions page: admin/people/permissions
Comment: [Custom Permissions](https://drupal.org/project/config_perms) can maybe help you
Comment: I used this solution to enable access. But they cant see the menu path in like the Admin Menu or anywhere -- they have to goto the URL directly. Any idea how to see the `Admin Configuration` but dissallow all modules that aren't my own for X role ? .... wizardy in `hook_menu_alter` ?
Comment: you could create a custom link to access directly to this page
Comment: thanks. `Custom Permissions` looks like what I've been looking for -- your general solution is still great.


print(..., end=' ') with immediate output

Question: I need a piece of Python code that loads (stresses?) CPU for a short moment. I would also like to get some output like counter printed during stressing CPU. Seems simple enough:
N=32

def fib(n):
    if n < 2:
        return 1
    else:
        return fib(n-1) + fib(n-2)

def main(num):
    for i in range(1, num+1):
        fib(N)
        print(i, end=' ')

if __name__ == '__main__':
    main(10)

However, when I use print(i, end=' '), it does not output counter as it executes, it only outputs 1 2 3 4 5 6 7 8 9 10 once it completes.
If I use regular print (print(i)) it prints the counter as it goes.
First of all, I want to know why this weird effect takes place, and second, how to make print with end behave in this regard like print without end keyword.
Answer: The print operation is buffered by default, but you can force it to flush the buffer and print immediately. See the Python documentation for more info.
print("foobar", flush=True)


Problemas (VRaptor + Hibernate request)

Question: Estou utilizando o Vraptor para desenvolver uma aplicação web. Mais em determinados testes, vi que o Hibernate está adicionando na base de dados, mas quando eu envio o Result para a minha pagina com uma nova lista daquele objeto que deletei do meu cliente, aparentemente ele está trazendo algo do cache. Na base meu cliente está com 3 itens e o Hibernate traz só os antigos 2.
Coloquei o Dao como @RequestScoped, justamente para não ter problemas deste tipo. Como Resolvo esse problema?
Código do dao:
public class DaoMaster {
private EntityManager manager;

@Inject
public DaoMaster(EntityManager manager) {
    this.manager = manager;
}

public DaoMaster() {
}

public void cria(Object o){
    manager.getTransaction().begin();
    manager.persist(o);
    manager.getTransaction().commit();
}

public void atualiza(Object o){
    manager.getTransaction().begin();
    manager.merge(o);
    manager.getTransaction().commit();

}

public void remove(Long id, Class<?> classe){
    Object o = buscaPorId(id, classe);
    manager.getTransaction().begin();
    manager.remove(o);
    manager.getTransaction().commit();
}

public Object buscaPorId(Long id,Class<?> classe){
    try{
        return manager.find(classe, id);
    }catch(Exception e){
        return null;
    }
}

public List<?> listaTodos(Class<?> classe){
    try{
        return manager.createQuery("select t from "+ classe.getSimpleName() +" t",classe).getResultList();
    }catch(Exception e){
        System.out.println("ERRO: "+e);
        return null;
    }
}

public List<?> listaPorQueryModificada(String queryModificada, HashMap<String, Object> parametros, Class<?> classe){
    try{
        TypedQuery<?> query = manager.createQuery(queryModificada,classe);
        if(parametros != null && parametros.size() > 0){
            for(String key: parametros.keySet()){
                Object value = parametros.get(key);
                query.setParameter(key, value);
            }
        }
        return query.getResultList();
    }catch(Exception e){
        System.out.println("ERRO: "+e);
        return null;
    }
}

public List<?> listaPorNamedQuery(String namedQuery, HashMap<String, Object> parametros,Class<?> classe){
    try{
        TypedQuery<?> query = manager.createNamedQuery(namedQuery,classe);
        if(parametros != null && parametros.size() > 0){
            for(String key: parametros.keySet()){
                Object value = parametros.get(key);
                query.setParameter(key, value);
            }
        }
        return query.getResultList();
    }catch(Exception e){
        System.out.println("ERRO: "+e);
        return null;
    }
}

public Object buscaPorNamedQuery(String namedQuery,HashMap<String, Object> parametros,Class<?> classe){
    Object objeto;
    try{
        TypedQuery<?> query = manager.createNamedQuery(namedQuery,classe);
        if(parametros != null && parametros.size() > 0){
            for(String key: parametros.keySet()){
                Object value = parametros.get(key);
                query.setParameter(key, value);
            }
        }
        return query.getSingleResult();
    }catch(Exception e){
        System.out.println("ERRO: "+e);
        return null;
    }
}

}
--Detalhamento--
Tenho uma tela que faço cadastro de subCategorias, ao cadastrar um novo item, chamo uma função com o Vraptor para adicionar, e no final mando ele redirecionar para a minha outra funcão que faz a chamada da tela. Na função da chamada da tela, listo todas as subCategorias com o hibernate e mando para o result, para poder mostrar na tela do usuário.
Só que tem vez que quando faço um cadastro de um novo item, a aplicação cadastra esse item na base, e quando vai para a funcão de chamar a tela novamente para fazer a nova pesquisa de todas as subCategorias existentes, parece que o hibernate está trazendo a antiga pesquisa da chamada anterior, onde não existia ainda aquele novo item que acabei de cadastrar, fazendo que o novo item não exista na tela.
Código das chamadas para o Vraptor:
@Admin
public void listaSubCategoria(Long categoriaID){

    List<SubCategoria> subCategorias = subCategoriaDao.listaPorCategoria(categoriaID);
    result.include("categoria",categoriaDao.buscaPorId(categoriaID));
    result.include("subCategorias", subCategorias);
    result.include("pagina", "categoria");
}

@Admin
public void adicionaSubCategoria(SubCategoria subCategoria, UploadedFile imagem){
    /*VERIFICAR SE JÁ EXISTE UMA SUB CATEGORIA COM O MESMO NOME PARA NÃO DAR ERRO*/
    //subCategoriaDao.adiciona(subCategoria,imagem);
    if(subCategoria.getId() != null){
        daoMaster.atualiza(subCategoria);
    }else{
        subCategoria.setCategoria((Categoria) daoMaster.buscaPorId(subCategoria.getCategoria().getId(), Categoria.class));
        daoMaster.cria(subCategoria);
    }

    adicionaImagem(NomenclaturaArquivo._NOMENCLATURA_IMAGEM_CATEGORIA, imagem, subCategoria.getId());

    result.redirectTo(this).listaSubCategoria(subCategoria.getCategoria().getId());
}

Comment: não sei se pode ser isso pois nunca utilizei esse plugin, eu já tive um problema semelhante e resolvi comitando minhas consultas.
Comment: Você está comitando todas as operações de banco?
Comment: Você disse que está deletando, e que na base tem 3 clientes, porque então são 2 registros antigos? Não era pra ser 4?
Comment: Para não ter problemas com interceptadores, todos os processos do dao, passa pelo `manager.getTransaction().begin();` e `manager.getTransaction().commit();`, as informações mesmo não vindo para a tela atualizadas, estão cadastradas no banco, sem nenhum problema.
Comment: Coloca seu código na postagem e tente exemplificar um pouco melhor o que está acontecendo.
Comment: Tente comitar as consultas também. Coloque um sysout pra exibir a lista e veja se ela traz os dados certos.
Comment: Fiz o teste, e novamente o hibernate cadastrou correto na base, mais quando mostra na tela, não trouxe a nova informação. Fiz o print de todos antes de adicionar a lista na tela, e também não consta na lista da função. Se eu reiniciar o tomcat da aplicação o mesmo vai aparecer.
Comment: Esqueci e mencionar, não sei se pode ser alguma configuração que falta, mais estou utilizando o plugin da JPA no vraptor. Não gero meus Entity Manager com classes minhas.
Comment: Você diz, chamando o begin da transação no início e o commit no fim, também nas funções de consulta?
Comment: Isso mesmo @Kelvin
Comment: @Techies fiz os testes, e aparentemente o problema realmente se resolve. Não sei realmente se vai resolver completamente com este pequeno teste que fiz, mais para esta simulação de erro que eu estava fazendo, resolveu. Muito obrigado pela sua ajuda! Agradeço por ter dado atenção para meu problema.  Obrigado.
Comment: Por nada, se o problema foi resolvido eu irei colocar uma resposta pra poder ajudar outras pessoas com o mesmo problema
Comment: @Techies Fiz os testes gerais nas outras telas do sistema, e nenhuma apresentou mais o problema. Posso dizer que sim, foi resolvido. Minhas consultas não estavam abrindo as novas transações e fechando no final.
Comment: Tranquilo, coloquei uma resposta, se ela te atende é só marcar como solução.
Answer: Analisando seu código vi que você não está dando commit nas suas consultas. O commit basicamente encerra a transação salvando todas as mudanças que ocorreram durante a transação.
É recomendado utilizar commit em todas as operações que envolvam banco, até nas consultas. Ficaria parecido com isso:
public Object buscaPorId(Long id,Class<?> classe){
    try{
        manager.getTransaction().begin();
        return manager.find(classe, id);
        manager.getTransaction().commit();
    }catch(Exception e){
        return null;
    }
}

Problemas (VRaptor + Hibernate request)


Can You Use HOOK_node_builder() to Set Custom Node ID?

Question: Drupal 8.x
How do you set the node id in HOOK_node_builder()? Is it even possible?
There is a similar question here: Specifying a custom node id when creating new content, however it is a different approach or need.
MYMODULE.module:
function MYMODULE_node_builder($entity_type, NodeInterface $node, $form, FormStateInterface $form_state) {

    $node->setTitle('Node Title');

}

I am able to set the title fine. I am hard pressed to find any docs or posts on this hook.
Answer: There is no HOOK_node_builder, here are the available hooks in the Entity API.
I think hook_ENTITY_TYPE_presave is the one you are looking for.
function MYMODULE_node_presave(\Drupal\node\NodeInterface $node) {
  $node->nid->value = 5;
  $node->enforceIsNew(TRUE);
}

Here is the order of hooks and other events that happen during an entity save:

preSave() is called on the entity object, and field objects.
hook_ENTITY_TYPE_presave()
hook_entity_presave()
Entity is saved to storage.
For updates on content entities, if there is a translation added that was not previously present:

hook_ENTITY_TYPE_translation_insert()
hook_entity_translation_insert()

For updates on content entities, if there was a translation removed:

hook_ENTITY_TYPE_translation_delete()
hook_entity_translation_delete()

postSave() is called on the entity object.
hook_ENTITY_TYPE_insert() (new) or hook_ENTITY_TYPE_update() (update)
hook_entity_insert() (new) or hook_entity_update() (update)
Comment: It's not a hook, it's a callback you can add to $form['#entity_builders'], see [EntityForm::buildEntity](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityForm.php/function/EntityForm%3A%3AbuildEntity/8.6.x)
Comment: @4k4, in this case, I think both methods work, but `hook_node_presave` is shorter/easier to implement.
Comment: @Prestosaurus, I added a short explanation and a link to the official documentation.
Comment: Do you have an idea why this hook works?


Forecasting the number of visitors in each hotel in a city

Question: I am looking for some suggestion on what a good approach would be for the following forecasting problem.
Problem statement: There are 100 hotels in a city and I have the monthly data on the total number of guests who stayed in the hotel for the past three years i.e. 36 data points for each of the 100 hotels. Using this data, I need to build a forecasting model to predict the number of visitors for the next 1 month for each hotel.
Some of questions I have are:

That hotels are competing against each other for visitors. So if the total number of visitors to a city remains roughly the same in a month then an increase in the number of visitors in one hotel should lead to a decrease in the number of visitors in another hotel. What kind of a time-series or any other model will take this into account?
In general what are some of the best practices for multi-category forecasting (in this example since we want to forecast for each, therefore each hotel can be considered as a category)
Answer: According to point 1. : The factor that is completely ignored is that the price from other (neighbouring) towns could also be relevant. From an observer's perspective, I am therefore not sure whether the number of visitors should be assumed to be fixed. A price dercrease in a hotel could attract new visitors in a city!
If the stable number of visitors is an important factor it might also be helpful to change the target variable and introduces a two step forcasting process. You could calculate the share of all visitors in a hotel per month and try to forecast it. Only market shares would be considered here. To multiply this then with the number of visitors would result in the actual desired size. However, the total number of visitors would also have to be forecast, which does not make it any easier.
You could also tackle this problem by some kind of competition feature, e.g. the relative market position of hotel x in comparison to other hotels.
According to point 2. : Why can't you just predict each hotel individually? I don't see any need to model this extra. You put the features of Hotel X for the next month into the model and get a single forecast. Could this be repeated for all hotels?
Comment: A valid point regarding prices but since we do not have this data so we will in this case limit our solution to available data. Regarding the point 2, we could build a model for each hotel if we have only a few hotels. But when you have hundreds of hotels, building a separate model for each hotel is not practical from availability and maintenance point of view.
Answer: In essence, you are trying to predict by category, along with the fact that the prediction for the next month would take into account both fixed and random effects, i.e. effects that are inherent to hotel prices themselves, and that also externally influence what you are trying to measure, e.g. time.
In this regard, your model might be best served by employing a multilevel model. This can be done using the lme4 library in R.
As a separate example, suppose we wish to determine whether school attended has a distinct effect on grade achieved by a student. In this regard, a multilevel model would model the following as such:
library(lme4)
library(mlmRev)
exam<-data.frame(Exam)
exam

lmer(normexam ~ 1 + (1 | school), data=Exam)

The output is as follows:
> lmer(normexam ~ 1 + (1 | school), data=Exam)
Linear mixed model fit by REML ['lmerMod']
Formula: normexam ~ 1 + (1 | school)
   Data: Exam
REML criterion at convergence: 11014.65
Random effects:
 Groups   Name        Std.Dev.
 school   (Intercept) 0.4142
 Residual             0.9207
Number of obs: 4059, groups:  school, 65
Fixed Effects:
(Intercept)
   -0.01325

In this case, we can see that depending on the school in question, there is a negative fixed effect present in this instance.
Suppose you are attempting to measure certain effects on hotel prices, e.g.
lmer(hotelprice ~ 1 + (1 | starrating), data=mydata)

From this, you could make a prediction by category through examining the effect of the fixed and random effects by category, or by hotel in this instance.
That said, do ensure that you have sufficient observations if each hotel is being considered a category. If not, then you might want to consider defining the category in other ways, e.g. X number of hotels with a certain star rating, a certain price range, etc.


My panel dont close

Question: im tring to makeI'm trying to make a button that closes the hack_panel but it didn't work
 public class Level1_Controller : MonoBehaviour {
 //Variables
 public Button Hack;
 public Button Develop;
 public Button Research;
 public Button SQ;
 public GameObject Hack_Panel;
 public bool isOpened;

 // Use this for initialization
 void Start () {
     isOpened = false;
     Hack.onClick.AddListener(Goto_hack);
     Develop.onClick.AddListener(Goto_develop);
     Research.onClick.AddListener(Goto_research);
     SQ.onClick.AddListener(Goto_sq);
 }

 public void Goto_hack() {
     if(isOpened == false) {
         Hack_Panel.gameObject.SetActive(true);
     } else {
         Hack_Panel.gameObject.SetActive(false);
     }

 }

 public void Goto_develop() {

 }

 public void Goto_research() {

 }

 public void Goto_sq() {

 }
 // Update is called once per frame
 void Update () {
     Goto_hack();
     Goto_develop();
     Goto_research();
     Goto_sq();
 }
}

Answer: Talvez porque você nunca atualiza a variável isOpened se o Update() roda a cada frame e ele executa o Goto_Hack(), isOpened sempre será false... Aliás não faz sentido algum você executar todos os metédos de clique a cada frame...
Considerando que o comportamento desejado é que o Hack_Panel abra e feche ao clicar no botão Hack, eu renomearia a variável isOpened para algo com mais sentido, como por exemplo showHackPanel manipularia ela no evento do botão e no Update() faria o controle de estado do Hack_Panel... veja exemplo abaixo.
 public class Level1_Controller : MonoBehaviour {
     //Variables
     public Button Hack;
     public Button Develop;
     public Button Research;
     public Button SQ;
     public GameObject Hack_Panel;
     public bool showHackPanel = false;

     // Use this for initialization
     void Start () {
         Hack.onClick.AddListener(Goto_hack);
         Develop.onClick.AddListener(Goto_develop);
         Research.onClick.AddListener(Goto_research);
         SQ.onClick.AddListener(Goto_sq);
     }

     public void Goto_hack() {
         showHackPanel =! showHackPanel;
     }

     public void Goto_develop() {

     }

     public void Goto_research() {

     }

     public void Goto_sq() {

     }

     // Update is called once per frame
     void Update () {
        Hack_Panel.gameObject.SetActive(showHackPanel);
     }
 }

Comment: obrigado leandro

My panel dont close


Add a having condition that makes use of COUNT

Question: I currently have a query that compiles to
SELECT n.nid AS nid, field_data_field_date.field_date_value AS incident_date, field_data_field_tweeted_date.field_tweeted_date_value AS tweeted_date, n.nid AS n_nid, (SELECT source.field_source_value AS field_source_value
FROM
field_data_field_sources sources
left JOIN field_data_field_source source ON source.entity_id = field_sources_value
WHERE  (sources.entity_id = n.nid)
ORDER BY sources.delta DESC
LIMIT 1 OFFSET 0) AS most_recent_source
FROM
node n
left JOIN field_data_field_incident_type incidenttype ON incidenttype.entity_id = n.nid
left JOIN field_data_field_date field_data_field_date ON field_data_field_date.entity_id = n.nid
left JOIN field_data_field_tweeted_date field_data_field_tweeted_date ON field_data_field_tweeted_date.entity_id = n.nid
WHERE  (n.type = 'incident') AND (n.status = 1) AND( (incidenttype.field_incident_type_tid IN  (9,25)) )
GROUP BY n.nid
ORDER BY field_data_field_date.field_date_value DESC

I want to add
HAVING COUNT(DISTINCT incidenttype.field_incident_type_tid) = 2

And I can get it to work in the query when I manually create it in my SQL gui, but I can't seem to add it to the query in drupal properly.
I added
$query->addExpression('HAVING COUNT(DISTINCT incidenttype.field_incident_type_tid) = 2');

But that didn't add it how I wanted to the query. The query compiled to
SELECT n.nid AS nid, HAVING COUNT(DISTINCT incidenttype.field_incident_type_tid) = 2
AS expression FROM {node} n left JOIN {field_data_field_incident_type} incidenttype ON incidenttype.entity_id = n.nid
left JOIN {field_data_field_date} field_data_field_date ON field_data_field_date.entity_id = n.nid
WHERE (n.type = :db_condition_placeholder_0) AND (n.status = :db_condition_placeholder_1) AND (n.created < :db_condition_placeholder_2) AND( (incidenttype.field_incident_type_tid
IN (:db_condition_placeholder_3, :db_condition_placeholder_4)) )
GROUP BY n.nid ORDER BY field_data_field_date.field_date_value

I'd like to have it between GROUP BY and ORDER BY since that seems to be what worked in the query I manually wrote. Also it added 'AS expression' to the end of it. Is there a way I can specifically add 'HAVING COUNT(DISTINCT incidenttype.field_incident_type_tid) = 2'? Or should I be going about it a different way?
Answer: Instead of putting everything in one expression. I was able to achieve what I needed by creating an alias for the COUNT like so
$query->addExpression('COUNT(DISTINCT incidenttype.field_incident_type_tid)','typeCount');

and then add a having Condition afterwards using the alias I created like so.
$query->addExpression('COUNT(DISTINCT incidenttype.field_incident_type_tid)','typeCount');


Sparse representation using overcomplete dictionary - when is L1 norm not good enough?

Question: I am trying to find a sparse representation of a signal consisting of a single sinusoid and a single spike (delta function), via what I think is traditionally called "basis pursuit", using $L_1$ norm minimization. Specifically, I have a discrete-time signal $y$, and I solve the following problem:
minimize    ${||x||}_1$,
s.t.        $Dx = y$
Consider the following cases that I have tried, in MATLAB, using a convex optimization package (CVX):
Case 1: Here, $y$ is a single sinusoid, and $D$ is the inverse discrete Fourier transform (IDFT) matrix. In this case, I am able to recover the DFT of $y$ (i.e., if I solve the above problem, the $x$ I get is indeed the DFT of $y$). The solution is indeed sparse, since there is only one non-zero coefficient. Everything works well here.
Case 2: Here, $y$ is the sum of the same sinusoid as that used in Case 1, and a spike/delta function. That is, somewhere in the middle, there is a spike in $y$. Thus, $y$ is no longer sparse in the Fourier domain. Some other dictionary $D$ must be chosen in the above problem in order to find a sparse $x$. The introduction of the spike brings to mind the trivial basis (kronekcer delta). However, $y$ is not sparse in this basis either, since it contains a sinusoid too. So, I tried the following overcomplete dictionary:
$D = [\Psi~ I]$
where $\Psi$ is again the IDFT matrix ($n \times n$), and $I$ is a ($n \times n$) identity matrix (where $n$ is the length of the signal $y$). In this case, $x$ would be a vector of length $2n$.
What I expected to find as the solution $x$ was a sparse solution where in the first $n$ elements of $x$ contain the DFT coefficients, and the last $n$ elements contain the delta-basis coefficients (i.e., the spike). However, this was NOT what I got.
What I got as the solution for $x$ was in fact the following: the first $n$ elements are all zero, and the last $n$ elements contain the signal $y$ itself. Thus, the optimal $x$ was not sparse at all.  At first I thought the solver was not giving me the optimal point. But I verified that this was indeed the minimum $L_1$ solution. The $L_1$ norm of $y$ (and thus, the $L_1$ of the solution $x$ I got, which contained $y$ in the second half corresponding to the delta basis) was less than the $L_1$ norm of the sparse $x$ (the one with the DFT coefficients in the first half and the time-domain spike in the second half) that I would have expected to get.
Thus, my conclusion here was that in this problem, with the specific overcomplete $D$ that I had chosen, minimizing the $L_1$ norm was not a good enough proxy for minimizng the $L_0$ norm.
I then modified $D$ a bit, by removing some of the columns at the end from the identity matrix part of it (but not the column corresponding to the spike location!). In particular, I tried the following (using some MATLAB notation):
$\tilde{D} = [\Psi~~ I(:,~1:n-p]$, where $p$ is small integer, such as 2.
I then got the sparse solution I wanted!
Here is my question finally:
What is wrong with my choice of $D = [\Psi~ I]$ (where $I$ is the full identity matrix, thus $D$ has size $n \times 2n$)? Why does $\tilde{D}$ work? Does $D$  not satisfy some properties (incoherence?) needed for $L_1$ minimization to be sufficient?
I suspect that the answer has something to with the 'incoherence' requirement, but don't quite understand that. Is this true? If so, can you explain what the requirements on $D$ are?
Thanks!
Answer: It may be the case that your columns aren't normalized. In order for basis pursuit to work, the columns need to all be roughly the same length ($\ell_2$ norm).
The columns of the inverse DFT are usually of magnitude $1/\sqrt{n}$, whereas the columns of identity matrix are of unit magnitude. So if $n$ is large, then this could prevent finding the sparse solution.
Comment: Thanks! I didn't realize the normalization requirement. I have now tried your suggestion by multiplying the identity block of $D$ by $1 / \sqrt{n}$, and seems to be working. So your suggestion seems to be very useful.


is that really caused segmentation fault (Expert C Programming 7.7)

Question: Hi  there is a example in the section 7.7 of Expert C Programming which would caused segmentation fault 。
<code>  int *p =0;
  *p =17; /*caused segmentation fault */
</code>
but i have test it as  below:
<code>#include <stdio.h>
int main()
{
        int *p =0;
        *p = 17;
        return 0;
}
</code>
when i doing gcc -c test.c it is OK and there is nothing error about segmentation fault ?
why ?
Comment: Segmentation fault is a runtime behavior. You won't see it when compiling.
Comment: [Segfaults for me](http://coliru.stacked-crooked.com/a/0bc795872e7fc761), but still, this is _undefined behavior_, it doesn't _have to_ segfault.
Comment: segmentation fault  is happen when running the program. but compile is OK
Answer: <code>*p=17;
</code>
p points to invaid memory and you are are storing a value there.
Its leading to undefined behaviour when you write to invalid memory, you are probably lucky program did not error in segment fault.
Comment: it make me confuse that  int *p = 0  is going set the pointer address as 0 not set value, and then *p=17 is going to set pointer value as 17 not set address ~~~~ although they are same format   " *pointer = value " ;
Answer: I add one more line in your program. It is core dumped. It will core dump, when you try to access the pointer variable, since you didn't allocate the memory for pointer variable p.
<code>    #include <stdio.h>
    int main()
    {
            int *p =0;
            *p = 17;
            printf("%d",*p);
            return 0;
    }
</code>
Answer: p is supposed to store the address of an integer, however, it's storing 0. Then, you are accessing address 0 and storing 17 there. 0 is likely not even a valid address so the behavior is undefined. Segfault is one of the possible outcomes.

is that really caused segmentation fault （Expert C Programming 7.7）


How to configure squid for retrieving (and caching) directly my static resources?

Question: I have an Apache/Tomcat/Spring tc Server running on CentOS EC2 VM.
I would like to install squid on the same machine as a proxy for retrieving (directly i.e. without forwarding the request to Apache/Tomcat) and caching static content ONLY identified by URIs :  /images, /css or /js.
Other URIs should be forwarded to the normal Web Server and not cached.
Since I am a newbie, I didn't find from squid documentation how to configure squid for this desired behavior (and if it is even possible).
Could you please help me and tell me how should I configure squid for this purpose?
Thank you.
Answer: By default, it will cache all static content, the predicate
hierarchy_stoplist cgi-bin ?
Is on by default, and is designed to prevent dynamic pages from being cached.
You can create an acl like the following:
acl static_content urlpath_regex ^/images
acl static_content urlpath_regex ^/css
acl static_content urlpath_regex ^/js

Then apply like this:
no_cache deny !static_content

Not tested..


Non-linear 1st order differential equation of $~x\frac{dy}{dx}+y=x\sqrt{y}~~~$where$~\sqrt{y}~$exists

Question: I think this is the first time when I handle of non-linear differential equation.
$$  \underbrace{x \frac{dy}{dx}  + y = x\sqrt{ y } }_{x > 0}   \tag{1}   $$
$$  \frac{dy}{dx} + \frac{1}{ x } y = \sqrt{ y }  $$
$$   \underbrace{\frac{d}{dx}\left(yx\right)}_{\text{LHS of eqn1} }  = x \sqrt{ y } ~~ \leftarrow~~ \text{What can I do for next?}   $$
Which website is suitable for this problem?
ADD
I got the following after I have read the post of @Gerd
$$  \frac{d}{dx}\left(yx\right) = x \sqrt{ y }   \tag{2}  $$
$$  \frac{d}{dx}\left(xy\right) = x^{\frac{1}{2} } \cdot x^{\frac{1}{2} } \sqrt{ y }  $$
$$ = \sqrt{ x } \sqrt{ xy }  $$
$$  z:=xy \tag{3}  $$
$$  \frac{  dz  }{ dx   } = \sqrt{ x }  \sqrt{ z } \tag{4}  $$
$$  \frac{  1  }{  \sqrt{ z }   } \frac{dz}{dx} = \sqrt{ x }  $$
$$  \int_{ }^{ } \frac{1}{ \sqrt{ z }  } \frac{dz}{dx}  \,dx   = \int_{ }^{ } \sqrt{ x }  \,dx    $$
$$  \int_{ }^{ } \frac{1}{ \sqrt{ z }  }  \,dz = \int_{ }^{ } x^{\frac{1}{ 2 } } \,dx     $$
$$  \int_{ }^{ } \frac{  1  }{  z^{\frac{1}{2} }  }  \,dz   = \frac{  x^{\frac{  3  }{   2 } }  }{  \frac{  3  }{  2  }   } + \text{const}_{1} $$
$$  \int_{ }^{ } z^{-1/2} \,dz = \frac{  2  }{  3  } x\sqrt{ x }  + \text{const}_{1}  $$
$$  \frac{  z^{\frac{1}{2}}  }{  \frac{1}{2}   }  = \frac{  2  }{  3  } x\sqrt{ x }  + \text{const}_{1}  $$
$$   2z^{\frac{1}{2}}  = \frac{  2  }{  3  } x\sqrt{ x }  + \text{const}_{1}  $$
$$  2 \sqrt{ z } = \frac{  2  }{  3  } x\sqrt{ x } + \text{const}_{1}  $$
$$  2 \sqrt{ yx } = \frac{  2  }{  3  } x\sqrt{ x } + \text{const}_{1}  $$
$$  2 \sqrt{ yx } - \frac{  2  }{  3  } x\sqrt{ x } = \text{const}_{1}  $$
$$  \underbrace{\sqrt{ x }  \left( 2 \sqrt{ y } - \frac{  2  }{  3  } x  \right) = \text{const}_{1} }_{\text{general solution} } ~~ \leftarrow~~ \text{Is this also correct?}   $$
Answer: For example, if you are interested in solutions on intervals $I\subseteq (0, \infty)$ write
$$
\frac{d}{dx}(xy(x)) =x \sqrt{y(x)} = \sqrt{x}\sqrt{xy(x)}.
$$
Then substitute $z(x):=xy(x)$ and solve $z'(x)=\sqrt{x}\sqrt{z(x)}$ by separation of variables (initial values $>0$ are adequate here). Then $y(x)=z(x)/x$ is a solution of the original problem.
Comment: I added the stuff to my post.
Comment: Calculations seem correct to me. Now you can resolve to $y$. However, I would not call it the general solution. If you want to solve the ode in $(-\infty,0)$ you have to set $x=\sqrt{-x}\sqrt{-x}$. Moreover $y(x)=0$ is a solution on any interval.
Answer: This is a special case of a Bernoulli differential equation, wich has a well know method of solution by transforming in a linear equation.
Answer: $$y'+\frac{y}{x} = \sqrt{y}$$
$$\frac{y'}{\sqrt{y}} +\frac{\sqrt{y}}{x} = 1$$
Using
$$z=\sqrt{y}$$
$$\frac{dz}{dx} = \frac{1}{2\sqrt{y}}\cdot y'$$
$$2\cdot\frac{dz}{dx} = \frac{y'}{\sqrt{y}}$$
Replace
$$2\cdot\frac{dz}{dx} +\frac{z}{x} = 1$$
And now you have built a linear system


For real number, Is it true that $sup\{x_i + y_i: i\in I\}=sup\{x_i:i\in I\}+sup\{x_i:i\in I\}$?

Question: If $I$ is an indexing set for real numbers so $x_i \text{and} y_i$ are reals.
Is it true that $sup\{x_i + y_i: i\in I\}=sup\{x_i:i\in I\}+sup\{x_i:i\in I\}$?
I thought I need this statement to prove an exercise but I found that I only need the statement:
$sup\{x_i + y_i: i\in I\}\le sup\{x_i:i\in I\}+sup\{x_i:i\in I\}$ which is a straightforward proof by the definition and so the exercise is done but the question whether or not the equlity holds is not answered yet.
My question is, Does the equality always hold? If yes, Could you provide a simple proof,please? if not, Why not give a counterexample and the conditions (if any) under which the equality holds please?
For me, it's intuitively true, for example consider  the special case when the sup is the maximum element.
Comment: Let $x_i $ be one on the odd numbers and zero on the even numbers. Let $y_i = 1-x_i$.
Comment: It fails even when $I$ has just two elements.
Comment: @MathsLover: I do, but I forget stuff. A bit like reading a book and realising after the first few pages that you have read this one before. I use intuition as a guide and analysis as my 'rock pro' (as in climbing, not music!).
Comment: @copper.hat, This shows how bad is my intuition! anyway, Could you provide a simple answer to close the question please?
Comment: @MathsLover: I frequently forget my intuition :-).
Comment: @copper.hat , What do you mean by that :) ? Do you mean you don't rely on your intuition?
Answer: Let $x_i$ be one when $i$ is odd and zero otherwise, let $y_i = 1-x_i$, then
$\sup_i x_i = \sup_i y_i = 1$ and $\sup_i(x_i+y_i) = 1$.
The issue is that the indices at which $x_i$ approaches its $\sup$ may be different that the indices at which $y_i$ approaches its $\sup$.


How can I change column type on rails 5

Question: I insert a column in my sqlite with a wrong type "stringimage".

How can I change the column type to string?
I tried change_column :users, :uid, :string
and
def up
  change_table :users do |t|
    t.change :uid, :stringimage
  end
end
def down
  change_table :users do |t|
    t.change :uid, :string
  end
end

but it doesn't works.
I tried many things but none of it works, maybe because I'm using rails 5.
Comment: After changing, did you run migration for the same ?
Comment: Have you consider running `rake db:migrate`
Comment: yes I runned `rake db:migrate`
Answer: You Need to write following two definitions into your migration :
def up
  change_column :my_table, :my_column, :string
end

def down
  change_column :my_table, :my_column, :stringimage
end

Comment: First you need to run `rake db:rollback` command, and then perform `rake db:migrate`
Comment: Can you please provide your last migration file content ?
Comment: You also can have this code, exactly after your class declaration :
`def change
    change_column :users, :uid, :string
  end`
Comment: I got this error: `== 20160722050406 ChangeUid: migrating
-- change_column(:users, :uid, :string)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

undefined method `to_sym' for nil:NilClass
C:/Sites/AirProject/db/migrate/20160722050406_change_uid.rb:3:in `up'
bin/rails:4:in `require'
bin/rails:4:in `'
NoMethodError: undefined method `to_sym' for nil:NilClass
C:/Sites/AirProject/db/migrate/20160722050406_change_uid.rb:3:in `up'
bin/rails:4:in `require'
bin/rails:4:in `'`
`
Comment: I got this: `== 20160722050406 ChangeUid: migrating ========
== 20160722050406 ChangeUid: migrated (0.0000s)` ... but nothing was changed on my column
Comment: This is the content of my last migration file `class ChangeUid < ActiveRecord::Migration[5.0]
  def change
 change_column :users, :uid, :string
  end
end
` ... Now i runned `rake db:migrate`, I didn´t get error, but the column type wasn't changed
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/118007/discussion-between-hardik-kanjariya--and-s-a).
Answer: Note that change_column is an irreversible migration. It will cause an error if you try to rollback. To prevent this, modify the usual change method in the migration to use two separate up and down methods like this:
class ChangeUsersUidType < ActiveRecord::Migration
  def up
    change_column :users, :uid, :string
  end

  def down
    change_column :users, :uid, :stringimage
  end
end

If you liked this answer you can read more in this article: https://kolosek.com/rails-change-database-column.
Answer: You can try this:
change_column(table_name, column_name, type, options): Changes the column to a different type using the same parameters as add_column.
Comment: I got this: `rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

undefined method `to_sym' for nil:NilClass
C:/Sites/AirProject/db/migrate/20160722050406_change_uid.rb:3:in `change'
bin/rails:4:in `require'
bin/rails:4:in `'
NoMethodError: undefined method `to_sym' for nil:NilClass
C:/Sites/AirProject/db/migrate/20160722050406_change_uid.rb:3:in `change'
bin/rails:4:in `require'
bin/rails:4:in `'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)`

How can I change column type on rails 5


How to solve "Query failed" error in drush sql-sync output 2?

Question: I have the exact same problem as in How to solve "Query failed" error in drush sql-sync output?, exact same output. That user found the answer as the password in settings.php was wrong, but my password is correct and it still doesn't work. Can anyone please help?
drush sql-query --strict=0 --file=/tmp/mob_20191203_224013.sql.gz --file-delete --uri=mob --root=/home/fc/1/de/mob/web -vvv
 [preflight] Config paths: /home/fc/1/de/mob/vendor/drush/drush/drush.yml,/home/fc/1/de/mob/drush/drush.yml
 [preflight] Alias paths: /home/fc/1/de/mob/web/drush/sites,/home/fc/1/de/mob/drush/sites
 [preflight] Commandfile search paths: /home/fc/1/de/mob/vendor/drush/drush/src,/home/fc/1/de/mob/drush
 [bootstrap] Starting bootstrap to max [0.04 sec, 8.57 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalRoot() [0.04 sec, 8.57 MB]
 [bootstrap] Change working directory to /home/fc/1/de/mob/web [0.04 sec, 8.57 MB]
 [bootstrap] Initialized Drupal 8.7.10 root directory at /home/fc/1/de/mob/web [0.04 sec, 8.76 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalSite() [0.04 sec, 9.06 MB]
 [bootstrap] Initialized Drupal site mob at sites/default [0.04 sec, 9.29 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalConfiguration() [0.04 sec, 9.29 MB]
 [debug] Add service modifier [0.04 sec, 9.45 MB]
 [info] Executing: command -v mysql [0.05 sec, 9.91 MB]
 [info] Executing: mysql --defaults-file=/tmp/drush_IsKDek --database=mob --host=localhost --silent -A < /tmp/mob_20191203_224013.sql.gz [0.05 sec, 9.96 MB]

In SqlCommands.php line 199:

  [Exception]
  Query failed.

/tmp/mob_20191203_224013.sql.gz exists, /tmp/drush_IsKDek does not
Drush is 9.7.1, Mint 19.2, alias
loc:
  root: /home/fc/1/de/mob/web
  uri: mob
  options:
    command-specific:
      sql-sync:
        sanitize: true
        structure-tables:
          common:
            - cache_advagg
            - cache_bootstrap
            - cache_config
            - cache_container
            - cache_data
            - cache_default
            - cache_discovery
            - cache_dynamic_page_cache
            - cache_entity
            - cache_menu
            - cache_page
            - cache_render
            - cache_toolbar
            - watchdog
            - history
            - sessions
    os: Linux
  paths:
    dump-dir: /tmp
    files: sites/default/files

Comment: Have you had a look at SqlCommands.php line 199?
Comment: Yes. Nothing useful.
`$result = $sql->query($query, $filename, $options['result-file']);`
$query is empty, filename is the .gz archive, resultfile empty, $result empty.
Comment: Probably better to report this one at GitHub. https://github.com/drush-ops/drush/issues
Comment: It looks like the problem is at `Executing: mysql ... < /tmp/asdf.sql.gz` I don't think mysql can unzip gz transparently. Removing the `--silent` flag and running that line directly would help with debugging, but I'm not sure how to convince drush to do that.
Answer: Same issue with Drush 10.6.x. https://github.com/drush-ops/drush/issues/4319#issuecomment-649223069 is outdated as the function has been moved elsewhere but the problem persists.
Solution is to manually set PHP CLI to a lower version, for example
sudo update-alternatives --set php /usr/bin/php7.3

Answer: At the time of writing this comment, there is a problem in drush 9 with php7.4 as mentioned here: https://github.com/drush-ops/drush/issues/4319#issuecomment-649223069
I solved it in my case (I have multiple PHP versions installed) by switching to php7.2 using this command:
sudo update-alternatives --set php /usr/bin/php7.2
I think it will work also with php7.0 and php7.1

How to solve “Query failed” error in drush sql-sync output 2?


Forcing nlme to give the results for the levels of a treatment as "absolute" values instead of contrasts

Question: I am using a nonlinear model to fit an equation to data using nlme in R.
Several values (one by treatment) are estimated for a fixed effect.
As usual, by default of nlme, the estimated values of this fixed effect
are given relative to the smallest value as contrasts.
I would like, instead, to have the results as "absolute" values of the
fixed effect for each treatment.
My question is the following: how  can I specify to nlme  that contrasts
should not be used to give the estimates of the  values of this fixed effect by  treatment.
Comment: This question appears to be off-topic because it is about how to use R without a [reproducible example](http://stackoverflow.com/q/5963269/1217536).
Comment: Correction: the default estimates are not relative to the smallest value. They are relative to the first level of the factor.
Comment: Many thanks for all answers. Sorry for not having provided the source in my question. Here it is : nlme.fit <- nlme(model = y ~ constrained.full.param.traj(a, a1, log(n0), x), data = my.data, method = "ML", fixed = list(a + a1 ~ 1, n0 ~ treat), random = a ~ 1 | pla, start = list(fixed = c(a = 13.7, a1 = 12.5, n0 = n0.start))) In nlme.fit, the smallest estimated value of n0 is given, but the other estimated values, for the rest of the treatments (treat), are given relative to this smallest value, as difference contrasts. J.-M. Ottorini
Answer: This is just about how categorical variables are coded in R and how the forumlas work.  It doesn't really have anything to do with whether the model is nonlinear or if you use a mixed model.  The easiest way to get your model returned fitted with level means coding instead of reference level coding is to suppress the intercept when you have a factor variable.  In R, this can be done with either +0 or -1.  Consider:
set.seed(123)                 # this makes the example exactly reproducible
x = runif(30, min=0, max=10)  # x is a continuous variable
g = as.factor(sample(rep(c("C","T"), 15), 30, replace=F))  # g is categorical
y = 3 + .3*x + 2*ifelse(g=="T",1,0) + rnorm(30)

## this is the typical way, which uses reference level coding:
mod.refL = lm(y~x+g)
summary(mod.refL)
# ...
# Coefficients:
#             Estimate Std. Error t value Pr(>|t|)
# (Intercept)  3.18841    0.41014   7.774 2.33e-08 ***
# x            0.28444    0.05557   5.118 2.22e-05 ***
# gT           2.15804    0.31838   6.778 2.80e-07 ***
# ...

## here I used '0' to suppress the intercept:
mod.Lmeans = lm(y~0+x+g)
summary(mod.Lmeans)
# ...
# Coefficients:
#    Estimate Std. Error t value Pr(>|t|)
# x   0.28444    0.05557   5.118 2.22e-05 ***
# gC  3.18841    0.41014   7.774 2.33e-08 ***
# gT  5.34644    0.36615  14.602 2.46e-14 ***
# ...

Answer: What you really want are predictions from the model at each treatment level. If it is just a one-factor experiment, with one covariate, do something like this:
grid <- data.frame(treat = c("t1", "t2", "t3"), covariate = c(rep(5.5,3))
predict(my.model, newdata = grid)

Of course, you should use the actual variable names and treatment levels you used. Typically, people would want to make the predictions at the mean value of each covariate.
[Earlier stuff with gung's example removed because it is linear. Also, note that his results with the second approach are predictions at x = 0, not x equal to its mean.].


raising custom events to allow web user controls to intercommunicate

Question: I have 2 web user controls, both inherit the same base class which extends UserControl. I want to raise an event on one and the other should be aware of it. both are on the same page however the 2nd control never handles the custom event i raised on the 1st one ! any ideas ? please just point to an implementation of possible (BTW, i'm googling it since morning but no luck !)
Comment: Can you show us the source code of what you have so far?
Comment: Here's a similar question (though it talks about different nested controls on the same page) http://stackoverflow.com/questions/2550283/asp-net-event-delegation-between-user-controls/2550325 You'll have to do something similar to the answer suggested to that question to attach control events together.
Comment: I have tried a lot of approaches, I will test this one !
Answer: You can easily do the following:
1) create an event in control 1.
2) create a public method in control 2, that gets called if the event in control 1 is raised
3) subscribe to the event of control 1 (where you instanciate them, e.g. another control, a content page or a master page)
4) inside the event handler from 3), call the method created in 2)
5) do the other thing around, if control 2 should communicate with control 1
This all require server-side execution. I'm sure there might be also client-side solutions.
Edit after comment:
There are only two possible communication ways I can think of:
1) the controls don't know each other and therefore can't communicate directly. => you need a third control/page/masterpage/whatever (database, service etc) to enable the communication
2) the controls reference each other and therfore can communicate directly => very bad OOP. If you use this, you do not understand OOP at all and should consider your job
Feel free to chose one of the options.
Comment: it seams that the parent page should be involved. can you recommend a solution is completely decoupled without having the parent page/control being involved in registering the custom event ?
Answer: You can Raise Events from User Controls using Delegates
Look Here for an example
Comment: it seams that the parent page should be involved. can you recommend a solution which is completely decoupled without having the parent page/control being involved in registering the custom event ?


Breadcrumbs disappear on cache clear, come back with subsequent cache clear

Question: I have a site where the breadcrumb is in different locations depending on what node type or page is being viewed.
In some places, it is interspersed with node content, so the only solution was for my colleague to inject it into the page as a variable, like so (from .theme):
$block = Block::load('breadcrumbs');
$variables['content']['breadcrumbs'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);

I've noticed that when I deploy code, the breadcrumbs disappear. I then have to clear the cache, clear Varnish, and clear the cache again and finally hard refresh in my browser to see them again.
Is this related to how breadcrumbs are being injected into the page and if so, is there a better way to do it?
Comment: What hook is that code in inside your .theme file? Also in D8 you can assign a block to more than one region... could you just put the crumbs block in both places it's required and then just hide one with css?
Comment: Depending on the page they can show up within node content area, not just a region, like in between fields. This is in hook preprocess node
Answer: In a node use the breadcrumb builder directly:
\Drupal::service('breadcrumb')->build(\Drupal::routeMatch())->toRenderable();

The node gets cached already and the cache metadata of the breadcrumbs bubbles up to the node.
In a page it's preferable to place the block in a region (can be a region of its own) and then place the variable of the region in the page template.
If you want to use code to place the block, make sure you use the block for the correct theme (you have to query the block table with the property theme for this). Now it seems like you use the breadcrumb block placed first on your site, not necessarily the one for your theme.
Comment: This helped with that particular node type, but I see it on others - updated the question with our breadcrumb build() method.
Comment: Don't think this is connected, you don't even need the cache data you provide now, if you embed the breadcrumbs in the node.
Comment: This one is actually served from the core block. I'll make a new question.


Cloning/downloading files via a python script

Question: I was wondering how to clone/download a github file or files via a python script. I cant seem to figure out how to
Answer: In addition to Maurice Meyer's method, you can do as follows:
In order to clone an entire git repository, you would use the following command line script:
git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
Taking that into account, you could have a python script which would execute this command, by using the subprocess library, such as:
import subprocess
subprocess.run(["git", "clone", "https://github.com/YOUR-USERNAME/YOUR-REPOSITORY"])


Odds of Coming Out Ahead in Roulette

Question: I have an interesting roulette problem that I initially thought was easy but now I'm second guessing my self. The problem is as follows:

A friend of yours thinks that he has devised a purely mathematical way of beating the standard European roulette wheel, which has 37 pockets. His plan is to come to the roulette table with 100 units with which to bet. On each spin, he places a one-unit, single-number bet. (Recall that winning such a bet returns 36 units to the winner.) He will make exactly 100 bets, no matter how much he wins or loses. He claims that this strategy results in a greater than 50% chance that he will come out ahead at the end of 100 spins, so using this strategy repeatedly will make him a winner.
a) Does he have a greater than 50% chance of coming away with more money than he started with?
b) If the answer to the previous question is yes, then does that make his strategy a winning one, meaning that it will lead to a long-term increase in bankroll?

So for part A I think he does have a greater than 50% chance of coming away ahead. He needs to win at least 3 times in order to walk away with more than he started with. And the probability of winning at least three times is 50.939% (I did 1 - the probability of winning 0, once, or twice with p=(1/37).)
So based on that it seems like he does have a greater than 50% chance of walking away ahead...
This goes against my intuition, especially for part b. If everyone could do this strategy and come out ahead then they would. But surely it can't be this simple... I don't see how this would lead to a long term increase in bank roll. Any thoughts?
Comment: Keep in mind:  it's easy to design games in which you win more than half the time yet your expected gain is negative. Say you are tossing a fair die and you win $\$1$ if you throw a $1,2,3,4,5$ and you lose $\$10$ if you throw a $6$.  In that game, you win five games out of six but it is still a losing game.  That's what is going on with your freind's strategy.
Comment: I really like this question and I would like to add that these pseudo arguments aren't just found in gambling settings the world over. You will find, if you pay close attention, that politicians for example are very skilled at using these and other pseudo arguments to convince their audience as well.
Comment: There are betting patterns such that a gambler has a better than 50% chance to walk away with more money than he started.  However the expected value of each wager remains negative.  The expected distribution of outcomes has a large probability of a small gain and a small probability of a very large loss.
Answer: Hint: Odds of winning aren't relevant to part b). What is relevant is the expected value. Calculate that and you will see whether it's positive (which would mean you've discovered a winning strategy) or negative.

edit: Let me add a little story to this answer which I think might be entertaining.
As a young adult I played poker rather successfully and thus spent many, many nights in casinos. It always struck me how much the casino, in a subtle but distinct fashion, encourages the suspicions and false believes of its customers. Roulette tables record the previous ~20(?) outcomes and advertise them to every bystander in big, illuminated letters (to encourage the belief that past outcomes somehow affect the likelyhood of future outcomes), slot machines have correct but irrelevant calculations printed on them (suggesting that there may be a winning strategy), you are constantly bombarded by special deals and jackpots both visually and audibly, ...
The later decision to become a mathematician, I think, has been fueled at least in part by the desire to truly understand these misleading claims.
In any way: The situation you describe here must be any casino-owner's wet dream. It's not the casino that convinced the customers of his perceived advantage -- it's the customer himself who came up with a fake recipe for his success.
Comment: Exactly. This is what every [Martingale system](https://en.wikipedia.org/wiki/Martingale_system) relies on - a high probability of winning a bit, a low but non-zero probability of losing very much more.
Comment: Hmm. that is helpful. So the expected loss per play is $. 027 and therefore after 100 plays your expected loss is $2.70. I'm still just struggling with why this is...if your odds are better than the house it seems like you should come out ahead! Maybe i just need to think about it a bit more. Feel like I am not understanding something very obvious...
Comment: @ElizaWattsSells If you are struggling to see why you should not come out ahead, take the situation to an extreme. For example, if we played a game where a diced is rolled and on a 1 you pay me £100,000 but otherwise I pay you £1. You are most likely to come out ahead, would you play? Why not?. It works a lot like this but less extreme. You are most likely to come out on top in one roll but after a few rolls I am most likely to come out with (a lot) more money
Comment: @ElizaWattsSells Richard Feynman: "The first principle is that you must not fool yourself – and you are the easiest person to fool." That quote, I think, is very important to keep in mind for any scientist. You have this calculation that doesn't prove you have a winning strategy but you _feel_ it should say exactly that. Your job is to find out whether the suggested meaning is the actual meaning of the calculation. In this case it isn't and the expected value enables you to prove just that.
Comment: @StefanMesken Thanks  - that is a great quote. Will put that one in my back pocket as I continue my studies!

Odds of Coming Out Ahead in Roulette


Why assigning to property resulting error "cannot set property of null"

Question: I am trying to assign some value to some property of object. But the console logged error ERROR TypeError: Cannot set property 'requested_date' of null. I have tried to find what is wrong but I think it's all fine.
Here is the code:
form = {
    data: null as IMediaStorageAdd,
    requester: null as string
}

The IMediaStorageAdd is an interface:
export interface IMediaStorageAdd {
    place: string;
    requested_date: any;
    temp_requested_date: any;
    details: any[];
}

and this is where i run the assignemnt:
ngOnInit() {
    this.form.requester = localStorage.getItem(`name`);
    this.form.data.requested_date = new Date();
    /* resulting error Cannot set property 'requested_date' of null */
}

Comment: @Hiteshdua1 get Item form local Stoage is working fine. Even though I comment the line, I still getting the error
Answer: Before setting the requested date, you need assign an empty object to data property of the form. Otherwise data is null and hence it is throwing the error. To fix it,
add a line before setting the requested_date as,
this.form.data = {};

Comment: Form already has both the properties.
``` form = {
    data: null as IMediaStorageAdd,
    requester: null as string
}```
Comment: He is suggesting to set it as `{}` instead of null. Then only you can add properties to it.
Comment: My bad, I am dumb ! :/ yes seems legit.
Comment: Actually, i don't understand why it should assigned by empty object first, because i have set the this.form.data with an interfae. But it's working. thank you
Answer: The answer of Sajeetharan is correct and it's working. I will try to shed some lights to clarify your doubts.
You are setting this.form.data to null and typecasting it using an interface, but still this.form.data is null and not an object.
I believe you can compile TS with --strictNullChecks to avoid this confusion in order to avoid assigning null or undefined to anything.
Anyway, in your case, I think either you initialise your form using same types as you expect:
form = {
    data: {} as IMediaStorageAdd,
    requester: '' as string
}

or you need to initialise your form data before use it:
1) If there's a class implemeting your IMediaStorageAdd interface
ngOnInit() {
    this.form.requester = localStorage.getItem(`name`);
    // where class MediaStorageAdd implements IMediaStorageAdd
    this.form.data = new MediaStorageAdd();
    // this could be done in the class MediaStorageAdd constructor actually
    this.form.data.requested_date = new Date();
}

2) If no class is implementing your IMediaStorageAdd interface, then you should define it as a type, first of all and then initialise your form data using an object literal
export type TMediaStorageAdd {
    requested_date: any;
    place?: string;
    temp_requested_date?: any;
    details?: any[];
}

form = {
    data: null as TMediaStorageAdd,
    requester: null as string
}

ngOnInit() {
    this.form.requester = localStorage.getItem(`name`);
    this.form.data = {
        requested_date = new Date();
    }
}


best practice for show News list in html5

Question: In my page i need to list last news with title only. I have two methods:
One:

Title One

Title Two

Title Three

Title .....

Title .....

Title .....

Two:

TTILE ONE

TTILE Two

TTILE THree

TTILE .....

In HTML5 which way is better and readable?! with

 Or

?!
Comment: Neither is better in terms of hot html can be read. However it is considered a list, and so your question can be answered by means of using
Answer: Neither is better in terms of how html can be read. However it is considered a list, and so your question can be answered by means of using

Answer: You have there a list of news, so the correct one is UL.
The first option, using paragraphs is bad, because... Do you thing titles are paragraphs? I think title != paragraph, so uou can't use
 tag.
Answer: Using an unordered list,
, would be more semantically correct than using a paragraph,
.
Obviously either one could be used, so semantics may feel like a 6 vs half dozen sort of thing,  but in the long run using the correct tags will make your job easier.
The
 will come with native styles, i.e. margins and so on, that will need to be removed in your css if you intend you use them this way. While
 and
 will probably only need to have bullet points accounted for.
Also not everyone experiences the web in the same way, try to keep in mind that screen readers will take markup into account when reading pages to the visually impaired.
In more extreme cases semantics can even effect your search engine optimization (SEO). Google, for instance, may grab your first paragraph and use it as a part of your site description.


Proving a non-negative measurable function is the limit of a sequence of simple functions

Question: I'm reading some notes on measure theory and am trying to understand a proof of a theorem that says:
Given a measurable function $f : \Omega \rightarrow \mathbb{R}$, there exists a sequence of isotone simple functions $(f_i)_{i \in \mathbb{N}}$ such that for each $x \in \Omega, \lim_{i\to\infty}f_i(x) = f(x)$.
The notes say they will prove this fact by proving there exists a family of sets $\{A_i\}_{i\in\mathbb{N}}$ such that $$f = \sum_{k=1}^\infty \frac{1}{k} \chi_{A_k}$$.
I understand all of the steps the proof takes after this, but I did not understand how proving such a family of sets exists proves the theorem.
Answer: A simple function $g$ is defined as
$$g(x)=\sum_{k=1}^N a_k\chi_{A_k}$$
with $A_k$ measurable. Then your can define a sequence of simple functions $g_N$ by
$$g_N(x)=\sum_{k=1}^N \frac{1}{k}\chi_{A_k},$$
i.e. basically cutting of the infinite sum. Then
$$f=\sum_{k=1}^\infty \frac{1}{k}\chi_{A_k}=\lim_{N\rightarrow\infty}\sum_{k=1}^N \frac{1}{k}\chi_{A_k}=\lim_{N\rightarrow\infty} g_N$$
Answer: Since sums of simple functions are simple, the expression $$\sum_{k=1}^\infty \frac{1}{k} \chi_{A_k}$$ is precisely a limit of simple functions.


Finding all pairs $(a,b)$ of positive integers such that $a^2+nab+b^2$ is a perfect square.

Question: When $n=2$, the question is trivial. Is there a general method to find all such pairs for $n\ge{3}$ and $n\in{\mathbb{N}}$?
Comment: Might have to investigate the norm in the number field $\Bbb Q[\sqrt{n^2-4}]$ ...
Comment: @AmagicalFishy the short version: this seems about improving a computer algorithm rather than mathematics itself. The behavior of this changes pretty violently based on $n$
Comment: Well if $a^2+nab+b^2=k^2$ then $(n-2)ab=(k-a-b)(k+a+b) $ and $(n-6)ab=(k-a+b)(k+a-b) $.  Don't know if the helps.
Comment: In other words, we are looking for triples $(a, b, c)$ of positive integers such that $a^2 + b^2 + nab = c^2$, correct?
Comment: Not really a reasonable question for arbitrary $n.$ The condition of positive integers is not especially good unless $n < 0.$ Put another way: why do you want to know this?
Comment: @WillJagy Why isn't this a reasonable question (I genuinely don't know enough about number theory that this is obvious to me)? Also, what do you mean "the condition of positive integers is not especially good unless $n < 0$. If $n < 0$, what condition of positive integers is there if $n < 0$? Also—and a bit facetiously—how is asking "why do you want to know this?" putting the other two objections in another way? It seems like a completely different question.
Comment: @WillJagy Is it not a reasonable question because there are too many variables? That is, being able to alter $n, a,$ and $b$ freely kind of make the question too mathematically vague?
Comment: @avs Yes, you are right.
Comment: @WillJagy Finding all such pairs in the case of $n=10$ will help with a problem I've been working on (please rest assured that it is NOT my homework).
Comment: @HagenvonEitzen Would you mind providing an example for a specific case (say, when $n=3$)?
Comment: Compare https://en.wikipedia.org/wiki/Eisenstein_triple
Comment: @Shu_HE:  Rather than "correct" the algebra in the posted Answer, you should probably raise your concerns with the Answer's author in Comments there.
Answer: Let $a^2+nab+b^2 = c^2$
Let $x = \dfrac ac$ and $y=\dfrac bc$.
Then we need to find rational soloutions $(x,y)$ to $x^2 + nxy + y^2 = 1$

We start with the particular solution $(x,y) = (-1,0)$ and "draw" the line
$y = \dfrac uv(x+1)$, where $u,v$ are integers, through that point. It should intersect the hyperbola $x^2 + nxy + y^2 = 1$ at a rational point.
\begin{align}
   x^2 + nxy + y^2 &= 1 \\
   x^2 + \dfrac uvnx(x+1) + \dfrac{u^2}{v^2}(x+1)^2 &= 1 \\
   x &= \dfrac{v^2-u^2}{u^2+uvn+v^2} &\text{(We discarded $x=-1$.)} \\
   y &= u\dfrac{nu+2v}{u^2+nuv+v^2}
\end{align}
We get  $a^2+nab+b^2 = c^2$ where
\begin{align}
   a &= v^2-u^2 \\
   b &= nu^2+2uv \\
   c &= u^2+nuv+v^2
\end{align}
If $(a,b)$ is a solution, then so too is $(-a,-b)$, $(b,a)$, and $(-b,-a)$. So all solutions can be characterized as
$$\{a,b\} \in \{v^2-u^2, nu^2+2uv\}, \quad c = u^2+nuv+v^2$$
Comment: stereographic projection gives all rational solutions. It is possible to take integers with $\gcd(u,v)$ yet end up with $\gcd(a,b,c) \neq 1.$ So, we get all primitive integer triples if we say to divide $a,b,c$ by $\gcd(a,b,c).$ I do not know what to say about the apparent demand for $a,b > 0,$ not really natural. Oh, to ignore the gcd bit, it is commonly necessary to use several recipes such as you give. This will depend heavily on $n$
Comment: @SchuHE The solutions of $a^2 + 6 b^2 = c^2$ quite naturally split  into recipes
$$ a = u^2 - 6 v^2, \; \; b = 2 uv, \; \; c = u^2 + 6 v^2,  $$
$$ a = 2u^2 - 3 v^2, \; \; b = 2 uv, \; \; c = 2u^2 + 3 v^2  $$ In both, $c > 0.$ In the first, $c \neq 2 \pmod 3.$ In the second, $c \neq 1 \pmod 3.$
Comment: @WillJagy Could you elaborate on what you meant by "several recipes"?
Comment: @WillJagy Thanks a lot. How did you find the different recipes (like did you use the same method except that you started with different solutions in each case), and how would you convince yourself that those recipes will cover all primitive solutions?
Comment: Is there a name for this method?
Comment: @SchuHE : It's got something to do with homogeneous coordinates and projective spaces.
Answer: Another way to approach this is to use Hilbert's theorem 90.
As in steven gregory's reply aim to solve
$$x^2+nxy+y^2=1$$
in the rationals. This is equivalent to
$$N\left(x+\frac{ny}2+\frac y2\sqrt{n^2-4}\right)=1$$
where $N$ is the norm map from $\Bbb Q(\sqrt{n^2-4})$
to $\Bbb Q$. By Hilbert 90, the norm $1$ elements of the
quadratic field are
$$\frac{u+v\sqrt{n^2-4}}{u-v\sqrt{n^2-4}}
=\frac{(u+v\sqrt{n^2-4})^2}{u^2-(n^2-4)v^2}$$
for rational $u$, $v$ not both zero. We can now grind out
general formulae for $x$ and $y$, which will be equivalent
to steven gregory's
Comment: Thanks for putting the problem and solution into a more number theoretic framework.
Answer: Generally speaking, this equation has a lot of formulas for the solution. Because it is symmetrical.
Write the formula can someone come in handy. the equation:
$$Y^2+aXY+X^2=Z^2$$
Has a solution:
$$X=as^2-2ps$$
$$Y=p^2-s^2$$
$$Z=p^2-aps+s^2$$
more:
$$X=(4a+3a^2)s^2-2(2+a)ps-p^2$$
$$Y=(a^3-8a-8)s^2+2(a^2-2)ps+ap^2$$
$$Z=(2a^3+a^2-8a-8)s^2+2(a^2-2)ps-p^2$$
more:
$$X=(a+4)p^2-2ps$$
$$Y=3p^2-4ps+s^2$$
$$Z=(2a+5)p^2-(a+4)ps+s^2$$
more:
$$X=8s^2-4ps$$
$$Y=p^2-(4-2a)ps+a(a-4)s^2$$
$$Z=-p^2+4ps+(a^2-8)s^2$$
In the equation:  $$X^2+aXY+bY^2=Z^2$$ there is always a solution and one of them is quite simple.
$$X=s^2-bp^2$$
$$Y=ap^2+2ps$$
$$Z=bp^2+aps+s^2$$
$p,s$ - integers asked us.


Run second site in the same VM: Is it possible?

Question: I would like to run all my Drupal 8 sites in one Vagrant VM instead of just one. Is this possible?
I tried to remove the default drupal site from the "web" folder and pulled(git) 2 of my current probject into it.
For any reason drush does not recongnize the drupal roots as proper drupal sites.
I am not sure how other modules react...  Is it normal to create each time a new VM for each Site you are developing. Seems a bit overkill.
Answer: Yes, this is possible, but take it from me as a guy who did it for about 12 sites - it gets tedious fast to manage it.
Setting up and tearing down VMs is so fast and cheap, it's simply more practical to me to create one per project. It's less to manage, and it just becomes a 'part' of the project codebase (you can fetch Drupal VM with Composer now for example, or download and keep it in a 'tools' folder outside of docroot).
Also it does not sound like you are setting up Drupal VM properly... I suggest re-reading the docs or posting more information.
Comment: I thought it would be a performance problem to run a hand full VMs at the same time, as resources must be copied over and so forth.

I encounter already with one Vagrant/ Virtualbox VM worse performance than with AMPPS for example. I wanted to keep it easy.
Comment: Why run them all at the same time?
Comment: copying over configurations, css, php code, inspecting html... many reasons. Its just better to have the ability to work with two sites at the same time.

Also sometimes other people of my team have to work on my machine to fill in content for example, while I need to work on another project.
Comment: Why can't they run VMs themselves? Kind of the whole point. Then have staging servers for content entry.
Comment: They are not developers. They fiill the sites just with content / text, images and so on. As far as its not simple to copy over nodes from one database to another this is also no option for d8.

We need to have one test/dev server that is useable over the local network.

I guess I have to stick then to Ampps.
One last question... Is the Vagrant/VBox solution performancewise faster than for example a xampp or mamp solution with you?


Making a another applications's window frontmost and focused

Question: I've been trying to get any given window from another Application to become front most and focused.
Here are the two methods I have tried:
AppleScript
tell application "Safari"
   set index of window "Downloads" to 1
   activate
end tell

Why it doesn't work: While it seems to change the z-Order, it doesn't change the focus! The previous frontmost window, even if obfuscated, retains focus.
CoreGraphicServices
CGSWindowOrder(cid, wid, kCGSOrderAbove, nil)

Why it doesn't work: Without being the Universal Owner, you can't change the order of a window owned by another process. In this case, making myself the Universal Owner is not an option -- I don't want to depose the Dock.
Recap
I need to make a window frontmost and focused from one process to another. AppleScript fails to focus, and CGS isn't an option since I don't own the window.
Any solutions/ideas?
Comment: Did you find a solution for this that can work today? Without accessibility enabled?
Answer: Try using the Accessibility API to send an AXPress action to the AXWindow. Obviously, the user will need to have access for assistive devices turned on.
Comment: Is there any easy to way create an AXWindow using a CGSWindow handle/id?
Comment: @Noitidart: The Accessibility APIs still exist. https://developer.apple.com/library/mac/documentation/Accessibility/Reference/AccessibilityLowlevel/
Comment: @Noitidart: Private interfaces are *more* likely to go away out from under you, not less. There isn't really a good solution there, except to file a bug asking for the usability of the accessibility-permission system to be improved (ideally with specific descriptions of difficulties your users have encountered): https://bugreport.apple.com/
Comment: @Noitidart: You should file bug reports for those. Here's the info on support incidents, what they're for, and how to use them: https://developer.apple.com/support/technical/ (Bug reports and TSIs are not mutually exclusive; it is valid to file a bug report to alert Apple to a problem, then use a TSI to try to unblock yourself.)
Comment: Edward: Nope. The only way to get an AXWindow is to find the window by title among the AXApplication's windows. This also means that if two windows have the same title, you're screwed.
Comment: This AX stuff is no longer around I think, is there any non accessibility method for these days? :) Thanks Peter!
Comment: Thanks @Peter you're right. But is it possible without accessiblity, maybe some private CoreGraphics stuff? My users are very newbie (firefox addon users) so they don't know how to turn on/off accesibility (especially granting a specific app access really is hard for them :( )
Comment: Thanks @Peter I'm going to buy that 100$ soon I badly need so many things. I got Windows and Linux sorted away but can't release till i have cross platform and OSX is a big chunk.
Comment: @Noitidart: Not sure what $100 you mean? You should be able to use the Apple Bug Reporter with only a (free) developer account; you shouldn't need to join the (not free) Developer Program.
Comment: Oh thanks for that, ill give it a shot. I thought they only help you out if you sing up.
Comment: @Noitidart: You may be thinking of support incidents, which are only available to Developer Program members.
Comment: Ah yeah I was thinking of doing that to ask them for stuff lke "always on top on windows" and stuff would they give me something? And i have another issue where `setApplicaitoniconImage` is not changing the icon that is overlaid ontop of minimized windows as this red arrow in img points out: ![](https://camo.githubusercontent.com/32204eb79b320f3894f6ef3c07a988ad48eb0ba6/687474703a2f2f692e696d6775722e636f6d2f68735254536b362e706e67)
Comment: Thanks very much @Hosey! :)