user registration redirect for custom form drupal 6

Question: I have worked on a solution which will redirect from the user registration form to my own form. My own form can be reached by typing the website name testweb/my_module/form. Here is the code of my module using a form_alter. When I run the function it doesn't redirect to my own form. Could someone advice me why it is not working?
function redirect_custom_reg_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register') {
    $form_state['redirect'] = 'my_module/form';
  }
}

Answer: It is $form['#redirect'], not $form_state['redirect'] in this case because user_register_submit() unsets $form_state['redirect'] (well, sets it to '') when it is confident that all is good with its part in the registration process...and hence allowing an alter to add in a #redirect.
Comment: Both of these are valid, see kiamlaluno's answer
Answer: Basing on the comment you left for this question, I get you want to show your own form; in this case, setting $form_state['redirect'], or $form['#redirect'] is not what you want to do, as the redirection take place after the form has been submitted, which means the form validation handlers, and the form submission handlers have been already executed.
From the user's point of view what would happen is:

The users see the default registration form used by Drupal.
The users enter the required information.
If they don't correctly fill the fields, the form is shown them again, together a list of error messages.
If they correctly fil the fields, the data is saved, and they are redirected to the page that has been set through $form_state['redirect'], or $form['#redirect'].

What you want is altering the registration form, and for that there are two cases:

You want to completely alter the existing registration form.
You want to simply add some fields to the existing registration form.

Completely altering the existing registration form
In this case, you implement [hook_menu_alter()][1] to alter the menu callback used when the registration form is needed.
The menu callback for the registration form is defined in [user_menu()][2] using the following array:
  $items['user/register'] = array(
    'title' => 'Create new account',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_register_form'),
    'access callback' => 'user_register_access',
    'type' => MENU_LOCAL_TASK,
  );

To alter it, you could use the following code in your module (replace "mymodule" with the short name if your module):
function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_user_register_form');
  }
}

mymodule_user_register_form() is the form builder function that return your registration form. In this case, you are completely overwriting the default registration form, which means Drupal doesn't have control over the registration process, and your code needs to handle the full process.
Adding some fields to the existing registration form
In this case, you implement [hook_form_FORM_ID_alter()][3] to add new fields to the registration form. This is what done from the System module (part of Drupal), which uses the following code to add the field that allows the users to set they timezone.
function system_form_user_register_form_alter(&$form, &$form_state) {
  if (variable_get('configurable_timezones', 1)) {
    if (variable_get('user_default_timezone', DRUPAL_USER_TIMEZONE_DEFAULT) == DRUPAL_USER_TIMEZONE_SELECT) {
      system_user_timezone($form, $form_state);
    }
    else {
      $form['account']['timezone'] = array(
        '#type' => 'hidden',
        '#value' => variable_get('user_default_timezone', DRUPAL_USER_TIMEZONE_DEFAULT) ? '' : variable_get('date_default_timezone', ''),
      );
    }
    return $form;
  }
}

In Drupal 6, you would implement [hook_user()][4]; when $op (the first parameter) is equal to 'register', the registration form is going to be shown, and the hook implementation needs to return the form fields to inject in the form.
In Drupal 6, the function that has the same purpose of system_form_user_register_form_alter() is system_menu().
function system_user($type, $edit, &$user, $category = NULL) {
  if ($type == 'form' && $category == 'account') {
    $form['theme_select'] = system_theme_select_form(t('Selecting a different theme will change the look and feel of the site.'), isset($edit['theme']) ? $edit['theme'] : NULL, 2);

    if (variable_get('configurable_timezones', 1)) {
      $zones = _system_zonelist();
      $form['timezone'] = array(
        '#type' => 'fieldset',
        '#title' => t('Locale settings'),
        '#weight' => 6,
        '#collapsible' => TRUE,
      );
      $form['timezone']['timezone'] = array(
        '#type' => 'select',
        '#title' => t('Time zone'),
        '#default_value' => strlen($edit['timezone']) ? $edit['timezone'] : variable_get('date_default_timezone', 0),
        '#options' => $zones,
        '#description' => t('Select your current local time. Dates and times throughout this site will be displayed using this time zone.'),
      );
    }

    return $form;
  }
}

The function uses a parameter list that is different from the one reported for hook_user(), which is hook_user($op, &$edit, &$account, $category = NULL); what system_user() calls $type is called $op in hook_user() documentation.
Comment: I tried using your method but for some reason it does not  seem to redirect I want my own form to be activate when the user clicks on the register new link . Then when the link is chosen I want it to redirect to my own form. I did try and add the weight but I am not sure I had the syntax correctly
Answer: Alternatively, you can utilize the LoginToboggan module. Here is a quote about it (from the module's project page):

... offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

Allow users to login using either their username OR their e-mail address.
Allow users to login immediately.
Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
Customize the registration form with two e-mail fields to ensure accuracy.
Optionally redirect the user to a specific page when using the 'immediate login' feature.
Optionally redirect the user to a specific page upon validation of their e-mail address.
Optionally display a user message indicating a successful login.
Optionally combine both the login and registration form on one page.
Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).
Integrates with Rules module to do various tasks when a user validates via email validation process.
Answer: you can use rules module to make actions after events, including redirect user after registration.


Finding the $n$th term of a particular sequence

Question: I have a sequence on $\mathbb{N}\times\mathbb{N}$ whose $n$th term I wish to find out. In fact, any information regarding this sequence will be helpful. The sequence is denoted as $(x_1,y_1),(x_2,y_2),(x_3,y_3)\cdots$ and is constructed as follows:

Set $x_1=1$.
Given that $x_i$ has been constructed let $y_i=x_i+2i$.
Assuming $(x_i,y_i)$ has been constructed we define $x_{i+1}$ as follows: Consider the multiset $M$ of all the numbers of the type $x_j$ or $y_j$, with $1\le j\le i$. Let $m$ be the least odd number in $\mathbb{N}$ which has multiplicity at most $1$ in $M$. Define $x_{i+1}=m$.
Go to step 2.

Note that the difference of the two coordinates successively yields the even numbers, and all odd numbers are used exactly twice.
So the initial few terms are : $(1,3),(1,5),(3,9),(5,13),(7,17),(7,19),(9,23),(11,27),(11,29)\cdots$.
Any help will be appreciated.
Comment: This is an unusual way to build a sequence.  What is its origin?
Comment: @vadim123: I am trying to construct a specific mathematical design. The sequence is going to be used in that.
Comment: Probably of no use, but what if you consider the sequence $\bigl(\frac{x_i-1}2,\frac{y_i-1}2\bigr)_i$? Perhaps it has a more visible pattern.
Answer: Earlier Answer without proof:
$x_n=2\lfloor \frac{n}{\sqrt{2}}-\frac{1}{2}\rfloor+1$ or equivalently $x_n=$ $n/\sqrt{2}$ rounded to nearest integer, doubled minus 1. $y_n=x_n+2n$.
I haven't been able to prove this despite speding quite some time.
Added Proof:
The given sequence can be equivalently defined as:
$x_1=1,x_2=1$ and for $n>1$
$x_{n+1} = \left\{\begin{array}{1}
x_n+2\text{ if }x_n=x_{n-1}\text{ or }x_n=x_j+2j\text{ for some }j \in \mathbb{N}\\x_n \text{ otherwise}\end{array}\right. $
We use induction to show that $x_n=a_n\equiv2\lfloor \frac{n}{\sqrt{2}}-\frac{1}{2}\rfloor+1$. The initial conditions hold as $a_1=a_2=1=x_1=x_2$. Suppose $a_i=x_i$ for $i=1,...,n>1$. We will show that $a_{n+1}=x_{n+1}$. Define $f(x)=\frac{x}{\sqrt{2}}-\frac{1}{2}$ so $a_n=2\lfloor f(n) \rfloor+1$.
Let $f(n)=\frac{n}{\sqrt{2}}-\frac{1}{2}=k+r$ where $k\in \mathbb{N},0<r<1$. Note $a_n=2k+1$ and $r$ is irrational.
Consider $j=\lfloor \frac{n}{\sqrt{2}+1}+\frac{1}{2}\rfloor=\lfloor (\sqrt{2}-1)n+\frac{1}{2}\rfloor=\lfloor 2(\frac{1}{2}+k+r)-n+\frac{1}{2}\rfloor= 2k-n+1+\lfloor2r+\frac{1}{2}\rfloor$. Now we consider 4 exclusive and exhaustive cases.
Case 1: $0<r<\frac{1}{4}$.
We have $k-1<k+r-\frac{1}{\sqrt{2}}=f(n-1)<k$ so $a_{n-1}=2k-1=a_n-2$ and $k<f(n+1)=k+r+\frac{1}{\sqrt{2}}<k+\frac{1}{4}+\frac{1}{\sqrt{2}}<k+1$ so $a_{n+1}=2k+1=a_n$. Also, $j=2k-n+1$ so $f(j)=\sqrt{2}k-\frac{n}{\sqrt{2}}+\frac{1}{\sqrt{2}}-\frac{1}{2}=(n-\frac{1}{\sqrt{2}}-r\sqrt{2})-(\frac{1}{2}+k+r)+\frac{1}{\sqrt{2}}-\frac{1}{2}=n-k-1-r(\sqrt{2}+1)$.
Using $0<r<\frac{1}{4}$, $\lfloor f(j) \rfloor = n-k-2$ and $\lfloor f(j+1) \rfloor = \lfloor f(j)+\frac{1}{\sqrt{2}} \rfloor = n-k-1$. That is, $j+\lfloor f(j) \rfloor = k-1$ and $(j+1)+\lfloor f(j+1) \rfloor = k+1$. So $\not\exists i \in \mathbb{N}$ such that $i+\lfloor i \rfloor=k$ or equivalently $x_i+2i=x_n$. By definition, $x_{n+1}=x_n=a_n=a_{n+1}$.
Case 2: $\frac{1}{4}<r<1-\frac{1}{\sqrt{2}}$.
Again, we have $k-1<k+r-\frac{1}{\sqrt{2}}=f(n-1)<k$ so $a_{n-1}=2k-1=a_n-2$ and $k<f(n+1)=k+r+\frac{1}{\sqrt{2}}<k+1$ so $a_{n+1}=2k+1=a_n$. This time, $j=2k-n+2$ so $f(j)=\sqrt{2}k-\frac{n}{\sqrt{2}}+\sqrt{2}-\frac{1}{2}=(n-\frac{1}{\sqrt{2}}-r\sqrt{2})-(\frac{1}{2}+k+r)+\sqrt{2}-\frac{1}{2}=n-k-1+\frac{1}{\sqrt{2}}-r(\sqrt{2}+1)$.
Using $\frac{1}{4}<r<1-\frac{1}{\sqrt{2}}$, $\lfloor f(j) \rfloor = n-k-1$ and $\lfloor f(j-1) \rfloor = \lfloor f(j)-\frac{1}{\sqrt{2}} \rfloor = n-k-2$. That is, $j+\lfloor f(j) \rfloor = k+1$ and $(j-1)+\lfloor f(j-1) \rfloor = k-1$. So $\not\exists i \in \mathbb{N}$ such that $i+\lfloor i \rfloor=k$ or equivalently $x_i+2i=x_n$. By definition, $x_{n+1}=x_n=a_n=a_{n+1}$.
Case 3: $1-\frac{1}{\sqrt{2}}<r<\frac{1}{\sqrt{2}}$.
We have $k-1<k+r-\frac{1}{\sqrt{2}}=f(n-1)<k$ so $a_{n-1}=2k-1=a_n-2$ and $k+1<k+r+\frac{1}{\sqrt{2}}=f(n+1)<k+2$ so $a_{n+1}=2k+3=a_n+2$. As in Case 2, $j=2k-n+2$ so $f(j)=\sqrt{2}k-\frac{n}{\sqrt{2}}+\sqrt{2}-\frac{1}{2}=(n-\frac{1}{\sqrt{2}}-r\sqrt{2})-(\frac{1}{2}+k+r)+\sqrt{2}-\frac{1}{2}=n-k-1+\frac{1}{\sqrt{2}}-r(\sqrt{2}+1)$.
Using $1-\frac{1}{\sqrt{2}}<r<\frac{1}{\sqrt{2}}$, $\lfloor f(j) \rfloor = n-k-2$ so $j+\lfloor f(j) \rfloor = k$ or equivalently $x_j+2j=x_n$. By definition, $x_{n+1}=x_n+2=a_n+2=a_{n+1}$.
Case 4: $\frac{1}{\sqrt{2}}<r<1$.
We have $k<k+r-\frac{1}{\sqrt{2}}=f(n-1)<k+1$ so $a_{n-1}=2k+1=a_n$ and $k+1<k+r+\frac{1}{\sqrt{2}}=f(n+1)<k+2$ so $a_{n+1}=2k+3=a_n+2$. Since, $x_n=a_n=a_{n-1}=x_{n-1}$, by definition, $x_{n+1}=x_n+2=a_n+2=a_{n+1}$.
Comment: Mostly guesswork. $x_{n+1}-x_n$ equals $0$ or $2$ and for large $N$, $(x_{N+1}-x_1)/N$ is approximately $\sqrt{2}$,  generating values based on your algorithm. The formula I gave produces odd numbers that change by $0$ or $2$ and does not result in more than 2 repetitions of a value. The problem is showing that a certain value occurs $1$ or $2$ times exactly as it should according to your algorithm. That is, decimal part of $n/\sqrt{2}-0.5$ is between $1-1/\sqrt{2}$ and $1/\sqrt{2}$ precisely when there exists $j$ such that $\lfloor n/\sqrt{2}-0.5 \rfloor = \lfloor j/\sqrt{2}-0.5 \rfloor + j$.
Comment: Thanks. Could you tell me how you arrived at this expression initially?
Comment: I am unable to understand how your equivalent definition is a good definition. It does not seem to unambiguously define $x_{n+1}$.
Comment: @Shahab I am not sure why you consider the definition ambiguous. Does qualifying $j<n$  help? Note $x_n$   is a non-decreasing sequence so $x_n =x_j +2j$  is not possible for $j\ge n$.


AngularJS service: gets error has no method 'save'

Question: I'm using AngularJS v1.0.7 and here's how I setup the service:
angular.module('myAngularJSApp.services',['ngResource'])
    .factory('RegisterNumber', ['$resource', function($resource) {
        return $resource( '../api/register/number/:id', {id:'@id'});
    }])
    .factory('RegisterChannel', ['$resource', function($resource) {
        return $resource( '../api/register/channel/:id', {id:'@id'});
    }])

and here's my controller:
angular.module('myAngularJSApp')
  .controller('RegisterCtrl', ['$scope', '$location', 'RegisterNumber', 'RegisterChannel', function ($scope, RegisterNumber, RegisterChannel) {

    $scope.step = 1;
    $scope.advanceStep = function(_step){
      var AcctNum = RegisterNumber
        , AcctChn = RegisterChannel

      switch(_step){
        case 1:
          var acctNum = AcctNum.save({ // This line throws the error
                          id : $scope.security_number
                        },
                        // SUCCESS
                        function(){
                          $scope.showError = false;
                          advance(_step);
                        },
                        // ERROR
                        function(response){
                          $scope.showError = true;
                        });
          break;
        case 2:
          var acctChn = AcctChn.save(
                        { id : $scope.channel},
                        // SUCCESS
                        function(response){
                          $scope.showError = false;
                          advance(_step);
                        },
                        // ERROR
                        function(response){
                        });
          break;
      }
    }
  }]);

And I get this error:
TypeError: Object #<Object> has no method 'save'
    at Object.$scope.advanceStep ...

I did some inspections: console.log(AcctNum) gives a LocationHashbangUrl object. However, strangely enough console.log(AcctChn) gives:
function Resource(value){
        copy(value || {}, this);
      }

which is correct. I have searched similar questions & tried the answers (here, here, and here) but I keep getting the same error. Did I miss something? Any thoughts?
Answer: That's because you have wrong injection:
angular.module('myAngularJSApp')
  .controller('RegisterCtrl',
    [
               '$scope', '$location',    'RegisterNumber', 'RegisterChannel',
      function ($scope,   RegisterNumber, RegisterChannel) { ... }
    ]
  );

You're missing $location param in controller function signature.
Comment: Oops! missed that one out. Thanks!
Comment: Can't we rewrite the controller definition as ; angular.module('myAngularJSApp')
  .controller('RegisterCtrl', function ($scope,   RegisterNumber, RegisterChannel) { ... }

  );
Comment: That way the app would break when minimised.


How to use default field_image if value is not provided?

Question: We are using Schema.org Metatag module to display meta tag attributes to the Article content type. We have a field that we using as an ImageObject using the field_image field. The field_image is setup so that if an image is not selected, then a default image will be displayed in the twig templates.
We had to add a [node:field_image:large:url] into the url field under ImageObject. When an image is selected, the correct url is added to the page. However, when the image is not selected (a default image should be used), the url field is displaying empty.
How to get the token to display the default value is the image is not added through the node edit process?
Current behavior:
"image" : {
  "@type" : "ImageObject",
   "representativeOfPage": "True",
}

Expected behavior (when image is not selected)
"image": {
  "@type": "ImageObject",
  "representativeOfPage": "True",
  "url": "https://path/to/default-image/large/cloud.jpg",
  "width": "400",
  "height": "260"
},

Comment: For reference, the bug report: [Image URL not using default value](https://www.drupal.org/project/schema_metatag/issues/2977390)
Comment: Hey, I updated my answer and added a working module as proof of concept.
Comment: @leymannx the module is a great starting point. If you decide to extend it further as a contributed module, I can try to offer any help I can.
Answer: Seems the default image procedure as it is now doesn't store a file ID or something more useful in that image field. Means the image field doesn't get populated properly.
What I'd try is to create a custom module that adds a config page with a form and a '#type' => 'file_managed'field. The resulting file ID on upload now becomes variable via \Drupal::configFactory()->getEditable()->set() (and together with the right config/install and settings YML files).
Then I'd alter the node form via hook_form_BASE_FORM_ID_alter (see comments) and add a custom validate and/or submit function. Maybe just an element validate callback on the image field. And then check on submit if this field is empty, and if so then retrieve the file ID from the config page via \Drupal::config()->get(), load the file and save it into the image field (maybe the file ID is just enough).
Now the image field should be populated properly and everything else should work as expected.

Proof of Concept
OK I just tried what I wrote above and it's working quite fine. Except I didn't use the node form but hook_entity_presave instead to check if the image field is empty before setting the file ID retrieved from the settings value of the uploaded file on said config page.

Download or clone https://gitlab.com/leymannx/tdi
into /modules/custom.
Enable the module.
Go to /admin/config/media/tdi and upload a default image, save.
Now in your IDE or code editor open /modules/custom/tdi/tdi.module and

update the bundle if ($entity->bundle() == 'XX-YOUR-NODE-TYPE-HERE-XX') {
and the field name $entity->get('field_XX-YOUR-FIELD-NAME-HERE-XX')->setValue([['target_id' => $fid]]);

Save the module file.
Go to a node with an empty image field, edit and resave it, done.

On every node creation or update this module will check if the image field is empty and add a real managed image with a real file ID then. Now the metatag module should work just fine. If updating all nodes manually is too fiddly I'd recommend you let some code do that instead :)
I'm thinking about extending this approach to let admins choose content types and field names this default image should be set automatically. Maybe tomorrow ;)

Alternatively
If this doesn't work or if it's just too messy, the next thing I'd try is to hook into hook_page_attachments_alter same as schema_metatag_page_attachments_alter does to actually attach its values to the HTML head, and try to alter the values there. Which might become messy as well, depending on what methods you have available when you get there or if all you get is just a string to be manipulated quick and dirty.
Comment: the proof of concept approach worked for me and appears to be quite extendible. I can already see ways on how I can extend it to be per content type and fields as you suggested.


Division Theorem

Question: Remainder Theorem

If there exists an integer $a$ and a positive $b$, then there exists a $r$ and $q$ such that
$$a=bq+r , \ \ \ 0 \le r\lt b$$

I wanted to know if my proof is correct for only the case that $a$ is negative integer.
Proof.
Assume the case of positive $a$ has been proved
Let $a$ be a nonnegative integer so that we get
$$-a = b\cdot q+r$$
$$\Longrightarrow r= -a-b\cdot q$$
Now let $\mathscr S $ be a set as follows:
$$ \mathscr S =\{ -a-bq\ |\ \ q \in \mathbb Z\} $$
and let the set $\mathscr R$ be defined as:
$$\mathscr R =\mathscr S \cap \mathbb Z^-$$
Thus $\mathscr R$ is the set of all negative remainders  and $-a \in \mathscr R$ since $-a = -a - b \cdot 0$ where $(q=o)$. Because $\mathscr R$ is non-empty and contains only negative elements, there exists a greatest integer in  $\mathscr R$. Let this greatest integer be denoted by $-r$.
Now $$-r <0  \Longrightarrow 0<r$$ so we know that $r$ is positive. Now take the next biggest remainder, namely $-r+b$. We know that $-r+b \gt -r$ , thus $-r+b \notin \mathscr R$ and consequently $-r+b \gt 0$. This implies
$$-r<-b \Longrightarrow r\le b$$
Therefore we have proven $r$ and $q$ exist such that $a<0$ and $a=bq+r , \ \ \ 0 \le r\lt b$
If it is incorrect can you please explain why or give the correct proof. Thank you.
Comment: Just to be clear - you are assuming the case of positive $a$ to prove the case of negative $a$? If so, you should state that explicitly.
Comment: @ThomasAndrews Yes I am. I'll correct that. But can this proven if I hadn't assumed the case of positive $a$?
Comment: If $a,b$ are integers, $\mathscr S\subseteq \mathbb Z$ so $\mathscr R=\mathscr S$. Did you mean $\mathscr R=\mathscr S\cap\mathbb Z^{\geq 0}$?
Comment: @ThomasAndrews Yes thanks again, staring at the computer screen for too long over looked that.
Answer: This proof is correct, however there is a weirdness/incompleteness to it because you never explicitly choose $q$. It follows that $q$ exists, but you never specify how to choose it. Simply saying something like "let $q_0$ be the value of $q$ such that $r=-a-bq$" would suffice.
A side note about theorem phrasing: "if there exists an integer $a$..." sounds weird to me, because of course there exist integers. $1$ is an example. It sounds like this proof says "if we assume integers exist, then ..." I think saying one of the following would be better:

"Let $a$ be a positive integer ..."
"For $a,b$, $a$ an integer and ..."
"If $a,b$ are integers with $b$ positive ..."
Comment: Not really, no. This is more or less the same as what I would write. It is worth noting though, that if you have proven the other case, you can use that to prove this case in a few lines by multiplying by $-1$ and then doing some arithmetic.
Comment: Thanks for the tips. I also wanted to ask if this is the best proof or there is some other way to do it that you might know of? Once again thanks.

Division Theorem


React Native - botão de um arquivo js chamando uma função ou variável em outro arquivo js

Question: Preciso de um help aqui:
Tenho 2 arquivos js: Header/index.js e Main/index.js
Na Header/index.js tem um botão: <TouchableOpacity onPress={() => {}} />
Na Main/index.js tem:
const onPressTiming = () => {
    Animated.timing(translateY, {toValue: 380, duration: 300, useNativeDriver: true,}).start();
  }

Preciso fazer funcionar o botão na Header/index.js, quando clicado executar a "cost onPressTiming" da Main/index.js
Simplificando, Um botão de um arquivo js chamando função ou variável dentro de outro arquivo js.
Answer: Você pode enviar a função como props para o seu componente Header. Para fazer isso, no contrutor do seu arquivo "Main", você pode fazer o bind com a função que deseja utilizar.
No exemplo abaixo, o componente "Main" enviar a função "deletar" para o componente "Excluir".
import {Container} from "./styles.js";
import Excluir from "../../components/Excluir/index";
export default class Main extends Component {
  constructor(props) {
    super(props);
    this.deletar = this.deletar.bind(this);
  }

  deletar = async id => {
    try {
      //Executar comandos
    } catch (error) {
      //Em caso de erro
    }
  };

  render() {
    return (
      <Container>

        <Excluir
          deletar={this.deletar}
          codigo={1}
        />

      </Container>
    );
  }
}

No seu componente "Excluir", você poderia usar a função criada na "Main" desta forma:
import {Container, RemoveButton, Title, Subtitle, TextButton} from "./styles.js";
const Excluir = ({deletar, codigo }) => (
  <Container>
    <Title>Remover</Title>
    <Subtitle>Tem certeza que deseja excluir?</Subtitle>
    <RemoveButton onPress={() => deletar(codigo)}><TextButton>Sim</TextButton></RemoveButton>
  </Container>
);

Comment: Blz! Obrigado, ficou bem claro!


Correct survey choice order effect

Question: I have a survey question that had yes/no answers only. The order of yes-no, no-yes was randomized. The results showed some order effects. Respondents tended to choose the first option. For example, they choose "no" in the "no-yes" order when the real answer could be "yes". The distribution of the answers are shown below.

Is here anyway I can estimate the true distribution of yes/no answers?
Answer:
Blockquote

My suspicions with yes/no sample questionnaire is that a fatigue factor quickly sets in!
As such, I suspect that the first few answers are probably more likely accurate and consistent in kind, and should be separately tabulated.
Later answered questions are probably more likely randomly responded to and should be disregarded or given a lower weight. This could be more quantitatively assessed with subsampling by phone call interviews, for example.
Also, one could insert test questions to ascertain as to whether the person is actually reading the question at various points, especially in longer yes/no surveys.
Perhaps inserting interesting graphics/pictures/..., as the questionnaire progresses, may assist in maintaining the reader's interest, and may even result in a higher quality survey product. This could also be verified by subsampling with people who took two (plain and graphic) versions of the same yes/no questionnaire.

Correct survey choice order effect


First-order model theory problem

Question: Are the following structures isomorphic?
a) $(\mathbb{R};=;+)$ and $(\mathbb{Q};=;+)$;
b) $(\mathbb{Z}, <)$ and $(\mathbb{Z},>)$;
c) $(\mathbb{N}, <)$ and $(\mathbb{N}, >)$;
Comment: What do *you* think?
Comment: @lemontree, I personally think that (b, c) are indeed isomorphic, while a - is NOT
Comment: There's an important difference between b) and c). Why do you think $\Bbb R$ and $\Bbb Q$ in a) are not isomorphic? (That's actually correct, btw.)
Comment: @Berci, there are issues with $\sqrt{2} \in \mathbb{R}$ for instance, however do not see any major difference between (b) and (c)..
Comment: Ok. I suggest to try to find explicit isomorphisms. You should be able to do that for b), and update your question with your attempts.
Answer: Your intuition is somewhat correct:
a) No. An isomorphism would require a bijection of sets, but the cardinalities of $\mathbb{Q}$ and $\mathbb{R}$ are different (the former is countable, the later is not).
b) Yes. Let $f: \mathbb{Z} \to \mathbb{Z}$ be the map $f(x)=-x$. This is clearly a bijection of sets, and also an embedding of structures as:
$x < y$ iff $ -x > -y$, i.e. $(x,y) \in   <$ iff $ (f(x),f(y)) \in   >$.
c) No (assuming equality is a logical symbol). Call the first structure $N_1$, and the second $N_2$. Suppose that they were isomorphic. Then they would satisfy the same sentences. But $N_1 \models \exists x \forall y (x \neq y \implies (x<y)$ (take $x=0$), and so $N_2 \models \exists x \forall y (x \neq y \implies (x>y)$. This is a contradiction as $\mathbb{N}$ has no upper bound, so the two structures can't be isomorphic.

First-order model theory problem


how to hot plug an interface to a running guest domain in python via libvirt module?

Question: Scenario: I am working on centos 7 with python libvirt module. I have running guest domain here in centos 7. Now i want to attach an interface to this guest domain using python script. Initially there was no interface attached to the guest domain. XML file of guest domain doesn't contains any interface tags and all.
Using shell commands I am able to attach interface. I am calling this
virsh detach-interface --domain link01 --type bridge --mac 96:5c:34:c0:5d:09 --persistent
command in python script to attach the interface and it is successfully attached.
How to achieve this in python??
Any suggestions related to this will be of great help!
Answer: There are two functions in libvirt.virDomain, that perform device attachment:
<code>attachDevice(xml)
attachDeviceFlags(xml, flags=0)
</code>
See their documentation for details.
You can take a predefined interface stanza from a domain's config as a sample and should omit or edit the "address" and "mac" tags to avoid conflicts.
<code>#generate or read your xml
import libvirt
conn = libvirt.open(name)
domain = conn.lookupByName(domain_name)
domain.attachDeviceFlags(xml, libvirt.VIR_DOMAIN_AFFECT_LIVE)
#or
domain.attachDevice(xml)
</code>


How can I tell which ColdFusion hotfixes are installed?

Question: I saw the new secruity hotfix for ColdFusion on adobe.com, but I'm unsure what is already installed. The version in ColdFusion Administrator is 8,0,1,195765.
How can I tell which ColdFusion hotfixes are installed?
Can I attempt to install a Cumulative hotfix without a problem?
Answer: If I remember correctly, ColdFusion hotfixes consist of a simple "replace some files".
To verify the installation status of a hotfix, there likely isn't any way other than to verify those files directly.
Installation of a cumulative hotfix should be safe regardless of current hotfix levels.
Answer: On both ColdFusion 8 and 9 hotfixes are installed to the {coldfusion-install}/lib/updates directory. Hotfixes are identified in the directory as hfvvv-xxxxx.jar where vvv is the version of ColdFusion and xxxxx is a bugid for a specific fix. Security hotfixes follow the same convention but the xxxxx is a sequential number. The last security hotfix for ColdFusion 8.0.1 (APSB12-21) is hf801-00007.jar.
Cumulative hotfixes are located in the same directory but are identified by chfvvvxxxx.jar, again where vvv is the version of ColdFusion and xxxx is a sequential number. The last Cumulative Hotfix for ColdFusion 8.0.1 is chf8010004.jar.
If you need an easy way to make sure your ColdFusion 8.0.1 or 9.0.x server is patched correctly, I'd recommend using Unofficial Updater 2
While what Ian linked to will be able to tell you if the contents of the CFIDE directory are correctly patched, there are files in other directories, particularly on ColdFusion 8.0.1 that need to be updated to be fully patched.
Answer: As Shane said, most have been just replacing files. In some cases there are additional JARs added. On a CF9 install they're in /opt/coldfusion9/lib/updates/ but I think that location is the same for CF8.
You could also look at this http://www.dcepler.net/post.cfm/file-integrity-checking-cfide which uses something called hashdeep and a pre-generated hash file to determine if your CFIDE matches the patched version.


Execute an action when an item on the combobox is selected

Question: I have a jcombobox containing item1 and item2, also I have a jtextfield.. when I select item1 on my jcombobox I want 30 to appear on my jtextfield while 40 if Item2 was selected... How do I do that?
Comment: http://stackoverflow.com/questions/8653901/jcombobox-actionperformed-event
Answer: this is how you do it with ActionLIstener
import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class MyWind extends JFrame{

    public MyWind() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField field = new JTextField();
        field.setSize(200, 50);
        field.setText("              ");

        JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item1");
        comboBox.addItem("item2");

        //
        // Create an ActionListener for the JComboBox component.
        //
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //
                // Get the source of the component, which is our combo
                // box.
                //
                JComboBox comboBox = (JComboBox) event.getSource();

                Object selected = comboBox.getSelectedItem();
                if(selected.toString().equals("item1"))
                field.setText("30");
                else if(selected.toString().equals("item2"))
                    field.setText("40");

            }
        });
        getContentPane().add(comboBox);
        getContentPane().add(field);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyWind().setVisible(true);
            }
        });
    }
}

Comment: I like your answer, one very minor nit pick, I might suggest you do "Item 1".equals(selected) instead - while highly unlikely, it will protect against possible NullPointerExceptions ;)
Answer: The simple solution would be to use a ItemListener.  When the state changes, you would simply check the currently selected item and set the text accordingly
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox06 {

    public static void main(String[] args) {
        new TestComboBox06();
    }

    public TestComboBox06() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private JComboBox cb;
        private JTextField field;

        public TestPane() {
            cb = new JComboBox(new String[]{"Item 1", "Item 2"});
            field = new JTextField(12);

            add(cb);
            add(field);

            cb.setSelectedItem(null);

            cb.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    Object item = cb.getSelectedItem();
                    if ("Item 1".equals(item)) {
                        field.setText("20");
                    } else if ("Item 2".equals(item)) {
                        field.setText("30");
                    }
                }
            });
        }

    }

}

A better solution would be to create a custom object that represents the value to be displayed and the value associated with it...
Updated
Now I no longer have a 10 month chewing on my ankles, I updated the example to use a ListCellRenderer which is a more correct approach then been lazy and overriding toString
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox06 {

    public static void main(String[] args) {
        new TestComboBox06();
    }

    public TestComboBox06() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private JComboBox cb;
        private JTextField field;

        public TestPane() {
            cb = new JComboBox(new Item[]{
                new Item("Item 1", "20"),
                new Item("Item 2", "30")});
            cb.setRenderer(new ItemCelLRenderer());
            field = new JTextField(12);

            add(cb);
            add(field);

            cb.setSelectedItem(null);

            cb.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    Item item = (Item)cb.getSelectedItem();
                    field.setText(item.getValue());
                }
            });
        }

    }

    public class Item {
        private String value;
        private String text;

        public Item(String text, String value) {
            this.text = text;
            this.value = value;
        }

        public String getText() {
            return text;
        }

        public String getValue() {
            return value;
        }

    }

    public class ItemCelLRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
            if (value instanceof Item) {
                setText(((Item)value).getText());
            }
            return this;
        }

    }

}

Comment: Don't forget to include the KeySelectionManager so the items in the combo box can be selected by key stroke as well. As soon as you use a custom renderer you break the default functionality of the combo box.
Comment: @kleopatra I totally agree, it was a fast cut due to a limited amount of time to actually code (no excuse), bad me
Comment: @camickr I think every implementation is different. The use of a cell render in this case (from the perspective of the OP) MAY be overkill (hard to ascertain from the question) but by using a custom object, we marry the text/view representation with that of its associated value, it makes it easier to add, change & remove elements. I also agree with kleo, toString should be used to provide stateful information about the object and renderers should be used to format the object for display. It's unlikely you would us the Date#toString value to render dates all the time
Comment: wrapper objects with overridden toString (instead of a proper renderer) are _evil_ - here it might appear as halfway justifyable because you seem to need another property for anothe view ... which is a home-grown problem, because the factoring of the business object is wrong, to start with: Item itself might be the business object, and its toString overridden with a complete description instead of with something relevant to a particular view ;-)
Comment: I still don't understand the problem with a general purpose Item class. It is specifically designed to be used with a "toString()" type of renderer and it contains additional information that can be used for processing once it is selected. If the class is well documented to support this type of functionality I don't see the problem. Almost every single HTML combobox contains this type of information. I don't see why you need to keep creating custom objects every time you need to do this. I think I need to be hit on the head a few more times before I will understand this.
Comment: Note sure how add/change/remove is easier? If you take your Item class and add a `getDisplayText()` method and then create a custom renderer and custom KeySelectionManager that takes advantage of this new method, would you then use the Item class for different combo boxes. Say for example you have an address form and you want to have "state" and "country" combo boxes. Would you reuse the Item class or create a StateItem and CountryItem (along with unique renderer and KeySelectionManager).
Comment: @camickr it would depend on the requirements. Is thinking that add it "custom" object is easier then adding a String and the having to define new logic for it in the listener
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/25450/discussion-between-camickr-and-madprogrammer)
Comment: @camickr personally, I hate chatting, especially in different timezones ;-) The base problem is that you are _adding_ the Item (which is tweaked for _View_ reasons) to the _Model_, that is mixing data and view: that mixing is against the very grain of what MVC (and its Swing variant) stands for, doing so intentionally is a complete no-go. Not having the object itself in the data will effect your complete application chain: each and every line of code that accesses the elements in the combo/model must be aware of the wrapper (aka: Item), including binding such as view updates on data mutations.
Comment: @camickr _custom renderer will break default KeySelectionManager_ - true but not the fault of the renderer ;-) The default implementation of the keySelectionManager is ... crappy in assuming the renderer will use the toString, basically not thinking about effects of custom renderers.
Answer: Not an answer to the original question, but an example to the how-to-make-reusable and working custom renderers without breaking MVC :-)
// WRONG
public class DataWrapper {
   final Data data;
   final String description;
   public DataWrapper(Object data, String description) {
       this.data = data;
       this.description = description;
   }
   ....
   @Override
   public String toString() {
       return description;
   }
}
// usage
myModel.add(new DataWrapper(data1, data1.getName());

It is wrong in a MVC environment, because it is mixing data and view: now the model doesn't contain the data but a wrapper which is introduced for view reasons. That's breaking separation of concerns and encapsulation (every class interacting with the model needs to be aware of the wrapped data).
The driving forces for breaking of rules were:

keep functionality of the default KeySelectionManager (which is broken by a custom renderer)
reuse of the wrapper class (can be applied to any data type)

As in Swing a custom renderer is the small coin designed to accomodate for custom visual representation, a default manager which can't cope is ... broken. Tweaking design just to accommodate for such a crappy default is the wrong way round, kind of upside-down. The correct is, to implement a coping manager.
While re-use is fine, doing so at the price of breaking the basic architecture is not a good bargin.
We have a problem in the presentation realm, let's solve it in the presentation realm with the elements designed to solve exactly that problem. As you might have guessed, SwingX already has such a solution :-)
In SwingX, the provider of a string representation is called StringValue, and all default renderers take such a StringValue to configure themselves:
StringValue sv = new StringValue() {
     @Override
     public String getString(Object value) {
        if (value instanceof Data) {
            return ((Data) value).getSomeProperty();
        }
        return TO_STRING.getString(value);
     }
};
DefaultListRenderer renderer = new DefaultListRenderer(sv);

As the defaultRenderer is-a StringValue (implemented to delegate to the given), a well-behaved implementation of KeySelectionManager now can delegate to the renderer to find the appropriate item:
public BetterKeySelectionManager implements KeySelectionManager {

     @Override
     public int selectionForKey(char ch, ComboBoxModel model) {

         ....
         if (getCellRenderer() instance of StringValue) {
              String text = ((StringValue) getCellRenderer()).getString(model.getElementAt(row));
              ....
         }
     }

}

Outlined the approach because it is easily implementable even without using SwingX, simply define implement something similar and use it:

some provider of a string representation
a custom renderer which is configurable by that provider and guarantees to use it in configuring itself
a well-behaved keySelectionManager with queries the renderer for its string represention

All except the string provider is reusable as-is (that is exactly one implemenation of the custom renderer and the keySelectionManager). There can be general implementations of the string provider, f.i. those formatting value or using bean properties via reflection. And all without breaking basic rules :-)
Comment: Last night I actually found a posting where you gave the same example. I didn't understand it then and I don't understand it now. Sometimes I need a concrete example before it sinks in. It seems to me like you are just creating another fancy wrapper class that invokes the getString() method instead of the toString() method. How would you use MadProgrammer's Item class and your StringValue class to add items to a ComboBoxModel? Also, since only the renderer know about the text, how do you add the ietms in sorted order. Does your StringValue class implement Comparable?
Comment: There an many uses for a value/description pairs. For example a Product. "1" is a Hammer (to hit me on the head with), "2" is a Screwdriver. Somewhere you need to keep this mapping of value/description. So to say that an Object can't have these two properties together doesn't make any sense to me. Now that these two properties are together in a class you can choose which of the properties you want displayed in the combo box by using an appropriate renderer.
Comment: Also, chances are your product will have multiple descriptions for different languages. So when you populate the Item class you will populate it with the appropriate description directly from your Database or resource file or whatever you use.
Comment: @camickr you are mixing concerns again and to me it seems now that you are doing it intentionally. If you don't want to follow MVC, that's what you don't want and I'm not going to discuss that :-) Just repeating: The value (== bean, having arbitrary properties) itself belongs into the (Swing) data realm, unchanged for view reasons. The string representation in the combo is-a problem of the (Swing) view realm, so solve it there, f.i. by factoring the production of the string to use into a class which does nothing else.
Comment: I'm not doing it intentionally. I am not always the best abstract thinker and sometimes need concrete examples. I still have no idea how to use your StringValue class. With regards to MVC. I honestly don't see the problem with having the value and description in the  class which is added to the Model (eg. the value represents a "product id" and the description is the "description" of the product). Then you can have customized views, one of the product and one of the description.
Comment: I down loaded Swingx and now understand the StringValue class and its use with a renderer and KeySelectionManager (KSM). I have versions of the renderer and KSM that use reflection. Not as flexible as your 3 class approach since it only supports rendering of a single property. I see JXComboBox doesn't support a sorted view, or am I missing something? So while I understand the view should be responsible for this, I'm guessing everybody cheats by just loading the combo box in sorted order.
Comment: @camickr you'r right, JXComboBox doesn't support sorting - somehow we never made it to the tweaked uis (as we have done for JXList)  that are required to fully support it :-)
Comment: Right, so my point is we take tweaks or short cuts and do external sorting before adding to the model. Now if I'm making a GUI builder and I want to be able to create and assign properties to a JLabel. I might use a JTextField for the text, a JCheckBox for opaque and a JComboBox for alignment (Left, Center, Right). If I select Left how do you map this to JLabel.LEFT so you can set the alignment property? I doubt you use if/else like the accepted answer here.


Is it possible to animate moving icons in deck.gl?

Question: I've been visualizing trip data using a trips layer, and I'm trying to put an icon at the head of each trip line. Is it possible to make multiple icons change position, appear, and disappear over time?
Example of what I'm trying to do (red arrow indicates motion over time)
Comment: Did you ever find a solution to this?
Answer: I've been looking to do this for a while and achieved it following Mudkips answer.
I've appended animated icons to the TripsData example from the DeckGl site below.
Look at the IconLayer creation below, in particular that getPosition and updateTriggers portions.
<code>import React, {useState, useEffect} from 'react';
import {Map} from 'react-map-gl';
import maplibregl from 'maplibre-gl';
import {AmbientLight, PointLight, LightingEffect} from '@deck.gl/core';
import DeckGL from '@deck.gl/react';
import {PolygonLayer} from '@deck.gl/layers';
import {TripsLayer} from '@deck.gl/geo-layers';
import {IconLayer} from '@deck.gl/layers';

// Source data CSV
const DATA_URL = {
  BUILDINGS:
    'https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/trips/buildings.json', // eslint-disable-line
  TRIPS: 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/trips/trips-v7.json' // eslint-disable-line
};

const ambientLight = new AmbientLight({
  color: [255, 255, 255],
  intensity: 1.0
});

const pointLight = new PointLight({
  color: [255, 255, 255],
  intensity: 2.0,
  position: [-74.05, 40.7, 8000]
});

const lightingEffect = new LightingEffect({ambientLight, pointLight});

const material = {
  ambient: 0.1,
  diffuse: 0.6,
  shininess: 32,
  specularColor: [60, 64, 70]
};

const ICON_MAPPING = {
    marker: {x: 0, y: 0, width: 128, height: 128, mask: true}
  };

const DEFAULT_THEME = {
  buildingColor: [74, 80, 87],
  trailColor0: [253, 128, 93],
  trailColor1: [23, 184, 190],
  material,
  effects: [lightingEffect]
};

const INITIAL_VIEW_STATE = {
  longitude: -74,
  latitude: 40.72,
  zoom: 13,
  pitch: 45,
  bearing: 0
};

const MAP_STYLE = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json';

const landCover = [
  [
    [-74.0, 40.7],
    [-74.02, 40.7],
    [-74.02, 40.72],
    [-74.0, 40.72]
  ]
];

export default function App({
  buildings = DATA_URL.BUILDINGS,
  trips = DATA_URL.TRIPS,
  trailLength = 180,
  initialViewState = INITIAL_VIEW_STATE,
  mapStyle = MAP_STYLE,
  theme = DEFAULT_THEME,
  loopLength = 1800, // unit corresponds to the timestamp in source data
  animationSpeed = 1,
  iconMapping = ICON_MAPPING
}) {
  const [time, setTime] = useState(0);
  const [animation] = useState({});

  const animate = () => {
    setTime(t => (t + animationSpeed) % loopLength);
    animation.id = window.requestAnimationFrame(animate);
  };

  useEffect(() => {
    animation.id = window.requestAnimationFrame(animate);
    return () => window.cancelAnimationFrame(animation.id);
  }, [animation]);

  const layers = [
    // This is only needed when using shadow effects
    new PolygonLayer({
      id: 'ground',
      data: landCover,
      getPolygon: f => f,
      stroked: false,
      getFillColor: [0, 0, 0, 0]
    }),
    new TripsLayer({
      id: 'trips',
      data: trips,
      getPath: d => d.path,
      getTimestamps: d => d.timestamps,
      getColor: d => (d.vendor === 0 ? theme.trailColor0 : theme.trailColor1),
      opacity: 0.5,
      widthMinPixels: 4,
      rounded: true,
      trailLength,
      currentTime: time,

      shadowEnabled: false
    }),
    new IconLayer({
        id: 'icon-layer',
        data: trips,
        iconAtlas: 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/icon-atlas.png', // Specify your icon atlas
        iconMapping: iconMapping, // Customize icon position
        sizeScale: 5, // Adjust icon size
        getColor: (d) => (d.vendor === 0 ? theme.trailColor0 : theme.trailColor1),
        getIcon: d => 'marker',
        getSize: d => 5,
        getPixelOffset: [0,-10],
        getPosition: (d) => {
          let x = null;
          let y = null;
          for(let i = 0; i < d.timestamps.length-1; i++) {
            if(time < d.timestamps[i + 1] && time >= d.timestamps[i]) {
              let frac = (time - d.timestamps[i]) / (d.timestamps[i+1] - d.timestamps[i])
              x = ((d.path[i+1][0] - d.path[i][0]) * frac) + d.path[i][0];
              y = ((d.path[i+1][1] - d.path[i][1]) * frac) + d.path[i][1];
              break;
            }
          }
          return [x,y];
        },
        updateTriggers: {
          getPosition: time
        }
      }),
    new PolygonLayer({
      id: 'buildings',
      data: buildings,
      extruded: true,
      wireframe: false,
      opacity: 0.5,
      getPolygon: f => f.polygon,
      getElevation: f => f.height,
      getFillColor: theme.buildingColor,
      material: theme.material
    })
  ];

  return (
    <DeckGL
      layers={layers}
      effects={theme.effects}
      initialViewState={initialViewState}
      controller={true}
    >
      <Map reuseMaps mapLib={maplibregl} mapStyle={mapStyle} preventStyleDiffing={true} />
    </DeckGL>
  );
}
</code>
Comment: Note this approach works for TextLayer and ScatterplotLayer too
Answer: Simply animate the data's position property, making sure it's a state change to trigger rerenders, before giving it to the layer. You can also put opacity in the data and animate that too.


Is a forward-pass on a neural network a similar operation to a predict operation?

Question: I understand that in the case of the forward-pass the outputs are passed into a loss-function, rather than used to generate a prediction, but up until that point they are the same right?
I'm asking as I'm looking at two methods of using the VGG16 model. In one method the keras -model.predict- is used on the convolutional base of the VGG to generate features for new classifier layers which are then trained. In the second method the VGG base is frozen and new classifiers are trained on data passed I think into the frozen VGG base. To me the output from the frozen VGG base seems to be the same as the output from -model.predict-.
I know from the guidance they are very different methods [the second method is much more expensive], but I can't separate them conceptually.
The guidance:https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/5.3-using-a-pretrained-convnet.ipynb
Comment: One difference between the 2 methods i guess is that the 2nd method pass each image through the whole model multiple times as training progresses. Whereas the 1st method only sees each image once in the expensive VGG base?
Answer: Terminology
A "forward pass" just means you put inputs in and propagate through the network, which in most implementations is a bunch of matrix multiplications and point-wise function applications. At the end, you get a set of outputs.
During training, the outputs are compared to what the answer should be, and the differences between the two--as measured by a loss function--are used to update model parameters, so now that input will cause the output to look a little bit more like the should-be answer.
Once the model is trained there is no backpropagation, no model-parameter-updating step, so there is no need to use the loss function. Actually, if you pass in some new input for which you don't know the answer, then there is nothing to compare the output against, so you don't even have all the information necessary to find a loss.
Keras
I interpret the methods you describe to be the same, at least by architecture: In both cases you use a convolutional network to get some simplified features out of the raw data and then pass those to a classifier that tells you something useful.
But there might be a difference in how they're trained. The word "frozen" implies that you train the CNN first and then stop updating its parameters while you train the classifier as a separate step. You can train the classifier via supervised learning because you presumably know what the classifications should be. But how do you train the CNN? One possibility is with an autoencoder architecture: A network tries to compress the input down to some smaller representation, and then a mirror network re-expands from that representation to the original space. (Imagine an input image compressed down to some key features and then propagated through a reverse network to yield a blurry or distorted version of the image.) The program can then use the difference between the true and re-constituted versions to decide how to update the network so that it can more accurately re-represent the input next time. Then take the first half (the compression part) of this autoencoder to be the CNN for your other problem. Voila.
But you say this is more expensive than the alternative: In principle it should be possible to backpropagate through all layers of both networks, so you could train both at once. This is likely what is happening in the method you say doesn't take as long.
Comment: thanks. I believe the 'fast' method uses the prediction values from the VGG base [VGG16 without its classification layers] as features to pass into and train new custom classification layers. Only these new classification layers get trained, hence the speed. I don't think autoencoders play a part here, only because they do feature in a later chapter in Chollet's book and have not yet been introduced, but maybe? Chollet makes use of augmented images in method 2, I'm wondering if part of the expense is simply processing more images, but I don't really think that's the whole story??
Comment: Reading more deeply through that notebook you posted makes me realize "frozen" just means you're just using someone else's pretrained convnet and only replacing the classifier. This can work because the output of the convnet should be generic like "this part of the image has high frequency color variations", "this part of the image has a curve like this in it", "this part of the image is colored like this". So yes, this method should be faster. (You said this, the second, was slower.)
Comment: yes, I should have been clearer about 'frozen' == (trainable=False). But in my mind the predict operation in method1 doesn't train either [just a forward-pass], so I'd expect similar speeds. One advantage Chollet explicitly states fort method2 is it allows for the use of augmented images as data [but again I don't see why augmented images can't be passed into method1]


How to create indexes from "open" variables

Question: I am running an impact evaluation to investigate the impact of a specific program on several indicators x. These indicators have values between 0 and up to 10000, and a high standard deviation.
For my purpose, I'd like to create one index for each indicator each that takes into account the initial level of the indicator x in the base year (year=0) and the change between the base year and the post-intervention year (year=1), for each observation (household). The index should be constructed from two components, the initial level wi and the change diffi, with wi and diffi each being normalized (0 to 1) and wi X diffi making the indicator. At least, thats how it was done in a previous paper, where the variables, however, had logical limits, i.e. months per year etc.
A total loss of the initial value between year 0 and year 1 (i.e. diffi=-100%) should be 0 and a gain of 100% or more (.e. diffi >= 100%) should be 1. I cannot simply focus on the change itself, as initial levels determine the "impact" of the change on the household (outcome variables are measures for food security in a drought-affected developing country).
Do you have any suggestions?
Answer: This sounds like a candidate for a log-transform of the diff variable. That way you'll be effectively measuring the percentage change in the variable. The losses will be transformed to negative values and the gains will be positive. If you felt that the percentage change was still impacted by the initial value, you could also use that as an offset term or as a predictor in  your model.
Comment: By predictor you mean I should use the initial level of x in year=1 as additional explanatory variable in my regression model? Well, I cannot do that in all of my models as I am estimating the ATT using a specific Stata command (psmatch2) that allows to include the additional variable in the equation to estimate the propensity score, but it is not possible to include additional explanatory variables to estimate the ATT on the outcome variable. Hence, I need to construct an integrated index, based on wi and diff.
Comment: I just meant if you thought that the percent change would vary depending on the initial value, then you could use it as one of the  explanatory variables. But it's not strictly necessary, just use a log transform of the difference between the year=1 value and the year=0 value, and that could be an effective index.


Is the product of hyperconnected separable topological spaces always separable?

Question: The classical Hewitt-Marczewski-Pondiczery theorem says in particular that the product of more than $|\mathbb{R}|$ topological spaces isn't separable, BUT it does the hypotesis that every space has two nonempty disjoint open sets, i.e. all spaces are not hyperconnected (and in the proof this is used very much).
So it is natural to asks if and in wich cases the product of hyperconnected separable topological spaces is always separable, or it depends on the cardinality, maybe in a different way from the non hyperconnected case.
In particular I'm concerned with understanding in $X^Y$ is separable in the following case: $X$ is an infinite set with the cofinite topology and $Y$ is whatever set.
Comment: An uncountable set with the cocountable topology is not separable.
Comment: Also, in the first sentence it seems you mean more than $|\mathbb{R}|$, not more than $2^{|\mathbb{R}|}$.
Comment: The proof of H-M-P given in General Topology by R. Engelking does not require any space(s) to have two non-empty disjoint open sets.  And this theorem does not imply that the product of more than $|\Bbb R|$ spaces is non-separable. For example if every $X_i$ has the coarse (anti-discrete) topology  then so does $\prod_{i\in I}X_i.$
Comment: @EricWofsey you are completely right.
Comment: @DanielWainfleet I was referring to the Dugundji's proof.
Answer: If $X$ is an infinite set with the cofinite topology, then $X^Y$ is separable for any $Y$.  Indeed, let $x_0,x_1,\dots$ be infinitely many distinct points of $X$ and let $c_n\in X^Y$ be the constant function with value $x_n$.  Then $\{c_n:n\in\mathbb{N}\}$ is dense in $X^Y$ (any nonempty basic open set can only exclude finitely many of the $x_n$'s on any coordinate).
As for what happens in general, suppose $(X_i)_{i\in I}$ is a family of hyperconnected separable spaces with countable dense subsets $D_i\subseteq X_i$ (which for covenience we assume are infinite).  Let us replace $X_i$ with $D_i$ and consider whether $\prod D_i$ is separable (since a countable dense subset of it will also be dense in $\prod X_i$).  Identifying each $D_i$ with $\mathbb{N}$, we are reduced to considering products of the form $\mathbb{N}^I$ where on each coordinate $\mathbb{N}$ has some hyperconnected topology (not necessarily the same on each coordinate).
Now suppose there exists a (proper) filter $F$ on $\mathbb{N}$ which contains every nonempty open set on each coordinate.  Let $c_n\in\mathbb{N}^I$ be the constant function with value $n$.  I claim then that $\{c_n:n\in\mathbb{N}\}$ is dense in $\mathbb{N}^I$.  Indeed, given a basic open set $\prod U_i\subseteq\mathbb{N}^I$, the intersection $\bigcap U_i$ is in $F$, since it is a finite intersection of elements of $F$ (since $U_i=\mathbb{N}$ for all but finitely many $i$).  In particular, $\bigcap U_i$ is nonempty, and then we see that for any $n\in\bigcap U_i$, $c_n\in \prod U_i$.
More generally, suppose there is a collection of $2^{\aleph_0}$ filters $F_j$ such that for each coordinate $i$, there is some $j$ such that every nonempty open set of the topology on the $i$th coordinate is in $F_j$.  Grouping the factors according to this value of $j$, we can write $\mathbb{N}^I$ as a product of spaces $P_j$ where each $P_j$ is separable by the previous paragraph.  So $\mathbb{N}^I$ is a product of at most $2^{\aleph_0}$ separable spaces and thus is separable.
Conversely, suppose no such family of $2^{\aleph_0}$ filters exists (for instance, $I$ might be the set of all ultrafilters on $\mathbb{N}$ and each coordinate has its nonempty open sets given by the corresponding ultrafilter). Then I claim $\mathbb{N}^I$ is not separable.  Let $F_i$ be the filter on $\mathbb{N}$ generated by the nonempty open sets on the $i$th coordinate (this is a proper filter since each topology is hyperconnected).  By hypothesis, we cannot partition $I$ into $2^{\aleph_0}$ pieces such that the union of the $F_i$ on each piece generates a proper filter.
Now suppose we have a countable dense subset $\{s_n:n\in\mathbb{N}\}\subset\mathbb{N}^I$.  Define a function $f:I\to \mathbb{N}^\mathbb{N}$ by $f(i)(n)=s_n(i)$.  The fibers of $f$ form a partition of $I$ into $2^{\aleph_0}$ pieces, so for some $x\in\mathbb{N}^\mathbb{N}$, the filters $F_i$ for $i\in f^{-1}(\{x\})$ are not compatible.  This means we can choose finitely many $i_1,\dots,i_n\in f^{-1}(\{x\})$ and $U_1\in F_{i_1},\dots,U_n\in F_{i_n}$ such that $U_1\cap\dots\cap U_n=\emptyset$.  We may moreover assume that each $U_k$ is open in the topology of the $i_k$th coordinate, since the filter $F_{i_k}$ is generated by the nonempty open sets.  Now let $U$ be the set of elements of $X^Y$ whose $i_k$th coordinate is in $U_k$ for $k=1,\dots,n$.  This is a nonempty open set so it contains $s_m$ for some $m$.  But $f(i_k)=x$ for each $k$ so $s_m(i_k)=x(m)$ for each $k$.  That is, $x(m)\in U_1\cap\dots\cap U_n$, which is a contradiction.

So, the upshot is that separability of a product of hyperconnected separable spaces depends not on the cardinality of the index set but on the diversity of the filters on the countable dense subsets determined by the topologies.  Note that the nonempty open sets of a hyperconnected topology generate a filter, and extending the topology to include all sets in that filter does not change which subsets are dense (even when you take a product of many such spaces).  So, we may as well think of a hyperconnected topology as a filter.  Given a family of hyperconnected spaces $X_i$ with countably infinite dense subsets $D_i$ of each one, the topologies on the $D_i$ give a family of filters on $\mathbb{N}$.  If those filters can be partitioned into at most $2^{\aleph_0}$ subfamilies where the filters in each subfamily are jointly compatible (i.e., together they generate a proper filter), then the product will be separable.  On the other hand, if the filters cannot be partitioned into $2^{\aleph_0}$ subfamilies in this way, then at least the product $\prod D_i$ of the countable dense subsets is not separable.  (The product $\prod X_i$ of the whole spaces might still be separable, though, since for instance each $X_i$ might have a dense point that is not in $D_i$.)


Reading file names, respectively?

Question: I have 1000 files in a folder, I want to find the name of the file, but when I do it
The file names are not sorted.
For example: These are my filenames
1-CustomerApp.txt
2-CustomerApp.txt
3-CustomerApp.txt
...

var adddress = @"data\";
str = "";
DirectoryInfo d = new DirectoryInfo(adddress);//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
foreach (FileInfo file in Files)
{
    str = str + ", " + file.Name;
}

Comment: They ARE sorted, but sorted as strings. When you have 1 2 10, they will be sorted as 1 10 2.
Comment: @Tony: if they *happen* to be sorted it's only because of a filesystem quirk (usually NTFS).  The same code run against the same set of files on an NFS or FAT partition will yield vastly different results.
Comment: Related question: [Natural Sort Order in C#](https://stackoverflow.com/questions/248603/natural-sort-order-in-c-sharp)
Comment: Take a look at:
[this answer][1]...

  [1]: http://stackoverflow.com/questions/12077182/c-sharp-sort-files-by-natural-number-ordering-in-the-name
Comment: What is your question? How is finding a file related to sorting file names?
Comment: @Dan-o The point is that he wrote they are unsorted, but they ARE.
Comment: @Tony: No.  The point is that any observed similarity to any kind of sortedness [numerical or alphabetical] is purely happenstance, a coincidence, a side effect.  *The observation is incorrect!*
Answer: You could use this to keep a "numerical" order
FileInfo[] files = d.GetFiles("*.txt")
.OrderBy(m => m.Name.PadLeft(200, '0')).ToArray();

200 is quite arbitrary, of course.
This will add "as many 0 as needed" so that the file name + n 0 are a string with a length of 200.
to make it a little bit less arbitrary and "brittle", you could do
var f = d.GetFiles("*.txt");
var maxLength = f.Select(l => l.Name.Length).Max() + 1;
FileInfo[] files = f.OrderBy(m => m.Name.PadLeft(maxLength, '0')).ToArray();

How does it work (bad explanation, someone could do better)  and why is it far from perfect :
Ordering of characters in c# puts numeric characters before alpha characters.
So 0 (or 9) will be before a.
But 10a, will be before 2a as 1 comes before 2.
see char after char
1 / 2 => 10a first
But if we change
10a and 2a, with PadLeft, to
010a and 002a, we see, character after character
0 / 0 => equal
1 / 0 => 002a first
This "works" in your case, but really depends on your "file naming" logic.
CAUTION : This solution won't work with other file naming logic
For example, the numeric part is not at the start.
f-2-a and f-10-a
Because
00-f-2-a would still be before 0-f-10-a
or the "non-numeric part" is not of the same length.
1-abc and  2-z
Because
01-abc will come after 0002-z
Comment: That's if they want it in alphabetical order.  If they want numerical order they'll have to employ some string manipulation
Comment: @Dan-o This will give a "pseudo numerical" order.
Comment: @Dan-o In this case it leads to numerical order. But it's extremely brittle. It only works because the string after the number has the same length of all names.
Comment: I can't believe I've never thought of that.
Comment: @BrunoLM Oracle history X ;)
Comment: @CodesInChaos I don't really agree with the "extremely" brittle... The second version is probably better, indeed.
Comment: @RaphaëlAlthaus can you elaborate on how does it work? why making them in the same length will cause the sort to be correct?
Comment: @RaphaëlAlthaus It's not the hardcoded 200 that I consider brittle. It's that you assume that the part after the number has the same length. `1-abc.txt` will sort after `2-z.txt`. That's not a problem for the OP's dataset, but can quickly run into trouble on minor changes.
Comment: @CodesInChaos oh yes, and also f-10.txt would also be after f-2.txt if he had another "file naming structure"
Comment: @user844541 little explanation added
Comment: @RaphaëlAlthaus that is so cool!! :) super smart. but if you have the following string 2myfile.txt and 10myfil.txt (stupid example) then the padding will not add anything because both are the same length.
Comment: @user844541 yes, added some failing cases in the answer.
Answer: They are sorted alphabetically. I don't know how do you see what they are not sorted (with what you compare or where have you seen different result), if you are using file manager, then perhaps it apply own sorting. In windows explorer result will be the same (try to sort by name column).
If you know template of how file name is created, then you can do a trick, to apply own sorting. In case of your example, extract number at start (until minus) and pad it with zeroes (until maximum possible number size), and then sort what you get.
Or you can pad with zeroes when files are created:
0001-CustomerApp.txt
0002-CustomerApp.txt
...
9999-CustomerApp.txt

Answer: Try the alphanumeric-sorting and sort the files' names according to it.
FileInfo[] files = d.GetFiles("*.txt");
files.OrderBy(file=>file.Name, new AlphanumComparatorFast())

Answer: This should give you more or less what you want; it skips any characters until it hits a number, then includes all directly following numerical characters to get the number. That number is then used as a key for sorting. Somewhat messy perhaps, but should work (and be less brittle than some other options, since this searches explicitly for the first "whole" number within the filename):
var filename1 = "10-file.txt";
var filename2 = "2-file.txt";

var filenames = new []{filename1, filename2};

var sorted =
    filenames.Select(fn => new {
                                  nr = int.Parse(new string(
                                             fn.SkipWhile(c => !Char.IsNumber(c))
                                               .TakeWhile(c => Char.IsNumber(c))
                                               .ToArray())),
                                  name = fn
                                })
              .OrderBy(file => file.nr)
              .Select(file => file.name);

Reading file names, respectively?


Make a one sequence

Question: A sequence of integers is a one- sequence if the difference between any two consecutive numbers in this sequence is -1 or 1 and its first element is 0.
More precisely: a1, a2, ..., an is a one-sequence if:
<code>For any k (1 ≤  k < n): |a[k] - a[k+1]|=1,
a[1]=0.
</code>
Given n and s ─ sum of all elements in a. W need to construct a one-sequence with the given parameters.
Like If n=8 and s=4 then one of such sequence is [0 1 2 1 0 -1 0 1].
Note if for given n and s we cant form such sequence than also we need to tell that its not possible.Otherwise we need to tell any of such one sequence.How to do this problem Please help.
Comment: Try some special cases. Fix $n=2$ and see which values of $s$ you can get. Then try $n=3$, then $n=4$, keep going until you see a pattern. Worth a try, I think.
Comment: @GerryMyerson I tried.But cant come up with a general sequence.Always got a catch for whatever i think off..:(
Comment: Come on. $n=2$. There are only 2 sequences possible; $0,1$ and $0,-1$, so the only values of $s$ are $1$ and $-1$. Now, you do $n=3$.
Comment: @GerryMyerson For small n its a cakewalk.But as n grew it becomes difficult to maintain the sum required
Comment: I don't know what you mean by "maintain the sum required". I don't require any sum. I suggest writing down all the sequences, and seeing which sums arise. Alternatively, pick a sum, say, $s=0$, and see whether you can get it with $n=1$, then with $n=2$, $n=3$, and so on, until you see a pattern in which values of $n$ work for that value of $s$. Then try the same with $s=1$, and so on. Show us your work!
Answer: Hint: Given a sequence of length $n$ summing to $s$, we can create two sequences of length $n+1$ summing to $s-n$ and to $s+n$, and this process is reversible. By induction, the possible sums for sequences of length $n+1$ are $\pm n \pm (n-1) \pm (n-2) \cdots \pm (1)$, where we can choose the signs independently. By considering this expression modulo $2$, we see that $s \equiv n(n+1)/2 \pmod{2}$, and also trivially $-n(n+1)/2 \leq s \leq n(n+1)/2$.
Given a number $s$ satisfying these two constraints, define $s' = s \pm n$, choosing the sign so that $-n(n-1)/2 \leq s' \leq n(n-1)/2$. Also, $s' \equiv n(n+1)/2-n \equiv n(n-1)/2 \pmod{2}$. Induction therefore shows that any sum satisfying the constraints is achievable, and the proof can be turned into an algorithm.
Note that this is only a hint so I only sketch the argument. You'll have to fill in the details on your own.

Make a one sequence


Let $Y$ have the Cauchy distribution, $f_Y(y)=\frac{1}{1+y^2},\;-\infty<y<\infty$

Question: (a) Show that $F_Y(y)=\tan^{-1}(y)$
I tried to use the usual method but quickly realized that it doesn't work.  I have been working other angles for hours and now I'm just stuck.
$F_Y=P(Y\leq y)$
$=\int\limits_{-\infty}^{y}f_Y(t)dt$
$=\int\limits_{-\infty}^{y}\frac{1}{1+t^2}dt$
$=[\tan^{-1}(t)]_{-\infty}^{y}$
$=\tan^{-1}(y)+\frac{\pi}{2}$
Obviously, this solution doesn't work.  I was thinking that there must be a transformation, $Y=g(X)$ on a standard Cauchy r.v., $X \sim$ Cauchy(0,1) with pdf $\;f_X(x)=\frac{1}{\pi(1+x^2)}$, so that I can get the pdf of $Y$ as stated in the problem.
EDIT 1:
I figured if I could get limits on $y$ such that $\int f_Y=1$ then I'd have something. So I got
$1=\int\limits_{-\infty}^{\alpha}\frac{1}{1+t^2}dt$
$=[\tan^{-1}(t)]_{-\infty}^{\alpha}$
$=\tan^{-1}(\alpha)+\frac{\pi}{2}$
$\Rightarrow \alpha=\tan(1-\frac{\pi}{2})$
So know I think I can say that $f_Y(y)=\frac{1}{1+y^2},\;-\infty < y \leq \tan(1-\frac{\pi}{2})$
But now what...
EDIT 2:
By suggestions, I made the transformation $Y=g(x)=\frac{X}{\pi}$.
$\Rightarrow g^{-1}(y)=y\pi\;$ and $\;|J|=\pi$ so that
$f_Y=f_X(g^{-1}(y))|J|=\frac{1}{1+(\frac{y}{1/\pi})^2}$
But I'm still not sure how to get to $\;F_Y(y)=\tan^{-1}(y)$
EDIT 3:
I'm pretty sure that I am somehow supposed to use the theorem stating that if $X$ is a continuous r.v. with cdf $F_X$, then a r.v. $Y=F_X$ is uniformly distributed on $(0,1)$, ie. $Y\sim Uniform(0,1)$. (probability integral transformation)
So if $X \sim$ Cauchy$(0,1)$ and $Y=F_X=\frac{1}{\pi}\tan^{-1}(x)+\frac{1}{2}$, then $g^{-1}(y)=\tan(\pi(y-\frac{1}{2}))$.  This inverse function is so similar to the value of the upper limit that makes $\int_{-\infty}^{\tan(\pi(1-\frac{1}{2})}\frac{1}{1+y^2}=1$, that I feel the answer must be close.
Comment: Firstly, $\dfrac{1}{1+y^2}$ is not a probability density function, since its integral is $\pi$, not $1$. That is repaired by normalising with the factor $1/\pi$. Secondly, your calculation is correct, the given formula is wrong.
Comment: Tell you what: not all mistakes get caught between the first and second edition.
Comment: There is no way the book is right on this. If $F_Y$ is the cdf, then $F_Y(-\infty)$ must be 0 and $F(\infty)=1$, which is clearly false. There are multiple typos in the book.
Comment: Daniel, I considered this many times, but I'm assuming it's not a typo since this book is in it's second edition. I've added some further work addressing your thoughts.
Comment: I concur with the other commenters. It's a typo.
Comment: I agree, it's a typo. I looked at the previous edition, and this question wasn't included in the chapter, so it's not as unlikely to be a typo than I thought. So how should I edit this in case another person runs across the same problem?
Answer: The book is wrong.  This is just the usual Cauchy distribution.
http://en.wikipedia.org/wiki/Cauchy_distribution
Comment: But it is. These are very serious typos so you could consider reading another book
Answer: Seems the density function should be normalized by $\pi$.
Comment: Ok. So went with this suggestion, but I don't end up with the right pdf. See above.


how to set mysql max_execution_time property use go

Question: Im so sorry ask this but i have no useful msg after google.
dba prevent slow query affect mysql server, so we need control select statement execute time. I know variable max_execution_time affect that。 but i can not  find func in dtabase/sql.go ,  Who big man can give me some advice
Answer: Execute SET max_execution_time=500 as a SQL statement. This limits the following SQL statements on the same connection to 0.5 seconds.
It is also possible as a SQL comment hint like SELECT  /*+ MAX_EXECUTION_TIME(1000) */ field1, field2 FROM tbl ... like
this answer.
If you show details about your slow query in a new question performance improvements may be possible.
Comment: The "on the same connection" caveat is important. As the go `sql` package uses connection pooling you cannot just `db.Exec("SET max_execution_time=500")` and the expect the next `db.Query` will use the same connection. An alternative is to use `context`.
Comment: Your hint made me enlightened, thank you


Converting the login / register / password reset tabs into three different pages?

Question: I want to separate the user account menu tabs structure into an individual page layout.
For short I want to remove the tabs, I know that the pages are different.
Snapshot attached.

What I have done so far is trying to use the theme suggestions but couldn't get any closer.
I get to know that it's being rendered from:

themes/bootstrap/templates/block/block--local-tasks-block.html.twig
Answer: You could create different twig templates for that three pages and remove the local tasks from the display. Depending on your theme, it may also be sufficient to just disable the "tabs" block on these three pages. Then you'd create a custom menu (and block) with these three links in it and display it where you need it.
Answer: You have to extend page.html.twig in your theme/templates folder with the name suggestion that you get on enabling twig debug and remove the header section from it.
Remove this code:
<code> {# Header #}
      {% if page.header %}
        {% block header %}
          <div class="col-sm-12" role="heading">
            {{ page.header }}
          </div>
        {% endblock %}
      {% endif %}
</code>
By this the tabs will be removed.
Answer: You can try this:
<code>  function module_name_menu_local_tasks_alter(&$data, $route_name) {
  $routes = ['user.pass','user.login','user.register'];
  if (in_array($route_name, $routes)) {
    unset($data['tabs'][0]['user.login']);
    unset($data['tabs'][0]['user.pass']);
    unset($data['tabs'][0]['user.register']);
  }
}
</code>


Converting String to Float is not giving exact value in iOS

Question: I wrote a sample to convert string to float in Objective-C:
NSString *sampleFloatString = @"1.3";
float sampleFloatValue = [sampleFloatString floatValue];

But when I display sampleFloatValue, it shows '1.29999995'. I know it's equal to 1.3, but why is it not exactly '1.3'? Why do we need to format it explicitly? Is there any other way of doing this conversion?
Answer: Its called "Floating point error".  The way that computers represent decimal numbers causes them to not be 100% accurate all the time:
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Comment: Yeah, It make sense. Thanks.
Answer: Try this
float sampleFloatValue = (float) sampleFloatString;

Hope it helps.
Answer: if you just wants to show these value somewhere than u can do these and it shows 1.3 exact..
NSString *sampleFloatString = @"1.3";
float sampleFloatValue = [sampleFloatString floatValue];
NSLog(@"%.1f",sampleFloatValue);


Traceback (most recent call last) math domain error

Question: import math

a = float(input("Digite 'a': "))
b = float(input("Digite 'b': "))
c = float(input("Digite 'c': "))

delta = b**2 - (4*a*c)

if(delta < 0):
  print("Raízes complexas!")
elif(delta == 0):
  print("2 raízes reais iguais!")
else:
  print("2 raízes reais diferentes!")

x1 = (-b + math.sqrt(delta))/2*a
x2 = (-b - math.sqrt(delta))/2*a

print("As raízes são:", x1, " e ", x2)

Digite 'a': 1
Digite 'b': 1
Digite 'c': 1
Raízes complexas!
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-51bd2b58d810> in <module>()
     14   print("2 raízes reais diferentes!")
     15
---> 16 x1 = (-b + math.sqrt(delta))/2*a
     17 x2 = (-b - math.sqrt(delta))/2*a
     18

ValueError: math domain error

Comment: Bom, ou vc usa o módulo `cmath`, que consegue trabalhar com números complexos (incluindo raiz quadrada de números negativos), ou então só calcule a raiz de delta se o delta for positivo, como foi feito por exemplo aqui: https://pt.stackoverflow.com/a/437857/112052
Comment: Da mesma forma que usou math: `import cmath` e depois `cmath.sqrt` (basicamente, onde tem "math", troque por "cmath")
Comment: Mas se possui raízes complexas por qual motivo você tenta calcula-las como se fossem reais?
Comment: Na realidade as raízes são: (-0.500000 - 0.866025*i) e (-0.500000 + 0.866025*i), onde i é a raiz quadrada de (-1).
Comment: O que eu estou tentando entender é quais são os fatores que causaram os 'ValueError', o que está errado no tocante a programação, não à matemática.
Comment: Sem ver o código é difícil adivinhar (seria bom [edit] a pergunta e adicioná-lo), mas *assumindo* que o delta foi calculado corretamente, então ele é negativo e `math.sqrt` lança um `ValueError` quando o número é negativo. Neste caso você deve usar o módulo cmath: https://docs.python.org/3/library/cmath.html#module-cmath - E sem querer ser chato mas já sendo, perceba que o erro está relacionado à programação **e também** à matemática :-)
Comment: Desculpe a ignorância, sou extremamente 'noob' na programação. Como eu uso o cmath?
Comment: E onde está `math.sqrt(delta)` use `cmath.sqrt(delta)`
Comment: Foi exatamente o que eu imaginei, muito obrigado.
Answer: O erro acontece por que o seu programa tenta conseguir a raiz quadrada de um número negativo, o que não é permitido pela função math.sqrt. Para pegar os valores complexos você terá que usar a biblioteca cmath:
import cmath

a = float(input("Digite 'a': "))
b = float(input("Digite 'b': "))
c = float(input("Digite 'c': "))

delta = b**2 - (4*a*c)

if(delta < 0):
  print("Raízes complexas!")
elif(delta == 0):
  print("2 raízes reais iguais!")
else:
  print("2 raízes reais diferentes!")

x1 = (-b + cmath.sqrt(delta))/2*a
x2 = (-b - cmath.sqrt(delta))/2*a

print("As raízes são:", x1, " e ", x2)


Passar locais e coordenadas de uma UITableView para um MapKit

Question: Esta é a minha primeira App e, basicamente, consiste em disponibilizar locais numa UITable (ponto de entrada da app) e consultá-los numa MapKit (modelo StoryBoard). Como posso fazer a ligação?
Estou a tentar usar um NSDictionary para os valores na tabela e depois o método PrepareForSegue. É possível incluir coordenadas específicas no Dicionário ou num Array separado? E como especificar no método PrepareForSegue?
O código:
@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _citySpots = @{@"Bars" : @[@"Hurricane", @"Black Swan", @"Texas"],
                       @"Clubs" : @[@"Electric Wizard", @"Offspring", @"The Tunnel"],
                       @"Restaurants" : @[@"Nando's", @"1/2 Burguer", @"Satellite"],
                       };

        _sectionTitles = [[_citySpots allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    }

O método PrepareForSegue:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"spotsDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

        MapViewController *destViewController = segue.destinationViewController;

        NSString *sectionTitle = [_sectionTitles objectAtIndex:indexPath.section];

         NSArray *citySpots = [_citySpots objectForKey:sectionTitle];
             //coordenadas?

    }
}

Answer: Você pode enviar o objeto pela UISegue pelo método -tableView:didSelectRowAtIndexPath::
- (void) tableView:(UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *) indexPath {
    NSString *sectionTitle = [_sectionTitles objectAtIndex:indexPath.row]; // ou indexPath.section, eleja o correto
    [self performSegueWithIdentifier:@"SUA_SEGUE_AQUI" sender:sectionTitle];
}

E capturá-lo em -prepareForSegue:sender::
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id) sender {
    if ([segue.identifier isEqualToString:@"SUA_SEGUE_AQUI"]) {
        MapViewController *destViewController = segue.destinationViewController;
        NSString *sectionTitle = (NSString *) sender;
        NSArray *citySpots = [_citySpots objectForKey:sectionTitle];
        destViewController.citySpots = citySpots;
    }
}


Compiler Integration Tests in Haskell

Question: I am planning to write a little toy compiler in Haskell for a very simple language in order to reinforce my Haskell skills and have fun designing a new language. I am still thinking about some general decisions and one of the biggest open points is how I would do integration tests. I have the following requirements:

It should be possible to create a list of triples (input, program, output), such that my integration test runs my compiler to compile the program, runs the compiled binary, passes the input to it and verifies that the output of the run is equal to the given output.

It should be possible to extend the integratiom test at a later point to test more complex interactions with the program, e.g. that it changes a file or sleeps for at least 20 seconds or something like that.

I also have the following optional requirements:

It should be as much an "end to end" as possible, i.e. it should treat the wholencompiler as a blackbox as much as possible and it shouldn't have to access the internals of the compiler or anything like that.
All code should be written in Haskell.
It would be nice if I would get typical testing framework functionality for free, i.e. without implementing it myself. E.g. a green "SUCCESS" message or a collection of error messages describing failures.

I have tried to find something that fulfills my needs, but I wasn't successful so far. The alternatives I considered are the following:

shunit would satisfy everything except the condition that I would like to write the code in Haskell.
QuickCheck would allow me to write everything in Haskell, but as I understand it, it seems to be mostly suited for tests that involve just a Haskell function and its result. So I would need to test functions in the compiler and relax my "end to end" requirement.
I could just write a Haskell program that starts the compiler in another process, passes it the input program and then starts the compiled code in another process, passes it the inpit and checks the output. This would however involve a lot of coding on my side in ordee to implement all the features that one gets for free when using a testing framework.

I am not sure yet which option I should choose and I still hope that I am missing a good solution. Do you have any idea on how I could create an integration test that fulfills all my requirements?
Answer:
I'm thinking unsafePerformIO should be quite safe here considering the programs should never interact with anything the testing environment/logic depends on, or, in other words, the compilation and execution should be viewable as a pure function in the context of testing in a controlled, isolated environment. And I reckon it's indeed useful to test your compiler in such conditions. And QuickCheck should then become an option even for blackbox testing. But some clearer minds could prove me mistaken.
So assuming your compiler is smth like:
type Source = String

compile :: Source -> Program

and your program execution is
data Report = Report Output TimeTaken OtherStats ...

execute :: Program -> IO Report

you could quite safely use unsafePerformIO to convert that into
execute' :: Program -> Report -- or perhaps 'executeUnsafe'
execute' = unsafePerformIO . execute

and then
compileAndExec :: Source -> Report
compileAndExec = compile . execute'

and use that with QuickCheck.

Whether execute invokes a subprocess, obtains an actual binary, executes that, etc, — or interprets the binary (or bytecode) in-memory, is up to you.
But I'd recommend separating byte code and binary generation: this way you can test the compiler separately from the linker/whatnot, which is easier, and also get an interpreter in the process.
Comment: Ok, thanks a lot, that is actually a good possibility. I haven't used unsafePerformIO yet and when I heard of it, I decided to avoid it as much as possible, but I guess this is exactly one of the cases where it is useful. The operation is kind of pure, but Haskell doesn't know that. And to get the QuickCheck framework to understand it, I have to use this. And besides, my fear of using unsafePerformIO should not apply to test code anyways.
Comment: _"but Haskell doesn't know that"_ — exactly! I actually even thought of adding that idea to the answer! The same goes about `unsafeCoerce` — it's when you _know_ for a fact something is correct but orthodox Haskell just doesn't seem to fit your fact in its belief system.

Compiler Integration Tests in Haskell


How do I add an edit button on each row of a "tableselect" form element?

Question: How do I add an edit button on each row of a "tableselect" form element?
The code I have is the following one.
<code>function example_elements_form() {
    $form = array();
    $header = array(
        'title' => array('field' => 'n.title', 'data' => t('Title')),
        'author' => array('field' => 'u.name', 'data' => t('Author')),
    );
    $query = "SELECT n.nid, n.title, u.name FROM {node} n INNER JOIN {users} u ON n.uid = u.uid". tablesort_sql($header);
    $result = pager_query(db_rewrite_sql($query));
    while($partial_node = db_fetch_object($result)) {
        $options[$partial_node->nid] = array(
            'title' => check_plain($partial_node->title),
            'author' => theme('username', $partial_node),
        );
    }
    if (!empty($options)) {
        $form['nodes'] = array(
            '#type' => 'tableselect',
            '#header' => $header,
            '#options' => $options,
        );
        $form['pager'] = array('#value' => theme('pager'));
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
        );
    }
    return $form;
}
</code>
Answer: Check out http://api.drupal.org/api/drupal/modules%21node%21node.admin.inc/function/node_admin_nodes/7
In particular, take a look at the lines that contain "operations". You need to set up a new element in $header to contain a column for the "operations", and then add at least one operation inside $options for each row.
You could either manually add a link to the edit with l(), or you could use module_invoke('node_operations') - again, an example of that is shown in the API.
Comment: Can I use image button instead of using text button for Edit button i.e, i want image instead of "EDIT"
Comment: Sure. You can use the l() function to add a class to your "a" tag, and then you can use CSS to put a background image on it and hide the text.


Workgroup Server 2019 - RD Licensing - No licenses issued, 60 minute client timeout message

Question: I have 2 machines with one (Server 2019 Standard) acting as a licensing server for my non-domain workgroup and the other a 2016 Standard machine. I configured the licensing server on the same day for both machines.
I installed the remote desktop licensing service on 18-Mar-2020 and installed 50 user and 50 device licenses. original install date for the machine running the licensing service is Feb-2019
I was then able to connect with 10+ clients on either machine simultaneously.
Today, 27 days later, connecting clients on the machine which hosts the licensing server receive:
"there is a problem with your remote desktop license and your session will be disconnected in 60 min"
This error does not appear when connecting to the other machine.
I have 7 sessions from a single laptop between both machines. The RD Licensing Manager shows "issued" as 0 for both device and user CALs.
I read that workgroup machines don't allow user CALs, so I converted mine to device CALs. Still 0 issued.
I verified that the local gp on either machine was configured (comp config > admin templates > rds > rd licensing > remote desktop session host > licensing >
1) use specified server is configured on both servers
2) remote desktop licensing mode was user, now set to device
used gpupdate /force when making changes, but the message about the 60m timeout persists on connection
RD licensing diagnoser "did not identify any problems to report"
i rebuilt the licensing database and re-applied the per-device licenses with no effect.
tried deleting MSLicensing registry key with no effect.
there are certificate entries in:
Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\RCM
...but I have not touched them
edit: I noticed that the license diagnoser on the 2019 machine is showing the version of the license server configuration is "Windows Server 2016" even though it is running on Windows Server 2019.
I also installed device licenses for 2016 as well, but this did not help.
Answer: I also ran into this problem, it seems that from the win 2016 version onwards if you have a user call it doesn't work unless they are put in an Active Directory.
see here: https://docs.microsoft.com/en-us/troubleshoot/windows-server/remote/cannot-connect-rds-no-license-server#nordcb
Comment: Unfortunately I cannot add anything to AD since these are not on a domain.