GitLab CI runner can't connect to tcp://localhost:2375 in kubernetes

Question: I followed this doc to install Gitlab on GKE :
https://docs.gitlab.com/ee/install/kubernetes/gitlab_chart.html
My installation's parameters are :
helm upgrade --install gitlab gitlab/gitlab \
  --timeout 600 \
  --set global.hosts.domain=***** \
  --set global.hosts.externalIP=***** \
  --set certmanager-issuer.email=***** \
  --set gitlab.migrations.image.repository=registry.gitlab.com/gitlab-org/build/cng/gitlab-rails-ce \
  --set gitlab.sidekiq.image.repository=registry.gitlab.com/gitlab-org/build/cng/gitlab-sidekiq-ce \
  --set gitlab.unicorn.image.repository=registry.gitlab.com/gitlab-org/build/cng/gitlab-unicorn-ce \
  --set gitlab.unicorn.workhorse.image=registry.gitlab.com/gitlab-org/build/cng/gitlab-workhorse-ce \
  --set gitlab.task-runner.image.repository=registry.gitlab.com/gitlab-org/build/cng/gitlab-task-runner-ce \
  --set gitlab.gitlab-runner.runners.privileged=true \
  --set gitlab.gitlab-runner.runners.cache_dir="cache"

Then I created my .gitlab-ci.yaml :
image: docker:latest

services:
  - docker:dind

variables:
  DOCKER_HOST: tcp://localhost:2375

stages:
  - package

package:
  stage: package
  before_script:
    - echo "${GKE_JSON_AUTH}" > gke-project-auth.json || exit 1
    - cat gke-project-auth.json | docker login -u _json_key --password-stdin https://eu.gcr.io || exit 1
  script:
    - docker info

I have read many threads, all get the solution in DOCKER_HOST and privilegedparameter, but I've always got this error :

Cannot connect to the Docker daemon at tcp://localhost:2375. Is the
  docker daemon running?

I also tried to put in a values.yaml file :
runners:
  privileged: true

and exectue this command :
helm upgrade --reuse-values gitlab gitlab/gitlab -f values.yaml

But without unsuccessfully...
Any idea? Thanks!
Comment: I am having the exact same issue
Answer: Apparently, according to this, this issue is more recently related to docker's update of its image docker:dind which use the last version of docker server which is not listening anymore at 2375 but at 2376.
So I updated my .gitlab-ci.yml as suggested in that entry and it worked for me:
image: docker:stable

services:
  - docker:18.09-dind

...

[UPDATE]
This was a temporary workaround. The docker:stable and docker:stable-dind images are now fixed.
Comment: Oh, thanks for this update... and what do you set in DOCKER_HOST so far?
Comment: OK, I set `tcp://localhost:2375` back instead of `2376` and it's working again... Bah
Comment: Hi, I tried that (using port 2376) in Dind on Kubernetes but I found out that 2376 expects TLS. I had to go back to old v18 version to have 2375 back. Can I enable non TLS port 2375 in new versions of Dind images? thanks.
Comment: @icordoba Hi, I must say that this was a temporary fix. The `docker:stable` and `docker:stable-dind` images don't have this issue any more. Regarding what you've asked you might find an answer for that [here](https://docs.gitlab.com/ee/ci/docker/using_docker_build.html#tls-disabled).
Comment: thanks @LeandroOrdonez I tried last docker:stable-dind but it only listens to port 2376 with TLS, not 2375. Is it possible to configure it to listen to 2375 too?
Answer: I found my mistake. The "Installation command line options" we can see here :
https://gitlab.com/charts/gitlab/blob/master/doc/installation/command-line-options.md says the privileged parameter is gitlab-runner.runners.privileged not gitlab.gitlab-runner.runners.privileged (and cache_dir doesn't exist).
So now it's OK with :
--set gitlab-runner.runners.privileged=true

Comment: @NoahMartin What is your complete command which doesn't work?
Comment: this was my problem: https://gitlab.com/gitlab-org/gitlab-ce/issues/64959
It's a fresh issue from gitlab.
Comment: This doesn't work for me. I still have the same problem
Comment: As written in gitlab-ci.yaml file in my first message, the DOCKER_HOST must be `tcp://localhost:2375` and not `tcp://docker:2375` for it to work.
Comment: Thanks for helping. I tried that also but didn't work. The link above explains my problem.
Answer: This solution using docker:18.09 and docker:18.09-dind images works.
.gitlab-ci.yml:
build_image:
  stage: build
  image: docker:18.09
  variables:
    DOCKER_HOST: tcp://docker:2375/
    DOCKER_DRIVER: overlay2
  services:
    - docker:18.09-dind

More discussion on this issue: https://gitlab.com/gitlab-org/gitlab-runner/issues/4501
Answer: Your root cause is probably linked to security update of dind : TLS certificates are required or must be explicitly disabled.
The elegant and reliable solution is here : https://about.gitlab.com/blog/2019/07/31/docker-in-docker-with-docker-19-dot-03/
Answer: The Docker-in-Docker service will be named after its image name: docker. You should set DOCKER_HOST to tcp://docker:2375.
Comment: When using docker in docker the docs say to use localhost - but it doesn't work neither does above answer
Comment: I've already tried this solution and I had this message : `error during connect: Post http://docker:2375/v1.39/auth: dial tcp: lookup docker on 10.0.0.10:53: no such host`


Prove that $\tilde{f}$ is a well-defined bijection

Question: I've been given a theorem:

Let $X$ be a space, ${\sim}$ be an equivalence relation on $X$ and $X/{\sim}$ the quotient space.
Suppose $f:X\rightarrow Y$ is a quotient map and $x \sim y\Leftrightarrow f\left(x\right)=f\left(y\right)$. Then, $X/{\sim}$ is homeomorphic to $Y$.

Here is my proof so far:

Let $\left[x\right]\in X/{\sim}$ denote the equivalence class of $x\in X$
Let $g:X\rightarrow X/{\sim}$, $x\mapsto\left[x\right]$ be the quotient function
Define $\widetilde{f}:X/{\sim}\rightarrow Y$,  $\widetilde{f}\left(\left[x\right]\right)=f\left(x\right)$ so that $f=\widetilde{f}\circ g$
Then, $\widetilde{f}$ is well-defined and a bijection*
Moreover, $U$ is open in $X/{\sim}\Leftrightarrow g^{-1}\left(U\right)$ is open in $Y$
$\Leftrightarrow f^{-1}fg^{-1}\left(U\right)$ is open in $Y$
$\Leftrightarrow fg^{-1}\left(U\right)$ is open in $Y$
$\Leftrightarrow\widetilde{f}gg^{-1}\left(U\right)$ is open in $Y$
$\Leftrightarrow\widetilde{f}\left(U\right)$ is open in $Y$
Therefore, $\widetilde{f}$ is a homeomorphism

I'm not sure how to show that $\tilde{f}$ is a well-defined bijection.
Answer: $\newcommand{\s}{{\sim}}\newcommand{\t}[1]{\widetilde{#1}\!}$I assume that your issue is in showing the "well-defined" part.
Note that you are defining $\t{f}([x]) = f(x)$. To show that this is well-defined, you need to show that $f(x)$ "only depends on $[x]$ and not $x$".
More precisely, you need to show that: $[x] = [y] \implies f(x) = f(y)$.
But this follows precisely from your definition of $\s$. Indeed, you have
$$[x] = [y] \implies x \sim y \implies f(x) = f(y).$$
(In fact, note that the above implications are reversible. Thus, $[x] = [y] \iff f(x) = f(y)$. This also shows you that $\t{f}$ is an injection. That it is a surjection follows from the fact that $f$ was a surjection to begin with.)


How do I hide render elements if a checkbox that controls a form #state is checked?

Question: I have a form where a user can either choose a gallery field to populate or a video field to populate but they have to choose one of the other -- there can't be a video and gallery on a page.
The logical way to do this is make three seperate content types, an article, a video and a gallery. However, since they all function about the same and an article could be about a video or a slideshow. Nevertheless, there isn't a case where a slideshow and video should be together. If they user wants video and images they can embed images through wysiwyg.
Using the #state mechanism, I have a select radios field that has the option of none, video, or image / gallery. This is set to hidden in the content display interface. If they choose image then the file field widget shows and if they choose video then the youtube field shows (once again I could use Media but that is huge and overkill for this application.)

The interface is quite sweet.

.

However, there is a problem because here a slideshow gallery has been created before the user decided to use a youtube video embedded.

What is the best practice for hiding the image gallery if the Youtube setting has been choosen? Do I make the media setting visible and then hide it and the image gallery? This doesn't make good sense because it is processed and therefore ineffient doing extra work. I don't want to force the form field to be deleted because then the work is lost. It just shouldn't be processed rather than have work deleted in the case the user would like to revert from one to the other. Any ideas?
EDIT:
I tried this code which works but I don't know if it's the best practice.
function helper_preprocess_node (&$variables) {
  switch ($variables['type']){
    case 'article':
      if (isset($variables['field_article_media'][0]['value'])){
        if ($variables['field_article_media'][0]['value'] == 'gallery'){
          unset($variables['content']['field_youtube']);
        }
        if ($variables['field_article_media'][0]['value'] == 'video'){
          unset($variables['content']['field_image']);
        }
        unset($variables['content']['field_article_media']);
      }
      break;

    default:
      break;

  }
}

Comment: Your acceptance rate is very low. Maybe you could consider accepting the best answers and upvote the ones that are ok in some of your posts ? This way the help you received *can help others*.  I don't want to patronise you because you may know all this but I highly recommend you read [the awesome faq page](http://drupal.stackexchange.com/faq), it is well worth the read.
Answer: You are right, a 3rd party module is overkill for this! I often find myself using a small js file to spice up the #states behavior. You can pretty much even bybass #states totally with this mecanism, but hey. #states is the drupal way of doing things. That does not mean it can't be assisted with JQuery.
Here is a quick snippet of my current quick project that is a form in a webform using the techniques (#states + jQuery) to tweak many things in the ui depending on what options are selected. This code should be in a .js file, loaded in module by the module's .info file, or you can have it in a drupal_add_js call.
I left all in there so you can see how with jQuery you can control fieldsets, option boxes and most anything you can think of. Notice also if you fancy as a bonus you can integrate all the jquery native animation functions like fadeIn() fadeOut(). There are also examples of that in the code below.
(function ($) {  // Notice code is in a behavior, use your module name
  Drupal.behaviors.yourModuleNameHere = {
    attach: function (context, settings) {

  // On load hide stuff. This will be shown when options are selected.
  $('#webform-component-inscription--enfant-1').removeClass('collapsed');
  $('#webform-component-inscription--enfant-2').removeClass('collapsed');
  $('#webform-component-inscription--enfant-1').hide();
  $('#webform-component-inscription--enfant-2').hide();
  // $('.form-submit').hide();

  $('#webform-component-inscription--information-supplementaire').hide();
  $('#edit-submitted-inscription-nombre-denfants', context).change(function () {

    var selected_option = $(this).val();

    if(selected_option === "1"){
        $('#webform-component-inscription--enfant-1').removeClass('collapsed');
        $('#webform-component-inscription--enfant-1').fadeIn(800);
        $('#webform-component-inscription--enfant-2').fadeOut(800);
        $('.form-submit').fadeIn(800);
        $('#webform-component-inscription--information-supplementaire').fadeIn(1000);
    }
    else if(selected_option === "2"){
        $('#webform-component-inscription--enfant-1').fadeIn(800);
        $('#webform-component-inscription--enfant-2').fadeIn(1500);
        $('#webform-component-inscription--information-supplementaire').fadeIn(2200);

    } else {
          $('#webform-component-inscription--enfant-1').fadeOut(800);
          $('#webform-component-inscription--enfant-2').fadeOut(800);
          $('.form-submit').fadeOut(800);
          $('#webform-component-inscription--information-supplementaire').hide();
          console.log("in extra information.");
         // $('#webform-component-inscription--enfant-1').addClass('collapsed');
        //  $('#webform-component-inscription--enfant-2').addClass('collapsed');
        }
      });
    }
  };
}(jQuery));

Of course, this method I am using  only acts on the presentation layer, if the fields you want to act on needs to be validated,  a server-side call is probably needed anyways and your method is probably better in that case.


How to apply CHMOD command to any file with a specific name recursively in Linux?

Question: I need to know how to apply a CHMOD command to only files that have a specific name recursively?
chmod 755 -R filename

Something like above but it should apply to any filename that exists in any sub folders.
Comment: do you want to apply this to a filename or a file type ie .html, .php etc
Comment: Just a file with the name `filename`
Answer: This will find all files named filename, recursively from the current directory, and pass them to chmod.
find -name filename | xargs chmod 755

See the manpages for find and xargs for more advanced options. In particular, look at the -print0 flag and corresponding -0 to xargs if you get errors about files with spaces in the name.
Answer: There's also a exec parameter in find that will do the same:
find . -name filename -exec chmod 755 {} \;

Comment: However, if your version of `find` supports it, you can use a `+` instead of the `\;` to get `xargs`-like functionality.
Comment: The trade off here is execution efficiency.  Xargs will only call chmod approximately the minimum number of times necessary for the number of files, the exec option to find will call it once for each file found.
Answer: You can get the best of both worlds if you use the + operator to find to make it run chmod on many files at once.
find . -name filename -exec chmod 755 '{}' +

You should always put a ' around your {}, otherwise a filename with a space in it could mess things up. In this case it's not a problem, but I have a habit of doing it.


How math deals with state or "algebra of sequential logic"

Question: Boolean algebra is well-studied and you could easily find a lot of introductory materials on different operators, properties, how eveything is nicely related to the algebra of sets, and so on.
Coming from the EE background, I also know that you can construct any circuit using NAND/NOR gates, because of their nice functional completeness properties. The same goes for stateful circuits, as you could build a simple stateful RS-Latch with 2 NAND/NOR gates, by applying them to each other.
This is where it gets interesting - does that mean that the state arises from the recursion? i.e.
<code> q = nand(r, nand(s, q))
</code>
Unfortunately, I couldn't find anything like "algebra of sequential logic" or any notion on how mathematics seems to deal with state (or, better say: time?!). Most likely, my search keywords are compeltely off.
Could you help me out? I would like to know how mathematicians deal with sequential circuits - any introductory book would be great.
Comment: @AxelKemper not the state machines, but the state itself.
Comment: My recommended search terms are [Moore Mealy FSM](https://www.google.de/search?q=moore+mealy+fsm&ie=utf-8&oe=utf-8&gws_rd=cr&ei=un6JWcDzCKz-6ASZ_pOwAQ).
Comment: algebraic automaton theory
Comment: The computers in the world run on the sequential switching theory. Montgomery intuited it, Caldwell and his PhD student Huffman developed. That put Americans on the Moon, because Apollo navigation computer used that very logic in its ICs.
Comment: And you're asking right questions. I want to work with you. Please, find me, and get connected.
Comment: https://ia802705.us.archive.org/12/items/bstj34-5-1045/bstj34-5-1045.pdf
Answer: The math involved is that of Semigroups and its application to "sequential circuits" is named "algebraic theory of machines".
Read just to start:
Krohn, Rhodes, Arbib - Algebraic Theory of Machines, Languages and Semigroups
Comment: And what about temporal logic? Is it related somehow?
Comment: Also, found this: Asynchronous Operators of Sequential Logic: Venjunction & Sequention. Do you know anything about this, by chance?
Comment: @artemonster It depends on what you need. This last book is not a mathematical book. If you want to learn the mathematics behind Mealy machines, Semigroups is the way to go and the book I suggested has been written by people with engineer-oriented minds that possibly inadvertently working on sequential circuits have discovered important results in the theory of the Semigroups. Following this approach you have the chance to start studing mathematical arguments that are difficult when approached abstractly (as most mathematicians inevitably do, not knowing sequential circuits).
Comment: Thank you, again. It's just that I was very dissatisfied with the basic definition of state machines (a tuple of a transition function, state set and output function) and wanted to know where the "state" comes from and if there is another meaning to the state, beyond just being a "symbol" :)
Comment: I've started the Krohn text and it seems to be exactly what I'm looking for. Are there any more modern texts with similar coverage you might recommend?
Comment: @Dragonsheep after that book you should see something more abstract like Clifford, Preston *The algebraic theory of semigroups* (1967) or Howie *Fundamentals of semigroup theory* (1995)
Answer: I don't know the answer, but I'd like to register a little bit of doubt regarding the position that semigroups/automata provide the most direct account of such phenomena. I'm not saying they aren't related, but I don't think knowing the basic definitions of that branch of knowledge directly answers your question. Anyway, I recommend reading up about traced monoidal categories, which are places where this kind of feedback is allowable. Specifically, you should probably read up on traced cartesian monoidal categories. You may also be interested in this old question of mine at MathOverflow.
Comment: I've found a lot of papers lately that state that the "mainstream" semigroup theory "is not enough" to describe stateful functions well. Maybe "Primitive Recursion and state machines" would be of interest to you. Thank you for links.
Comment: Also, this quite blew my mind : "the existence of a trace operator is equivalent to the existence of a "parameterized" fixed point operator satisfying certain properties".
Soooo, basically, state arises from a fixed point, i.e. q = not not q?


How to add constraint on associated type in Swift

Question: I am trying to create a protocol R with an array of objects n which can be, in principle, different classes (N1, N2) but all subjects of the same protocol N. Classes that submit to the protocol R (M1, M2) can decide whether their property array n will hold only specific kind of R or any.
This compiles just fine:
protocol N { }
class N1: N { }
class N2: N { }

protocol R {
    associatedtype NType
    var n: [NType] { get set }
}

class M1: R {
    var n: [N] = [N1(), N2()]
}

class M2: R {
    var n: [N1] = [N1(), N1()]
}

But I don't understand how to add a constraint to the associatedtype Ntype that it must conform to N. Something in the lines of
protocol N { }
class N1: N { }
class N2: N { }

protocol R {
    associatedtype NType: N
    var n: [NType] { get set }
}

class M1: R {
    var n: [N] = [N1(), N2()]
}

class M2: R {
    var n: [N1] = [N1(), N1()]
}

This doesn't compile saying that Type 'M1' does not conform to protocol 'R'.
Comment: You can make `N` an `@objc` protocol. See [here](https://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself) for more info.
Comment: Or skip the associated type and declare n as `var n: [N] { get set }` although then you must always implement `n` exactly as that.
Comment: @Sweeper Thanks, your method works!
Comment: @JoakimDanielson As you commented yourself the solution is not optimal because then `M2` can't have property `n` stored as `[N1]`.
Answer: Using swift 5.7.1 you can use [any N] I would not change N, N1, N2 or R:
protocol N { }
class N1: N { }
class N2: N { }

protocol R {
    associatedtype NType
    var n: [NType] { get set }
}

But I would implement M1 differently using and array of any N eg.:
class M1: R {
    var n: [any N] = [N1(), N2()]
}

which compiles and prints:
let m1 = M1()
print(m1.n) // [__lldb_expr_13.N1, __lldb_expr_13.N2]
m1.n.append(N2()) // [N1, N2, N2]
m1.n.append(N1()) // [N1, N2, N2, N1]

but it can also hold a specific kind of N, eg.:
class M2: R {
    var n: [N1] = [N1(), N1()]
}

which outputs:
let m2 = M2()
print(m2.n) // [__lldb_expr_17.N1, __lldb_expr_17.N1]
m2.n.append(N1()) // [N1, N1, N1]
m2.n.append(N2()) // No exact matches in call to instance method 'append'

as you can see m1.n is an heterogeneous array of objects conforming to NType aka N while m2.n can only hold N1 values.
Comment: "Here you have a protocol R with an array of objects `n` which can be, in principle, different classes (`N1`, `N2`) but all subjects of the same protocol `N`." Where exactly is this constraint placed in your code? Let's say I create an array `r: [any R]` and an element of `r` will know that it has a property called `n` of type `[NType]`, but `NType` is at this point undefined, i. e. `Any`.  I can cast it to `[N]` but I want to avoid it.
Comment: This is true and I have already provided this solution in the first code snippet in the question. What I would like to know is how to add constraint on NType that it must conform to protocol N, which now that I ask it like that, requires a protocol to conform to itself, which I know is not allowed. But maybe there is a way by restructuring the code or something. I know that it works if I convert `N` to a class, but this is not an ideal solution.
Comment: I don't see `[any N]` in you code snippets, `Any N` means any type conforming to `N` and it looks like what you are looking for. Anyway this is the way I would _restructure_ the code. I edited my answer for clarity.
Comment: But using this solution I must force  cast `n` to `[any N]` if I only know that an instance is conforming to protocol `R` but not necessarily which class it is. In other words, you do not answer the question on how to add constraint on `Ntype` so that it conforms to `N`.
Comment: Here you have a protocol R with an array of objects `n` which can be, in principle, different classes (`N1`, `N2`) but all subjects of the same protocol `N`. Classes that submit to the protocol `R` (`M1`, `M2`) can decide whether their property array `n` will hold only specific kind of `N` or `any N`. Can you explain why you need to force cast?


JqGrid, mostra sucesso no carregamento, mas não monta a Grid

Question: Estou com uma grid em meu site que uso o JqGrid. O que esta acontecendo é que quando os dados voltam da requisição, eles estão formatados da maneira correta porque o próprio JqGrid entra no método loadComplete, porém, ele não carrega esses dados na Grid.
Javascript do JqGrid.
    $(document).ready(function () {
    $("#jqGrid").jqGrid({
        url: 'adm/controller/medico.php?acao=listarMedico',
        mtype: "POST",
        styleUI : 'Bootstrap',
        datatype: "json",
        colModel: [
            { label: 'id', name: 'idMedico', key: true, width: 75, hidden:true },
            { label: 'Nome', name: 'nomeMedico', width: 75 },
            { label: 'CRM', name: 'crmMedico', width: 150 },
            { label: 'Especialidades', name: 'especialidadesMedico', width: 150 },
            { label: 'Endereço', name: 'enderecoMedico', width: 150 },
            { label: 'Telefone', name: 'telefoneMedico', width: 150 }
        ],
        viewrecords: true,
        rowNum: 20,
        rowList: [20, 40, 100],
        //height: "auto",
        height: 400,
        emptyrecords: "Nenhum médico com o filtro selecionado",
        loadtext: "Buscando e carregando...",
        rowNum: 20,
        pager: "#jqGridPager",
        caption: "Médicos Conveniados",
        loadComplete: function(data){
            console.log('sucesso');
            console.log(data);
        },
        loadError: function (xhr,st,err) {
            console.log('HTTP status code: ' + xhr.status + '\n' +
                  'textStatus: ' + st + '\n' +
                  'errorThrown: ' + err);
            console.log('HTTP message body (jqXHR.responseText): ' + '\n' + xhr.responseText);
        }
    });
});

O retorno que o PHP me traz e esse em JSON:
{
  "total": 1,
  "page": 1,
  "records": 20,
  "rows": {
    "1": {
      "id": "1",
      "cell": {
        "idMedico": "1",
        "nomeMedico": "dsda",
        "crmMedico": "jknjk",
        "especialidadesMedico": null,
        "enderecoMedico": " ,  -  - ",
        "telefoneMedico": "() "
      }
    },
    "2": {
      "id": "2",
      "cell": {
        "idMedico": "2",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": " ,  -  - ",
        "telefoneMedico": "() "
      }
    },
    "3": {
      "id": "3",
      "cell": {
        "idMedico": "3",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": " ,  -  - ",
        "telefoneMedico": "() "
      }
    },
    "4": {
      "id": "4",
      "cell": {
        "idMedico": "4",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": " ,  -  - ",
        "telefoneMedico": "() "
      }
    },
    "5": {
      "id": "5",
      "cell": {
        "idMedico": "5",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endere\u00e7o , Bairro - \u00c1gua Doce do Norte  - ES",
        "telefoneMedico": "() "
      }
    },
    "6": {
      "id": "5",
      "cell": {
        "idMedico": "5",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endere\u00e7o , Bairro - \u00c1gua Doce do Norte  - ES",
        "telefoneMedico": "() "
      }
    },
    "7": {
      "id": "5",
      "cell": {
        "idMedico": "5",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endereco , Bairro - Afonso Cl\u00e1udio - ES",
        "telefoneMedico": "() "
      }
    },
    "8": {
      "id": "5",
      "cell": {
        "idMedico": "5",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endereco , Bairro - Afonso Cl\u00e1udio - ES",
        "telefoneMedico": "() "
      }
    },
    "9": {
      "id": "6",
      "cell": {
        "idMedico": "6",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": " ,  -  - ",
        "telefoneMedico": "() "
      }
    },
    "10": {
      "id": "7",
      "cell": {
        "idMedico": "7",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": " ,  -  - ",
        "telefoneMedico": "() "
      }
    },
    "11": {
      "id": "8",
      "cell": {
        "idMedico": "8",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endere\u00e7o , Bairro - Afonso Cl\u00e1udio - ES",
        "telefoneMedico": "() "
      }
    },
    "12": {
      "id": "8",
      "cell": {
        "idMedico": "8",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endere\u00e7o , Bairro - Afonso Cl\u00e1udio - ES",
        "telefoneMedico": "() "
      }
    },
    "13": {
      "id": "9",
      "cell": {
        "idMedico": "9",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endere\u00e7o , Bairro - Afonso Cl\u00e1udio - ES",
        "telefoneMedico": "() "
      }
    },
    "14": {
      "id": "9",
      "cell": {
        "idMedico": "9",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endereco , Bairro - \u00c1gua Doce do Norte - ES",
        "telefoneMedico": "() "
      }
    },
    "15": {
      "id": "10",
      "cell": {
        "idMedico": "10",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endere\u00e7o , Bairro - Afonso Cl\u00e1udio - ES",
        "telefoneMedico": "(81) 98125-8886"
      }
    },
    "16": {
      "id": "10",
      "cell": {
        "idMedico": "10",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endereco , Bairro - \u00c1gua Doce do Norte - ES",
        "telefoneMedico": "() "
      }
    },
    "17": {
      "id": "11",
      "cell": {
        "idMedico": "11",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endere\u00e7o , Bairro - Afonso Cl\u00e1udio - ES",
        "telefoneMedico": "(81) 98200-5300"
      }
    },
    "18": {
      "id": "11",
      "cell": {
        "idMedico": "11",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endere\u00e7o , Bairro - Afonso Cl\u00e1udio - ES",
        "telefoneMedico": "(81) 98125-8886"
      }
    },
    "19": {
      "id": "11",
      "cell": {
        "idMedico": "11",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endereco , Bairro - \u00c1gua Doce do Norte - ES",
        "telefoneMedico": "() "
      }
    },
    "20": {
      "id": "12",
      "cell": {
        "idMedico": "12",
        "nomeMedico": "Henrique",
        "crmMedico": "CRM",
        "especialidadesMedico": null,
        "enderecoMedico": "Endere\u00e7o , Bairro - Afonso Cl\u00e1udio - ES",
        "telefoneMedico": "(81) 98200-5300"
      }
    }
  }
}

Alguém saberia o porque o JqGrid não esta montando os dados na Grid?
Answer: O problema foi resolvido.
Fiz essa mesma pergunta no stackoverflow em inglês, e a resposta que me deram me ajudou a resolver o problema.
No meu JSON eu não montei o rows da maneira que o JqGrid espera que é na chave do rows ser dessa maneira:
[
    {"idMedico":"1",...},
    {"idMedico":"2",...},
    ...
    {"idMedico":"12",...}
]

Para conseguir isso, no PHP eu criei a chave rows no array X, montei um arrayseparado com as linhas que queria e dei um array_push passando o array X e especificando a chave rows.


C# Generating Labels Dynamically

Question: I have got the below code to generate labels using for loop, however there is a problem with the for loop, if the productList has 4 items, it generates 1 label instead of 4. I can't figure out what the problem is.
List<models.Car> carList = carController.getCars();
for (int i = 0; i < carList.Count; i++)
{
    List<models.Product> productList = productController.getProducts(carList[i].Model);

    for (int j = 0; j < productList.Count; j++)
    {
        productLabels.Add(new Label());
        var productLabelsPoint = new System.Drawing.Point(200, 40 + i * 50);
        (productLabels[j] as Label).Location = productLabelsPoint;
        (productLabels[j] as Label).Size = new System.Drawing.Size(150, 15);
        (productLabels[j] as Label).Text = productList[j].Title;
        this.Tab.TabPages["tab1"].Controls.Add((productLabels[j] as Label));
    }
}

Comment: which list? the carlist or the productList?
Comment: In the question, when you say "if the list has 4 items" does 'the list' mean productList or carList ?
Comment: @LeonBambrick for each increment of carList, productList is updated with new data and generates a new labels until the carList is finished.
Comment: Ok @PRCube. I hear what you're saying. Now stick with me here. I have a question about your question. There is something that I cannot understand. I need to know the answer here, when you say "if *the list* has 4 items".... it's a good example... but I don't know what it means by 'the list'.
Comment: @LeonBambrick I ment the productList, which is used as the number of labels to generate. so productList.Count = number of labels needed.
Comment: Okay I updated my answer accordingly. Please see if it makes any change.
Comment: @LeonBambrick unfortunately, it only generates label for the last two items in the productList. I think it might be overlapping like you said.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/76411/discussion-between-leon-bambrick-and-prcube).
Answer: This only relies on i, not on j:
System.Drawing.Point productLabelsPoint = new System.Drawing.Point(200, 40 + i * 50);

So you might be drawing the labels one on top of the other.
In which case, you'd need to add j into the mix, for example like this:
System.Drawing.Point productLabelsPoint = new System.Drawing.Point(200, 40 + i * 50 + j * 50);

I would also change the way you are referencing the label. (I can't tell from the context if what you are doing is okay or not, as it depends how that productLabels variables has been instantiated.)
Comment: Rather add a new variable telling the number of the label added and use that to calculate the position, since they might still overlap. And the referencing the label from the List was definitely wrong.
Comment: just above my code, this is how I declare the labels.

ArrayList productLabels = new ArrayList();

C# Generating Labels Dynamically


Show $\triangle AES$ is equilateral iff $\triangle IKE$ is equilateral....

Question: Question
Let the $\triangle ABC$ and $D$, $E$, $F$ be the intersection points of the center circle $I$, inscribed in the triangle, with the sides $BC$,$ AC$, $AB$, respectively.  We denote by $K$ the symmetry of $D$ with respect to the center of the inscribed circle.  We denote by $S$ the intersection between $FK$ and $DE$.  Show that the $\triangle AES$ is equilateral if and only if the $\triangle IKE$ is equilateral.
My Idea

I don't know what to do forward. I got stuck with that $60°$ angle. Hope one of you can help me! Thank you!
Comment: If we can prove that $\angle FSE=\frac{\angle A}{2}$. Then the circle with $A$ as center, $AE=AF$ as radius will pass through $S$. This implies $AS=AE.$
Comment: Because the OP wants to continue his argument. A new proof does not answer his question.
Comment: *Hint*: uniqueness
Comment: Please use descriptive titles.
Comment: @LiKwokKeung Any idea that will lead to the corect answer are good for me. Maybe my idea isnt going anywhere.
Comment: @IonelaBuciu Please see my answer.
Answer: I would prove that $\Delta AES \sim \Delta IKE$ and consequently one is equilateral iff the other is.
But we first need a lemma.

In the figure, if $AX=AY$ and $\angle XAY = 2 \times \angle XZY$, then $Z$ lies on the circle with $A$ as center, $AX$ as radius. In other words, $AX=AY=AZ.$
Reason: $\mathrm{angle \; at \; center} = 2 \times \mathrm{angle \;  at  \; circumference.}$
Proof that $\Delta AES \sim \Delta IKE$ :

$(1)$ $I, F, B, D$ are concyclic $\implies \angle KIF=\angle B \implies \angle IDF=\frac{\angle B}{2}$
$(2)$ $I, D, C, E$ are concyclic $\implies \angle EIK=\angle C \implies \angle IDE=\frac{\angle C}{2}$
$(3)$  In $\Delta DFS, \angle FSD=180^{\text o}-90^{\text o}-\frac{\angle B}{2}-\frac{\angle C}{2}=\frac{\angle A}{2}$
$(4)$ Note that $AE=AF$ by tangent property. Hence by our lemma, $AS=AE$.
$(5)$ Thus both $\Delta AES$ and $\Delta IKE$ are isosceles triangles. We are done if we can prove that $\angle AES = \angle IEK$.
$(6)$ By angle in alternate segment, $\angle AEK=\angle EDK=\frac{\angle C}{2}$.
$(7)$ $\therefore \angle AES=90^{\text o}-\frac{\angle C}{2}$.
$(8)$ $\because IE=IK, \angle IEK=\frac{180^{\text o}-\angle KIE}{2}= \frac{180^{\text o}-\angle C}{2}=90^{\text o}-\frac{\angle C}{2}$.
$(9)$ From $(7)$ and $(8)$, we have $\angle AES=\angle IEK$ .
$(10)$ Thus $\Delta AES \sim \Delta IEK$ and one triangle is equilateral iff the other is equilateral.
Comment: Surprise use of a basic lemma, nice. So $\triangle CDE \sim \triangle IEK \sim \triangle AES$ because their angles are $C, 90- C/2, 90- C/2$. Also $AS \parallel BC$.
Answer:
Hint:You showed $\angle AES=60^o$. Extend DK to meet AS or its extension at H.  A perpendicular from A on BC meets it at P. We have:
$\angle EDC=\angle DEC=60^o$
$\Rightarrow \angle ACP= 60^o$
$\Rightarrow \angle PAC=30^o$
Also $\angle SDH=30^o\Rightarrow HS||BC\Rightarrow \angle ASE=60^o$
that is triangle AES is equilateral.
Comment: Thank you so much for your answer! May you explain me why $HS$ and $BC$ are parallel???
Comment: @lonela buciu, You'r welcome, because they are both perpendicular on BC.


gcc version not compatible with progol software

Question: I am using an ILP system named proGol which is not anymore state of the art; progol implementation has been in C though the syntax of coding is similar to prolog. However, I can run it on old machines with gcc version of 3.4.3. Such machines are very old and I need to run my code on new servers with gcc version on 4.6.3. When I do that, the software outputs segmentation error. I believe the problem is the gcc versions that are not compatible and progol itself probably can be run only on 32 bit processors. Does anyone know how I can adjust the gcc version of machine to older versions?
Comment: I'd make a guess that the old code modifies string constants (probably because a string literal is passed to a function as a `char *` and the function then modifies the string).  Such code was never portable; the version 4 GCC compilers no longer support the old `-fwriteable-strings` option (with one or two e's in the option).  Your main choices AFAICS are (1) fix proGol code so it does not modify string literals, or (2) rebuild the GCC 3.4.x compiler on the newer machine.  Long term, you'd be best off dealing with (1); short term, there's a chance that (2) seems simpler.
Comment: you comment was very helpful.
Answer: I know this is an old question but I recently have to deal with this same error and I ended here looking for an answer since this is at this moment the first google result when someone looks for "progol segmentation fault".
Compiling progol using gcc-4.8 has worked for me. I just simply changed the gcc alias in the Makefile by 'gcc-4.8'.
I hope this could help someone.


Extract value from json response python?

Question: I am making a request to an endpoint and getting a json response in the following format.
r = requests.get(url)
print(r.json())

{"context":"product=fhvh, price=25,product=vfjvnf,price=37,product=fvfv,price=3.....}

I want to loop over them and get the count of the products that have a price point of more than 22.
How can i get that? I tried to loop over the json response initially but i don't believe that will work due to the format of the output. Is there a better solution? How can i convert the response to maybe a dict or tuple first? Can someone help me. Thank you.
Comment: It looks like this question is more about string processing rather than JSON.
Comment: Do you know the structure of the response? Can you provide the skeleton?
Comment: @PraveenPremaratne Yes, i have. This is the skeleton :-
```{"context":"product=fhvh, price=25,product=vfjvnf,price=37,product=fvfv,price=3.....}```
Comment: Do you know if it always comes in pairs? `product=fhvh, price=25`
Comment: @PraveenPremaratne Yes, it always comes in pairs.
Comment: Are the products all unique?
Comment: @RichardDodson Yes, they are all unique.
Comment: So your response is coming in as an unordered ordered list within a string with no validation (e.g. product=fhvh, etc.)? Can you just post the actual JSON?
Comment: @psychopg2 Unfortunately this the actual data that i am getting.
Comment: I've a solution but its not an ideal or one I'd personally use
Comment: @PraveenPremaratne Can you share it please?
Answer: This is the worst possible solution, it relies on the response always has a product and a price and can be very unreliable.
r = requests.get(url)
data = r.json()

context=data.get('context')
elements = context.split(',')
chunks=[elements[i:i + 2] for i in range(0, len(elements), 2)]
print(chunks)

[['product=fhvh', ' price=25'], ['product=vfjvnf', 'price=37'], ['product=fvfv', 'price=3']]

I'd look into data processing libraries used by Big Data like Pandas that might have a more reliable way to doing it.
Update
r = requests.get(url)
data = r.json()

context=data.get('context')
elements = context.split(',')
chunks=[elements[i:i + 2] for i in range(0, len(elements), 2)]
print(chunks)

product_list = []
for item in chunks:
     obj1=item[0].split('=')
     obj2=item[1].split('=')
     product = { obj1[0].strip(): obj1[1].strip(), obj2[0].strip(): float(obj2[1].strip())}
     product_list.append(product)

print(product_list)

for product in product_list:
     if product.get('price') > 22.0:
             print(product)

Comment: Yes, as long as the response provides it in that sort of order. So if the response dos this `product=fhvh, product=vfjvnf, price=25, price=37` you're screwed.
Comment: Well i will still accept this as a potential answer and will look into pandas.
Comment: Hmmm, so you converted it into smaller lists. How can i get the product whose price is more than 22?
Comment: It does always have a price and product.
Comment: It's an array of arrays... so you can just iterate and build another array that has elements that are over a certain price.
Comment: This is why its very unreliable, you're putting faith in the API to always be consistent
Comment: @Somethingwhatever check the update, that should work.
Answer: Your issue is that the payload you have isn't JSON but some alternative format. My advice would be to convert each entry in context into an object:
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = float(price)

def parse_data(resp):

    # First, read in the JSON
    raw_data = r.json()

    # Next, split the context field in the JSON into a list-of-tuples
    # where each item represents a key and value.
    parsed_data = [tuple(item.strip().split('=')) for item in raw_data["context"].split(',')]

    # Finally, convert each product to our type and return the list of them
    # This assumes that the payload contains a product followed by a price
    return [Product([i][1], y[i + 1][1]) for i in range(0, len(y), 2)]

r = requests.get(url)
filtered = [product for product in parse_data(r) if product.price > 22]

This code obeys separation of concerns and produces the output you want (all products with a price greater than 22). That being said, this relies heavily on assumptions about what is returned from the API you're requesting. You'll want to add data checks to ensure that you're not getting bad data.
Comment: @PraveenPremaratne I think that's a valid point. Actually, I don't think I did any parsing of the value at all.
Comment: This looks much better than mine, but I'd parse the price as a `float`. It may have decimals.


Convergence of sups of sequence of compactly supported continuous functiosn

Question: Let $\Omega\subset \Bbb R^n$ be open and bounded and $(f_n)\subset C_c^0(\Omega)$ a sequence which converges pointwise to $f\in C_c^0(\Omega)$. Does $\sup_{x\in\Omega}|f_n(x)|\to \sup_{x\in\Omega}|f(x)|$ as $n\to\infty$? This is obviously true when the convergence is uniform, but we don't have that here. If this is too much to hope for, is at least the sequence $(\sup_{x\in\Omega}|f_n(x)|)$ bounded?
Answer: Assuming $C^0_c(\Omega)=$ space of continuous function with compact support on $\Omega$, set $\Omega=(0,1)$ and
$$
f_n=n1_{(0,\frac{1}{n}]}+ne^{1-nx}1_{(\frac{1}{n},1)}
$$
$\{f_n\}$ converges pointwise to $0$ but $\{\sup_{x\in\Omega}|f_n(x)|:n\in\mathbb N\}$ is not even bounded.
Comment: These functions are not continuous, but something along those lines should work.


$\operatorname{Spec}(A)$ is called "the (prime) spectrum of $A$". What is $\operatorname{Proj}(A)$ called?

Question: Modern algebraic geometry makes heavy use of two constructions that turn rings into schemes: Spec and Proj. The first construction turns a commutative ring $A$ into a scheme $\operatorname{Spec}(A)$, called the "prime spectrum" of $A$. The second construction turns a graded ring $S$ into a scheme $\operatorname{Proj}(S)$, called $\dots$ "Proj of $S$", according to these three standard sources:

The Stacks Project (http://stacks.math.columbia.edu/tag/00JM)
Vakil's The Rising Sea (section 4.5)
Hartshorne's Algebraic Geometry (section II.2)

Usually the name of a mathematical object precedes its notation, but for $\operatorname{Proj}(S)$, it seems like the name is the notation. Is that right? What is $\operatorname{Proj}(S)$ actually called?
In the interest of staying within the scope of MSE and avoiding personal opinions, I'd like a reference to a source that gives $\operatorname{Proj}(S)$ a name.
Answer: After writing this question, I dug a bit deeper and looked at (where else?) EGA. Section 2.3 of Chapter II calls $\operatorname{Proj}(S)$ the spectre premier homogène, which I would translate as homogeneous prime spectrum. In retrospect, this name is very reasonable; I'm not sure why it isn't more widely used. (Googling "prime spectrum" gives 20,400 hits but "homogeneous prime spectrum" gives only about 500.) It's probably just easier to say "Proj of $S$."
Comment: I could swear I've also heard "projective spectrum" somewhere, which isn't quite as wordy...


How to push form values to database in Drupal

Question: I am building a drupal site in which I would like the admin to have the ability to input goals into a table on the drupal database that can then be output to other users to be completed.
The form for the input and the table get created, however the values are not added into the table when submit is pressed and I'm not sure why.
I have the following code from the module that I am hooking into my site. I think the problem occurs at the top where I am creating the fields, or at the bottom when I submit the values. I'm really not sure.
Can anyone tell me where I went wrong and how to fix it?

function achievementList_init() {
if(!(db_table_exists('achievements'))) {
    $achvmnt_list_schema = array(
        'description' => 'Achievement Fields',
        'fields' => array (
            'achvmntID' => array('type' => 'int', 'unsigned' => TRUE, 'AUTO_INCREMENT' => TRUE, 'not null' => TRUE),

            'achvmntName' => array('type' => 'varchar', 'length' => 256, 'not null' => TRUE, 'default' => ''),

            'achvmntDesc' => array('type' => 'varchar', 'length' => 256, 'not null' => TRUE, 'default' => ''),

            'achvmntPts' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE),

    ));
    db_create_table('achievements', $achvmnt_list_schema);
}
}

function achievementList_menu($form, &$form_state) {
$items = array();
$items['achievementList/addAchievement'] = array(
    'title' => 'Achievement Input',
    'description' => 'Input Achievement info to add achievement to database',
    'page callback' =>'drupal_get_form',
    'page arguments' => array('achievementList_form'),
    'access callback' => TRUE
);
return $items;
}

function achievementList_form($form, &$form_state) {
$form['name'] = array (
    '#type' => 'textfield',
    '#title' => 'Achievement Name',
    '#size' => '20',
    '#maxlength' => '20',
    '#required' => TRUE
);
$form['description'] = array(
    '#type' => 'textfield',
    '#title' => 'Achievement Description',
    '#size' => 50,
    '#maxLength' => 400,
    '#required' => TRUE

);
$form['points'] = array(
    '#type' => 'textfield',
    '#title' => 'Point Award',
    '#size' => '20',
    '#maxlength' => '20',
    '#required' => TRUE
);
$form['add_button'] = array(
    '#type' => 'submit',
    '#value' => t('Add Achievement')
);
return $form;
    }

function achievementList_validate($form, &$form_state) {
$name = $form_state['values']['name'];

if($form_state['values']['name'] = '') {
    form_set_error('name', t('Achievement must have a name!'));
}
if($form_state['values']['description'] = '') {
    form_set_error('name', t('Please describe the achievement!'));
}
if(!($form_state['values']['points'] > 0)) {
    form_set_error('name', t('Achievement must be worth points!'));
}
}

function achievementList_submit($form, &$form_state) {
db_insert('achievements')
->fields(array(
'achvmntName' => $form_state['values']['name'],
'achvmntDesc' => $form_state['values']['description'],
'achvmntPts' => $form_state['values']['points'],
))
->execute();
}

Answer: You're not far off, a couple of things:

Creating a table like that in an init hook is definitely not recommended; Drupal provides hook_schema() so you can describe tables to the system. Uninstall and install your module again after implementing it and you'll see the table appear.
The reason your insert is failing is because you have a NOT NULL integer field which you're not providing (achvmntID). Drupal has the serial field type rather than an AUTO_INCREMENT key to get a serial field:
'achvmntID' => array(
  'type' => 'serial',
  'unsigned' => TRUE,
  'not null' => TRUE,
),

Answer: You need to make some changes like
It is better to create hook_schema as @Clive mention above.
For this recommended to create achievementList.install file in module
 <?php
/**
 * Implementation of hook_install().
 */
function achievementList_install() {
    //drupal_install_schema('achievementList');
    //for d6 uncomment above line
}

/**
 * Implementation of hook_uninstall().
 */
function achievementList_uninstall() {
    //drupal_uninstall_schema('achievementList');
    //for d6 uncomment above line
}

function achievementList_schema() {
    $schema['achievements'] = array(
    'description' => t('Achievement Fields'),
        'fields' => array(
                'achvmntID' => array(
                    'type' => 'serial',
                    'unsigned' => TRUE,
                    'not null' => TRUE
                ),
                'achvmntName' => array(
                    'type' => 'varchar',
                    'length' => '256',
                    'not null' => TRUE,
                    'default' => ''
                ),
                'achvmntDesc' => array(
                    'type' => 'varchar',
                    'length' => '256',
                    'not null' => TRUE,
                    'default' => ''
                ),
                'achvmntPts' => array(
                    'type' => 'int',
                    'not null' => TRUE,
                    'size' => 'normal',
                    'auto increment' => TRUE,
                ),
            ),
            'primary key' => array('achvmntID'),
        );
    return $schema;
}

function achievementList_menu($form, &$form_state) does not contain parameter.
Use function achievementList_menu()
function achievementList_validate($form, &$form_state) here "form" missing
use function achievementList_form_validate()
function achievementList_submit($form, &$form_state) here "form" missing
use function achievementList_form_form()
.module file
<?php
function achievementList_menu() {
$items = array();
$items['achievementList/addAchievement'] = array(
    'title' => 'Achievement Input',
    'description' => 'Input Achievement info to add achievement to database',
    'page callback' =>'drupal_get_form',
    'page arguments' => array('achievementList_form'),
    'access callback' => TRUE
);
return $items;
}

function achievementList_form($form, &$form_state) {
$form['name'] = array (
    '#type' => 'textfield',
    '#title' => 'Achievement Name',
    '#size' => '20',
    '#maxlength' => '20',
    '#required' => TRUE
);
$form['description'] = array(
    '#type' => 'textfield',
    '#title' => 'Achievement Description',
    '#size' => 50,
    '#maxLength' => 400,
    '#required' => TRUE

);
$form['points'] = array(
    '#type' => 'textfield',
    '#title' => 'Point Award',
    '#size' => '20',
    '#maxlength' => '20',
    '#required' => TRUE
);
$form['add_button'] = array(
    '#type' => 'submit',
    '#value' => t('Add Achievement')
);
return $form;
    }

function achievementList_form_validate($form, &$form_state) {
$name = $form_state['values']['name'];

if($form_state['values']['name'] = '') {
    form_set_error('name', t('Achievement must have a name!'));
}
if($form_state['values']['description'] = '') {
    form_set_error('name', t('Please describe the achievement!'));
}
if(!($form_state['values']['points'] > 0)) {
    form_set_error('name', t('Achievement must be worth points!'));
}
}

function achievementList_form_submit($form, &$form_state) {
//print_r($form_state);
//die();
db_insert('achievements')
->fields(array(
'achvmntName' => $form_state['values']['name'],
'achvmntDesc' => $form_state['values']['description'],
'achvmntPts' => $form_state['values']['points'],
))
->execute();
}

Comment: @cluckles are you able to fix the above issue?
Comment: Sort of. I get the table and everything going but it still won't submit. It looks like the submit function is not successfully being called. I cant echo or print_r anything out of it
Comment: Can you update your question what you have changed as i have mentioned in submit function you missed "form" word.
Comment: @Cluckles did you manage to get this work? I'm intrested of this kind of functionality too.
Comment: @hene Yes I did! It has been a while, but I think the issue was that it was recreating the table every time the page was refreshed(possibly because of the init function holding the raw create table functionality). Now I have an if statement in the init. If the table does not exist, create it. Now everything populates properly per the code above, with a couple tweaks to the UI!


Five lemma diagram without the middle vertical map

Question: \begin{matrix}
A_1 & \longrightarrow & A_2 & \longrightarrow & A_3 & \longrightarrow & A_4 & \longrightarrow & A_5 \\\ \downarrow h_1 & \ &\ \downarrow h_2 & \ &  \ & \ &\ \ \downarrow h_4 & \ &\ \ \downarrow h_5 \\B_1 & \longrightarrow & B_2 & \longrightarrow & B_3 & \longrightarrow & B_4 & \longrightarrow & B_5
\end{matrix}
I am looking for an example of a commutative diagram with exact rows and vertical maps $h_1, h_2, h_4, h_5$ isomorphisms for which there does not exist a map $h_3 : A_3\rightarrow B_3$ making the diagram commute.(Exercise 2.34 in An Introduction to Homological Algebra by Joseph J. Rotman)
I don't know how to start to construct such a diagram.
Answer: How about this:
$$\require{AMScd}
\begin{CD}
0 @>>> {\mathbb{Z}_2} @>>> {\mathbb{Z}_4} @>>> {\mathbb{Z}_2} @>>> 0 \\
@VVV @VVV @. @VVV @VVV \\
0 @>>> {\mathbb{Z}_2} @>>> {\mathbb{Z}_2\oplus\mathbb{Z}_2} @>>> {\mathbb{Z}_2} @>>> 0 \\
\end{CD}
$$
I haven't specified what any of the maps are, since you can probably guess. Let me know if you'd like me to be more explicit.


How to Add Another Physical Drive to Adaptec maxView RAID6 Logical Drive

Question: I have an ASR71605.  I've added another drive to the controller which shows up in max view as ready.  The logical drive is RAID 6 with 5 drives in it now. I'm adding this additional drive which is identical to the other 5. (same brand, same model, same size, 512k just like the other ones. The new drive is initialized
When I select the logical drive and choose expand, I choose RAID 6 again, and then on the next screen add the additional drive and then click next. On the next screen the manual says that I should be able to set the size, but it just says "New Size" without anywhere to enter anything and there is no next button or even cancel. I've tried in all supported browsers.
Also I've tried this command line:
sudo /usr/StorMan/arcconf modify 1 FROM 0 TO max 6 0 4 0 5 0 6 0 7 0 9 0 8
which I understand from the docs to mean on controller 1, logical drive 0, change the size to max, raid 6 and then a list of channel and device id in pairs. All on are on channel 0 and start at 4 and go to 9. 8 is the one being added.
It tells me:
The requested operation cannot be performed as one or more physical devices are not part of logical device.
I'm at a loss.
What am I doing wrong?
Answer: In case anyone else has this issue like I and the OP did, here is how I was able to get the expansion to work.  I have a ASR81605, so I'm not sure if it is the same with the 7 series, but the MaxView web interface has the exact same issue and the command line has the exact same error.  Also, I'm expanding a RAID 5, but hopefully this will work for everyone.
After fighting with this for hours, I finally found the latest (as of 07/04/2020) MaxView Storage Manager download for Windows x64 at https://adaptec.com/en-us/speed/raid/storage_manager/msm_windows_x64_v3_04_23699_zip.php.  You should probably search for the latest version as they may eventually fix the web version too.
Once I downloaded this update and installed it, the MaxView web interface is still broken in the same way, but amazingly I was able to start the expansion with the command line.
This exact arcconf.exe command that failed in the old version now successfully completed in version 3.04.23699 dated 01/27/2020:
<code>arcconf modify 1 from 0 to MAX 5 0 8 0 9 0 10 0 11 0 12 0 13 0 14 0 24 0 25
</code>
ID's 8-14 were the original and 24 and 25 were added.  Once the command completed, the MaxView web interface should the migration/expansion task running.
Comment: Wow, I have stepped on the same rake as well, but the fresh version of Storage Manager ( https://download.adaptec.com/raid/storage_manager/msm_linux_x64_v2_05_22932.tgz) works perfectly. :-)


Thin web server freezes / times out / stops responding periodically only on GCE not on AWS

Question: I'm using Nginx to forward requests to two Thin web server processes on ports 5000 and 5001. Every once in a while one of the Thin processes will stop responding to requests and Nginx will spit out the following error.
2014/11/28 21:40:05 [error] 21516#0: *1458 upstream timed out (110: Connection timed out) while reading response header from upstream, client: X.X.X.X, server: www.X.com, request: "HEAD / HTTP/1.1", upstream: "http://127.0.0.1:5001/", host: "www.example.com", referrer: "http://www.example.com/"

Thin will go out for a couple of minutes and start responding again on its own. When that one Thin process is in a frozen state it will also not respond to wget (e.g. wget http://127.0.0.1:5000) nor something like a request from Python (e.g. requests.get('http://127.0.0.1:5000')).
I set up three machines: two on Google Compute Engine - Debian 7.7 and Ubuntu 14.04 - and one AWS instance - Ubuntu 14.04. This error only happens on Google Compute Engine - Amazon Web Services does not have the same problem.
The software on all machines is as close to identical as can be. All operating systems are completely up to date through apt-get and the project is pulled from the same Git commit. I use the same deployment method on all three machines and they are all using the same Google Cloud SQL service.
I'm using Thin 1.5.1, Ruby 1.9.3-p448, and Rails 3.2.11. Updating Thin to 1.6.3 did not make a difference.
Answer: I worked on this issue for far too long.
The reason it was timing out was that Google Compute Engine closes idle TCP connections after 10 minutes. Thin's connection to the database was being axed by GCE and Thin would just hang on a read from the database. This would explain why AWS wasn't timing out even though it was connected to the same database.
Using the suggested keep-alive settings in the previous link seems to fix the problem.


Is there any way to change home page on small screen?

Question: I want to change the home page for small screen. Is there any way to set the front page according to the screen size by using hook_preprocess_page() or any other?
Comment: Use **Responsive Layout CSS** for your requirement. References
**[Responsive Theming](http://evolvingweb.ca/story/responsive-theming-how-apply-responsive-design-techniques-drupal-theme)**
Comment: I am using panels module and created a layout. I have to change different layout and can't be possible with media queries.
Comment: If you add the **responsive CSS** then the layout will adjust based on the screen size. No need to use **media queries**, just add the responsive CSS.
Comment: Don't give exact width just use percentage like `height: auto;max-width: 100%;` this will resize based on the screen size.
Comment: I know that, but my structure is something different.
Answer: To actually answer your question (Is there any way to set the front page according to the screen size). No. Especially as you mentioned that you don't want to use JavaScript in a comment to Inizio.
The server by itself has NO idea of the screen size of the client, so the only way to get that info back would be using JavaScript (either implementing drupal.settings or some kind of custom AJAX callback). Any module that you use would alos have to utilise JavaScript.
If you want to change the frontpage based on DEVICE, then that's more realistic, with something like Mobile Detect, Browscap, WURFL (or something similar) but again - not foolproof.
Comment: I used mobile detect thanx.
Answer: I used Mobile_Detect API and redirect the page using hook_preprocess_page in template.php.
Comment: May you expand your answer to make it more helpful for future readers?


Spring Boot Consider switching to 'HttpSecurity' Lambda DSL syntax

Question: My code is here. new AuthEntryPoint() code error to Consider switching to 'HttpSecurity' Lambda DSL syntax. How can i solved. pls help me
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.csrf().disable();

    http.httpBasic().authenticationEntryPoint(new AuthEntryPoint());

    http.authorizeHttpRequests()
            .requestMatchers(HttpMethod.POST, "/api/1.0/auth").authenticated()
            .and()
            .authorizeHttpRequests().anyRequest().permitAll();

    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    return http.build();
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }
}

i try google bard and chatgbt :(
Comment: Please post the exact text of the error, and explain what you were/are wanting the code to do.
Answer: Rewrite the above code similar to this and there will be no need of .and()
http.cors(cors -> cors.disable()).csrf(csrf -> csrf.disable())
        .authorizeHttpRequests(authorizeRequests ->
             authorizeRequests.antMatchers("/admins-only/**").hasAuthority(ADMIN)
                .antMatchers(HttpMethod.GET, "/**").permitAll()
                .anyRequest()
                .authenticated());

Similarly, you can try for the different configurations you already have.
If you want specifically for authEntryPoint
http.httpBasic(withDefaults()).authenticationEntryPoint(AuthEntryPoint::new)

Comment: @Burak Demirer I don't that could be an error, probably a warning if am not wrong or it should be a report by sonar
Comment: I don't think* that it*
Answer: your configuration style is still valid and supported. This is a warning from your IDE, not an error message. Adding lambdas was included in Spring Security 5.2 release and is intended to provide more flexibility, but their usage is optional.
As in the documentation:

The Lambda DSL was created to accomplish to following goals:

Automatic indentation makes the configuration more readable.
The is no need to chain configuration options using .and().
The Spring Security DSL has a similar configuration style to other Spring DSLs such as Spring Integration and Spring Cloud Gateway.

Check the article Spring Security - Lambda DSL in Spring Blog for more information.


What are use-cases of non-surjective total functions?

Question: Total functions are so "interesting" in Mathematics that the term "total" is often implicit. Therefore, it is common to use "function" to refer to a "total function" and only mention "partial function" or "potentially partial function" if the special need arises.
My question is, why don't surjective functions get the same benefit? For every function $f: A \to B$ there exists a unique function $f_s: A \to Im_f(A)$ such that $\forall x \in A. f(x) = f_s(x)$. And that function is surjective. For all purposes that I can think of, $f_s$ can do the job just fine. Is there any great loss in expressivity for common use cases that I am overlooking which warrant talking about non-surjective functions by default? What would be those use-cases?
Edit: I am not trying to challenge the status quo. I am just trying to find examples which emphasize the interest in the non-surjectivity of a function.
Comment: Functions spaces. Endomorphism groups.
Comment: Yes: what you suggest would be a royal pain in most settings. Typically we want to consider families of functions from some object (set, space, group, etc.) $X$ to some object $Y$, and the codomain $Y$ is more important than the ranges of the individual functions.
Comment: @BrianM.Scott That is my intuition as well. I am not challenging the status quo here. I am just trying to find concrete examples of such uses. Ideally ones which emphasize the non-surjectivity.
Answer: There are tons of situations where you care about functions that need not be surjective (but where you do care about their codomain).  Here are just a couple examples.
Given a set $X$, a metric on $X$ is a function $d:X\times X\to[0,\infty)$ which satisfies certain axioms that say that $d(x,y)$ behaves like the "distance" from $x$ to $y$.  A set $X$ together with a metric $d$ on $X$ is called a metric space.  Metric spaces play a huge role in modern mathematics and are ubiquitous in analysis and topology.  And there are plenty of natural and important examples of metrics which are not surjective.  For instance, if you take $X=[0,1]$ and $d(x,y)=|x-y|$, the image of $d$ is just $[0,1]$, rather than all of $[0,\infty)$.  If all functions were surjective, you would have to awkwardly define a metric to be a function from $X\times X$ to some subset of $[0,\infty)$, when that subset is usually of little interest.
Given a topological space $X$ and a point $x_0\in X$, the fundamental group of $X$ at $x_0$ is the set of continuous functions $f:[0,1]\to X$ such that $f(0)=f(1)=x_0$, modulo a certain equivalence relation (roughly, $f$ and $g$ are equivalent if you can "continuously deform" $f$ into $g$).  As the name suggests, this set has a natural group structure, and this group is hugely important in topology and geometry.  It is essential here that the codomain of $f$ is the space $X$ (the idea is that $f$ represents a "curve" drawn in the space $X$), but $f$ is not required to be surjective.  The definition of the equivalence relation also involves certain maps with codomain $X$ which are not required to be surjective.
The common theme in these examples is that we are not just talking about one particular function (for which you could always just change the codomain to make it surjective), but we are interested in studying an entire class of functions with some common properties.  One of the important common properties is that these functions take value in a certain set (such as $[0,\infty)$, or our chosen topological space $X$), but there is no reason for them to be surjective onto that set and they may have different images.  By allowing functions to not be surjective we can just specify their common codomain without caring about what their image is.
Comment: Your two definitions (for metric space and for topological space) seem to assume that $f$ and $f_s$ from the question are the same function. Otherwise your first definition excludes metrics like (for example) the geodesic distance on the unit sphere, whose codomain may be defined as $[0, π]$. In the Set category (in which your definitions live) it matters whether a morphism goes from $X \times X$ to $[0, π)$ or to $[0, \inf)$ because they would be two different morphisms.
Comment: But my point is that there is no reason to use the "surjective version" of the metric.  That is, it is at least as useful (if not more useful) to define the geodesic distance on the unit sphere to be a function $S^2\times S^2\to [0,\infty)$, rather than a function $S^2\times S^2\to [0,\pi]$.  For all purposes you ever care about, you want to treat all metrics the same regardless of whether their image is all of $[0,\infty)$ or just some subset of it, so you should define them all to have codomain $[0,\infty)$.
Comment: I am not sure you understood my point regarding category theory (which is at the essence of the question itself) if you claim "for all purposes you ever care about".
Comment: If you have a question about category theory, you should state clearly what that question is.  Your question as written is "why is it useful to define 'function' to mean 'not-necessarily-surjective function'?", and an answer to that question is obviously going to be about how functions are actually _used_ in math (hence, "for all purposes you ever care about").  This has basically nothing to do with category theory (except in that category theory is one branch of math).
Comment: Because otherwise, a function defined as $g_s: S^2 \times S^2 \to [0, π]$ could __not__ be a metric just because of its codomain being different than $[0, \infty)$. Even if otherwise it would satisfy the axioms a the metric. Such a function would only be a metric according to your definition if it was _the same function as_ $g: S^2 \times S^2 \to [0, \infty). \forall (x, y) \in S^2 \times S^2. g_s(x, y) = g(x, y)$ .
Comment: Yes, and that is the standard mathematical convention.  What's wrong with that?  Given any such function $g$, you can always compose it with the inclusion map $[0,\pi]\to[0,\infty)$ to get an actual metric.  And why do you want to define $g$ to have codomain $[0,\pi]$ instead of $[0,\infty)$ to begin with?  That doesn't make it any easier to define $g$ (if anything, it makes it harder...).
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/48590/discussion-between-victor-savu-and-eric-wofsey).


Conditional Probability and simultaneity of events

Question: We have two events $A$ and $B$, and i'm trying to understand why :
$P(B|A)P(A)=P(A|B)P(B)=P(A\cap B)$
What i think is that if we are searching the probability that two events A and B happen simultaneously, maybe the fact that A arrives before B causes a different probability respect the case in which B arrives before A.
Why am i wrong ?
Comment: In the probabilistic model the issue "simultaneous" is not captured.
Comment: This is best understood with cards imo. Consider picking two cards both spades out of 52 card deck. Intuitively we quickly say the probability of fhat happening is $13/52 \cdot 12/51$. Note that latter fraction depended on the fact that one spade was already chosen (and not replaced). This is precisely $P(A\cap B) = P(A) P(B|A)$ where $A$ is the event that a spade card was picked and $B$ is the event that another spade was picked.
Answer: @drhab pretty much explained it - you want both events to happen, this doesn't really mean that they happen simultaneously, there is no such thing as "time" when it comes to events - you can think of them as outcomes.
If you want informal explanation of the formula:
The probability of both $A$ and $B$ happening is the same as the probability of $A$ happening times the probability of $B$ happening given that $A$ happened. If you swap $A$ and $B$ you get the other identity.


@font-face is not working in Wordpress theme

Question: I'm currently working on my online portfolio. As you can see, @font-face runs like a charm. However, I'm now converting that static HTML into a dynamic Wordpress theme. Here's when @font-face stops working. I'll First explain how I've done it in static HTML/CSS.
I've installed the fonts in a folder called "fonts" in the main directory of my website (where index.html is sitting). With the following code I declare the font at the top of my css-file:
@font-face {
font-family: 'MaidenOrange';
src: url('fonts/MaidenOrange-webfont.eot');
src: url('fonts/MaidenOrange-webfont.eot?#iefix') format('embedded-opentype'),
     url('fonts/MaidenOrange-webfont.woff') format('woff'),
     url('fonts/MaidenOrange-webfont.ttf') format('truetype'),
     url('fonts/MaidenOrange-webfont.svg#MaidenOrangeRegular') format('svg');
font-weight: normal;
font-style: normal;
}

Then I call the font with font-family: MaidenOrange; in the rest of my css-file.
When I was converting this to Wordpress, I first copy pasted my whole stylesheet, and installed the "fonts" folder I created in the theme directory. That didn't work (it never does the first time). My first Google session gave me the impression it had to do with an absolute path vs. relative path problem. So I changed the @font-face declaration in my Wordpress Theme stylesheet to the following:
@font-face {
font-family: 'MaidenOrange';
src: url('<?php bloginfo('template_directory'); ?>/fonts/MaidenOrange-webfont.eot');
src: url('<?php bloginfo('template_directory'); ?>/fonts/MaidenOrange-webfont.eot?#iefix') format('embedded-opentype'),
     url('<?php bloginfo('template_directory'); ?>/fonts/MaidenOrange-webfont.woff') format('woff'),
     url('<?php bloginfo('template_directory'); ?>/fonts/MaidenOrange-webfont.ttf') format('truetype'),
     url('<?php bloginfo('template_directory'); ?>/fonts/MaidenOrange-webfont.svg#MaidenOrangeRegular') format('svg');
font-weight: normal;
font-style: normal;

}
That still isn't working! My theme just shows Arial (which is the second font I passed in the css). I've googled my ass off to solve this, but I'm getting nowhere. Any help would be much appreciated!
Answer: Maybe I'm misreading what you wrote, but I don't think you can have php code in your css file. Try moving your second code block into your theme's header.php file, wrapped in


How to get object in different language in Jena?

Question: I am pulling abstract information for http://dbpedia.org/page/The_Bronx and it gives me in German, but I would like to get in English. I cannot work with SPARQL.
Here is my code:
    Resource bronx=model3.getResource("http://dbpedia.org/resource/The_Bronx");
System.out.println("Description:"+bronx.getProperty(model3.getProperty("http://dbpedia.org/ontology/abstract")).getObject().toString());

And it prints this:
Description:Die Bronx [b????ks] ist seit dem 10. Januar 1874 der nördlichste Stadtbezirk (borough) von New York City. Er deckt sich mit Bronx County, dem am drittstärksten besiedelten County des Bundesstaates New York.@de
The question is how can I get this text in English (@en)?
Answer: The property abstract is multi-valued but you asked for one object so Jena picked one, which happened to be the German ("..." @de) one.  See listProperties and look for the objects which are @en.  Or use SPARQL.


Odds of getting at least 50% correct answers

Question: If I have four digits : xxxx that can take either 1 or 0. Then I have 16 permutations. (from binary 0000 to 1111). And when written down, we see that 11 of them have at least two 1's (68.75%), and 5 of them have at least three 0's (31.25%).
Suppose we have an exam where students should answer by "yes" or "no", and suppose that for a student to succeed he must answer correctly to at least 50% of the questions, and that students do not know the answers to the questions so they have to choose at random.
We know that in the case of one question the odds are 50%, for two questions the odds are 75%, for four questions (like the case of four digits) the odds are 68.75%.
How can we calculate the probability of getting at least 50% correct answers (1's) in case we have 100 questions for example? what equation to use in this case?
Thanks
Answer: For every case where a student answers the questions one way, there is an exact opposite case where as student answers every question the exact opposite way.  If the student answers exactly half correctly, the exact opposite will also have exactly half the answers correct.  Other wise one way will have more than half and the exact opposite will have less then half correct.
So the number of ways to get more than half correct-- is half of the number of ways to get more than half correct or less than half correct -- is one half of the total number of ways minus then number of ways to get exactly half correct.
The probability of at least half being correct is $\frac {\text{# more than half correct} + \text{# exactly half correct}}{\text{total # of ways}}=$
$\frac {\frac 12(\text{# total} - \text{# exactly half}) + \text{# exactly half}}{\text {# total}}=\frac 12\frac {\text{# total} + \text{# exactly half}}{\text {# total}}=$
$\frac 12 + \frac 12 P(\text {exactly half})$.
So if $n$ is odd then probability of at least half is exactly $1/2$ (which makes sense as either you have more than half or less than half and each equally likely.)
If $n = 2k$ then the number of ways to get exactly half is ${2k \choose k} = \frac {(2k)!}{k!k!}$.
So Probability of getting at least $k$ out of $2k$ questions right is $\frac 12 + \frac 12\frac {(2k)!}{k!k!2^{2k}}= 1/2 + \frac {n!}{(k!)^22^{n+1}}$
So $n = 2;k=1$, then $P = 1/2 + \frac {2!}{2^3} = 3/4$
If $n = 4; k=2$ then $P = 1/2 + \frac {4!}{2!2!2^5}= 1/2 + \frac {3}{16}=\frac{11}{16} = 68.75%$ etc.
If $n =100; k= 50$ then $P = \frac 12 + \frac{100!}{(50!)^22^{101}}=$
$\frac 12 + \frac{51*.....*100}{50!2^{101}}$.
Comment: Thank you so much for this useful answer +1 :)
Answer: Let $1$ be rewarded to every correct answer, $0$ for every wrong answer.
Then we need to find how many binary strings of $100$ numbers contain $50$ or more $1$'s.

For exactly $50$: There are $100$ slots for our numbers. Choose $50$ of them (the order you choose them does not matter), put $1's$ in them and $0's$ in the rest (there's only one way to do that, the order in which you put the ones into the chosen slots does not matter to us, similarly with the zeros as we will end up with the same exact  outcome).
There are ${100 \choose 50}(1)(1)={100 \choose 50}$ ways to do that.
For exactly $k$: There are $100$ slots for our numbers. Choose $k$ of them to put $1's$ and put $0's$ in the rest, again the order you chose slots does not matter as in the end we're going to put $1's$ in each one anyways and end with the same exact outcome.
There are ${100 \choose k}$ ways to do that.
We can have $50,51,....100$ ones, so we need to account for the number of ways we can get exactly each.

That number is $\sum_{k=50}^{100} {100 \choose k}$.
The total possibilities is $2^{100}$ because we either have a $0$ or a $1$ in each slot for two choices for every slot.
So the probability of getting at least half of the answers correct on a true/false test with exactly a hundred questions is,
$$P=\frac{\sum_{k=50}^{100} {100 \choose k}}{2^{100}}$$
$$=0.53979...$$
Comment: Thank you so much for your precious answer Ahmed, that was exactly what I was looking for, Best +1
Comment: Your welcome! ${}{}{}{}$


Create a Ubercart Drupal site to sell memberships?

Question: I want to create a website to sell licenses (not software licenses).
Basically, these licenses are sold in the form of packages for, say, package of 1 license or package of 2 licenses.
If a user comes to the site and buys a package with n number of licenses then n number of Drupal users will be created.
The created users can have different role types to allow different content to be accessible for different users.
Is it possible to achieve that with some Drupal 7 modules?
I did some research and found that it is possible to sell roles/subscriptions using the Ubercart module but I don't know how to create users that way -- with different roles after buying license package(s).
Answer: I was also trying to do this fairly recently.  Found a nice tutorial on Site Membership and Ubercart from Torontowebsitedeveloper.
https://www.youtube.com/watch?v=vbeqlNjBvwQ


Ocaml's named parameters

Question: Trying to understand Ocaml's mechanism for named parameters. I understand the basics, but the doc shows an example like this:
# let f ~x ~y = x - y;;
val f : x:int -> y:int -> int = <fun>

# let x = 3 and y = 2 in f ~x ~y;;
- : int = 1

What exactly is going on when only the tilde is used in application? Is it just shorthand for ~x:x, similar to definitions? If so, can someone explain why this:
# ListLabels.fold_left;;
- : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a = <fun>

# let add = (+) and i = 0
in ListLabels.fold_left ~add ~i [1;2;3];;

produces
- : f:((add:(int -> int -> int) -> i:int -> 'a) ->
   int -> add:(int -> int -> int) -> i:int -> 'a) ->
init:(add:(int -> int -> int) -> i:int -> 'a) -> 'a = <fun>

Answer: The man says
"beware that functions like ListLabels.fold_left whose result type is a type variable will never be considered as totally applied."
Here is what happens in your example. Beware it's a bit involved.
# ListLabels.fold_left;;
- : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a = <fun>

is just the classic use: ListLabels.fold_left taks 3 arguments, namely a function labeled f, an initializer init and a list.
Now, in
let add = (+) and i = 0
in ListLabels.fold_left ~add ~i [1;2;3];;

the application ListLabels.fold_left ~add ~i [1;2;3] is considered incomplete (as the man says). That means that `ListLabels.fold_left receives first its unamed argument, [1;2;3] and returns a function of type f:('a -> int -> 'a) -> init:'a -> 'a. Let us call this function foo.
Since you're giving two named arguments, labeled add and i, the type 'a is inferred to be a functional type, of type add:'c -> ~i:'d -> 'e.
Based on the type of the variables add and i, the type 'c must be int -> int -> int, and 'd must be int.
Replacing those values in the type 'a, we derive that the type 'a is add:(int -> int -> int) -> i:int -> 'e.
And replacing this in the type of foo (I'm glad there is copy-pasting ;-), its type is
f:((add:(int -> int -> int) -> i:int -> 'e)
    -> int
    -> (add:(int -> int -> int) -> i:int -> 'e))
-> init:(add:(int -> int -> int) -> i:int -> 'e)
-> (add:(int -> int -> int) -> i:int -> 'e)

Removing unecessary parentheses, and alpha converting (i.e. renaming) 'e to 'a, we get
f:((add:(int -> int -> int) -> i:int -> 'a)
    -> int
    -> add:(int -> int -> int) -> i:int -> 'a)
-> init:(add:(int -> int -> int) -> i:int -> 'a)
-> add:(int -> int -> int) -> i:int -> 'a

That is the type of foo. But remember that you are passing two arguments to foo, labeled ~add and ~i. So the value you get at the end is not of type add:(int -> int -> int) -> i:int -> 'a but indeed of type 'a. And the whole type of your example is, as returned by the compiler,
f:((add:(int -> int -> int) -> i:int -> 'a)
    -> int
    -> add:(int -> int -> int) -> i:int -> 'a)
-> init:(add:(int -> int -> int) -> i:int -> 'a)
-> 'a

Comment: Wow - what a mess! It actually does make sense though, thank you so much!

Ocaml's named parameters


Show whether $\sum \limits_{k=1}^\infty \frac{k!}{k^k}$ and $\sum \limits_{k=1}^\infty \frac{1}{\sqrt{(k+1)k}}$ converge.

Question: title, I'm not sure how to reason about series converging or not (outside of using the calculus tests, but this is real analysis...) and intuition isn't enough for a rigorous proof.
Comment: Hint for second. $k(k+1)\le(k+1)^2$
Comment: @tetori is this valid for all k?
Comment: yes. This inequality is vaild if $k\ge 1$.
Comment: @terribleatmath. Even if the inequality is valid only after some $k>N$ the divergence would be still true
Comment: @boywholived can you explain why this series diverges?
Comment: @terribleatmath. If you can tell where you are facing problem I can help.
Comment: Well, im confused as to how I should be thinking of this in an analysis class. I have a number of tools I already know of to consider this (ratio test, comparison test, etc) but thinking purely definition-wise, I could consider partial sums and look for limits, etc. What do you do?
Answer: Hint for first series If $k>3$ then
$$
\frac{k!}{k^k} =\frac{k}{k}\cdot \frac{k-1}{k}\cdots \frac{2}{k}\frac{1}{k}\le\> ???
$$
give a appropriate upper bound and use comparison test.
Possible upper bound (If you bring your mouse pointer at below then you can see this.)

 $$\frac{k}{k}\cdot\frac{k-1}{k}\cdots\frac{3}{k}\cdot \frac{2}{k}\cdot\frac{1}{k} \le 1\cdot 1\cdots 1\cdot\frac{2}{k}\cdot  \frac{1}{k}$$
Comment: thanks! also, you have a typo in your answer: "approciate" should be "appropriate"
Answer: $\frac{(k+1)!}{(k+1)^{k+1}}/\frac{k!}{k^k}=\frac{k!}{(k+1)^{k}} \times \frac{k^k}{k!}=\left(\frac{k}{k+1}\right)^k \to 1/e <1$
The series is convergent by d'Alambert test.
Comment: never heard of the d'Alambert test -- what is it?
Comment: This is what you call ratio test.


Data type of a MAC address?

Question: I have this JSON data file
[{"entityClass":"DefaultEntityClass","mac":["00:00:00:00:00:02"],"ipv4":[],"vlan":[],"attachmentPoint":[{"switchDPID":"00:00:00:00:00:00:00:02","port":1,"errorStatus":null}],"lastSeen":1398463052792}]

and I want to get the "mac". but I don't know which data type I have to use, since the server
says that it is neither a long nor a string value. Which datatype is this "mac" ?.
my code:
try {
        JSONArray arraydevice = new JSONArray(devicesJson);
        JSONObject obj = arraydevice.getJSONObject(0);
        long mac = obj.getLong("mac");
        System.out.println("The mac address of the host is " + mac);

    }
catch (JSONException e) { // TODO Auto-generated catch block
        e.printStackTrace();
    }

Thanks in advance
Comment: Do you really have to use org.json? :/ It's the "worst" JSON library in existence
Comment: I just found it while googling. Why is it considered bad ?.
Answer: ["00:00:00:00:00:02"]

is an array with one element, and that element is a string.
String mac = obj.getJSONArray("mac").getString(0);

though it would probably be a good idea to check the .length() of the array before you try and get anything out of it, in case it turns out to be empty.
Answer: From the JSON Schema the MAC Address looks like an Array of String. However if you have a Class structure defined on the server , you can use that for converting the JSON into an object.

Data type of a MAC address?


Evaluate limit of an integral: $\lim_{x\to \infty }\frac{1}{x}\int _0^x\:\frac{dt}{2+\cos t}$

Question: $$\lim _{x\to \infty }\frac{1}{x}\int _0^x\:\frac{dt}{2+\cos t}$$
Can someone explain to me if it is a limit of type $\frac{\infty}{\infty}$ or not and why ? I considered it to be one, applied L'Hospital and got $\cos\infty$, which would mean that the limit does not exist, but the answer is $\frac{1}{\sqrt{3}}$
Comment: Thats not an indeterminate to apply lhospital. Try half angle to convert it to tangent function.  then wierstrass substitution then integrate it and get the result
Comment: You forgot one requirement of L'Hopital's rule: The limit of $f'(x)/g'(x)$ **must exist** in order to apply the rule and conclude that $\lim f/g = \lim f'/g'$. As you've noted, $\lim f'/g'$ doesn't exist in this case. This means that you can't apply L'Hopital's rule. It **doesn't** mean that $\lim f/g$ doesn't exist.
Comment: +1 for coming up with a limit which beats the L'Hospital's rule. The hypotheses of the rule are true here (denominator tends to $\infty$) but it is not helpful because the limit of $f'/g'$ does not exist.
Answer: $f(t)=\frac{1}{2+\cos(t)}$ is a positive, bounded and $2\pi$-periodic function. It follows that the mean value of $f$, i.e. the wanted limit, equals the mean value of $f$ over one period:
$$ \lim_{x\to +\infty}\frac{1}{x}\int_{0}^{x}\frac{dt}{2+\cos t} = \frac{1}{2\pi}\int_{0}^{2\pi}\frac{dt}{2+\cos t} = I $$
and through the substitution $t\mapsto 2t$ we have:
$$ I = \frac{1}{\pi}\int_{0}^{\pi}\frac{dt}{1+2\cos^2(t)}=\frac{2}{\pi}\int_{0}^{\pi/2}\frac{dt}{1+2\cos^2(t)} $$
then by setting $t=\arctan(u)$:
$$ I = \frac{2}{\pi}\int_{0}^{+\infty}\frac{du}{3+u^2}=\color{red}{\frac{1}{\sqrt{3}}}.$$
Comment: @AhmedS.Attaalla: the average value of $\cos x$ is zero hence the average value of $\cos(x)+2$ is $2$. Assume that $x=2\pi k+\tau$ and a $2\pi$-periodic bounded function has mean value over its period equal to $M$. Then $$\frac{1}{x}\int_{0}^{x}f(t)\,dt = \frac{1}{2\pi k+\tau}(2\pi k M+ B)$$ approaches $M$ as $x\to +\infty$.
Comment: @RafaelWagner: the (integral) mean value of a bounded, continuous, $2\pi$-periodic function is its mean value over $(0,2\pi)$, that is quite trivial. Typo fixed.
Comment: @Liviu: $\cos^2(x)$ is a symmetric function with respect to $x=\frac{\pi}{2}$ and $\cos^2\arctan(t) = \frac{1}{t^2+1}$ is a useful trigonometric identity.
Comment: @Liviu: if $f\left(\frac{\pi}{2}-x\right)=f\left(\frac{\pi}{2}+x\right)$, then $$\int_{0}^{\pi} f(x)\,dx = 2 \int_{0}^{\pi/2} f(x)\,dx.$$ Draw a graph and shade some regions: it will become obvious.
Comment: where is the $1/x$ of the question?
Comment: Where can I find proof that this works for a positive, bounded, $2\pi$.
Comment: @AhmedS.Attaalla Because it is bounded, and furthermore, periodic.  Note that: $$\int_0^x\frac{dt}{2+\cos(t)}=ax'+\int_0^{x'}\frac{dt}{2+\cos(t)}$$where $a=\int_0^{2\pi}\frac{dt}{2+\cos(t)}$. and $x'=x\pmod{2\pi}$.
Comment: Why is $\frac{1}{\pi}\int_{0}^{\pi}\frac{dt}{1+2\cos^2(t)}=\frac{2}{\pi}\int_{0}^{\pi/2}\frac{dt}{1+2\cos^2(t)}$ and how did you write the $\cos$ after substitution with $\arctan$
Comment: Thank you so much for responding to my question @JackD'Aurizio
Comment: You actually showed that a result is "quite trivial" by proving it in comments. It it were non-trivial it would need an answer. +1 for your answer as well as the comments dealing with the trivial result.
Comment: @JackD'Aurizio I stil don't understand the $\cos^2(x)$ part... I understood that $\cos(x)=\cos(-x)$ and that $\cos^2(x)$ is symmetric with respect to $x = \pi/2$ but why is that $2 \cdot$ in front of the integral  ? Can you explain when this applies and how it's done, please ?


Give an external IP to a Virtual Machine

Question: I've a Windows Server 2008 R2 with 8 public IPs assigned (fixed), recently i've installed VirtualBox and create a VirtualMachine with OpenBSD.
I would like to give one IP to the VM, but every try that i tested this fails.
In Windows there's a public IP 22.214.171.124 (for this example), that IP i've configured in OpenBSD VM at the /etc/hostname.em0 file, which content is:
inet xxx.xxx.xxx.208 255.255.255.255

/etc/mygate file is:
zzz.zzz.zzz.65          Same gateway ip than windows

i put the same mask that is assigned in windows for each IPs.
At windows i've created rules for firewall to VirtualBox.exe application.
In VirtualBox VM's setting: Network the current configuration:
Attached to: Bridged Adapter
Name: Intel(R) 82574L Gigabit Networkd Connection
Advanced:
    Promiscuous Mode: Deny
    Cable connected is checked.

i can't figure out what is missing... if is needed some information, ask please, i'll give such information.
thanks!!
New information:
i've removed IP from windows config
Windows Config:
IPv4 Address:     xxx.xxx.xxx.209
IPv4 Subnet Mask: 255.255.255.255

IPv4 Address:     xxx.xxx.xxx.210
IPv4 Subnet Mask: 255.255.255.255

IPv4 Address:     xxx.xxx.xxx.211
IPv4 Subnet Mask: 255.255.255.255

IPv4 Address:     xxx.xxx.xxx.212
IPv4 Subnet Mask: 255.255.255.255

IPv4 Address:     xxx.xxx.xxx.213
IPv4 Subnet Mask: 255.255.255.255

IPv4 Address:     xxx.xxx.xxx.214
IPv4 Subnet Mask: 255.255.255.255

IPv4 Address:     xxx.xxx.xxx.215
IPv4 Subnet Mask: 255.255.255.255

IPv4 Address:     yyy.yyy.yyy.83
IPv4 Subnet Mask: 255.255.255.224

IPv4 Default Gateway  zzz.zzz.zzz.65

IPv4 DNS Servers   hhh.hhh.hhh.202
                   hhh.hhh.hhh.200

The IP xxx.xxx.xxx.208 i've removed from windows.
If i set the ip xxx.xxx.xxx.208 in windows, when i start openbsd, an error message apear: duplicate IP address xxx.xxx.xxx.208
Comment: That doesn't sound right.  What's the subnet mask of the gateway?
Comment: If you configure the IP on the BSD VM, you'll have to remove it from the Windows PC.  Since the network adapter in the VM is bridged, it's treated just like another device on the network.
Comment: yeah, I forgot to say that, but still does not work.
Comment: Can you ping any of the Windows IPs from BSD or vice versa?
Comment: no... pinging using hostname or ip address doesn't work
Comment: I think you need to use the proper subnet mask in the hostname.em0 file - not 100% sure, as I'm not familiar with BSD, but try it.  If that's correct I'll submit as answer.
Comment: i use the same mask that windows for each IP: 255.255.255.255
Answer: Based on the info above, it appears that your subnet mask is incorrect.  Based off of 8 usable IPs, your subnet mask should probably be 255.255.255.240.  Try that.  You'll want to change it on the Windows host as well.
Comment: I concur, the netmask 255.255.255.255 is probably wrong, with that mask, the host will only be able to communicate with itself. Use the same netmask that you're using for an already-working IP on the windows server.
Comment: The problem was the netmask, I took one of the server's secondary IPs (one in the same subnet as the VM: xxx.xxx.xxx.209) and changed the netmask to 255.255.255.248, then on VM put that IP as gateway. I also had to enable the "Rounting and Remote Access" service on the windows server.


The Security Implications of Implementing Facebook Connect on your Website

Question: The organization I work for is rolling out a Wordpress Multi-User install for it's members to have a "Personal Mini-Website/Blog," that will be hosted on our main organization's website.  They are looking at using a Wordpress plugin which would allow users to comment on the blogs via Facebook Connect.
I wanted to hear your thoughts on what the risks of using Facebook Connect in this type of a scenario would be.  (Or any scenario, really)
From both a SysAdmin & a Dev viewpoint.
Comment: It means Facebook can impersonate any of your users, and if a flaw in their login process is ever discovered then it may be exploited by a malicious person to login as anyone they want.
Answer: My understanding of Facebook connect is that it adds an option for Facebook users to login to your blog and make comments.  The API also lets you see your WP comments in Facebook (and I believe viceversa).  I don't think this would be a security issue unless you were planning in making some blogs restricted.
If your concern is more about the actual API and how secure it is, you might want to post this in StackOverflow (...as it would be more of a programmer type question)


Is there a way to view logs from three different remote nodes on one tab on Chainsaw

Question: Is there a way to view logs from three different remote nodes on one tab? Right now I get three tabs open for three nodes.
Here is my log4j config for the same app deployed on three different linux boxes
<code>log4j.appender.HUB=org.apache.log4j.net.SocketHubAppender
log4j.appender.HUB.port=39867
log4j.appender.HUB.LocationInfo=true
log4j.appender.HUB.Threshold=INFO
log4j.appender.HUB.application=remotehost
</code>
Answer: Yes.
You can create a new tab from existing events via the 'view, create tab from expression' menu item - it will combine events matching the expression into a new tab.  As new events which match the expression arrive, they will also be added to the new tab.
This isn't persistent - restart Chainsaw and you have to go through that process again.
If you want to permanently change things, you can modify the 'tab name/event routing expression' under Chainsaw preferences.  As events come in, the expression in the 'event routing expression' box is resolved with the values for the current event.  If a tab exists with that tab name, the events are added to that tab.  If no tab exists, a new tab is created.
An example expression you could use in the 'view, create tab from expression' expression box (assuming the events you are interested in all have an 'application' column with 'remoteHost' as the value in that column):
PROP.application=remoteHost
This second option just builds a string - isn't really an expression like the search and filter expression syntax...
An example tab name/event routing expression you could use to get all events with 'remoteHost' as the application on a tab called 'remoteHost':
PROP.application
By the way, I would suggest checking out the latest developer snapshot of Chainsaw, available here:
http://people.apache.org/~sdeboy


Generating 3 columns from one with .apply on dataframe

Question: I want to extract some data from each row, and make that new columns of existing or new dataframe, without repeatedly doing the same operation of re. match.
Here's how one entry of the dataframe looks:
00:00 Someones_name: some text goes here

And i have a regex that successfully takes 3 groups that I need:
re.match(r"^(\d{2}:\d{2}) (.*): (.*)$", x)

The problem I have is, how to take matched_part[1], [2], and [3] without actually matching for every new column again.
The solution that I don't want is:
new_df['time'] = old_df['text'].apply(function1)`
new_df['name'] = old_df['text'].apply(function2)`
new_df['text'] = old_df['text'].apply(function3)`

def function1(x):
  return re.match(r"^(\d{2}:\d{2}) (.*): (.*)$", x)[1]

Answer: you can use str.extract with your pattern
df[['time','name', 'text']] = df['col1'].str.extract(r"^(\d{2}:\d{2}) (.*): (.*)$")
print(df)
#                                        col1   time           name  \
# 0  00:00 Someones_name: some text goes here  00:00  Someones_name

#                   text
# 0  some text goes here