how to update symfony2/doctrine entity from a @Groups inclusion policy JMSSerializer deserialized entity

Question: I'm trying to update symfony2/doctrine entities using JMSSerializer with an @ExclusionPolicy:None @Groups Inclusion Policy.
 * @Serializer\ExclusionPolicy("none")
 */
 class Foo
 {
    /**
     * @Serializer\Groups({"flag","edit"})
     */
    protected $id;

    /**
     * @Serializer\Groups({"edit"})
     */
    protected $name;

    /**
     * @Serializer\Groups({"flag"})
     */
    protected $flag;

    /**
     * @Serializer\Exclude()
     */
    protected $createdBy;
 }

reference: http://jmsyst.com/libs/serializer/master/reference/annotations
the result for the following record:
Foo (id:1, name:'bar', flagged:false ,created_by:123)

is serialized using Group inclusion to avoid serializing information I don't need (associations, blobs, etc..) so when I want to update an entity I deserialize only the updated fields of the entity from the JSON.
$foo->setFlagged(true);
$data = $serializer->serialize($foo, 'json', SerializationContext::create()->setGroups(array("flag")));

result:
{id:1,flagged:true}

which when passed back to the application deserializes into the entity
$foo = $serializer->deserialize($jsonFoo,'Foo','json');

result:
Foo (id:1, name:null, flagged:true, created_by:null)

The problem is when I try to merge the entity back into the doctrine entity manager:
$foo = $em->merge($foo);
$em->persist($foo);
$em->flush();

The resulting foo is trying to update excluded properties (name,created_by) with null.
How do I tell JMSSerializer or Doctrine Entity Managers merge that I don't want to overwrite existing properties with null?
Comment: the only option I found fo far http://stackoverflow.com/questions/8726611/how-to-update-a-doctrine-entity-from-a-serialized-json which means bypassing the JMSSerializers deserialize and checking it/updating the entity manually (in this examples case bypassing the setters).
Answer: I found the answer.
$serializer is a service created by the symfony2 integration bundle JMSSerializerBundle.
The default service is jms_serializer.serializer initializes the JMSSerializer with the default Object Constructor UnserializeObjectConstructor and for doctrine I needed to deserialize with the DoctrineObjectConstructor.
because I only use JMSSerializer in the project for serialize/deserialize of doctrine entities, I overwrote JMSSerializerBundle's jms_serializer.object_constructor with the alias of the proper object constructor service.
<service id="jms_serializer.object_constructor" alias="jms_serializer.doctrine_object_constructor" public="false"/>

Is there a better way to configure what object constructor the serializer uses?
I also added the proper context to deserialize:
$serializer->deserialize($jsonFoo,'Foo','json', DeserializationContext::create()->setGroups(array('flag')));

result:
Foo (id:1, name:'bar', flagged:true ,created_by:123)

Using the doctrine object constructor, it figures out that I want to find the object and only apply updates to fields provided in $jsonFoo (and the flag group). This totally eliminates the need for doctrines entity manager merge and I can just persist the object properly.
$em->persist($foo);
$em->flush();

Answer: in addition to @Heyflynn's answer (thanks!), I needed this to work with doctrine_mongodb, so I modified my services.yml as follows:
services:
    jms_serializer.doctrine_object_constructor:
        class:        %jms_serializer.doctrine_object_constructor.class%
        public:       false
        arguments:    ["@doctrine_mongodb", "@jms_serializer.unserialize_object_constructor"]

    jms_serializer.object_constructor:
        alias: jms_serializer.doctrine_object_constructor

important fact is the @doctrine_mongodb as argument for jms_serializer.doctrine_object_constructor instead the original doctrine parameter in the bundle's services.xml:
    <service id="jms_serializer.doctrine_object_constructor" class="%jms_serializer.doctrine_object_constructor.class%" public="false">
        <argument type="service" id="doctrine"/>
        <argument type="service" id="jms_serializer.unserialize_object_constructor"/>
    </service>
    <service id="jms_serializer.unserialize_object_constructor" class="%jms_serializer.unserialize_object_constructor.class%" public="false" />
    <service id="jms_serializer.object_constructor" alias="jms_serializer.unserialize_object_constructor" public="false" />

Answer: To use JMS deserializer for MongoDB documents and ORM entities you can use
jms_serializer.doctrine_mongodb_object_constructor:
    class:        %jms_serializer.doctrine_object_constructor.class%
    public:       false
    arguments:    ["@doctrine_mongodb", "@jms_serializer.unserialize_object_constructor"]

jms_serializer.doctrine_object_constructor:
    class:        %jms_serializer.doctrine_object_constructor.class%
    public:       false
    arguments:    ["@doctrine", "@jms_serializer.doctrine_mongodb_object_constructor"]

jms_serializer.object_constructor:
    alias: jms_serializer.doctrine_object_constructor
    public: false

As you see in jms_serializer.doctrine_object_constructor second argument (fallbackConstructor) is jms_serializer.doctrine_mongodb_object_constructor it means that if your object isn't entity then jms will try to use fallbackConstructor and if your deserialised object isn't Document either then will be used default unserialize_object_constructor
if you deserialize entity
$em->persist($foo);
$em->flush();

if document
$dm->persist($foo);
$dm->flush();


Conditional clauses with Entity field Query

Question: I have a syntax issue on using conditional clauses with EFQ, but the documentation on drupal.org is a bit unclear for me. I have google the whole Internet for this with no results at all. My hook implementation is based on another drupal.stackexchange question
The code works for a single ->fieldCondition but when I try to implement the hook below,
    $query = new EntityFieldQuery();
    $entityFormSubmissionIds = $query->entityCondition('entity_type', 'entityform')
      ->addTag('or')
      ->execute();

/**
  Implements hook_query_TAG_alter
@param QueryAlterableInterface $query
  */

function mymodule_query_or_alter(QueryAlterableInterface $query) {
 $or = db_or()->condition('field_a',$term->tid)
       ->condition('field_B', $term->tid);
    ->condition($or)
    ->execute();

Fatal error: Call to undefined method DatabaseCondition::execute()
Comment: When you alter the query it's not a EFQ any more, it's just a standard query. So you can't use `fieldCondition` and other EFQ-specific methods. You'll need to use the usual `condition` method
Comment: If you are setting your conditions like that, it won't work. You need to add the conditions to the db_or object then add the db_or to the query.
Comment: @Clive I edited my question based on your comment.
Comment: @AlfredArmstrong, Can you provide a small example?
Comment: Instead of $query->condition('field_A1', $my->tid) write $db_or->condition(...) and so on for your other fields. That creates an OR clause containing those fields, which you then add to your query using the condition method on the query itself.
Comment: @AlfredArmstrong, I couldn't make it, but I have updated the question based on your comment. Can you write a quick answer? I believe we're quite close
Answer: In the alter hook, you should not be calling execute(). You don't want to run the query at this point, just change it.
function mymodule_query_or_alter(QueryAlterableInterface $query) {
 $or = db_or()->condition('field_a',$term->tid)
       ->condition('field_B', $term->tid);
 $query->condition($or)
}

Comment: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_A' in 'where clause': SELECT entityform.entityform_id AS entity_id, entityform.type AS bundle, :entity_type AS entity_type, NULL AS revision_id FROM {entityform} entityform WHERE ( (field_A = :db_condition_placeholder_0) OR (field_A_s = :db_condition_placeholder_1) )AND( (field_B[:entity_type] => entityform ) in EntityFieldQuery->execute() (line 1216 of entity.inc).
Comment: field_a and fields_b are part of fieldable entity of type entityform, but it looks like EFQ is looking to compare entityform ids's with they taxonomy term field_a and b term id's.
Comment: This is because those fields are not part of the base table. Thinking about it you will be better off forgetting about EFQ and starting with a db_select instead. Then you won't need an alter and you can handcraft the query exactly to you needs.
Comment: The thing is I don't know how to db_select entityform. The fields are not in it's table, and everything else is inside a Blob
Comment: Fields are never in an entity's table. They will be in tables called "field_data_NAME_OF_FIELD'. So you have to join them as part of the query. There's an example here https://www.drupal.org/docs/7/api/database-api/dynamic-queries/joins


Javascript - Capturar src por class name

Question: Como capturar o atributo src de uma imagem com uma class name x?
por exemplo:
var Image = document.getElementByClassName("Picture");
console.log(Image.src)

Answer: Pode ser feito dessa forma:
var image = document.getElementsByClassName('Picture');
console.log(image[0].src);

O que você está errado é chamada da função getElementByClassName que está escrita de forma errada faltando o 's' de 'Elements', e o fato dessa função retornar um array com todos os elementos que ela encontrar com o nome de class especificada no argumento passado, assim também ao invés de capturar o valor da String src da imagem estava tentando acessar uma propriedade src do array, onde essa propriedade não existe.
Comment: Muito obrigado!! Me ajudou um milhão!!!


HTML Meta Refresh - Error After File is Removed

Question: I am using a combination of .htaccess redirect and HTML meta refresh to put in a temporary splash page while restoring my web site from a backup.
Here's the index.html:
<!DOCTYPE html>

        <title>Site Restore</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="refresh" content="15">
        <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?3.5.1/build/cssreset/cssreset-min.css&3.5.1/build/cssfonts/cssfonts-min.css&3.5.1/build/cssbase/cssbase-min.css">

Site Restore

This web site is being restored from a back-up, and will be back online shortly.

If you leave this page open, it will redirect when the site restore is complete.

.htaccess Redirect:
RewriteEngine On
RewriteBase /
RewriteRule ^.+$ / [R=302,NC,L]

After the backup restore is complete, I remove the RewriteRule ^.+$ / [R=302,NC,L] line from .htaccess and delete the index.html file. Even though index.html is not in the URL, I get this error back from the web server:

Forbidden
You don't have permission to access /index.html on this server.
  Apache/2.2 Server at dev.swissmangocms.com Port 80

If I manually refresh the browser window, index.php is loaded as I would expect. How do I avoid the error message and manual step?
Comment: Sounds like a browser cache issue
Comment: @JonLin - That makes sense, but how do I overcome it?
Answer: Jon Lin's comment caused me to look in the direction of disabling browser caching. I found another post on SO, "Using  tags to turn off caching in all browsers?", and added these lines to my index.html  section:
<meta http-equiv="cache-control" content="max-age=0">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT">
<meta http-equiv="pragma" content="no-cache">

That fixed the error!


Getting return value in JSP

Question: Below is the code for auto generate purchase order number from the MySQL database in JSP. I want to return "POno" String but It shows error because It is outside the if condition.
How can I get this String as a return?
<%!
    public String autoPONo()throws SQLException{

        rs=pst.executeQuery();

        if(rs.next()){
            String po= rs.getString("max(PONo)");
            int intNo = Integer.parseInt(po);
            intNo+=1;

            String POno = Integer.toString(intNo);
        }

           return POno;
     }
%>

Comment: Why getting `PONo` as string and converting it to `int`, you can directly use `rs.getInt` it can reduce `Integer` parsing.
Answer: Declare the variable otsido of your loop:
<%!
    public String autoPONo()throws SQLException{
               String POno = null;
                rs=pst.executeQuery();

                if(rs.next()){
                   String po= rs.getString("max(PONo)");
                   int intNo = Integer.parseInt(po);
                   intNo+=1;

                   POno = Integer.toString(intNo);
                }

           return POno;
        }
    }
%>

Answer: You must declare the POno out of the if or return inside if, so that the POno is accessible for return statement.
    rs=pst.executeQuery();

     String POno = "";
        if(rs.next()) {
           String po= rs.getString("max(PONo)");
           int intNo = Integer.parseInt(po);
           intNo+=1;
               POno = Integer.toString(intNo);
        }

    return POno;

or
    rs=pst.executeQuery();

    if(rs.next()) {
         String po= rs.getString("max(PONo)");
         int intNo = Integer.parseInt(po);
         intNo+=1;

         String POno = Integer.toString(intNo);
         return POno;
     }

    return "";

Getting return value in JSP


How to copy and paste text from one text file to another using C#?

Question: I'm creating a C# code that is required to read a text file line by line and then copy each line onto a new text file. I was able to figure out how to read line by line, but I'm having trouble copying line by line to the new text file I created.
This is what I am using to read my original text file line by line:
<code>        int counter = 0;
        string line;

        // Read the file and display it line by line.
        System.IO.StreamReader file = new System.IO.StreamReader(@"c:\AnswerFile.txt");

        while ((line = file.ReadLine()) != null)
        {
            System.Console.WriteLine(line);
            counter++;
        }

        file.Close();
        System.Console.WriteLine("There were {0} lines.", counter);
        // Suspend the screen.
        System.Console.ReadLine();
</code>
Any help is appreciated! Thank you
EDIT: I did not forget to write the code that copies the text onto another text file. That is the part I am having trouble with. I tried using streamwriter while specifying the directory of the file I want the text to go to, but something wasn't right. I want to create a code that literally reads line by line from one text file and copies line by line (as it reads from the initial file) to the new text file. I hope that clarifies my question.
EDIT2: Figured it out guys. Thank you for all the help! I had to call my company's security department to grant me access to write in the c drive.
Comment: What's wrong with [`File.Copy`](http://msdn.microsoft.com/en-us/library/system.io.file.copy(v=vs.110).aspx)?
Comment: Are you looking for `File.Copy`?
Comment: Your code is reading a file but never writes to another file. Did you forget to post the code that writes or are you asking how to write to a file in general?
Comment: You are correct to use `StreamWriter`, I suggest showing that code too. make sure you specify a full **file** path for the writer though, not just a directory path
Comment: My answer shows you how to do what you're asking.
Answer: <code>        int counter = 0;
        string line;

        try
        {
            // Read the file and display it line by line.
            using (System.IO.StreamReader file = new System.IO.StreamReader(@"C:\\AnswerFile.txt"))
            {
                using (System.IO.StreamWriter fileWriter = new System.IO.StreamWriter(@"C:\outputFile.txt"))
                {
                    while ((line = file.ReadLine()) != null)
                    {
                        System.Console.WriteLine(line);
                        fileWriter.WriteLine(line);
                        counter++;
                    }
                }
            }
            System.Console.WriteLine("There were {0} lines.", counter);
            // Suspend the screen.
            System.Console.ReadLine();
        }
        catch (System.IO.IOException ex)
        {
            // Handle the Error Properly Here
        }
</code>
Updated answer in response to comments about missing exception handling and closing of File handles in case of error.
Comment: Who's going to close your files if you get an error?
Comment: @Garerth: I'm just making a point, personally I would prefer to make sure the OP knows not to let it slip as they are clearly still learning some basics. But I won't knock your answer for not including it, it's not a requirement to solve the question. Also, I would recommend a `using` block instead of try/catch
Comment: Wrap it in a Try Catch Finally block and do the File.Close() in the finally block.  Or do some error handling.  Figured doing that was outwith the scope of the question.
Comment: Good point well made, musefan.
Comment: I tried that earlier, but it still gives me an issue. It highlights : System.IO.StreamWriter fileWriter = new System.IO.StreamWriter(@"C:\outputFile.txt") and tells me "unauthorizedaccessexception was unhandled. Access to path is denied". I don't know why it is denying it if I created the file myself and I made sure it is accessible by checking that on the file's properties. Any ideas on how to resolve this?
Comment: @رحابصديق: That doesn't mean the code is wrong, it means you don't have access to write in that location. Try a different location, where you know you can definitely create new files
Comment: Yes, the code is correct throughout. I just don't know how to get access to write in that location. Any tips? This is what I get when I run --> "access to path c:\\... is denied". I don't have access to write in that location.
Comment: @musefan I've modified my code block to be more correct.  Could you remove the downvote?
Comment: @GarethOates: I cannot do that, because it is not my downvote. You shouldn't worry about it, it isn't important
Comment: @musefan true. Sorry for assuming it was you! :)


FINDSTR using variable from text file (Batch,Scripting)

Question: I have a statement, which removes a specific string out of a text file, although how can I define this string from a text file.
E.g. the text file has one line of text and I efectively want that text to go inbetween "/c:"<HERE>" >>"
The statement is below
type ignore_tmp.lst | findstr /v /c:"%ignore%p" >> ignore_tmp_.lst

So I think the real question is, if I echoed the text file, maybe using the type command, how could I set the output as a variable?
Comment: So I think the real question is, if I echoed the text file, maybe using the type command, how could I set the output as a variable?
Answer: The for command can do what you're looking for, both by reading the file itself or by capturing the output of the type or findstr command, like you said.
C:\>echo test1 > input.txt
C:\>for /f "delims=" %a in (input.txt) do @set input_content=%a
C:\>echo %input_content%
test1
C:\>echo test2 > input.txt
C:\>for /f "delims=" %a in ('type input.txt') do @set input_content=%a
C:\>echo %input_content%
test2


Finding the sum of special multiplications

Question: Let $n$ be an integer and $a_1, \dots, a_n$ positive reals.
$\forall 1 \leq i < j \leq n$ let $a_{i, j}$ be a positive number.
Let $k \leq n$ be a positive integer.
I would like to find an efficient way (either a closed formula, or an algorithm polynomial in $n$, $k$) to find
$ \sum_{S \subseteq \{1,\dots,n\}, |S| = k} \prod_{i \in S} a_i \prod_{i, j \in S, i < j} a_{i, j}$
EDIT:
I see that it is sufficient to find
$ \sum_{S \subseteq \{1,\dots,n\}, |S| = k} \prod_{i, j \in S, i < j} a_{i, j}$
We can multiply each $a_{i,j}$ by $\sqrt[k-1]{a_i a_j}$ and this way to get rid of $a_1,\dots,a_n$.
If you can't find a solution (possibly there is none), than any directions for how to get to this problem would be appreciated. Even an approximation algorithm is fine
Comment: Can you go by induction from k to k+1?
Comment: Not in an efficient way. For instance, I can find all the sums of sets of size $k + 1$ containing $i$ ($1 \leq i \leq n$)  by solving a problem for $k$: in this problem I get rid of $i$. For all $a_j$ for $j \neq i$ I multiply $a_j$ by $a_{i,j}$. Now I find the sums in this problem. I can do this for all $1 \leq i \leq n$, sum everything and divide by $k + 1$ to get a solution. But this means that I have to solve $n$ different problems for going from $k$ to $k + 1$ which leads to an exponential time.
Answer: Define $$f(r,m)=\sum_{S\subseteq\{1,\ldots,n\},\atop|S|=r,\max S=m}\prod_{i,j\in S,\atop i<j}a_{i,j} $$
You want $$\sum_{m=k}^nf(k,m).$$
We have the recurrence
$$ f(r,m)= \sum_{r-1\le i<m}f(r-1,i)a_{i,m}$$
Thus to compute all $f(r,m)$, $1\le m\le n$, from the $f(r-1,m)$ takes $O(m^2)$ time, and to compute everything up to $r=k$ takes $O(km^2)$ time - and with suitable bookkeeping $O(n)$ space.
Comment: Thanks for your reply but it has a problem: note that each multiplication in the desired sum is a multiplication of ${k \choose 2}$ elements (one element for each pair in S), while in your solution, there are only $k$ multiplications (when going from $r - 1$ to $r$ you add only one multiplication instead of $r - 1$ multiplications - we had to multiply by $a_{j,m}$ for each $j \in S$.


Is it right to say that if two vectors, $A$ and $B$, have same $L^p$ norms, for all $p$, then $A = B$?

Question: Is it right to say that if two vectors, $A$ and $B$ (all elements of $A$ and $B$ are positive), have same $L^p$ norms, for all p, then $A = B$ ?. Thanks.
Comment: What do you think of the $l^p$ norms of $A$ and $-A$?
Comment: Then don't we have $\|(1,2)\|_p = \|(2,1)\|_p$ for all norms $\| \cdot \|_p$ on $\mathbb R^2$?
Comment: (By the way, writing "$L^p$ norms" and then talking about components is confusing. The $L^p$ spaces are well defined vector spaces of functions with a specific norm. Because you are talking about components, I take it you actually mean the $\| \cdot \|_p$ norm applied to the vector spaces $\mathbb R^n$.)
Comment: Thanks. Tryss. Let me rephrase the question, and include (A /= -B).
Comment: @rex: same issue with $(2,2,1,1,2)$ and $(-2,2,1,-1,2)$. Maybe you want to assume that $A$ and $B$ have non-negative components.
Comment: Yes, Jack D'Aurizio, thanks. My vectors have only positive elements. Let me update the question.
Comment: [This question was also asked recently here,](http://math.stackexchange.com/questions/1411806/characterization-of-vectors-via-ell-p-norms/1411817) but only considering equivalence up to permutation.
Comment: Thanks. Simon S, and Chester. The answer by mathcounterexamples.net in Chester's link seems to be what I wanted to know. Thanks everyone. Have a great weekend.
Answer: As Crostul and Simon S pointed out, there is always the possibility of a permutation of the coordinates which leaves the norm invariant.
But one can show that these are indeed the only such possibilities i.e.
that if two increasing sequences $(a_i)_{i=1}^n, (b_i)_{i=1}^n$ with positive elements satisfy
$$\sum_{i=1}^n a_i^p=\sum_{i=1}^n b_i^p$$
for all $p$ then you must have $a_i=b_i$ for all $i$.
This can be proved by an iterated argument using the fact that for $p \to \infty$ the $p$-norm of a vector assumes the value of the maximal coordinate.
Hence we conclude that $a_n=b_n$ must hold.
Then, looking at the sequences $(a_i)_{i=1}^{n-1}$ and $(b_i)_{i=1}^{n-1}$, they must still satisfy the equation and hence we conclude $a_{n-1}=b_{n-1}$
Iterating this we obtain $a_i=b_i$ for all $i$. (Writing formally, we use mathematical induction here.)
So the possibilities of permutation mentioned above are indeed the only such possibilities.
Answer: No. For a  vector $v=(x_1, \dots, x_n)$ the $p$-norm is $$||v||_p = \left( \sum_i |x_i|^p \right)^{\frac1p}$$
so you can see that for any permutation of indexes $\sigma \in S_n$ you have
$$||v||_p = ||(x_{\sigma(1)}, \dots, x_{\sigma(n)})||_p$$
Answer: Take A=(1,1,2) and B=(1,2,-1) and A is not equal to B
For p=2 , N(A)=sqrt(1^2+1^2+2^2)=sqrt(6)
          N(B)=sqrt(1^2+2^2+1^2)=sqrt(6)
  i.e N(A)=N(B)
But A is not equal to B
Therefore This result is not true in general


run cron job between 00:00 - 00:02 - 04:00 - 23:59 on every hour

Question: I want to run a cron job between 0:00am - 02:00am - 04:00am and 23:59am on every hour.
I want to know if this is the correct syntax.
0,0-59 0-2,4-23/1 * * *
Thanks!
Answer: No, your syntax is not correctly formatted.
You can use:
0 0 0/1,0-2 ? * *

This will run according to the following rules:
At second :00, at minute :00, every hour between 00am and 02am,
  and every hour starting at 00am, of every day

You can check CRON syntax with an explanation at:Cron Expression Generator & Explainer.
Also, I think this site has a really good breakdown to help understand what each section of the CRON expression relates to.
Edit: I just noticed you had the second part about running at 23:59. For this you will need to set up a second CRON job:
0 59 23 * * ? *
Use Case: At 23:59:00pm every day

Comment: I added a second part to this, it looks like I missed the 23:59 part in the initial answer. You will need a second job for that part.
Comment: Did you have other questions or did this work for you?


Insert image tag in checkboxes list

Question: A Form having a form element of term reference with checkboxes widget. I want to insert a image tag with each taxonomy term name,
For example here is the html of taxonomy term reference

  < input type="checkbox" id="edit-field-user-interest-und-24"
name="field_user_interest[und][24]" value="24" checked="checked"
class="form-checkbox ajax-processed">
  -uejo

so how can i insert image tag inside div tag so that its html become this

  < input type="checkbox" id="edit-field-user-interest-und-24"
name="field_user_interest[und][24]" value="24" checked="checked"
class="form-checkbox ajax-processed">
  -uejo

Answer: You should be able to add a prefix or suffix with the field. See Field Suffix in the Form API, So your code might be:
$form['copy'] = array(
'#type' =>'checkbox',
'#title' => t('my taxonomy term.'),
'#field_suffix' => '',
);

You can use field_prefix if you want it to come before.
Answer: I believe that the best option would be to use a custom module to perform a hook_form_alter() and add the image programmatically to the form array.
There are no exiting contrib modules that I am aware of that will do this for you, seeing as it is a very specific need that requires an individualized solution.
Comment: How i write my code in form alter so that image tag would be show as sibling with input and label tag.
Comment: The Form API provides for additional fields which you can put the image into.  Two examples are [#field_suffix](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#field_suffix) and [#field_prefix](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#field_prefix).

Insert image tag in checkboxes list


How do i add a background image to a imput submit button in my module?

Question: So i have a input submit button that needs an image.
I've been looking at the module styling documentation where it says i can attach the styling to a render array of a block plugin. What does this mean and how do i do this? I'll include the trimmed down code where i want to include this styling.
LoginBlock.php:
class LoginBlock extends BlockBase implements ContainerFactoryPluginInterface {

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('plugin.manager.pixelpin_openid_connect_client.processor'),
      $container->get('form_builder')
    );
  }

  public function build() {
    return $this->formBuilder->getForm('Drupal\pixelpin_openid_connect\Form\LoginForm');
  }

}

LoginForm.php:
class LoginForm extends FormBase implements ContainerInjectionInterface {

  public function buildForm(array $form, FormStateInterface $form_state) {

        //submit button that i want to add styling too

          $value = 'Log in Using PixelPin';
          $label = 'Log in Using PixelPin';

          $form['pixelpin_openid_connect_client_pixelpin_login'] = array(
            '#type' => 'submit',
            '#value' => t($value, array(
              '@client_title' => $client['label'],
            )),
            '#name' => $client_id,
            '#prefix' => '
',
            '#suffix' => '
',
          );
    }
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    //code
  }

}

pixelpin_openid_connect.libraries.yml:
pixelpin_logo:
  version: 1.x
  css:
    theme:
      css/style.css: {}

style.css:
#edit-pixelpin-openid-connect-client-enable-login {
  background: #f0f0f0 url(/ppicon.png) no-repeat center;
  cursor: pointer;
  height: 26px;
  margin-left: 0;
  margin-right: 0;
  overflow: hidden;
  padding: 0;
  text-indent: -9999px;
  direction: ltr;
  width: 34px;
}

Answer: You can attach it to any render array; the submit button itself seems as good as any:
$form['pixelpin_openid_connect_client_pixelpin_login'] = [
  ...
  '#attached' => [
    'library' => [
      'pixelpin_openid_connect/pixelpin_logo',
    ],
  ],
  ...
];

Comment: I just tried this and it doesn't appear to be loading the css, what can cause this?


Como receber os dados de entrada de um programa em C vindos de um arquivo?

Question: Tenho um programa em C. Vamos supor que o nome dele compilado seja a.out (padrão).
Quando uso o seguinte comando para executá-lo...
./a.out < arquivo.txt

...como faço para ler o conteúdo do arquivo.txt dentro do programa (na função main mesmo)?
Answer: Basicamente o que você precisa fazer é ler o stdin que é de onde virá os dados do arquivo. Uma implementação simplificada seria essa:
#include <stdlib.h>
#include <stdio.h>
#define BUFF_SIZE 1024

int main(void) {
    char buffer[BUFF_SIZE];
    while (fgets(buffer, BUFF_SIZE, stdin) != NULL) {
        printf("%s", buffer);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Desta forma o que vier pelo pipe do sistema operacional será impresso na tela. O pipe pegará uma fonte de dados, pode ser um arquivo mas pode ser outra fonte também.
Comment: Obrigado pela resposta. Eu testei, mas não imprimiu nada. Então removi o `if`, compilei e tentei executar de novo mas dá um erro: `Segmentation fault (core dumped)`
Comment: Eu fiz uma mudança, eu tinha comido bola, dava para fazer algo mais simples. Ainda não garanto que está ok porque não tenho como testar aqui mas se não der certo, me fale o problema que eu tento resolver.
Comment: Agora deu certo! Obrigado.


There are fewer than $q(q-1)/2$ rationals of the form $m/n$, with $n<q, m,n \in \mathbb{Z^{+}}$ in any open interval about an irrational number $a$

Question: While studying the GRE Math Subject test, I came across a property in a proof that for the function
                            $$f(x)=
                           \begin{cases}
                                0,      & x \notin \mathbb{Q} \cap(0,1)\\
                                \frac{1}{n},     & x=\frac{m}{n}
                            \end{cases}
                        $$
 with $GCD(m,n)=1, n>0$, that $f$ is continuous on every irrational point in $I=(0,1)$, and discontinuous on the rationals there.
The property in question is the following:
Given a positive integer, $q$, and an irrational number $a$ in any open sub-interval of $I$ centred at $a$, there are fewer than $1+2+ \cdots + (q-1) = \frac{q(q-1)}{2}$ rationals of the form $\frac{m}{n}<1$ with $n<q$.
Can someone help me make sense as to why this might be true?
Comment: sure is a typo!  fixed.
Answer: It all starts with Dirichlet's approximation theorem (a short proof here). Everything else is just counting, with the $\frac{m}{n}<1 \Rightarrow 0<m < n$ constraint. E.g.
$$n=q \Rightarrow m \in \{1,...,q-1\}$$
$$n=q-1 \Rightarrow m \in \{1,...,q-2\}$$
$$...$$
$$n=2 \Rightarrow m \in \{1\}$$
Altogether, counting all the possible values for $m$, maximum $\frac{q(q-1)}{2}$.
Answer: This seems like a crude estimate of the number of fractions with denominators less than or equal to $q$ in the entire interval $(0,1)$.  There is 1 fraction with denominator equal to 2, 2 fractions with denominator equal to 3, 3 fractions with denominator equal to 4, up to $q-1$ fractions with denominator equal to $q$.
Comment: @Shuri2060  It should definitely read something like "*fractions* of the form $\frac{m}{n}<1$ with $n<q$."
Comment: Yes. and it's fixed. And after reading it a couple more times and messing with some values...
Yes sharding4, denominators less than q.  derp.  For every integer $q$, there are $q-1$ fractions less than $1$ with denominator less than $q$.   _Obviously_ the number of fractions in for a given denominator will be one less than value of the denominator so the total number of such fractions, for a given $q$ will be less than $\frac{q(q-1)}{2}$. But _fewer_ than that will be co-prime. Thanks.  Apologies for asking a silly question and for the typo.


Sum of normally distributed random variables expressed with respect to one component

Question: A rather elementary question: If we have:
$X = X_1 + X_2 + ... + X_n$ and $X_i \sim N(0,\sigma^2)$ and independent,
can we express $X$ as $\sqrt n X_i$ for any $i = 1,...,n$ ?
I think since all the components $X_i$ follow the normal distribution and we are summing $n$ of them up, the resulting rv is $X \sim N(0, n\sigma^2)$ and therefor we can use $X = \sqrt n X_i$.
Is this reasoning correct? If yes, under what condition it can be false?
Comment: Multiplication part is totally wrong
Comment: I meant that the reasoning is wrong
Answer: A random variable is a real-valued function, $X_j = h_j(y),\; y\in S_y$, where $S_y$ is the domain of the function. A function is fully determined by three things: its domain, its range, and its functional form. So let's check:
Although it is not mentioned, let's say that the $X$ variable and the $\sqrt n X_i$ r.v. have the same domain, say, the reals (that domain has nothing to do with the distribution they follow). Since they are both normally distributed, they have the same range (which is the "support" i.e. it is the domain of the distribution they follow), $(-\infty, \infty)$. Do they have the same functional form? Unlikely.
We have $X = \sum_{j=1}^nX_j = \sum_{i=1}^nh_j(y)$ while $X_i = \sqrt nh_i(y)$. For these to be identical we should have
$$\frac {1}{\sqrt n -1}\sum_{j\neq i}^nh_j(y) = h_i(y),\;\; \forall y$$
This relation may, or may not hold. So in general, writing $X=\sqrt n X_i$ is wrong.
But, they are identically distributed... what does that mean? A function becomes a random variable if its range has such properties which can be summarized by another function possessing certain properties, a "cumulative distribution function", and in our case by the latter's derivative, the probability density function also (since it exists). But we just saw that two random variables may have identical distributions and at the same time they may be different functions. To put it in symbols, for two r.v.'s,
$$Z = Y \Rightarrow Z\sim_d Y$$
(and so also $E(Z^r) = E(Y^r) \;\; \forall r$), but
$$Z\sim_d Y \nRightarrow Z = Y$$
Yet another way to think of it intuitively is the following: assume that $X_i$ acquires a specific value, say $x_i^*$. Is it true that then the other random variables will acquire such values so as we will necessarily have
$\sum_{j\neq}^nx^*_j = (\sqrt n-1) x_i^*$? No. Therefore, $X$ and $\sqrt nX_i$ are not identical functions.
See also
Can two random variables have the same distribution, yet be almost surely different?
Comment: I read the comments, and my impression that they all refer to the distributional relations between random variables. We usually say "identical random variables" but we only mean "identically distributed" not "identical as functions".
Comment: Yes it is, this notation expresses the "identically distributed" aspect.
Comment: The reason I asked the OP is because in another question I posted [here](http://stats.stackexchange.com/questions/88628/distribution-of-the-ratio-of-dependent-chi-square-random-variables) I was left with the impression that I can do it. Your reasoning here is undoubtedly correct, so I assume either I did not understand the answer given there correctly,  or the commentator was wrong.
Comment: Is it correct then to say $X \sim \sqrt n X_i \sim N(0,n\sigma^2)$ ?
Answer: $Cov(X,\sqrt{n}X_i)=\sqrt{n}\sigma^2$, but if $X$ were $\sqrt{n}X_i$, then we'd have $Cov(X,\sqrt{n}X_i)=n\sigma^2$
hence, the answer is No


Model Formula with deflator

Question: I'm having difficulties to find the right model formula for my model:
$Y_i=a+bX_i$  where Y and X are both deflated by another variable
y1/def ~ x1/def + x2/def

returns a model with interactions. How can i prevent R from doing so?
Comment: Did this help you get the desired behavior?
Comment: As a word of caution, be careful with dividing by `def`, however--if it's a **random variable** then dividing both sides by `def` could completely change the **functional form** of your regression. Just throwing that out there...
Comment: Thank you for your answer and the hints on deflating. I wasnt able to check yet. Will comment when I did so.
Answer: If you want to perform a transformation on the variables in the regression, you'll have to use the I() function:
I(y1/def) ~ I(x1/def) + I(x2/def)

Try that instead and see if it works the way you want it to...
Explanation:
Basically, you use the I() function in a formula whenever you want an expression to be treated "as is". For example, if you have a data frame with three columns, a, b, & c, and you want to regress c onto the sum of columns a and b you would write: c ~ I(a + b) since--as you've seen yourself--entering: c ~ a + b would give you a totally different regression.

Model Formula with deflator


Powershell - ODBC MSAccess Commit transaction refresh data for Select Query after Insert

Question: I'm connecting with ODBC in powershell to an .accdb Access Database. After inserting new data into a table (insert into via ExecuteNonQuery), I'm unable to pull the data with a select command for futher processing (create a PDF table). The resulting object of the query is empty (0 rows), though "Select @@IDENTITY" returns the most recent index identifier. The Workflow is something like this:
Data entered into a forms window -> new record is created -> data is pulled off and processed into a report -> report is sent by mail -> record is flagged as sent
I tried to use the SQL transaction mechanism, but even after the commit is done, the data is not immediately retrievable with a select-query. After inserting another record, the previously inserted one can be pulled with a select query, but not the new most recent one.
I have not found any working solution to this behavior. I've heard about this, when using Access forms, where the data will be available when the form has been moved to the next record. Any ideas how I can solve this?
Below are my getter and setter functions. In general they work as intended but using Set-Data with an insert first and firing Get-Data with a select afterwards does not provide any records.
<code>Function Get-Data($SQLCommand){
    try{
        $Connection = New-Object System.Data.Odbc.OdbcConnection($DSN)
        $Connection.Open()
        $AccdbCommand = New-Object System.Data.Odbc.OdbcCommand($SQLCommand, $Connection)
        $AccdbAdapter = New-Object System.Data.Odbc.OdbcDataAdapter($AccdbCommand)
        $AccdbDataSet = New-Object System.Data.DataSet
        $AccdbAdapter.Fill($AccdbDataSet)
        $Connection.Close()
        return $AccdbDataSet
    }
    catch
    {
        [System.Windows.Forms.MessageBox]::Show($_.Exception.Message + "`r`n" + $_.Exception.InnerException, "Fehler",'OK','Error')
    }
}

Function Set-Data($SQLCommand){
    try
    {
        $Connection = New-Object System.Data.Odbc.OdbcConnection($DSN)
        $Connection.Open()

        $Transaction = $Connection.BeginTransaction()

        $AccdbCommand = New-Object System.Data.Odbc.OdbcCommand($SQLCommand, $Connection, $Transaction)
        $AccdbCommand.ExecuteNonQuery()
        $transaction.Commit()

        $AccdbCommand = New-Object System.Data.Odbc.OdbcCommand("Select @@IDENTITY", $Connection)
        $result = $AccdbCommand.ExecuteScalar()

        $Connection.Close()
    }
    catch
    {
        [System.Windows.Forms.MessageBox]::Show($_.Exception.Message + "`r`n" + $_.Exception.InnerException, "Fehler", 'OK', 'Error')
    }
}
</code>
Answer: I've resolved this Problem. The commit itself is working as intended. The missing data record in the output process was a result of an error in looping the rows in the dataset with a for Statement.


Going back to normal terminal I/O after closing ncurses window

Question: In a game I made I create an ncurses window using initscr(), then the user plays the game and when the game ends the program closes the window using endwin() and then prints some statements and gets input from the user using printf and scanf, respectively. My problem is that whenever the game ends scanf always executes before printf. So it waits for a response, and once the user enters the response it prints everything that was before and after the scanf statement. Here is some example code:
...

endwin();
system("clear"); /* Clears terminal window */
printf("New high score!\nPlease enter your first name: ");
scanf("%s",name);

... /* file I/O stuff */

printf("Congratulations, %s!",name);

As you can see, the printf statement is before the scanf statement but for some reason scanf executes first. I tested the code without an ncurses window and I get the desired result. Does anyone know what is causing this?
Comment: You need to `fflush(stdout);` after your `printf()` call, or terminate the format string with a newline. Nothing to do with curses.
Comment: You don't - you call it to make `printf()` actually write to the screen before your `scanf()` call starts.
Comment: @PaulGriffiths Ok, that worked, but why do I have to call `fflush(stdout)` to get `scanf()` to start working again? From what I gather it basically forces all output streams to update, but I wouldn't normally need that when using `printf()`/`scanf()` (or would I?)
Answer: You can read about it in the manual page where it discusses NCURSES_NO_SETBUF:

to get good performance, most curses implementations change the output buffering from line-oriented to buffer-oriented (so that the library can make larger, more efficient writes)
because that meant that all writes to the standard output would be buffered, it was a nuisance.  ncurses provided an option (the environment variable) to override the buffering.
that changed in 2012, by eliminating the stdout buffering altogether to solve a problem with signal handling.
however, "eliminating" the buffering means that ncurses uses its own buffer.  It'll flush that in endwin, but doesn't flush stdout when switching to/from curses mode.
a few applications required modification to flush stdout.

The 2012 change for ncurses was part of the ncurses6 release in August 2015.  The OP's question is in terms of ncurses5.9 (or earlier), since it describes an application where the standard output is buffered.
Answer:
Nothing to do with curses.

This statement is obviously wrong since using curses makes a difference, as the question states:

As you can see, the printf statement is before the scanf statement but
  for some reason scanf executes first. I tested the code without an
  ncurses window and I get the desired result. Does anyone know what is
  causing this?

While it is right that fflush(stdout) gives the desired result, that does not answer the question.
What is causing this is presumably the implementation-defined standard I/O characteristic to flush a line buffered stdout when input is requested (sometimes documented in man setbuf), and curses setting stdout to fully buffered, thereby disabling the automatic flush.


Lsmeans: Is this what I did?

Question: after doing the linear mixed model with lme4, I have used lsmeans for pairwise comparison with this command:
<code>lsmeans(lmer52, pairwise~color, adjust="tukey")
</code>
I am not sure if it is "multiple pairwise comparisons, using Least Squares Means
 (LSMEANS) and Tukey's adjustment". Anyone have any idea if it is exactly the same thing?
Answer: I just saw this. Yes, it is all pair wise comparisons, using a P value adjustment based on the Tukey HSD method.

Lsmeans: Is this what I did?


Should I test my website against all browsers & all versions?

Question: Prob 1 : Do I need to care about some bugs of Firefox 2, firefox 3, chrome7,8, opera 8,9... etc that can make my site look weird on these old browser ? I wonder if the developer changed the HTML-render-engine everytime they update their browser & make my site imcompatible with all version.
Will almost visitors keep their browser up2date ? If not, please suggest me with some tools that can help me test my site against FF, Chrome, IE, Opera, Safari in all major versions.
(I've try this by some online services but it's extremely slow to take screen shot of my site)
Prob 2 : Is there any difference among browser for PC, Tablet, Mobile (except the screen resolution) that can cause a display error for my website ?
Thanks a lot!
Answer: Well, whether you should test your website against:

all browsers: Yes, because Windows users have any among IE, Chrome, Firefox & in remote cases, Safari, Opera among others. Whereas Mac users will have Safari, Chrome as their preferred one.
all versions: Probably no. Limit yourself to only those which are still supported, i.e. IE 7 onwards & so on.

But, the key lies in the engine upon which the browser is based upon. It can be said:
<code>                     *OS: Kernel :: Browser:Engine*
</code>
For instance, Chrome, Safari, both are based upon "webkit" layout engine.
Check out, web-layout engines: http://en.wikipedia.org/wiki/List_of_web_browsers
(This consideration will save a lot of effort as you can be rest assured that browsers using same engine will behave in a similar manner.)
Also, keep in consideration your target audience, this can help you limit your browser choices.
And yeah, most browsers have developer tools (F12 key), which allow you to simulate the previous versions of the browser.

But, all in all, the answer is relative & depends solely upon how much time you have & how much effort, time, testing are you willing to spend...
Answer: Developers should always try to make their websites cross browser compatible. I personally wouldn't worry about the very old versions of browsers (ie. Firefox 2) and would instead display a message telling the user that they should upgrade their browser.
As a lot of users don't always upgrade their browsers straight away, you should still try to maintain the compatibility of your site with these browsers.
I would recommend this tool for checking the browser compatibility of your website https://browsershots.org/
Answer: As a general rule there is a quick and dirty way to test your site. The dirty assumption is that if it works on IE, it will work in anything since IE handles more things differently than other browsers.
With that being said, you can test on IE by opening up an IE9 browser window and hitting F12. This will bring up a box on the bottom that allows you to check the site for compatibility quickly. On the top right hand corner of the box that popped up there are two drop down menus to change the IE engine that is interpreting the site (The one on the left is the Engine and the one right is compatibility mode that the engine is running). You can switch between IE7 engine to IE9 engine seamlessly and without needing a 3rd party application to do so.
Comment: Working on IE does not mean it'll work on anything. It could be an IE bug.
Comment: That's rigth alex. I've faced some weird bugs with Chrome & Opera.


Standard Jazzmaster HH bridge/saddle height adjustment

Question: The Fender Standard Jazzmaster HH is a modern hybrid, with a few differences compared to the classic design: the tailpiece has been moved closer to the bridge, and the saddles are a sort of Jazzmaster/Mustang hybrid, with one deep ridge instead of several small grooves.

image from fender.com (with an unrealistic intonation setup, the saddles on mine are way further back)
Moving the tailpiece closer increases the angle of the strings over the bridge, and the one-ridge saddles stop the string from moving out of position when you strum hard. However, this design introduces new problems:

If you set the whole bridge high, and the individual saddles quite low, the strings buzz against the edge of the bridge.
If you set the whole bridge low, and the indivual saddles quite high, the intonation screws are at such an angle that the strings buzz against their tips.
The sweet spot between these two settings is very small, and even then some strings touch the back edge of the bridge or the intonation screw heads.

The previous owner had the bridge on backwards, probably to alleviate the setup difficulties, but then the intonation screws are less accessible. I was thinking of getting shorter (1/2" instead of 5/8") intonation screws (which isn't easy in a metric part of the world), but I was wondering if anyone had found a better solution for the setup of this particular bridge and saddle combination?
(I know about the Mastery bridge, but that's a bit expensive for a second-hand MIM guitar.)
Comment: Is that intonated properly? The saddles look out in comparison to most of my guitars.
Comment: @Tim That's an image from the Fender website; it's most definitely not intonated properly. When intonated the saddles are halfway or further back.
Comment: I'm a bit confused about what you mean by "intonation screws"; you can adjust the saddle height for each individual string and the total length. The naming convention "intonation" somehow stuck to the length adjustment, whereas it mainly affects the "correctness of the octaves. Apart from the naming things, I have to agree that the whole bridge design is flawed. Replacing it in total might go over budget; but there are replacement saddle elements. which might help to alleviate some of your troubles (which also means no imperial-metric mixing issues).
Comment: @cherub The Fender website calls them intonation screws: https://shop.fender.com/en-GB/parts/bridges/american-vintage-stratocaster-saddle-intonation-screws/0015693049.html?rl=en_GB&rdl=en_US
Answer: I don't own one of those bridges, and I've never had to set one up before, but there are two simple-ish ways to handle it: washers, or cutting the screws to length.
Washers:
If you can locate washers that have an outer diameter small enough to not interfere with the feel of the bridge, and an inner diameter large enough to allow the screws through, then all you really need to do is back the screws out, put enough washers on it to eliminate the screw protruding from the end of the saddle, and then get everything put together. Get the guitar intonated, and then, aside from some screws sticking out a little farther than normal from the back of the bridge, everything should Just Work.
Cutting to Length:
If you are handy with a dremel tool, hack saw, and/or files, one other, trickier solution might be to carefully cut the existing screws to a shorter length than what they currently are. Figure out about where the screws need to be set for proper intonation, and use a sharpie or some other method to mark just in front of the saddle where the screw should be cut.
One thing to be concerned with would be any burrs or sharp edges created along the edge of the cut. Those can make it difficult or impossible to get the screws back in to their receptacle. Careful filing/champfering of the screw ends can alleviate that.
Holding the screws while they are being cut can also present it's own problems. To address that, you might be able to leave the screw set all the way through the saddle, and use a bench vise with some pieces of wood to hold the saddle in place while you work on the screw. That or use some softer wood in the vise and clamp down on the screw head itself, leaving the threads and the cutting target over the top, or out the side of the vise.
If you get a set of the replacements from the fender website, you'd at least have some spares in case trimming them does not work out properly the first time.
Comment: I've ordered a set of replacement screws from allparts, and I'll try to dremel them to the correct length. I think this will be the better option of the two.
Comment: Cool, good luck! A bench vise and two scrap pieces of wood to help hold the work piece in place will make the job much easier. I've also used a dremel tool to deburr cut screws, and it's definitely doable, just be careful to leave yourself enough material that if you remove a bit more than intended, you won't cause yourself any major issues.


Calculate integral $\int_{0}^{2\pi} \frac{dx}{a^2\sin^2x+b^2\cos^2x}$

Question: Any hints of how to approach solving this integral?
$$\int_{0}^{2\pi} \frac{dx}{a^2\sin^2x+b^2\cos^2x}, \quad a,b>0$$
I tried substituting $z=e^{ix}$ but I get a rather complex form I can't do anything with.
Comment: have you tried using $sin^2 x =1 - cos^2 x$ in the denominator, then collecting like terms?
Comment: Then, since there is the appearance of a trigonometric function, use the universal substitution $t=\tan(x)$ (or $t=\tan(x/2)$ if you prefer).
Comment: Also related: https://math.stackexchange.com/questions/518173/calculate-the-integral-int-02-pi-frac1a2-cos2tb2-sin2tdt.
Comment: Hint: Enforcing the change of variables $x= t-π$  lead to

$$\int_{0}^{2\pi} \frac{dx}{a^2\sin^2x+b^2\cos^2x}=2\int_{0}^{\pi} \frac{dx}{a^2\sin^2x+b^2\cos^2x}=4\int_{0}^{\pi/2} \frac{dx}{a^2+(b^2-a^2)\cos^2x},$$

then use $u=tan(x)$
Answer: Try converting the limit to $ 0 $ to $\pi/2$ and then split it into two integral of limits $ 0 $ to $\pi/4$ and $ \pi/4$ to $\pi/2$ . Substitute u=tan x in first integral and v=cot x in second.


Is the result of comparing samples from 2 log normal distributions, uniform?

Question: I have sample values coming from two truly random log normal distributions, A and B.   They are continuous (analogue voltages actually).  They are totally independent of one another, but theoretically identical in all aspects of size and shape.   I then repetitively compare sample value A with sample value B, as in
<code>IF valueA > valueB THEN RESULT = TRUE

IF valueA < valueB THEN RESULT = FALSE
</code>
The comparison is done with analogue circuitry (not digital) so A = B cannot happen.  What is the distribution of RESULT?  I think that it has to be uniform.  I think that it's effectively a Von Neumann extractor that will remove all bias /asymmetry from the log normal input distributions.   Does anyone concur?
Comment: No, whuber's hint means for you to use thought, not the actual device. You described assumed properties which - if they're true - should let you give an answer to that question without building the device. As a different form of the same hint, if you identified which was which using sticky notes (with "A" and "B" written on them, respectively) but then *interchanged the sticky notes*, what would be different about your description?
Comment: No answer as yet. 6 months - still waiting for a simple yes /no by your leave...
Comment: @Glen_b  I'm not entirely sure otherwise I wouldn't have asked, especially as some time and expense ride on the outcome of this enquiry.  Is a clear answer really so difficult?  Can the readers infer that what might be considered simple statistics questions (for experts) are not welcome here?
Comment: Hint: What happens to your situation when you interchange $A$ and $B$?  How does that affect the results?
Comment: @whuber I haven't built the thing yet as the decision to proceed rests with the answer to this question :-)
Answer: You have two independent random variables $X, Y$ with identical distributions (we also assume the distribution is continuous, so exact equality has probability zero).  You ask for
$$  \DeclareMathOperator{\P}{\mathbb{P}}
   p= \P (X < Y)
$$
But the assumption of identical distributions tell you that
$$
  1-p = \P (Y < X)
$$
must be equal!  So, $p=1-p$ which has the solution $p=\frac12$.
Without that insight, it could be done by "brute force", by calculus.   We will use integration by parts:  https://en.wikipedia.org/wiki/Integration_by_parts
$$
\P(X < Y) = \int \P(X < Y \mid Y=y) f(y)\; dy = \\
\int \P(X < y) f(y) \; dy = \int F(y) f(y) \; dy = \\
F(y) F(y) \bigg\rvert_{-\infty}^\infty - \int f(y) F(y)\; dy =\\
1- \int F(y) f(y)\; dy
$$
so we got the same equation, with the same solution.  By the way, we didn't use the lognormal assumption at all.  Moreover, our first argument neither did use independence, it only needs exchangeability, so the result is also valid with a symmetric kind of dependence.  The second (calculus) argument did use independence, though, showing that the simple argument is really superior.


Another description for the map $\text{Ext}^1_\mathbb{Z}(A,G)\to H^2(G,A)$

Question: Group extensions of $G$ by $A$ $0\to A\to E\to G\to 0$ up to equivalence (where $G$ and $E$ may be nonabelian) are in bijection with the second group cohomology $H^2(G,A)=\text{Ext}^2_{\mathbb{Z}[G]}(\mathbb{Z},A).$
On the other hand, if $G$ is abelian, and we seek only abelian extensions, such extensions are (up to equivalence) in bijection with $\text{Ext}^1_{\mathbb{Z}}(G,A)$ (whence the $\text{Ext}$ functor gets its name).
Hence there is an inclusion $\text{Ext}^1_{\mathbb{Z}}(G,A)\hookrightarrow \text{Ext}^2_{\mathbb{Z}[G]}(\mathbb{Z},A).$ Perhaps we could say it's induced by the inclusion functor of abelian groups into groups, acting on group extensions. Other than the description given, using the bijection to group extensions, is there another way to see this map?
Comment: In your first line, you should write "Central group extensions".
Answer: $H^2(G, A)$ can also be written $[BG, B^2 A]$, where

for spaces $X, Y$, $[X, Y]$ denotes the set of homotopy classes of maps $X \to Y$,
$BG$ denotes the Eilenberg-MacLane space $K(G, 1)$, and
$B^2 A$ denotes the Eilenberg-MacLane space $K(A, 2)$.

If $G$ is also abelian, then $BG$ and $B^2 A$ can both be modeled by simplicial abelian groups, and we can ask for homotopy classes of maps between them as simplicial abelian groups (more intrinsically this might be equivalent to asking for homotopy classes of infinite loop space maps; I'm not sure). We can then pass to chain complexes by Dold-Kan, and we get that the resulting set of homotopy classes of maps is $\text{Ext}^1(G, A)$.
Comment: Oops, Dold-Kan might not even cut it here; I need an equivalence between the homotopy category of simplicial abelian groups and the derived category of (connective) chain complexes of abelian groups, or something like that.
Comment: I was expecting an answer in terms of homological algebra. In fact I was certain that the change of rings spectral sequence would provide an answer, but I couldn't get it to work out right. Of course, I like your homotopy theoretic answer far better.


Beautiful Soup is giving none, though value is present

Question: Why my following code is giving an output NONE
from bs4 import BeautifulSoup
import urllib3
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
urllib3.disable_warnings()
url = "https://www.amazon.ae/dp/B07N62ZGWQ/ref=br_msw_pdt-5?_encoding=UTF8&smid=ABO0A2K2SKD5O&pf_rd_m=A2KKU8J8O8784X&pf_rd_s=&pf_rd_r=GZ376KPZWEXC0TBHXPKY&pf_rd_t=36701&pf_rd_p=da8f558b-6ee9-4705-8e31-6a4c345b29e8&pf_rd_i=desktop"
http = urllib3.PoolManager()
r = http.request('GET', url)
content = r.data.decode('utf-8')
soup = BeautifulSoup(content,'html.parser')
print(soup.find('span', {'id':"priceblock_ourprice"}))

I tried using soup.find(id="priceblock_ourprice"), soup.select("#priceblock_ourprice"), but both gave None output .
ID is present on the page and has a value as well.
Comment: I tested code - if I use `html.parser` and `find` then it can't find it. If I use `lxml` and `find` then it finds it.
Comment: You are checking different things: the content variable and what you see when you open the URL in your brower. Try print (content) and open the html in your browser to see the page you are actually getting
Comment: print the soup to check that what you expect is really there and not populated with a javascript
Comment: I have checked the content and the element is present there as well.
Comment: amazon uses JavaScript to add elements and requests/beautifulsoup can't run JavaScript. Open web browser, turn off JavaScript and load amazon page to see what beautifulsoup can see. You may have to use Selenium to control web browser which will load page, run JavaScript and then you can get HTML from Selenium.
Comment: you can also have other situation: amazon may recognize that you run script and it may send page with warning for bots or with captch. You may write `content` to file and open in browser to see what you get.
Comment: yes that worked, can you tell me why is that happening?
Answer: First, I altered urllib3 to requests because urllib3 was giving an exception
See the code below:
import requests
from bs4 import BeautifulSoup

url = "https://www.amazon.ae/dp/B07N62ZGWQ/ref=br_msw_pdt-5?_encoding=UTF8&smid=ABO0A2K2SKD5O&pf_rd_m=A2KKU8J8O8784X&pf_rd_s=&pf_rd_r=GZ376KPZWEXC0TBHXPKY&pf_rd_t=36701&pf_rd_p=da8f558b-6ee9-4705-8e31-6a4c345b29e8&pf_rd_i=desktop"

response = requests.request('GET', url)
content = response.content.decode('utf-8')
soup = BeautifulSoup(content, 'html.parser')
table = soup.find('table', attrs={'class': 'a-lineitem'})
price_blocks = table.find_all('span', attrs={'id': 'priceblock_ourprice'})
prices = [block.text for block in price_blocks]
print(prices)

Output console:
['AED26.00']


creating simple CRUD-extension for Typo3

Question: I'm making some first steps in Typo3 and am currently trying to make a simple CRUD extension. I want to be able to edit a db-table - create records, read them, edit them and finaly delete them. Just something like phpMyAdmin does, but just in the Typo3 BE.
But I can't find anything about CRUD and Typo3. I've created my extension with kickstart and already created the table, I've found a way to read its content and print it in the BE, but how do I make the other things? Is there a tutorial, or does anyone know a simple extension that does something similar I can look into to learn how it's done?
Answer: by adding the table in the kickstarter and installing the extension, you can modify the records of this table through the List module. So I don't know, what else you want to do with this records (as the whole CRUD thing (for BE editors) is handled by the list module).
If you want to display the records in Frontend, you have to create a Plugin, which makes some output (probably based on the records in your table..).
Comment: That FE-plugin would be the next step. I'll have a look at the List module, thanks!
Comment: I accepted this answer, as it fitted better to my needs. Extbase might be the future, but the list module is included in Typo3 and can be used out of the box.
Answer: If you are using Typo3 version 4.3 or later, I strongly advise you to have a look at the extbase/fluid MVC Framework and Extbase Kickstarter extension. By default, Extbase Kickstarter allows you to create models of any complexity and generate simple CRUDs for the models.
BTW it can be a nice introduction to Flow3 and Typo3 v5, which should be released in stable version soon.
You can download blog_example from TER as a nice example to delve into.
I also found this tutorial but hadn't read it through : http://mocsystems.com/tutorials/writing-backend-modules-with-extbase/
Comment: Of course, this is the future any you might directly want to learn Extbase instead of Pi-based Frontend Plugins! FLOW3 will be stable within the next few months. TYPO3v5 hopefully by the end of next year.
Comment: Yeah, that looks nice. I'll give it a try :)


Multiple DKIM and SPF DNS records

Question: We uses both Mailgun and Google App engine mail services to send transaction emails from our products. Both needs DKIM and SPF text record in the DNS server. Is it possible to set multiple DKIM and SPF record in DNS configuration? Will it work?
Answer: You would only need a single SPF record as you can have multiple rules within it. Check this article for assistance on setting up more than just Google's entries in your SPF record.. Your DKIM signature will specify the subdomain on your domain to check for the signature key. Google Apps uses the google._domainkey subdomain when it specifies the DKIM location to lookup. I'm not sure what mailgun uses but chances are it won't overlap.
Update:
After a quick look around I found this article on Mailgun's website and would think your SPF record should look like this:
v=spf1 include:mailgun.org include:_spf.google.com ~all
Comment: In mailgun, it says to set domain key for hostname `mx._domainkey`.
Comment: In my case, Mailgun requires a TXT record for `k1._domainkey` which clashes with the CNAME record for `k1._domainkey` as required by MailChimp.

Multiple DKIM and SPF DNS records


File widget custom upload location

Question: I am working on a custom module (based on Model project) with a file field attached to my custom entities, now I would like to save files in certain directories according to entity id eg:
public://files/my_custom_entity_ID/filename

I've tried with hook_file_insert but can't get the entity id in order to use it later in file_move.
Which hook (if any) should I use? Or I am missing the whole approach?
Comment: Which version of Drupal? D7 or D8?
Answer: Assuming D8
If this is part of a "BaseFieldDefinition" of your own entity, you may set a lot of options like so:
// create photo
$fields['photo'] = BaseFieldDefinition::create('image')
    ->setLabel("Photo")
    ->setDescription('Ein Photo')
    ->setSettings(array(
        "file_directory" => 'profilbilder/[date:custom:Y]-[date:custom:m]',
        "file_extensions" => 'png gif jpg jpeg',
        "max_filesize" => '600 KB',
        "max_resolution" => '600x800',
        "min_resolution" => '30x40',
        "alt_field" => false,
        "alt_field_required" => false,
        "title_field" => false,
        "title_field_required" => false,
    ))
    ->setDisplayOptions('form', array(
        'type' => 'image_image',
        'weight' => 5,
    ))
    ->setDisplayOptions('view', array(
        'type' => 'image',
        'weight' => 1,
        'label' => 'hidden',
        'settings' => array(
            'image_style' => 'thumbnail',
        ),
    ));

As you see, you can use tags in the file_directory setting.
If you craft your fields using the Drupal 8 field UI, you can also use tags in the UI field.
If it's D7, you should change to D8 :-)
Comment: It's still Drupal7

File widget custom upload location


How to use curly braces in schema default value?

Question: I have a long varchar field that I'm using to save serialised data with drupal_write_record. I'd like to set the default value of the column to "a:0:{}" (which is serialize(array())).
However, when Drupal runs database updates, they are run through the update_sql() function which includes the default value in the query. This means that the '{' and '}' are interpreted as prefixing table names and removed, leaving the actual value of "a:0:" in the database, which is not what I want.
Is there a way to use curly braces in a field spec's "default" value?
Comment: May you show the code you use to update the database schema?
Answer: In your schema, for the field you want to serialize, you can add the key serialize => TRUE and use the drupal_write_record() function to write the field in the database. After, you have just to send a simple array()(without serialize()) and Drupal will do it by himself.
You can have more information in the documentation.
Comment: I am already doing this. You do have to serialise the value yourself when you define the field in your schema and database update function, e.g.: `$spec = array('default' => serialize(array()), 'type' => 'varchar', ...);` And yes, it works correctly for use from `drupal_write_record`... the real question is how to specify the default value that is compatible with that.
Comment: Ok I see, like you added on drupal.org it's a real bug, even in Drupal 7 and I didn't check but I guess it's the same in Drupal 8.
Answer: If you use db_query, you can do something like this, normally only the curly braces inside the SQL string are replaced.
db_query("UPDATE {mytable} SET myfield = :data", array(':data' => "a:0:{}"));

Comment: What I was really after was a way to specify it in the schema using drupal schema api, so that the module could be deployed, etc.
Comment: We normally never provide a default for serialized fields, why do you need to do it?
Comment: Why do you ever have default data? Why do you ever have serialized fields? They are both valid, independently of each other. A default value can be set in the schema, and it works, so long as there is no curly braces in them.
Comment: I think you misunderstood me, we use default values if we can and if it makes sense, but I never saw Drupal core and/or any other module use a default for serialized data. I agree it would be nice if you could specify a default, but AFAIK it isn't necessary.
Comment: Best thing todo is to open an issue (bug report or feature request) against Drupal 8 core, so it might get fixed.
Answer: There is already a bug report for Drupal 6, Impossible to insert serialized data with update_sql(), but the bug was never fixed.
The issue is only for Drupal 6, as Drupal 7 doesn't use anymore update_sql(). The only workaround is using your own function, instead of update_sql().
function mymodule_update_sql($sql) {
  $args = func_get_args();
  array_shift($args);

  $result = db_query($sql, $args);
  $sql = mymodule_query_get_string($sql, $args);
  return array('success' => $result !== FALSE, 'query' => check_plain($sql));
}

function mymodule_query_get_string($query) {
  $args = func_get_args();
  array_shift($args);
  $query = db_prefix_tables($query);

  if (isset($args[0]) and is_array($args[0])) {
    // All arguments are in one array.
    $args = $args[0];
  }
  _db_query_callback($args, TRUE);
  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
  return $query;
}

You can use mymodule_update_sql() in the same way you use db_query(), as it can use placeholders.


Displaying validation errors at the right position in a Django page containing multiple form fields

Question: In a Django social networking website I built, users can chat in a general room, or create private groups.
Each user has a main dashboard where all the conversations they're a part of appear together, stacked over one another (paginated by 20 objects). I call this the unseen activity page. Every unseen conversation on this page has a text box a user can directly type a reply into. Such replies are submitted via a POST request inside a <form>.
The action attribute of each <form> points to different urls, depending on which type of reply was submitted (e.g. home_comment, or group_reply). This is because they have different validation and processing requirements, etc.
The problem is this: If a ValidationError is raised (e.g. the user typed a reply with forbidden characters), it gets displayed on multiple forms in the unseen_activity page, instead of just the particular form it was generated from. How can I ensure all ValidationErrors solely appear over the form they originated from? An illustrative example would be great!

The form class attached to all this is called UnseenActivityForm, and is defined as such:
class UnseenActivityForm(forms.Form):
    comment = forms.CharField(max_length=250)
    group_reply = forms.CharField(max_length=500)
    class Meta:
        fields = ("comment", "group_reply", )

    def __init__(self,*args,**kwargs):
        self.request = kwargs.pop('request', None)
        super(UnseenActivityForm, self).__init__(*args, **kwargs)

    def clean_comment(self):
        # perform some validation checks
        return comment

    def clean_group_reply(self):
        # perform some validation checks
        return group_reply

The template looks like so:
{% for unseen_obj in object_list %}

    {% if unseen_obj.type == '1' %}

    {% if form.comment.errors %}{{ form.comment.errors.0 }}{% endif %}
    <form method="POST" action="{% url 'process_comment' pk %}">
    {% csrf_token %}
    {{ form.comment }}
    <button type="submit">Submit</button>
    </form>

    {% if unseen_obj.type == '2' %}

    {% if form.group_reply.errors %}{{ form.group_reply.errors.0 }}{% endif %}
    <form method="POST" action="{% url 'process_group_reply' pk %}">
    {% csrf_token %}
    {{ form.group_reply }}
    <button type="submit">Submit</button>
    </form>

    {% endif %}

{% endfor %}

And now for the views. I don't process everything in a single one. One function takes care of generating the content for the GET request, and others take care handling POST data processing. Here goes:
def unseen_activity(request, slug=None, *args, **kwargs):
        form = UnseenActivityForm()
        notifications = retrieve_unseen_notifications(request.user.id)
        page_num = request.GET.get('page', '1')
        page_obj = get_page_obj(page_num, notifications, ITEMS_PER_PAGE)
        if page_obj.object_list:
            oblist = retrieve_unseen_activity(page_obj.object_list)
        else:
            oblist = []
        context = {'object_list': oblist, 'form':form, 'page':page_obj,'nickname':request.user.username}
        return render(request, 'user_unseen_activity.html', context)

def unseen_reply(request, pk=None, *args, **kwargs):
        if request.method == 'POST':
            form = UnseenActivityForm(request.POST,request=request)
            if form.is_valid():
                # process cleaned data
            else:
                notifications = retrieve_unseen_notifications(request.user.id)
                page_num = request.GET.get('page', '1')
                page_obj = get_page_obj(page_num, notifications, ITEMS_PER_PAGE)
                if page_obj.object_list:
                    oblist = retrieve_unseen_activity(page_obj.object_list)
                else:
                    oblist = []
                context = {'object_list': oblist, 'form':form, 'page':page_obj,'nickname':request.user.username}
                return render(request, 'user_unseen_activity.html', context)

def unseen_group_reply(group_reply, pk=None, *args, **kwargs):
            #similar processing as unseen_reply

Note: the code is a simplified version of my actual code. Ask for more details in case you need them.
Comment: Please also add the view where you are creating the form and unseen objects. It looks like you are using the same form for all the unseen objects. Looking at the template it also seems that the same URL is being used in all the forms.
Comment: @AKS: Indeed, you're right. I added views as well, have a look. What would be a workaround here?
Comment: You need to create separate form for each unseen activity to make sure that only the form related to certain activity displays the error. Also, the `action` you are using in each form is not utilizing the `pk` url params at all.
Comment: @AKS: sorry the `action` was erroneously shown - I've amended it (in my real code, I did include the `pk`). Re: making separate forms for each unseen_activity, this is the part that's confusing me. I'm generating the forms in a for loop - there can be many unseen activities (so I paginate it by 20). How would I create them manually with a unique identity here? Can't seem to wrap my head around it. Can you give me an example?
Comment: The `form` you are using in the for loop is created in the view and passed to template through context. So you are using the same form instance for all the unseen activities. What you need to do is create a separate form for each unseen activity in the view context itself. And, have a mapping between the form and the activity which you can use to render the form later.
Answer: Following the discussion in the comments above:
What I suggest is that you create a form for each instance in the view. I have refactored your code to have a function which returns object lists which you can use in both unseen_reply and group_reply functions:
def get_object_list_and_forms(request):
    notifications = retrieve_unseen_notifications(request.user.id)
    page_num = request.GET.get('page', '1')
    page_obj = get_page_obj(page_num, notifications, ITEMS_PER_PAGE)
    if page_obj.object_list:
        oblist = retrieve_unseen_activity(page_obj.object_list)
    else:
        oblist = []

    # here create a forms dict which holds form for each object
    forms = {}
    for obj in oblist:
        forms[obj.pk] = UnseenActivityForm()

    return page_obj, oblist, forms

def unseen_activity(request, slug=None, *args, **kwargs):
    page_obj, oblist, forms = get_object_list_and_forms(request)

    context = {
        'object_list': oblist,
        'forms':forms,
        'page':page_obj,
        'nickname':request.user.username
    }
    return render(request, 'user_unseen_activity.html', context)

Now, you need to access the form in template using the object id from forms dict.
{% for unseen_obj in object_list %}

    {% with forms|get_item:unseen_obj.pk as form %}
        {% if unseen_obj.type == '1' %}

            {% if form.comment.errors %}{{ form.comment.errors.0 }}{% endif %}
            <form method="POST" action="{% url 'process_comment' pk %}">
                {% csrf_token %}
                {{ form.comment }}
                <button type="submit">Submit</button>
            </form>

        {% elif unseen_obj.type == '2' %}

            {% if form.group_reply.errors %}{{ form.group_reply.errors.0 }}{% endif %}
            <form method="POST" action="{% url 'process_group_reply' pk %}">
                {% csrf_token %}
                {{ form.group_reply }}
                <button type="submit">Submit</button>
            </form>

        {% endif %}
    {% endwith %}
{% endfor %}

While processing the reply, you again need to attach the form which throws error with the particular object pk:
def unseen_reply(request, pk=None, *args, **kwargs):
    if request.method == 'POST':
        form = UnseenActivityForm(request.POST,request=request)
        if form.is_valid():
        # process cleaned data
        else:
            page_obj, oblist, forms = get_object_list_and_forms(request)

            # explicitly set the form which threw error for this pk
            forms[pk] = form

            context = {
                'object_list': oblist,
                'forms':forms,
                'page':page_obj,
                'nickname':request.user.username
            }
            return render(request, 'user_unseen_activity.html', context)

Comment: I see. Very nuanced answer, exciting to try it out right now. I'll get back to you in a bit, thanks a bunch for chiming in mate :-)
Comment: Btw I got curious while thinking about this: would `formsets` have worked for my particular problem?


getClan.then is not a function

Question: I have a script that I wrote to scrape a element off a page in a function and then call for the function later.
(I am using javascript, node.js, axios, and cheerio)

const axios = require('axios')
const cheerio = require ('cheerio')

var clanName = ''
var clanID = 5402
const page_url = 'https://www.brick-hill.com/clan/' + clanID

getClan = async function getClanName() {
  const { data } = await axios.get(page_url);
  const $ = cheerio.load(data);
  const header = $('body > div.main-holder.grid > div:nth-child(2 > div.card > div.top > span)');
  const name = header.find('.clan-title').each((i, element) => {
    const nameElement = $(element);
    const nameText = nameElement.text
    console.log(nameText)
  })
}
console.log(page_url)

getClan.then(function(result) {
  console.log(nameText)
})

But the thing is, its giving me an error:
TypeError: getClan.then is not a function
I can't figure out whats wrong with the code. Send help!
Comment: You have to actually call functions... `getClan().then(...)`
Comment: Why aren't you using a `const/let` before the identifier of your function?
Comment: Sorry everyone i'm new to javascript and i'm just figuring this out, but thanks for the help so far.
Comment: No problem, Just ask if there was a specific reason why you didn't enter const or let.
Answer:  ---------------- Read my comments carefully ----------------
const axios = require('axios')
const cheerio = require ('cheerio')

var clanName = ''
var clanID = 5402
const page_url = 'https://www.brick-hill.com/clan/' + clanID

const getClan = async function getClanName() { // used const here to solve the problem
  const { data } = await axios.get(page_url);
  const $ = cheerio.load(data);
  const header = $('body > div.main-holder.grid > div:nth-child(2 > div.card > div.top > span)');
  const name = header.find('.clan-title').each((i, element) => {
    const nameElement = $(element);
    const nameText = nameElement.text
    return nameText  // returned nameText
  })
}
console.log(page_url)

getClan().then(function(result) { // you have to invoke the function with ()
  console.log(result) // logged result
})

Comment: Thanks Faruk! I totally forgot to define the function with const haha and I've really never used the .then part so thanks!

getClan.then is not a function


Preprocess language switcher block

Question: I'm trying to modify the output of the language switcher block to make the output more inline with other menu styles on my site. However, I can't figure out how to modify the output.
I'm attempting to use the following:
<code>function my_module_preprocess_block(&$variables) {
  var_dump($variables['elements']['#id'];
}
</code>
This gets every block on the page except for the language switcher.
How can I preprocess or modify this?
Comment: What do you need to change exactly? Markup or classes (or both)?
Answer: We added a filter to drop the languages that did not have translations from the language switcher.  Here's the code from that:
<code>/**
 * Implements hook_block_view_BASE_BLOCK_ID_alter().
 */
function mymodule_block_view_language_block_alter(array &$build, BlockPluginInterface $block) {
  $build['#pre_render'][] = '_mymodule_language_block_prerender';
}
</code>
FYI - Used pre_render because I was removing links from the [content][[#links] element.

Preprocess language switcher block


Repair Table After Server Upgrade

Question: Hello i hope someone can help me with this on here as i posted on drupal.org and folks told me it wasnt a drupal issue. I dont mind learning stuff but ive got so much drupal things that i do know about to get on with to get my site open that i dont want to spend a week trying to learn more about databases. All help appreciated. thanks.
My hosting company upgraded their servers the other now. Now my statistics module is all messed up and it's asking me to repair a table. The error message is-

User warning: Table './onlineba_d939/node_counter' is marked
  as crashed and should be repaired query: SELECT totalcount, daycount,
  timestamp FROM node_counter WHERE nid = 4389 in _db_query() (line 148
  of /home/onlineba/public_html/includes/database.mysql.inc).

and

User warning: Table './onlineba_d939/node_counter' is marked
  as crashed and should be repaired query: SELECT node.nid AS nid,
  node.title AS node_title, node_counter.totalcount AS
  node_counter_totalcount FROM node node LEFT JOIN og_ancestry
  og_ancestry ON node.nid = og_ancestry.nid LEFT JOIN node
  node_og_ancestry ON og_ancestry.group_nid = node_og_ancestry.nid LEFT
  JOIN og_uid og_uid ON node.nid = og_uid.nid LEFT JOIN node_counter
  node_counter ON node.nid = node_counter.nid WHERE (node.status = 1)
  AND (og_uid.uid = 1) ORDER BY node_counter_totalcount DESC LIMIT 0, 10
  in _db_query() (line 148 of
  /home/onlineba/public_html/includes/database.mysql.inc).

I have access to PHPmyadmin and i have a very very basic understanding of it. Is there a line of code or query i need to put in it to repair? I should go look maybe there is just a repair button. I think i saw that before. Anyone offer me any help before i destroy everything?
thanks
Comment: Managed to get an answer over by. Soz. I just wanted it to be sorted. The answer is

The table's name is node_counter. The statement then becomes.

REPAIR TABLE node_counter;

Nice and easy. Thanks
Answer: Since you have PHPMyAdmin, you should be able to fix this with some point and clicking.

Navigate to the node_counter in your Drupal database
Go to the 'Operations' tab
Hit check tables
If something isn't right it should give you the option to repair

If the option to repair doesn't come up and it doesn't appear in the Operations tab (some of these move around version to version of PHPMyAdmin), you can run the command
<code>REPAIR TABLE node_counter;
</code>
from the SQL tab.
Good luck!

Repair Table After Server Upgrade


Send SSL requests to localhost:port using apache

Question: I'm running a meteor application, due to restrictions I must use Apache as the webserver. There are also other existing websites hosted on the same domain under different locations e.g. https://example.com/phpsite1, https://example.com/phpsite2.
The application I'm interested in runs on http://localhost:3000.
Essentially I would like to have a new location on the same domain, https://example.com/mymeteorapp where requests to this page map to http://localhost:3000.
I've been playing with proxypass but struggling to get something working. Any help or examples would be great.
Answer: The classic reverse proxy syntax would be set up within a <Location> tag in the Apache config. Something like:
<Location "/mymeteorapp1/">
  ProxyPass "http://localhost:3000/"
</Location>

Should do what you want. This will strip everything off after the /mymeteorapp1/ and  feed it to the backend application running on port 3000. The documentation at https://httpd.apache.org/docs/current/mod/mod_proxy.html#proxypass provides some very clear examples.
Comment: thanks! due to routing in the meteor application i couldn't use the location `"/mymeteorapp1/"` i had to use `"/"`. also to make sure i could access the other php sites at different locations i needed to add `ProxyPass /phplocation !`


Update activity data (Data from cumming form server) without refresh activity

Question: I have a question please help me. I make an app in which on a activity i get data from server. I have an admin panel in which there is form, I fill form and save data in Database. My question is i want when i save or update any data in Database the app show the new data without refresh the activity like cricket score updates etc. Please give your suggestions.
Comment: Whats do you mean by refresh?
Comment: Like my app show 10 balls 50 runs, and user stay on that activity. Then admin update data in Database and now new data is 20 balls 100 runs. I want to instant update of data in activity of app.
Answer: It can be done using Room database.
Databse class may look like this:
open abstract class MDatabase : RoomDatabase() {
abstract fun dataDAO(): DataDAO

}
The Dao interface may look like the below:
@Dao
interface DataDAO {
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun saveData(dataEntity: DataEntity)

@Query(SELECT_ALL_DATA)
fun observeDB(): LiveData<Array<DataEntity>>

}
In the activity:
database.dataDAO()
.observeDB()
.observe(this, Observer<Array<DataEntity>> {
   //Update UI
})


About the $\dim(\{\phi\in V^*:\phi\wedge T=0\})$

Question: Hi I need help with this exercise:
Let $V$ a vector space such that $\dim (V)=n$ and $n(T)=\{\phi\in V^*:\phi\wedge T=0\}$.  I want to show that if $T\in\wedge^{n-1}V^*$ then $\dim(n(T))=n-1$. Thanks.
Answer: I guess you are assuming $T\neq0$. You can write everything in coordinates. Let $dx^1,\ldots,dx^n$ be a basis of $V^*$. So, write $$T=\sum T_idx^1\wedge\ldots\widehat{dx^i}\ldots\wedge dx^n,$$and then $\phi\wedge T=0$ becomes a homogeneous linear equation in $\phi_1,\ldots,\phi_n$, where $$\phi=\phi_idx^i.$$