new \stdClass continua mostrando warning "Creating default object from empty value"

Question: Tenho o seguinte código php
    $obj = new \stdClass;

    foreach($_GET as $key => $value) {
        $obj->get->$key = $value;
    }

    foreach($_POST as $key => $value) {
        $obj->post->$key = $value;
    }

    return $obj;

O código funciona normalmente porém o warning do php

Warning: Creating default object from empty value in C:\Users\User\Desktop\loren\core\Route.php on line 31

continua sendo mostrado, mesmo eu instanciando o stdClass
O que deve ser feito?
Comment: Qual a versão do php que tem a correr ? O `obj` tem alguma utilização no código acima do que mostrou ?
Comment: Não é mais fácil fazer: `$obj = (object) $_POST;`?
Answer: O código que você fez faltou também dizer que os membros (get and post) também é do tipo \stdClass?
<?php

    $obj = new \stdClass;
    $obj->get = new \stdClass; // faltou isso
    $obj->post = new \stdClass; // faltou isso

    foreach($_GET as $key => $value) {
        $obj->get->$key = $value;
    }

    foreach($_POST as $key => $value) {
        $obj->post->$key = $value;
    }

    print('
');
    print_r($obj);


Where can I find the Dropbox log files?

Question: I am running Dropbox on a Debian server. Once I start Dropbox using
python dropbox.py start

it stops working after a while and
python dropbox.py status

reports:

Dropbox isn't running!

I have no clue why it stops working, all I see is that while running it consumes up to 100% of the CPU.
So I was wondering: Are there any Dropbox log files and if so, where can I find them?
Comment: seems like they are encoded or in a binary format?
Comment: could you check in ~/.dropbox/logs
Comment: @UeliHofstetter did you ever figure this out?
Comment: Anyone get an answer to this?
Comment: https://docs.python.org/2/library/pdb.html
Comment: I would advise to follow this lead:
https://unix.stackexchange.com/questions/198782/why-does-dropbox-say-killed-on-arch-linux Looking into this with `strace` would provide some feedback.
Answer: As described here you could install the Dropbox daemon as a system service, which then logs into journalctl.
Answer: I couldn't find the Dropbox log file location but the following workaround maybe useful.
Check your locale by the following command:
$ sudo locale

LANG=en_IN.UTF-8
LANGUAGE=en_IN
LC_CTYPE="en_IN.UTF-8"
LC_NUMERIC="en_IN.UTF-8"
LC_TIME="en_IN.UTF-8"
LC_COLLATE="en_IN.UTF-8"
LC_MONETARY="en_IN.UTF-8"
LC_MESSAGES="en_IN.UTF-8"
LC_PAPER="en_IN.UTF-8"
LC_NAME="en_IN.UTF-8"
LC_ADDRESS="en_IN.UTF-8"
LC_TELEPHONE="en_IN.UTF-8"
LC_MEASUREMENT="en_IN.UTF-8"
LC_IDENTIFICATION="en_IN.UTF-8"
LC_ALL=

Your locale maybe any result other than the above.
As dopbox doesn't work well with some specific locales try to change it to another one preferably en_US.UTF-8 or en_GB.UTF-8
To find available locale on you system try the following command:
$ sudo locale a

And to change the locale use the following command:
$ sudo update-locale LANG=LANG=en_US.UTF-8 LANGUAGE
OR
$ sudo localectl set-locale LANG=en_US.UTF-8

After successful start maybe you could change back to your desired locale.
Answer: Dropbox may be logging into the /tmp folder by default, and when navigating there, you may see files with a name like dropbox-antifreeze-Z8o8vO in that location.
In my experience, the contents of that log file may only indicate the startup/exit status of the dropboxd process, and other log information appears to be something that's not written to disk, but is communicated to the dropbox.py script when it communicates with the dropboxd process through the socket file at ~/.dropbox/command_socket

Where can I find the Dropbox log files?


How do I perform structural equation modelling with ordinal variables in stata?

Question: I'm doing a summer research project as an undergraduate, and I'm a bit lost with regards to how I should deal with ordinal variables. I'm testing a mediation model with latent variables in Stata, using structural equation modelling. The independent, dependent, and mediator variables are all latent variables with ordinal indicators.
I've found CenterStat's SEM workshop very helpful, but they only discuss continuous variables. From what I've read, I may need to use a different estimator than Maximum Likelihood, or I might be ok to treat my variables as continuous (according to this paper) I'm a bit stuck for where to go next - are there any good resources you might recommend for learning mor about this topic, or about how to go about it in Stata?
Thanks,
Evan
Comment: Never too late to try open source projects like [semopy](https://semopy.com/) or [lavaan](https://lavaan.ugent.be/).
Comment: Check out the `gsem` documentation.
Answer: This is a great question about ordinal indicators, and one that's usually not very well understood in terms of assumptions when we use Likert-type indicator variables. In brief, if you want to estimate a model that accounts for the non-continuous nature of the indicators you can use Stata's gsem command, which can also be invoked in the SEM model builder within Stata. Usually though you're right that most people treat such data as continuous and then use robust estimators such as MLR. You can request this within Stata if you'd like.


why anova() function is not applicable for models build using ridge regression and lasso regression in R?

Question: linRidgeMod <- linearRidge(Class ~ ., data = training[,vars])
anova(linRidgeMod)

or
mod <- lmridge(Class ~ ., data = training[,vars],K = 0.012)
anova(mod)

or
ridge_reg <- glmnet(x_train, y_train, nlambda = 25, alpha = 0, family = 'gaussian', lambda = lambdas)
anova(ridge_reg)

I have tried all the three methods to train model using ridge regression. The same common error is displayed for all these methods which is shown below.
Error in UseMethod("anova") :
  no applicable method for 'anova' applied to an object of class "ridgeLinear".

Error in UseMethod("anova") :
  no applicable method for 'anova' applied to an object of class "glmnet".

Answer: Same reason why LASSO or RIDGE do not return standard errors or test statistics or p-values. It does not make sense to do so because the models introduce bias in the coefficients by design (to improve predictions), which makes any tests on mean values  of coefficients inappropriate.


ngxs state operator to insert or replace item in array (upsert)

Question: I'm trying to replace or insert an array item (upsert) with existing ngxs state operators. I am currently using the following iif-statement. Is there an easier way to do this?
setState(
  patch({
    contractList: iif<Contract[]>(
      contractList=>
        contractList.some(
          contract =>
            contract.id === contractId
        ),
      updateItem<Contract>(
        contract =>
          contract.id === contractId,
        patch(loadedContract)
      ),
      insertItem<Contract>(loadedContract)
    )
  })
)

Answer: State operators exist but it doesn't mean you're forced to use them, right. There is a recipe called Immutability Helpers. It's going to be published to the main site in 1-2 weeks.
If we're talking about state operators then it's possible to create custom operators, that's some kind of decomposition:
function insertOrUpdateContract(id: string, loadedContract?: Contract) {
  return iif<Contract[]>(
    contracts => contracts.some(contract => contract.id === id),
    updateItem(contract => contract.id === id, patch(loadedContract)),
    insertItem(loadedContract)
  );
}

Thus there will be less code in your action handler and it will be more self-descriptive:
ctx.setState(
  patch({ contractList: insertOrUpdateContract(contractId, loadedContract) })
);

Otherwise you could have used immer library or something else preferred, that would save more code:
import { produce } from 'immer';

const state = produce(ctx.getState(), draft => {
  const index = draft.contractList.findIndex(contract => contract.id === contractId);
  // It exists then let's update
  if (index > -1) {
    draft.contractList[index] = loadedContract;
  } else {
    draft.contractList.push(loadedContract);
  }
});

ctx.setState(state);

For sure immer is an additional package for the project but it's very lightweight. It provides more declarative way to do such immutable updates. Choose what suits you best!
I would stop on some immutability helper when it comes to such complex state updates.


Dimension problems

Question: Let $f: \mathbb{R}^n \to \mathbb{R}^n$ be a linear transformation. Prove that there exists a subspace
$S \subseteq \mathbb{R}^n$ that verifies $\ker(f^2) = \ker(f) \bigoplus S$ and $\dim S = \dim f(S) \leq \dim(\ker(f))$.
My attempt at solution: So far I extended from the $\ker(f)$ to the $\ker(f^2)$ like this: let a base of $\ker(f)$ be $B = \{v_1,\ldots,v_r\}$ extending to a bae of $\ker(f^2)$ we get $B' = \{v_1,\ldots,v_r,v_{r+1},\ldots,v_m\}$. So I know that from $1$ to $r$ are elements linearly independent of $\ker(f)$, and from $r+1$ to $m$ I have my desired $S$. This verifies part of the second thing I'm asked, which is that $\dim S = \dim f(S)$, the thing is I'm having trouble with the inequality $\dim f(s) \leq \dim \ker(f)$. I've been trying to get the inequality using the dimension theorem but I cant seem to get it.
Comment: how do you know that $dim(ker(f^2))=n$ ??
Comment: my bad, thats m, not n.
Answer: You're defining $S$ to be the subspace with basis $\{v_{r+1}, \dots, v_m\}$, where $m \leq n$, right? The key property of this set is that $S \subset \ker(f^2)$ but $S$ is not in $\ker(f)$.  That means that if $w \in S$, then $f(w) \neq 0$ but $f(f(w)) = 0$.  Thus, $f(w) \in \ker(f)$.  You can conclude that $f(S) \subset \ker(f)$, which gives your inequality.

Dimension problems


How to convert bytes to MB on disk

Question: I have a file on my mac, when I clicked the Get Info, it showed as below

I wondered how 1,363,802bytes convert into 2.1MB ?
Answer: The "on disk" size measurement is telling you how much space your hard drive is using to store that file. The file is still only 1.36MB of data, but your hard drive has allocated 2.1MB of space to store it. Disks allocate storage space in units called "blocks" of a pre-defined size such as 4KB, so disks are often forced to allocate a little extra space in order to store files. The extra space is unused, but still counts of part of the file's size on disk.
Why is this image being allocated disk space almost 1.5X its size? Not sure!

How to convert bytes to MB on disk


An example in the fundamental theorem of equivalence relations?

Question: I've read about the fundamental theorem of equivalence relations. The idea that an equivalence relation on a set $X$ partitions $X$ is understandable. But the idea that for any partition of $X$ there is an equivalence relation on $X$ is a little weird.
Suppose I partition $\mathbb{N}$ as follows:
$$\{\{\text{primes}>3\},\{\text{even numbers}\},\{1\}\}$$
Then what would be the corresponding equivalence relation?
Comment: Note that the set of sets you suggest is not a partition of $\mathbb N$. **Edit:** Your question is discussed in great detail on Velleman's book. See Theorem 4.6.6 and onwards (second edition).
Comment: More specifically, there are naturals which don't fit in any of the sets of your suggested partition (such as 3 and 9).
Comment: @GitGud Yes. I forgot the non-prime odd numbers.
Answer: The equivalence relation would be "belongs to the same set of the partition". Nobody said that it had to be expressed without referring to the partition.
(And where is $9$ in your partition?)
Comment: Another thing: I was thinking about equivalence relation in the sense of equality. That's why it didn't make sense, but the equivalence relation could be about anything, right?
Comment: @Vÿska Exactly. Equivalence doesn't mean equality. I could define an equivalence relation on the set of natural numbers, such that "any two numbers are related".
Comment: Yes. I forgot the non-prime odd numbers. Silly mistake.
Answer: Let $P$ be a partition of set $S$. Then we can define the relation $R=\{ (a, b)\mid \exists T\in P: a\in T \wedge b\in T\}$. Which is basically the relation "belongs to the same set of the partition" (as said by the other answer). This relation can quite easily be proven to be an equivalence relation.
For some intuitive understanding:
Reflexive: an element $x$ of $S$ does of course belong to the same set of the partition as $x$.
Transitive: if $x$ is in the same set of the partition as $y$ and $y$ is in the same set of the partition as $z$ then $x$ and $z$ belong to the same set of the partition.
Symmetry: if $x$ is in the same set of the partition as $y$, then $y$ is in the same set of the partition as $x$.
You should be able to write a more formal proof on your own.


FIBA Shot Clock reset on throw-in touching ring

Question: I was going over a sample Q&A for a next level refs exam coming up. An answer stated the shot clock is reset to 14 secs after touching the ring.
It cited Art 29.  Which has this rule.

Article 29.2.3. After the ball has touched the ring of the opponents'
  basket, the shot clock shall be reset to
    24 seconds, if the opposing team gains control of the ball.
    14 seconds, if the team which regains control of the ball is the same team that was in control of the ball before the ball touched the ring.

However, during previous exam I recall the FIBA official interpretations using this exact scenario as an example.

17-20 Example: With 5 seconds remaining on the shot clock during the
  throw-in A1 passes the ball towards the basket where it touches the
  ring.
Interpretation: The shot clock operator shall not reset his
  clock, as the game clock has not started yet. The shot clock shall be
  started simultaneously with the game clock when the first player on
  the playing court touches the ball.

I would not reset the clock.  And plan to raise this with the committee.
Is there another section in the FIBA 2017 rules that supports the no reset as shot clock hasnt started view?
The interpretation should be based on an article.
Answer: There is nothing explicit in any rule to support this interpretation. However, Article 49 requires that

The timer shall measure  playing time  as follows:
Starting the game clock when:
...

During a throw-in, the ball touches or  is legally touched by a player on the playing court.

Since the ball is not in play when it first touches the ring, an argument can be made that it should not be included as a circumstance for Article 29.2 to be applied.
This is however a very weak argument, and without a statement from FIBA such as that in the Official Interpretations document, it would otherwise be ignored.
Comment: I think arguing you can not reset the shot clock if the game clock isnt running is the best point. Indeed I have seen a clock have this restriction  physically inbuilt which causes an issue if the game clock operator is slower to react that the shot clock operator.
Answer: There are a few situations covered by the FIBA rules. If it's just a throw-in with no extra info added, then the shot clock will start simultaneously with the game clock as defined in §50.1 (merely because the game clock is restarted under the same conditions):

Shot clock operator: Duties
50.1 Started or restarted when:

On  the  playing  court  a  team  gains  control  of  a  live  ball.  After  that,  the  mere  touching of the ball by an opponent does not
  start a new shot clock period if the same team remains in control of
  the ball.
On a throw-in, the ball touches or is legally touched by any player on the playing court.

With 5 secs remaining this scenario also may apply:

50.6 Switched off, after the ball becomes dead and the game clock has been stopped in any period when there is a new control of the ball
  for either team and there are fewer than 14 seconds on the game clock.


Get all registered Users into a Field Type List

Question: I would like to create a content/form where an authenticated user is able to choose another registered user from a list/dropdown. I've been searching for ways to get this done but am not able to find any working solution. Token can only display current-user, not all users. I can list all users using Views but not able to import them into the field of type list.
ie:
Nomination Form
Favorite Sport : [options](list from taxonomy)[/options]
Favorite Users : [options](list of all registered users)[/options]
etc
Appreciate if someone can point out what I am missing. Thank you
Answer: You can create form using Entity form.
It provides interface you to fetch content from the drupal fields taxonomy and other fields.
Term reference is inbuilt in drupal to add the Sports list.
For user reference list you can add the references module which will ask you to choose users from the registered users.
Hope it will help you


batch api for large batches

Question: After a form submit, can I create multiple batches based on the maximum table size for the serialized batch string and how can this be done?
I am using a batch process to pass users to an external site using their API.
For each user I set <code>$batch['operations'][] = array('process_funcion', array(LIST OF VARIABLES));</code>
The batch processing works for upto 5000 users; anything over that I get the following error:

Access denied
  You are not authorized to access this page.

I thought this had to do with max_packet size, but I am not to sure of that anymore.
The batch is being initiated after a form is being processed.
Do you have any ideas on how I can process 5000 users at a time, or why I am getting this error?
I think that the insert to the batch table is to big, so I am trying to split this into separate batches like this.
<code>$contactCount = 1;
foreach ($contacts as $contact) {
  $batch['operations'][] = array('_contact_add_batch', array($module, $acc_id, $Group_ID, $verb,$contact));
  //Due to max_packet_size restrictions, need to set multiple batches
  if (($contactCount % 2000) == 0){
    batch_set($batch);
  }
  $contactCount++;
}
// For the last set of batches, in the event that there is not 2000, lets add them also.
if (!empty($batch['operations'])) {
  batch_set($batch);
}
</code>
I am still getting the Access Denied error.
Comment: You sure that the error message is an Access Denied one instead of an Internal server error ? In most times, 5000 items shouldn't be the problem i guess. I have used it for 20,000 items..
Comment: @AyeshK It seems that when the batch is being set, the batch string is being serialized and placed into the batch table for processing. I understand that the amount of data being passed is more than what can be held in the table cell and so the serialized string is not actually written to the table.

What I am trying to do is set multiple batches to process around 2000 users per batch, but this does not seem to be working.
Answer: Batch API in Drupal 6 serializes everything into one row, causing the problem you've seen.
You need to do manually what Batch API does for you automatically in Drupal 7: use a queue.
The Drupal Queue module is a Drupal 6 backport of the Queue API that is in core for Drupal 7.
Basically, queue the items you want to process, and then only pass the queue ID to Batch API.
Batch API then fetches the queue and processes the queue part by part until it's done.
See batch_example_batch_2 from the Examples project for reference.
The Examples project also has an example module for queue usage, see:
http://drupalcode.org/project/examples.git/tree/refs/heads/7.x-1.x:/queue_example
Comment: That sounds like the perfect solution!!
I have been trying to work with queues for some time now and the documentation is really lacking.

If you have any good links for queue documentation, please could you share them.

In the mean time I will give this a try.
Comment: Edited my answer to provide a link to the queue example.

You can also read the docs at http://api.drupal.org/api/drupal/modules!system!system.queue.inc/group/queue/7
Comment: Tried this solution and it worked like a charm!!

batch api for large batches


Criando uma Sequencia de caracteres no PostgreSQL

Question: Então, eu tenho essa sequencia em uma coluna de uma tabela onde toda vez que eu faço uma inserção seu valor é definido por nextval ('ptable_pr_codigo_seq' :: regclass)
CREATE SEQUENCE public.ptable_pr_codigo_seq
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 103
  CACHE 1;
ALTER TABLE public.ptable_pr_codigo_seq
  OWNER TO postgres;

Agora, como posso fazer uma nova sequencia de forma que toda vez que eu faça uma inserção, o valor não é um número auto-numérico, mas sim um caractere em um intervalo [A ~ ZZZ] (de forma que ele avance a sequencia a cada inserção)?.

Exemplo: Primeiro insert           = A (valor da coluna)
         Segundo                   = B
         Terceiro                  = C
         27th                      = AA
         ...
         ?Th                       = ZZZ

Comment: Bem vindo ao SOpt. Por favor, traduza a questão para o português.
Comment: resolvido o problema
Comment: RT no comentário do @8biT
Comment: Da documentação [https://www.postgresql.org/docs/current/sql-createsequence.html]: você pode especificar opcionalmente um tipo de dado e os tipos válidos são: smallint, integer e bigint, (default bigint) portanto não é possível especificar uma string.
Comment: Mas lembre-se de que o PostgreSQL é um software livre e portanto nada impede que você crie e implemente seu próprio conjunto de rotinas de tratamento de sequences e o façam da maneira com que deseja. O código fonte está disponível em: https://doxygen.postgresql.org/
Comment: Basically it would be a "function" that would call the sequence and do a 'base conversion' an imaginary base 26, A B C D ... AA  / Basicamente seria uma "function" que chamaria a sequence e faria uma 'conversão de base' uma imaginária base 26 , A B C D ... AA...
Comment: e aí jovem ? resolveu seu problema ?
Answer: Não sei qual o objetivo, e quais poderiam ser vantagens e desvantagens disso;
Nunca havia pensado nisso até ver sua pergunta e pela curiosidade elaborei a resposta. Fiz a seguinte função no postgresql:
CREATE OR REPLACE FUNCTION public.to_char_sequence (bigint)
RETURNS varchar AS
$body$
declare

retorno varchar DEFAULT 'A';
letra varchar DEFAULT '';
xaux integer := $1;
currnum integer;

BEGIN

while (xaux > 0) LOOP

  currnum := (xaux - 1) % 26;
  letra := chr(currnum+65);
  retorno := retorno || letra;
  xaux = (xaux - (xaux + currnum+1))/26;

END LOOP;

return retorno;

END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;

Ao executar a função: Select to_char_sequence(27)

'AA'

Agora, crie uma sequência normalmente:
CREATE SEQUENCE public.teste_serie_id_seq
  INCREMENT 1 MINVALUE 1
  MAXVALUE 9223372036854775807 START 1
  CACHE 1;

E, na coluna que quer o incremento, defina o default value para:
to_char_sequence(nextval('teste_serie_id_seq'::regclass))

Pronto, vejamos o resultado:

Extra: Para que fique documentado, o código da função reversa:
CREATE OR REPLACE FUNCTION public.from_char_sequence (varchar)
RETURNS bigint AS
$body$
declare

retval bigint DEFAULT 0;
col varchar := upper($1);
colnum integer;
letra varchar;
len integer;
val integer;

BEGIN
retval := 0;
len := length(col);

FOR i IN REVERSE len..1 LOOP
    letra := substring(col from i for 1);
    colnum := ascii(letra)-64;
    val := colnum * ( pow(26 , (len - (i))))::integer;
    retval := retval + val;
END LOOP;

return retval;

END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;


Get list of taxonomy terms for current node through Views

Question: I've been trying this for awhile, and I keep finding answers that are close - but not quite.
If there is a node with taxonomy terms attached to it, I want to create a block in Views that I can place in the sidebar that will load the terms that are attached to THAT node.
I want to do it through Views so I can rewrite the URL with a custom query using the term IDs.
I'm open to other suggestions as well! I've also tried Display Suite, but I didn't want to go too far down that path just yet. The attached image is ideal, where the category taxonomy terms are being loaded based on terms that are attached to the node.
Ideal Wireframe Example
Comment: Just remember ask yourself what you're querying. Views is just a mysql gui with too many buttons. :)
Comment: Hah, yea. I find that turning the on the SQL queries helps me when debugging.
Answer: Come on it's not that hard!
I'm assuming you want to display all taxonomy terms across multiple taxonomy reference fields/vocabularies.
You can however filter the list of taxonomy terms that the View returns using Vocabulary filters.

Create a new view on Taxonomy table. You are basically showing taxonomy terms.
In the View creation page, uncheck "create page" and check "Create block". Give it a title "Categories". Click "Continue and Edit".
In the Views UI, add a new Relationship Taxonomy term: Content with term, and uncheck "require this relationship".
Add a new Contextual filter : Content: Nid  and choose the just-created relationship as the relationship, Provide default value > Content ID From URL under When the filter value is NOT available. Also add basic validation check to the contextual filter.

5 .  Save the View and put the block where you want to display.
You can check the view by entering a test node ID to the preview field. It should show all taxonomy terms attached to THAT node.
Comment: Oh my god, wow. I seriously thought I tried that combination. I was getting into some seriously complex contextual filters and relationships.

Thanks for the help!


Automatically modify iptables based on Apache log data to block badly behaved clients

Question: Is there any tool on Linux to automatically modify iptables so as to block a troublesome client based on an analysis of the Apache log? I help run a site that sometimes get overwhelmed by requests from a particular user. The only solution is to add an entry in iptables to block the offending client. Its usually too late by the time I can react manually - hence, I would like some rule based mechanism to modify the iptables. I would guess that some kind of fuzzly logic or statistical analysis would be necessary.
Answer: You can use something like fail2ban, which IIRC, has an Apache log checker built in.
Comment: fail2ban comes very close to doing what I want. Looks like I'll have to dig through the source a bit.
Answer: You might want to consider using iptables to rate-limit incoming connections. Which in its most basic setting will give you the ability to limit incoming connections to a number per minute.
For example, you might want to only allow 10 pings per minute from a single IP address. It does get a little more sophisticated than that, with the option to set burst limits on top of long term average limits.
Some good instructions on setting it up http://kevin.vanzonneveld.net/techblog/article/block_brute_force_attacks_with_iptables/
Comment: Excellent - I had no idea that iptables could even do that. This could be very useful.
Comment: I'll dig out an excellent guide i read recently on it
Comment: my bookmarks

http://www.debian-administration.org/articles/187

http://kevin.vanzonneveld.net/techblog/article/block_brute_force_attacks_with_iptables/
Answer: Check out OSSEC.  Best log file analyzer I've used. It also supports active response based on analysis.


Autosys BOX job containing no CMDs

Question: I am  new in my job and one of my responsibilities is to maintain a string of workload automation processes that run out of Autosys.  In browsing through the jobs, I noticed that some of them are job_type: BOX with no children of job_type: CMD within and no conditions either.  I can't figure the purpose of such a job.
Any idea?
Answer: Here are a few reasons:
One possible reason for this can be that the the children included jobs were decommissioned one by one but the box was never decommissioned.
Could be a place holder for future jobs that are to be put in later and are in design phase now.
Could be a coding error wherein the jobs that were to be included in the box got included in the main box.
Try running the following command to see the dependent jobs if any on your box.
job_depends -c -J box_name    if you do not get any dependent processes, you can verify if it is a place holder for a future job and if not, you can go ahead and delete it.
Hope this helps.

Autosys BOX job containing no CMDs


Logrotate wtmp `su prime gadmin` Contabo Ubuntu 20.04

Question: Logrotate gives error in Ubuntu server 20.04 from Contabo VDM:
Oct 31 00:00:01 foo logrotate[364456]: error: wtmp:3 unknown user 'prime'
Oct 31 00:00:01 foo logrotate[364456]: error: found error in /var/log/wtmp , skipping

I have in /etc/logrotate.d/wtmp
/var/log/wtmp {
    su prime gadmin
    missingok
    monthly
    create 0664 root utmp
    minsize 1M
    rotate 1
}

Ownership:
-rw-rw-r--  1 root    utmp             160128 Oct 30 23:10 wtmp

There is no user prime in passwd and there is no a gadmin command.
Any ideas what is that record and how to make it workable?
I simply commented out the first line for a test. It looks like Contabo provides customized distributions for their servers.
Comment: I guess you will have to ask Contabo why they put it there. That is not standard ubuntu. You can remove it with no ill effect.
Comment: Why do you try to use a username that does not exist?
Comment: This is a new Ubuntu 20.04 server from Contabo. I just found the error in the system log.
Answer: Removing the questionable instruction fixed the problem.
/var/log/wtmp {
    missingok
    monthly
    create 0664 root utmp
    minsize 1M
    rotate 1
}


Maya python: find bright spots in light texture in hdri and get the 3d coordinates

Question: This is my first time posting here. I hope someone can guide me to resolve my question.
In Maya,
Is there a way to get the 3d coordinates of the bright spots on the Hdri texture on Dome light. And extract those coordinates?
Can we do this in Nuke?
In Nuke, can we find the 2d coordinates of the brightest spots of an image and convert to 3d coordinates. Any help on this. Would be incredible!
Thank you!
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: In NUKE, if you import a 3D scene there, you can use a CurveTool node with the MaxLumaData tool to determine the brightest pixel of the shader's speculars, and a PointsTo3D node to generate 3D axis based on the position of the 2D point.

Camera must be animated, of course.
Comment: Thanks so much for getting back to me @andy.
I shall give this a go and revert back :)
Comment: i tried this and this does give me some translation values! Thats awesome!
Is there a way to get the rotation values and to get it re created in Maya itself?
Comment: Of course, but in Maya you need a "heavy" scripting for that.


Representação de instruçoes assembly

Question: Como interpretar uma instrução Assembly com seu valor hexadecimal em um endereço de memória?
8B 4C 24 04 CORRESPONDE A ISSO -> MOV ECX,DWORD PTR SS:[ESP+4]
Mas se tivesse só os valores hexadecimais como chegaria a esta instrução Intel x86?
Comment: Esses são Opcodes. Você tem que olhar no manual do processador. Esse [site](http://ref.x86asm.net/coder32.html#x8B) também pode ajudá-lo
Comment: Dê mais detalhes do que você quer. Mostre exemplos. Com perguntas pela metade você não consegue nem 10% de uma resposta. E vê se a *tag* está certa também. Não coloque qualquer uma. Coloque uma que ajude identificar o problema.
Comment: Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Nem tente fazer isto. É trabalho insano. Se quer fazer isto é melhor pegar um disassembler. Veja alguns disponíveis.
Se quiser fazer esta insanidade tem que ler toda documentação do processador. É bem mais complicado do que imagina, até para os programadores de baixo nível mais experientes.

Representação de instruçoes assembly


Aplicativos Android / iOs HTML

Question: Preciso desenvolver um aplicativo mobile, gostaria de fazer no estilo do aplicativo da globo, o qual é um site responsivo que é exibido, que programa devo usar para desenvolver em html e ser compilado para as plataformas?
Comment: Tente o Phonegap, atende bem as suas necessidades.
Answer: Você tem diversas formas de trabalhar com isso.
Pode usar o IONIC (Phonegap), tem o Intel XDK entre outras ferramentas.
Você também pode fazer um site responsivo, e encapsular dentro de uma webview no android, ios ou windows phone.
Comment: Só uma ressalva: O Ionic e o Phonegap são coisas diferentes. Vide [explicação](https://www.reddit.com/r/learnprogramming/comments/4cah35/what_is_the_difference_between_phonegap_and_ionic/)
Comment: eu gostaria dessa ultima opção, porem nao sei como encapsular em uma webview, existe algum programa para isso?
Comment: você ja tem o site pronto? se tiver basta criar um projeto no android studio.
Use o componente WebView e passa a Url do seu site.
Para funcionar libere acesso a internet no android manifest.
Caso não conheça programação mobile, vai ter que dar uma estuda basica para gerar os apps.
Comment: Sim, é o habitamais.com, apenas irei desenvolver uma pagina especifica para o app, você poderia me indicar tópicos para eu estudar? é bem simples o que quero fazer porém nunca tive experiencia com mobile
Comment: Vai ser multiplataforma ou apenas android?

Aplicativos Android / iOs HTML


Generate Unique Numbers in Array

Question: I'm new to javascript and trying to get comfy with Functions, For loops, and If statements. I'm working on a simple exercise that generates 5 random numbers from a function call. One bit of logic that I'm struggling with putting together is comparing the numbers created by Math.random that are pushed into an array. What's the best method to use to ensure that all numbers to push to the array are unique (no duplicates)? Would I add an If statement in the For codeblock that checks every number, and if they match, rerun the Math.random function? Trying to figure out if that's the best way to approach the problem.
function randoNumbers(min, max){

let randomNumbers = [];

for (let counter = 0; counter < 5 ; counter++){
    randomNumbers.push(Math.floor(Math.random() * (max - min) + +min));
    }
    console.log(randomNumbers);

}

randoNumbers(1, 10);

Comment: Possible duplicate of [Generate unique random numbers between 1 and 100](https://stackoverflow.com/questions/2380019/generate-unique-random-numbers-between-1-and-100)
Comment: Potential duplicate of https://stackoverflow.com/questions/2380019/generate-unique-random-numbers-between-1-and-100
Comment: https://gist.github.com/guilhermepontes/17ae0cc71fa2b13ea8c20c94c5c35dc4
Answer: A very plain solution would be to generate numbers until the generated number is not already included in the array, and then push it to the result array:

function randoNumbers(min, max) {
  const randomNumbers = [];
  for (let counter = 0; counter < 5; counter++) {
    let num;
    do {
      num = Math.floor(Math.random() * (max - min) + min);
    }
    while (randomNumbers.includes(num))
    randomNumbers.push(num);
  }
  console.log(randomNumbers);
}

randoNumbers(1, 10);

For slightly better complexity, you could use a Set instead (set.has is quicker than arr.includes):

function randoNumbers(min, max) {
  const set = new Set();
  for (let counter = 0; counter < 5; counter++) {
    let num;
    do {
      num = Math.floor(Math.random() * (max - min) + min);
    }
    while (set.has(num))
    set.add(num);
  }
  console.log([...set]);
}

randoNumbers(1, 10);
Comment: It depends on the situation, but ceteris paribus, simple is better, because code readability is one of the most important things to strive for. But, for example, if performance is a significant factor (which it rarely is), more complex code that runs more quickly can be worth it. (make sure to comment liberally if what the code is doing isn't obvious at a glance)
Comment: This is great thank you! So overwhelmed with the fact that there are so many ways to solve this example. What's the best method for selecting the right approach, simplicity or complexity? I'll check out the `includes` function to better understand how the solution works
Comment: Although, here I would argue that using a `Set` doesn't make the code any less readable and I would prefer it over using an array.
Comment: @slider Yep, it's not more complicated at all.
Answer: There are many ways to solve this problem. I am contributing my way of solving it.

function randoNumbers(min, max) {

  let randomNumbers = [];

  for (; randomNumbers.length < 5;) {
    const value = Math.floor(Math.random() * (max - min) + +min);
    if (!randomNumbers.includes(value))
      randomNumbers.push(value);
  }
  console.log(randomNumbers);

}

randoNumbers(1, 10);

Generate Unique Numbers in Array


How can I re-install live production server with minimal downtime?

Question: I need to reinstall Ubuntu Server running on VMWare VPS. The simplest way would certainly be to make a fresh install from mini ISO. But it's a production server and I can't afford an hour or more of downtime. Is it possible to reinstall with almost no downtime (say, 15 minutes or so)?
In other words, I'm looking for a way to upgrade OS release on live Ubuntu Server without noticeable downtime. I will transfer all settings and data manually.
Server facts:

Ubuntu Server 10.04.2 LTS amd64
VMWare VPS with console access (I can mount a local ISO image)
Single drive:

/boot, 92 MB on sda1 @ext4
/, 1.5 GB on LVM root @ext4
/srv, 19 GB on LVM data @ext4
swap on LVM swap

I have no experience with Linux file system tools (chroot and the like) yet. However, I guess a plan of action similar to the following might work (host is target VPS machine, upgrade is new OS):

Install upgrade OS
Install a fresh Ubuntu Server on local Virtual Box.
Transfer services and settings
Transfer services and settings from current OS to upgrade OS. I keep config as portable as possible and use etckeeper to track configuration changes.
Copy upgrade OS file system to host
I plan to use rsync to copy upgrade OS file system to host. But where to place it on host? I thought of:

a separate partition; I'd need to shrink LVM data on host and prepare new partition for the upgrade OS file system.
a file image; I'd create a file image on host's /srv partition, mount it on host (don't know how to yet) and copy upgrade OS file system into it.
a folder; I'd transfer mirror into folder on host's /srv partition. This would be the best option IMO, if at all possible.

Replace current OS with upgrade OS file system
I'm aware it depends on where the mirror has been transfered to. In any case it should be possible to switch first to test it working and replace file systems afterwards. I can afford to reboot and use recovery console or boot mini ISO for that.

Steps 3 and 4 are main question marks on which I need instructions. If you can advice changes to my 'plan' or a different approach, please, go ahead. Reference to instructions or documentation would be appreciated.
Edit: As suggested I'd go with a clone machine if I there's no other solution.
Comment: No experience with Ubuntu Server, but all my OS upgrades on both Ubuntu Desktop and Debian were in-place, with no reformats required. If you have a working system, and just want to upgrade the OS, why not make a backup and [do a normal upgrade](https://help.ubuntu.com/community/LucidUpgrades#Upgrade%20from%208.04%20LTS%20to%2010.04%20LTS) (example instructions for 8.04-10.04 upgrade. No idea which versions you need)?
Comment: @MikeRenfro I'm aware of dist upgrade in Ubuntu and been considering this. However, I **prefer** a clean environment, which only a new install can provide.
Answer: I've no idea what your commercial relationship is with your VPS provider but if this were my VMWare environment I'd simply clone the current production VM, bring the clone up with an adjacent IP address, apply changes/updates, move over anything that's changed from the production since the cloning, test the updated clone then when happy switch over the IPs and eventually kill the original VM.
Comment: Yes, that's definitely the simplest and most efficient method to upgrade or reinstall. The only drawback is the extra machine has to payed for, while I'm payed already. Thus I'm looking for a method to reinstall in-place. I can't vote yet, but I'd give +1 if I could.
Comment: There's another drawback I can think of. This method relays on VMWare and can't be applied to dedicated server (may be expensive) or other virtualization platforms, which don't support cloning.
Comment: I know the whole 'paid for' bit but the price paid for another VPS/VM for the week or two required will be worth it if it means a quick and safe upgrade. Oh and all other virtualised platforms DO support cloning, but you're right that it doesn't really work for physicals but then the OP said it was a VPS.


How to limit througput on an Apache Beam pileline in Go?

Question: I wrote a basic pipeline in Go running on Google Dataflow.
Basically it transforms Pubsub events to elastic documents and then update Elastic document in bulk.
I need to find a way to limit the number of Bulk request per second. Because when my pubsub subscription accumulated a lot of messages and my Dataflow streaming job wants to "catch up", it's literally killing my Elastic cluster.
How would you do it?
Comment: I have never user the Go SDK. In Python you would use something like this [RPC batching](https://beam.apache.org/documentation/programming-guide/#batching-rpcs), however, it seems that in Go [timers](https://beam.apache.org/documentation/programming-guide/#timers) have [not been implemented](https://github.com/apache/beam/issues/22737) yet.
Answer: You can use the Throttle transform. This transform limits the number of elements that pass through it per unit of time. You can specify the number of elements and the duration of the time window. Here is an example:
<code>import "github.com/apache/beam/sdks/go/pkg/beam"

func ThrottlePipeline(s beam.Scope, input beam.PCollection) beam.PCollection
{
    return beam.ParDo(s, func(_ []byte, emit func(interface{})) {
        emit(1)
    }, input).
        Apply(s, beam.WindowInto(window.NewFixedWindows(time.Second))).
        Apply(s, beam.CombinePerKey(sum.SumInt64)).
        Apply(s, beam.ParDo(func(_ []byte, count int64) {
            time.Sleep(time.Duration(count) * time.Second)
        }, beam.Impulse(s)))
}
</code>
You can adjust the duration of the time window to change the throughput rate.


Is a note that is enharmonic to a diatonic note of some diatonic scale, also diatonic in regards to that scale?

Question: I'm learning some music theory from a book, and encountered some question in my head that I can't seem to answer.
The question is in the title:

Is a note that is enharmonic to a diatonic note of some diatonic scale, also diatonic in regards to that scale?

An example:

Let's take the C major scale.
I know the note D is diatonic to this scale (it is the II degree of the scale).
What about Ebb? Is it also said to be diatonic to the C major scale?

It is the same pitch.

I understand a piece would be better to just use D and not Ebb 99% of the time, but we're talking theory here.
Answer: No, notes enharmonic to a diatonic scale are not diatonic in regards to that scale.
An easier example to envision for this purpose is whether D♭ is a diatonic note in A major since the enharmonic C♯ is. ...No, that D♭ is almost always a misspelling of a perfectly good diatonic note instead.
If sung, the enharmonic note should be more likely to be made slightly out of tune compared to its diatonic spelling (i.e. the C♯ should be sung in tune in that A major song, but the D♭ won't necessarily be sung in tune).
Comment: (Or, if a Db shows up in a piece with an A major signature, besides being a mistake it might be a non-diatonic moment—I'm having a hard time fabricating a plausible one for Db, but in general: the point stands that you don't just swap enharmonic equivalents at will; it will be one or the other for a good reason.)
Comment: @AndyBonner - The most common justified use for Db in an A major piece I can think of is one where the piece has modulated to a key where Db *is* diatonic...which makes one suspect the key signature should also be changed by that point.
Comment: Yeah, I was toying with some kind of crazy pivot-chord scenario, but couldn't come up with one that was real-world enough.
Answer:
I understand a piece would be better to just use D and not Ebb [in the key of C major] 99% of the time, but we're talking theory here.

Then let's talk theory. Theory should explain "why" it would be used or not used.
What does it mean to be diatonic? It isn't just a collection of frequencies, it's a collection of named pitches using the gamut of letters ABCDEFG, which creates the important sense of steps between scale degrees. When everything is spelled correctly the scale degrees are separated by steps and those steps then have functional, tonal, and modal identities within the scale.
When you use accidentals the diatonic purpose is to either change the tonal center - the tonic, even if it's just implied - or the mode, and that changes the function of the changed tone.
If we take away the specifics and just ask "what do flat type accidentals do?" We can say they normally lower tones to create new subdominants or change major mode to minor. In the specific case of a double flat, we can also say the tone being lowered must already be some kind of flat.
So, with an E double flat we are starting from something that would already be a flat, an E flat, and then we have lowered it to become either a subdominant or a minor mediant. E flat is the subdominant of B flat major, so E double flat is the subdominant of B double flat major. E flat is the minor mediant of C minor, so E double flat is the minor mediant of C flat minor.
In either case, it would obviously be easier to not use theoretical key signatures and spell our tone as D natural to be the subdominant of A major, or the minor mediant of B minor.
The interesting thing is the E double flat/D natural in those two cases isn't the only accidental involved with the changes. A G sharp would be important for the change to A major, and an A sharp would be important for the change to B minor. Both of those involve black keys on the piano, and in C major would require accidentals. It's hard to imagine what would prompt someone to then notate that white key above middle C as an E double flat!
The only reason I can think of for such odd enharmonic spellings is hypothetically using an accidental without a sense of functional reason, or not understanding key signatures and spelling chords in thirds.
I suspect the question arises, because in the specific case of E double flat in C major, the enharmonic is to a natural tone, a white key on the piano, and those white key sort of always seem diatonic. If the scenario were, for example G sharp, in F sharp major, respelled as A flat, I wonder if there would be the same sense of A flat is diatonic to F sharp major?
Bottom line: if you have introduced an accidental, you are not in the same place you started. You have either changed mode or tonic, and that resets the notion of what is diatonic.
Enharmonic equivalents will both be diatonic somewhere, but not in the same place.
Answer: Diatonic notes are those belonging to major or minor keys.It means the opposite to chromatic.
So the names of notes pertinent to a particular scale/key have specific names. That in itself means note D is diatonic to key C, whereas E♭♭ isn't - it's a different note name - and possibly even a different pitch in anything other than 12tet.
It's not even the case where a simpler C♯ is diatonic to key D, whereas D♭ is not. There won't be two different 'D' notes in a key.
Looking from a different angle, say key C, and slight modulation may include something like E♭♭ (can't bring one to mind though !!), but at that point, it would have to in fact be E♭♭, and not D♮, rendering it absolutely non-diatonic.
Comment: @Richard - yes, silly of me to forget that key C often modulates into key Fbb... Though I do find playing in Eb more comfortable.  I'm glad you're on board here with the more technical issues.
Comment: E♭♭ is the temporary leading tone to F♭♭, obviously ;-)
Answer: No.  The concept of 'diatonic' is all tied up with the concept of 'spelling it right'.    You could have picked a much simpler example - the seventh note of C major scale is B, not C♭.
Don't get too hung up on being diatonic.  The scale of the key or mode you're currently in is a framework, not a restriction.   It's absolutely fine to take that B and suddenly put an A♭ minor chord around it.   Then it would make sense to spell it as C♭, and this wouldn't necessarily imply a shift away from C major!
Comment: Cb actually is rare enough, especially as an enharmonic spelling, that I thought picking a black note instead would be the much simpler example (as those are commonly involved in enharmonic respellings). I actually think D<->Ebb and B<->Cb have much the same problems thinking-wise: the rarity of the second note of each pair makes one tempted to think it is diatonic anyway if the first one is.
Answer: There is a difference in describing the frequencies you hear and attribute to the scale versus the letter names and their convention.
All diatonic scales derive their letter names from the sequence
{A, B, C, D, E, F, G, A, B, C, D, ... etc}
As is, these are all "natural notes", meaning that they are in the key of C.  Consecutive notes are a step apart except for {B, C} and {E, F} which are 1/2 steps.
So, the degrees of the D major scale have the names {D, E, F, G, A, B, C, D}, i.e. some type of F is the third of D.  To make this a major scale you need to include the accidentals that make the sequence of steps (w-w-h)-w-(w-w-h).  For the sequence of letters to describe the D maj scale we need {D, E, F#, G, A, B, C#, D}.
Enharmonic tones, as you know, are two different names corresponding to the same sound, like A# and Bb, or B# and C.  However, as many answers point out, even though Gb is the "same" note as F#, Gb will never be the major 3rd of D by our naming convention.
It is also worth mentioning that this phenomenon is present on the piano, guitar, other fretted instruments, and some horns, because they are constructed to have equal tempered tuning.  In other tuning systems A# may not be the same frequency as Bb in any key.


TCP sockets with Zend Framework

Question: I want to query a WHOIS server with PHP. This means that I have to TCP connect to Port 43 on the WHOIS server. Is there a way to do this with the ZEND Framework? I only found HTTP socket adapters.
I will do it with the native PHP socket functions if ZF does not provide wrapper classes.
Thank you
Lennart
Answer: There is none. Your best bet is either plain php sockets, or you could check out phpclasses.org for already made whois classes.
Answer: why not using phpwhois for this?
It does not relate to zend framework, but this should be no problem.

TCP sockets with Zend Framework


CKEditor 5 change height event

Question: i want to trigger the height changes in the text area of ckeditor5. On the website i found the event 'change:height' but it isn't firing.
Here is my code:

 ClassicEditor
        .create(document.querySelector('#Comment'),{
            toolbar: [ 'heading', '|', 'bold', 'italic', 'blockQuote' ],
        })
        .then(editor => {
            console.log(editor);
            Editor = editor;
            console.log(Editor);
            editor.model.document.on( 'change:data', () => {

            } );
            editor.ui.focusTracker.on('change:isFocused', (evt, name, isFocused) => {

            } );
            editor.model.document.on( 'change:height', (eventInfo, name, value, oldValue) => {
                alert('height'); // ?????
            } );
        })
        .catch(error => {
            console.error(error);
        });
}

But it doesn't work ...
Do you have any ideas on how to fix it?
Thank you for your time and have a nice day :)
Answer: You can check the editor height inside the change event and see if the height has changed.
Please run the below snippet and check the console:

let editorWidth;
let editorHeight;

ClassicEditor
  .create(document.querySelector('#Comment'), {
    toolbar: [ 'heading', '|', 'bold', 'italic', 'blockQuote' ],
  })
  .then(editor => {

    editor.model.document.on('change', (eventInfo, name, value, oldValue) => {
        const newWidth = editor.ui.view.element.offsetWidth;
        const newHeight = editor.ui.view.element.offsetHeight;

        if(editorWidth !== newWidth || editorHeight !== newHeight) {
          console.log('Editor size changed. New size:', newWidth, newHeight);
          editorWidth = newWidth;
          editorHeight = newHeight;
        }
    });

  })
  .catch(error => {
      console.error(error);
  });

Comment: It works THANK YOU!!! Have a nice evening, stay healthy (and survive corona ^^)

CKEditor 5 change height event


Find the two points where the shortest distance occurs on two lines

Question: Find the point P on $\vec{AB}$ and point Q on $\vec{CD}$ such that $\vec{PQ}$ is the shortest distance
between the lines AB and CD, given $\vec{AB} = \begin{pmatrix}
1\\
0\\
2\\
\end{pmatrix}
+ u\begin{pmatrix}
-2\\
2\\
1\\
\end{pmatrix}
,\vec{CD} = \begin{pmatrix}
0\\
1\\
1\\
\end{pmatrix}
+ v\begin{pmatrix}
2\\
-1\\
-2\\
\end{pmatrix}
$ the normal vector $n=\begin{pmatrix}
-3\\
-2\\
-2\\
\end{pmatrix}
$
and the shortest distance is $\frac{3}{\sqrt{17}}$. I figured all this out from 4 given points but don't know how to find points P and Q. Please help, I'm stuck...
Answer: Once you know that the normal vector is $n$, the vector equation
$$
\begin{pmatrix}
1\\
0\\
2\\
\end{pmatrix}
+ u\begin{pmatrix}
-2\\
2\\
1\\
\end{pmatrix}
+w\begin{pmatrix}
-3\\
-2\\
-2\\
\end{pmatrix}
 = \begin{pmatrix}
0\\
1\\
1\\
\end{pmatrix}
+ v\begin{pmatrix}
2\\
-1\\
-2\\
\end{pmatrix}
$$
is equivalent to a system of three linear equations in three unknowns, which indeed has the unique solution
$$
u=\frac{19}{17},v=-\frac{15}{17},w=\frac{3}{17}.
$$
That tells you that the points on $\vec{AB}$ and $\vec{CD}$ are
$$
\begin{pmatrix}
1\\
0\\
2\\
\end{pmatrix}
+ \frac{19}{17}\begin{pmatrix}
-2\\
2\\
1\\
\end{pmatrix}
\quad\text{and}\quad\begin{pmatrix}
0\\
1\\
1\\
\end{pmatrix}
-\frac{15}{17}\begin{pmatrix}
2\\
-1\\
-2\\
\end{pmatrix},
$$
respectively. (It also tells you that the distance between the two lines is the norm of $\frac3{17}(-3\ {-2}\ {-2})$, or $\frac3{\sqrt{17}}$ as you indicated.)
Answer: If the normal vector is not provided in the question, you can still solve the question.
Any point $P$ on line $\vec{AB}$ given $u$ can be represented as
$\begin{pmatrix}
  1-2u \\
2u\\
2+u
\end{pmatrix}$
, whilst point any point $Q$ on line $\vec{CD}$ given $v$ can be represented as
$\begin{pmatrix}
  2v \\
1-v\\
1-2v
\end{pmatrix}$,
$\vec{PQ}=$
$\begin{pmatrix}
-1+2u+2v \\
1-2u-v\\
-1-u-2v
\end{pmatrix}$
You can interpret the shortest distance between $\vec{AB}$ and $\vec{CD}$ at points $P$ and $Q$ as a separate line that is perpendicular to both $\vec{AB},\vec{CD}$ at the same time, similar to how the shortest distance from a point to a line functions:
$$
\vec{PQ} \perp \vec{AB} \\
\vec{PQ} \perp \vec{CD}
$$
The dot product between two perpendicular vectors is 0, which gives:
$$
\vec{PQ} \cdot \vec{AB} =
\begin{pmatrix}
-1+2u+2v \\
1-2u-v\\
-1-u-2v
\end{pmatrix}
\cdot
\begin{pmatrix}
-2 \\
2\\
1
\end{pmatrix} =
0 \\
\vec{PQ} \cdot \vec{CD} =
\begin{pmatrix}
-1+2u+2v \\
1-2u-v\\
-1-u-2v
\end{pmatrix}
\cdot
\begin{pmatrix}
2 \\
-1\\
-2
\end{pmatrix} =
0
$$
Which gives the following system of equations
$$
\begin{aligned}
3-9u-8v = 0\\
-1+8u+9v=0
\end{aligned}
$$
Solving for $u,v$ gives $u=\frac{19}{17},v=-\frac{15}{17}$, which can be substituted back to calculate the coordinates of $P$ and $Q$, giving $P=(\frac{38}{17}, \frac{53}{17}, -\frac{21}{17}), Q=(-\frac{30}{17}, \frac{32}{17}, \frac{47}{17})$


Clarification of notation related to law of indices for rings

Question: I am new to abstract algebra. While reading a text on ring theory,a part of the law of indices was stated as :
for all $a,b$ belonging to a Ring $(R,+,\cdot)$ ; $a^m \cdot a^n=a^{m+n}$ where $m$ and $n$ are positive integers.
Since $+$ and $\cdot$ could be any binary operations satisfying the definition of a ring and hence possibly different from addition and multiplication, I wish to know to know if the $+$ in $a^{m+n}$ refers to any such binary operation or just addition. I think that this should generally be true only for addition.
Answer: The $+$ in $a^{m+n}$ is the addition in $\mathbb N$.
The $\cdot$ in $a^m \cdot a^n = a^{m+n}$ is the multiplication in the ring $R$.


Shapley for Logistic regression?

Question: Does shapley support logistic regression models?
Running the following code i get:
logmodel = LogisticRegression()
logmodel.fit(X_train,y_train)
predictions = logmodel.predict(X_test)
explainer = shap.TreeExplainer(logmodel )

Exception: Model type not yet supported by TreeExplainer: <class 'sklearn.linear_model.logistic.LogisticRegression'>

P.S. You are supposed to use a different explainder for different models
Answer: Shap is model agnostic by definition. It looks like you have just chosen an explainer that doesn't suit your model type. I suggest looking at KernelExplainer which as described by the creators here is

An implementation of Kernel SHAP, a model agnostic method to estimate SHAP values for any model. Because it makes not assumptions about the model type, KernelExplainer is slower than the other model type specific algorithms.

The documentation for Shap is mostly solid and has some decent examples.
Comment: No problem. Glad it helped.
Comment: Ah  i see. Thanks, this was simpler than i though, i appreciate it
Answer: explainer = shap.LinearExplainer(logmodel) should work as Logistic Regression is a linear model.
Comment: It does, but only if there are two classes.
Answer: Logistic Regression is a linear model, so you should use the linear explainer.

Shapley for Logistic regression?


Scroll an overflowing div by scrolling anywhere on the page

Question: I'd like to trigger scrolling of a div with overflowing content by scrolling anywhere on the page, not just by moving the mouse and clicking within the div. Also, i'd like to hide the div's scrollbar such that only the page's scrollbar is visible.
Preferably the solution would be CSS-based but a JS solution would work too.
here's my jsfiddle that demonstrates the problem: http://jsfiddle.net/trpeters1/RMZsX/8/
I'd copy the code here but there I put a bunch of filler text to trigger the scrollbars.
For you reference though, the name of the internal div I'd like to scroll on scrolling the page has an id="scrollMeToo".
Comment: That is not a simple thing to implement. Do you have any javascript experience?
Comment: @laymanje yes, i have javascript experience. let me try perdickss's solution below to see if that solves the problem...
Comment: @laymanje i tried implementing perdickss's solution but it didn't quite work, can you give it a shot? http://jsfiddle.net/trpeters1/RMZsX/11/
Answer:

var curScroll = 0;

$(window).bind('mousewheel DOMMouseScroll', function(e){
    var evt = window.event || e;
    var delta = evt.detail? evt.detail*(-120) : evt.wheelDelta;
    if(delta < 0) {
        //scroll down
        curScroll += 10;
    }
    else {
        //scroll up
        curScroll -= 10;
    }
    $('#scrollMeToo').scrollTop(curScroll);
    return true;
});
#scrollMeToo {
    height: 200px;
    width:150px;
    overflow: auto;
    position: relative;
    overflow-y: hidden;
}

            Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

            Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

            Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

@fat

            Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

@mdo

            Veniam marfa mustache skateboard, adipisicing fugiat velit pitchfork beard. Freegan beard aliqua cupidatat mcsweeney's vero. Cupidatat four loko nisi, ea helvetica nulla carles. Tattooed cosby sweater food truck, mcsweeney's quis non freegan vinyl. Lo-fi wes anderson +1 sartorial. Carles non aesthetic exercitation quis gentrify. Brooklyn adipisicing craft beer vice keytar deserunt.

one

            Occaecat commodo aliqua delectus. Fap craft beer deserunt skateboard ea. Lomo bicycle rights adipisicing banh mi, velit ea sunt next level locavore single-origin coffee in magna veniam. High life id vinyl, echo park consequat quis aliquip banh mi pitchfork. Vero VHS est adipisicing. Consectetur nisi DIY minim messenger bag. Cred ex in, sustainable delectus consectetur fanny pack iphone.

two

            In incididunt echo park, officia deserunt mcsweeney's proident master cleanse thundercats sapiente veniam. Excepteur VHS elit, proident shoreditch +1 biodiesel laborum craft beer. Single-origin coffee wayfarers irure four loko, cupidatat terry richardson master cleanse. Assumenda you probably haven't heard of them art party fanny pack, tattooed nulla cardigan tempor ad. Proident wolf nesciunt sartorial keffiyeh eu banh mi sustainable. Elit wolf voluptate, lo-fi ea portland before they sold out four loko. Locavore enim nostrud mlkshk brooklyn nesciunt.

three

            Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

Keytar twee blog, culpa messenger bag marfa whatever delectus food truck. Sapiente synth id assumenda. Locavore sed helvetica cliche irony, thundercats you probably haven't heard of them consequat hoodie gluten-free lo-fi fap aliquip. Labore elit placeat before they sold out, terry richardson proident brunch nesciunt quis cosby sweater pariatur keffiyeh ut helvetica artisan. Cardigan craft beer seitan readymade velit. VHS chambray laboris tempor veniam. Anim mollit minim commodo ullamco thundercats.

This should do what you need, if you don't want the document to scroll, just change the return true; to return false;.
Non-jQuery method:

var curScroll = 0;

function controlScroll (e) {
    var evt = window.event || e;
    var delta = evt.detail? evt.detail*(-120) : evt.wheelDelta;
    if(delta < 0) {
        //scroll down
        curScroll += 10;
    }
    else {
        //scroll up
        curScroll -= 10;
    }
    document.getElementById('scrollMeToo').scrollTop = curScroll;
};

if (document.attachEvent) {//if IE (and Opera depending on user setting)
    document.attachEvent("onmousewheel", controlScroll)

}
else if (document.addEventListener) { //WC3 browsers
    document.addEventListener("mousewheel", controlScroll, false)
}
#scrollMeToo {
    height: 200px;
    width:150px;
    overflow: auto;
    position: relative;
    overflow-y: hidden;
}

            Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

            Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

            Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

@fat

            Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

@mdo

            Veniam marfa mustache skateboard, adipisicing fugiat velit pitchfork beard. Freegan beard aliqua cupidatat mcsweeney's vero. Cupidatat four loko nisi, ea helvetica nulla carles. Tattooed cosby sweater food truck, mcsweeney's quis non freegan vinyl. Lo-fi wes anderson +1 sartorial. Carles non aesthetic exercitation quis gentrify. Brooklyn adipisicing craft beer vice keytar deserunt.

one

            Occaecat commodo aliqua delectus. Fap craft beer deserunt skateboard ea. Lomo bicycle rights adipisicing banh mi, velit ea sunt next level locavore single-origin coffee in magna veniam. High life id vinyl, echo park consequat quis aliquip banh mi pitchfork. Vero VHS est adipisicing. Consectetur nisi DIY minim messenger bag. Cred ex in, sustainable delectus consectetur fanny pack iphone.

two

            In incididunt echo park, officia deserunt mcsweeney's proident master cleanse thundercats sapiente veniam. Excepteur VHS elit, proident shoreditch +1 biodiesel laborum craft beer. Single-origin coffee wayfarers irure four loko, cupidatat terry richardson master cleanse. Assumenda you probably haven't heard of them art party fanny pack, tattooed nulla cardigan tempor ad. Proident wolf nesciunt sartorial keffiyeh eu banh mi sustainable. Elit wolf voluptate, lo-fi ea portland before they sold out four loko. Locavore enim nostrud mlkshk brooklyn nesciunt.

three

            Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

Keytar twee blog, culpa messenger bag marfa whatever delectus food truck. Sapiente synth id assumenda. Locavore sed helvetica cliche irony, thundercats you probably haven't heard of them consequat hoodie gluten-free lo-fi fap aliquip. Labore elit placeat before they sold out, terry richardson proident brunch nesciunt quis cosby sweater pariatur keffiyeh ut helvetica artisan. Cardigan craft beer seitan readymade velit. VHS chambray laboris tempor veniam. Anim mollit minim commodo ullamco thundercats.

In order to change the scrolling speed, simply modify this block to suit your needs:
if(delta < 0) {
    //scroll down
    curScroll += 10;
}
else {
    //scroll up
    curScroll -= 10;
}

Just change the 10 values to whatever you need.
Update:
var curScroll = 0;

$(window).on('mousewheel DOMMouseScroll', 'body', function(e){
    var evt = window.event || e;
    var delta = evt.detail? evt.detail*(-120) : evt.wheelDelta;
    var loc = $('#scrollMeToo').scrollTop() + $('#scrollMeToo').innerHeight();
    var height = $('#scrollMeToo')[0].scrollHeight - 10;
    var height2 = $('#scrollMeToo')[0].scrollHeight - $('#scrollMeToo').innerHeight();
    if(delta < 0) {
        //scroll down
        if (curScroll < height2) {
            curScroll += 10;
        }
    }
    else {
        //scroll up
        if (curScroll > 0) {
            curScroll -= 10;
        }
    }
    if (loc >= height && !$('#scrollMeToo').hasClass('appended')) {
        var moreContent ='a link';
        $('#scrollMeToo').append(moreContent);
        $('#scrollMeToo').addClass('appended');
        console.log('appended');
    }
    $('#scrollMeToo').scrollTop(curScroll);
    return true;
});

This modification should suit your needs, according to what you've described.  I've also altered the function slightly for some general fixes.
The content will appear just before the bottom of the div is reached, and will only appear once.
Comment: -@daedalus, what parameters do I change to make the scrolling "speed" more in line with the document? Would you mind and that in comments to the jsfiddle or your answer?
Comment: @timpeterson I've edited my answer for you to include that information.
Comment: -@daedalus, this is working great, you understood my scroll "speed" request. one more question if it is not too much trouble. I'd like to use this scrolling with AJAX appended data.  My append() event is triggered when you scroll to the bottom of the page but now that the y-overflow is hidden, the data isn't showing. Any thoughts on how to modify the JS/CSS to show this data? I've tried using the jQuery `on()` method instead of `bind()` for the `mouseScroll` but that didn't help.
Comment: @timpeterson I'm afraid I'm having difficulty understanding your request; if a fiddle is possible, that could possibly assist.
Comment: Rather than simply having the overflowing content appear within the `#scrollMeToo` div upon scrolling, i'd like to AJAX load it and have it appear as if it was always there to begin with. i'd like to trigger this `append` once one scrolls to the bottom of the page. here's a fiddle which kinda shows what i mean: http://jsfiddle.net/trpeters1/gtEvp/9/. I say "kinda" because I don't want to append the content everytime you scroll only when once you hit the bottom of the page. Unfortunately, It's hard to emulate AJAX on jsfiddle. Thoughts?
Comment: @timpeterson I've updated my answer according to your request.
Comment: thanks so much for taking a shot at this! I'm gonna accept your answer. Your newest fiddle looks close but i'm not seeing the google link appended after the word "thundercats". Is there a small JS error in there somewhere?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/11353/discussion-between-daedalus-and-tim-peterson)
Answer: you can set overflow:hidden for div .and set css to deselection div content.
 var clicking = false;
 var position;
 var scrollpos;
$(window).mousedown(function(e){
    clicking=true;
    position = e.pageY;
});
$(window).mouseup(function(){
      clicking = false;
})
$(window).mousemove(function(e){
      if(clicking == false)
            return;
      scrollpos=$('#scrollMeToo').scrollTop();
      $('#scrollMeToo').scrollTop(scrollpos + (e.pageY-position)) ;
})

Comment: -@perdickss hi, can you explain your comment, "set css to deselection div content"? I can't quite understand what you mean. thanks,
Comment: -@perdickss, can you try implementing your solution in the jsfiddle? my version of it doesn't work http://jsfiddle.net/trpeters1/RMZsX/11/
Comment: i mean : when you scroll every where of page your div will be scrolled but div content will select when you scrolling .for solution you can set css attribute for deselectable your div content. sorry for bad english.
Comment: -@perdickss, can you show the code in the jsfiddle or in your answer what the CSS change looks like? I'm still having trouble understanding you
Comment: ok look at [here](http://cbest.ir/css/1.html) . and pay attention to css attributes in source code.
Comment: -@perdickss, thanks for this. The content doesn't scroll though, can you explain?
Comment: sorry.now i fixed it for IE and FF and chrome.
Comment: -@perdickss can you share the link for your fixed demo? Your previous link, http://cbest.ir/css/1.html, still doesn't work.
Comment: test with diff browsers . see [http://jsfiddle.net/freealone/eEhky/](http://jsfiddle.net/freealone/eEhky/)
Comment: if still it doesn't work for you test with jquery 1.6.4 library not with higher version.


SQL converting Date datatype from Varchar to Date

Question: so I'm trying to convert my date column datatype from varchar to date.
Currently my date is in d/m/yyyy format and I want to convert to standard mm/dd/yyyy
Here's the script that I'm running
update [table]
set [PERIOD]= CONVERT(varchar(20),cast([PERIOD] as date),101)

But I'm getting an error
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Any tips or am I stuck?
Comment: Are all of the dates in a recognizable format(by SQL) in the table?
Comment: going back to the ol pre Y2K format eh?
Comment: `mm/dd/yy` is hardly *standard*, at least since people learned a few decades ago the problems with storing 2-digit years. (Unless, of course, you've discovered the secret of time-travel and are posting here from the 1990s before SO existed.)
Comment: @KenWhite Oops I screwed up. `mm/dd/yyyy` is what I'm trying to achieve. Thanks Ken
Comment: sorry @Kritner I meant `mm/dd/yyyy`. Thanks for catching that
Comment: Check whether there is junk data in [PERIOD] column. What is the datatype of [PERIOD] column? @Mike V.
Comment: @SarathAvanavu datatype is `varchar(MAX)`
Comment: @MikeV.  You are definitely getting the error because you cannot `CAST()` `d/m/yyyy` as `DATE`, hence the `CONVERT()` in my answer.  If you get the same error using `CONVERT()` instead of `CAST()` then it means you have invalid values.
Answer: I suggest instead of updating one string date to another format of string date, that you add a new DATE or DATETIME field to store the dates properly.
ALTER [table] ADD Proper_Date DATE
GO
UPDATE [table]
SET Proper_Date = convert(date, [PERIOD], 103)

If you must, you can wrap the above in another CONVERT():
update [table]
set [PERIOD]= CONVERT(varchar(20),convert(date,[PERIOD], 103),101)

Answer: You may have junk value and can get the junk values by executing the following query
SELECT [PERIOD]
FROM YOURTABLE
WHERE ISDATE([PERIOD]) = 0

To avoid junk values and update the rest try the below
update YOURTABLE
set [PERIOD]= CONVERT(varchar(20),cast([PERIOD] as date),101)
WHERE ISDATE([PERIOD]) = 1

Answer: I think if you can segregate the day and month and the year by using substring or any other string functions then use the below query
update tableA
set period = convert(datetime,cast(day(1)as varchar)+'/'+cast(MONTH(1)as varchar)+'/2014',102)

Hope its works.
Answer: Try this.
update [table]
set [PERIOD]= CONVERT(varchar(20),CONVERT(date,[PERIOD] ,103),101)

Problem in your query is
cast([PERIOD] as date)

You cannot directly convert d/m/yyyy format to date. So use 103 style to convert
Comment: Whoever downvoted please comment whats wrong in the answer so that i can improve.


Sine integral inequality $\int^{\infty}_{0}\sin(x)f(x)\,dx\leq\int^{\infty}_{0}\sin(x)g(x)\,dx$

Question: Let $f(x)$ and $g(x)$ be two real valued functions such that $f(x)\leq g(x)$ for all $x\in\mathbb{R}$. Assume that $\int^{\infty}_{0}\sin(x)g(x)\,dx<\infty$. Is it true that $$\int^{\infty}_{0}\sin(x)f(x)\,dx\leq\int^{\infty}_{0}\sin(x)g(x)\,dx$$
Comment: why should that be true? $\sin$ is changing signs.
Comment: for instance if $f(x)=\frac{1}{x}$ for $x>0$ and zero otherwise, while $g(x)=\frac{2}{x}$ for $x>0$ and zero otherwise then on the left you get $\frac{\pi}{2}$ and on the right you get $\pi$. This is one example. I am interested if this is true for any pair of functions satisfying these conditions.
Answer: Not true. Let $f( x ) = 0$ for all $x$ belongs to $\mathbb R, g( x ) = 1$ when $\pi < x < 2\pi$, and $g( x ) = 0$ otherwise.
Comment: I don't think your example contradicts the statement. On the left side one would get $0$ as $f(x)$ is identically zero, on the right side you would get $-\cos(2\pi)-(-\cos(\pi))=-1-(-1)=0$.
Comment: @Adrian $-(-\cos(\pi)) = -(-(-1)) = -1$
Comment: In case $f(x)$ and $g(x)$ are non-negative and $0<\int^{\infty}_{0}\sin(x)g(x)\,dx<\infty$ would the statement hold then?
Comment: @Adrian It is the same. Choose an interval in which sin is positive, and modify the f and g above such that they are equal and positive in this interval,and moreover, the integration on it cancel the -2 which make the total integration positive.


Implementando busca com Angular 4

Question: Observem a imagem

O usuário ira digitar no campo titulo para efetuar uma busca na tabela, porém aparece um erro no console do navegador

A mensagem de erro informa que o problema está no método pesquisar no arquivo HTML, bem aqui;
 <form autocomplete="off" (ngSubmit)="pesquisar()">

O código completo está aqui;

    <form autocomplete="off" (ngSubmit)="pesquisar()">

        Título
        <input pInputText type="text" name="titulo"
        [(ngModel)]="titulo">

        Fonte
        <input pInputText type="text" style="width: 200px" name="font"
      >

        <button pButton type="submit" label="Pesquisar"></button>

    </form>

        <ng-template let-lanc="rowData" pTemplate="body">
          {{ lanc.dataNoticia | date:'dd/MM/yyyy' }}
        </ng-template>

              <ng-template let-lanc="rowData" pTemplate="body">
                <button pButton icon="fa-angle-double-right"
                pTooltip="Visualize" tooltipPosition="top"
                ></button>
              </ng-template>

Preciso corrigir o problema, eu acho que pode está no componente ou no serviço.
Componente
titulo: string;
  noticias = [];

  constructor(private noticiaService: NoticiaService) { }

  ngOnInit() {
     this.pesquisa();
  }

  pesquisa() {
      this.noticiaService.pesquisar({ titulo: this.titulo })
      .subscribe(noticias => this.noticias = noticias);
  }

Serviço
import { Noticia } from './../core/model';

import { Http,  URLSearchParams } from '@angular/http';
import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';

export interface NoticiaFiltro {
  titulo: string;

}

@Injectable()
export class NoticiaService {

  noticiasUrl = 'http://localhost:8080/noticias';

  constructor(private http: Http) { }

  pesquisar(filtro: NoticiaFiltro): Observable <Noticia[]> {

    const params = new URLSearchParams();

    if (filtro.titulo) {
      params.set('titulo', filtro.titulo);
    }

    return this.http.get(`${this.noticiasUrl}`, {search: params})
      .map( response => response.json().content);

  }

}

Answer: No html você está chamando pesquisar e no componente o nome do método pesquisa
Comment: Parabéns, muito obrigado

Implementando busca com Angular 4


python regex and replace

Question: I am trying to learn python and regex at the same time and I am having some trouble in finding how to match till end of string and make a replacement on the fly.
So, I have a string like so:
ss="this_is_my_awesome_string/mysuperid=687y98jhAlsji"

What I'd want is to first find 687y98jhAlsji (I do not know this content before hand) and then replace it to myreplacedstuff like so:
ss="this_is_my_awesome_string/mysuperid=myreplacedstuff"

Ideally, I'd want to do a regex and replace by first finding the contents after mysuperid= (till the end of string) and then perform a .replace or .sub if this makes sense.
I would appreciate any guidance on this.
Answer: You can try this:
 re.sub(r'[^=]+$', 'myreplacedstuff', ss)

The idea is to use a character class that exclude the delimiter (here =) and to anchor the pattern with $
explanation:
[^=] is a character class and means all characters that are not =
[^=]+ one or more characters from this class
$  end of the string
Since the regex engine works from the left to the right, only characters that are not an = at the end of the string are matched.
Comment: Thanks so much for this. So, does the `+$` look for end of string?
Comment: No only `$`, `+` is quantifier for `[^=]` that mean 1 or more times, I will edit a more detailed explanation soon.
Comment: Thanks so much for your detailed explanation - I have certainly learnt here. Accepted your answer.
Answer: You can use regular expressions:
>>> import re
>>> mymatch = re.search(r'mysuperid=(.*)', ss)
>>> ss.replace(mymatch.group(1), 'replacing_stuff')
'this_is_my_awesome_string/mysuperid=replacing_stuff'

You should probably use @Casimir's answer though. It looks cleaner, and I'm not that good at regex :p.
Comment: you should read more about regexps on sites like [courses on the MIT](http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-045j-automata-computability-and-complexity-spring-2011/lecture-notes/MIT6_045JS11_lec04.pdf) and also practice on [tutorial sites](http://regexone.com/). I think it helps a lot to understand that Regexps are "simply" automata with cabalistical characters. In the end, it's expression is far less sophisticated than most programming language.. but the paradox is that it is harder to learn :-)
Comment: thanks so much for the alternative solution. I agree, Casimirs answer is a clean one liner. I agree - I am trying to be good with regex! I am quite bad at this!
Comment: @JamesW Well, you aren't alone :)

python regex and replace


Multiclass SVM with Spark 1.6?

Question: I ran a multi-class Logistic Regression with Spark but I would like to use
 SVM to cross validate results.
It looks like Spark 1.6 only supports SVM binary classifications. Should I use other tools to do this? H20 for example?
Answer: After some research, I found this branch which was not integrated in Spark 1.6 that allowed me to run the SVM on a multi class classification problem.
Big thanks to Bekbolatov.
The commit can be ofund here:
https://github.com/Bekbolatov/spark/commit/463d73323d5f08669d5ae85dc9791b036637c966

Multiclass SVM with Spark 1.6?


How do I cache my custom entities using entity api with entitycache?

Question: I have implemented custom entites, extending on Entity API. This is essentially identical to what the Model module does with a few extra customisations (fields, solr/facet integration etc).
I want to cache my custom entities using the Entity Cache module to get fast loading of entities when using Views and Apachesolr along with automatic cache updating when my entities are updated.
What do I have to do to implement this?
Answer: You can achieve this quite easily with a few hooks and additions to your existing hooks.
Define the cache table in your hook_schema() implementation in your module's .install file:
// Optional cache table for entitycache support.
$schema['cache_entity_my_entity'] = drupal_get_schema_unprocessed('system', 'cache');
$schema['cache_entity_my_entity']['description'] = 'Cache table used to store my_entity entity records.';

This adds a db table that can be used to store your cached entities.
Add an update hook to create the table:
function my_entity_update_700X() {
  if (!db_table_exists('cache_entity_my_entity')) {
    $schema = drupal_get_schema_unprocessed('system', 'cache');
    $schema['description'] = 'Cache table used to store my_entity entity records.';
    db_create_table('cache_entity_my_entity', $schema);
  }
}

Enable entitycache in hook_entity_info(). Add this near the bottom before return $info;
if (module_exists('entitycache')) {
  $info['my_entity']['field cache'] = FALSE;
  $info['my_entity']['entity cache'] = TRUE;
}

Implement hook_flush_caches() in your .module file:
/**
 * Implements hook_flush_caches().
 */
function my_entity_flush_caches() {
  return array('cache_entity_my_entity');
}

And that's it! Entity API takes care of the interactions and things like load() and resetCache() (I found you have to implement those functions when adding entitycache functionality to non-entityapi entities)


Robust variance/covariance matrix in Poisson regression

Question: Suppose I have survival data with more than one row per subject, because I have splitted the follow-up time of each subject into pieces (maybe because I have  one or more time-varying variables or maybe just because I want to fit a Poisson model with a non-constant hazard over time).
Do I have to use the robust variance / covariance estimator (that is implemented for example in Stata with the option vce(cluster clustvar)) to take into account that I have more than one observation per subject (i.e. they're not independent)?
Edit (15 March 2012):
Lambert and Royston in their book carry out this analysis: they split each subject's follow-up on one time-scale (let's say attained age)[*] and fit a Poisson regression including attained age as the dependent variable (modelled for example using splines) plus the offset, so that it's possible to model the incidence of some disease according to attained age.
They do not use the robust variance/covariance estimator, but I haven't found in the text any explanation of why the single rows (or episodes) can be considered independent.
The question: Can someone explain to me why the single rows (or episodes) can be considered as independent?
[*]To clarify what's been done, let's take for example subject number 1001. He/she enters the study at 80.00219 years of age and develop the disease at 85.037236 years (_d==1). This is what happens to the record of this subject after splitting it up.
(The offset variable is defined as ln(_t-_t0))
  id   _d          _t        _t0
1001    0          81   80.00219
1001    0          82         81
1001    0          83         82
1001    0          84         83
1001    0          85         84
1001    1   85.037236         85

Comment: If you're happy with proportional hazards assumptions, you don't need to use clustering in this way; contributions to the partial likelihood at each time point only reflect people in the risk set at that time point, and (in your case) what covariates they had at that time point. Robust variance estimators (i.e. `, robust` in Stata) can still be useful though; they give you standard errors that appropriately summarize variability in your point estimates, regardless of whether the hazard ratio is truly log-linear in the covariates.
Answer: Thanks to @guest's comment and to this lecture note by Germán Rodríguez, I think my question has been answered.
From G.R.'s lecture note:

It is important to note that we do not assume that the $d_{ij}$ have independent Poisson distributions, because they clearly do not. If individual $i$ died in interval $j(i)$, then it must have been alive in all prior intervals $j < j(i)$, so the indicators couldn't possibly be independent. Moreover, each indicator can only take the values one and zero, so it couldn't possibly have a Poisson distribution, which assigns some probability to values greater than one. The result is more subtle. It is the likelihood functions that coincide. Given a realization of a piece-wise exponential survival process, we can find a realization of a set of independent Poisson observations that happens to have the same likelihood, and therefore would lead to the same estimates and tests of hypotheses.

Plus, I realize only now that Royston and Lambert give a brief answer to my question in their book (page 53) (I missed it the first time I read it and I apologize with the authors):

We [Royston and Lambert] are not actually assuming that the $d_{ij}$ have independent Poisson distributions. However, when we express the model in this way, it is the likelihood function that is equivalent to that from a piecewise exponential model.

However, for a more detailed and in-depth explanation, read G.R.'s notes.


changing values of an array

Question: I have a given numpy array, data.
I want to change its values in the ascending order from 0.
I could solve it by manually making the look up table, LUT.
import numpy as np

data = np.array([[2, 6, 16, 39, 43],
                        [43, 6, 16, 39, 2]])

LUT={2:0,
    6:1,
    16:2,
    39:3,
    43:4}

def changer(X):
    res = np.copy(X)
    for i, j in LUT.items():
        res[X==i] = j
    return res

result = changer(data)
print (result)

[[0 1 2 3 4]
 [4 1 2 3 0]]

The result is correct as I expected.
However, sometimes, I am lazy to make LUT manually.
So, how could I get the same results programmatically?
edit
I tried to make dictionary, LUT as follows.
list = [2,6,16,39,43]

LUT = {}
for i in enumerate(list):
    LUT.update({list[i]: i})

But,

D.update({list[i]: i})
TypeError: list indices must be integers, not tuple

Comment: Possible duplicate of [Rank items in an array using Python/NumPy](https://stackoverflow.com/questions/5284646/rank-items-in-an-array-using-python-numpy)
Comment: It is not a good idea to hard code any look up tables in high level code into python! Except with some edge case scenarios this will hurt you. Please explain what you are trying to do and why are you trying to do so.
Comment: Are you looking for something like this?`dict(enumerate([2, 6, 16, 39, 43]))`
Comment: @mad_ yes. Could you see my edit?
Comment: @mad_ how can i inverse, dict(enumerate([2, 6, 16, 39, 43]))?
Comment: By converting values to keys `dict(zip(d.values(),d.keys()))`
Comment: thanks @mad_ it solved my problem           .
Answer: Use np.unique with the return_inverse flag:
data = np.array([[2, 6, 16, 39, 43],
                 [43, 6, 16, 39, 2]])

unq, ranked = np.unique(data, return_inverse=True)

unique without axis set flattens, so we need to reshape
ranked = ranked.reshape(data.shape)
ranked
# array([[0, 1, 2, 3, 4],
#        [4, 1, 2, 3, 0]])

Answer: If I understand what you want, np_lu should be automatically generated from your data.
In [24]: np_lu=sorted(set(data.ravel()))
In [25]: np_lu
Out[25]: [2, 6, 16, 39, 43]

Create an array of indices 2->0, 6->1, ... 43->4
In [29]: indx=np.array(np_lu)
In [33]: d=np.zeros(indx.max()+1)
In [34]: d[indx]=np.arange(len(indx))
In [35]: d
Out[35]:
array([ 0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,
    0.,  0.,  0.,  2.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
    0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
    3.,  0.,  0.,  0.,  4.])

In [36]: data
Out[36]:
array([[ 2,  6, 16, 39, 43],
       [43,  6, 16, 39,  2]])

Create a result array, res.
In [37]: res=np.zeros_like(data)

Fill res with the data in d, indexed by data.
In [41]: res=d[data]
In [42]: res
Out[42]:
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 4.,  1.,  2.,  3.,  0.]])

This will only work for data of int type.  There's probably a lot of tidying up that can be done in my code.
Answer: I think this is really np.argsort:

Returns the indices that would sort an array.

import numpy as np
data = np.array([[2, 6, 16, 39, 43],
                        [43, 6, 16, 39, 2]])
data.argsort(1).tolist()

Output:
[[0, 1, 2, 3, 4], [4, 1, 2, 3, 0]]

And to go backwards giving 1D array, l, and 2D array of indexes, iarr:
l = np.array([2, 6, 16, 39, 43])
iarr = np.array([[0, 1, 2, 3, 4], [4, 1, 2, 3, 0]])

We can use broadcasting:
l[iarr]

Output:
array([[ 2,  6, 16, 39, 43],
       [43,  6, 16, 39,  2]])

Comment: Is there also a way to reverse the output to input?
Comment: Reverse the output?  Change the sort order?  [[4->0],[0->4]] like this?
Comment: to get `input` from `output`.
Comment: `[[0, 1, 2, 3, 4], [4, 1, 2, 3, 0]]` into `[[2, 6, 16, 39, 43],
                        [43, 6, 16, 39, 2]]`
Comment: Given a list of [2,6,16,39,43] and [[0, 1, 2, 3, 4], [4, 1, 2, 3, 0]] -> [[2, 6, 16, 39, 43], [43, 6, 16, 39, 2]]?
Comment: but we do not know `l`, we know only `data` and `iarr`
Comment: Yes, then it is not possible.  You can't got from a an index to numbers with a reference.
Answer: if i get right your needs , all you need is:
import numpy as np
lst = np.array([[i for i in range(len(data[0]))],[i for i in range(len(data[1])-1,-1,-1)]])

Comment: Nope. Not even close. OP is looking for functionality similar to lookup. Your code just iterates and print index of items in some fashion.
Comment: he wanted to use lookup as a method to resolve his problems,
looking over his desired outcome , i think this nails it...
Comment: Can you confirm if the output matches? This does not give the desired results. Thanks
Comment: @mad_ i ran it on his initial data set (array with 2 lists)with my commands and it worked

changing values of an array


How do I rationalize the equation $\frac{3-x}{1- \sqrt{x-2}}$?

Question: How do I rationalize this equation
$$\frac{3-x}{1- \sqrt{x-2}} ? $$
Comment: The collection of symbols
$$\frac{3-x}{1- \sqrt{x-2}}$$
is an **expression**, not an equation (note the lack of an equals sign).
Comment: Since you're new, I'd like to give you some advice about the site: **To get the best possible answers, you should explain what your thoughts on the problem are**. That way, people won't tell you stuff you already know, and they can write answers at an appropriate level; also, people tend to be more willing to help if you show that you've tried the problem yourself.
Comment: [Please see here](http://meta.math.stackexchange.com/q/5020/264) for a guide to writing math with MathJax, and [see here](http://math.stackexchange.com/help/formatting) for a guide to formatting posts with Markdown.
Comment: last note  to @One With The Basic Que,if some answer  is usefully and helpful  for you,just accept it
Answer: $$\frac{3-x}{1-\sqrt{x-2}}=\frac{3-x}{1-\sqrt{x-2}}\frac{1+\sqrt{x-2}}{1+\sqrt{x-2}}=\frac{(3-x)(1+\sqrt{x-2})}{1-(x-2)}=$$
$$=\frac{(3-x)(1+\sqrt{x-2})}{3-x}=1+\sqrt{x-2}$$


getting MAC layer data from higher layers (TraciDEMO)

Question: I am using VEINS 4.4 and trying to get/use MAC layer data real-time during the simulation such as from TraciDemo11p.cc?
The data can be mac address, average mac delay, etc.
Is there any way to do that without changing too much code?
Thank you.
Answer: OMNeT++ simulations are written in C++, so all code is available to you for inspection. If you find the C++ code that defines the behavior of the MAC layer you can augment it with result recording statements (see the OMNeT++ user manual) to log any and all internal state.


Why does pROC roc work with non-probability predictions?

Question: With the pROC package, I can do this:
true <- c(1, 1, 1, 0)
predicted <- c(0.5, 0.1, 0.6, 0.1)
roc(true, predicted)

which gives as expected:
> Call:
> roc.default(response = true, predictor = predicted)

> Data: predicted in 1 controls (true 0) < 3 cases (true 1).
> Area under the curve: 0.8333

I'm not sure why the following is working.
true <- c(1, 1, 1, 0)
predicted <- c(5, -1, 600, 10)
roc(true, predicted)

> Call:
> roc.default(response = true, predictor = predicted)

> Data: predicted in 1 controls (true 0) > 3 cases (true 1).
> Area under the curve: 0.6667

I was expecting an error about predictors being non-probability values, but things are silently accepted. Can someone tell me what's happening behind the scene?
Answer: If you can rank your scores, you can use ROC analysis. Ranking can be done with real numbers, not only probabilities.
One of the interpretations of ROC AUC is the probability that a randomly-chosen positive is ranked higher than a randomly chosen negative; again, this ranking just requires that you can sort the data, but does not require that the data are assigned probabilities.
More elaboration on roc curves and auc can be found in our archives.

How to calculate Area Under the Curve (AUC), or the c-statistic, by hand
What does AUC stand for and what is it?
Answer: To insist on Sycorax answer: as soon as you can rank your scores, you can build a ROC curve. The scores don't even have to be numbers. R has a data type called ordered which is a special type of factor with a built-in order. You can use it to build a ROC curve:
> true <- c(1, 1, 1, 0)
> predicted <- ordered(c("medium", "low", "high", "low"), levels=c("low", "medium", "high"))
> print(predicted)
[1] medium low    high   low
Levels: low < medium < high
> rank(predicted)
[1] 3.0 1.5 4.0 1.5

> roc(true, predicted)

Call:
roc.default(response = true, predictor = predicted)

Data: predicted in 1 controls (true 0) < 3 cases (true 1).
Area under the curve: 0.8333
roc(true, predicted)