Not able to create Hive table with TIMESTAMP datatype in Azure Databricks

Question:
org.apache.hadoop.hive.ql.metadata.HiveException:
java.lang.UnsupportedOperationException: Parquet does not support
timestamp. See HIVE-6384;

Getting above error while executing following code in Azure Databricks.
spark_session.sql("""
                    CREATE EXTERNAL TABLE IF NOT EXISTS dev_db.processing_table
                    (
                      campaign STRING,
                      status STRING,
                      file_name STRING,
                      arrival_time TIMESTAMP
                    )
                    PARTITIONED BY (
                      Date DATE)
                    ROW FORMAT SERDE
                      'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
                    STORED AS INPUTFORMAT
                      'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat'
                    OUTPUTFORMAT
                      'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat'
                    LOCATION "/mnt/data_analysis/pre-processed/"
             """)

Answer: As per Hive-6384 Jira, Starting from Hive-1.2 you can use Timestamp,date types in parquet tables.
Workarounds for Hive < 1.2 version:
1. Using String type:
CREATE EXTERNAL TABLE IF NOT EXISTS dev_db.processing_table
                    (
                      campaign STRING,
                      status STRING,
                      file_name STRING,
                      arrival_time STRING
                    )
                    PARTITIONED BY (
                      Date STRING)
                   Stored as parquet
                   Location '/mnt/data_analysis/pre-processed/';

Then while processing you can cast arrival_time,Date cast to timestamp,date types.
Using a view and cast the columns but views are slow.
2. Using ORC format:
CREATE EXTERNAL TABLE IF NOT EXISTS dev_db.processing_table
                    (
                      campaign STRING,
                      status STRING,
                      file_name STRING,
                      arrival_time Timestamp
                    )
                    PARTITIONED BY (
                      Date date)
                   Stored as orc
                   Location '/mnt/data_analysis/pre-processed/';

ORC supports both timestamp,date type
Comment: do you have any idea, how to update hive metastore version in Azure Databricks
Comment: For anybody that showed up here as I did, here is the guidance from Azure on how to update the Hive metastore - https://learn.microsoft.com/en-us/azure/databricks/kb/metastore/parquet-timestamp-requires-msver12


Retrieving information about $G$ from $G/H$ for a subgroup $H$ of $G$.

Question: Gallian states in his algebra book that

When the subgroup $H$ of $G$ is normal, then the set of left (or right) cosets of $H$ in $G$ is itself a group—called the factor group of $G$ by $H$ (or the quotient group of $G$ by $H$). Quite often, one can obtain information about a group by studying one of its factor groups. This method will be illustrated in the next section of this chapter.

He then gives the example for $G=4 \Bbb Z$ and constructs $\Bbb Z/4\Bbb Z$ and shows that it's isomorphic to $\Bbb Z_4$.
However I think I'm missing the point here. Everyone seems to motivate normal subgroups as a way to retrieve information from the original group $G$, but these examples don't show how this is true.
If anyone happens to know a specific example of how the statement

Quite often, one can obtain information about a group by studying one of its factor groups.

is true I would be very delighted. I don't think that in Gallian's example of $\Bbb Z/\Bbb 4\Bbb Z$ gives any information about $\Bbb Z$ itself?
Comment: See [here](https://math.stackexchange.com/q/153591/977780)
Comment: $\Bbb Z/n$ gives some information about $\Bbb Z$ itself. One understands why $\Bbb Z$ is [residually finite](https://blog.jpolak.org/?p=2053). Also, for solving a Diophantine equation over the ring $\Bbb Z$, it is useful to look at the ring $\Bbb Z/4$. For example, $x^2+y^2=2019$ has no solution over $\Bbb Z$. If so, it had one over $\Bbb Z/4$, which is obviously impossible (looking modulo $4$).
Comment: For example, you can prove that from $G/Z(G)$ cyclic follows that $G$ is Abelian (and hence $G/Z(G)$ is actually trivial).
Answer: From Dummit and Foote's Abstract Algebra:

More precisely, there is a one-to-one correspondence between the subgroups of $G$ containing $N$ and the subgroups of $G/N$, so that the lattice for $G/N$ (or rather, an isomorphic copy) appears in the lattice for $G$ as the collection of subgroups of $G$ between $N$ and $G$.

The example which I often use: if you know the subgroup lattice diagram of $D_8/\langle r^2\rangle\cong V_4\cong \mathbb{Z}_2\oplus\mathbb{Z}_2$) (information about factor group), then you can know a "part" of the subgroup lattice diagram of $D_8$ (information about the whole group).

By the way, this website https://hobbes.la.asu.edu/groups/groups.html is very helpful for studying subgroup lattice diagrams.


Juniper VPN client hardware?

Question: I am using Juniper Network Connect software VPN client (v7.1) to connect to my company's network. I have to present a client certificate and additionally enter username/password to connect - a painful process that I keep repeating many times throughout my work day.
Juniper does not provide a way to automate this process. There are some command line clients but they won't work with client certificates.
Split tunneling is not allowed with my company's vpn.
So I was wondering if there is a hardware device that would support this kind of vpn setup and act as a gateway to which I would redirect my network traffic when I need VPN.
I am not familiar with Juniper hardware and googling on this does not bring me any further.
Thanks!
Comment: Talk to your admin, the site isn't meant for people to come in and figure out ways to get around or undo the tech that is put in place for users.
Answer: The level of security is high because it allows access to your remote network.  If it was automated then it wouldn't be a security measure. Don't try to circumvent it, go see your admin and talk about whether that level is appropriate.
Comment: I highly appreciate all your suggestions. Thanks for answering.

I work for a large company where talking to network administrators is not possible.
Installing this kind of device at my work place would not increase security risk, but would hugely ease my work.

So the question still stands.
Comment: Well company policy is usually set by the person who is qualified to assess the risk.  Circumventing it can be a fireable offence.
Answer: NetworkConnect is a software SSL VPN.  I am not aware of any hardware that would connect to one, it is a software-only solution.
If you only need access to the VPN some of the time, you could make yourself a VM, connect that to the VPN, and do non-VPN-related things in your real system.  I use this technique for connecting to multple clients with VPNs -- I have a VM for each customer, and this lets me connect to multiple sites at the same time.
Answer: The Network Connect client is prompting you with the cert most likely because it isn't trusted and the IT dept there just used a self-signed cert instead of a valid 3rd party cert when setting up the certificates on the interfaces on the Juniper SA appliance.
The IT dept can do (and should do) two things to help you and everyone else out:

Use a VALID 3rd party cert for the SSL VPN to use with a proper FQDN.  Sames holds true IF they require client-side certs, but typically this isn't setup and if it were here they would be using valid certs to begin with I would presume.
They can go into the SA admin portal and configure session timeouts for users, down to the user themselves if they so wish, but typically it is done globally or through one of the connection profiles.  Change from the current setting, possibly 1 hour, to something like 4 or 8 hours.

This should help.
Comment: Thanks for answering. As I already noted, in this kind of large company it is virtually impossible to reach the network administering staff.

Juniper VPN client hardware?


branching and merging strategies

Question: I am looking for information on branching and merging strategies for .net projects. I have been discussing best practice approaches with other developers and would like to read up on the topic.
For example, we have Main/Head which is the main source tree of source code. Release branches are created for branches and merged to main where appropriate. Development branches are created for pieces of work and are merged to and from main. I am looking for guidelines to best practises strategies, do's and dont's etc.
Our source control is TFS2008.
Any links or articles on this topic would be great?
Answer: The best place to start is with the branching guidance produced by the ALM Rangers, the latest version is for TFS 2010 but it's applicable to 2008. If you're building software as products then the guidance is very good, if you're building in house software then I'd suggest droping the idea of a service pack branch.

branching and merging strategies


Prove that $\Bbb Z[\sqrt{2}, \sqrt{3}]$ does not equal $\Bbb Z[\sqrt{2} + \sqrt{3}]$.

Question:
Prove that $\Bbb Z[\sqrt{2}, \sqrt{3}]$ does not equal $\Bbb Z[\sqrt{2} + \sqrt{3}]$.

This is homework. I want to prove that these are different sets. The first set is the smallest ring containing the integers and the two radicals separately. The second is the smallest ring containing the integers and the sum of the two radicals. Unfortunately I cannot find any similar proofs to learn from. I've been trying to show that the second set does not contain the square roof of $6$, for instance, or the square root of $3$. We haven't looked at what the second set might contain. We've only looked at adjoining a single radical and not the sum of radicals on class.  If someone could solve a similar example or give me a crucial insight, that would be great.
Comment: Is $\sqrt 2$ a member of one set and not another?
Comment: I suppose that root 2 is not in the second set, since that would imply that root 3 was and thus that the sets are equal. But it's not clear to me how to prove this.
Comment: Can you describe the elements of the second ring?
Comment: Honestly, no. We simply have not been taught how to do so. Of course I know that all sums and products are involved. But I don't know how to shape the chaos. With just root 2 adjoined, I could do so.  Playing around with sums and products, it seems that one cannot isolate root 2 or root 3 or root 6. But I can't formalize this, only conjecture.
Comment: Well, you seem to know what the elements of $\mathbb Q(\sqrt2+\sqrt3)$ are... Maybe a similar idea works?
Comment: Let's start with: what is the definition of the second ring?
Comment: Surely, both sets contain $\sqrt2+\sqrt3$ and all its powers. I suggest that you write out the first few powers of this number, simplifying appropriately, of course.
Answer: Hint $\ $ Note $\,\ \sqrt{3}\,\not\in \Bbb Z[\alpha]\ $ for  $\ \alpha\, =\, \sqrt 3 +\! \sqrt{2}\ $  of degree $\,4\,$ over $\Bbb Q,\,$ else
$$\!\!\!\! \begin{eqnarray}
\alpha\,(2\sqrt 3-\!\alpha)&=&\phantom{._{I^{I^I}}}\!\!\!\!\!\!\!\!\!\! (\sqrt 3+\!\sqrt 2)(\sqrt 3-\!\sqrt 2)\, =\, \color{#0a0}{1}\\
\Rightarrow\ \  \alpha\sqrt 3\,  =\, \dfrac{\alpha^2}{\color{#c00}2}\!&+&\!\dfrac{\color{#0a0}{1}}2\,\in\,\color{}{\Bbb Z}[\alpha]\, =\,\color{}{\Bbb Z}\!+\!\alpha\Bbb Z\!+\!\color{}{\alpha^2{\color{#c00}{\Bbb Z}}}\!+\!\alpha^3\Bbb Z \,\ \Rightarrow\ \dfrac{1}{\color{#c00}2} \in \color{#c00}{\Bbb Z}\end{eqnarray}$$
Comment: This is quite violently unmotivated.
Comment: @MarianoSuárez-Alvarez: Conjugating $\sqrt{3} + \sqrt{2}$ seems like a natural thing to do, and then trying to express the conjugate $\sqrt{3} - \sqrt{2}$ as a $\mathbb{Z}$-linear combination of $\sqrt{3}$ and $\alpha$ makes sense. Solving $\sqrt{3} - \sqrt{2} = m\alpha + n\sqrt{3}$ yields $m=-1$, $n=2$.
Comment: But why would anyone compute $a(2\sqrt3-a)$?
Comment: @Bungo, and the answer would go from an opaque *verification* to an instructive example on how to deal with these things if it explain that. That is my point.
Comment: @Bungo Alas, I don't think there is a nice way to adequately explain what is going on here without employing more advanced concepts from algebraic number theory.
Comment: The same argument works for $\,\sqrt{a}+\sqrt{b},\ $ see [this answer.](http://math.stackexchange.com/a/641633/242)
Comment: We haven't talked about degrees, but this proof is terse and gives me the kind of contradiction I was hoping for. Thanks.
Comment: @s.z. There is further discussion in the comments of the linked generalization which may prove helpful in that regard.
Comment: For your description of the ring you need more than knowing that a is of degree four over the rationals.
Comment: @Mariano It's a hint / sketch. As I remarked, if the OP needs further details they are in the linked comments - which address your first remark.
Comment: @MarianoSuárez-Alvarez: I agree with your point. This answer (even as a hint) is a bit cryptic as written.
Answer: Not the most elegant solution, but note that
$$(\sqrt2+\sqrt3)^{2n+1}=a_n\sqrt2+b_n\sqrt3,$$
where $a_0=b_0=1$ and
$$(\sqrt2+\sqrt3)^2(a_n\sqrt2+b_n\sqrt3)=(5+\sqrt6)(a_n\sqrt2+b_n\sqrt3)=(5a_n+6b_n)\sqrt2+(5b_n+4a_n)\sqrt3,$$
so
$$2\mid a_{n+1}-b_{n+1}\iff 2\mid(5a_n+6b_n)-(5b_n+4a_n)=a_n-b_n+2b_n.$$
Therefore the difference $a_n-b_n$ is even for all $n$. Even powers $(\sqrt2+\sqrt3)^{2n}$ contain just $\sqrt6$. But the elements of $\mathbb Z[\sqrt2+\sqrt3]$ have the form
$$\sum_{k=0}^d z_k(\sqrt2+\sqrt3)^k.$$
This means the difference of multiples of $\sqrt2$ and $\sqrt3$ always has to be even, which contradicts $\sqrt2$ or $\sqrt3$ being elements of this ring.
I obviously assume we already know $\sqrt2, \sqrt3$ and $\sqrt6$ are linearly independent over $\mathbb Q$.
Comment: Write down the first, second, and third powers of $\sqrt2+\sqrt3$ and observe that the fourth power is a $\Bbb Z$-linear conmbination of $1$ and these three numbers.
Comment: Right you are. I find nothing inelegant in this.
Comment: @Lubin I'm sure there's some slick argument why the difference is even and I missed it.
Comment: Thanks for your help. We haven't talked out things being "over Q" yet. We've just learned the definition of IDs and fields. The approach to these added elements was just a sketch.


is it possible to automate the Python scripts each time when returning an error?

Question: I want to automate the python to re-run the code when it returns error, is it possible and how can I do it?
I have a script and each time that returns an error I have to run it again. The error does not interfere in the process, so it can't be a problem re-run.
Comment: Why not use a `try - except` block to catch the error, and handle it that way?
Comment: this got nothing with python but with the way you run it.
Comment: It's seems a good idea.
Answer: When you face an error, typically, the program will halt.
That's why there are error handlers in place to not let that happen.
Look at some already answered examples here
So, lets say you want the user to input integer values and it shouldn't halt, so you could use a loop and break it when the entered value is an integer (there's no error thrown)
<code>...
while True:
  try:
    i = int(input("Integer: "))
    break
  except:
    print("Error")
...
</code>
You get the idea.


Guarantee execution order of script tags in ASP.NET

Question: I have a page that contains multiple script-tags that reference .aspx-pages (in the same app and site).
As far as I know these are all called in order of appearance by the browser. However, it looks like when the calls arrive at the web server, the order of execution is no longer the same (usually).
Is there a way in ASP.NET (we are using version 4.5) to make sure the order of execution is always the same as how they appear in the HTML?
Answer: The tags likely fire in order at the client. They may not arrive in order at the server. The browser may send requests on separate connections and order will not be respected. You may force one script tag to activate the next, and so on.
Comment: Thanks! But what I was trying to say was: Is there a way to make ASP.NET execute the .aspx-pages (as called by the script tags) in an order I decide?


Differences of the TTL value in Tracert and Ping

Question: When I ping localhost on my Windows XP system, the TTL value returned is 128 and it shows me that the default TTL value in the ping for my system is 128.
Then when I ping google.com the returned TTL value is 45, and I assume it means that (128 - 45) / 2 hops are existed in my way to google.
When I tracert google.com, it says that the packets goes for maximum 30 numbers of hops, but it reaches the destination.
Why does it happen? Is it any difference between the TTL value showed in ping and the TTL value of tracert ?!
Thanks in advance . . .
Answer: Different operating systems send replies to pings with different TTL (it doesn't depend upon the TTL in the incoming ping). Common starting values include 64, 128 and 255. I.e., your words "it means that (128 - 45) / 2 hops exist in my way to google" are wrong. Assuming that they use regular linux systems, they send ICMP packets with TTL = 64, and thus there are only 19 hops.
Answer:
Why does it happen?

Some host in path filtering you traceroute

Is it any difference between the TTL value showed in ping and the TTL value of tracert ?!

no difference(ping ttl=55, tracepath ttl=back=55)... no host filtering trace
<code>ping ya.ru
PING ya.ru (184.108.40.206) 56(84) bytes of data.
64 bytes from www.yandex.ru (18.104.22.168): icmp_seq=1 ttl=55 time=36.6 ms

 tracepath ya.ru

 ....................

 8:  l3-s550-s450.yandex.net (184.108.40.206)              97.070ms
 9:  l3-s650-s550.yandex.net (220.127.116.11)              97.992ms
10:  www.yandex.ru (220.127.116.11)                            91.306ms reached
     Resume: pmtu 1500 hops 10 back 55
</code>

Then when I ping google.com the returned TTL value is 45, and I assume it means that (128 - 45) / 2 hops are existed in my way to google.

No. Path = 64(default google.com ttl) - 45(ping ttl) = 19 hops
Comment: @bindbn: "tracepath ttl=back=55" tracepath print number of return hop's, not received TTL.


Make a view content only appear when user is logged in

Question: In Drupal 7, I need to create a view of member-only nodes. They're all of a certain type. This type—and I've already set that up with role-based access control—can only be seen by logged in users.
Now, I can create a view called Member Area that shows these nodes, and make it accessible only to logged in users (through the View access control), but when I create a menu entry for that view, the link obviously disappears when the user isn't logged in.
What I need is a link that points to a "please log in" text (could be on a static page, whatever) when the user isn't logged in. If the user then logs in, I want to display the view which shows only the restricted content.
Giving a specific example, I currently have this. The block is conditionally shown in the sidebar only on the page called Member Area. The page displays the static You are not logged in… text.

Once the user logs in, I want to show them the view of restricted content:

The horrible kludge that I use now is that I link the user to another view in the user menu, but that's really bad UX.
Can I set this up somehow?
Answer: What I did was quite simple:

Create the view normally, without access restrictions and link it to the menu.
Make sure the nodes themselves can only be seen by logged in users.
Create a No results behavior text that tells users to log in.
Show the login block only on the view's page.
Answer: I believe you're looking for https://drupal.org/project/r4032login
In addition to that, this module: https://drupal.org/project/menu_item_visibility will allow you to set the menu item to be visible to anonymous users as well even though they can't access its content. when they click on it they're redirected to login.
Comment: Ah, I found a workaround for my situation (see my answer), but those modules you mention would both work great. Thank you.


Estou com um problema onde realmente eu não sei como fazer um evento que escute uma ação no Laravel

Question: Tenho um slide show de imagens onde aparece as imagens cadastradas no banco. A tabela se chama eventos. Nessa tabela tem um campo chamado de data_fim, que seria referente ao final da data do evento, e também tenho um campo chamado status, onde ele e do tipo boolean que quando ela esta como true ela esta ativa no slide. O que preciso para que um serviço escute, que, quando a data atual (date('d')) não for mais a igual a data do campo data_fim que ele seja desativada o campo status == false. Como faria para realizar essa façanha?
Estava fazendo assim veja:
<code>$evento = Evento::whereDay('data_fim', '<='  ,date('d'))->first();
    if($evento){
         $evento->status = false;
         $evento->save();
    }
</code>
Mais eu acho que isso é muito gambiarra. Existe uma forma mais inteligente para fazer o mesmo. Gostaria de aprender com serviços no Laravel. Não sei muito bem. Peço que vocês me oriente.
Comment: Você quer verificar sempre antes de salvar?
Comment: Não quero que quando a data do evento passar da data atual que ele desative um campo da tabela
Comment: Certo, mas **quando**?
Comment: Vamos supor a data do evento e dia 28/09/2017 a dia 30/09/2017
Enta eu tenho 2 campos na tabela eventos data_inicio e data_fim
quando a data atual Ex que hj e dia 31/09/2017 então o campo status seja desativado automaticamente da tabela eventos.
Comment: Então eu fiz assim. Não sei se isso e gambiarra mais funciona hehehe. Gostaria da sua opinião:
 $expirar = Evento::whereDay('data_fim', '<' ,date('d'))->where('status' , true)->where('expirar', true)->first();

       // dd($expirar);
        if(isset($expirar) and $expirar->count() >= 1 ){
            $expirar->expirar = false;
            $expirar->save();
        }
Answer: Uma forma de você fazer isso, é criar uma tarefa agendada usando crontab
Uma formula parecida com essa:
<code>10 0 * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
</code>
Basicamente, a instrução que passo pro servidor, é que ele rode esse script, todos os dias ás 00:10.
Então o que você pode fazer é, criar um script que verifique a data_fim e compare com a data atual, e dependendo do resultado, você faz o update do campo status na sua tabela eventos
Aqui tem mais coisas na documentação: https://laravel.com/docs/5.5/scheduling
E também tem esse site que ajuda na hora de você montar a task: https://crontab.guru
Comment: um crontab pra permiti exibir uma slideshow? Você tem certeza que este é o problema do autor, como ele disse "evento" no caso se refere a uma tabela no banco e não me parece necessariamente eventos reais.
Comment: Acredito que seja uma das formas de se solucionar o problema dele.
Pelo que entendi, ele precisa verificar se a data atual é menor ou igual a **data_fim** da tabela.
O crontab não é para exibir ou não o slideshow, e sim para atualizar o campo **status** da tabela **eventos**.
Comment: crontab pra uma checagem no banco parece uma volta ao mundo para chegar na esquina, o problema dele é só checar as datas e permitir exibir o slide naquele momento, isso se resolve com o where do proprio Eloquente ou até mesmo com uma `if` básica, usar CRONTAB pra isso é o mesmo que colocar 200 cavalos para puxar um carro que está funcionando, ou seja vai dar mais trabalho e no final vai fazer a mesma coisa que poderia fazer simplesmente dando a partida no carro.
Comment: Acho que você não entendeu a dúvida do autor.
O problema não é apenas exibir, é atualizar o campo **status**.

|

> O que preciso para que um serviço escute, que, quando a data atual (date('d')) não for mais a igual a data do campo data_fim que ele seja desativada o campo status == false

|

**Eu** acredito que usar crontab seja sim uma solução, se vai onerar mais recurso do que precisa, ai depende do que a aplicação dele precisa.


PHP / MYSQL sql selection

Question: need some help figuring this out.
My function:
function cleanDatabase()
{
    $allowedTime = $this->time - 10;
    $query = mysql_query("SELECT * FROM `chatsessions` WHERE `last_active` < ".$allowedTime." AND `public` = 0");
    if( mysql_num_rows($query) > 0 ){
        while($row = mysql_fetch_array($query)){
            //move messages to history for evrey cID
            $query2 = mysql_query(" SELECT * FROM `messages`, `chatsessions`
                                    WHERE messages.cID = ".$row['cID']."
                                    AND chatsessions.cID = messages.cID
                                    AND chatsessions.public = 0");
            if( mysql_num_rows($query2) > 0 ){
                while($row2 = mysql_fetch_array($query2)){
                    $insert = mysql_query("INSERT INTO `message_history` (`cID`, `mID`, `user_id`, `sender`, `sendtime`, `message`) VALUES
                                          (".$row2['cID'].", ".$row2['mID'].", ".$row2['user_id'].", '".$row2['sender']."', ".$row2['sendtime'].", '".$row2['message']."')");

                    if($insert)
                        $delete = mysql_query("DELETE FROM `messages` WHERE `cID` = ".$row2['cID']);

                    if(!$delete)
                        return false;
                }
            }
            $query3 = mysql_query("DELETE FROM `chatsessions` WHERE `cID` = ".$row['cID']." AND public = 0");
        }
    }
}

The function does

select unactive chats the are NOT public 1
Fetch messages from the selected chat
insert messages to history
if inserted delete old messages
delete chat sessions what dont have public = 1

What it needs to do:

select unactive chats the are NOT public 1
Select messages from cID when the last row with that cID is removed (public rows wont get removed so those messages should always stay)
insert messages to history
if inserted delete old messages
delete chat sessions what dont have public = 1

The problem is there are multiple rows in chatsession with the same cID (one for every user and the permanent with pulbic=1 )
i dont know how to NOT delete messages IF there is a chatsession with that ID that has public = 1
edit: step 2 of how it should work
Comment: Solved it by adding a count to total chats with unactive chat ID and if unactive chats equal total chats the messages go to history.
Answer: Just trying to understand your setup, you retrieve the cID from chatsessions, which would be either be public or private ( public = 1 or 0 ).
Would the messages within the chatsession (cID) all be public or private, as they would inherit the properties from the chat session.
Or is there the ability to have a public message broadcast from a private room (if this is the case - there is a subquery / 2nd statement you can run)
EDIT:
you could reduce the whole procedure and only use 2 sql statements (no loops) - something like
function cleanDatabase() {
$allowedTime = $this->time - 10;

// update history
$query = mysql_query("INSERT INTO `message_history` (`cID`, `mID`, `user_id`, `sender`, `sendtime`, `message`) SELECT messages.cID, messages.mID, messages.user_id, messages.sender, messages.sendtime, messages.message FROM `messages`, `chatsessions`  WHERE `last_active` < ".$allowedTime." AND chatsessions.cID = messages.cID AND chatsessions.public = 0");

// delte old rows
$query = mysql_query("DELETE FROM  `messages`, `chatsessions`  WHERE `last_active` < ".$allowedTime." AND chatsessions.cID = messages.cID AND chatsessions.public = 0");
}

I can test this better later, but should point you in the right direction?
Mark
Comment: messages are only linked to the cID they dont have private or public, if its a private room the messages have to go to history, I alredy noticed a flaw in my own logic, updated post.
Comment: That looks much cleaner! but before moving the messages I need it to check if the cID selected is the last row of that cID, if there are other it needs to only remove that row
Comment: Alright i did get rid of a few query's thanks for your time and surgestions, by the way deleting multiple tables you need to define what you want to delete too: DELETE messages.*, chatsessions.* FROM. Cheers

PHP / MYSQL sql selection


Show/Hide fields not working for Condition Fields on node display

Question: I have Conditional fields installed, with a checkbox as the dependency which shows two textareas when checked. The issue is when viewing the content type, the checkbox is NOT checked and the text areas still show up. I have checked in Manage Dependencies and the dependants are required and visible when checkbox field is checked.
Is there another place to adjust these settings, if so where would I look?
Answer: This is a quirk of the module, per the documentation on the view context:

The "Value", "Filled" and "Empty" conditions are special: they are the
  only conditions that have ANY effect on form validation and content
  view.

If you want to show/hide fields with the module during content display, you'll need to set the Condition to Value and the according value for your checkbox.


Bitbucket - No binary for Chrome browser on your platform

Question: I'm working on basic react project and I'm able to run test with karma and mocha on my mac with chrome.
But bitbucket pipeline says that I do not have a chrome, so the question is how to install chrome there and will I have to install it every time with build?
my yml
image: node:7.10.0
    pipelines:
      default:
        - step:
            script:
              - npm install -g bower
              - bower install --allow-root
              - npm install
              - npm test

karma.conf.js
module.exports = function(config) {
config.set({
    basePath: '',
    frameworks: ['mocha'],
    files: [
        './tests/*.js'
    ],
    exclude: [],
    preprocessors: {
        './tests/*.js': ['webpack']
    },
    // webpack configuration
    webpack: require('./webpack.dev.js'),
    webpackMiddleware: {
        stats: 'errors-only'
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'], //run in Chrome
    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,
    concurrency: Infinity
});

};
Answer: The line image: node:7.10.0 in your bitbucket-pipelines.yml file specifies a Docker image to use. In your case, it's a plain node version 7.10.0 image, so there is no Chrome contained in it.
There are two things you can do:

Read about Docker, learn how to create your own image that includes Chrome (or whatever other software) and then use that image in your pipeline
Or, probably far easier: search for an existing Docker image created by someone else which includes node, Chrome and possibly other software you might need. Then, use that image in the image: <image-name> configuration line.

In either case, once you have a suitable image, this will be needed when your pipeline is run and Chrome will be available immediately, and you will not need any kind of "installation".
Comment: As a bonus, if all the tools are already in the image, then you don't need to spend build minutes fetching or installing them.
Comment: I use [circleci node-browsers images](https://hub.docker.com/r/circleci/node/) which contain most usual things needed for testing with Firefox and Chrome.


Como remover todos os itens de uma relação many-to-many no Django?

Question: Tenho os seguintes models na minha aplicação Django:
class Tag(models.Model):
    name        = models.CharField(max_length=150)
    description = models.TextField(null=True, blank=True)
    created_at  = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tags'
        ordering = ('name', )

class Question(models.Model):
    title = models.CharField(max_length=300)
    text  = models.TextField()
    user  = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='questions')
    tags  = models.ManyToManyField(Tag, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at  = models.DateTimeField(auto_now=True)

No caso, Question tem N relacionamentos com N tags. Supondo que na Question 1 eu tenha relacionamento com as tags 1, 2 e 3, como eu faria para remover todas as tags relacionadas a Question?
Exemplo:
 question = Question.objects.get(pk=1)
 # Quero desassociar  todas as tags dessa questão

Answer: Para remover todas as tags relacionadas o Django oferece a funçao clear que remove todos os objetos do conjunto de objetos relacionados sem deletar as relações apenas só removendo a associação, caso você queira remover e deletar os objetos relacionados use a funçao remove, alguns exemplos pra esclarecer a idéia
Remove apenas as associações(as tags ainda vão existir)
>>> question = Question.objects.get(pk=1)
>>> question.tags.clear()
>>> question.tags.all()
<QuerySet []>
>>> Tag.objects.all()
<QuerySet [<Tag: 1>, <Tag: 2>, <Tag: 3>]>

Remove as associações e deleta as tags(as tags não vão mais existir)
question = Question.objects.get(pk=1)

# deleta as tags
for tag in question.tags.all():
    tag.delete()

Tag.objects.all() # retorna <QuerySet []>

Eu testei a função remove e não funcionou, então fiz esse código acima pra remover manualmente.


I need help in interpreting mixed effects output with interaction

Question: I have data structured in a long format which contains repeated values for every participant v001. I run a mixed models analysis with random coefficients to investigate the relationship between my dependent variable ln_slope, which is an index measure for bronchial hyperreactivity, and some predictors. I want to investigate if changes in ln_slope depend on some factors. I calculated time for every individual starting from baseline (0).
The data looks like the:
structure(list(v001 = c(10002, 10002, 10002, 10002, 10002, 10004,
10004, 10004, 10005, 10005, 10005, 10006, 10006, 10006, 10006,
10006, 10006, 10006, 10007, 10007), time = c(0, 3, 6, 9, 12,
0, 3, 6, 0, 6, 9, 0, 3, 9, 12, 15, 18, 21, 0, 3), age = c(46.4394250513347,
49.4565366187543, 52.4462696783025, 55.4496919917864, 58.444900752909,
22.9158110882957, 25.9247091033539, 28.9199178644764, 15.3182751540041,
21.3169062286105, 24.3066392881588, 14.8856947296372, 17.8809034907598,
23.8795345653662, 26.8939082819986, 29.8726899383984, 32.8843258042437,
35.8740588637919, 27.4579055441478, 30.466803559206), bmi = c(27.6094517551723,
29.7520661157025, 29.3946871824648, 30.119375573921, 29.3946871824648,
25.3902185223725, 26.4855397496689, 25.7210322145387, 18.8323917137476,
21.6788067984738, 22.2569083130998, 20.8979591836735, 23.7196092506476,
23.2005432322318, 25.207756232687, 27.4445450430059, 27.1669192713546,
27.7488727020465, 23.6202879121581, 22.8571428571429), ln_slope = c(0.0507723253734231,
0.606135803570316, 0.192160005794242, 0.10951852580649, 0.374693449441411,
NA, 0.218445030532656, NA, 0.313091787977149, NA, -0.0361572285993463,
0.800960043896479, NA, NA, NA, 1.37147927533475, 1.53234783071453,
0.996237878364571, -0.133531392624523, -0.0408887702539783),
    sexe = structure(c(2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("female",
    "male"), class = "factor"), bronch = structure(c(2L, 2L,
    2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L,
    1L, 2L, 2L), .Label = c("yes", "no"), class = "factor")), .Names = c("v001",
"time", "age", "bmi", "ln_slope", "sexe", "bronch"), row.names = c(5L,
6L, 7L, 8L, 9L, 12L, 13L, 14L, 20L, 22L, 23L, 29L, 30L, 32L,
33L, 34L, 35L, 36L, 41L, 42L), class = "data.frame")

And the model I run was:
model.1=lme(ln_slope~time+sexe*time+age*time+bmi*time+bronch*time,random=~1|v001,data=gaga,na.action="na.omit")

My questions are:

How can I interpret the interactions with time for variables such as BMI and categorical ones such as bronch? Considering that my dependent variable is also a changing variable.
What does the coefficient for time indicate?
What is the difference between the coefficients between, say, bronchno and time:bronchno?

Here is the output: (bronchno is the estimate for people who said no when asked if they have bronchitis, the reference group is bronchyes - those who said yes)
                   Value    Std.Error   DF    t-value      p-value
(Intercept)   -0.1405926367 1.017008e-01 4312 -1.3824144 1.669161e-01
time           0.0081936566 8.151101e-03 4312  1.0052208 3.148470e-01
sexemale      -0.0040153945 2.743607e-02 1490 -0.1463546 8.836613e-01
age            0.0054305993 1.224855e-03 4312  4.4336684 9.494741e-06
bmi            0.0129494923 3.772421e-03 4312  3.4326738 6.032847e-04
bronchno      -0.0395274443 3.429395e-02 4312 -1.1526069 2.491357e-01
time:sexemale  0.0033349796 1.936829e-03 4312  1.7218765 8.516362e-02
time:age       0.0002534342 8.304164e-05 4312  3.0518934 2.287877e-03
time:bmi      -0.0001388647 2.758376e-04 4312 -0.5034291 6.146883e-01
time:bronchno -0.0053347104 3.243086e-03 4312 -1.6449490 1.000532e-01

Answer: I've generally been advised to run a main effects-only model before running a model with interaction effects. The latter can be tricky to interpret. But, to your questions. Let's assume that time is coded in months (and you had measures at baseline, then 3, 6, 9, and 12 months).
2) The average change in log-hyperreactivity (in females, age 0, with bronchitis) is 0.00819 units per month. But remember, you logged your DV.
3) The coefficient for no bronchitis (that's the variable bronchno) means this: those without bronchitis had baseline log-hyperreactivity measures 0.0395 less than those with.
1) For bronchitis: those without bronchitis have an growth rate in log-hyperreactivity of 0.0053 units less than those with.
It's a bit harder to comprehend continuous-continuous interactions, but the explanation is similar. Here, each unit of BMI was associated with a 0.0129 unit increase in log-hyperreactivity at baseline, but a lower growth rate in log-hyperreactivity.


Addressing instability in anchors for mobile web

Question: I have a rather intense (yet wonderfully simple) UI in JQ where anchors are required for the UI to position.
The problem is in iOS/Chrome (webkit) and various other browsers.  When an anchor is clicked about 50% of the time the a tag will trigger the Chrome URL address bar to slide down, press again and it goes away.  The offset is serious no bueno.
As you would expect this messes up the UI positioning and the address bar offsetting is rather hard to predict as it is a device+screen size reaction.
I think this is a bug when the first fragment is used where there was previously none OR the change of a fragment state (new or changed). These actions, or similar, are telling the browser "a tag clicked, activate url bar".
I like this solution (CSS) but this does not address the problem as the address bar is not an element to predict against reliably (unless I want to write a foolish amount of JS for a small problem):
https://stackoverflow.com/a/13184714/860715
I am skipping the long-winded full screen API as not all mobile have that feature.
My current solution, in testing now, is to add onclick="return;" to the a tags anchoring the UI.  This method seems to capture the anchor activity and skip the a tag triggering the address bar.
Thoughts on a better solution and/or possible issues in the UI for various mobile browsers.

Thx to Louys Patrice Bessette for the solution, a minor edit was required:
$(document).ready(function(){
    $("a").on("click", function(e){
      if( $(this).attr("href").substr(0,1) == "#" && $(this).attr("href").length > 1 ){
        var targetPos = $(document).find("a[name='"+$(this).attr("href").substr(1)+"']").offset().top;
        $("html, body").scrollTop(targetPos);
        e.preventDefault();  // this was moved -<-<
    }
});});

Answer: I would prevent the default behavior of an anchor when it's used to scroll the page.
$(document).ready(function(){
  $("a").on("click", function(e){

    // It the href attribute begins with # and is not ONLY #
    if( $(this).attr("href").substr(0,1) == "#" && $(this).attr("href").length > 1 ){

      // Prevent the default anchor behavior.
      e.preventDefault();

      // Get the offset of the target a having the name attribute matching the href of the clicked anchor.
      var targetPos = $(document).find("a[name='"+$(this).attr("href").substr(1)+"']").offset().top;

      // Scroll the page to that position.
      $("html, body").scrollTop(targetPos);
    }
  });
});

Comment: Ok, got it to work, ```e.preventDefault();``` was in the wrong place, needed to follow ```scrollTop```. Tested on Chrome/Webkit iOS, Chrome OSX, FFox OSX.  This solution is what I was expecting, but my problem was keeping some behavior and denying others. Good work/thx. Posted correction in in original.
Comment: Really interesting idea. I will try this out but I think the Chrome behavior could still get in the way. I am going to drop in some JS to watch screen-vertical size as the address-bar comes and goes.  Will report back as this progresses in deployments.
Comment: Isn't it better if the address bar does not "come and go" uselessly ?? ;) The above solution should do that.


Vue testing with jest: $route is always undefined

Question: I've tried a lot of things but $route seems to always be undefined and I have this error on shallowMount: TypeError: Cannot read property 'params' of undefined.
In my component, I want to check the params of the $route but it is always undefined. I've looked the documentation and mocked the $route to set it but it seems like the $route is not mocked. I've also tried using localVue.use(VueRouter), thinking that it would set $route but it didn't. Does anyone have an idea why the following doesn't work in both cases?
my-component.ts
@Component
export default class MyComponent extends Vue {
  get organisationId() {
    return this.$route.params.organisationId;
  }
}

I've tried the 2 following tests with the solutions I've talked about:
my-component.spec.ts
import { createLocalVue, shallowMount } from '@vue/test-utils';
import MyComponent from '@/components/MyComponent.vue';
import router from '@/router';

const localVue = createLocalVue();

describe('MyComponent', () => {
  let cmp: any;

  beforeEach(() => {
    cmp  = shallowMount(MyComponent, {
      localVue,
      router,
      mocks: {
        $route: {
          params: {
            id: 'id'
          }
        }
      }
    });
  });

  it('Should render a Vue instance', () => {
    expect.assertions(1);
    expect(cmp.isVueInstance()).toBeTruthy();
  });
});

my-component.spec.ts
import { createLocalVue, shallowMount } from '@vue/test-utils';
import MyComponent from '@/components/MyComponent.vue';

const localVue = createLocalVue();

describe('MyComponent', () => {
  let cmp: any;
  localVue.use(VueRouter);
  const router = new VueRouter();

  beforeEach(() => {
    cmp  = shallowMount(MyComponent, {
      localVue,
      router
    });
  });

  it('Should render a Vue instance', () => {
    expect.assertions(1);
    expect(cmp.isVueInstance()).toBeTruthy();
  });
});

Comment: I found the problem! In my component, I use a directive but I forgot to use it in my `localVue` instance.
Answer: You were mocking $route right in #1 test. You can access $route property of test component via wrapper.vm.$route (or cmp.vm.$route in your case). And There is example:
import { shallowMount, Wrapper } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'

let wrapper: Wrapper<MyComponent>

describe('MyComponent', () => {
  beforeEach(() => {
    wrapper = shallowMount(MyComponent, {
      mocks: {
        $route: {
          params: {
            id: 'id'
          }
        }
      }
    })
  })

  it('$route has passed params', () => {
    expect(wrapper.vm.$route.params.id).toBe('id')
  })
})

Comment: Sadly, I still had the error mocking $route and I don't really understand why
Comment: Strange.. Hope you have noticed that I am neither importing ```router``` object nor creating new instance of ```VueRouter``` in the test.
Comment: Yes, I did the same but I found the problem ! In my component, I use a directive but I forgot to use it in my localVue instance. The error didn't lead me to that at all but I finally solved it ! Thanks for your help Eduardo
Answer: I know I'm answering my question 2 years later but I thought it could help people with the same issue so here is how I've fixed it:
In my component, I used a directive but I forgot to use it in my localVue instance. The error didn't lead me to that at all. When you use a directive in your component, you should add
import directive from '@/directives/my-directive';

const localVue = createLocalVue();
localVue.directive('myDirective', directive);


Why can a null character be embedded in a conversion specifier for scanf?

Question: Perhaps I'm misinterpreting my results, but:
#include <stdio.h>

int
main(void)
{
    char buf[32] = "";
    int x;
    x = scanf("%31[^\0]", buf);
    printf("x = %d, buf=%s", x, buf);
}
$ printf 'foo\n\0bar' | ./a.out
x = 1, buf=foo

Since the string literal "%31[^\0]" contains an embedded null, it seems that it should be treated the same as "%31[^", and the compiler should complain that the [ is unmatched.  Indeed, if you replace the string literal, clang gives:
warning: no closing ']' for '%[' in scanf format string [-Wformat]
Why does it work to embed a null character in the string literal passed to scanf?
-- EDIT --
The above is undefined behavior and merely happens to "work".
Comment: Maybe the compiler (the static analyzer of it) is just not "trained" to interpret the `\0` inside string literals? It does not have to have a full format string interpreter.
Comment: What C library? glibc? Most probably when `]` is missing, it continues parsing. Still, it's your fault - [it's ub](https://port70.net/~nsz/c/c11/n1570.html#126.96.36.199p13). I get `x = 0, buf=` and it checks out with [glibc code](https://code.woboq.org/userspace/glibc/stdio-common/vfscanf-internal.c.html#2537).
Comment: I would say it doesn't work, for the reason you state.
Answer: First of all, Clang totally fails to output any meaningful diagnostics here, whereas GCC knows exactly what is happening - so yet again GCC 1 - 0 Clang.
And as for the format string - well, it doesn't work. The format argument to scanf is a string. The string ends at terminating null, i.e. the format string you're giving to scanf is
scanf("%31[^", buf);

On my computer, compiling the program gives
% gcc scanf.c
scanf.c: In function 'main':
scanf.c:8:20: warning: no closing ']' for '%[' format [-Wformat=]
    8 |     x = scanf("%31[^\0]", buf);
      |                    ^
scanf.c:8:21: warning: embedded '\0' in format [-Wformat-contains-nul]
    8 |     x = scanf("%31[^\0]", buf);
      |                     ^~

The scanset must have the closing right bracket ], otherwise the conversion specifier is invalid. If conversion specifier is invalid, the behaviour is undefined.
And, on my computer running it,
% printf 'foo\n\0bar' | ./a.out
x = 0, buf=

Q.E.D.
Comment: Isn't the question merely "why the compiler does not detect that the string with embedded `\0` is invalid?" Maybe I am misinterpreting it.
Comment: @EugeneSh. that doesn't match the behaviour however, it seems it is doing *something* on OPs computer...
Comment: I guess the `-Wformat-contains-nul` edit is the actual QED :)
Comment: My question originally was "why does it work", and the correct answer is "it is undefined behavior and just appears to work".
Comment: @WilliamPursell maybe you should add the operating system
Comment: @AnttiHaapala I'm doing this on Macos, but since it's UB it's probably not worth worrying about.
Comment: @EugeneSh. clang on my computer outputs no diagnostics by default <3 yay for "clang has so much better diagnostics" :D
Comment: I'm on MacOS also, and wonder of wonders, I can reproduce William's behavior perfectly.
Answer: This is a rather strange situation.  I think there are a couple of things going on.
First of all, a string in C ends by definition at the first \0.  You can always scoff at this rule, for example by writing a string literal with an explicit \0 in the middle of it.  When you do, though, the characters after the \0 are mostly invisible.  Very few standard library functions are able to see them, because of course just about everything that interprets a C string will stop at the first \0 it finds.
However: the string you pass as the first argument to scanf is typically parsed twice -- and by "parsed" I mean actually interpreted as a scanf format string possibly containing special % sequences.  It's always going to be parsed at run time, by the actual copy of scanf in your C run-time library.  But it's typically also parsed by the compiler, at compile time, so that the compiler can warn you if the % sequences don't match the actual arguments you call it with.  (The run-time library code for scanf, of course, is unable to perform this checking.)
Now, of course, there's a pretty significant potential problem here: what if the parsing performed by the compiler is in some way different than the parsing performed by the actual scanf code in the run-time library?  That might lead to confusing results.
And, to my considerable surprise, it looks like the scanf format parsing code in compilers can (and in some cases does) do something special and unexpected.  clang doesn't (it doesn't complain about the malformed string at all), but gcc says both "no closing ']' for '%[' format" and "embedded '\0' in format".  So it's noticing.
This is possible (though still surprising) because the compiler, at least, can see the whole string literal, and is in a position to notice that the null character is an explicit one inserted by the programmer, not the more usual implicit one appended by the compiler.  And indeed the warning "embedded '\0' in format" emitted by gcc proves that gcc, at least, is quite definitely written to accommodate this possibility.  (See the footnote below for a bit more on the compiler's ability to "see" the whole string literal.)
But the second question is, why does it (seem to) work at runtime?  What is the actual scanf code in the C library doing?
That code, at least, has no way of knowing that the \0 was explicit and that there are "real" characters following it.  That code simply must stop at the first \0 that it finds.  So it's operating as if the format string was
"%31[^"

That's a malformed format string, of course.  The run-time library code isn't required to do anything reasonable.  But my copy, like yours, is able to read the full string "foo".  What's up with that?
My guess is that after seeing the % and the [ and the ^, and deciding that it's going to scan characters not matching some set, it's perfectly willing to, in effect, infer the missing ], and sail on matching characters from the scanset, which ends up having no excluded characters.
I tested this by trying the variant
    x = scanf("%31[^\0o]", buf);

This also matched and printed "foo", not "f".
Obviously things are nothing like guaranteed to work like this, of course.  @AnttiHaapala has already posted an answer showing that his C RTL declines to scan "foo" with the malformed scan string at all.

Footnote:
Most of the time, an embedded in \0 in a string truly, prematurely ends it.  Most of the time, everything following the \0 is effectively invisible, because at run time, every piece of string interpreting code will stop at the first \0 it finds, with no way to know whether it was one explicitly inserted by the programmer or implicitly appended by the compiler.  But as we've seen, the compiler can tell the difference, because the compiler (obviously) can see the entire string literal, exactly as entered by the programmer.  Here's proof:
char str1[] = "Hello, world!";
char str2[] = "Hello\0world!";

printf("sizeof(str1) = %zu, strlen(str1) = %zu\n", sizeof(str1), strlen(str1));
printf("sizeof(str2) = %zu, strlen(str2) = %zu\n", sizeof(str2), strlen(str2));

Normally, sizeof on a string literal gives you a number one bigger than strlen.  But this code prints:
sizeof(str1) = 14, strlen(str1) = 13
sizeof(str2) = 13, strlen(str2) = 5

Just for fun I also tried:
char str3[5] = "Hello";

This time, though, strlen gave a larger number:
sizeof(str3) = 5, strlen(str3) = 10

I was mildly lucky.  str3 has no trailing \0, neither one inserted by me nor appended by the compiler, so strlen sails off the end, and could easily have counted hundreds or thousands of characters before finding a random \0 somewhere in memory, or crashing.
Comment: Let's just face it, clang has worse diagnostics :D
Answer:
Why can a null character be embedded in a conversion specifier for scanf?

A null character cannot directly be specified as part of a scanset as in "%31[^\0]" as the parsing of the string ends with the first null character.
"%31[^\0]" is parsed by scanf() as if it was "%31[^".  As it is an invalid scanf()
specifier, UB will likely follow.  A compiler may provide diagnostics on more than what scanf() sees.

A null character can be part of a scanset as in "%31[^\n]".  This will read in all characters, including the null character, other than '\n'.
In the unusual case of reading null chracters, to determine the number of characters read scanned, use "%n".
int n = 0;
scanf("%31[^\n]%n", buf, &n);
scanf("%*1[\n]"); // Consume any 1 trailing \n
if (n) {
  printf("First part of buf=%s, %d characters read ", buf, n);
}

Comment: @SteveSummit  Disagree with the hypothetical-ness and possible uses.  IAC, OP is certainly not a newbie.  This answers to a level that OP can handle.
Comment: @SteveSummit, I'm no C newbie, and I sometimes use `scanf` for things.  I don't handle character data with embedded null characters particularly frequently, but I would comfortable doing so.  I daresay C experts will be happy to use `scanf` when it is a good tool for the job. That may be rare, but not so rare as to be hypothetical.
Comment: @JohnBollinger, chux: Okay, I retract the comment.


Disable submit button until all fields are filled in Python Tkinter

Question: I'm currently working on a project and when my program launches it needs to get the names off of two players before beginning, the way my program is at the moment, it is possible to press submit without entering names, how do I prevent this?
Many Thanks Jayode18
<code># Program by Jack O'Donnell (Jayode18 StackOverflow/GitHub)
# Date Started: 16th March 2019

# Import winsound and create functions for each of the sound effects & their functionalities.
import tkinter
import time
from tkinter import *
import random
import winsound

def gameOver():
    winsound.PlaySound("Gameover", winsound.SND_FILENAME)

def pointsDrop():
    winsound.PlaySound("Points drop", winsound.SND_FILENAME)

def pointsGain():
    winsound.PlaySound("Points gain", winsound.SND_FILENAME)

def flipCoin():
    winsound.PlaySound("coinflip", winsound.SND_FILENAME)

def rollDice():
    winsound.PlaySound("Dice", winsound.SND_FILENAME)

# Other Definitions #
def goToPrimary():
    primaryWindow = tkinter.Tk()
    primaryWindow.iconbitmap("icon.ico")
    primaryWindow.geometry("500x500")
    primaryWindow.title("YGO Calculator ver. 1.0 ALPHA")

    gainLPButton = Button(primaryWindow, text = "LP Gain", command = pointsGain)
    gainLPButton.grid(row = 2, column = 1)

    loseLPButton = Button(primaryWindow, text = "LP Loss", command = pointsDrop)
    loseLPButton.grid(row = 2, column = 2)

    gameOverButton = Button(primaryWindow, text = "LP = 0", command = gameOver)
    gameOverButton.grid(row = 2, column = 3)

    flipCoinButton = Button(primaryWindow, text = "Coin Toss", command = flipCoin)
    flipCoinButton.grid(row = 2, column = 4)

    rollDiceButton = Button(primaryWindow, text = "Roll Dice", command = rollDice)
    rollDiceButton.grid(row = 2, column = 5)

# Button Commands #

def OnSubmit():
  e = entry_duelist.get()
  print(e)
  time.sleep(0.25)
  window.destroy()
  goToPrimary()

# import tkinter and create the window window, then populate it with buttons to text window.
window = tkinter.Tk()
window.resizable(width = False, height = False)
window.title("YGO Calculator ver. 1.0 ALPHA")
window.iconbitmap('icon.ico') # Give window the correct icon

mainWindow = Frame(window)

window.geometry("180x75")

label_duelist = Label(mainWindow, text="Duelist 1:")
label_duelist_2 = Label(mainWindow, text="Duelist 2:")

entry_duelist = Entry(mainWindow)
entry_duelist_2 = Entry(mainWindow)

label_duelist.grid(row = 4, column = 0)
label_duelist_2.grid(row = 5, column = 0)

entry_duelist.grid(row = 4, column = 1, columnspan = 4)
entry_duelist_2.grid(row = 5, column = 1, columnspan = 4)

submit_button = Button(mainWindow, text = "Submit", command = OnSubmit)

submit_button.grid(row = 7, column = 4, columnspan = 2)

mainWindow.grid(row = 5, column = 0)

window.mainloop()
</code>
All help would be amazing, thanks again! :D
Thank you everyone for your help. I managed to find a working solution!
Answer: You can check the entry texts for example
<code>if entry1.get() != "" And entry2.get() != "":
    # entries are not empty, do something
</code>
Comment: You typed `And` with an uppercase 'A', is this a typo?


Java, second print output is different than the rest, based on a loop

Question: I'm trying to write a program where it asks the user to enter integers and to keep entering them until the user enters a Q. After every input, the program should prompt with the string: "Enter an integer, or Q to quit: ".
On my terminal, every second out.print only prompts the user for input and not the string to ask for the input. For example, output would look like this:

Enter an integer, or Q to quit: 90
  80
  Enter an integer, or Q to quit: 100
  Enter an integer, or Q to quit: 25
  Enter an integer, or Q to quit: 7
  Enter an integer, or Q to quit: Q

My code is as follows...
<code>    Scanner in = new Scanner(System.in);

    System.out.print("Enter an integer, or Q to quit: ");

    int largest = in.nextInt();

    if (in.hasNextInt())
    {

        while (in.hasNextInt())
            {

                int input = in.nextInt();
                if(input > largest)
                {
                    largest = input;
                }

                System.out.print("Enter an integer, or Q to quit: ");

            }
    }

    System.out.println(largest);
</code>
My first guesses were the ordering of certain statements, but I haven't had any luck. Any suggestions?
Answer: The problem is that you are waiting for two numbers... change it to as follows:
<code>        Scanner in = new Scanner(System.in);

        System.out.print("Enter an integer, or Q to quit: ");
        int largest = Integer.MIN_VALUE;

        while (in.hasNextInt())
        {
            int input = in.nextInt();
            if (input > largest)
            {
                largest = input;
            }

            System.out.print("Enter an integer, or Q to quit: ");

        }

        System.out.println(largest);
</code>
The problem with your previous version of the code was that you were expected 2 numbers initially, one of them being the largest value.


Help with a residue integration problem. Complex analysis

Question: I have to prove this using the residue theorem, but I don't know which contour I have to use. I also have problems finding which function I have to consider, but I suppose is something related with the exponential because of the sinus of the result. Any advice?
$$\int_{0}^{\infty}\frac{t^{a-1}}{1 + t}dt = \frac{\pi}{{sin}(\pi a)} \; \; \;  \forall a \in (0, 1).$$
Thank you!
Comment: For one thing, you should be able to choose any contour that connects your limits of integration.
Answer: First note that by a change of variables we can write
$\displaystyle \int_0^\infty \frac{t^{a-1}}{1+t}dt = \int_{-\infty}^\infty \frac{e^{ax}}{1+e^{x}}dx$ by setting $t = e^x$.
Then integrate the function $\displaystyle f(z) = \frac{e^{az}}{1+e^z}$ along a rectangle, lying on the real axis ("centered" at the origin) going out a distance of $R$ to both sides, and with a height of $2\pi i$.
The only pole in this contour is at $\pi i$, and the residue of $f$ at $\pi i$ is $\displaystyle \lim_{z\to \pi i} (z-\pi i)\frac{e^{a\pi i}}{e^z - e^{\pi i}} = e^{a\pi i} \lim_{z \to \pi i} \frac{z-\pi i}{e^z - e^{\pi i}} = -e^{a\pi i}$. Do you see why? Note that I used the fact that $e^{i\pi}=-1$.
You can show that along the vertical sides go to $0$ as $R \to \infty$, and moreover the integral along the top segment of the rectangle is a complex multiple of the integral along the bottom segment (the one you want). Factor, and you'll have it.
Comment: Got it! Thank you very much!


Terminal color using terminfo?

Question: I am writing a C++ class permitting the usage of color in terminal. I want it works on every terminal :

printing with true color (24 bits) on terminals that supports it,
with 256 color (6x6x6) on terminals that supports it,
else with the basic 16 colors.

I wrote once C functions using termcap, and I thought using it in this case. However, the man page says :

The termcap database is an obsolete facility for describing the capabilities of character-cell terminals and printers. It is retained only for capability with old programs; new ones should use the terminfo database and associated libraries.

So I tried to use terminfo, but I could not find how to do this. There is not terminfo.h in my system (I run on Debian).
My questions is :
How can I get the color possibilities of the current terminal in C/C++, using the newest tools (ie not termcap, according to manpage) ?
Comment: AFAIK, you have to include `curses.h` and `term.h`. You should look for `man tgetent` on your system.
Comment: Not necessarily on recent systems. [die.net] says for `man getent` *tgetent, tgetflag, tgetnum, tgetstr, tgoto, tputs - direct curses interface to the terminfo capability database*, and so does my FreeBSD 10.1 box.
Comment: Are not they termcap functions ?
Comment: Ok : so, I already known that function. But, there is no way to have the truecolor possibility, as far as i can see, with this set of functions.
Answer: The short answer is that you could not get the information from terminfo until ncurses 6.1 was released in January 2018.
The longer answer:

to effectively use TrueColor, you need an interface handling 3 parameters (for red, green, blue).  Termcap cannot do this. Terminfo can handle multiple parameters, but...
there is no standard terminal capability (a name for a feature which may be a boolean, number or a string) dealing with TrueColor as such.
you could adapt existing capabilities, but they have limitations

Looking at the terminfo(5) manual, you might see these (strings):
   initialize_color          initc  Ic   initialize color #1
                                         to (#2,#3,#4)
   initialize_pair           initp  Ip   Initialize color
                                         pair #1 to
                                         fg=(#2,#3,#4),
                                         bg=(#5,#6,#7)

which are related to these (numbers):
   max_colors                colors Co   maximum number of
                                         colors on screen
   max_pairs                 pairs  pa   maximum number of
                                         color-pairs on the
                                         screen

ANSI colors and schemes compatible with those (such as 16-, 88- and 256-colors) assume you are coloring foreground and background in pairs.  The reason for that was that long ago, hardware terminals just worked that way.  The initialize_color capability is for a different scheme (Tektronix), which might seem useful.
However, terminfo is compiled, and the resulting binary files stored only signed 16-bit integers.  You could not use the terminal description to store a suitable max_pairs or max_colors for 24-bit color.  (termcap stores everything as strings, but as noted is unsuited for this application).
A couple of years after this question and answer were first written, terminfo was updated to use a new file format that uses signed 32-bit integers, which is enough for expressing the number of colours in 24-bit RGB colour.
More details can be found in release announcement for ncurses 6.1 and in the updated term(5) manual page, which latter notes that there are still restrictions in the old API used by some applications that access the terminfo data directly.
Further reading:

Why only 16 (or 256) colors? (ncurses FAQ)
Can I set a color by its number? (xterm FAQ)
Is ncurses terminfo compatible with my system? (ncurses FAQ)
Comment: >  "signed 16-bit integers."
Is this mentioned anywhere that it stores them in signed 16 bit rather than unsigned. I was hoping to find it somewhere but only search result is this answer for me.
Comment: man [term(5)](http://invisible-island.net/ncurses/man/term.5.html) refers to "short integers" (if they were unsigned, it would be noted there).

Terminal color using terminfo?


Using theme hook, how do I get block contents into the $comm line?

Question: if ( isset($vars['content']['#block_content']) ) { // check for custom content
    if ($vars['content']['#block_content']->type[0]->getValue()['target_id'] == 'js_file_block') { // only run on js_file_block types
      $storage = \Drupal::entityTypeManager()->getStorage('block-content');
      $comm = current($storage->loadByProperties(['type' => 'block']));
      $route_match = \Drupal::routeMatch();
      $vars['inlinejs2'] = array();
      if ($comm !== false) {
        foreach ($comm->get('field_js_url') as $script_block) {
          $vars['inlinejs2'][] = $script_block->value;
        }
      }
    }
  }

I dont know what I am doing wrong, but it will not make the array.
Answer: If you try to access the entity in a template preprocess hook, there is a much simpler way:
function MYTHEME_preprocess_block(array &$variables) {
  // check for custom content block
  if ($variables['base_plugin_id'] == 'block_content') {
    // the entity is alreary availale in the preprocess hook, no need for another query
    $blockContentEntity = $variables['elements']['content']['#block_content'];
    // my advice: pass the entire entity to the template, so you can access all the block fields
    // in Twig without further preprocessing, similar to node templates, e.g.
    // {{ block_content.field_whatever.0.value }}
    $vars['block_content'] = $blockContentEntity;
    // further processsing only for custom content blocks of type 'js_file_block'
    if ($blockContentEntity && $blockContentEntity->bundle() == 'js_file_block') {
        //...whatever you need in here...
    }
  }
}

Answer: THis code works for me.

function MYTHEME_preprocess_block(&$variables) {
    if ($content['#block_content']->bundle() == 'megamenu_image_video_block') {
      if(isset($content['#block_content']->get('field_select_campaign')->target_id) && !empty($content['#block_content']->get('field_select_campaign')->target_id)) {
        $selectedCampaign = node_load($content['#block_content']->get('field_select_campaign')->target_id);
        $variables['headerMegamenuCampaignTitle'] = $selectedCampaign->get('title')->value;
      }
    }
}


Make second card in card-columns fill all remaining width

Question: I am new to Bootstrap (and web development in general) and I am trying to achieve the following effect:

Part of my code is:

Dashboard

Check your app stats by country

                    <select id="country-select" class="form-control form-select form-select-lg mb-3" aria-label=".form-select-lg example">
                        <option selected>Select a country</option>
                    </select>

Chart

Check your app stats by country

                    <canvas id="myChart" width="400" height="400"></canvas>

My Bootstrap version is 4.6 and the full code is available on JSFiddle
Comment: Should the graph block grow proportionally in height?
Comment: That'd be good. For the moment, I am trying to use a flexbox, no card-columns. I honestly have no idea what's the best approach.
Answer: Your problem was using class card-columns, which strictly divides your cards into three columns, the column-count: 3 rule.
Flex will be preferable for your task. Instead of class card-columns, I have specified flexibility classes. Here:

Also, for indentation, I used the gap rule, adding this selector to the css.
For the second div with class card, I added the flex-sm-grow-1 class to allow this div to take up all of the free space.

.container-fluid > .d-flex.align-items-sm-baseline {
    gap: 20px;
}

@media (max-width: 767px) {
    .container-fluid > .d-flex.align-items-sm-baseline {
        flex-direction: column !important;
        align-items: stretch !important;
    }
}
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <title>Android Rank Checker</title>

        <link rel="stylesheet" href="https://email@example.com/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous" />

        <link rel="stylesheet" href="style.css" />

                Android Rank Checker

Dashboard

Check your app stats by country

                                <select id="country-select" class="form-control form-select form-select-lg mb-3" aria-label=".form-select-lg example">
                                    <option selected>Select a country</option>
                                </select>

Chart

Check your app stats by country

                                <canvas id="myChart" width="" height=""></canvas>

Comment: Thank you so much! Is there a way to prevent the chart from filling all available height of the screen? I'd also like to make the flexbox wrap (have the chart under the  when not on a computer. Do you know how to do it? Thanks again in advance and sorry for the inconvenience!
Comment: @xvlaze, no problem. Yes, it can be fixed if you remove the **height** and **width** values from ``. I have updated the answer. Check, pls.
Comment: @xvlaze, and I added a media query to your css. The template is now responsive. Breakpoint - 767px.
Comment: Absolute genius work. Thank you very much!! :)
Answer: You should have 2 columns, you have 3.
@media (min-width: 576px)
.card-columns {
    -webkit-column-count: 2;
    -moz-column-count: 2;
    column-count: 2;
    -webkit-column-gap: 1.25rem;
    -moz-column-gap: 1.25rem;
    column-gap: 1.25rem;
    orphans: 1;
    widows: 1;
}

Comment: I'm afraid this is not the solution.
Answer: I would use Bootstraps grid system.
Solution: https://jsfiddle.net/b459x1uy/2/

        // Dashboard card

        // Chart card

Wrap your cards with columns. In this example first column (.col-4) takes 12/4 of the width, second column (.col) takes all the available space on that row.
Using Bootstrap columns gives you also control about the responsive layout in one go. I would not write extra CSS to size your columns without considering Bootstraps grid system first.
Comment: I'm sorry but I'm looking for the chart to be on the same row as the . This just puts the chart under the select.
Comment: It does keep them on one row. Did you look at the jsfiddle example I made?
Comment: It might be a display issue, but the output of the JSFiddle shows the cards in one column no matter the output window size.


How to use css variable colors and js to change div background

Question: So this is a very basic function (found and edited for my purposes) that alternates the div background color to white or black.
I would like to change the code to utilize the css variables I have in the root property and have no onClick functions inside the html. I want to keep html and js seperate, but I don't know how to go about this.
Can I have two buttons that can switch between the css variable colors for the div?
Thank you.

function changeColor(color) {
  var element = document.getElementById('box');
  element.style.backgroundColor = color;
}
root {
  --white { color: #fff}
  --black { color: #000}
}

.box {
  width: 100px;
  height: 100px;
  border: 1px solid #aaa;
  background-color: #fff;
}

<button onClick=changeColor('white')>white</button>
<button onClick=changeColor('black')>black</button>
Comment: You want to access `css` properties?
Comment: @Maheer Ali that is my question, yes. Also, removing js from html while using css variables to change color of div bg
Answer: You can set one css variable and onclick change the color.
Use  document.body.style.setProperty('--main-color',color) to set color to var

function changeColor(color) {
  document.body.style.setProperty('--main-color',color)
}
root {
  --main-color{ color: #fff}
}

.box {
  width: 100px;
  height: 100px;
  border: 1px solid #aaa;
  background-color: var(--main-color);
}

<button onClick=changeColor('white')>white</button>
<button onClick=changeColor('black')>black</button>
Comment: I dont want to use js in the html
Comment: you mean that you don't want use function? but you  must you can do it shortly `white`
Answer: You can add a data-color attribute to your buttons which specifies the color (variable) to change to when clicking on the given button. Then you can add the click event listener to all your buttons with the class color-btn. Then when you click on a given button the event listener will be called, which will get the data attribute from the button clicked, and then use your changeColor function to change the div to the appropriate color (using the variable).
Also, you haven't defined your variables correctly. Firstly, you need to target the root using :root. Then you nee to set your variables using --variableName: COLOR. Lastly, in your changeColor function you need to use .style.backgroundColor = "var(--" +color +")" to correctly use the variable.
See working example below

[...document.getElementsByClassName("color-btn")].forEach(elem => {
  elem.addEventListener('click', function() {
    const btnColor = this.getAttribute('data-color');
    changeColor(btnColor);
  });
})

function changeColor(color) {
  var element = document.getElementById('box');
  element.style.backgroundColor = "var(--" +color +")";
}
:root {
  --w: #fff;
  --b: #000;
}

.box {
  width: 100px;
  height: 100px;
  border: 1px solid #aaa;
  background-color: #fff;
}

<button class="color-btn" data-color='w'>white</button>
<button class="color-btn" data-color='b'>black</button>
Comment: this seems like a great example for me to use. Thank you!
Answer: Register an onClick event on those buttons (you would have to assign a unique ID to them to reference them properly)
Example:
document.getElementById("myBtn").addEventListener("click", changeColor("white"));

edit
I see you're using jQuery, so:
$("#myBtn").on( "click", function() {
  changeColor("white");
});

That way your HTML doesn't have JS in it. You would have 2 events, one for each button.
Answer: <!DOCTYPE html>

    <button onClick=changeColor('white')>white</button>
    <button onClick=changeColor('black')>black</button>


Internal server error 500

Question: I can't view my admin area and blog
<code>[19-Mar-2020 15:54:42 UTC] PHP Warning:  require(/home/medicine/public_html/wp-includes/version.php): failed to open stream: No such file or directory in /home/medicine/public_html/wp-settings.php on line 24
[19-Mar-2020 15:54:42 UTC] PHP Warning:  require(/home/medicine/public_html/wp-includes/version.php): failed to open stream: No such file or directory in /home/medicine/public_html/wp-settings.php on line 24
[19-Mar-2020 15:54:42 UTC] PHP Fatal error:  require(): Failed opening required '/home/medicine/public_html/wp-includes/version.php' (include_path='.:/opt/alt/php72/usr/share/pear') in /home/medicine/public_html/wp-settings.php on line 24
</code>
Answer: Do you have permissions to do an
<code>ls
</code>
on /opt/alt/php72/usr/share/pear
I doubt if the files are there
A reinstall would probably fix the issue
Comment: Sir now my host install new WordPress.

Internal server error 500


Check a revision exists for a node

Question: How do I check there is a revision exists for a node? I can load the node details using the following code.
$nid = "my_node_id";
$node_details = \Drupal\node\Entity\Node::load($nid);

How do I check if there is a revision for a node? Putting it differently: How can I get the revision ID of a node after creating a new revision?
I create a new revision using this code.
  $original_revision = \Drupal\node\Entity\Node::load($nid);
  $original_revision->my_field_to_be_modified= "my_value";
  $original_revision->setNewRevision(TRUE);
  $original_revision->setRevisionCreationTime($time_stamp);
  $original_revision->save();

Answer: Use getRevisionId(); The revision identifier of the entity, or NULL if the entity does not have a revision identifier.
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21RevisionableInterface.php/function/RevisionableInterface%3A%3AgetRevisionId/8.2.x
Answer: alter way query form database and check $count if 1 mean it exists else 0
$count = \Drupal::database()
        ->select('node_revision')
        ->condition('vid', {revision_number})
        ->countQuery()->execute()->fetchField();

Check a revision exists for a node


If $f(g(x))=\sqrt {x^2-2x+8}$ and $f(x)=\sqrt x,$ find $g(x)$.

Question:
If $f(g(x))=\sqrt {x^2-2x+8}$ and $f(x)=\sqrt x,$ find $g(x)$.

There is no example like this in my math book.
Answer: HINT:
$$f(x)=\sqrt x\implies f(x^2-2x+8)=\sqrt{x^2-2x+8}$$
Answer: Maybe it will help you to see what $g(x)$ must be by the following: $$f(g(x)) = \sqrt {g(x)} = \sqrt{x^2 - 2x + 8}$$
Spoiler:

 $$g(x) = x^2 - 2x + 8$$
Comment: @amWhy. So is the answer x^2-2x+8?
Comment: @CSES: Yes, that's $g(x)$.
Comment: Yes, $g(x) = x^2 - 2x + 8$.
Comment: I guess I thought it was going to be harder. Thanks amWhy and @rubik
Comment: You're welcome, CSES!


How to update specific flutter SDK channel?

Question: Currently, i m using flutter 3.3.9 i want to update it to 3.7.3
Any particuler command?
Note : I don't want to affect my current code
Need perment solution for it.
Answer: For these cases, try to use FVM (Flutter Version Management).
fvm install 3.7.3
fvm use 3.7.3

For get more detail here its official website https://fvm.app/
The advantages is you can any cases you can simply go back to your previous flutter version. And also you can work different flutter project with different version
Comment: @RandalSchwartz I haven't work with it. But seems to be amazing. Will try it.
Answer: Change channel if you are not in correct channel otherwise go to step 4

Open a terminal or command prompt on your computer.

Check the available Flutter channels by running the command flutter channel.
This will show you the list of available channels and the current channel you are on.

Switch to the desired channel by running the command flutter channel <channel-name>.

For example, to switch to the stable channel, you can run flutter channel stable.

Choose the version.
This is possible now with flutter version. In the console do flutter version to list the versions available. Then choose a version to switch to: flutter version v3.7.3
Comment: i want to update specific channel... not want to switch
Comment: `flutter version` is not supported anymore


Return data when not all values in column are equal

Question: I have a simple table which looks like this:
| yyyy_mm_dd | id | name     | count |
|------------|----|----------|-------|
| 2020-10-31 | 1  | price    | 90    |
| 2020-10-31 | 1  | restrict | 90    |
| 2020-10-31 | 1  | checkin  | 90    |
| 2020-10-31 | 2  | price    | 322   |
| 2020-10-31 | 2  | restrict | 322   |
| 2020-10-31 | 2  | checkin  | 311   |
...

How can I construct a query that will return the ids that do not have the same count for each name? So using the above data, id 2 would be returned as not all name counts are equal.
It would be great if it's possible without hardcoding each name individually as there are a lot in the real dataset.
Answer: A simple method is aggregation:
select name
from t
group by name
having min(count) <> max(count);

If you want to be sure there are three rows, then add and count(*) = 3.
Comment: Actually, I think you should do `!=` here but a minor change anyway. With `=`, all rows with the same count will be returned instead of instead of those where the count differs.


htaccess redirect specific url to another domain

Question: I want to redirect specific URL with params to another domain
http://domain.tld/buy/?w=X1234 to http://anotherdomain.tld/product.php?id=X1234
Here my htaccess
RewriteCond %{REQUEST_URI} !^/*buy/(.*)$ [NC]
RewriteRule ^/*buy/?w=([a-zA-Z0-9]+)$ http://anotherdomain.tld/product.php?id=$1 [NC,L,R=301]

but not working. maybe the problem is param ?w=
Thank you
UPDATE: i solve the problem by using Query string, after reading How to REGEX and .htaccess rewrite url
RewriteCond %{QUERY_STRING} ^w=([a-zA-Z0-9]+)$
RewriteRule ^/*buy/$ http://anotherdomain.tld/product.php?id=%1 [NC,L,R=301]

Thank you stackoverflow and folks! i m start understanding regex from here ^_^
Answer: That's right, your params won't be picked up, but they can be passed on.
Something like;
RewriteRule ^buy/([a-zA-Z0-9]+)$ http://anotherdomain.tld/product.php?id=$1 [NC,L,R=301]

Where your original url would be; /buy/X1234
Comment: I m not allowed to change the w params. How to make `?w=` as string in htaccess regex


How to make the Webform submit button use an uploaded submit-image?

Question: I am building a D7 website and I want the following feature for the site admin, regarding the Webform module:
When the admin creates a webform, the admin uploads a submit-image and this image is used as the submit button for the webform. so if he uploads a "click-me.png" I want the path to this image to be used in the input[type=image] class="form-submit" src="/path to uploaded image"
Is there a simple way to achieve this, or do I have to seperately hardcode the behaviour I want for each webform?
P.S. By default webform's submit button is of type "text" and not "image", but I easily managed to change this using this excellent solution.
Answer: The easiest way to do this would be to write your own module. The place to start looking would be here: http://drupalcontrib.org/api/drupal/contributions!webform!webform.api.php/function/hook_webform_component_info_alter/7
Comment: what you propose is reasonable although in drupal there are so many modules and ways to achieve a goal that I wouldn't be surprised if I am missing sth ready or almost-ready for my case.
Comment: I'd say your case is pretty unique. I don't think you'll be able to find an out-of-the box solution unfortunately. This is probably pretty simple to achieve. I would include an upload field on your image, then it would probably be only a few lines of code from the webform API to tell it to use that image as the button image vs. the default. If you never made your own module, look here: https://drupal.org/node/1074360. One of things that makes Drupal great is it's "hook" based API system. Meaning it's pretty easy to alter default behavior like this and not need a ton of programming experience.


OpenMP atomic substantially slower than critical for array

Question: The examples that I have seen for OpenMP's omp atomic generally involve updating a scalar, and usually report that it is faster than omp critical. In my application I wish to update elements of an allocated array, with some overlap between the elements that different threads will update, and I find that atomic is substantially slower than critical. Does it make a difference that it is an array, and am I using it correctly?
#include <stdlib.h>
#include <assert.h>
#include <omp.h>

#define N_EACH 10000000
#define N_OVERLAP 100000

#if !defined(OMP_CRITICAL) && !defined(OMP_ATOMIC)
#error Must define OMP_CRITICAL or OMP_ATOMIC
#endif
#if defined(OMP_CRITICAL) && defined(OMP_ATOMIC)
#error Must define only one of either OMP_CRITICAL or OMP_ATOMIC
#endif

int main(void) {

  int const n = omp_get_max_threads() * N_EACH -
                (omp_get_max_threads() - 1) * N_OVERLAP;
  int *const a = (int *)calloc(n, sizeof(int));

#pragma omp parallel
  {
    int const thread_idx = omp_get_thread_num();
    int i;
#ifdef OMP_CRITICAL
#pragma omp critical
#endif /* OMP_CRITICAL */
    for (i = 0; i < N_EACH; i++) {
#ifdef OMP_ATOMIC
#pragma omp atomic update
#endif /* OMP_ATOMIC */
      a[thread_idx * (N_EACH - N_OVERLAP) + i] += i;
    }
  }

/* Check result is correct */
#ifndef NDEBUG
  {
    int *const b = (int *)calloc(n, sizeof(int));
    int thread_idx;
    int i;
    for (thread_idx = 0; thread_idx < omp_get_max_threads(); thread_idx++) {
      for (i = 0; i < N_EACH; i++) {
        b[thread_idx * (N_EACH - N_OVERLAP) + i] += i;
      }
    }
    for (i = 0; i < n; i++) {
      assert(a[i] == b[i]);
    }
    free(b);
  }
#endif /* NDEBUG */

  free(a);
}

Note that in this simplified example we can determine in advance which elements will overlap, so it would be more efficient to only apply atomic/critical when updating those, but in my real application this is not possible.
When I compile this using:

gcc -O2 atomic_vs_critical.c -DOMP_CRITICAL -DNDEBUG -fopenmp -o critical
gcc -O2 atomic_vs_critical.c -DOMP_ATOMIC -DNDEBUG -fopenmp -o atomic

and run with time ./critical I get:
real    0m0.110s user    0m0.086s sys 0m0.058s
and with time ./atomic, I get:
real    0m0.205s user    0m0.742s sys 0m0.032s
So it uses about half the wallclock time with the critical section (and I get the same when I repeat it).
There is another post that claims critical is slower than atomic, but that uses a scalar, and when I run the provided code the atomic result is actually slightly faster than the critical one.
Answer: Your comparison is not fair: the #pragma omp critical is placed before the for loop, so the compiler can vectorize your loop, but #pragma omp atomic update is inside the loop, which prevents vectorization. This difference in vectorization causes the surprising runtimes. For a fair comparison place both inside the loop:
for (i = 0; i < N_EACH; i++) {
#ifdef OMP_CRITICAL
#pragma omp critical
#endif /* OMP_CRITICAL */
#ifdef OMP_ATOMIC
#pragma omp atomic update
#endif /* OMP_ATOMIC */
   a[thread_idx * (N_EACH - N_OVERLAP) + i] += i;
}

Due to this vectorization issue, most probably runtime of your real program will be the shortest if you use single thread only.
Comment: I agree with your assessment. To expand on the difference in cost: The atomic update will compile into a ```lock add``` instruction. This has a throughput of 1 per 18 clock cycles on current Intel CPUs, and this isn't even factoring in the negative effects on the cache. The crittical section instead compiles into a SSE2 or AVX ```paddd``` instruction with throughput of 4-16 ints per clock cycle. So, if the array is large enough, the cost of the critical section is dwarfed by the sheer difference in per-thread performance, especially for low thread counts.
Comment: Thank you for your thoughts, and you are right that critical is slower when it is inside the loop. I'm not sure I agree that my comparison is "not fair", though: I believe this is how one would use critical and atomic in this case, so in practice for this situation critical is faster. I cannot use a single thread as in my real application there are other calculations within the parallel section that do benefit from multithreading.
Comment: OK, you are welcome. Why don't you use -O3 (or -Ofast) and e.g. -mavx2 compiler flags?


Proving the representability of a functor, which is covered by open subfunctors

Question: I want to prove Theorem 8.9 from Algebraic Geometry I ( U.Görtz, T.Wedhorn), which reads as follows:
Let $S$ be a scheme  $F: Sch/S°\rightarrow Set $ a functor such that:

F is a sheaf for the Zariski topology
F has a cover by open subfunctors  $\alpha_i:F_i\rightarrow F$, such that every $F_i$ is representable by a scheme $X_i$

Then F is representable.
A cover by open subfunctors means, that for every scheme $T$ and for every morphism $h_T\rightarrow F$, the pullback $F_i\times_F h_T$ is representable, say by $Y_i$ and the morphism of schemes $Y_i\rightarrow T$ corresponding to the projection $F_i\times_F h_T\rightarrow h_T$ is an open immersion. In addition the images of $Y_i\rightarrow T$ form an open covering of $T$
Let me explain what I have done so far and where I am stuck:
The $X_i$ can be glued to a scheme $X$.
The morphisms $h_{X_i}\cong F_i\rightarrow F$ correspond via the yoneda lemma to elements $f_i\in F(X_i)$.  Using the sheaf property of F, the $f_i$ glue together to an element $f\in F(X)$ which gives us a natural transformation $\alpha: h_X\rightarrow F$. For a scheme $T$ and a morphism $g\in\mathrm{Hom}(T,X)$ this is given by $\alpha(T)(g)=F(g)(f)$. The last step is to show that this assignment is bijective. I managed to show the surjectivity, but can't find a proof for the injectivity. It would suffice to show that the following diagram is a pullback
$\require{AMScd}$
\begin{CD}
h_{X_i} @>>> h_X\\@VidVV @VV\alpha V\\ h_{X_i} @>>> F
\end{CD}
where the morphism $h_{X_i}\rightarrow h_X$ is induced from the open immersion $X_i\rightarrow  X$. I tried to prove this with ideas similiar to the answer of
Representable open immersion of functors is a monomorphism.
I also looked at the proof in EGA I (Springer edition 1971), where this is Proposition 4.5.4 in chapter 0. From what I understand, it is also used, that this square is a pullback, but not commented on why this is indeed a pullback.
I am thankful for any idea on how to proove the injectivity or the fact, that this square is a pullback.
Comment: I recently learned this proof in class! I'll try to answer tomorrow; I'm unfortunately too busy tonight
Comment: Now posted on MathOverflow: [Proving the representability of a functor that is covered by open subfunctors](https://mathoverflow.net/q/333480)
Answer: I found another way to prove this Theorem, which then also shows that this map is injective. Consider two Zariski sheaves $F,G:\mathrm{Sch}^{\circ}\rightarrow\mathrm{Set}$ and for each sheaf a cover by open subfunctors $\alpha_i:F_i\rightarrow F$ and $\beta_i:G_i\rightarrow G$. Suppose  we have isomorphisms $\varphi_i: F_i\rightarrow G_i$, such that the diagram
$\require{AMScd}$
\begin{CD}
F_i\times_FF_j @>>> F_i @>\varphi_i>> G_i\\@VVV  @. @VV\beta_iV \\ F_j @>\varphi_j>> G_j @>\beta_j>>G
\end{CD}
commutes and the induced morphism $F_i\times_F F_j\rightarrow F_i\times_G F_j$ is an isomorphism. Then $F\cong G$. The proof of this statement is similiar to the situation, where $F$ and $G$ are sheaves on a topological space and $\varphi_i:F_{|U_i}\rightarrow G_{|U_i}$ are isomorphisms of sheaves agreeing on overlaps. We can apply this to the functor $h_X$ with open cover $h_{U_i}\rightarrow h_X$ and the functor $F$ with open cover $\alpha_i:F_i\rightarrow F$. One can check that the isomorphisms $h_{U_i}\cong F_i$ satisfy the conditions above. In this way we obtain an isomorphism $h_X\rightarrow F$. The yoneda lemma implies, that this morphsim is actually the same as the morphism defined in my question.