Problema com checkbox e o evento OnItemClick

Question: Criei uma lista com checkbox desabilitado, onde o objetivo é que quando o usuário clique em um item da lista, abra-se uma nova tela e o check seja marcado, porém não consigo fazer com que o check seja marcado automaticamente.

Classe ListaActivity

public class ListaActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{

private ListView listView;

private AdapterListView adapterListView;

private ArrayList<ItemListView> Itens;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_lista);

    listView = (ListView) findViewById(R.id.lstLista);

    listView.setOnItemClickListener(this);

    CriarLista();
}

private void CriarLista(){

    Itens = new ArrayList<ItemListView>();

    ItemListView Item1 = new ItemListView("Frase 1", 0, false);
    ItemListView Item2 = new ItemListView("Frase 2", 1, false);
    ItemListView Item3 = new ItemListView("Frase 3", 2, false);
    ItemListView Item4 = new ItemListView("Frase 4", 3, false);
    ItemListView Item5 = new ItemListView("Frase 5", 4, false);
    ItemListView Item6 = new ItemListView("Frase 6", 5, false);
    ItemListView Item7 = new ItemListView("Frase 7", 6, false);
    ItemListView Item8 = new ItemListView("Frase 8", 7, false);
    ItemListView Item9 = new ItemListView("Frase 9", 8, false);
    ItemListView Item10 = new ItemListView("Frase 10", 9, false);

    Itens.add(Item1);
    Itens.add(Item2);
    Itens.add(Item3);
    Itens.add(Item4);
    Itens.add(Item5);
    Itens.add(Item6);
    Itens.add(Item7);
    Itens.add(Item8);
    Itens.add(Item9);
    Itens.add(Item10);

    adapterListView = new AdapterListView(this, Itens);

    listView.setAdapter(adapterListView);

    listView.setCacheColorHint(Color.TRANSPARENT);

}

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){

    ItemListView item = adapterListView.getItem(arg2);

    item.setCheck(true);

    Intent EnviarDados = new Intent(ListaActivity.this, FraseActivity.class);

    int id = item.getId();

    Bundle bundle = new Bundle();

    bundle.putInt("id", id);

    EnviarDados.putExtras(bundle);

    startActivity(EnviarDados);
}

}

Class ItemListView

public class ItemListView {
private String Texto;
private int Id;
private boolean Check;

public ItemListView(String texto, int id, boolean check){
    this.Texto = texto;
    this.Id = id;
    this.Check = check;
}

public String getTexto(){
    return Texto;
}

public void setTexto(String texto){
    Texto = texto;
}

public int getId() {
    return Id;
}

public void setId(int id) {
    Id = id;
}

public boolean getCheck() {
    return Check;
}

public void setCheck(boolean check) {
    Check = check;
}

}

Classe AdapterListView

public class AdapterListView extends BaseAdapter{
private LayoutInflater mInflater;
private ArrayList<ItemListView> Itens;

public AdapterListView(Context context, ArrayList<ItemListView> Itens){
    this.Itens = Itens;
    mInflater = LayoutInflater.from(context);
}

public int getCount(){
    return Itens.size();
}

public ItemListView getItem(int position){
    return Itens.get(position);
}

public long getItemId(int position){
    return position;
}

public View getView(int position, View view, ViewGroup parent){
    ItemListView item = Itens.get(position);
    view = mInflater.inflate(R.layout.item_listview, null);

    ((TextView) view.findViewById(R.id.txtItem)).setText(item.getTexto());
    ((CheckBox) view.findViewById(R.id.chkItem)).setChecked(item.getCheck());

    return view;
}

}

Answer: Você se esqueceu de chamar notifyDataSetChanged().
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){

    ItemListView item = adapterListView.getItem(arg2);

    item.setCheck(true);

    // Como o próprio nome sugere, notifica o adapter
    // que os dados da sua lista foram alterados.
    // Ao ser chamado, atualiza suas views/items
    adapterListView.notifyDataSetChanged();

    // ...
}


Enviar JavaScript por email

Question: Eu tenho um código em C# que manda emails com HTML, até aí ok, o problema é que eu não consigo mandar scripts(JS). Sim, entendo porque,deve ser motivos de segurança. Mas não tem como burlar ou fazer de outra forma? -- Sem nenhuma intenção maliciosa. Meu código:
using (MailMessage mail = new MailMessage())
        {
            mail.From = new MailAddress("firstname.lastname@example.com");
            mail.To.Add("email@example.com");
            mail.Subject = "xxx";
            mail.Body = @"";
            mail.IsBodyHtml = true;

            using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
            {
                smtp.Credentials = new NetworkCredential("email@example.com", "xxx");
                smtp.EnableSsl = true;
                smtp.Send(mail);
            }
        }

Comment: Então, os servidores de e-mail, por exemplo Gmail, Hotmail e afins, por segurança não deixam nada disso executar, não há como burlar, a única forma, vejo eu, seria utilizar algum receptor de e-mail que não dependam desses serviços de e-mail, aí sim, pois estes utilizam algum tipo de stripHtml ao receber a mensagem, ou seja, a sua mensagem chega em qualquer leitor de terceiros ou outros, já sem estes scripts! Acredito ser uma demanda em vão, encontre alternativas!
Comment: Como vc perguntou se isso não pode ser feito de outra forma, qual seria a função do script?
Comment: @dvd Apenas mostrar um alerta. Eu sei que posso exibir a mensagem no HTML,mas eu queria exebir um `alert` em JS, só para ver se iria funcionar.
Comment: @isaque qual é o seu objetivo com isso?
Answer: Você sempre pode enviar blocos de script junto HTML do seu e-mail, o problema é que ele será removido no servidor ou não será executado. A grande maioria dos clientes de e-mail vão remover ou desabilitar a execução de scripts por questões de segurança, independente se o seu código é malicioso ou não.
Antigamente, início dos anos 2000, isso ainda era possível. Inclusive alguns clientes como o Outlook e Exchange executavam até VBScript e isso era bem arriscado no ambiente windows.
Porém, dependendo do que você espera e acha que precisa do JavaScript para alcançar, pode ser realizado de outras formas. Como por exemplo a confirmação de leitura, que pode ser feita incluindo um parâmetro na url de carregamento de uma imagem e monitorar isso no log do servidor (desde que o usuário habilite e aceite exibir as imagens).

Enviar JavaScript por email


iTunes Connect In App Purchase free trial duration gone?

Question: One month ago, I can choose free trial days(3,7days...) for In App Purchase in iTunes Connect, however, I couldn't find it anymore. Do I miss something or does Apple change it silently?
Comment: It has now moved under "Introductory Pricing"; You now have more flexible options beyond a free trial.
Comment: @Paulw11Thank you for your guide, it is there!
Comment: UPDATE: Sorry, you are correct, it's under introductory pricing, it was just very misleading that you have to specify a start/end date. Please disregard this: (I don't think it's the same. Free trial means that a user can cancel in a given period since his purchase. Introductory pricing means that before  a certain date, we give a discount. Am I mistaken?)
Answer: Please look for it under Introductory Pricing instead, as Paulw11 observes.


Interval between next coming date

Question: I have a table structure as below, Now i want to calculate the interval between next coming date from second column
TABLE STRUCTURE
Calendar    |NEXT DAY

15-07-1997   15-07-1997
16-07-1997
17-07-1997
18-07-1997   18-07-1997
19-07-1997
20-07-1997
21-07-1997
22-07-1997
23-07-1997
24-07-1997
25-07-1997
26-07-1997    26-07-1997

EXPECTED RESULT
Calendar   |NEXT DAY    |DIFFDATE|

15-07-1997   15-07-1997    0
16-07-199                  2
17-07-1997                 1
18-07-1997   18-07-1997    0
19-07-1997                 7
20-07-1997                 6
21-07-1997                 5
22-07-1997                 4
23-07-1997                 3
24-07-1997                 2
25-07-1997                 1
26-07-1997    26-07-1997   0

Answer: You can use lead(ignore nulls):
select t.*,
       (coalesce(next_day,
                 lead(next_day ignore nulls) over (order by calendar)
                ) - calendar
       ) as diffdate
from t;

Interval between next coming date


Apache Tomcat and IIS on Win Server 2008

Question: We have Apache Tomcat running on Windows Server 2008. Is there a problem to install IIS on the same machine?
Answer: You will need to either bind them to different IP addresses or different ports.
If I remember correctly, Tomcat's default port is 8080? If it's still running on 8080 then they will live side by side quite nicely. Otherwise, you will need to add a 2nd IP address to your Windows installation and bind Tomcat to one and IIS to the other.
Answer: This should not be a problem.
There is a module for IIS that will allow you to serve up tomcat through IIS. This way you can use port 80 or 443 for everything.
http://tomcat.apache.org/connectors-doc/reference/iis.html
There is a slight security risk whenever you host multiple applications on the same server in that a security hole with either application could allow both to be compromised by an attacker.


How can I solve a problem with click on item in horizontal RecyclerView?

Question: I have a horizontal recycler view. There are some buttons. I will provide my code below. So the problem is that when I click on a button, does not happen anything. It just thinks that I did not click to it. I have another recycler view, but vertical and the code is pretty similar, but the second one works. I am traying to find a mistake for ages. I really hope you can help me. Thank you.
in my main:
  adapter1 = new RecyclerViewAdapterContinentsList(this, idList,continentList);
            recyclerViewForContinents.setAdapter(adapter1);
            adapter1.setClickListener(new RecyclerViewAdapterContinentsList.ItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Toast.makeText(getApplicationContext(),"name",Toast.LENGTH_SHORT).show();

                }
            });

recyclerView class:
public class RecyclerViewAdapterContinentsList extends RecyclerView.Adapter<RecyclerViewAdapterContinentsList.ViewHolder>{
    private List<String> mId;
    private List<String> mName;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;
    Context context;

    RecyclerViewAdapterContinentsList(Context context, List<String> id, List<String> name) {
        this.mInflater = LayoutInflater.from(context);
        this.mId = id;
        this.mName = name;
        this.context = context;
    }

    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.activity_recycler_view_adapter_countinent_list, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder,final int position) {
        String id = mId.get(position);
        String name = mName.get(position);
        holder.continentBtn.setText(name);
    }

    // total number of rows
    @Override
    public int getItemCount() {
        return mName.size();
    }

    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        Button continentBtn;

        ViewHolder(View itemView) {
            super(itemView);
            continentBtn = itemView.findViewById(R.id.continentBtn);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) {
                Toast.makeText(context,"name",Toast.LENGTH_SHORT).show();
                mClickListener.onItemClick(view, getAdapterPosition());}
        }
    }

    // convenience method for getting data at click position
    String getItem(int id) {
        return mId.get(id);
    }

    void setClickListener(RecyclerViewAdapterContinentsList.ItemClickListener itemClickListener) {
        Toast.makeText(context,"name",Toast.LENGTH_SHORT).show();
        this.mClickListener = itemClickListener;
    }

    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

Answer: Change your ViewHolder code to attach the OnClickListener to the button and not the itemView.
ViewHolder(View itemView)
{
    super(itemView);
    continentBtn = itemView.findViewById(R.id.continentBtn);
    continentBtn.setOnClickListener(this);  // <-- button not itemView
}

In your ViewHolder, itemView is the root viewGroup of your layout R.layout.activity_recycler_view_adapter_countinent_list, a RecyclerView can listen to click events on the entire row using setOnItemClickListener.
Comment: Omg, it was so simple. Thanks a lot. Can you please say what means itemView in this siruation?
Answer: It is Easy ,
First you give id in your button view Than in  your Adapter in onBindViewHolder
set listner in view and perform any event in listner.
 @Override
    public void onBindViewHolder(@NonNull final recycler_item_ads.ViewHolder holder, final int position) {
        holder.installnow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                   //here print toast
                }

            }
        });

holfer.install now is my button in layout file


Online Music Degrees -- Free or not: Are they worth it?

Question: Lately I have come across many online music degrees, certificates, and even online BA and MA programmes! I will list some examples below:

Berklee's Introduction to Music Theory (Certificate).
https://www.edx.org/course/introduction-music-theory-berkleex-oharm100x-3
The University of Edinburgh's Fundamentals of Music Theory
(Certificate). https://www.coursera.org/learn/edinburgh-music-theory
Berklee's Music Composition for Film, TV, and Games (Bachelor's
degree).
https://online.berklee.edu/music-degrees/music-composition-for-film-tv-and-games

The tuition fees for the full online BA/MA programmes are simply out of my budget. They are simply five times more expensive than pursuing an on-campus Music BA in my city.
What is the value of Coursera/edX certificates? i.e. Let's say someone receives many of those online 'certificates' and has a very good understanding of music, theory, composition, etc. on the same level of an MA graduate, can he then enter a PhD in music?
Comment: I have removed the part of your question asking for free degrees. That is off topic here. The rest of your question is on topic.
Comment: This is an issue in many fields: if one has certain competences, but not documentation to "prove" it, then what? (Certificates will not successfully certify that one knows as much as a Bachelor's or Master's holder...)
Answer: The Berklee Introduction course says "Length, 6 weeks, effort, 5 hours per week". Do you really think 30 hours study is enough to "enter a PhD in music?" There's nothing wrong with paying for a certificate if having the certificate makes you feel good, and the course is probably fine (Berklee certainly has a good reputation) - but this is a very basic introduction to the subject, not the equivalent of a BA in music.
Comparing it with UK music exams like ABRSM, it doesn't look equivalent even to ABRSM Grade 5 which is about the same academic level as the UK school GCSE exams intended for 16-year olds, and you would take two more years of school courses, after that, and pass another exam, to qualify to start a BA music degree at university.
The Edinburgh course looks to be at a similar level - the web site clearly says "Level: Beginner". For example the first 3 weeks of the 5 are about "how to read basic music notation" - so more than half the course is the musical equivalent of "learning to read English in elementary school".
The Berklee "Music composition for Film, etc" is at a higher level, but read the first sentence of the Overview: "Gain the practical skills to compose, arrange, and orchestrate effective dramatic music for visual media, including film, television, and interactive media." This is a practical course, not an academic one to prepare you for an MA or PhD. Also, note that the admission requirements include submitting two original compositions in sheet music form, plus a video demo of your performing ability.
If you read the all the comments, you find this difference between the Berklee college courses and the online version:

While both degrees are from Berklee and share the same accreditation
  from the New England Association of Schools and Colleges (NEASC), the
  Bachelor's of Music (BM) program has private lesson requirements,
  ensemble/instrument lab requirements, audition requirements, and also
  a different set of core music requirements. Otherwise, the BM and
  Bachelor of Professional Studies (BPS) programs are the same. The
  career opportunities for both programs are very similar. However, if
  you are planning to later pursue graduate and/or doctoral studies,
  some of these programs require that students have a BM from undergrad.
Comment: You must have completely misunderstood me. I did **NOT** say 'get one of those certificates and then apply for a PhD'. I said what if someone has **many** of those online certificates, in music theory, composition, etc. and has equally as much knowledge as a Master's degree student.
Comment: Ya know, the first part of this answer is pretty condescending
Comment: @aleph I have just removed that first sentence. As per Kolob's comment it just detracts from your post.
Answer: I think these online courses just scratch the surface.  I have done alot my self but all it does is adding a little  to what you already know or just introducing  you to them as it were,  I think it makes more sense  to have one study properly in the institutions. In simple words I think the wax courses are certificate courses not degrees so can not be compare with BA or MA


Proving probability theorem $A$ subset of $B$, then $P(A) \leq P(B)$

Question: I'm trying to understand the proof for:
If $A \subset B$, then $P(A) \le P(B)$.
I have two versions of the proof and could use help understanding the last step.
FIRST PROOF VERSION:
$P(B) = P(A \cap B) + P(B - A)$ : by $P(B-A) = P(B) - P(B \cap A)$
$P(B) = P(A) + P(B-A)$ : by $A = A \cap B$
$P(B) \ge P(A)$ : by Axiom $P(A) \ge 0, P(B-A) \ge 0$
my question how is the last step arrived at and $P(B - A)$ dropped.
SECOND PROOF VERSION:
Similarly, here is another proof from Casella and Berger.  Where does the $0$ come from?  Can I rearrange to inequality to $P(A) \le P(B \cap A^c) = P(B)$?
Thanks
Comment: In your "first proof" I think you meant to say $P(B-A) \ge 0$ by the probability measure properties, not $P(A) \ge 0$.
Comment: @hardmath I think you're right.  I mention it now.  If thats the case, I'm still confused on how the inequality sign is established.
Answer: The first axiom of probability states that events always have nonnegative probability.

$P(A) + P(B-A) \ge P(A)$ comes from $P(B-A) \ge 0$.
$P(B \cap A^c) \ge 0$ is again another direct application of the axiom.
Comment: How are you arriving at or is it a mistake: $P(A) + P(B-A) \ge P(A)$.  Confused by the two $P(A)$ terms.
Comment: Clearly $P(A)=P(A)$ and by definition $P(B\smallsetminus A)\geq 0$.  Therefore $P(A)+P(B\smallsetminus A)\geq P(A)+0$.
Comment: How are you arriving at two $P(A)$ terms?  There is only a single one in both proofs.  The other is $P(B)$.
Comment: @Nick $P(B) = P(A) + P(B - A) \ge P(A) + 0 = P(A)$
Answer: With manipulation both the proofs arrive at this form:

If $P(B \cap A^C) \ge 0$ (by the Axiom $P(A) \ge 0$) then the RHS of the equality implies that $P(B) \ge P(A)$ must be satisfied to satisfy the LHS.  For instance $P(B)=1, P(A)=0$ satisfies, but $P(B)=0, P(A)=1$ does not satisfy because the RHS will be negative.


How to maintain Timezone

Question: My client is in india and server in USA . If user submit his post from india it get stored in USA server so when i display post submit time to user it is as per USA time . I want to show it as per clients timezone
Comment: js dates don't have a timezone, they are just numbers, so you should be able to simply reformat them.
Comment: See if this helps you. http://stackoverflow.com/questions/41264307/how-to-handle-date-between-india-time-on-client-side-and-server-date-in-us-time/41265842#41265842
Answer: The simplest way to handle timezones is to work with Epoch time behind the scenes, and translate it to the user's preferred timezone on render (or with client-side code).
Epoch time is the number of seconds since it became 1 January 1970 in London. For example, right now the time is 1483130714. This means we've got one simple number, that can be effortlessly compared and sorted, to represent precise moments without needing to care about dates, timezones, locales and their frustrating details. Virtually all languages in popular use have the ability to parse these numbers into their own timestamp values. In JavaScript, you can do this with new Date(1483130714). You'll get a date object and you can then present that however you like (eg with toLocaleString).
If you don't use Epoch time, you'd want to use UTC, the next-best thing. The important thing is to store in a consistent universally-understood format and then translate it to the user's preferred form as needed.
Answer: You need to store date in UTC and then convert it as per browser culture and timezone. So store all dates in UTC and depending on browser culture you can add offset, this could be tricky if user sets wrong culture and time.

How to maintain Timezone


WmiPrvSE.exe using lots of RAM

Question: I've got a server running Windows Web Server 2008 SP1 (Version 6, Build 60001, SP 1).
Looking in task manager I've got an instance of WmiPrvSE.exe running under the SYSTEM account using more than 400MB of RAM in its Working Set.
How can I find out what this is and why its using so much RAM?
Answer: It appears that this is the HP Network monitor.

WmiPrvSE.exe using lots of RAM


Dynamic SQL not Capturing all Columns

Question: I am trying to capture a set of columns, but the set can change depending on the data in question (it changes every month). Because of this, I am working on a way to capture the distinct values in the Service column, and put the column names separated by commas into a variable to call later. Here is the code (parsed down to only what is important).
DECLARE @cols AS NVARCHAR(MAX);

SELECT @cols = ISNULL(@cols + ',','') + QUOTENAME([Service])
FROM(
    SELECT DISTINCT Billing_Table.[Service]
    FROM Billing_Table
    ) AS Services;

The issue is that when I run
SELECT DISTINCT Billing_Table.[Service]
FROM Billing_Table

by itself, I get all of the distinct services listed (which is good, it's what I am expecting). But the variable @cols does not contain all of the same columns, which is not good.
Any reason why this is? What can I modify to fix this?
Answer: The reason your code did not work is because you are using the variable @cols recursively. It will not work like that with SQL. (To the best of my knowledge, recursion in T-SQL must be done through CTE).
Try this
    SELECT @cols = STUFF((
        SELECT DISTINCT CONCAT(',',[Service]) FROM Billing_table
        FOR XML PATH(''),type).value('.','NVARCHAR(MAX)'),1,1,'')

Test:
DECLARE @tmp TABLE (
    ID INT
);

DECLARE @cols NVARCHAR(MAX);

INSERT INTO @tmp (ID)
VALUES
(1), (2), (3);

SELECT @cols = STUFF((
    SELECT DISTINCT CONCAT(',',ID) FROM @tmp
    FOR XML PATH(''),type).value('.','NVARCHAR(MAX)'),1,1,'')

SELECT @cols;

Comment: I saw the edits, and it works decent in my code (just tweaking a little bit for it to work properly and changing for other cases with similar data)
Comment: @PartyHatPanda try again. I have an extra table name in there.

Dynamic SQL not Capturing all Columns


Postfix forward to port another than 25

Question: I have server with postfix installed. It is configured so that when system sends mail to root, it is forwarded to email@example.com It is configured in /etc/aliases like this:
postmaster: root
root: firstname.lastname@example.com

Now it stopped sending any emails to firstname.lastname@example.com because my ISP blocked port 25. How to configure postfix to send this emails to port 587?
My system is ubuntu 9.10, if it matters.
Thanks!
Answer: You need to create an entry in the Postfix transport table - http://www.postfix.org/transport.5.html has full details, and even an example that almost does what you want:
In the case of delivery via SMTP, one  may  specify  host-
       name:service instead of just a host:

            example.com      smtp:bar.example:2025

       This directs mail for email@example.com to host bar.example
       port 2025. Instead of a numerical port a symbolic name may
       be used. Specify [] around the hostname if MX lookups must
       be disabled.

You'll have to configure your main.cf to use the transport map as well - see the DATABASE_README linkd at the bottom of that page for more.
Comment: Although, as Womble says, a better solution is to get a proper ISP, one that actually provides an Internet service, instead of just something closely resembling internet service.

FWIW, http://www.marksanborn.net/linux/send-mail-postfix-through-gmails-smtp-on-a-ubuntu-lts-server/ has an apparently complete (although I've not tested it) guide to setting up the neccessary authentication.
Answer: In general, you can forward to a non-standard port on another mail server with a transport map (see transport(5) and the transport_maps option in postconf(5)).  However, the submission port (587) isn't designed to be used without authentication, so you'll also want to look at the smtp_sasl_* options in postconf(5).  However, that's a lot of hassle to go through when the best answer is to tell your ISP to remove the port 25 block on your connection.  If they're too stupid or intransigent to permit that on a per-customer basis, find a new ISP.

Postfix forward to port another than 25


Counterexample to If f is one-to-one on A, then f'(x) $\neq$ 0 on A

Question: I'm having a hard time thinking of a counter example to
If $f$ is one-to-one and differentiable, then $f^\prime(x) \neq 0$ on A.
At first I was thinking of using a simple piece wise function but this wouldn't work because I still wouldn't have $f'(x) = 0$.
Would $\sin(x)$ where $A=(0,\pi/2)$ work?
Comment: Why not, it is just $A\subseteq \Bbb R$.
Comment: $x^3$ is a good example for $A=\mathbb R$.
Comment: An element of $S_3$ is also a one-to-one function from $A=\{1,2,3\}$ to itself, but makes no sense. Probably you have some assumption of $f$.
Comment: Ahh yes, the problem begins with let $f$ be differentiable.
Comment: Yes. Hence I have the tag "real-analysis". In the future should I include that in the problem as well?
Answer: No, your example never has a zero derivative. What about $f(x)=x^3$, $A=\mathbb{R}$?
Comment: @financial_physician Well there is no "next" value. It's flat, but only at one point, which has no width.
Comment: @amWhy I added the stipulation that $A=\mathbb R$.
Comment: Ahhh. That's really interesting. So with a saddle point you can still have a surjective function? I guess I'm used to thinking that f'(x)=0 would mean the next value will be the same but clearly this is not the case here. Wild.
Answer: In your example, if you set $f(x)=sin(x), \quad x \in (0, \frac{π}{2}) $ then it is not possible to prove this, as $ f'(x)=cos(x)$ and $f'(x)=0 \Rightarrow x=π/2 $ but your domain for $D_{f'}=(0, \frac{π}{2})$. The correct counter example, as many above me have mentioned before me, is $f(x)=x^3, \forall x \in R$, as $f'(x) \geq 0, \forall x\in R$. If the inequality for $f'$ contains "=" but it only equals zero on specific points of $D_f$ then still, $f:\uparrow \Rightarrow f:1-1$, and that's where the counterexample is proving what you want.
The opposite of that is not valid, however, and an easy way to prove it is by using Rolle's Theorum (but you probably already know this)


Precise semantic of annotated associations with { bag } and multiplicity bound constraints

Question: Suppose I have   A ---r1 {bag} [1..2]--> B in a UML class diagram (that is, r1 is an association from A to B and is annotated with {bag} and multiplicity [1..2].
My Question: if a:A is an instance of A, is the following collection valid?

a.r1={(b1,1),(b1,2),(b2,1)}   //collection contains two copies of b1 and one b2

In other words, multiplicity bounds (i.e., [1..2]) apply to the association when it is interpreted purely as r1:A --> B, or it applies to r1: A --> Bag(B)? In the former interpretation, the above collection is valid, since r1 contains at most two instances of B, but in the latter it is not, since r1 contains three elements of Bag(B)! which interpretation is correct?
Multiplicity constraints in UML are explained in Chapter 7.5.3 of UML document as I am referred to in this question.
p.s.1: A similar question arises when we substitute {bag} with {seq}.
p.s.2: I added haskell tag to get comment from large haskell community here as @xmojmr suggested. Thanks to @peter that nicely draw the pictures in his answer.
Comment: in my eyes you've already compromised the Stack Overflow community and your questions is far from comprehensible practical coding problem. Can you simplify/translate it for non-haskell guys like me.. `UML` talks pictures. Can you translate your `A ---r1 {bag} [1..2]--> B` code into `UML` picture? At the other side of `UML` is some `code`, imagine `C#` code. Can you translate your `a.r1={(b1,1),(b1,2),(b2,1)}` into `C#` code example? It seems that you have doubt which one of 2 possible interpretations is correct. Can you show the 2 cases side by side clearly? (picture+code)*2?
Comment: I think @peter kindly did what you asked. Now the problem is that if I want to implement the picture in his answer, and I have a collection of type bag, putting in this collection two b1 and one b2, violates the constraints or not. There is two interpretation as I wrote in the question: 1) it violates because collection contains three elements. 2) does not violate because there is only two references to B instances in the collection.
Comment: Your problem may be warmly received at [cstheory.stackexchange.com](http://cstheory.stackexchange.com) or maybe deciphered here if you add the [haskell](http://stackoverflow.com/questions/tagged/haskell) tag as smart-guy attention attractor
Comment: Thanks for your suggestion, but can I add tags here just for attracting  another communities attention when the question is not directly related. It would be good, but I am worried that I would compromise the stackoverflow rules by doing so. wouldn't I?
Answer: As stated in specs, Bag is unordered, nonunique collection.
However this describes the relation between the elements you are pointing to.
So your example can be expressed in either way:

This means that A has reference to one to two B instances, and those references are stored in a Bag (or any nonunique, unsorted collection; but that is implementation detail).
To answer your question: no, because the Bag contains three instances of B, whilst the allowed maximum is two B's.
Comment: Well you chose Bag, which is nonunique, that means that even the same element twice will count as two distinct elements; so A still has three distinct references. If you want not to distinguish the same B's then use Set instead (unique, onordered). I drew those in http://www.umlet.com/ which is a great tool for quick sketching.
Comment: You wrote my class model "means that A has reference to one to two B instances". In my provided instance, A has references to exactly two distinct B's, but three bag elements. In fact, the bag itself contains two instances of B (i.e., b1,b2) such that whose three elements are built out of these two instances. Actually, confusion still stays on the board. p.s. BTW, Is there any handy tool to draws quickly the useful picture you included?


flash builder 4.7 AIR app how to get iPhone time and date?

Question: is there anyway to access time on the Iphone(or other ios devices) from AIR app made with flash builder?
Answer: You can access time like on every other device. Use this code:
<code>var currentTime:Date = new Date();
trace(currentTime);
</code>
You need to call new Date() anytime you want the actual time.
See documentation for details.
Works with the iOS-Simulator and should work on the device as well.
Comment: ok, thanks! Is there a list of all device related commands for air for ios?
Answer: You should use the Date() class.
(Maybe I misunderstood your question)


Find the domain and range of the function $f(x) =\sqrt{\csc(3x)}$

Question:
Find the domain of and range of the function f(x) ,and express your
  answer in interval form $f(x)=\sqrt{\csc(3x)}$

I got the domain, like how its restricted and $\sin(x)$ can't equal to zero. However, I'm stuck on the range part of the question. I'm not sure how to do it. I got 0 ≤ $\sqrt{csc(3x)}$ ≤ 1, which is wrong when I checked online graphing calculator
This is a review question for University Calculus.
Comment: hint: $csc(3x)$ goes to infinity when $x$ approaches 0
Comment: Welcome to MSE. Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: you can make a plot of your function!
Comment: see here https://www.wolframalpha.com/input/?i=plot+sqrt(csc(3*x))+for+x%3D-2+to+2
Answer: Assuming the function is real-valued:
$f(x)=\sqrt{\csc(3x)}$
For the expression $\sqrt{a}$ to be defined, we need $a\ge0$. Thus, $\csc(3x)\ge0$.
Since $\csc(x)=\frac{1}{\sin(x)}$, we also need $\sin(3x)\ne0\Leftrightarrow3x\ne n\cdot\pi\Leftrightarrow x\ne n\cdot\frac{\pi}{3}, n\in\mathbb{Z}$
Now $\csc(3x)\ge0$ iff $\sin(3x)\ge0$
We know $\sin(x)\ge0$ iff $x\in\left[2n\pi;(2n+1)\pi\right], n\in\mathbb{Z}$
Then $\sin(3x)\ge0$ iff $x\in\left[\frac{2n}{3}\pi;\frac{2n+1}{3}\pi\right], n\in\mathbb{Z}$
Combining these two restrictions yields the Domain $D=\{x\in\mathbb{R}\colon \exists n\in\mathbb{Z}\left(x\in\left(\frac{2n}{3}\pi;\frac{2n+1}{3}\pi\right)\right)\}$
As seen above, for this domain the expression $\sin(3x)$ takes on the values in the interval $(0;1]$
Then $\csc(3x)=\frac{1}{\sin(3x)}$ takes on values in the interval $[1;+\infty)$
Finally, this means that $\sqrt{\csc(3x)}$ will take on values in the interval $[1;+\infty)$, meaning that the range is $R=\{x\in\mathbb{R}\colon x\ge1\}$
Note: Knowing the sines periodic behavior we can see that $f(x)$ behaves the same in any interval $\left(\frac{2n}{3}\pi;\frac{2n+1}{3}\pi\right)$ for any $n\in\mathbb{Z}$ and will take on all the values in its range in any of these intervals.
Answer: To determine the domain of $\sqrt{\csc(3x)}$, you have to first look at where $\sin(3x) = 0$ and $\csc(3x) < 0$. Notice that this is determined in the following manner:
$$\sin(3x) =0 \implies 3x = \sin^{-1}(0) \implies 3x = k\pi, k \in \mathbb{Z}, \implies x = \frac{k\pi}{3}, k \in \mathbb{Z}.$$ We also note that $\csc(3x) < 0$ when $\sin(3x) < 0$, so we see that $$\sin(3x) < 0 \implies \pi < 3x< 2\pi \implies \frac{\pi}{3} + 2k\pi < x < \frac{2\pi}{3} + 2k\pi, k \in \mathbb{Z}.$$ Therefore the domain of $\sqrt{\csc(3x)}$ is the set of all $x \in \mathbb{R}$ such that $x \neq \frac{k\pi}{3}$ and $x \not \in \left( \frac{\pi}{3} + 2k\pi, \frac{2\pi}{3} + 2k\pi \right)$.
To determine the range of $\sqrt{\csc(3x)}$ note that $$\sqrt{\csc(3x)} = \frac{1}{\sqrt{\sin(3x)}}. $$ Since $\sin(3x) \to 0$ as $x \to 0$, the function is clearly unbounded (above).
It is also worth noting that the range of the function $f(g(x))$ is the range of $f$ when restricted to the domain of $g(x)$ such that the function is well defined. Notice that $\sqrt{\csc(3x)}$ is the composite of $\sin(3x)$ and $\frac{1}{\sqrt{x}}$. Therefore, the range of $\sqrt{\csc(3x)}$ is the range of $\frac{1}{\sqrt{x}}$ when restricted to the domain determined above. It so follows that the range of $\sqrt{\csc(3x)}$ is $[1, \infty)$, since the largest value of $\sin(3x)$ on the restricted domain is $1$. Hence the minimum of $\sqrt{\csc(3x)}$ is $\sqrt{1}=1$.
Hope this helps.
I disagree with the comments made by Dr. Sonnhard Graubner. One should not be forced to rely on graphical techniques. While the student should be able to graph this type of functions, a purely analytic solutions should be able to be provided.


MsDeploy is returning 403 forbidden

Question: We had a Web Application working on an intranet and I'm trying to publish it to the internet using Visual Studio 2010. The destination server is running iis7 and the Web Management Service is running.
On Visual Studio 2010 my service URL is:

https://xxx.xxx.xxx.xxx:8172/MsDeploy.axd

And site/application is:

Default Web Site/WebApp

Marking as IIS App on destination and Allow untrusted certificate is checked and i'm using an administration account.
Visual Studio return the following error:

Start Web Deploy Publish the Application/package to
  https://xxx.xxx.xxx.xxx:8172/MsDeploy.axd?site=Default%20Web%20Site ...
  C:\Program
  Files\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets(3588,5):
  Error : Web deployment task failed.(Remote agent (URL
  https://xxx.xxx.xxx.xxx:8172/MsDeploy.axd?site=Default Web Site) could
  not be contacted.  Make sure the remote agent service is installed and
  started on the target computer.)
Remote agent (URL
  https://xxx.xxx.xxx.xxx:8172/MsDeploy.axd?site=Default Web Site) could
  not be contacted.  Make sure the remote agent service is installed and
  started on the target computer. An unsupported response was received.
  The response header 'MSDeploy.Response' was '' but 'v1' was expected.
  The remote server returned an error: (403) Forbidden.

Any ideas how to publish it without a valid SSL certificate?
Answer: If you go into IIS,
Click on the server node in the "Connections" list,
Double click "Management Service" then you are taken to a screen which has an "Enable remote connections" check box.
This checkbox (and the rest of the sreen) maybe greyed out because the service is running.  Just click the "Stop" link in the Actions pane, then check the "Enable remote connections" box and any other settings you want to change here, then click 'Apply' and 'Start' on the Actions pane again.

That should hopefully let you connect, with proper credentials, to the service from a remote machine. (If the correct ports and stuff are opened and all that jazz.)

I think this helps your situation.  At least you won't get 403's but you may have some other MsDeploy error.
Comment: The next error will be **Not Found** . To fix it go *Add and remove programs* find your *Web Deploy* click *Change* then install all features.
Comment: What made me laugh is that after spending an hour or so following all of the MS doc Web Deploy installation articles and Troubleshooting Web Deploy articles word-for-word, none of them mentioned that simple checkbox _"Enable Remote Connections"_ and you **STILL** have to do that _Add and remove programs_ fix. smh. Fail.
Comment: I had the same problem. I believe my config was corrupt due to a hard reboot during a config change. I took these steps, but didn't change anything. (Changed auth to Windows only, Apply, and then back to Windows + ISS Mgr). That fixed it for me.
Comment: Other resolutions include uninstalling Web Deploy 3.6 and installing 3.5. Worked for me:
http://stackoverflow.com/questions/32004797/error-the-configuration-section-system-webserver-management-delegation-canno
Comment: I had the same error on Window Server 2012 R2 and Web Deploy 3.6. The problem was webdeploy wasn't completely installed at first it asked to restart the machine. So when I restarted the server and launched [WPI](http://www.microsoft.com/web/downloads/platform.aspx) again the installation continued and everything worked. But after restart the WPI won't start so I had to launch it manually. Hope this will help some seeking similar problems.
Comment: @CihanYakar You earned a cookie from me. Thank you.
Comment: @CihanYakar Are you a wizard?!
Comment: @KaseySpeakman Thanks. Something about the way the service is installed and/or IIS manager for some reason requires this. Maybe the configuration doesn't get reset unless changes are detected. Finally got this working after flipping auth back and forth and restarting the service like you suggested. (Just restarting the service alone didn't work.)
Comment: I had the same problem but I already had the checkbox "Enable remote connections" checked. So, I solved just restarting "Management Service".
Comment: In my IIS there isn't "Connections" list but "Management Service"
Comment: Please take a look at Lee Gunn's answer below, saved me a lot of time: https://stackoverflow.com/a/48283631/10307728
Comment: What a pain in the a** of a program. Should have stayed with the file copy deployment option, but once you've started the process you don't really want to give up.
Answer: Web Deploy can give you a whole bunch of errors if not setup correctly. Do yourself a favour and use the Web Platform Installer (https://www.microsoft.com/web/downloads/platform.aspx). You should uninstall WebDeploy first if you've already tried to install it. From the WebPI select: "Web Deploy 3.6 for Hosting Servers".
Comment: Had the same problems 6 months later. Just read my own answer and installed "Web Deploy 3.6 for Hosting Servers". Everything works first time :)
Comment: This worked for me, I had installed "Web Deploy 3.6" From **Web Platform Installer**, the key was uninstalling that and installing "Web Deploy 3.6 for Hosting Servers" instead. Worked right away, thanks!
Answer: I had the same problem. Talk about jumping through hoops...
The solution requires set up of user and deployment permissions etc.

after getting the error 'NOT FOUND' as predicted by Cihan Yakar
above, I had to change webdeploy (for me it required re-download search for 'WebDeploy_x64_en-US.msi')
enabling all options.
got a new error, always good, ERROR_USER_NOT_AUTHORIZED_FOR_CONTENTPATH. for this I looked at the web deploy errors (see below for link).

Diagnosis - A non-administrative user attempted to perform an
  operation with a Web Deploy provider for which the user is not
  currently authorized. Resolution - Web Deploy 2.0 setup, by default,
  creates Management Service Delegation Rules which allow
  non-administrators to perform operations with this provider. It is
  possible that a delegation rule required for this provider has not
  been setup correctly. Workaround: From the Programs Control Panel, run
  Repair on Web Deploy 2.0. Alternatively, create the delegation rule
  manually.

It turns out I had to create it manually from 'Configure the Web Deployment Handler'(see below for link), using this guide to 'Configure WMSVC and IIS Manager Permissions' and 'Create Delegation Rules for Web Deploy Users' sorted the problem.
notes:
Diagnosed using 'web deploy error codes' from:
http://www.iis.net/learn/publish/troubleshooting-web-deploy/web-deploy-error-codes
and eventually configured using processes from 'Configure the Web Deployment Handler':
http://www.iis.net/learn/publish/using-web-deploy/configure-the-web-deployment-handler
Comment: All the sequence of problems solved in one post, this helped. Also there is another work  around, i have uninstalled web deploy and re installed along with IIS: recommended configuration from Web Platform Installer.
Comment: I'm stuck on your #2 ..and i can't for the life of me figure it out. you don't happen to remember any "gotcha's" do you? i've been working on resolving this error for about 6 hours now... and i used your two links extensively during it. i just don't know what else i may be missing.
Answer: In my case, after Enable remote connections checkbox, I need to reinstall Web Deploy to make it work.

MsDeploy is returning 403 forbidden


Creating a tuple without using tuple function

Question: I have to create a list of tuples without using the tuple() function. The input is a list of lists where each list contains a profile ID and the calendar date on which the user went of a date. The output is a list of tuples showing the profile ID and the number of dates the user went on.
The final output should be a list of tuples, but my code outputs each element individually.
Below is the code I wrote to try to convert the list elements to tuples.
for stuff in datingTrack:
        for smallerStuff in stuff:
            tuplesList = (smallerStuff)
            datingTrack2.append(tuplesList)

input: [["B111", "10/2/2022"], ["B222", "9/25/2022"], ["B333", "8/1/2022"], ["B222", "9/2/2022"]]

my output: ['B111', 1, 'B222', 2, 'B333', 1]

Expected output: [('B111', 1,) ('B222', 2), ('B333', 1)]

Comment: `tuplesList = (smallerStuff)` is *exactly equivalent* to `tuplesList = smallerStuff`, note, it isn't the *parentheses* that make the tuple, it is the commas! (except for the special case of an empty tuple, which is `()`)
Comment: BTW, `tuple` is not a function, but a [class](https://docs.python.org/3.8/library/functions.html#func-tuple) that, as with many classes from the Standard Library, is normally used _as a function_ just because there's a simple synaxis to create tuples without explicitly calling it.
Answer: You can get the expected output with collections.Counter:
from collections import Counter

lst = [
    ["B111", "10/2/2022"],
    ["B222", "9/25/2022"],
    ["B333", "8/1/2022"],
    ["B222", "9/2/2022"],
]

c = Counter(v for v, _ in lst)
print(list(c.items()))

Prints:
[('B111', 1), ('B222', 2), ('B333', 1)]

EDIT: Solution without Counter:
lst = [
    ["B111", "10/2/2022"],
    ["B222", "9/25/2022"],
    ["B333", "8/1/2022"],
    ["B222", "9/2/2022"],
]

out = {}
for v, _ in lst:
    out[v] = out.get(v, 0) + 1

out = list(out.items())
print(out)

Prints:
[('B111', 1), ('B222', 2), ('B333', 1)]

Comment: if they can't use `tuple` then why would they b e able to use `collections.Counter`?
Comment: @juanpa.arrivillaga Well, OP wanted solution without using `tuple()`, he/she got it ;) But I get your point...
Comment: Ya I can't use counter either :,( it has to be done using a loop somehow
Answer: This one almost does what you want:
datingTrack = [["B111", "10/2/2022"], ["B222", "9/25/2022"], ["B333", "8/1/2022"], ["B222", "9/2/2022"]]

dt2 = [(ID,len ([i for [i,j] in datingTrack if i==ID])) for (ID,date) in datingTrack]

Almost, because there will be multiple identical entries.
But that can be solved with:
dt2 = list(set(dt2))

Answer: EDIT: This does not answer the question. Please refer to the answers above

If you're forced to not use the tuple construtor, this will do it
my_input = [["B111", "10/2/2022"], ["B222", "9/25/2022"], ["B333", "8/1/2022"], ["B222", "9/2/2022"]]

my_output = [(*item,) for item in my_input]
# [('B111', '10/2/2022'), ('B222', '9/25/2022'), ('B333', '8/1/2022'), ('B222', '9/2/2022')]

Comment: But this doesn't show the number of occurrences of each ID...
Comment: If this is the answer then the question is the wrong one.


como deixar um embed com width e height fixo responsivo?

Question: Alguém sabe como deixar este embed responsivo, não consigo pois tras um width e um height fixo?

Comment: Por favor, faça uma pergunta completa da forma que seja simples sua dúvida.
Answer: Você pode usar embed-responsive se estiver usando bootstrap ou esse css:
.videoWrapper {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
  padding-top: 25px;
  height: 0;
}

.videoWrapper object,
.videoWrapper embed {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

Seguindo essa ideia você vai usar:

<embed ...>

Answer: poderia criar uma classe que iria conter o embed, e definir o valor que quer (altura e largura) depois iria colocar overflow:hidden, e no embed, colocaria centralizado na div pai.
sei que nao é a melhor forma, porque iria cortar parte do embed, mas tem outra forma que é alterar no elemento por estilo em linha (aquele <embed style="width: tal; height: tal;"> ), em linha porque é o que nao irá sofre alterações externas, pois é aplicado diretamente no local


Return JSON from Express app: Uncaught (in promise) SyntaxError: Unexpected end of input

Question: I need a pair of fresh eyes please.
I'm trying to get a simple Express app to return some json (it happens to be a Firebase token, but that's not relevant) every time a request is made to it.
This is my Express server code:
app.get('/validate', function (req, res) {
  var customToken = firebase.auth().createCustomToken(req.query.token);
  res.json({
    token: customToken
  });
});

app.listen(8000, function () {
  console.log('Listening on port 8000');
});

And this is the request from the client (listening on port 3000):
export function login() {
    return fetch('http://localhost:8000/validate?token=666', {
      method: 'GET',
      mode: 'no-cors',
      headers: new Headers({
          'Authorization': apiClient.headers.Authorization,
          'Content-Type': 'application/json'
        })
      })
      .then(response => console.log('RESPONSE: ', response.json()))
      .catch(response => console.error('ERROR: ', response));
  }

The Express app seems to be working fine because when I open http://localhost:8000/validate?token=666 in a browser I can see the json I need.
However, when I make the client request I get this error
Uncaught (in promise) SyntaxError: Unexpected end of input
and this is what the Response log looks like
RESPONSE:  Promise {[[PromiseStatus]]: "rejected", [[PromiseValue]]: SyntaxError: Unexpected end of input
    at SyntaxError (native)
    at eval (eval at <anonymous> (h…}__proto__: Promise[[PromiseStatus]]: "rejected"[[PromiseValue]]: SyntaxError: Unexpected end of input
    at SyntaxError (native)
    at eval (eval at <anonymous> (http://localhost:3000/main.js:1381:2), <anonymous>:78:42)message: "Unexpected end of input"stack: "SyntaxError: Unexpected end of input↵    at SyntaxError (native)↵    at eval (eval at <anonymous> (http://localhost:3000/main.js:1381:2), <anonymous>:78:42)"get stack: stack()set stack: stack()__proto__: Error
login.js?b88c:54

Any pointers to what I'm doing wrong would be appreciated.
Comment: try logging the raw response like `console.log(response)` and inspect
Comment: Not useful I'm afraid: `RESPONSE:  Response {type: "opaque", url: "", status: 0, ok: false, statusText: ""…} body: (...) bodyUsed: false headers: Headers null}`
Answer: Had a similar problem and after some researching I realized that the only reason { mode: 'no-cors' } exist is for opaque response that cannot be accessed directly. To access the response you'll need to cache it with Cache API and later on get it with a service worker.
I ended up solving that by adding the Access-Control-Allow-Origin: * header to my server side (make sure this setup is safe for you in production and that you are absolutely sure that you are the only one who are able to make request to your server) + removing the mode:'no-cors' option from the request.
Comment: I did solve it with something along the lines you suggest.
Comment: I haven't accepted your answer because I've solved my problem _before_ you answered. But I've added +1 to reward your effort nonetheless.
Answer: In case it helps anyone, I've solved my issue by adding
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

to the server side code.


Remote Desktop ActiveX control maximised

Question: In my application i am utilizing the Remote Desktop ActiveX control
How do i maximize the RDP session? I would like it to be full screen once connected.
Comment: Can you provide a bit code of how you have implemented the RDP ActiveX control so better to help with the best way to set the property?
Comment: http://msdn.microsoft.com/en-us/library/aa381340%28v=vs.85%29.aspx
Comment: @HansPassant I found that also but how do i use the property?
Answer: I'm not sure from your question if you're using this via the web or WinForms app but if it's from a WinForms application you can do the following.
First you need to subscribe to the OnConnected event
<code>  // Subscribe to the OnConnected Event in the constructor or via the form designer.
  this.axMsRdpClient91.OnConnected += new System.EventHandler(this.axMsRdpClient91_OnConnected);

private void btnFullscreen_Click( object sender, EventArgs e )
{
  if ( axMsRdpClient91.Connected == 0 )
  {

    axMsRdpClient91.UserName = "Username";
    axMsRdpClient91.Server = "address to server to connect to";
    // Connect to the server
    axMsRdpClient91.Connect();
  }

}
// When the the ActiveXControl raises the OnConnected event set the screen to full screen mode.
private void axMsRdpClient91_OnConnected( object sender, EventArgs e )
{
  ( (AxMSTSCLib.AxMsRdpClient9)sender ).FullScreen = true;
}
</code>


How can I know if a type of content is moderated?

Question: I'm trying to find out if a type of content (not a node) is being moderated. How can I determine it?
For example:
function MY_MODULE_form_node_type_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   $content_type = $form_state->getFormObject()->getEntity(); // $content_type is a Drupal\node\Entity\NodeType
}

I can't find a way to find out if this type of content is being moderated by some type of workflow.
Comment: You sure you are not mixing up terms? Content type is a bundle to be used for many nodes and a content type can't be moderated as far as I know. But nodes can. And they then are connected to a moderation state entity I think.
Answer: You should be able to get that from ModerationInformation:: shouldModerateEntitiesOfBundle(), via the content_moderation.moderation_information service:
$moderation_info = \Drupal::service('content_moderation.moderation_information');
$entity_type = \Drupal::entityTypeManager()->getDefinition('node');
if ($moderation_info->shouldModerateEntitiesOfBundle($entity_type, $content_type->id())) {
  // ...
}


How to read comma seperated value in xml using javascript

Question: How to read the csv in js from like these
and process the right answer to grade
note: the answers are included in the xml and are seperated by commas
<finalquiz>
<question>
<qnumber>1</qnumber>
<qtitle>what is 2+2 </qtitle>
4
6
<c>2</c>
<d>0</d>
</question>
<question>
<qnumber>2</qnumber>
<qtitle>what is 3+3 </qtitle>
4
6
<c>9</c>
<d>3</d>
<rightanswers>a,b</rightanswers>
</finalquiz>

Comment: Looks like you need an xml-parser
Comment: That is a weird CSV file. So read the text from the xml tag and split it on the comma https://stackoverflow.com/questions/5269856/how-to-split-comma-separated-string-using-javascript
Comment: But the problem is how to do i read rightanswers into js, i am able to read the question and options and even put radio buttons on it, but not able to process answers
Comment: i used it and i am able to read it as string, Thanks !! , should i use split and make a grade function ? Can you explain a bit on that?
Comment: If you can post the string you have as part of your question, it will be easier for us to suggest solutions.
Comment: var answer="";
  answer +=  xmldoc.getElementsByTagName("rightanswers")[0].childNodes[0].nodeValue;   // this is what i have to read right answer the string is : "a,b"
Answer: As has been discussed in the comments, you have already parsed the XML and have a string containing the values you need, separated by commas.  So the hard work is all done.  The solution at this point is very easy - just use "split" to separate the string on the commas.  Something like this:
var rightAnswersString = "a,b"; // Assume you have come up with something like this by parsing the XML
var rightAnswersArray = rightAnswersString.split (",");
for (let i=0; i<rightAnswersArray.length; i++) {
   console.log (rightAnswersArray[i]); // Replace console.log with whatever you need to do with each value
}


What is it called when you move chords a step up or down?

Question: What is the name or concept that explains or refers to when chords become other chords if you move them one step up or down? For example, B♭ Major becomes A Major once it's moved a step down, and vice versa (A major becomes B♭ Major when it's moved a step up).  Is this the same as key modulations as well?
Answer: The concept you refer to is called Transposition, which is moving one or more notes up or down by a given amount. You can transpose individual chords, or phrases, or entire pieces.
For example, if you have a piece in C major, and transpose it up a whole step, the resulting piece will be in D major. If the piece modulates partway through, for example, from C to G (up a fifth), then the transposed piece will modulate from D to A (also up a fifth).
Comment: thank you very much for your answer, also how could i incorporate transposition into a key modulation is it possible?
Comment: I already answered what happens when you transpose a piece that has a modulation.
Comment: thank you also is there anyway you can give more of an example of the modulations from one key to another, and part way modulations in more of a simpler form, im really new to the theory. much appreciated .
Comment: Modulation is not the same as transposition, and works entirely differently.  Transposition is playing an entire piece of music in a different key.  Modulation is moving from one key to another inside a piece of music.  Don't think of them as different aspects of the same thing.  The simplest way to modulate is to play a chord which is common to the key you are leaving and the key you want to go to, and follow it with more chords from the target key.  For example C F C G (common chord) D7 G, and now you can go on in G.  Or a (lower case=minor) E7 a F G7 C will move you from a to C.


PostBack remove os items selecionados DropDownList múltiplo

Question: Possuo um DropDownList (ddl1) múltiplo estático na minha página aspx. Ele possui 4 opções, na qual podem ser selecionadas de 0 à 4 opções.
Um outro DropDownList (ddl2) que também é estático no formulário possui o evento OnSelectedIndexChanged e quando este evento é disparado o dll1 perde as seleções múltiplas, mantendo apenas a primeira opção selecionada (ou nenhuma, caso o usuário não selecionar).

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Panel ID="PanelPesquisa" runat="server" CssClass="form-group">

    <asp:DropDownList ID="dpBuscaEtapasCapacitacao" runat="server"
CausesValidation="false" ValidationGroup="BuscarQuestao"
ClientIDMode="Static" CssClass="chosen-select form-control" data-
placeholder="Selecione as Etapas" multiple="multiple" TabIndex="4">
        <asp:ListItem Text="Nivelamento" Value="0"></asp:ListItem>
        <asp:ListItem Text="Capacitação EaD" Value="1"></asp:ListItem>
        <asp:ListItem Text="Capacitação Presencial" Value="2">
</asp:ListItem>
        <asp:ListItem Text="Atualização" Value="3"></asp:ListItem>
    </asp:DropDownList>

    <asp:DropDownList ID="dpBuscaPageSize" runat="server" CssClass="form-
control" AutoPostBack="true" CausesValidation="true"
OnSelectedIndexChanged="BuscaDados" ClientIDMode="Static">
        <asp:ListItem Text=""></asp:ListItem>
        <asp:ListItem Text="5"></asp:ListItem>
        <asp:ListItem Text="10"></asp:ListItem>
    </asp:DropDownList>

        </asp:Panel>

    </ContentTemplate>
</asp:UpdatePanel>

O evento apenas atualiza a grid na tela, sem interação com os ddl's.
O que devo fazer para manter os items do ddl1 selecionados após o eventos serem disparados? Lembrando que o ddl não é carregado dinamicamente, então não tem como eu "chamar a função no postback" pois não há função.
Code Behind:
protected override void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        CarregaDados();
}

private void CarregaDados(){
    var lst = consulta_no_banco(" - sql_query - ");

    GridPrincipal.PageSize = int.Parse(dpBuscaPageSize.SelectedItem.Text);
    GridPrincipal.DataSource = lst;
    GridPrincipal.DataBind();
}
/*
    Esta função é chamada em todos os eventos dos Controls de filtro da tela.
    Cada TextChanged e SelectedItemChanged do filtro é direcionado para cá, mas
    ainda não estou fazendo o filtro em sí.
*/
protected void BuscaDados(object sender, EventArgs e)
{
    CarregaDados();
}

Comment: Onde está o code behind?
Comment: O code behind está bem seco ainda. Ele só faz uma consulta no banco e joga numa GridView. A única parte que um dos ddls aparece no código é o seguinte:
`GridPrincipal.PageSize = int.Parse(dpBuscaPageSize.SelectedItem.Text)`

O PostBack não chama nada. O Carrega() é chamado apenas quando é !isPostBack, que por sua vez joga os dados na GridView e deu. Creio que não haja nenhuma relevância este caso. O change do ddl2 chama o Carrega() também.
Comment: mas tem o seu load e o evento que está disparando o postback...
Comment: Pronto. Não fiz os filtros ainda pois esse ddl não está se comportando como deveria, quando terminar a tela daí sim faço a parte funcional
Answer: Precisa utilizar o UpdatePanel? Não consegue trocar para um Panel?
Outra coisa que podes verificar é se a ViewState está habilitada
Comment: Pior que preciso, não dá pra tirar ele não. Verifiquei e a ViewState está habilitada na página inteira.
Answer: Resolvido
Ao invés de um DropDownList, utilizei um select. No codeBehind há poucas diferenças mas são necessários alguns tratamentos a mais.
Não entendi exatamente o motivo mas mantive todos os demais elementos (inclusive UpdatePanels) e troquei apenas este. Os items pararam de ser resetados!
<select id="dpModulosLicenciados" runat="server" class="chosen-select form-control" data-placeholder="Selecione os Módulos" multiple="true" tabindex="4"></select>

Vida que segue minha gente. O importante é que funciona


Show for prime numbers of the form $p=4n+1$,  $x=(2n)!$ solves the congruence $x^2\equiv-1 \pmod p$. $p$ is therefore not a gaussian prime.

Question: I need to show that for prime numbers of the form $p=4n+1$, $x=(2n)!$ solves the congruence $x^2 \equiv-1\pmod p$.
I then need to show this implies p isn't a gaussian prime.
I have started to solve this using Wilson's theorem that a number $z$ is prime iff $(z-1)!\equiv-1\pmod z$. Therefore the endpoint of my proof should be that $(p-1)!\equiv-1\pmod p$.
As $p$ is of the form $p=4n+1$, I only need to prove that $4n!$ is congruent to $-1$ modulo $p$.
Here is my working so far: Starting with the congruence $x^2 \equiv -1\pmod p$:
$$\eqalign{x^2 = -1\pmod p&\implies
 x^2 + 1 = kp
\implies (x-i)(x+i) = kp\cr
&\implies ((2n)!-i)((2n!)+i))=kp
\implies 4n!- 1 =kp\cr}$$
This is where I start to run out of any ideas that seem to get me anywhere.
Any tips would be greatly appreciated!
Comment: You have confused $(2n)!$ with $(2n!)$. Also the square of $(2n)!$ isn't $4n!$ (or even $(4n)!$).
Answer: If $p=4n+1$, then the nonzero elements of $\mathbb{Z}_p$ are $\{1,2, \dots, 4n \}$. You can write this as $\{1,2, \dots, 2n, -2n, \dots, -2,-1 \}$. The product of all of these elements is $-1$ from Wilson's Theorem. But this is the same thing as $(1 \cdot 2 \cdots 2n)^{2}(-1)^{2n} = (1 \cdot 2 \cdots 2n)^{2} = ((2n!))^{2}$.
Answer: I think the part about $p$ not being a Gaussian prime has not been addressed. You have arrived at $p\mid(x+i)(x-i)$ (with $x=(2n)!$). Now $p$ divides neither $x+i$ nor $x-i$, since $${x\pm i\over p}={x\over p}\pm{1\over p}i$$ is not a Gaussian integer. But the Gaussian integers are a unique factorization domain, and in such a domain a prime that divides a product divides (at least) one of the terms being multiplied. Thus, $p$ can't be a prime in the Gaussians.


Non significant Pearson correlations included in hierarchical regression?

Question: I would like to perform hierarchical regression in which all variables are based on previous research/theory. But when I perform Pearson correlations, I found that some variables did not correlate to the DV. Should I still include those non-significant variables in the hierarchical regression as suggested by previous research even though they were not significant in Pearson correlations?
Thank you very much for your help.
Answer: Pearson correlation only tells you about the degree of "linear relationship" between variables. But there can actually be strong "non-linear" relationship between two variables too! Depending on what type of variable you have, you can use different correlation coefficients. So I think you should check possible non-linear relationships and associations. If the independent variables are by no means correlated to the dependent variable, then they will contribute little to a predictive model. But you can always include ALL the variables in your model and test the significance. So that option is also always open to you. Your research experience may also help you presume the presence of possible non-linear relationship with the DV.
Comment: Thank you very much Blain Waan. I really appreciate it. Very helpful!
Comment: You are most welcome @Simon


Spark SQL Performance optimisation

Question: I am running a Spark SQL query with huge amount of data (approx 50 million records).Due to heavy records, Query becomes slower in the cluster, So that it was taking long time (20 mins) to process  the entire data. I am using inner join,left join inside the query.How can i improve the performance.
Answer:
Since you are performing join operation and data size is huge, chances are lot of shuffling and I/O operation is involved. So if you are not using kryo serialization, your code would be using default Java Serialization. Use Kryo serialization, it gives better performance.
This one depends how you are storing your data in Hdfs. if its in a file format. Try creating Hive tables on top of it. Hive provides many optimisation technique.
a. Partitiong and Bucketing : Partitioning speeds up query since you don't have to scan entire table while reading data. Bucketing speeds up join operation.

b. Map Side join can be used: Here smaller table is sent to memory where join operation is performed in mapper itself and thus speeding up query.
Apache Spark provides option to take benefit of Hive using Hive Context.

Spark SQL Performance optimisation


Como manter a posição do scroll dentro de uma div após atualizar dinamicamente com AJAX?

Question: Estou construindo um mini fórum, e nele, os usuários podem fazer posts e respondê-los.
Para a página não ficar muito longa, eu coloquei uma div com uma altura e largura fixas, e, se o texto passar desse valor, ele irá acrescentar uma barra de rolagem,
O problema é:
Eu utilizo o AJAX para atualizar as respostas de tempos em tempos, e sempre que eu atualizo,e ele volta a barra de rolagem para a posição inicial, queria saber se tem como eu pegar a posição atual da barra de rolagem dentro da div, e quando atualizar com o ajax, ele voltar a barra nessa posição.
Esse é o código do AJAX:

Answer: Como não posso comentar, vou deduzir que você está destruindo os elementos e populando novamente de acordo com o que você retorna em sua requisição Ajax, caso esteja fazendo isso, esse comportamento de a barra ir para o topo é de se esperar.
Sugiro que você faça um incremento dos dados que estão sendo atualizados nos elementos que já estão criados, assim a barra de rolagem ira manter sua posição atual.
Comment: Faz sentido... Mas teria como você postar algum código ou me direcionar pra algum tópico que me ajude com isso?
Comment: Para eu postar algum código, preciso pelo menos do seu código de requisição do Ajax e ver a melhor maneira de fazer o incremento das informações.
Answer: Você deve gravar o conteudo de window.scrollTop em uma variavel antes de abrir o campo de edição e após salvar ou recarregar algo com ajax, também pode-se usar via jQuery (já que usou a tag jquery)
Ficaria algo como:
function atualizaScroll(lastScrollY)
{
    $('#respostas').scrollTop(lastScrollY);
}

function atualizarDados()
{
    var lastScrollY = $('#respostas').scrollTop();

    $.ajax("pagina.php", {
        ... //Dados da requisição aqui
    }).done(function () {
       //Completa a requisição
    }).fail(function () {
       //mostra erro
    }).complete(function () {
       /*
        * Executa mesmo com erro ou sucesso
        * (restaura posição do scroll)
        *
        * Delay é para evitar algo com o tempo da renderização
        */

       setTimeout(atualizaScroll, 10, lastScrollY);
    });
}

Comment: Eu testei o código acima, mas aparentemente ele funcionaria bem se fosse o scroll "global" da página, no meu caso, eu precisaria que esse comportamento acontecesse com o scroll dentro de uma Div. Como eu faria isso?
Comment: @kyro23 a sim entendi, falha minha, vou editar :)
Comment: @kyro23 corrigi o código e corrigi o setTimeout também, me avisa se falhar ;)
Comment: @kyro23 ué, o exemplo não funcionou? Você não deu retorno
Comment: Então, eu não dei retorno porquê passei um boom tempo procurando a solução para esse problema, e pelo que eu entendi, é um pouco mais complexo que só o scroll da div... Basicamente eu vou ter que fazer long pooling para manter uma conexão aberta com o servidor, e verificar se o resultado mudou, ai sim, quando ele mudar, eu exibo a nova informação na tela. O problema é que como eu quero fazer o site rodar em um servidor, eu vou ter que usar web sockets pra fazer essa conexão, então eu ainda to estudando qual seria a melhor solução. Mas valeu pela ajuda!
Comment: @kyro23 mas long pooling ou ajax são apenas maneiras de obter os dados, o problema é no front-end, não tem haver com a origem, me diz você quer recuperar a posição do scroll ou você quer forçar o scroll sempre ficar na posição da mensagem mais recente, igual aos chats/bate-papos online?
Comment: Bom, basicamente é o seguinte:
Da forma que eu fiz, o AJAX vai fazer uma requisição ao servidor a cada 10 segundos, e quando ele terminar essa requisição, ele mostra todas as informações na tela, e quando atualizar, isso acontece denovo e denovo. Mas seria muito mais fácil se ele só atualizar quando houver uma informação nova no banco de dados. É ai que entraria o webSockets, pois, imagina um servidor com mil usuários ao mesmo tempo recebendo informações de cada usuário a cada 10 segundos, obviamente o server vai cair. E eu também tenho planos de fazer  outros sistemas semelhantes no site.
Comment: @kyro23 tudo bem eu entendo, mas ainda sim isto não tem haver com a duvida e se você colocar que o problema é "qual o melhor caminho de comunicar front-end com back-end" você vai mudar o sentido da pergunta. Entenda que não somos um fórum e sim um Q&A, a pergunta deve ser objetiva, edita-la e mudar o assunto invalidaria as respostas ao meu ver....
Comment: ... Outra coisa **independente** de como obtém os dados a solução que eu mostrei é para resolver algo com o scroll e deve funcionar em qualquer situação, agora a duvida que mais importa: você quer recuperar a posição do scroll ou você quer forçar o scroll sempre ficar na posição da mensagem mais recente, igual aos chats/bate-papos online? @kyro23
Comment: Eu entendo que o correto seria eu abrir uma nova pergunta, pois a questão aqui é sobre o scroll e não sobre webSockets, porquê o meu problema inicial era só o scroll, mas eu acabei percebendo que não era SÓ o scroll... Pra você ter uma idéia do que eu to falando, esse é o site que eu estou desenvolvendo: http://indieworld.atwebpages.com/topico.php?t=VkZaRk9WQlJQVDA9 , e como pode perceber, se você mexer no scroll dentro da div, ele volta pra posição inicial, justamente porquê ele está atualizando essa div, onde o certo seria somente incrementar uma nova div.
Comment: E respondendo a sua pergunta, o comportamento do scroll que eu desejo é que ele mantenha-se na mesma posição que o usuário deixou.
Comment: @kyro23 então acho que a resposta aqui funciona perfeitamente sendo ajax ou webscoket, deve ter falhado porque você colocou na ordem errada algum evento. Notei que no site ainda esta o script antigo
Comment: Sim, a ideia é que a div tenha uma altura fixa e quando essa altura estourar ele criar o scroll
Comment: @kyro23 **achei o problema**, você usou vários IDs repetidos, o atributo ID não pode ser repetido. Você repetiu id=resposta e id=respostas algumas vezes, ID deve ser unico sempre
Comment: O código atualizado ainda ta no localhost, mas mesmo alterando de id para class o resultado continua sendo o mesmo
Comment: @kyro23 mas não basta alterar uma coisinha ou outra, deve ser uma falha sua, desculpe mas só estou querendo lhe orientar para o real problema, estou apenas tentando ajudar, não é uma critica negativa ;)
Comment: Sim, eu entendo, mas a solução mais lógica é mudar essa forma de atualização dinâmica, porquê pro que eu planejo fazer iria requisitar muito do servidor (que ainda é um plano gratuito de testes), além de que eu pretendo implementar a mesma tecnologia em outras funções, como um chat e um sistema de notificações, ou seja, essa maneira de atualizar a página não se encaixa na demanda que eu preciso. Mas mesmo assim, obrigado por me ajudar :D


GraphQL query argument that accepts key value pairs?

Question: I'd like to pass the following key:value pairs to a GraphQL query. I imagine it working something like this, but have been unable to find a way to achieve this.
query myPortfolio {
  portfolio(holdings: {"btc": 0.12, "ltc": 12.1}) {
    # ...
  }
}

I attempted to create a special type and pass it as an array, but this failed compilation.
type Holding {
  coin: String!
  amount: Float!
}

type Query {
  portfolio(holdings: [Holding!]): Portfolio!
}

Error: The type of Query.portfolio(holdings:) must be Input Type but got: [Holding!].
Answer: like the message says, the arguments needs to be of input type. Change your schema to something like
type Holding {
  coin: String!
  amount: Float!
}

input HoldingInput{
  coin: String!
  amount: Float!
}

type Query {
  portfolio(holdings: [HoldingInput!]): Portfolio!
}


Manipular XML com PHP

Question: Alguém poderia me dizer como eu faço para pegar apenas o valor de nome no código abaixo.
pagina index.
<?php

$curl = curl_init('http://localhost/server.php');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$resultado = curl_exec($curl);
curl_close($curl);

$xml = simplexml_load_string ($resultado);

echo $resultado;
echo $xml->nome;
?>

Página server:
$note=<<<xml
<note>
<nome>xiro</nome>
</note>
xml;

$xml = simplexml_load_string ($note);
var_dump($xml);

Comment: Qual o problema que você está tendo?
Comment: Eu quero chamar o nome(xiro) na pagina index, Mas não vem. igual esse exemplo https://www.youtube.com/watch?v=ipNK8Nigm08
Comment: Infelizmente não. Eu gostaria de manter a estrutura inicial com o object(SimpleXMLElement) e o  public. Dá uma olhada no vídeo que postei acima.
Comment: Se você explicar melhor o que você quer fazer, talvez haja outro modo de fazer isso.
Comment: Obrigado pela ajuda amigo, Segui o seu exemplo mesmo e fiz algumas adaptações. creio que no vídeo o pessoal do pagseguro usa uma mascara para formatar o XML.
Comment: Ótimo. Se quiser postar uma resposta explicando como você resolveu o problema seria bom, não se esqueça de aceitar a sua resposta como aceita. Isso poderia ajudar outras pessoas com problemas semelhantes ao seu.
Comment: Cara, pelos arquivos que você passou, faça esse teste tira essas duas linhas $xml = simplexml_load_string ($note); var_dump($xml); e coloca echo $note; do arquivo server e me fala o resultado.
Answer: Você tem que passar também os parâmetros "Pai" do elemento.
$xml->note->nome;

Como você pode ver <nome> está dentro de <note> então você terá que setar note no código.
Comment: ñ deu certo Alisson
Comment: @XiroNakamura tente usar **$xml = new SimpleXMLElement($resultado)** ao invez de **$xml = simplexml_load_string($resultado)** ... E para exibir, use `$xml->{'note'}->{'nome'}`
Comment: Alisson, tentei fazer assim como você disse e retornou o erro `SimpleXMLElement::__construct(): Entity: line 1: parser error : Start tag expected, '<' not found in...`
Comment: Obrigado pela ajuda Alisson.
Comment: Na documentação do PHP (http://php.net/manual/pt_BR/class.simplexmlelement.php), quando ele faz o load, ele considera o note, como root do documento, a leitura ficaria de fato $xml->nome;
Comment: O exemplo do que disse http://ideone.com/CrBJPq
Answer: Você tem que fazer um foreach no XML, veja é muito Simples:
<?php
$note=<<<xml
<note>
<nome>xiro</nome>
</note>
xml;

$xml = simplexml_load_string($note);

echo $xml->getName() . "
";

foreach($xml->children() as $child) {
    echo $child->getName() . ": " . $child . "
";
}

Aqui tem uma demonstração

Manipular XML com PHP


Filtro de categorias usando ngIf em algular

Question: Preciso criar um filtro por categorias, então adicionei uma função nos botões que quando eu clico elas passam uma variável chamada categoria. O valor dessa variável está vindo certo, porém o filtro não está funcionando. Esse é o código que estou usando:
<ion-content>

    <ion-col sizeLg="4.5" sizeMd="4" sizeXs="12" *ngFor="let book of books">

      <ion-card class="ion-text-center">

              <ion-grid>
                <ion-row class="ion-justify-content-center">
                    <ion-img [src]="book.image"></ion-img>
                </ion-row>
              </ion-grid>

{{ book.title }}

                <ion-text>

Autor: {{ book.autor }}

Sinopse: {{ book.sin }}

                  Clique para ir para a playlist!
                </ion-text>

              <ion-button class="button-edit" [routerDirection]="'root'" [routerLink]="['/update-book', book._id]" routerLinkActive="active">
                <ion-label><ion-icon name="pencil"></ion-icon></ion-label>
              </ion-button>

Answer: Acredito que o problema seja onde está usando o *ngIf:

Neste caso, a div em questão está sendo incluída no código, mas não faz nada. Para funcionar (acredito que esteja querendo mostrar o componente <ion-card> se book.category == categoria, certo?), basta passar o fechamento dessa  para o final do componente, ou colocar o *ngIf dentro do próprio componente, assim:
  <ion-col sizeLg="4.5" sizeMd="4" sizeXs="12" *ngFor="let book of books">
    <ion-card class="ion-text-center" *ngIf= "book.category == categoria">

          <ion-grid>
            <ion-row class="ion-justify-content-center">
              <ion-img [src]="book.image"></ion-img>
            </ion-row>
          </ion-grid>

{{ book.title }}

            <ion-text>

Autor: {{ book.autor }}

Sinopse: {{ book.sin }}

              Clique para ir para a playlist!
            </ion-text>

          <ion-button class="button-edit" [routerDirection]="'root'" [routerLink]="['/update-book', book._id]" routerLinkActive="active">
            <ion-label><ion-icon name="pencil"></ion-icon></ion-label>
          </ion-button>

    </ion-card>
        ...
    </ion-col>

Espero ter ajudado :-)
Comment: Deu certo, obrigada!


Locate an Element Which Will Come in Four Different Scenarios

Question: <input type="submit" name="ccBtnBook" value="Book" id="ccBtnBook"
class="bookbtn2 flR" style="background-color:Transparent;border-
style:None;">

<input type="submit" name="ccRepItinerary$ctl00$ccLbtnSelect" value="Book"
id="ccRepItinerary_ctl00_ccLbtnSelect" class="bookbtn2" style="background-
color:Transparent;border-style:None;">

<input type="button" value=" Book " class="bookbtn2" onclick="iSB('1')">

<input type="button" value=" Book " class="bookbtn2"
onclick="iSB('4','MCT','DXB','DXB','MCT','True')">

<input type="button" value=" Book " class="bookbtn2"
onclick="iSB('1','MCT','DXB','','','False')">

<input type="button" value=" Book " class="bookbtn2" onclick="iSB('4')">

I have tried using the class name and xpath, but failed for both.
I even tried to use a JavaScript click.
For case two finding the element by its ID works.
Comment: You mean the element could be any one of those options? you should also post what you tried and what was the problem with it?
Comment: I have edited the context
Comment: You didn't add any new information. *I have tried using* doesn't mean anything. Post the code and tell what happened when you tried it. If there is an error message post it as well.
Comment: driver.findElement(By.className("bookbtn2")).click();
Comment: WebDriverWait wait = new WebDriverWait(driver,50);
  wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input.bookbtn2")));
Comment: Error is, Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not interactable
Answer: Use the class, that seems to be common
//*[contains(@class, 'bookbtn2')]

Answer: As per the HTML you have shared to locate the element in four different scenarios you can use either of the following Locator Strategies:

cssSelector:
driver.findElement(By.cssSelector("input.bookbtn2[value='Book'][type='button'][onclick^='iSB']"));

xpath:
driver.findElement(By.xpath("//input[@class='bookbtn2' and @value='Book'][@type='button' and starts-with(@onclick,'iSB')]"));


two-way MANCOVA

Question: I am currently trying to run a two way MANCOVA as I have to independent variables with 2 levels each 1) sleep chronotype (late and early) and weekly sleep loss (high and low). I have four dependent variables (score and speed for planning) and (score and number of positive choices for gambling).  I also have one covariate which is depression. I was wondering if it is okay to have 2 dependent variables for one measure such as score and speed.  Also I was wondering if a two way mancova is the same as 1 way mancova with an additional independent variable and all the assumptions are similiar too. I cannot find any information on two way Mancova on any books or websites.
Answer: These are two of my go to sites (statisticshowto and laerd). The statistics how to link below discusses how the assumptions of a mancova are the same as that of a manova except with a couple other ones for the covariates (which they discuss in that site). Thus, if you take the assumptions from the two way manova (on the laerd link below) and add on the assumptions of the covariate (from the statisticshowto link), you should be covered.
https://www.statisticshowto.datasciencecentral.com/mancova/
https://statistics.laerd.com/spss-tutorials/two-way-manova-using-spss-statistics.php
Additionally, you asked about having 2 DVs for one measure (i.e., score and speed for planning). I would usually say look to the literature for how those measures were used in the past. For instance, have score and speed been used as separate measures to get at planning before. It sounds like this may not be a validated scale from the literature, though. If that's the case and it's just a value for score and speed, I would suggest checking to make sure they're not too correlated with each other ( > .95) to ensure there isn't redundancy in your measures thus indicating you are just measuring the same thing with two separate things. If the correlation is not too high, you should be fine to use both of them as two separate DVs.
Comment: Thank you very much Brittany for your helpful answer. I appreciate it very much
Comment: No worries. If you found my response to answer your question you can upvote it and check it as answered

two-way MANCOVA


Can $R[[x]]$ contain constants?

Question:
Consider the ring $R[[x]]$ of formal power series $\sum_{n=0}^\infty a_nx^n$ with coefficients in $R$. I was wondering whether $R[[x]]$ contains elements of $R$ (polynomials of degree $0$).

I'm trying to solve Commutative Algebra problems. I feel it is possible, as all of $\{a_1,a_2,\dots\}$ simply have to be equal to $0$, which I think is possible.
Thank you.
Comment: @blue- Nothing. I just edited the question for clarity.
Answer: Yes, it can. ${}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}$
Comment: Well, to do it it has to be able to do it. :-)
Comment: Yes, it *does*!
Comment: Yup yup yup yup yup! ;-)
Answer: If the coefficients are in $A$, we usually write $A[x]$, $A[[x]]$ instead of $R[x]$, $R[[x]]$, and I shall do so here.  This being said:
Yeah, it works.  Formally, $A[[x]]$ is often defined as the set of sequences of elements of $A$; that is, letting $\Bbb Z_0 = \{n \in \Bbb Z \mid n \ge 0\}$, the set of maps from $\Bbb Z_0 \to A$.  The sequences are added pointwise, so that $(a_i) + (b_i) = (a_i + b_i)$, and multiplied according to the rule $(a_i) \times (b_i) = (\sum_{j + k = i} a_j b_k)$, where $i$ is the sequence index in the sum on the right.  $A[x]$ is similarly defined, except the sequences in this case must stabilize to $0$ after some finite index is reached; that is, $(a_i) \in A[x]$ if $(a_i) \in A[[x]]$ and $a_j = 0$ for $j > N \in \Bbb Z_0$.  The least such $N$ is in fact the degree of $(a_i) \in A[x]$.  Soooooo . . . it is easy to see that in either case the ring $A$ (or an isomorphic copy thereof!) may be considered to be the sequences $(a_i)$ with $a_i = 0$ if $i > 0$.
Hope this helps.  Cheerio,
and as always,
Fiat Lux!!!
Comment: @freebird:  looks like my answer pre-dates your edits a bit; I wrote before you changed "$A$" to "$R$"!

Can $R[[x]]$ contain constants?


Prevent Drupal from rewriting # as %23 in URLs

Question: I have a field where I am rewriting the output, trimming it and providing a read more link. The read more link contains a # because it's a page anchor that triggers a views accordion on the destination page.
Views is converting the # character into %23 in the actual displayed link, which is breaking the link.
How can I convert it back to a # character in the url?
Comment: Somewhat related: http://drupal.stackexchange.com/questions/21124/adding-a-query-string-to-a-link-in-views. I had to resort to preprocessing the view, I couldn't get it to work using the UI
Answer: function drupal_urlencode($text) {
  if (variable_get('clean_url', '0')) {
    return str_replace(array('%2F', '%3F', '%3D', '%26', '%2523'),
                       array('/', '?', '=', '&', '#'),
                       urlencode($text));
  }
  else {
    return str_replace('%2F', '/', urlencode($text));
  }
}

Answer: So this was what we actually ended up doing, no preprocess or overrides required. Thanks to Peter Bull at Acquia for the help on this:
We handled this with some additional Views fields to rewrite the HTML.

Added an additional field for the term description, identical to how you I currently had it, except select "Exclude from display" and remove the "more link".
Changed the order of fields so the new term description field is loaded before the existing one.
Edited the original term description field. Check "Rewrite the output of this field" and put the token for the new field in the textarea, and then append the HTML for your link. So you are rewriting the HTML output as:

[token-for-new-term-description-field] more
Then I removed the more link as it was included in the rewrite above.
This workaround will preserve the trimmed output of the description field, and allow you to render the link with the appropriate counter ID in the anchor, without running that path through l() and check_plain().
Also needed to prepend the link with a / so it's root-relative. Since it's not being passed though l() it won't do that automatically and if this view page has a path that's not relative to the docroot you could get broken links.
Wheeeee!
Answer: $url = l(t("title of your page"),"$link_url",array('fragment' => 'hash url without #'));

first argument is title of your page
second argument is $link_url means ex. www.google.com/link_url.
and last is array of fragment
in this array you can pass link you want to pass after #
ex.http://domain.com/india#rajkot
so you haven,t need to use encode or decode any any other conversion
full syntax is
l(t('My Anchor Link'), '', array(
 'fragment' => ' ',
 'external' => TRUE,
 'attributes' => array(
 'title' => 'Title here.'
 ),
 ));
?>


How to Display a DIV with 'fixed' and 'inline-block' Added to its CSS Properties

Question: I want to be able to display a DIV in a fixed position and have its width fit to content but each time I add position: fixed;, the div gets computed to display: block; and the div becomes full length.
HTML:

CSS:
.veil{
    display: inline-block;
    position: fixed;
    top: 34%;
    left: 0;
    right: 0;
    margin: 0 auto;
    background-color: lavender;
}

Answer:
each time I add position: fixed;, the div gets computed to display: block; and the div becomes full length.

It's not display: block, it's position: fixed makes div stretch relatively to browser window, and since you have left: 0 and right: 0 you observe this behavior that div takes all window width.
Depending on your HTML structure you can use position: absolute instead or as pointed in comments (thanks @Paulie_D) don't use right: 0.
Comment: No...it doesn't. It displays as inline-block....at least it does in the fiddle. It won't center...if that's what you mean.
Comment: @Paulie_D If you remove the `right`proprety, the `div` will still be `diplay:block`.
Comment: Check under the computed styles for the `.veil`.
Comment: @Paulie_D - What do you mean by displays as inline-block? That it shrink-wraps, or something else?
Comment: Yes, sorry I deleted the comment but yes it "computes" as block but **displays** (thus shrink wrapping) as `inline-block"...and that I think was the point.
Comment: And actually if you look at this - http://jsfiddle.net/vynn9k0e/3/ under computed styles you can see that (by clicking the little-arrow to expand) it does show `inline-block` for the `.veil` div. The `p` inside it is `block` though.
Comment: Alternatively, you can use `display:table` to shrink wrap, which `position:fixed` preserves. Like this: http://jsfiddle.net/2c5y6u3h/
Answer: Just add another container.
and split the contradiction in CSS between them.
HTML:

CSS:
.container
{
    position: fixed;
    top: 34%;
    left: 0;
    right: 0;
}
.veil
{
    display: inline-block;
    margin: 0 auto;
    background-color: lavender;
}


Searching using Solr within Views

Question: I'm learning Drupal, and having a lot of fun. I am approaching the phase were I'd like to make my content more accessible to users.
I haven't implemented it yet, but I am really liking the ApacheSolr Search Integration module. I was wondering if there was any module to search within Views. My problem is that most of my site is based on Views; I have a lot of content on external databases, which I am maintaining, and Views queries that content for the users.
If Solr doesn't have anything I need, is there any other solution?
Answer: Please see the Apache Solr Views module for combining Solr and Views together.
If you are looking for a Views-only approach, you should watch this screencast on Exposed Filters.
Comment: wow thanks for the super quick reply.  I saw the views module but it said I need views-3, I'm using views-2 with drupal6..would upgrading to views3 from views2 cause any issues?
Comment: The upgrade path from Views 2 to Views 3 is relatively stable. However, it is unidirectional; you cannot downgrade later. Test it out locally, after a full backup, and you should be fine.
Answer: You have external data which you are exposing with views.
So you have a couple of options, one would be to get something to index your whole site but as this question shows that is not straightforward.
The second option is to get solr to index your external data. The inbuilt solr module (and solr views) are very node centric. If you have your data in nodes this works fairly simply.
If you are only showing external data with views then this solution won't work for you.
So what you can do is to use a solr data import handler to index your data (that is outside the scope of DA but have a look here for some info)
If you get this working you still then have a way to go. Firstly you need to get drupal to talk to solr for non node terms. The solr module will happily talk to any solr server if you are happy to code things yourself, but for views integration you have a bit more work. There are a couple of projects looking to do this, but they are not really mature projects just yet.
Once you have views pointing to solr and searching working you can then format your search results so that they link to your other views.
So for example if you have an external entity with an id XZY you may have a view which takes a url argument at '/myview/XZY' you can edit your search results view so that it points to that url. I have done this here, most of the site is generated using views and solr.
However I think for most of this to work you will have to use views3.
Answer: If you are still having issues, you can check out the IndexTank module.

Searching using Solr within Views


Error sending message to DM of a user discord.py

Question: I am currently trying to send a message to a user's DM but I only get the following error
user = client.get_user(499642019191324692)
AttributeError: module 'discord.client' has no attribute 'get_user'

This is my code
@bot.command()
async def test(ctx):
    user = client.get_user(499642019191324692)
    await user.send('Hello')

Comment: @GhostOps Surely you must realize that would be an entirely different error.
Comment: @AxelGarcia can you add your bot definition
Comment: the user id must be string i guess... and also, a user don't have ```send``` attribute, you can just ping the user in your msg
Comment: You have done `from discord import client`, but you must create an object of type `Client`.  That's where the `get_user` method is located.
Comment: yeah, and also, why its showing ```discord.client``` ? shouldn't be like ```discord.Client``` ?
Comment: @TimRoberts I have the `from discord import client`
imported since before the error occurs I don't think that is it
Comment: @GhostOps `discord.client` is well rendered, I don't think it's the error
Comment: @AxelGarcia How about user id in string?
Comment: @GhostOps If the string has a valid id, I even tried calling it as `int(499642019191324692)` but it didn't work anyway
Comment: Have you tried using `bot.get_user` instead? You're using `@bot.command()`, did you define your bot as `bot=command.Bot` or the likes?
Comment: @yotamrec My complete code https://pastebin.com/hbcWHD0x
Comment: @Bagle If I already try to use `bot.get_user` and I have` bot = command.Bot` defined you can see it in my code https://pastebin.com/hbcWHD0x
Answer: Thx @Astrogeek for your answer, even if only covering part of the issue. I got a similar issue, and this "bot" instead of client helped me A LOT.
To take the example back :
@bot.command()
async def test(ctx):
    user = bot.get_user(499642019191324692)
    await user.send('Hello')

Should instead be :
@bot.command()
async def test(ctx):
    user = await bot.fetch_user(499642019191324692)
    await user.send('Hello')

await fetch_user(user_id)
This function is a coroutine.
Retrieves a User based on their ID. This can only be used by bot accounts. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
(from DiscordPy API Reference)

Since it's a coroutine, you have to "await" it. If you don't, the coroutine hasn't time to get the user from its ID and it results in a "can't send non-None value to a just-started coroutine" with bot.fetch_user(id)
As said in API you can get user from ID that way, but it only guarantees to deliver the message if bot and user are in a same guild or are friends.
Answer: you've used bot.command so it'll be bot.get_user instead of client.get_user
@bot.command()
async def test(ctx):
    user = bot.get_user(499642019191324692)
    await user.send('Hello')

Comment: Unfortunately that method returns an error which is this `AttributeError: 'NoneType' object has no attribute 'send'`
Comment: Try using `user.say` instead of `user.send`
Comment: It returns the error `AttributeError: 'NoneType' object has no attribute 'say'`


tailwind css only first row is hoverable

Question: This is my table and hover:bg-orange-100 is handling the hover part.

                        Name
                        Email
                        Team

                        Role

                        @foreach($data as $row)

                            {{--run function once per user id--}}

                            <input type="text"  value="{{$row->vendor_name}}" class="bg-transparent" readonly>
                            <input type="text"  value="{{$row->vendor_contact}}" class="bg-transparent" readonly>
                            <input type="text"  value="{{$row->vendor_email}}" class="bg-transparent" readonly>
                            <input type="text"  value="{{$row->vendor_role}}" class="bg-transparent" readonly>

                                <button type="button" wire:click="edit({{ $row->id }})" class="mr-3 text-sm bg-blue-500 hover:bg-blue-700 text-white py-1 px-2 rounded focus:outline-none focus:shadow-outline">Edit</button>
                                <button type="button" wire:click="delete({{ $row->id }})" class="text-sm bg-red-500 hover:bg-red-700 text-white py-1 px-2 rounded focus:outline-none focus:shadow-outline">Delete</button>

                    @endforeach

how do i make it so it apply to every row?
Comment: You are looping over table cells rather than rows, is that correct? `` = [table cell](https://www.w3schools.com/tags/tag_td.asp) and `` = [table row](https://www.w3schools.com/tags/tag_tr.asp), which could be the problem only one row is hoverable.
Comment: Is this the full code of the table? Since you start with a `` tag instead of a ``.
Comment: as @node_modules suggested, you should move the foreach before the tr
Comment: I added the full code of the table, i tried adding hover at the upper part but it doesnt affect anything
Comment: It works! how did i not notice that, thanks for the help!
Answer: Just go up one line @foreach($data as $row) over

Answer: Try putting your @foreach before the


Identifying duplicated rows

Question: I have a larger data frame (~50K rows and 50 to 75 columns) that has a small number of row that are duplicated in, say, 7 of the 75 columns. Although it's simple enough to locate rows that duplicate rows above using duplicated(...), I want to be able to pull out the duplicated rows and the row that is duplicated, or if (stolen from an earlier post)
a <- c(rep("A", 3), rep("B", 3), rep("C",2))
b <- c(1,1,2,4,1,1,2,2)
d <- c('x','y','x','z','y','y','z','x')
df <- data.frame(a,b,d)
df
  a b d
1 A 1 x
2 A 1 y
3 A 2 x
4 B 4 z
5 B 1 y
6 B 1 y
7 C 2 z
8 C 2 x

duplicated(df[,c(1,2)]) gives me rows 2, 6, and 8. Row 2 duplicates row 1, row 6 duplicates 5, and row 8 duplicates 7 on the basis of columns 1 and 2. So I want to review rows 1 and 2 to see what the differences, if any, might be in column d. Easy enough with 8 rows and 3 columns, but my problem is much bigger.
To sum up, I'm looking for a simple way to find the row indices for, say rows 1 and 2, 5, and 6, and 7 and 8 based on a subset of the 50-75 columns, so I can visually compare the rows duplicated based on the subset.
Thoughts?
Answer: which(duplicated(df[,1:2])|duplicated(df[,1:2],fromLast=T))
#[1] 1 2 5 6 7 8

Identifying duplicated rows