sssd ldap authentication cannot automount home directories

Question: I have managed to setup ldap authentication. but I do not manage to have the home directories automatically mount when logged in.
the auto.master and auto.home are stored in the ldap.
this is my sssd.conf:
    [sssd]
    config_file_version = 2
    services = nss, sudo, pam, autofs
    domains = default

    [nss]
    filter_users = root,ldap,named,avahi,haldaemon,dbus,radiusd,news,nscd

    [pam]
    reconnection_retries = 3
    offline_credentials_expiration = 2
    offline_failed_login_attempts = 3
    offline_failed_login_delay = 5

   [domain/default]
   ldap_tls_reqcert = never
   auth_provider = ldap
   ldap_search_base = dc=domain,dc=net
   ldap_group_member = uniquemember
   id_provider = ldap
   ldap_id_use_start_tls = True
   chpass_provider = ldap
   ldap_uri = ldaps://ldapsrv.domain.net
   ldap_chpass_uri = ldaps://ldapsrv.domain.net
   cache_credentials = True
   ldap_tls_cacertdir = /etc/openldap/cacerts
   entry_cache_timeout = 600
   ldap_network_timeout = 3
   sudo_provider = ldap
   ldap_sudo_search_base = ou=SUDOers,dc=domain,dc=net
   debug_level = 9

   #autofs

   autofs_provider = ldap
   ldap_autofs_search_base = dc=domain,dc=net
   ldap_autofs_map_object_class = nisMap
   ldap_autofs_entry_object_class = nisObject
   ldap_autofs_map_name = nisMapName
   ldap_autofs_entry_key = cn
   ldap_autofs_entry_value = nisMapEntry

   [sudo]
   debug_level = 9

   [autofs]
   debug_level = 9

I can login using the ldap credentials do sudo but cannot mount the homedir that are shared by nfs on the ldap server.
it seems it read the auto.master from ldap but fails after... tried ldap and ldaps.
lookup_nss_read_map: reading map ldap ldap:nisMapName=auto.home,domain.net
parse_server_string: lookup(ldap): Attempting to parse LDAP information from string "ldap:nisMapName=auto.home,domain.net".
parse_server_string: lookup(ldap): server "(default)", base dn "nisMapName=auto.home,domain.net"
parse_ldap_config: lookup(ldap): ldap authentication configured with the following options:
parse_ldap_config: lookup(ldap): use_tls: 0, tls_required: 0, auth_required: 4, sasl_mech: (null)
parse_ldap_config: lookup(ldap): user: (null), secret: unspecified, client principal: (null) credential cache: (null)
do_init: parse(sun): init gathered global options: (null)
read_one_map: map read not needed, so not done
mounted indirect on /export/home with timeout 300, freq 75 seconds
st_ready: st_ready(): state = 0 path /export/home
st_expire: state 1 path /misc
expire_proc: exp_proc = 140100367800064 path /misc
expire_cleanup: got thid 140100367800064 path /misc stat 0
expire_cleanup: sigchld: exp 140100367800064 finished, switching from 2 to 1
st_ready: st_ready(): state = 2 path /misc
handle_packet: type = 3
handle_packet_missing_indirect: token 582, name testuser, request pid 15127
attempting to mount entry /export/home/testuser
lookup_mount: lookup(ldap): looking up testuser
do_bind: lookup(ldap): auth_required: 4, sasl_mech (null)
get_server_SASL_mechanisms: Can't contact LDAP server
do_bind: lookup(ldap): autofs_sasl_bind returned -1
do_bind: lookup(ldap): auth_required: 4, sasl_mech (null)
get_server_SASL_mechanisms: Can't contact LDAP server
do_bind: lookup(ldap): autofs_sasl_bind returned -1
lookup(ldap): couldn't connect to server default
lookup(ldap): lookup for testuser failed: connection failed

this is my ldap entries:
dn: nisMapName=auto.home,dc=domain,dc=net
objectClass: top
objectClass: nisMap
nisMapName: auto.home

dn: cn=*,nisMapName=auto.home,dc=domain,dc=net
objectClass: nisObject
cn: *
nisMapEntry: -rw,sync ldapsrv.domain.net:/export/home/&
nisMapName: auto.home

dn: nisMapName=auto.master,dc=domain,dc=net
objectClass: top
objectClass: nisMap
nisMapName: auto.master

dn: cn=/export/home,nisMapName=auto.master,dc=domain,dc=net
objectClass: nisObject
cn: /export/home
nisMapName: auto.master
nisMapEntry: ldap:nisMapName=auto.home,dc=domain,dc=net

thanks
Answer: According to messages like lookup(ldap): couldn't connect to server default your nsswitch.conf doesn't use sss for automount, but the native LDAP connector, ldap. Either use sss for automount or configure automounter to lookup the maps directly.
Comment: I have configured nsswitch.conf to use sss

  `automount:  files sss`
Comment: if it still doesnt work, please upload new logs..
Comment: hello

the automount has been properly setup from the onset.. it is actually done when you run the authconfig command


Why does flow startup up soo many processes on the same ports?

Question: Whenever I start a simulation, several sumo simulators will be spawned on ports 51402 and 51403 over and over again. Why does this occur ? Is it a bug or is there something that I am not understanding ?
screenshot
Comment: I can only see one of each there. Dot post pictures of text, or links to them. Post the text.
Comment: Thanks, I will keep that in mind.
Answer: Are you running it with RLlib or in the SUMO examples? If in RLlib, it's because it parallelizes it by nature. If it's by SUMO, please post on the github and we will look into it!
Comment: RLlib examples. Thanks
Comment: To get rolling RLlib starts up by creating the envs a couple of times. So, it'll spawn a few SUMO instances before the experiments get started.


Good source for learning about Binary Classification

Question: When dealing with binary classification, I most often find myself estimating a logistic regression model. I have tried a few other approaches as well, but to be honest I feel like I know way too little about all of the other possibilities.
I understand that it isn't as easy as following a 'model choice' guide. So what I'm looking for is a source where I can read up on the theory behind the different approaches, and then take it from there. Any ideas?
Answer: An Introduction to Statistical Learning also covers linear and quadratic discriminant analysis, tree-based methods (classification trees, random forests, bagging, and boosing), and support vector machines at a reasonably introductory level. The Elements of Statistical Learning goes into more depth, and adds in neural networks.


datasource.rowIdentifier is undefined error in react native

Question: I am accessing data from database and I wanted to display it in ListView.
I am performing this operation in following way.
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

const LoadingPage=()=>(
   <View style={{backgroundColor:"blue"}}>
     <Image style={{width:150, height:100,bottom:60}} source={require('./drawable/drawable/asap.png')}/>

  </View>
)
const Row = (props) => (
  <View style={styles.container}>
  <Text style={styles.text}>
      {`${props.paymentType.name} ${props.amount} ${props.date} ${props.description}`}
  </Text>
  </View>
);

async fetchData(){
    var DEMO_TOKEN = await AsyncStorage.getItem(STORAGE_KEY);

    fetch(" http://asaptest-sas71.rhcloud.com/api/approvals", {
         method: 'get',
         dataType: 'json',
         headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/json',
           'Authorization': DEMO_TOKEN
         },
        }).then((response) =>
         {
           return response.json() // << This is the problem
         }).then(function(data) {
            console.log(data);
            const tempNames = [];

            for(var i=0;i<data.length;i++){
              tempNames.push(data[i]);
            }
            this.setState({ approvals: tempNames,dataSource: ds.cloneWithRows(this.state.approvals)});
            alert(JSON.stringify(this.state.approvals,null,4))

          }.bind(this)).catch(function(err) {
            //alert("Error is"+err)

           console.log(err);
         })
        .done();

}
componentDidMount(){
    this.fetchData();
   setTimeout(this.setTimePassed()
          , 2000) ;
}
setTimePassed() {
 this.setState({timePassed: true});
}
render(){
  if (!this.state.timePassed){
  return <LoadingPage/>
  }
  else{
    return (

      <ListView
      dataSource={this.state.dataSource}
     />)
  }
 }

But it is giving error that undefined is not an object(evaluating  'dataSource.rowidentifiers')
Please help me solving this issue.
Answer: Please can you refactor to using FlatList instead. It's so much easier to use and has improvements over the ListView. And my bet is your error would disappear when you change to using a FlatList.
Reason why: http://facebook.github.io/react-native/blog/2017/03/13/better-list-views.html
Docs: https://facebook.github.io/react-native/docs/flatlist.html
An article on migrating from ListView to FlatList: https://hackernoon.com/react-native-new-flatlist-component-30db558c7a5b
Cheers


What is the explanantion of plim X'X/n =Q?

Question: Let X be a matrix where X may be any mixture of constants and random variables generated.
What is the meaning or intuitive explanation for the behaviour of the data in large samples where we have the following assumption:
$plim_{n \rightarrow \infty} \dfrac{X'X}{n}= Q$ where Q is a positive definite matrix?
Comment: Does the statement make sense for you if you put scalars there? E.g, does $x^2/n\to q$ in probability, where q is a real number give you any intuition?
Comment: For example, this assumption rules out a regressor with a growth trend.
Comment: Thank I got it! It means that by LLN E[$x^2$] is positive.
Comment: When $X$ is "a matrix" then $n$ is *fixed.* In what sense does $n$ go to infinity, then?
Comment: I'm not sure there is much to get from my comment, the notation I used does not make much sense, which I think is what @whuber is hinting at. Anyway, I wrote some thoughts in an answer instead.
Answer: For simplicity and to get some intuition, suppose $ X=[x_1, x_2,\dots ,x_n]^T$ is an $n\times1$ vector of observations of some random variable $\textbf{x}$. Then you have $$\frac{1}{n}X'X=\frac{1}{n}\sum_{i=1}^nx_i^2.$$ It is clear that this is the sample analogue of $\mathbb{E}\textbf{x}^2$ so you can guess that the requirement has something to do with bounding the variance.
Since you tagged with econometrics, I guess you encounter this assumption when deriving some properties in relation to the OLS estimator. Then the assumption is, loosely speaking, just a way to make sure that as we collect more and more information, our sample estimate of the moment matrix consistently estimates the population moment matrix and that it is finite.
Now, you can try a more abstract case where $X$ has two columns of observations, perform the matrix multiplication and see what you get in each element of the resulting $2\times2$ matrix.
Comment: Thanks for making some sense of this.  BTW, I see that you have been here only two weeks and have been quite productive in contributing thoughtful answers.  Welcome to our site!


How to import an external database to D8 and create a search form?

Question: I have a MySQL database with 2000 doctors, which are accessed classicaly through a HTML form and PHP. With the form you can search with criterias like ZIP, town, target group, treatment, languages, etc. Then a result list with doctors is shown and when clicking on one a profile page is opened with all the details of the doctor.
How can I migrate this to Drupal 8? I already read a lot and often Feeds is sugggested, but unfortunately it is not yet ready for Drupal 8.
Comment: If it were me, I would use Migrate and create Doctor as a custom entity, and migrate them in. Youc an store the address with Address field, and other fields as needed (selects, text fields, taxonomy). The search can easily be built with Views after that.
Comment: I know that views can use filters, but how do you implement search fields?
Comment: Install Search API and use Solr (if it were me). But you might get away with Search API DB. Then you just make a View of that index, and expose fields that you indexed as exposed filters. Expose the form as a block in Views, then place the block in Block Layout in the region you want to show it in.
Comment: I'm not 100% sure if I understood everything you said, but I will experiment a bit with the module...
Answer: The best and most flexible option at your disposal will be to use the Drupal Migrate module. It's included by default in D8.
The steps you'll have to follow is as below:

Migrate your data from MySQl to a Drupal content type or an entity. You could also consider exporting your data to CSV and import from the CSV.
If you are not expecting very large traffic, use views and exposed filter to implement your search form with filters. If you are expecting the more traffic and scale user search_api and use something like Solr in the backend.

Some of the links where you can get started:

Migrate to Drupal 8 from MySql.
Migrate to Drupal 8 from CSV file.
Official Migrate API documentation.

I am assuming you already know what content type, entity, views, exposed filters etc are. In case you don't know any of it, plenty of resources are available online.


On referencing environment and scope

Question: If the scope is the "place" where a variable is visible and
the referencing environment is the set of variables visible in a point
in a program is there a difference between them?
For example here is said that """
The converse of scope is referencing environment..."""
but I don't understand very well that assertion!
Answer: i'd consider the term 'converse' a misnomer, let alone for contrasting two materially different categories, namely (sets of) variables and locations in code where access to said variable(s) is possible. 'complement' might be a better choice.
for the reason given, yes, there is a difference.
what the reference you're citing probaly intends to extol is variable/parameter masking. consider some variable 'a' declared local to a procedure. assume that part of the procedure body is a block local to which another variable also named 'a' is declared.
the first variable 'a' would be part of the procedure's (local) referencing environment.
its scope extends across the whole procedure body, apart from the block with its own declaration of variable 'a'. in pseudocode (real-world code could be e.g. c, perl, plsql):
<code>proc xy
   local a;
   ...
   block
      local a;
      ...
   endblock
   ...
endproc
</code>
this example is for illustrative purposes only, as details have been left out: it assumes static scoping, abstracts away from other local blocks that might also define some 'a' as well as special mechanisms to access the 'outer a' (namely perl allows runtime access to the whole symbol table).

On referencing environment and scope


Solve the $1$st order DE $x^2y'+3xy=1$.

Question: I try dividing $x^2$ for both side. Then, I don't know what should I do next.
Comment: Hi and welcome to Math.SE. What is the form of the differential equation you end up with? Do you know about how to work with an integrating factor? Also, please use [mathjax](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) while typing your questions, it is easier to read. Finally, according to your title, you want to find the differential equation. Do you? Or do you want to solve the differential equation?
Comment: $$x^2y'+3xy=1\implies \left(\tfrac12x^2\right)'=x=x^3y'+3x^2y=(x^3y)'\implies x^3y=\tfrac12x^2+C\implies y=\ldots$$
Answer: Again substitute $y(x)=z(x)/x$ solution you find $x z'(x)=1-2 z(x)$ and then (by separating the variable)
$$
-\frac{1}{2}\log(1-2z)=c+\log(x)
$$
or
$$
z=\frac{1}{2}+\frac{c}{x^2}
$$
or
$$
y=\frac{c}{x^3}+\frac{1}{2x}
$$
Answer: Rewrite
$$y'=-3\frac{y}{x}+\frac{1}{x^2}$$
Solving the homogenous equation is pretty eays (e.g. using method of separation) $$y_h=c_1x^{-3}$$
Then you guess (is faster for easy ODEs) a particular solution of the form $y_p=\frac{k}{x}$. Plug this into the equation and find k.
Note: You can also get the particular solution using the general formula for a linear ODE or variation of constants.
As always you general solution is
$$y=y_h+y_p=\frac{c}{x^3}+\frac{k}{x}$$
Comment: Why that guess for $y_p$?
Comment: I mentioned that you can also calculate it, but i find guessing faster sometimes.
Answer: $${ x }^{ 2 }\frac { dy }{ dx } +3xy=1\\ \\ { x }^{ 2 }\frac { dy }{ dx } +3xy=0\\ \frac { dy }{ dx } =-3\frac { y }{ x } \\ \int { \frac { dy }{ y }  } =-3\int { \frac { 1 }{ x } dx } \\ \ln { \left| y \right| =-3\ln { \left| cx \right|  }  } \\ y=\frac { C }{ { x }^{ 3 } } \\ y=\frac { C\left( x \right)  }{ { x }^{ 3 } } \\ \frac { dy }{ dx } =\frac { { C }^{ \prime  }\left( x \right) { x }^{ 3 }-3{ x }^{ 2 }C\left( x \right)  }{ { x }^{ 6 } } \\ { x }^{ 2 }\frac { { C }^{ \prime  }\left( x \right) { x }^{ 3 }-3{ x }^{ 2 }C\left( x \right)  }{ { x }^{ 6 } } +3x\frac { C }{ { x }^{ 3 } } =1\\ { C }^{ \prime  }\left( x \right) =x\\ { C }\left( x \right) =\frac { { x }^{ 2 } }{ 2 } +C_{ 1 }\\ y=\frac { \frac { { x }^{ 2 } }{ 2 } +C_{ 1 } }{ { x }^{ 3 } } =\frac { 1 }{ 2{ x } } +\frac { C_{ 1 } }{ { x }^{ 3 } } \\ \\ $$
Comment: Just a bunch of formulas without any explanation at all, and the wrong answer... I vote this down.
Comment: $C'(x)=x$, not $C'(x)=1$.
Comment: Good, then I'll upvote, since your solution is the only one (so far) that is not picking a rabbit out from a hat... :) Addition: In fact, it would be better if there were some words/explanations between the steps. After all, it is not the final answer that is important, but the method, and that is difficult to learn with just a bunch of formulas.
Comment: yes,it is beacuse i am poor in english,you said i have wrong aswer without any explanation,you can  show my mistake,i will be thankfull for you
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/29240/discussion-between-battani-and-mickep).
Answer: $$x^2y'+3xy=1$$
divide by $x$
$$xy'+3y=\frac{1}{x}$$
we can solve this O.D.E by Euler-Cauchy Method
1- to find the complementary solution
$$xy'+3y=0$$
assume
$$y_c=x^m$$
$$y'=mx^{m-1}$$
substitute it to get
$$m=-3$$
hence
$$y_c=C_1x^{-3}=\frac{C_1}{x^3}$$
2- to find the particular solution
         $$y_p=\frac{A}{x}$$
         $$y'_p=-\frac{A}{x^2}$$
   substitute it to get
    $$A=\frac{1}{2}$$
$$y=y_c+y_p=\frac{C_1}{x^3}+\frac{1}{2x}$$
Answer: When you have a first order non-linear and/or non-autonomous differential equation you could always try testing if it is an exact differential equation
$$
p(x,y) + q(x,y) \frac{dy}{dx} = 0,
$$
where
$$
p(x,y) = 3xy - 1,
$$
$$
q(x,y) = x^2.
$$
In this case $\frac{\partial p}{\partial y} \neq \frac{\partial q}{\partial x}$, however if you multiply this equation by some other function $\mu(x,y)$ the new $p(x,y)$ and $q(x,y)$ might satisfy this relation.
Since all terms in the existing differential equation only contain powers of $x$ and $y$, a good guess would be
$$
\mu(x,y) = x^a y^b.
$$
The values for $a$ and $b$ can be found by equating
$$
\frac{\partial \mu(x,y) p(x,y)}{\partial y} = \frac{\partial \mu(x,y) q(x,y)}{\partial x},
$$
which is equal to $\frac{\partial}{\partial x} \frac{\partial}{\partial y} \Psi(x,y)$, such that differential equation is equivalent to
$$
\frac{\partial}{\partial x} \Psi(x,y) + \frac{\partial}{\partial y} \Psi(x,y) \frac{dy}{dx} = \frac{d}{dx} \Psi(x,y) = 0,
$$
thus $\Psi(x,y)$ has to be equal to a constant, represented by $c$.
The solution to the differential equation can then be found by integrating to find $\Psi(x,y)$
$$
\Psi(x,y) = \int{\mu(x,y) p(x,y) dx} + f(y),
$$
$$
\Psi(x,y) = \int{\mu(x,y) q(x,y) dy} + g(x).
$$
Both integrals will contain the same terms, which both depend on $x$ and $y$, such that $g(x)$ will be equal to the terms of the first integral, which only depends on $x$ and $f(y)$ will be equal to the terms of the second integral, which only depends on $y$.

Solve the $1$st order DE $x^2y'+3xy=1$.


react native passing data from parent to child modal

Question: I have a FlatList rendered along with a ListItem so that onPress of a  specific row I can get that data inside my  ListTrips component. As shown below in my console.warn It will print the data of the selected item.
Component A
<code> import Component B from ...
 ....
  toggleModalConfirmTrip = item => {
console.warn(item);
// this.props.navigation.navigate('SelectedTrip', { item });

if (this.ModalConfirmTrip) {
  this.ModalConfirmTrip.toggleModal();
}
};

 <ListItem
 onPress={() => this.toggleModalConfirmTrip(item)}
 ....
</code>
Yet inside my ModalConfirmTrip.js I am unable to access the item. My question is how can I access it inside Component B?
I have tried playing around with props and state but cannot seem to get it right.
Component B
<code>export default class ModalConfirmTrip extends Component {
constructor(props) {
super(props);
this.state = {
  locationFrom: '',
  locatonTo: '',
  isVisible: false,
  id: null,
 };
}

toggleModal = () => {
this.setState({ isVisible: !this.state.isVisible });
 };

// API Call to update trip to active

render() {
const { isVisible, item } = this.state;

console.warn('Modal', this.state);
console.warn(this.props);

return (
  <View style={styles.container}>
    <Modal
      onBackdropPress={() => {
        this.toggleModal();
      }}
      isVisible={isVisible}
      hideModalContentWhileAnimating
    >
      <View style={styles.modalViewContainer}>
        <Text style={styles.title}>{this.state.item}</Text>
</code>
Answer: Found the solution!
So you have to pass item as a prop in Component A
<code>    <ModalConfirmTrip
      ref={ref => {
        this.ModalConfirmTrip = ref;
      }}
      item={this.state.item}
    />
</code>
Also to note you cannot pass an object of an array so I just passed the id of the trip. Hope this helps someone.


Twitter bot APIs are not working

Question: Since yesterday, I'm facing an issue where, strangely, twitter APIs are working and sometimes not!
Error:

Bad twitter streaming request: 410
  The site streams and user streams endpoints have been turned off. Please migrate to alternate apis.

Is this only me or anyone else is facing this problem?
Comment: But it says "...been turned off. Please migrate to alternate apis."? Does that not answer your question?
Comment: https://twitter.com/TwitterAPI/status/1030122500561166336
Answer: As it says in the error message, the API has been deprecated.
https://twittercommunity.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746
Answer: Please check this link
Twitter recently announced that they are shutting down some services and endpoints and, to force the developers to use new services and apis, they are flickering the apis periodically. (you can get more information of flicker in the above link)
So, you need to change(upgrade) your apis to avoid the issues you're facing right now.
Comment: Why answer the same thing as an existing answer _and_ an existing comment?
Comment: Earlier, I also had the same issue.and I was typing and unaware of your answer.

Twitter bot APIs are not working


Leitura de arquivos em PROLOG

Question: Como posso ler em PROLOG um arquivo.txt dessa forma:
iago.neves pedro.santos
joao.vitor larissa.figueiredo

Sendo Iago Neves, um nome e Pedro Santos outro nome, João Vitor e Larissa Figueiredo. Tentei usar o comando read, mas ele para a leitura até o ponto e não consigo ler os sobrenomes junto com os nomes de maneira correta .
Alguém, por favor?
Answer: O comando read/1 serve para ler termos de um arquivo com a mesma sintaxe do Prolog. Para ler conteúdo arbitrário (i.e. strings) você vai precisar dos métodos de leitura de caracteres primitivos, como por exemplo o get_char/1. Um exemplo (sem entrar no mérito da codificação do arquivo, que eu assumo que você já especificou ao abrir a stream de entrada) seria:
ler_chars(S) :-
    get_char(C),
    ler_resto(C,S).

ler_resto(end_of_file, []).
ler_resto(C, [C|R]) :-
    get_char(C2),
    ler_resto(C2, R).

Após chamar ler_chars numa stream, seu conteúdo será retornado em uma lista de caracteres. Se você quiser esse conteúdo em uma string, basta chamar atom_chars/2 no resultado:
?- abrir_stream, ler_chars(Chars), atom_chars(String, Chars).

Mas uma opção melhor é interpretar o conteúdo desse arquivo através de uma gramática DCG. Pelo que eu entendi, você tem uma série de nomes separados por espaços ou quebras de linha, certo? E cada nome consiste em nome.sobrenome. Isso expresso em DCG ficaria:
nomes([]) --> [].
nomes([Nome|R]) --> nome(Nome), [' '], nomes(R).
nomes([Nome|R]) --> nome(Nome), ['\n'], nomes(R).
nomes([Nome]) --> nome(Nome).

nome(pessoa(Nome,Sobrenome)) --> palavra(CNome), ['.'], palavra(CSobrenome),
                                 { atom_chars(Nome, CNome),
                                   atom_chars(Sobrenome, CSobrenome) }.

palavra([]) --> [].
palavra([C|R]) --> [C], { is_alpha(C) }, palavra(R).

Chamando esse código no resultado da leitura te produz uma lista onde cada elemento é da forma pessoa(Nome,Sobrenome):
?- abrir_stream, ler_chars(Chars), nomes(Pessoas, Chars, []).

Pessoas = [pessoa(iago, neves), pessoa(pedro, santos), pessoa(joao, vitor), pessoa(larissa, figueiredo)]

Exemplo no ideone.

Leitura de arquivos em PROLOG


For any positive number $k$, find the value of $1^k + 2^k + 3^k+...+(p-1)^k$(mod $p$)

Question: For any positive number $k$, find the value of
$1^k + 2^k + 3^k+...+(p-1)^k$(mod $p$) and prove that your answer is correct. A Little confused about this problem. Any help? Would love to see a solution for this.
Thank you.
Answer: If $g$ is a primitive root,
$S:\{s, 1\le s\le p-1\}, T:\{g^r\pmod p, 1\le r\le p-1\}$ will be the same set
$$\implies\sum_{s=1}^{p-1}s^k\equiv\sum_{r=1}^{p-1}(g^r)^k\equiv \sum_{r=1}^{p-1}(g^k)^r\pmod p$$
If $(p-1)\mid k, g^k\equiv1\pmod p $  $$ \sum_{r=1}^{p-1}(g^k)^r\equiv \sum_{r=1}^{p-1}1^r\pmod p\equiv p-1\equiv-1$$
Else $g^k\not\equiv1\pmod p\iff (g^k-1,p)=1$  $$ \sum_{r=1}^{p-1}(g^k)^r=g^k\frac{(g^k)^{p-1}-1}{g^k-1}=\frac{(g^p)^k-g^k}{g^k-1}\pmod p$$
As $g^p\equiv g\pmod p,(g^p)^k\equiv g^k,$
$$ \sum_{r=1}^{p-1}(g^k)^r\equiv\frac{g^k-g^k}{g^k-1}\equiv0\pmod p$$ as $ (g^k-1,p)=1$
Comment: The summation on the left doesn't include the term for $r=0$, so shouldn't we subtract one from the quantity on the right of each $=$ sign? But also $g^p \equiv g$, so the whole thing comes out $\equiv 0$ anyway.
Comment: @DavidK, Which line you are referring to?
Comment: Just the last line, sorry for the confusion.
Comment: @DavidK, Thanks for your input.
Comment: Just saw your edit. Yes, that almost works. I still thought $1=g^{p-1}$ not $g^p$, do I misremember?
Comment: @DavidK, Now I believe, it should be very well possible to prove it more generally w/o using cases.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/19135/discussion-between-david-k-and-lab-bhattacharjee).
Comment: I see dankness, I updoot.


Error after validation by email

Question: I have the following problem with drupal 6 and I am using the Login Tobogan module.  When an user creates a new account in Drupal, the user receives the respective email.  When the users click in the link for validate the account, the account is validated but appears the next error:
<code>Unable to send e-mail. Please contact the site administrator if the problem persists.
You have successfully validated your e-mail address.
</code>
Thanks for your help.
Answer: I have disabled the Login Tobogan and I have enabled again the Login Tobogan again and the error was fixed.
Answer: I have this problem once, but then realized that it happened for wrong email configuration. For my case, it was the server restricted gmail mail address to send emails from the servers. So, I changed the site email address something to email@example.com & it worked.
If you're using smtp module, then please check all other settings on smtp page as well, specially web-server username& passwords to match your hosting mailbox password.
Send a testing emails & enabling debug option will help you to understand better if other problems were there.
Hope now you can use LoginToboggan & smtp both without that problem :)

Error after validation by email


Why entity_metadata_wrapper->save() doesn't update node's revision?

Question: I'm developing a module to update nodes(enable revision). It looks like this.
 $nodes = node_load_multiple(array(), array('type' => $bundleType));
 foreach ($ndoes as $node){
    $w = entity_metadata_wrapper('node',$node);
    $w->MyFields->set($someValue);
    $w->save();
 }

It set fields correctly but node's revision-id didn't change after $w->save().
How can I update the revision ID?
Comment: Is the `create new revision` flag set on the node for the content type? Have you tried like `$w->revision->set(1);` before saving? ....
Comment: Yes, "create new revision" is on. I don't know much about `$w->revision->set(1)`, is that a manual way to let the drupal knows that the node has been updated? I will try it.
Comment: hmm, `$w->revision->set()` works. It seems I misunderstand `$w->save()`. I thought it should increase the revision-id automatically while saving. Is there anyway to get next  increase revision id? Thank you
Comment: no, `revision->set(1)` tells the node to record a new revision on the upcoming/current edit of the node. I'm not sure why the metadata wrapper isn't seeing the global setting of create new revision ..... but setting the revision flag is a very simple workaround as you've now seen. I'm provided my comment as an answer below if you care to upvote it to help other users in the future find a correct answer.
Answer: When you edit a node via the UI, it is done via node_form().  This has a call near the top to node_object_prepare(), which sets up default values for that node.  This includes setting the default value of $node->revision, which is used by node_save() to determine whether a new revision is needed or not.
The Entity API is revision aware, but node_object_prepare() is a node-specific thing.  This means that you need to manage the values yourself, including setting the revision property to mimic what the node edit form will do.
Answer: Is the create new revision flag set on the node for the content type? Have you tried like $w->revision->set(1); before saving? ....
EDIT:
Author says setting $w->revision->set(1) solves his issue.
Comment: It's a easy workaround! Just don't understand why it's needed lol. Thank you!
Answer: None of these answers are actually correct, doing ->set(1) makes it sound like your actually changing the revision number and therefore should increment it.
This is actually just a boolean flag so the correct answer is $node->revision->set(true);
As zhuchun says: he doesn't understand why its needed, when explained as a boolean flag it makes perfect sense rather than the number.
Comment: There was a time when creating new drupal content involved most easily calling `drupal_submit_form` for example. If you inspect the POST values for a node submit form you'll see things like `revision = 1` in the POST fields because the form items `create new revision` box was checked. Since `1 == TRUE` the code works either way. But, your point is valid.
Comment: this should be accepted answer
Comment: Also see: https://blog.arvixe.com/drupal7-entitymetadatawrapper-save-my-revision/
Answer: If the node type doesn't have revisions enabled by default, the most succinct way to request a new revision is:
$w->revision = TRUE;
which is exactly the same as using:
$w->revision->set(TRUE);
but with less typing required.


Bind a My.Settings StringCollection to multiple ComboBoxes

Question: I have a set of ComboBoxes. I want to use them mostly like short data-entry TextBoxes, so I have them set to
AutoCompleteMode = SuggestAppend
AutoCompleteSource = ListItems
DropDownStyle = DropDown
What I want to do is to have each ComboBox have a common DataSource (the My.Settings StringCollection) whereby any String added to or removed from the DataSource is added to or removed from the DataSource of each ComboBox.
Through various experiments with BindingSources and DataBindings and the like, I have managed to get the ComboBoxes either all having the same DataSource, but all showing the same text, or getting them all to have the same DataSource, but not being able to reflect changes to the DataSource between ComboBoxes to various new and wonderful ways of throwing exceptions.
So, basically, what I want is for all the ComboBoxes to use a StringCollection as their DataSource, to propagate changes to the DataSource through all the ComboBoxes, but for the choice of SelectedItem to be independent between all the ComboBoxes.
Any ideas?
Thanks.
Answer: DropDown.DataSource = My.Settings.StringCollection

This will work:
Here's an example from my code:
    ddl_NoMatch_Option.DataSource = My.Settings.NoMatch_Option_List
    ddl_NoMatch_Option.SelectedText = My.Settings.NoMatch_Option

I've added a StringCollection in My.Settings called NoMatch_Option_List, and save the result in the NoMatch_Option string setting.


recuperar o id de registro na tabela

Question: não tenho ideia de como recuperar o ´id´ da minha tabela sem passar ele pelo form
tenho o seguinte form
NOTICIAS
<form method="post" autocomplete="off">

        nome*
        <input type="text" name="nome"/>

        tags*
        <input type="text" name="tags"/>

        <input type="hidden" name="postar" value="postou"/>
        <input type="submit" value="próximo passo"/>

</form>

PHP
if(isset($_POST['postar'])&&$_POST['postar']=='postou'){
    var_dump($_POST);
    //verifico se a noticia ja foi postada
    $vDup=$conn->prepare("SELECT id,nome FROM `noticias` WHERE `nome` = '".$_POST['nome']."'");

    $vDup->execute();

    $count=$vDup->rowCount($_POST['nome']);

    if($count>=1){
        echo "Essa notícia já foi publicada.";
    }else{
        if(empty($_POST['nome'])){
            echo "O nome da notícia não pode ficar vazia.";
        }else{

            //modificação
            $pID=$vDup->fetchAll(PDO::FETCH_OBJ);
            foreach($pID AS $listID){
            $id=$listID->id;

            $id=$id;

            $nome=trim($_POST['nome']);
            $slug=$_POST['nome'];
            $tags=trim($_POST['tags']);

            $insertNoticia=$conn->prepare("INSERT INTO `noticias` (nome,slug,tags) VALUES ('$nome','$slug','$tags')");

            $insertNoticia->execute();

            if($insertNoticia){
                //preciso recuperar o id da minha notícia nessa url
                header("refresh: 3;painel.php?p=escrever-noticia&chave=".$_SESSION['id']."&autor=".$_SESSION['login']."&slug=".$slug."&id=".$id."");
                echo "Processando, aguarde...";
            }else{
                echo "Erro ao postar essa notícia.";
            }
          }//fecha o foreach
        }
    }
}

http://www.meupainel.com/painel.php?p=escrever-noticia&chave=2&autor=admin&slug=noticia-teste&id=1

meu problema esta em recuperar esse ´id´, como eu não passo via post nem get, não sei como recuperar ele, essa outra página que o form manda quando a noticia e postada, se refere a outra tabela, oque eu preciso e recuperar o ´id´ da tabela noticias, pra fazer ligação entre as duas
Comment: Traz o ID junto no seu SELECT da tabela noticias.
Comment: @GuilhermeRigotti editei a pergunta com oque voce falou, porem agora nao esta cadastrando nem dando nenhum erro, mais a logica e essa mesmo que vc falou, porem estou errando em alguma coisa
Comment: você tem varias opções, como session `$_SESSION`, ou pode também passa o id pelo html: exemplo: ``
Comment: @Mayron Da um `var_dump` no retorno da seu select para ver o que esta vindo.
Comment: @Bulfaitelo como assim pegar por ´$_SESSION´ a ´$_SESSION´ que eu uso e do meu login, esse jeito ´´ nao entendi como funciona
Comment: @GuilhermeRigotti editei a pergunta com o ´var_dump´ mesmo assim nao retorna nada, outra coisa, aquele SELECT eu uso pra saber se a noticia ja foi postada, sera que pode ser esse o problema que nao esta puxando o id? `SELECT id, nome FROM noticias WHERE nome` = '".$_POST['nome']."'` repare que o WHERE  so puxa se for correspondente ao nome certo
Comment: @Mayron roda o `var_dump($_POST);` logo na primeira linha antes dessa validação de postar, e posta o resultado.
Comment: @Bulfaitelo ´array(8) { ["nome"]=> string(1) "teste" ["tags"]=> string(5) "tag 1"  ["postar"]=> string(6) "postou" }´
Comment: @Mayron agora coloca esse vara_sump dentro do if  só para vermos se ele está entrando dentro dele.
Comment: @Bulfaitelo esta entrando sim, retornou a mesma coisa
Comment: @Bulfaitelo eu acho que o problema e aquele SELECT, porque ele so vai executar se estiver alguma noticia com o mesmo nome que eu postar, sera que seria melhor eu fazer outro SELECT? porem e estranho ele nao estar cadastrando a noticia
Comment: @Mayron qual é o resultado do select roda um `var_dump($vDup->execute());` e me fala o retorno
Comment: @Bulfaitelo deu isso bool(true)
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/86987/discussion-between-bulfaitelo-and-mayron).
Answer: Verificando seu código você está reescrevendo o id, que que pegar, mas como ele ainda não existe, o correto seria inserir no banco para assim pegar o id do ultimo cadastro.
if(isset($_POST['postar'])&&$_POST['postar']=='postou'){
    var_dump($_POST);
    //verifico se a noticia ja foi postada
    $vDup=$conn->prepare("SELECT id,nome FROM `noticias` WHERE `nome` = '".$_POST['nome']."'");

    $vDup->execute();

    $count=$vDup->rowCount();

    if($count>=1){
        echo "Essa notícia já foi publicada.";
    }else{
        if(empty($_POST['nome'])){
            echo "O nome da notícia não pode ficar vazia.";
        }else{

            $nome=trim($_POST['nome']);
            $slug=$_POST['nome'];
            $tags=trim($_POST['tags']);

            $insertNoticia=$conn->prepare("INSERT INTO `noticias` (nome,slug,tags) VALUES ('$nome','$slug','$tags')");

            $insertNoticia->execute();
            $id = $conn->lastInsertId();
            if($insertNoticia){
                //preciso recuperar o id da minha notícia nessa url
                header("refresh: 3;painel.php?p=escrever-noticia&chave=".$_SESSION['id']."&autor=".$_SESSION['login']."&slug=".$slug."&id=".$id."");
                echo "Processando, aguarde...";
            }else{
                echo "Erro ao postar essa notícia.";
            }
        }
    }
}

removi o foreach, e adicionei o lastInsertId() para pegar o ultimo id inserido no banco de dados.

recuperar o id de registro na tabela


SESSION not remembered php

Question: I came across the problem that my session vars aren't remembered when you are linked to another page. This might sound a bit strange. To clear it up a bit, I will explain my problem with some code:
This code is a snippet from 'Login.php'. Here I set the SESSION vars for Email and wachtwoord(Password).
$query = "SELECT * FROM user WHERE Email='$email' AND Wachtwoord='$Wachtwoord'";

$result = mysqli_query($connection, $query) or
die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if ($count == 1){
    session_start();
    $_SESSION['email'] = $email;
    $_SESSION['wachtwoord'] = $Wachtwoord;

$sql = "UPDATE user SET Ingelogd = 1 WHERE Email='$email'";
$ressql = mysqli_query($connection, $sql) or
die(mysqli_error($connection));

}else{
    echo "Invalid Login Credentials.";
}

Inside this snippet, the email and wachtwoord session are correctly set(I believe, because I can echo these and get the right output)
But when the user gets redirected to chat.php which contains this php code(indirectly, this code is in 'LoginCheck.php'. Linked to as: Include('../Php/LoginCheck.php');):
Include('connect.php');
//IF ((! $_SESSION['email']= NULL)&&(! $_SESSION['wachtwoord']=NULL)){
    $email = $_SESSION['email'];
    echo $_SESSION['email'];
    $Wachtwoord = $_SESSION['wachtwoord'];
    echo $_SESSION['wachtwoord'];
    echo 'something';

$sql = "SELECT * FROM user WHERE Email='$email' and Wachtwoord='$Wachtwoord' and Ingelogd=1";
$result = mysqli_query($connection,$sql) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if (!$count == 1){
 //header('Location: Login.php');
}
//}

When php tries to do something with a SESSION var it gives this error:
Undefined variable: _SESSION in F:\xampp\htdocs\Chives-Functional\Php\LoginCheck.php on line 4
The line, in which $email is declared.
What I want to check is whether the user is still logged in or not.
How can I get this to work? What am I doing wrong? And why isn't it remembered?
Thanks in advance, any help is appreciated!
Kind Regards,
Ps. If more information is required, feel free to ask!
Comment: you need to call `session_start();` on every page
Comment: did you call `session_start()`?
Comment: add `session_start()` at the start of LoginCheck. It starts or resumes a session.
Comment: you are right, I'm sorry, I didn't know that
Comment: Your query is unsafe though. It is vulnerable to SQL injection. You should consider escaping your query variables using [`mysqli_real_escape_string`](http://php.net/manual/en/mysqli.real-escape-string.php)
Comment: @RubenRutten I know it's unsafe but it doesn't need to be safe. It is just an informatics project. However, if I decide to do some serious projects in the future it's really handy to know. So thanks anyway ;)
Comment: Even if it is, you should never skip security, even if it's such an easy solution. I'm sure your teacher will appriciate it too.
Comment: @RubenRutten Yes, I think you're right
Answer: Have you made sure to start the session on top of every page?
session_start();

SESSION not remembered php


Iterating through an ArrayList of different objects

Question: I have an abstract class with several subclasses. A tester class has an ArrayList with 1 object of each subclass in it. They each have a method of the same name, how can I iterate through the ArrayList and call that method for each object?
One of my subclasses (others basically the same):
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;

public MyMath(int pagesRead, String typeHomework) {
    super(pagesRead, typeHomework);
}

public void createAssignment(int p) {
    setPagesRead(p);
    setTypeHomework(typeHomework);
}

public void toString(int pagesRead, String typeHomework) {
    System.out.println("Homework type: " + typeHomework + ". Number of pages read: " + pagesRead + ".");
}

}
In my tester class main method:
ArrayList homework = new ArrayList();
homework.add(new MyMath(5, "Math"));
homework.add(new MyScience(5, "Science"));
homework.add(new MyEnglish(5, "English"));
homework.add(new MyJava(5, "Java"));

Comment: Use `List homework = new ArrayList<>();`
Comment: Does the abstract class also have a method with the same name (and parameter types)?
Comment: @Stephanie , adding some of your code would be helpful!
Comment: The abstract class has an abstract method that each subclass overrides.
Comment: Then any list iteration (for-each, plain for loop, etc.) should work fine, as given in both answers below.
Comment: Oh, have you covered generics in class yet?  You need those for this to work well.
Answer: Well, if the method is specified in your abstract class, and you have already built the ArrayList with all the objects inside it, you should simply be able to iterate through the ArrayList (for-loop) and just call the .method()
Comment: Can I use a foreach loop, or does that not work on this because they are different types of objects?
Comment: The for-each construct should work fine.
Comment: Yes, as markspace has said, the for-each construct should work! I was just giving an example of a way to iterate through the ArrayList
Comment: @StephanieFu As long as the objects have already been initialized, I should think you could use a for each such as `for(SuperClass a : list)` and in the loop, `a.method();`.
Comment: @CalvinP. I tried doing that, and I got a "Type mismatch: cannot convert from element type Object to Homework" error. Homework is the superclass.
Comment: Thanks for the answers, I figured what I was doing wrong - I didn't create the ArrayList correctly, so the types were all Objects instead of Homeworks.
Answer: If your ArrayList is of type and your interface also has the method then you can call them like so
for(int i = 0; i < list.length();i++)
{
    list[i].METHOD_NAME();
}

Answer: You can iterate through the arraylist ant it contains objects and you can call the method on that object. for example,
ArrayList<AbstractClass1> objs = new ArrayList<AbstractClass1>();

objs.add(); // you have added objects already.

Then
for(int i = 0; i< objs.size() ; i++){

objs.get(i).methodYouDefined();

}

Answer: If you haven't covered generics yet in class, you have to cast manually.  If you have covered generics, you should use them!  See lak91's answer.
public abstract class AbstractTest
{
   public abstract void oneTwo( int i, String s );

   public static void main(String[] args) {
      List list = new ArrayList();
      list.add( new One() );
      list.add( new Two() );
      for( Object test : list ) {
         AbstractTest abTest = (AbstractTest) test;
         abTest.oneTwo( 0, "test" );
      }
   }

}

class One extends AbstractTest {

   @Override
   public void oneTwo( int i, String s )
   {
      System.out.println("One");
   }

}

class Two extends AbstractTest {

   @Override
   public void oneTwo( int i, String s )
   {
      System.out.println("Two");
   }

}


What is the best way to learn Eclipse RCP? Does it feel different to only me?

Question: I am used to structural programming (eg:C), OO programming(eg:Java), Scripting(eg:Javascript), Web (eg:HTML,JSP,Servlets,CSS) etc.
Now, when I am getting started with Eclipse RCP plugin development, the whole thing gives a strange feel to me in terms of programming. The way things are in Eclipse RCP development is quite different from other languages that I have mentioned above and honestly I don't enjoy the fact much.
Am I the only who feels this way?
What other things you suggest to make my transition into Eclipse RCP life better? (if it can feel any better).
P.S.: I have already seen this thread, for the tutorials, just wanted to know how others feel if their development background is similar to me!
Comment: I've been tasked with helping to develop an RCP app. I had no java or Eclipse experience at the time.  I've been working on it 3/4 time for about six weeks.  Question:  How does anyone learn it?  I have a book (maybe the wrong one) and I've done online tutorials, and, while it's beginning to make sense, I'm constantly googling for how to do x or y, or asking someone, and getting a reply like "right click on Z, and choose A, then go over to the B tab and type in "foo"... modify MANIFEST.MF ... add to classpath, add to buildpath..."  I have no idea what I did.  How do people learn this?
Answer: It may feel different because it is heavily based on OSGI
That involves splitting your application into components, which should typically have a set of responsibilities that can be isolated from the rest of your application through a set of interfaces and class dependencies.

Identifying these dependencies purely by hand can range from rather straightforward for a well designed highly cohesive but loosely coupled application to a nightmare for interlocked source code that you are not familiar with.

So building an RCP application involves respecting the whiteboard pattern on which the services concept of OSGi is build, and that can be quite different than traditional OO development.
Answer: There are 2 main approaches to building an RCP app
1.) You are using RCP just for the platform features - SWT/startup exe/Auto-update. The application code will be isolated from RCP conventions and libraries as much as possible for the actual app biz functionality.
2.) Your app is completely immersed in RCP. You try to reuse RCP API's wherever possible
I have tried out Option 1. In this case, the experience is very similar to Java development. You might want to try this option out. The advantages are -
-- SWT is very well integrated into RCP. You dont need to run into hoops to get it working. I would recommend SWT over Swing any day as it is very easy for an average programmer to create a responsive and native-feeling SWT app while it takes a Swing expert to create a decent Swing app
-- With a client app, the ability to auto-update is very useful. Eclipse automatically offers this functionality.
RCP stuff you still need to learn are:
-- How the Eclipse classloader works. This is to ensure you can explicitly load resources from your jars in the correct way [NOTE: It is not simple]
-- You will need to package the JVM along with the app. And invoke the JVM on startup using relative naming convention
Comment: @jacob.arun What is the best way to learn "How the Eclipse classloader works"? :)


Python help: OOP Rectangles

Question: Please help with completing this. I am stuck and cant seem to get it. Below this is what i was given and below the code is what the output needs to be.
def main():
print ("Rectangle a:")
a = Rectangle(5, 7)
print ("area:      {}".format(a.area))
print ("perimeter: {}".format(a.perimeter))

print ("")
print ("Rectangle b:")
b = Rectangle()
b.width = 10
b.height = 20
print (b.getStats())

Expected Output
When the Rectangle class has been properly created, the output should look like the following:
Rectangle a:
area:      35
perimeter: 24
Rectangle b:
width:     10
height:    20
area:      200
perimeter: 60

this is what i have done from what i know. I missed the lecture for a family emergency and dont know how to finish it.
class Rectangle:
    def __init__ (self, H=0, W=0):
        self.width = W
        self.height = H

@property
    def area (self):
        return self.width * self.height

def main():
    print ("Rectangle a:")
    a = Rectangle (5, 7)
    #print ("area: {}".format(a.area))
    #print ("perimeter: {}".format(a.perimeter))
    print ("")
    print ("Rectangle b:")
    b = Rectangle()
    b.width = 10
    b.height = 20
    #print (b.area)
    #print (b.getStats())

main ()

Comment: And where is something that you've done? I won't do your homework for you.
Comment: ill post an answer with what i have done so far and where im stuck.
Comment: Don't post that as an answer, instead add that and explanation in your question.
Comment: i added what i have below everything.
Comment: You forgot to explain why you are stuck, what seems to be the problem
Comment: i dont know how to get it to actually show the needed outputs. When i run what i have all that comes out is: Rectangle a: Rectangle b: but there is no outputs for the rectangles
Comment: possible duplicate of [How can I write a socket server in a different thread from my main program (using gevent)?](http://stackoverflow.com/questions/22691736/how-can-i-write-a-socket-server-in-a-different-thread-from-my-main-program-usin)
Answer: First and foremost, you should roll a newspaper and whack the teacher on the nose for proposing the use of function named main(). Python already comes with __main__ which you are welcome to use.
As for your ongoing issue, I took a liberty of reworking your code a bit, and you should be able to follow its lead on the road to success.
class Rectangle:
    def __init__ (self, H=0, W=0):
        self.width = W
        self.height = H

    @property
    def area (self):
            return self.width * self.height

if __name__ == "__main__":
    a = Rectangle (5, 7)
    print ("Rectangle a.w: %s a.h: %s" % (a.width, a.height))
    b = Rectangle()
    b.width = 10
    b.height = 20
    print ("Rectangle b.w: %s b.h: %s" % (b.width, b.height))

Python help: OOP Rectangles


Restrict core to generate taxonomy terms' URLs

Question: I'm working on very large existing Drupal site that has thousands of nodes, user in it and bunch of Taxonomies as well.
I understand very well that Drupal core generates default URLs (taxonomy/term/tid) as we create a taxonomy term but my requirement is not to so is there a way we can control it?
Updated
Actually, I'm working on SEO of the site so according to the SEO report there are more than 10K redirections to 404 page from the Location taxonomy term pages (URL aliases generated by pathauto module and redirected by custom code to 404). So the owners want to reduce 404 redirections.
I was thinking I can achieve this

By deleting URL aliases of terms so aliases URLs'll not be listed in the google search (would be less SEO friendly) and user'll not try to access, by this way we can reduce 404 redirection.
By deleting taxonomy/term/tid, path to such terms will permanently removed so I'll also help to reduce 404.

What do you suggest?
Comment: Can you explain little more about this and what you tried to acheive this
Comment: Core doesn't generate any URLs, there's a route listening for a pattern matching `/taxonomy/term/tid`. Removing that route would probably cause problems, maybe your best approach would be to deny access to those pages. You can do that easily with the Rabbit Hole module, or with a route subscriber in code
Comment: Can't path auto module help you with changing the urls to a new url alias?
Comment: @AjayReddy , see updated question.
Comment: @Clive, see updated question and please suggest an idea
Comment: I recommend the same as my original idea. If you don't want the URLs to get into Google, simply don't link to them anywhere. Google can't find the pages if you don't link to them (and don't include them in a sitemap). For URLs that are already in Google, maybe serve a more accurate status code like 410. Your SEO advisor will be able tell you the best approach for that
Answer: My approach to this previously has been to ensure that there are no links within the site to taxonomy terms and that they are removed from the XML sitepath (using https://www.drupal.org/project/xmlsitemap) so they don't get into the search engines' database in the first place.
I would also recommend a module such as https://www.drupal.org/project/rabbit_hole which can force either a redirect, page not found, or access denied for taxonomy pages (and others) automatically.
I don't think there's any sense in trying to remove taxonomy links from the system when you can use the modules above to achieve this automatically for you.


C++ time spent allocating vectors

Question: I am trying to speed up a piece of code that is ran a total of 150,000,000 times.
I have analysed it using "Very Sleepy", which has indicated that the code is spending the most time in these 3 areas, shown in the image:

The code is as follows:
<code>double nonLocalAtPixel(int ymax, int xmax, int y, int x , vector<nodeStructure> &nodeMST, int squareDimension, Mat &inputImage) {

    vector<double> nodeWeights(8,0);
    vector<double> nodeIntensities(8,0);
    bool allZeroWeights = true;
    int numberEitherside = (squareDimension - 1) / 2;
    int index = 0;
    for (int j = y - numberEitherside; j < y + numberEitherside + 1; j++) {
        for (int i = x - numberEitherside; i < x + numberEitherside + 1; i++) {

            // out of range or the centre pixel
            if (j<0 || i<0 || j>ymax || i>xmax || (j == y && i == x)) {
                index++;
                continue;
            }
            else {
                int centreNodeIndex = y*(xmax+1) + x;
                int thisNodeIndex = j*(xmax+1) + i;

                // add to intensity list
                Scalar pixelIntensityScalar = inputImage.at<uchar>(j, i);
                nodeIntensities[index] = ((double)*pixelIntensityScalar.val);
                // find weight from p to q
                float weight = findWeight(nodeMST, thisNodeIndex, centreNodeIndex);
                if (weight!=0 && allZeroWeights) {
                    allZeroWeights = false;
                }
                nodeWeights[index] = (weight);
                index++;
            }
        }
    }

    // find min b
    int minb = -1;
    int bCost = -1;

    if (allZeroWeights) {
        return 0;
    }
    else {
        // iteratate all b values
        for (int i = 0; i < nodeWeights.size(); i++) {
            if (nodeWeights[i]==0) {
                continue;
            }
            double thisbCost = nonLocalWithb(nodeIntensities[i], nodeIntensities, nodeWeights);

            if (bCost<0 || thisbCost<bCost) {
                bCost = thisbCost;
                minb = nodeIntensities[i];
            }
        }
    }
    return minb;
}
</code>
Firstly, I assume the spent time indicated by Very Sleepy means that the majority of time is spent allocating the vector and deleting the vector?
Secondly, are there any suggestions to speed this code up?
Thanks
Comment: If the vectors are fixed size why not use `std::array` (virtually zero allocation time)?
Comment: You did enable the optimizer?
Comment: Is `findWeight(nodeMST, thisNodeIndex, centreNodeIndex);` pass by value or reference? Is there a reason `nodeMST` is not a const reference?
Comment: When I use std::array, I get a stack overflow error and I have no idea why. The only lines of code I change are the two initialising a vector and the nonLocalWithB arguments to accept arrays.
Comment: In response to Retired Ninja. findWeight passes nodeMST by reference as it is very large. I'm not just the advantages of making it a const reference are? It does change its values every time I run this code.
Answer:
use std::array
reuse the vectors by passing it as an argument of the function or a global variable if possible (not aware of the structure of the code so I need more infos)
allocate one 16 vector size instead of two vectors of size 8. Will make your memory less fragmented
use parallelism if findWeight is thread safe (you need to provide more details on that too)

C++ time spent allocating vectors


Manter aplicação (Windows Form) aberta na bandeja de ícones com C#

Question: Como fazer que ao fechar a aplicação (seja por botão de fechar, ALT F4, ou qualquer outro método que não o gerenciador de processos), a aplicação continue rodando na bandeja de ícones do Windows:

E é muito complicado fazer um menu para quando clicar com o botão de contexto (geralmente botão direito do mouse) sobre o ícone da aplicação na bandeja?
Answer: Fazer não é, resolver tudo o que isto implica pode ser um pouco mais. Para te passar tudo o que é necessário seria muito longo. Você pode ir fazendo perguntas específicas. Para te dar uma base para começar eu achei uma resposta no SO que pode fazer um teste.
static class Program {
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.Run(new MyCustomApplicationContext());
    }
}

public class MyCustomApplicationContext : ApplicationContext {
    private NotifyIcon trayIcon;

    public MyCustomApplicationContext() {
        trayIcon = new NotifyIcon() {
            Icon = Resources.AppIcon,
            ContextMenu = new ContextMenu(new MenuItem[] {
                new MenuItem("Exit", Exit)
            }),
            Visible = true
        };
    }

    void Exit(object sender, EventArgs e) {
        // Hide tray icon, otherwise it will remain shown until user mouses over it
        trayIcon.Visible = false;
        Application.Exit();
    }
}

Coloquei no GitHub para referência futura.
Um tutorial mais completo.
Answer: Para mandar a aplicação para a bandeja do sistema , você pode adicionar um NotifyIcon no designer do seu form e deixá-lo visível sempre que fores minizar ou (nesse caso) fechar a aplicação.
Para adicionar um menu de contexto no seu NotifyIcon você pode adicionar um ContextMenuStrip (ainda no designer do form) e vincular o menu ao NotifyIcon usando a propriedade ContextMenuStrip.
Para mostrar o NotifyIcon sempre que a aplicação for fechada, você pode implementar o evento FormClosing no seu form principal, seria algo como:
public form1_FormClosing(object sender, EventArgs e)
{
    e.Cancel = true; // Cancelar o fechamento do form
    Hide(); // Ocultar o form
    // use this.WindowState = FormWindowState.Minimized; para minimizar
    notifyIcon.Visible = true; // Mostrar o notify icon
}

Um ponto importante é que você não pode esquecer de tirar a visibilidade do seu NotifyIcon antes de fechar a aplicação, pois, caso contrário, o ícone permanecerá na bandeja do sistema até que o usuário passe o mouse por cima do ícone. (Não sei o porquê desse comportamento, mas já sofri muito com ele).
Answer: 1) Acrescentar no form o "notifyIcon";
2) Acrescentar código no evento "notifyIcon1_MouseDoubleClick";
3) Código:
        if (this.WindowState == FormWindowState.Minimized)
        {
            notifyIcon1.Icon = SystemIcons.Application;
            notifyIcon1.BalloonTipText = "Aplicação minimizada";
            notifyIcon1.ShowBalloonTip(1000);
        }

        else if (this.WindowState == FormWindowState.Normal)
        {
            notifyIcon1.BalloonTipText = "Aplicação maximizada";
            notifyIcon1.ShowBalloonTip(1000);
        }

4) Código no botão que minimiza:
    private void button2_Click(object sender, EventArgs e)
    {
        Hide(); // Ocultar o form
        this.WindowState = FormWindowState.Minimized;
    }


html  style code not working

Question: Trying to code a simple webpage and am learning html.  I wonder why my simple styling code for the  makes no changes.  Here it is below.
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/
font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/topnav-index.css">

  Home
  News
  Contact
  About

Title

Responsive Topnav Example

B This site explores the connection between XXX and the
 historical events...

Now the Top Nav bar works but none of the formatting for the p text seems to do anything.  It's in the header & I understand the p, in the greater/less than signs, acts as a specialty container of it's own...
Comment: just a typo font-family: palatino; (not palantino)
Comment: You are using HTML comments within CSS. Do not use `` use `/*` `*/` for CSS comments
Comment: thanks, made the change but no apparent visual effect
Answer: in css  you should use /*  */ for comment and not
p {
    color: red;
    text-align: left;
    font-family: palatino;
    font-size: 16pt;
    background-color: #909090;
    /* margin: 4 prop is top, R, bott, L */
    margin-left: 32px;
    margin-top: 30px;
    /*margin: 20,25,35,40;  */
    padding-left: 12%;
    padding-top: 10%;
}

Comment: thanks I've now advanced quite a bit. can't believe I was making these silly errors at the time.

html  style code not working


Add context menu to XBMC-Plugin

Question: I am trying to get a context menu to display, where I have a button e.g. to delete (or whatever) the selected item.
Answer: On all your ListItems, use addContextMenuItems which takes a list of (label, action) pairs. For action you can use XBMC.RunScript(somescript.py, someid) and implement your delete (or whatever) there.
You can check out XBMC Flicks for an example on how to implement something like this.
Answer: Using the Simpleplugin framework, there is the context_menu parameter for virtual folders.
Same with xbmcswift2.

Add context menu to XBMC-Plugin


Change detection in circular data

Question: Suppose I have a data set that represents circular data measured in degrees:
x <- c(rnorm(1000, 0, 10), rnorm(700, 110, 3), rnorm(1100, 230, 5)) %% 360

The R package circular provides a very nice way to represent that data, and a basic tool for detecting change points in it:
library(circular)
x <- circular(x, units='degrees')
cp <- change.point(x)

However, this particular algorithm is limited, because it's (in my experience) relatively inefficient, and it's limited to finding one change point at a time, so if multiple change points are present, a recursive approach is needed.  This causes some difficulty in deciding when to terminate.
If a linear change point algorithm is used, it will have difficulty with x[1:1000] because some values will be close to 0 and some close to 360.
For linear data, I like the 'PELT' algorithm of Killick, Fearnhead, and Eckley (2011) implemented by the R package changepoint's cpt.mean() function.  It's fast and seems to be pretty reliable.  Has anyone looked at adapting this method to circular data?
Or other recommendations?
Answer: I'm not aware of any multiple changepoint algorithms for circular data available within R.
PELT can be applied to any test statistic which satisfies the assumptions in the paper.  The PELT code is the same regardless of the cost function.  The existing changepoint package implementation is in C.  It is simply a case of coding up a new cost function that can be plugged into the existing PELT code instead of e.g.mll.mean for the PELT.mean.norm function in C.
Which test statistic from the change.point function were you interested in?  I can then check if it satisfies the assumptions for PELT.  If it does then it isn't a large job to code it up.
Comment: To be honest I don't really know what `change.point()` is doing - it's an implementation of an algorithm given in a book, but the book is $175 on Amazon.  Luckily the code is open, but I haven't been able to look into it yet.  Nor do I necessarily like its results yet, I just like the fact that it's circular. =)
Comment: Essentially, you just want to extend the single changepoint method to multiple changes.  The easiest way to do this (not necessarily the best) is to implement Binary Segmentation.  That is essentially a smart `while` loop which starts with the entire data, runs the `change.point` function then splits the data at the changepoint if one is identified.  Then you run `change.point` again on the sub series.  Repeat the above until no more changepoints are found.  This is an approximate segmentation though compared to PELT which is exact.

Change detection in circular data


Como fazer o Postgres criar um arquivo para povoar um banco?

Question: Tenho um banco no POSTGRESQL povoado , queria  saber se existe um comando
SQL que retorne um aqruivo  que tivesse o seguinte comando para todas as tabelas existentes:
INSERT INTO aluno(id , nome, idade ) values(1,'Raul',23)

Queria fazer isso para povoar um outro banco que possui dados similares ao banco antigo , porem possui novas tabelas!
Comment: Só para ver se entendi, você precisa que seja gerado um arquivo com os comando SQL's de inserção dos dados já cadastrados em suas tabelas antigas para poder adicioná-los a tabelas novas porém com a mesma estrutura?
Comment: Se for isso, veja se esse link te ajuda http://www.guj.com.br/t/postgresql-gerar-script-de-um-banco-populado-resolvido/291383/3
Comment: Essas tabelas novas estão criadas em qual banco? É PostgreSQL também
Comment: É um outro banco, no  PostgresSQL tambem!
Answer: Para gerar os comandos insert dos dados que contém no banco você pode fazer da seguinte maneira:
Selecionar o formato Plain

Na aba Dump Options 1, marcar "Data"

Na aba Dump Options 2, marcar "User Insert Commands"

Sugiro utilizar o notepad++ para abrir
Comment: Obrigado pela atenção, sua resposta parece estar certa mas não consigo ver os dados no notepad++ , uso a versao 7.2 e o PGadmin  9.6. Qual versao do PGAdmin você usa?
Comment: Você selecionou o tipo de dados "Plain"? Uso o postgresql 9.5 e pgAdmin 3. Mas acredito que o formato que você usou não é "Plain"
Comment: @Deu bronca porque eu usava o  postgresql 9.6  e o pgAdmin 3! Mas vou installar a versao 9.5! Essa versao 9.6 veio com o pgAdmin masi lento e uma interface estranha !!Obrigado!
Answer: Utilize o utilitário pg_dump:
https://www.postgresql.org/docs/current/static/app-pgdump.html


How to do deep traversals with FindItem queries

Question: I am sending the following XML query to EWS using the Office.context.mailbox.makeEwsRequestAsync method. It works as long as Traversal is set to "Shallow".  I get a "The request is invalid" error when I set Traversal to "Deep".
 How do I recursively search subfolders if I can't do deep searches?
  <?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
      <t:RequestServerVersion Version="Exchange2013_SP1" />
    </soap:Header>
    <soap:Body>
      <m:FindItem Traversal="Shallow">
        <m:ItemShape>
          <t:BaseShape>AllProperties</t:BaseShape>
        </m:ItemShape>
        <m:IndexedPageItemView MaxEntriesReturned="10" Offset="0" BasePoint="Beginning" />
        <m:Restriction>
          <t:Contains ContainmentMode="FullString" ContainmentComparison="IgnoreCase">
            <t:FieldURI FieldURI="item:Categories" />
            <t:Constant Value="MyCategory" />
          </t:Contains>
        </m:Restriction>
        <m:ParentFolderIds>
          <t:DistinguishedFolderId Id="inbox" />
          <t:DistinguishedFolderId Id="sentitems" />
        </m:ParentFolderIds>
      </m:FindItem>
    </soap:Body>
  </soap:Envelope>

Comment: Sorry but deep searches in the inbox do NOT work with FindFolder. Source: https://learn.microsoft.com/en-us/exchange/client-developer/web-service-reference/findfolder-operation ...
Remarks FindFolder returns only the first 512 bytes of any streamable property. For Unicode, it returns the first 255 characters by using a null-terminated Unicode string. **Deep traversal queries cannot be performed on public folders.**
...
Answer: The FindItem EWS call does not support Traversal="Deep". See FindItem.
This is because the call will search for items in the folders specified in ParentFolderIds. In order to do a recursive search, you will need to get the list of folders to include in the search by using the FindFolder EWS Operation which supports Traversal="Deep" on non public folders. See FindFolder for additional documentation.


Assert that two labels are less than N bytes apart in NASM

Question: In NASM, can I compile-time assert that two labels are less than N bytes apart?
I.e., something like:
label1:
; some code
; goes here
label2:

; here I want to check that the distance between label1 and label2 is less than 50 bytes...

The issue should be caught at compile-time, ideally with an understandable error message.
Answer: Assuming that the labels occur before the check, this should work:
label1:
resb 50  ; For testing purposes
label2:

%if (label2 - label1) >= 50
%error "Blah blah blah"
%endif


Converter string no formato dd/mm/yyyy hh:mm para Date

Question: Como posso converter uma data que está em string para um tipo data?
Tentei fazer da seguinte forma mas não funcionou:
var string = "19/07/2019 14:18"
var date = new Date(string);

Quando dou um console.log(date); me mostra "data inválida".
Comment: Conforme a [MDN](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date), quando você passa uma `dataString` a *string* deverá estar uma formato reconhecido pelo método [`Date.parse()`](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date/parse)
Comment: Segue a solução: https://pt.stackoverflow.com/questions/6526/como-formatar-data-no-javascript
Answer: Você precisa passar uma string de data em uma formato válido.
De acordo com a documentação, entre as diversas formas de instanciar uma data, existe a opção de passar uma string. Nesse caso:

Um valor do tipo String que representa uma data. A string deverá estar uma formato reconhecido pelo método Date.parse() (IETF-compliant RFC 2822 timestamps e também uma versão da ISO8601).

Assim, a forma mais fácil é converter a sua string (que está no formato brasileiro), para o formato compatível com o ISO. Nesse caso:
YYYY-MM-DDTHH:mm

Em que:

YYYY ⇒ representa o ano;
MM ⇒ representa o mês;
DD ⇒ representa o dia;
T ⇒ representa a separação entre a "data" e a hora;
HH ⇒ representa a hora do dia;
mm ⇒ representa os minutos da hora.

Então, podemos criar uma função para converter a data:

// A data passada deve estar no padrão:
// DD/MM/YYYY HH:mm
function toISOFormat(dateTimeString) {
  // Primeiro, dividimos a data completa em duas partes:
  const [date, time] = dateTimeString.split(' ');

  // Dividimos a data em dia, mês e ano:
  const [DD, MM, YYYY] = date.split('/');

  // Dividimos o tempo em hora e minutos:
  const [HH, mm] = time.split(':');

  // Retornamos a data formatada em um padrão compatível com ISO:
  return `${YYYY}-${MM}-${DD}T${HH}:${mm}`;
}

console.log(toISOFormat('19/07/2019 14:18'));

Agora que você tem o meio de converter a data, basta instanciá-la:

// A data passada deve estar no padrão:
// DD/MM/YYYY HH:mm
function toISOFormat(dateTimeString) {
  // Primeiro, dividimos a data completa em duas partes:
  const [date, time] = dateTimeString.split(' ');

  // Dividimos a data em dia, mês e ano:
  const [DD, MM, YYYY] = date.split('/');

  // Dividimos o tempo em hora e minutos:
  const [HH, mm] = time.split(':');

  // Retornamos a data formatada em um padrão compatível com ISO:
  return `${YYYY}-${MM}-${DD}T${HH}:${mm}`;
}

const dateString = toISOFormat('19/07/2019 14:18');
const date = new Date(dateString);

// Testando:
console.log(date.getFullYear());

É importante dizer que existem muitas formas de se construir uma data no JavaScript. Essa resposta aborda somente uma das diversas possibilidades. Para saber mais, não deixe de consultar a documentação do Date na MDN.
Comment: Por que o negativo?
Comment: minha data está nesse formato 2019-07-19 19:46:00
porém quando uso  no console.log(new Date(stringDate)) ele me retorna data invalida
a data está no formato correto ?
Comment: Qual o seu navegador e a versão dele? Tente instanciar a data com esse formato: `new Date('2019-07-19T19:46:00')`. Funciona?
Answer: Como muitos já disseram, quando você passa uma string para o construtor de Date, a documentação diz que esta string deve estar em um formato reconhecido por Date.parse. Qualquer outro formato pode resultar em uma data inválida (ou em comportamento indefinido, dependente do browser).
Dito isso, o formato que você está usando não está entre os que são citados na documentação. Uma alternativa seria transformar a string em um dos formatos reconhecidos, como já foi sugerido pelas outras respostas. Mas o construtor de Date também pode receber os valores numéricos diretamente, então basta extraí-los da string:

let s = "19/07/2019 14:18";
let [dia, mes, ano, hora, minuto] = s.split(/[\/: ]/).map(v => parseInt(v));
let data = new Date(ano, mes - 1, dia, hora, minuto);
console.log(data);
console.log(data.getTime());

Usei a regex [\/: ] (uma barra, ou dois pontos, ou espaço) para separar todos os campos de uma vez (é meio "ingênuo", pois se a string for "19 07:2019/14 18", também funcionará - se quiser ser mais restrito quanto ao formato, pode usar as opções sugeridas nas outras respostas).
Em seguida uso map com parseInt para transformar cada trecho em um número (já que o split retorna um array de strings) - assim você já valida que cada parte é um número, já que parseInt retorna NaN caso não receba um número, e o resultado será uma data inválida.
Repare também que tive que subtrair 1 do mês, já que nesta API os meses são indexados em zero (janeiro é zero, fevereiro é 1, etc).
Apesar disso, o construtor aceita valores aparentemente inválidos, como mês 15, dia 32, etc, e faz alguns ajustes automáticos e "não-intuitivos" (dia 32 acaba virando o dia 1 do mês seguinte, mês 12 acaba virando janeiro do ano seguinte, etc). Então se quiser, você ainda pode incluir validações a mais antes de criar a data (if (1 <= dia && dia <= 31), etc) para garantir que os valores são realmente válidos.
Por fim, eu imprimo a data e também o valor de getTime(), que retorna o respectivo timestamp. E aqui tem um detalhe muito importante...

O que é o Date do JavaScript
Um Date do JavaScript representa na verdade um timestamp: a quantidade de milissegundos desde o Unix Epoch (que é 1970-01-01T00:00Z, ou 1 de janeiro de 1970, à meia-noite, em UTC).
O detalhe é que o timestamp é "universal", no sentido de ser o mesmo no mundo todo (diferente dos fusos horários, que em cada parte do mundo pode ser uma data e hora diferente).
Por exemplo, na minha máquina, rodando o código acima, o retorno de data.getTime() foi 1563556680000. Este timestamp representa um único instante, um ponto na linha do tempo. Este exato instante, porém, pode representar uma data e hora diferentes em cada parte do mundo:

No Horário de Brasília, é 19 de julho de 2019, às 14:18
No Japão, é 20 de julho de 2019, às 02:18 da manhã
Em UTC, é 19 de julho de 2019, às 17:18

O mesmo valor de timestamp (1563556680000) corresponde a todas as datas e horas acima. O instante (o ponto na linha do tempo) é o mesmo, o que muda é o valor da data e hora local, de acordo com o timezone (fuso horário) que você usa.
E por que estou dizendo tudo isso? Por que quando eu criei o Date acima passando os valores de data e hora, ele usa o timezone do browser para calcular o timestamp (e o browser, por sua vez, geralmente usa o que está configurado no sistema operacional). Como meu browser está usando o Horário de Brasília, ele entende que estou criando uma data correspondente a 19/07/2019, às 14:18, neste timezone.
Mas se eu mudar o timezone (fuso horário) do meu sistema para o fuso do Japão, o JavaScript vai criar uma data correspondente a 19/07/2019, às 14:18, no fuso horário do Japão. E neste caso, o valor de getTime() será 1563513480000 (um valor completamente diferente, já que 19/07/2019, às 14:18 no Japão ocorreu em um instante diferente de 19/07/2019, às 14:18 no Brasil).
Claro que, dependendo do que você está fazendo com a data, pode não fazer diferença. Mas como você disse nos comentários que quer calcular a diferença para a data atual, pode ser que faça alguma diferença.
A string "19/07/2019 14:18", por exemplo, foi gerada em qual fuso horário? Se for o mesmo que o browser está usando, tudo bem, pois você estará comparando datas e horas no mesmo timezone. Mas caso eles sejam diferentes (por exemplo, o browser está usando o fuso dos EUA, mas a string refere-se a um horário no Brasil - não foi dito onde nem como a string foi gerada, então não é seguro assumir que ela necessariamente usou o mesmo timezone do ambiente no qual o parsing ocorrerá), aí a comparação poderá retornar um resultado incorreto.
Se você usar o código da resposta do Jorge, por exemplo, vai obter uma data correspondente a 19/07/2019, às 14:18 em UTC (que corresponde ao timestamp 1563545880000, e às 11:18 no Horário de Brasília). Isso ocorre porque ele adicionou o Z no final, e isso indica que a data/hora está em UTC. Já a solução do Luiz Felipe não adiciona o Z, então a data/hora é interpretada usando-se o timezone do browser (comporta-se igual ao construtor que recebe os valores numéricos).

Mais um caso bizarro: horário de verão
Atualmente o Brasil não tem horário de verão, mas como isso é algo definido por governos, não há nenhuma garantia de que isso não mude no futuro (e isso costuma mudar o tempo todo). De qualquer forma, existem duas situações envolvendo o horário de verão que podem causar alguns resultados estranhos ao se transformar uma string para data.
Um é quando o horário de verão começa. Por exemplo, no Brasil, em 4 de novembro de 2018, à meia-noite os relógios foram adiantados em uma hora. Em muitos sistemas isso já estava automatizado, e na prática o que acontece é que os relógios pulam automaticamente de 23:59:59.999 para 01:00. Isso quer dizer que todos os minutos entre meia-noite e 00:59 não existem neste dia, neste fuso-horário. Então o que acontece se tentarmos criar uma data exatamente neste dia e hora (o código abaixo assume que o timezone do seu sistema está configurado com o Horário de Brasília e ele está atualizado com as regras do horário de verão):

let date = new Date(2018, 10, 4, 0, 30);
console.log(date, date.getTime());

O timestamp resultante é 1541302200000, que corresponde a 04/11/2018, às 01:30 no Horário de Brasília (ou 03:30 em UTC). Como 00:30 não existe nesse dia (graças ao "pulo automático" do horário de verão), então o JavaScript automaticamente ajusta para 01:30 (é como se ele simulasse alguém olhando o relógio, percebendo que esqueceu de adiantá-lo e corrigindo o horário). Ou seja, se você receber a string "04/11/2018 00:30" e estiver usando o timezone do Brasil, pode ocorrer esta situação, caso a data e hora caiam neste intervalo de minutos que são pulados (também chamado de DST Gap - Daylight Saving Time Gap).
E quando o horário de verão termina, a situação é igualmente estranha. Em 2018, por exemplo, isso ocorreu em fevereiro. No dia 18/02/2018, à meia-noite, os relógios são atrasados de volta para 23:00 do dia 17. Isso quer dizer que todos os minutos entre 23:00 e 23:59 ocorrem duas vezes (uma no horário de verão, outra no horário "normal" - isso é chamado de DST Overlap). Então se você receber a string "17/02/2018 23:30", qual das duas ocorrências será criada?

let date = new Date(2018, 1, 17, 23, 30);
console.log(date, date.getTime());

O timestamp resultante foi 1518917400000, que corresponde à primeira ocorrência das 23:30 (ainda em horário de verão). Se eu quiser a segunda ocorrência (depois que o horário de verão já terminou), tenho que somar uma hora manualmente:

let date = new Date(2018, 1, 17, 23, 30);
date.setTime(date.getTime() + (1000 * 60 * 60));
console.log(date, date.getTime());

Isso pode fazer diferença se você for calcular a diferença com relação a data atual (no caso, pode dar uma hora de diferença). Infelizmente a API nativa do JavaScript não fornece uma maneira melhor de trabalhar com datas, e principalmente com fusos horários.

Moment.js
Uma alternativa é usar o Moment.js, uma API excelente para se trabalhar com datas. Exemplo:

// transformar string em data
let data = moment("19/07/2019 14:18", "DD/MM/YYYY HH:mm");

// diferença em minutos para a data atual
let minutos = moment().diff(data, 'minutes');
console.log(minutos);

// se quiser um Date do JavaScript
let jsDate = data.toDate();
console.log(jsDate);

O Moment.js também usa o timezone do browser e tem o mesmo comportamento descrito acima durante os gaps e overlaps do horário de verão, então os mesmos pontos de atenção já citados se aplicam aqui.
Caso queira que as datas estejam em um fuso horário específico, pode usar o Moment Timezone. Com ele você pode controlar qual o fuso horário usado para a data/hora:

// data no horário de Brasília
let dataBr = moment.tz("04/11/2018 00:30", "DD/MM/YYYY HH:mm", "America/Sao_Paulo");
// data no fuso do Japão
let dataJp = moment.tz("04/11/2018 00:30", "DD/MM/YYYY HH:mm", "Asia/Tokyo");

// diferença em minutos para a data atual
console.log(moment().diff(dataBr, 'minutes'));
console.log(moment().diff(dataJp, 'minutes'));

// se quiser um Date do JavaScript
console.log(dataBr.toDate());
console.log(dataJp.toDate());

Repare como a diferença em minutos e o Date correspondente é diferente, dependendo do timezone usado, já que 04/11/2018 00:30 ocorreu em instantes diferentes no Brasil e no Japão. Não sei se você vai precisar chegar a tal grau de preciosismo, mas de qualquer forma, "o diabo está nos detalhes", então fica aí a opção, caso seja necessário.
Os nomes dos timezones ("America/Sao_Paulo", "Asia/Tokyo") são definidos pelo IANA Timezone Database. Para saber quais os timezones disponibilizados pelo Moment, use moment.tz.names().
Answer: Converta a data para o Formato UTC
Veja  mais sobre em:
https://stackoverflow.com/questions/40768606/i-have-a-utc-string-and-i-want-to-convert-it-to-utc-date-object-in-javascript/40768745#40768745

var string = "19/07/2019 14:18"
p = string.match(/(\d\d)\/(\d\d)\/(\d\d\d\d) (\d\d):(\d\d)/)
var date = new Date(p[3]+'-'+p[2]+'-'+p[1]+'T'+p[4]+':'+p[5]+':00Z');

console.log(date)
Comment: isso me retornou

 Fri Jul 19 2019 11:49:00 GMT-0300 (Horário Padrão de Brasília)

fazendo dessa forma conseguiria pegar a diferença dessa data com a data atual e me retornar a diferença em minutos usando o .getTime() ? @Jorge Costa
Comment: executando o exemplo na página o resultado é 2019-07-19T14:18:00.000Z"


Quasi-separatedness of diagonal of DM stacks and group stabilizer of a point

Question: I was studying Jarod Alper's book on stacks (https://sites.math.washington.edu/~jarod/moduli.pdf) and after the definition of stacks and some basic discussion about them, he proposes the following exercise:

If $\mathcal{X}$ is DM stack, $k$ a field and $x \in \mathcal{X}(k)$, then the group scheme $G_x$ is étale over $k$.

Here $G_x$ is the group stabilizer of $x$, and this is exercise 3.2.8 at page 102 of the current version.
My problem is that, a priori, $G_x$ is just a group algebraic space, not a scheme, and i am having trouble proving its schemeness. Just above the exercise, Alper mentions a result to be proved later that says that, if the diagonal of $\mathcal{X}$ is quasi-separated, then $G_x$ is a group scheme locally of finite type over $k$. Assuming this i think i have managed to solve the exercise, but this requires the diagonal of $\mathcal{X}$ to be quasi-separated (i will write qs in the following), but i have not managed to show this.
I have seen that some authors define DM stacks by asking that the diagonal be qs, but Alper does not, and neither does Olsson in his book on stacks. For completion, i recall that Alper defines a DM stack $\mathcal{X}$ to be a stack with an étale surjective representable map $U \to \mathcal{X}$ from a scheme $U$ (he then shows representability of the diagonal).
Is it true that Alper's definition implies that $\Delta_\mathcal{X}$ is qs? If this is not true, how could i solve the exercise?
Answer: The diagonal of a Deligne-Mumford stack is not necessarily quasi-separated; take the classifying stack $BG$ of the non-quasi-separated scheme $G = \mathbb{A}^{\infty} \cup_{\mathbb{A}^{\infty} \setminus 0} \mathbb{A}^{\infty}$ viewed as a group scheme over $\mathbb{A}^{\infty} = {\rm Spec} k[x_1, x_2, \ldots, x_n]$.
To solve the exercise, first show that $G_x$ is an etale group algebraic space over $k$.  If $k= \bar{k}$, use that any section of the structure morphism $G_x \to {\rm Spec} k$ is an open immersion to give an open covering of $G_x$ by schemes, and then use that any group scheme over a field is separated (see Tag 047L).  Over a general field, apply effective descent for separated and locally quasi-finite morphisms to conclude that $G_x$ is a scheme. This shows that the stabilizer of any field-valued point of a Deligne-Mumford stack (w/out any conditions on the diagonal) is a separated etale group scheme.
Comment: Now it's much clearer, right! Thanks for the answer


How to prevent empty field wrapper from rendering in views

Question: In views I display fields for specific content types. One field is referenced to taxonomy term. Not every node has the term reference. I need to style this field with paddings and colours so I would want it not to be rendered at all if term reference is missing. I have chosen under "no result behaviour" in field settings in views to "hide if empty" and "hide rewriting if empty". However, the two divs still get rendered in HTML at empty fields.. (.views-field and inside .field-content).
Is this expected behaviour? I tried to fix it with twig template (views-view-fields), but I can't seem to find solution of how to check for empty content (null or empty don't work on field.content as it returns length>0, I suppose the html is already in field.content)
Answer: It may seem a bit ugly solution, but if you wanna avoid a template override you can archive this effect simply by using the css selector :empty on the divs, something like:
div.class:empty {
  display: none;
}

Comment: Thanks, this didn't work because I had some twig debug comments inside field and within them some whitespace characters. But you set me on the right track. I removed twig debug temporarily and then views started hiding whole field's html wrapper as designed.

So twig debugger somehow prevented views to hide the field even if "empty".

If I added some text under "no results behaviour", it worked even with twig debug enabled. So at some point views realized it's empty.  It just didn't hide HTML.


Calculating Conditional Expectations

Question: Say $X$ is continuous and distributed according to CDF $G$.
How would we calculate $\text{E}[X|X<a]$?
Comment: The conditional mean equals $\frac{E(X\mathbf1_{X<a})}{P(X<a)}$.
Comment: This is only true, if $P(X 0$. Is that the case?
Comment: What is $E(X1_{X<a})$?  And what does $G(a-)$ mean?
Comment: It is indeed the case that $P(X0$
Comment: @Guest Is this for some course? Can you find the conditional (truncated) distribution $X\mid X<a$ and hence find the expectation?
Comment: @StubbornAtom Yes, I'm looking for an integral with the original PDF in it, if it's possible to get a conditional expectation in that form. I'm guessing just restrict the limits?
Answer: If the CDF is $G\left(x\right)=P\left(X\leq x\right)$ and the PDF is $g\left(x\right)=\frac{d}{dx}G\left(x\right)$ then the conditional expectation is $$E\left[X|X<a\right]=\frac{\int_{-\infty}^{a}u\cdot g\left(u\right)du}{\int_{-\infty}^{a}g\left(u\right)du}=\frac{\int_{-\infty}^{a}u\cdot g\left(u\right)du}{G\left(a\right)}$$

Calculating Conditional Expectations


Handle NodeJS error event?

Question: I have a worker class that has lots of different utility methods, and emits error messages when there's a problem anywhere in the execution. Due to NodeJS magic, error messages are special, and if nothing is listening to them, they're turned into thrown Errors, so I currently do:
var myWorkerFunction = function(input) {
  var w = myFactory();
  try {
    w.dothis();
    w.dothat(input);
    w.hokeypokey();
    return w.finalize();
  } catch(e) {
    return false;
  }
}

What I wonder though, is it possible to avoid the try/catch block entirely? NodeJS's documentation seems to indicate it's best to avoid not re-throwing a caught exception (I'm doing no checks here to see that it really was my worker's logic that threw the exception and not a critical fault from Node).
So I'd like to do something like:
var myWorkerFunction = function(input) {
  var w = myFactory();
  w.on('error', function() {
    // How to tell caller of myWorkerFunction() I failed,
    //   and stop the rest of the myWorkerFunction function? (return false)
  });
  w.dothis();
  w.dothat(input);
  w.hokeypokey();
  return w.finalize();
}

But how to trigger that "return" for myWorkerFunction inside that event listener function? I could have myWorkerFunction emit an "error" message too, but that just kicks the can to the next layer, and doesn't stop the execution of the worker script (i.e. if dothis() fails, don't keep going and call dothat(input)). Is there a programming pattern for situations like this?
EDIT: The one solution I could come up with is something like:
var myWorkerFunction = function(input) {
  var w = myFactory();
  var hasFailed = false;
  w.on('error', function() {
    hasFailed = true;
  });
  w.dothis();
  if (hasFailed) return fa;se
  w.dothat(input);
  if (hasFailed) return false;
  w.hokeypokey();
  if (hasFailed) return false;
  var out = w.finalize();
  if (hasFailed) return false;
  return out;
}

Which is not very elegant having to constantly check if we've failed or not before every line of code.
Comment: You can use domains for this, and then figure out what to do with the error in the callback.
Comment: @adeneo: could you give a code example of how to do that?
Answer: A couple thoughts on this. First you might want to take a look at Caolan McMahon's fine async nodejs library because it feels like you're reinventing flow control that would be handled quite well with 'async.waterfall'.
If you don't feel it's a good fit you - following the pattern you've adopted you could opt to post events on completion of each step (see the 'done' events in the sample below). This would allow you to listen for those events as indication that no error has occurred and that it makes sense to move onto the next step. Let 'finalize' take an optional error to allow your worker to differentiate normal vs abnormal completion. This is not tested but here's what something like that might look like:
var myWorkerFunction = function(input) {
  var w = myFactory();
  w.on('error', function(error) {
    // Handle error, log whatever - and finalize with an error?
    w.finalize(error);
  });
  w.on('doneWithThis', function() {
    w.dothat(input);
  });
  w.on('doneWithThat', function() {
    w.hokeypokey();
  });
  w.on('doneWithHokeypokey', function() {
    w.finalize();
  });

  w.dothis(); //starts the ball rolling.
}

Comment: Good advice; in the intervening two years since I posted this, I have learned about the `async.waterfall` class, and have used that where I control the library (like this case where the worker methods are mine). As the javascript roadmap is moving towards Promises as a native mechanic, having the worker methods return promises that resolve when done would be another means of doing this.
Comment: @MidnightLightning is it reasonable to mark this as the correct answer?

Handle NodeJS error event?


get a two dimensional array out of a query sql

Question: i have a query like that:
$pd= DB::table("projects")
            ->orderBy("project_number", "asc")
            ->select('name' , "type")
            ->get()->keyBy('date_scheduled');;

and i get a array keyed By the date_scheduled which is fine, but the problem is date_scheduled is not unique so it overwrites the entries. So i need to get a two dimensional array with keyby date_scheduled like:
[
 'date_1_of_date_scheduled' => [0 => '1', 1 => '4', 2 => '17']
 'date_2_of_date_scheduled' => [0 => '15', 1 => '64', 2 => '1142']
 'date_3_of_date_scheduled' => [0 => '25', 1 => '125', 2 => '66']
]

Answer: You can use groupBy() instead of keyBy(): https://laravel.com/docs/8.x/collections#method-groupby
$pd = DB::table("projects")
    ->orderBy("project_number", "asc")
    ->select('name' , "type")
    ->get()
    ->groupBy('date_scheduled');

Answer: You can use the laravel map function for the purpose
Try that:
$pd= DB::table("projects")
            ->orderBy("project_number", "asc")
            ->select('name' , "type")
            ->get()
            ->map(function ($item) {
               return ['date_'.$item->date_scheduled.'_of_date_scheduled' => $item->YOUR_DESIRED_DATA] ;
             }


Changing date-time to Month, Day, Year

Question: I am integrating a new bootstrap template on my current Rails website. I am working on my blog and right now I have posts shown like "10 minutes ago". I want to change the date format like Dec, 21, 2012 in separate lines.
The new template does this by just hardcoding the date:

    Dec
    21
    2012

The way I get the date is by using this:
time_ago_in_words(post.created_at)

My question is how can I extract the date that the post was created in separated elements like the month, the year and the day?
Answer: time_ago_in_words will convert the Time object to a human representable and easily readable string.
In your case you don't need that. You can simply use the date/time methods on post.created_at to get back the year, month and day:

post.created_at.year
post.created_at.mday
post.created_at.month

Note that these will return the results in numbers (eg 12 instead of Dec). You can use I18n utils to get back the abbreviated name like this:

I18n.t("date.abbr_month_names")[post.created_at.month]

You can alsu use strftime to convert a Time to string:

post.created_at.strftime('%b')

Note however, that this won't go through Rails' I18n engine if you care about internationalization.

Changing date-time to Month, Day, Year


google.load is loading the old version of jquery causing versioning issues

Question: I have these two lines of code in my web page:
    google.load("jquery", "1.7.0");
    google.load("jqueryui", "1.8.16");

And I decide to upgrade to the newer version:
    google.load("jquery", "1.8.2");
    google.load("jqueryui", "1.9.0");

Now the whole page breaks. When I inspect in Google Chrome by looking in the Sources tab I see that the old versions of the files are there. Also when I look at console for errors I get these errors:
Uncaught Error: Module: 'jquery' with version '1.8.2' not found!
Uncaught ReferenceError: $ is not defined
Uncaught ReferenceError: jQuery is not defined
Uncaught TypeError: undefined is not a function
Note: This problem is not browser specific. Also, I have upgraded in the past with no issues. Whats going on here. And how do I resolve it? Many thanks!
Answer: if you're only using the google object to load jQuery, then you can simply load jQuery directly and avoid any problems that has to do with the google script

in addition, jquery 1.8 is not in the Google Loader
If you go directly to https://www.google.com/jsapi you will see at the bottom all of the supported versions and that 1.8.1 does not exist.
Comment: That does fix the problem. Therefore the issues seems to be with google loader. It has worked for me in the past however.
Comment: Yes, the reason it breaks is that it is not included in the google loader. I guess there are two different people at Google responsible for updating the cdn and updating the google loader, and it appears that, either they don't talk to each other or the one responsible for google loader has not updated his code. I assumed that if the cdn was updated, the loader was updated also. My big mistake.
Comment: You should use the google.load for google APIs, I don't see the point of loading an entire API if all you're going to use it for is load another API... spare you users the traffic and gain the maximum speed.. also notice that on the cdn page, they don't say anything about using the google loader.
Answer: Try to take a look at your google variable and ensure the links are similar to the ones listed in here:
https://developers.google.com/speed/libraries/devguide#jquery
Answer: @note Google's api/library loader api has apparently changed somewhat since first released.
Then, we were able to .load('jquery', '1.8') or .load('jqueryui', '1.9') and still get the stable edge release. Now we cannot seem to specify the revision/minor release w/any reliability - only the major eg. '1' or exact eg. '1.8.3'.
@see this page and scroll down to Versioning for specifics. It details the above and 'recommends' requesting an api's 'test version' for our development environments via wildcard eg. '1.x' in to facilitate feedback and essentially early regression testing.  My tests w/two popular libraries failed w/this construct and while that documentation needs work, this may work only for google (and not 'hosted') libraries. Additionally, while requesting only '1' versions works, you'll get only very outdated versions.
@net For hosted libraries, I'm planning on dumping the google.load pattern and going w/the src="" method documented here:. Libs can will still be loaded async with tag injection or just drop the tags in before their needed if more convenient. Then, while faster from google, I'll still be backing these up w/my own copies to be loaded in case - a recommended practice.