Tag Users and Taxonomy terms in body field of a post

Question: I am building a Social Networking site in drupal. My client requirement is to tag users and taxonomies using a '$'. For example "$john" will tag a user john with that post. and "$Arts and Entertainment" should tag the Taxonomy term to the post.
I tried hashtags module. But it is for tagging the words in body with a "#". The words are tagged under a separate vocabulary called "Hashtags".
My functionality needs twitter OR facebook like tagging of both users and Taxonomies(with a autocomplete Dropdown).
For tagging the taxonomies, I have created a separate field called Industry Tags of type Term Reference in that content type. This field will store the mapping of that particular node to the Industry Terms(Taxonomy Terms). Iam not going to display this Industry Tags field in the frontend. Instead of that i have to save the terms that user enters in the Body field prefixed with "$" to in this field. Example: "$Education".
Also for tagging users i can use "User Reference" in the same manner i mentioned above for industry tags. But i need the functionality to be something similar to twitter / facebook.
Please suggest me some ideas for implementing this.
Answer: It will be interesting logic to figure out whether $art is a user or the start of the $art and entertainment taxonomy term, but, regardless, what you are most probably looking for is an input filter that can recognize a pattern in the text and then both create a link to either the user or taxonomy term as well as actually tagging the node with that taxonomy term if it is one.
A start might be to take a peek at the Hashtags Module and change its use of # to $ for the taxonomy portion and then extend it to include users.
Comment: your need for a different token ($ vs #) plus the need for it to be able to link in users as well as taxonomies (plus autocomplete dropdowns) dictates in my opinion a custom module.
Comment: Thanks for your reply. I think the hashtags module is for tagging the words in body with a "#" and those words will be tagged under a separate vocabulary called "Hashtags". My functionality needs twitter / facebook like tagging of both users.
Comment: Also i have tried Rules Autotag Module to extract the terms out of body. But that does not support the prefixing of the term with "$". I have added some more points to my question. Should i go for a custom module for this.? Please advice.
Comment: @Manojkumar Is it possible to have hashtags functionality in D8?
Answer: For taxonomy terms you can use Active Taxonomy Links...I'm not sure for users...
Answer: The mention module can do this
"The Mentions module offers Twitter like functionality, recording all references to a user's username - using the [@username] or [@#uid] filter format - from various locations, providing a centralized page to track all mentions."
https://drupal.org/project/mentions


Regularity of the initial condition for a stochastic differential equation

Question: We consider a continuous stochastic stochastic process $X_t$ with the following dynamic on $[0,T]$ :
$$
dX_{t}^{x} = rX_{t}^{x}dt + \sigma X_{t}^{x}dB_t
$$
Where $X_{0}^{x}=x$ is the initial condition, $r>0$, $B_t$ is a standard Brownian motion and $\sigma>0$.
Consider $\psi$ a $C^1$ and lipschitz function from $\mathbb{R}\to\mathbb{R}$.
My aim is to compute the derivative of
$$
f(x) = \mathbb{E}\left[\psi\left(\int_{0}^{T}X_{s}^{x}ds\right)\right]
$$
It seems natural to study the regularity of $f(x)$ first and given the strong assumption on $\psi$, the fact that $f$ is $C^{1}$ should be the minimum we expect from $f$, something I would like to prove first.
Finally, in order to find the derivative of $f(x)$ I have some ideas using the fact that a lipschitz function has bounded derivative (something which should be compatible with a dominated convergence theorem).
However the fact that the variable of interest is the initial condition of my SDE makes me think that before using the regularity of $\psi$ I should look to the regularity of the mapping $x\mapsto X^{x}$ something I have not seen in stochastic calculus.
If someone is able to help me in my understanding of this notion of regularity w.r.t the initial condition it would be helpful.
Thank you a lot !
Comment: Can you fix the Latex formatting issue? Can't read the definition of $f$
Answer: The geometric Brownian motion
$$
dX_{t}^{x} = rX_{t}^{x}dt + \sigma X_{t}^{x}dB_t
$$
is a linear equation with solution given by (see here generally Solution to General Linear SDE)
\begin{align*}
X_t^x =& x \exp\left( t\left( r - \frac{1}{2}\sigma^2(s) \right)  + \sigma B_t\right) =xX_{t}^{1}.
\end{align*}
Thus, for simplicity we let
$$\int_{0}^{T}X_{s}^{x}ds=x\int_{0}^{T}X_{s}^{1}ds=x\Phi_{T}^{1}.$$
So we have by chain rule
$$(\psi\left(x\Phi_{T}^{1}\right))'=\phi'(x\Phi_{T}^{1})\Phi_{T}^{1}.$$
So if $\psi$ has nice enough properties to swap derivative and expectation, we get
$$f'(x)=\mathbb{E}\left[\psi'\left(x\Phi_{T}^{1}\right)\Phi_{T}^{1}\right].$$
Comment: @coboy see updated answer with more details.
Comment: Thank you a lot for your answer Thomas ! The part about the solution to this sde is very clear. However I do not see how you differentiate $\psi\left(\int_{0}^{T}X_{s}^{x}ds\right)$ with respect to $x$ that is the initial condition ?
Comment: Thank you a lot ! I did not think of make appear explicitly $x$ in order to differentiate it, I should. Also by directly proving it is differentiable we get for free the fact it is continuous, which reduces the work to proving that the derivative is a also continuous.


How can I enable clean URLs?

Question: I installed Drupal 7 on Wamp Server. I can't find any checkbox or link to enable clean URLs; I see only the Run the Clean URL Test button.
How can I enable clean URLs?
Answer: The settings for the clean URLs are at admin/config/search/clean-urls.
That page shows the "Enable clean URLs" checkbox only when it is possible to enable them; when the server is not configured to support them, that page shows the following message:

Clean URLs cannot be enabled. If you are directed to this page or to a Page not found (404) error after testing for clean URLs, see the online handbook.

On an Apache server, and with the default settings used from Drupal, clean URLs work if:

The mod_rewrite module is enabled for the server
The following directives are present in the Apache configuration file
AllowOverride All
AccessFileName .htaccess

Comment: I needed to alter AllowOverride specifically within this section of httpd.conf:

    -----

Not within the  section
Answer: Enable the mod_rewrite module then restart the wampserver.
I think you can enable the mod_rewrite from the quick launch icon. Right click and view open the apache modules menu and make sure the mod_rewrite is enabled.
UPDATE:
Open the file httpd.conf inside apache installation folder and edit the following line:
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
AllowOverride None

To be:
AllowOverride All

Comment: I cannot find mod_rewrite module in the apache modules.
Comment: I had changed the httpd.conf file. But nothing happens.
Comment: Disable the apache service and re-enable it. If still no effect, restart your PC.
Comment: I already done these. Any other reason?
Comment: doesn't work.  There are 3 instances of "AllowOverride" in my httpd.conf.  Only 1 can be changed and the sites be served (on restart). Also believe setting ".htaccess" is a red herring: this is default. Possibly you *can't* actually enable Clean_URLs on a Windoze box with Apache... (?)
Answer: How I solved my problem:
Clean URLS:

Enable the mod_rewrite with this command:
a2enmod rewrite

Then under /etc/apache2/sites-available edit the "default" file and replace Override None with Override All. This needs to be changed twice.
Restart Apache
Comment: OP wants an answer which applies to Windows OS
Comment: I have the following configuration CentOs 6.7
Drupal 7.39 Just by changing 'AllowOverride None' to 'AllowOverride All' helped me to fix the issue. I have not done 'a2enmod rewrite'
Answer: Please enable rewrite_module for apache using wampserver interface.
To access it click on the green "w" icon in systray, go to apache > apache modules > click on rewrite_module.
your wampserver icon should turn red and then orange and green. If not try restarting wampserver. When the icon is green visit the apache modules again and ensure that rewrite_module is checked.
enabling rewrite_module is essentially turning on mod_rewrite, but dont know why wampserver calls it so. Hopefully it solves your issue with clean urls, you can verify its fixed by running the test again.
Answer: For cleaning URL open Terminal -> Type the command vim /etc/apache2/sites-enabled/000-default
It would open the 000-default file there you would see
<VirtualHost *:80>
ServerAdmin webmaster@localhost

DocumentRoot /var/www
<Directory />
    Options FollowSymLinks
    AllowOverride none
</Directory>
<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
    AllowOverride None
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Order allow,deny
    Allow from all
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>

</VirtualHost>

So select the entire code and put this in place of the code in 000-default file.
<VirtualHost *:80>
ServerAdmin webmaster@localhost

DocumentRoot /var/www
<Directory />
    Options FollowSymLinks
    AllowOverride All
</Directory>
<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
    AllowOverride None
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Order allow,deny
    Allow from all
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>

</VirtualHost>

Now restart the aparche server using
sudo service apache2 restart

Comment: OP using Windows box (the "W" in WAMPP).  Drupal's Clean_URLs seems to be designed to work on Linux.  The different platform is therefore the point of OP's post, I believe.
Answer: You can use this by .htaccess file
First find this line of code in .htaccess file
#RewriteBase /

and replace it with following line of code:
RewriteBase /~yoursitename/yoursitename

Remove # from the code. Here yoursitename is the folder name after domain name like example.com/~yoursitename/yoursitename.
Answer: We need to uncomment or add the line:
LoadModule rewrite_module modules/mod_rewrite.so

to enable mod_rewrite Apache module.

How can I enable clean URLs?


Android WorkManager - get unfinished works from WorkManager

Question: is there any way to get all unfinished works from WorkManager from android-jetpack? I know you can get Works by id/tag. But cannot find some way to get all unfinished Works? Thanks for answers :)
Comment: This doesn't look like one of the supported use cases...
Can you expand a bit your question...What are you trying to implement here?
Comment: My usecase is that you must continue you work after all request all done. And do you if in WorkManager is way to call Works in the order in which they were created?
Comment: You can append work in a unique work request, this creates a Chain for you that maintains the order of execution. Is this what you're looking for?
Comment: Yes, that is what I am looking for. Do you have some examples for working with unique requests in chain?
Answer: If what you want to achieve is to maintain the order of your work requests, an approach is to use an UniqueWorkRequest using as ExistingWorkPolicy the APPEND one. This creates for you a chain of work:
WorkManager.getInstance(context).enqueueUniqueWork("unique name", ExistingWorkPolicy.APPEND, myOneTimeWorkRequest)

You can find more information in WorkManager's Unique Work guide. Keep in mind that if you cancel a work request in the chain or return failure from your worker, the all chain is cancelled or marked as failed.
Comment: And is there some way to cancel one of the work by tag?
Comment: If we're talking about Workers in a chain (like for a unique work request using the APPEND policy), you can only cancel the whole chain.
In general, as far you have assigned a tag to a work request, you can use `WorkManager.cancelAllWorkByTag(String)`. You can see the doc at:  https://developer.android.com/topic/libraries/architecture/workmanager/how-to/cancel-stop-work
Comment: Thanks a lot :) . And is there some way, to cancel the Work by tag in chain (i am using unique work with APPEND policy)? My use case is that you have works in chain waiting for network constraint, but in some point I need to cancel one of the work in chain?
Comment: As I wrote, you cannot cancel a single Worker in a chain. You need to handle such situation passing the information that a Worker don't need to run in some other way (maybe setting some flag in your datastore).


DownloadFileAsync Error

Question: I keep get this error while trying to download a file using WebClient.DownloadFileAsync

System.Net.WebException: The underlying connection was closed: An
  unexpected error occurred on a receive. ---> System.IO.IOException:
  Unable to read data from the transport connection: An established
  connection was aborted by the software in your host machine. --->
  System.Net.Sockets.SocketException: An established connection was
  aborted by the software in your host machine
  at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
  at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
  --- End of inner exception stack trace ---
  at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
  at System.Net.PooledStream.EndRead(IAsyncResult asyncResult)
  at System.Net.Connection.ReadCallback(IAsyncResult asyncResult)
  --- End of inner exception stack trace ---
  at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
  at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
  at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)

The code:
try
{
    client.DownloadFileAsync(URL, location);
    client.Dispose();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

Comment: press ctrl+c on message box to copy the error message and paste it here instead of uploading it's picture.
Comment: can you give us the url and location parameter?
Comment: Well i'm not sure how to do that, in java i use synchronized(OBJECT_LOCK).... to avoid those kind of errors but in c# i'm still learning so could you be more clear if you don't mind
And okay the link is the code http://pastebin.com/mPNsyrXC
Comment: try testing your code with known file url. maybe the url is incorrect
Comment: That actually worked for me, thanks alot where i can give rep if that possible :D
Answer: I think the problem is in the URL you supplied to the DownloadFileAsync method.
try double checking the URL, test it with a known URL that exists.

DownloadFileAsync Error


Reducing $\frac{\left(\left(\sqrt{\frac{a + b}{a - b}}\right)^2+1\right)\cdot c}{2c\sqrt{\frac{a + b}{a - b}}}$ to $\frac{1}{\sqrt{1 - b^2/a^2}} $

Question: I want to rearrange
$$ \frac{\left(\left(\sqrt{\frac{a + b}{a - b}}\right)^2+1\right) \cdot c}{2c \cdot \sqrt{\frac{a + b}{a - b}}} $$
into $$ \frac{1}{\sqrt{1 - b^2/a^2}} $$
I would be grateful for some hints or full explanation.
I do know you can get rid of $c$ and the root above easily.
Answer: HINTS: After cancelling the $c$ as you mention, we have
\begin{align}
\frac{\left(\sqrt{\frac{a + b}{a - b}}\right)^2+1}{2 \sqrt{\frac{a + b}{a - b}}}
= \frac{\left(\sqrt{\frac{a + b}{a - b}}\right)^2}{2 \sqrt{\frac{a + b}{a - b}}} + \frac{1}{{2 \sqrt{\frac{a + b}{a - b}}}}
\end{align}
Now you can easily cancel stuff in the first term. Do you see how?
If you get stuck along the way, check out the spoilers by hovering your mouse over them (if you're on a computer).
Step 1: Canceling as mentioned above.

 $$=\frac{\sqrt{\frac{a + b}{a - b}}}{2} + \frac{1}{{2 \sqrt{\frac{a + b}{a - b}}}}  = \frac{\sqrt{a + b}}{2\sqrt{{a - b}}} + \frac{\sqrt{a - b}}{2\sqrt{a + b}}$$

Step 2: Make denominators equal.

 $$=\frac{a + b}{2\sqrt{{(a - b)(a + b)}}} + \frac{a - b}{2\sqrt{(a + b)(a - b)}}$$

Step 3: Now add and cancel.

 $$=\frac{a + b + (a - b)}{2\sqrt{{(a - b)(a + b)}}} = \frac{2a}{2\sqrt{{(a - b)(a + b)}}}$$

Step 4: Bring everything under the square root.

 $$= \frac{a}{\sqrt{{a^2 - b^2}}} = \sqrt{\frac{a^2}{a^2 - b^2}}$$

Step 5: Divide to get the desired form.

 $$ = \sqrt{\frac{1}{\frac{a^2}{a^2} - \frac{b^2}{a^2}}} = \frac{1}{\sqrt{1 - b^2 / a^2}}.$$


Relative interior of Cartesian product

Question: I need to manipulate a relative interior in the context of a convex optimisation problem I am dealing with. However, it is a notion I am not familiar with and I would like to check that my reasoning is correct. I want to prove $-$ disclaimer: I am unsure whether this is true $-$ the following property:

$$ \forall \, i \in [1,k], \, n_i \in \mathbb{N} \, : \, \text{relint} \left(\prod_{i=1}^k \mathbb{R}^{n_i}\right) = \prod_{i=1}^k \mathbb{R}^{n_i} $$

By commutativity of the Cartesian product and the relative interior (Relative interior commutes with cartesian product), it suffices to prove for $n \in \mathbb{N}$:
$$\text{relint}(\mathbb{R}^n) = \mathbb{R}^n$$
Now, letting $\text{aff}$ be the affine hull of a set $S$, to me it is clear that:
$$ \text{aff}(\mathbb{R}^n) = \mathbb{R}^n $$
Indeed, from the definition of an affine hull:
$$ \text{aff}(\mathbb{R}^n) = \left \{ \sum_{i=1}^m \lambda_i x_i : m>0, x_i \in \mathbb{R}^n, \lambda_i \in \mathbb{R}, \sum_{i=1}^m \lambda_i = 1 \right \} $$
It suffices to take $m=1$ and $\lambda \equiv \lambda_1 = 1$, then every element $x$ of $\mathbb{R}^n$ is equal to $\lambda x$.
Subsequently, from the definition of the relative interior $-$ where $N_{\epsilon}(x)$ is a ball of centre $x$ and radius $\epsilon$:
$$\text{relint}(\mathbb{R}^n) = \left \{ x : x \in \mathbb{R}^n, \ \exists \, \epsilon \in \mathbb{R}_+^*, \ N_{\epsilon}(x) \cap \text{aff}(\mathbb{R}^n) \subseteq \mathbb{R}^n \right \} $$
Given that $\text{aff}(\mathbb{R}^n) = \mathbb{R}^n$ and for any $x \in \mathbb{R}^n$, any ball $N_{\epsilon}(x)$ is in $\mathbb{R}^n$, we get:
$$\ N_{\epsilon}(x) \cap \text{aff}(\mathbb{R}^n) \subseteq \mathbb{R}^n \Leftrightarrow \ N_{\epsilon}(x) \subseteq \mathbb{R}^n $$
which is true for all $x \in \mathbb{R}^n$, and we can conclude that:
$$ \text{relint}(\mathbb{R}^n) = \mathbb{R}^n $$
Is my reasoning correct?
Answer: Your proof is correct, but in general if the interior of a set is nonempty then interior and relative interior coincide i.e.,
$$ \text{int} (A) = \text{relint} (A) $$
Now your claim trivially follows .

Relative interior of Cartesian product


Data table aggregation and using toString()

Question: I was trying to create a function where I aggregate data table values on the basis of one column but I can't pass the argument in toString() for column names. The following example can show it better:
t1 <- data.table(P = c("a", "b", "c", "d", "a", "b"), Q =
c("1","2","3","4","5","6"))

t1[ ,toString(Q), by = P] # this works
t1[ ,toString(colnames(t1)[2]), by = P] #  this does not give me the desired result

I get the following result with the above:
   P V1
1: a  Q
2: b  Q
3: c  Q
4: d  Q

As compared to the expected:
   P   V1
1: a 1, 5
2: b 2, 6
3: c    3
4: d    4

I have tried removing the quotes using noquotes() but nothing works out for me.
Can anyone point out where I might be making a mistake?
Answer: We can use get to return the value
t1[ , toString(get(colnames(t1)[2])), by = P]
#   P   V1
#1: a 1, 5
#2: b 2, 6
#3: c    3
#4: d    4

Or with eval/as.symbol
t1[, toString(eval(as.symbol(names(t1)[2]))), by = P]

Or the standard way would be to specify in .SDcols
t1[, toString(.SD[[1]]), by = P, .SDcols = names(t1)[2]]

Comment: Thanks a lot!. What is the difference when I use noquote() though?
Comment: Also what if I have a string. I am planning to create a function that passes the column name as an argument.


How can I open Poll for Anonymous users?

Question: I wonder how I can open my poll for everyone including anonymous users, not just registered users.
Answer: Visit admin/user/permissions and check the checkbox for vote on polls for anonymous.


Trying to access array offset on value of type null warning in php

Question: So , i'm tying to use a session in my paynow.php from server.php  but i get a Undefined variable $_SESSION warning followed by the above warning.
Here is my   server.php
<?php
session_start()
  if (isset($_POST['request'])) {
    $amount = $_POST['amount'];
    $value=200;
    $price =$amount *$value;
    $query = "INSERT INTO payments (amount) VALUES ('$price')";
    $result =mysqli_query($db,$query);
    if($result){
        $_SESSION['cost'] = $price;
        header('location:paynow.php');
    } ?>

here is where i'm trying to use the session in   paynow.php
<?php if (isset($_SESSION['cost'])) : ?>

Pay<?php echo $_SESSION['cost']; ?> dollars

    <?php endif ?>

The data is sent to the database but the problem is that i cant use my session. Can someone help please
Answer: I just did not <?php include('server.php')?> in my paynow.php
Comment: Please mark as resolved
Answer:     I think you forgot to put a semicolon.
    <?php
    session_start(); <=== put it here at the end of the line
      if (isset($_POST['request'])) {$amount = $_POST['amount'];
        $value=200;
       ...
        } ?>

Also you should start the session at the top of paynow.php

<?php session_start(); ?>

<?php if (isset($_SESSION['cost'])) : ?>

Pay<?php echo $_SESSION['cost']; ?> dollars

    <?php endif ?>


Mudar conteúdo de um Spinner através de um radiobutton

Question: Usei esse código para mudar o conteúdo de um Spinner com um radiobutton mas não resulta. Peço vossa ajuda:
public class ExemploActivity extends Activity {
    ImageView image;
    EditText nome,codigo;
    Spinner sexo, curso;
    RadioButton tecnologias, letras;
    RadioGroup r1;
    private static final String[] sex = {"","Masculino","Feminino"};
    private static final String[] AFCT = {"","Energias Renovaveis","TIC's"};
    private static final String[] AFAG = {"","Direito","Recursos Humanos"};
    ArrayAdapter<String> operation,genero,tecs,Camera;

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

        if(tecnologias.isSelected()){
            operation = new ArrayAdapter<String>(ExemploActivity.this,android.R.layout.simple_spinner_item,AFCT);

        }else if (letras.isSelected()){
            operation = new ArrayAdapter<String>(ExemploActivity.this,android.R.layout.simple_spinner_item,AFAG);

        }

        curso.setAdapter(tecs);

        genero = new    ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,sex);
        nome = (EditText)findViewById(R.id.editText1);
        codigo = (EditText)findViewById(R.id.editText2);

        sexo=( Spinner)findViewById(R.id.spinner1);
        sexo.setAdapter(genero);

        tecnologias=(RadioButton)findViewById(R.id.radio1);
        letras=(RadioButton)findViewById(R.id.radio2);

        image = (ImageView)findViewById(R.id.imageView1);
        Camera = new    ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,sex);
        /*image.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 0);
            }
        });*/

        image.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 0);
                return true;
            }
        });

        curso=( Spinner)findViewById(R.id.spinner2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0){
            Bitmap theImage = (Bitmap)data.getExtras().get("data");
            image.setImageBitmap(theImage);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.exemplo, menu);
        return true;
    }
}

Comment: Informe o problema que está ocorrendo, e detalhes do erro que está dando, a stack de erro. Para que possamos lhe ajudar.
Answer: Você deve estar recebendo um NullPointerExeception certo ?
você só esta associando o atributo "tecnologias"  depois de tentar usar um método interno dele, seu código deveria ficar mais ou menos assim para estar correto:
tecnologias = (RadioButton) findViewById(R.id.radio1);
    letras = (RadioButton) findViewById(R.id.radio2);

    tecnologias.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            operation = new ArrayAdapter<String>(ExemploActivity.this, android.R.layout.simple_spinner_item, AFCT);
            operation.notifyDataSetChanged();
        }
    });

Você tem que adicionar listeners para saber quando seus RadioButtons forem acionados pelo usuário.  Se baseia nisso e da uma estudada que tu consegue...
Att


Android: how to deny access to the components of my application from other applications?

Question: Iwant to know how to deny access to the components of my application from other applications
Comment: let me know if it helps u mate...
Answer: By default android os don't allow other app to access your component. So you don't need to worry about it. You have to change permission in case you want to allow other app to access your component.


Pass raw html to #markup

Question: I have some html content, it comes from a external library so i can not change it, it has many  and
 tags with attributes like:
, but when i use:
$render = array(
  '#markup' => $myhtmlcontent,
);

In a render array, Drupal strips the attributes, and it keeps just  without the styles.
So, how can I avoid Drupal changes what I pass as markup, which doesn't need any filter because the library makes it safe, or at last make it allow styles?
Comment: style attributes are always stripped out
Answer: Use inline template:
  return [
    '#type' => 'inline_template',
    '#template' => '{{ somecontent }}',
    '#context' => [
      'somecontent' => $somecontent
    ]
  ];

In your case without context, just straight up html.
You can also use the html_tag element for things like script or link and so on.
Comment: Try {{ variable | raw }} or {{variable}}
Comment: This filters out IFRAME tags.
Comment: @IvanJaros That will just skip auto escaping the variable, but `\Drupal\Component\Utility\Xss::filterAdmin()` will still filter out tags like `
Comment: And script and style tags
Comment: Well, of course if you want to use script or any other "high risk" tags you are not supposed to do it via this method bud via theme function and template, duh.
Answer: In a render array, simply do this:
return [
  '#children' => $html,
];

EDIT: Alternatively use the method described by @nvahalik in the other answer, in combination with '#markup'. I think this is closer to the intended usage of the render API.
use Drupal\Core\Render\Markup;

[..]
return [
  '#markup' => Markup::create($html),
];

E.g. if the $html was produced with PHP's highlight_string(), it will contain style attributes which would be removed with #markup. But #children preserves them.
How to test this?
Go to devel/php (with devel module installed).
$elements = [
 ['#markup' => '
markup onionpowder
' . "\n"],
 ['#children' => '
children onionpowder
' . "\n"],
 ['#markup' => \Drupal\Core\Render\Markup::create('
safe markup onionpowder
' . "\n")],
];

var_export(drupal_render($elements)->__toString());

I personally get this output:
"""
'
markup onionpowder
\n

children onionpowder
\n

safe markup onionpowder
\n
'
"""

(The "onionpowder" allows to set conditional break points in the render functions)
But perhaps it depends on the Drupal version?
Also it can happen that this will be (perhaps unintentionally) processed again in a different point in the pipeline.
Technical notes
See https://git.drupalcode.org/project/drupal/blob/8.8.x/core/lib/Drupal/Core/Render/Renderer.php#L184
The '#markup' is filtered in ->ensureMarkupIsSafe(), which is called from within ->doRender(). The same does not apply to '#children' in the version of Drupal I was using (It's a local test site, cannot update atm).
Comment: Yes - it worked for me. instead #markup use some other keywords like #scode or #children or #customname
Comment: any 'style' attribute is still stripped out of that too (Drupal core 8.8.1)
Comment: @WilliamTurrell Interesting. Do you know which code is responsible for this filtering?
Comment: @donquixote Xss:filterAdmin (see the comments on answer by user21641), and there's a [note here](https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/group/theme_render/8.8.x) (under 'Render Arrays', #markup). Note, [I was having this problem](https://drupal.stackexchange.com/questions/289647/add-inline-style-to-render-array-attributes-without-xss-filtering) when writing a Field Formatter, even using external template files for the output, - which I didn't expect, so I worked around it by overwriting the views-view-fields template too & putting the style attribute there.
Comment: @WilliamTurrell Your links are all about #markup, not #children.
Comment: @donquixote I did *try* returning my FormatterBase render array with an $html string in #children, and it's style attribute was still removed. I'm not sure what else could cause it (all the comments I've seen refer to filterAdmin)
Comment: @WilliamTurrell I added some notes and testing instructions to the answer, can you check if this produces the same behavior for you? Perhaps do some debugging to explore where your #children are filtered?
Comment: 2021, Drupal 9, this worked
Answer: As documented in Render API overview, in Drupal 8 a #markup value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. You can use #allowed_tags to set the list of allowed tags, but that would not stop Drupal from stripping attributes (for example, the style attribute).
$output['audio_controller'] = array(
  '#markup' => '<audio src="//www.example.com/resources/sample.mp3" controls>
Your browser does not support HTML5 audio tags.
</audio>',
  '#allowed_tags' => ['audio'],
);

Since in your case you are passing complex HTML markup, you should use #type or #theme. In this case, #type seems a better solution.
You could also implement a new type, with a render element plugin, but if that is the only case where you need it, then implementing a render element plugin is probably excessive.
Comment: @rockstardev It's better to specify the allowed tags if possible, so that you don't open yourself to as many security risks.
Comment: You can also do '#allowed_tags' => TRUE, instead of specifying each one.
Answer: If you want to add plain Markup to render arrays, you can create it using \Drupal\Core\Render\Markup. This will allow you to put raw HTML into something. For instance, here's how it's used in the Permission Report module to put HTML into tables:
$rows[] = [
  [
    'data' => $this->l($meta['title'], new Url('permission_report.permission', ['user_permission' => $perm], $options)),
  ],
  ['data' => $users_having_role],
  ['data' => Markup::create(implode(', ', $display_roles))],
];

Comment: I know this is two years down the line but thanks. For beginners let me simplify it: use \Drupal\Core\Render\Markup $HeaderSettingsIcon = Markup::create('');
Comment: Even if I pass a style attribute to Markup::create, whilst it's still there in Markup::create's output, it gets stripped out again further up the render array. (I'm trying to generate a CSS background-image on a div dynamically).

Pass raw html to #markup


Uniform convergence - Is f continuous and is f differentiable $f(x) = \sum_{n=1}^{\infty}\frac{1}{2n^2-\sin(nx)}$

Question: Let
f(x) = $\sum_{n=1}^{\infty}$$\frac{1}{2n^2-\sin(nx)}$ ($x\in\mathbb{R}$)
(a) Decide whether f is continuous on R.
(b) Is f differentiable?
Don't even know where to begin with this question, I assume we need to work out if it converges uniformly first but unsure how. I've been practicing with the Weierstrass M-Test for questions such as $\sum_{n=1}^{\infty}$$\frac{\sin(nx)}{n^3}$ etc but not any of this form. Any help would be great!
Answer: The partial sums for $f$, and the deriatives of the partial sums, converge absolutely and uniformly on $\mathbb{R}$. Indeed, if $f_{N}$ denotes the $N$-th partial sum, note $$f_{N}(x) = \sum_{n =1}^{N} \frac{1}{2n^2-\sin(nx)}, f_{N}'(x)= \sum_{n =1}^{N} \frac{n \cos(nx)}{(2n^2-\sin(nx))^2}$$
and we have that $$\left|\frac{1}{2n^2 - \sin(nx)}\right| \leq \frac{1}{2n^2-1}, \ \ \  \left|\frac{n \cos(nx)}{(2n^2-\sin(nx))^2}\right| \leq \frac{n}{(2n^2-1)^2}$$
Comment: beat me to it narrowly!
Answer: Noting that:
$$\frac 1 {2n^2 - \sin (nx)} \le \frac 1 {2n^2 - 1}$$
since $-1 \le \sin nx \le 1$ ($x$, $n$ are real) should help you with the Weierstrass M-test.
For the second part, note that we can examine the uniform convergence of:
$$\sum_{n = 1}^\infty \frac \partial {\partial x} \left(\frac 1 {2n^2 - \sin(nx)}\right)$$
to give a sufficient condition for $f$ being differentiable and being equal to its "termwise derivative", noting that each term is differentiable in $x$.


How to get count of *ngFor array in COMPONENT file

Question: How to bind variable c (count of data items) with variable in component.ts file?
In HTML file:

In component.ts file:
if (c > 5) ... else ...

For the sake of simplicity, let's suppose that data is dynamically generated so we can't use data in our component. Only thing I want to accomplish is to use c in component file.
It's NOT DUPLICATE of this: Gunters solution I want clear data binding, without relying on generated DOM.
UPDATE: Real scenario is more complex, I didn't want to add it in order to keep focus on above question, but because someone asked for it, it's here:
In HTML file:

In component.ts:
    if (c > 5) ... // c here is the count of data items after data is filtered
Yes, I know I can manually trigger someFilter in component code and then count number of data items, but that's not preferable solution when you have pipes.
Comment: Can you provide some code showing what you are asking to make things more clear?
Comment: @DanielWStrimpel I have edited my question, look after "UPDATED" section. The thing is I am using filter on for loop, so I can't get count of items iterated in component.ts file.
Comment: I've never used a regular DOM node, but did you see if you can use `ViewChildren` to get a reference to the `` nodes? Like this `@ViewChildren('tr') tableRows: QueryList`. If that works you can watch for changes to that and get the length that way
Answer: Well, I supouse you can use some like:

  <ng-container *ngIf="last">
       Total Count {{i+1}}
  </ng-container>

But I think that is almost "bizarro". I go on thinking that the best approach is have two variables: data and dataFiltered, calculate dataFiltered and make the *ngFor over the dataFilteres.
Answer: Just create a varable c in your component.ts
c = arrayName.length;

Or you can do it in html directly too.
Count: {{arrayName.length}}

Answer: You can add another pipe after your filtering pipe "someFilter", count elements and store the result in a service. Then it can be accessed from anywhere.
transform(input: Model[]): Model[] {
    if (input && this.myService.count !== input.length) {
        this.myService.count = input.length;
    }

    return input;
}


Is it possible to use "route ADD ... MASK ..." command to exclude an application or website from VPN connection?

Question: Following this question, I was pointed out to this page, where it suggests using the
<code> route ADD <destination_network> MASK <subnet_mask> <gateway_ip> <metric_cost>
</code>
command to "Add a Static TCP/IP Route to the Windows Routing Table". However, I don't know how to use this command to exclude certain software (e.g., Skype for Business, Microsoft Teams, Microsoft Outlook, Citrix CVViewer ...) and certain websites from the VPN connection. I would appreciate it if you could help me know how to do it on a Windows machine where I don't have admin privileges.
My environment is Windows 10 version 1803 and my VPN software appears to be F5
Answer: Routing works based on the destination IP address, it doesn't care or even know which application is trying to reach it.
You can add routes to specific target IP addresses or networks, but you will need to know which destination a software will try to reach; otherwise there is no way to do what you are asking.
Comment: It depends on the software. Also, if the software connects to a cloud service, the destination IP ranges can vary wildly. Last but not least, a comunications software such a S4B or Teams will establish peer-to-peer connections to the people you are talking with, which can really be anywhere.
Comment: It would be a lot easier to do the opposite and only use the VPN connection for traffic you actually want to go there (such as traffic directed to your company network) and use your Internet connection fof everything else. This is called split-tunneling. However, you can only do that if the VPN software allows it. You should really ask your network admin.
Comment: Yes, it's possible, but you have to control the VPN configuration; VPNs can work in two ways: either they send *all* your traffic through the tunnel (which seems to be your case), or they only handle the traffic directed to your company network and leave everything else alone. This is part of the VPN configuration, which is usually handled centrally by the VPN server to which you connect.
Comment: F5 supports split-tunneling: https://support.f5.com/csp/article/K55104964. But it needs to be configured on the firewall, you can't do that from the client side.
Comment: If you don't even have admin privileges on your machine, there is *nothing* you can do. Even if this could be managed by manually altering the routing table (which I doubt), you would still need admin rights to do that.
Comment: I don't know what the routes and a target IP are. Any Idea how I can find the destination a software (e.g., Skype for Business) tries to reach?
Comment: Maybe I can create something like a white list instead? Because there are a few software and some network drives on my system that requires the VPN connection. Is it possible to find the IP addresses they communicate with and put them through the VPN?
Comment: Well, I work at a consortium with more than 20K employees. things are really slow here. Usually, I can solve my problems better than the IT department.
Comment: OK, so you think most probably it can't be done in my case? I mean there is not much I can do without the network admins or admin privileges on my machine.


How to get href content

Question: I'm trying to extract link from href.
This is what is visible in page view source but when i inspect using firebug, href will contain http://home.website.com/preview/preview?uname=3eadsf132sdas. I tried using htmlagilitypack but href is returning null. How to extract the link in href.
Comment: That's because an empty `href` means "whatever the current URL is". Agility pack cannot know where you got your HTML from.
Comment: Maddy, you can't. That information *is not available* in the source. What the browsers is showing users *is not coming from the HTML source.* It is probably being populated with javascript or is just missing as the first commenter said (and represents the base page url).
Comment: Is it possible to extract the link. How to get the link in href.
Comment: @Maddy to reiterate what the first commenter says, there is nothing to extract. Firebug is showing you what the *web browser* knows. HTML Agility Pack only knows what the *HTML source* knows. The browser knows where it loaded the HTML from, Html Agility Pack does not. Instead of looking at firebug, look at "view source". That is what HAP actually sees.
Comment: Thank you @jamietre. I got it. My problem is , when a user clicks on that `href` tag, it will be redirected to another page. I want to extract that link. When view source is only not showing the link then how to extract it.
Answer: If you have not tried this way than please try it this way
    HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();

        htmlDoc.OptionFixNestedTags=true;

        htmlDoc.Load(filePath);

 foreach(HtmlNode link in htmlDoc.DocumentElement.SelectNodes("//a[@href"])
 {
    if(link != null)
    {
      if(link["href"] != null)
      {
       HtmlAttribute att = link["href"];
       var url = att.Value;
      }
    }

Comment: Thank you HatSoft, but DocumentElement is giving error and if i use DocumentNode then it's giving error saying that we can not use node as an array.
Comment: @Maddy what's the error thrown by DocumentElement, I use this all the time
Answer: You could try something different, like getting the html content using the WebRequest class (see here how).
If the href doesn't contain any link it could mean that it is being populated using Javascript or some other programming language to add the dynamic content. If you have access to the scripts then you might have a small chance to get the links, but don't think so.

How to get href content


Proving convergence of sequence of points in product space $\prod X_{\alpha}$ iff its projection mappings converge

Question:
Let $x_1, x_2, ... $ be a sequence of points of the product space $\prod X_{\alpha}$. Show that this sequence converges if and only if the sequence $\pi_{\alpha}(x_1)$, $\pi_{\alpha}(x_2)$, ... converges to $\pi_{\alpha}(x)$ for every $\alpha$

My Attempted Proof
Suppose $x_1, x_2$ converges to some point $x = (x_{\alpha})_{\alpha \in J} \in \prod X_{\alpha}$. Assume the sequence $\pi_{\alpha}(x_1)$, $\pi_{\alpha}(x_2)$ ... does not converge to $\pi_{\alpha}(x)$ for some $\alpha$. Put $\gamma = \alpha$ for this $\alpha$. Then we have $\pi_{\gamma}\left((x_{\alpha})_{\alpha \in J}\right) \neq x_{\gamma}$, reaching a contradiction.
Conversely suppose $\pi_{\alpha}(x_2)$, ... converges to $\pi_{\alpha}(x)$ for every $\alpha$. Let $\pi_{\alpha}\left(x_i\right) = x_{i_{\alpha}} $ denote the projection of $x_i \in \prod X_{\alpha}$ onto its $\alpha$th coordinate. Then we have $$x_{1_{\alpha}}, x_{2_{\alpha}}, .... \to x_{n_{\alpha}}$$ where $n  > 0$. Hence we have $$(x_{i \in I})_{\alpha \in J} \to (x_{n})_{\alpha}$$ where $I$ is an arbitrary indexing set and $n = \sup I$. Thus we can see that $x_1, x_2, .. \to x_n = x$. $\square$

Is my proof correct? If so how rigorous is it? I was having some difficulty in proving this as it seemed something that intuitively obvious.
Any comments and criticism on the level of rigor of my proof is greatly appreciated.
Comment: Possible duplicate of [Convergence in product topology](https://math.stackexchange.com/questions/524481/convergence-in-product-topology)
Comment: Your notation is really bad, as you are using subscripts in the same location to mean two different things. Try using superscripts for one of them: The sequence is $\{x_n\}_{n=1}^{\infty}$, and denote $\pi_{\alpha}(y)$ by $y^{\alpha}$ for any $y$. So $x^\alpha_n :=\pi_\alpha(x_n)$.
Comment: There are plenty of topologies for which $\pi_\gamma(x_n)$ does not necessarity converge to $\pi_\gamma(x)$ just because ${x_n}$ converges to $x$. This convergence is a property of the product topology. The fact that your "proof" of this makes no mention of the properties of the product topology is a dead giveaway that it is flawed. the statement "then we have $\pi_\gamma((x_\alpha)_{\alpha \in J}) \neq x_\gamma$" is a non-sequitor. It does not follow from what is before.
Answer: You do need the specifics of the product topology to show this, not just the continuity of projections.
So suppose $X = \prod_{\alpha \in A} X_\alpha$ has the product topology, and $x_n = (x^{(n)})_\alpha$ are points in $X$ for $n \in \mathbb{N}$. Then $x_n \rightarrow p = (p_\alpha)_\alpha \in X$ in the product topology iff for each $\alpha \in A$, $x^{(n)}_\alpha \rightarrow p_\alpha$ in $X_\alpha$.
The left to right implication of this just follows from continuity of $\pi_\alpha$, as $\pi_\alpha(x_n) = x^{(n)}_\alpha$ and $\pi_\alpha (p) = p_\alpha$ and continuity preserves convergence.
For the right to left implication, assume all components converge as stated. Then let $O$ be a basic open neighbourhood of $p$ in the product topology, so $O = \prod_\alpha O_\alpha$ where all $O_\alpha$ are open and $F = \{\alpha \in A: O_\alpha \neq X_\alpha \}$ is finite. Then for each $\alpha \in F$ ,pick $N_\alpha \in \mathbb{N}$ such that $$\forall n \ge N_\alpha: x^{(n)}_\alpha \in O_\alpha$$
by the definition of convergence in the compenent space $X_\alpha$ (as $O_\alpha$ is an open neighbourhood of the limit $p_\alpha$ there).  Then as $F$ is finite (this is esesential here!) there is $N$ such that $N \ge N_\alpha$ for all $\alpha \in F$ (their maximum will do). Then for all $n \ge N$, we know that $x^{(n)}_\alpha \in O_\alpha$ for all $\alpha \in F$, which means that $x_n \in O$ for all $n \ge N$ as well (the only real conditions are on the coordinates from $F$). As we can find such $N$ for every basic open subset of the product, we have shown that $x_n \rightarrow p$, as required.
Note that this argument straightfowardly translates to nets as well, if you know about those. The way we found the $N$ from the $N_\alpha, \alpha \in F$ works in any directed index set not just $\mathbb{N}$.
A critique on your proof: you never use anything specific for the product topology , like their specific base elements, but this property fails for the box topology, which is another topology making the projections continuous (the only thing you're using if you think about it), or for many topologies on sequence spaces (essentially subsets of infinite products) in analysis as well.


Spring Hibernate Many-to-Many Association with transient value

Question: I have two tables Teacher and Student
Teacher(Teacher_id, Teacher_name)
Student(student_id, student_name)
Teacher_Student(id, Teacher_id, Student_id)

I have corresponding model also for each table such as Teacher.java Student.java and TeacherStudent.java
I want to be able to get a result set with list of teachers information and no_of_students per teacher. Eg:
Teacher_id, Teacher_name, No_of_students

I do not want to get a list if teachers and then loop through each teacher_id and find the number of students.
I have a SQL query that does this in one query, but how do I make this work on hibernate. Also I want the No_of_Students value to be transient.
Comment: what did you mean by `but how do I make this work on hibernate`
Comment: I mean to say without having to do two queries, i.e. first query for fetching the list of teachers and then going through each teacher_id to get no_of_students. I am using NamedQuery in the models. So which model should this query reside in?
Answer: No need for two queries you can just use :
Query query = em.createQuery("SELECT t.id, t.name, t.listStudent.size() FROM Teacher");

This will return a List of an array of Object like this :
List<Object[]> result = query.getResultList();

To get the information you can use :
List<Teacher> listTeachers = new ArrayList<>();
for(Object[] info : result){
    listTeachers.add(
       new Teacher(
          (Long) info[0],   // the id
          (String) info[1], // the name
          (Long) info[2]    // the number of students
       )
   );
}

I assume in your Teacher Entity you have a constructor :
public Teacher(String id, String name, Long nbrStudent){
   this.id = id;
   this.name = name;
   this.nbrStudent = this.listStudent.size();
}

and a @Transient variable :
@Transient
private @Getter @Setter Long nbrStudent;

Or in one step :
Query query = em.createQuery(
        "SELECT com.namepackage.Teacher(t.id, t.name, t.listStudent.size()) FROM Teacher"
);
List<Teacher> result = query.getResultList();

Note that I used com.namepackage.Teacher(t.id, t.name, t.listStudent.size())


Read n lines at a time using Bash

Question: I read the help read page, but still don't quite make sense. Don't know which option to use.
How can I read N lines at a time using Bash?
Answer: With Bash≥4 you can use mapfile like so:
while mapfile -t -n 10 ary && ((${#ary[@]})); do
    printf '%s\n' "${ary[@]}"
    printf -- '--- SNIP ---\n'
done < file

That's to read 10 lines at a time.
Comment: @Oliver: thanks for your comment and your downvote. Unfortunately, programming is not simple. The first answer you link is difficult to scale: what if you want to read 120 lines at a time? what if you want to read `N` times at a time (where `N` is a variable)? The second answer you link is just broken, in case your stream/file contains single quotes. Maybe my method isn't user-friendly, but at least it is correct and scales without any problems.
Comment: This seems to be the most efficient and elegant approach and hence should have been the accepted answer.  It's great if explanation for `&& ((${#ary[@]}))` is added.
Comment: @codeforester `&& ((${#ary[@]}))` essentially means till there are lines to read (number of elements in the array return something)
Comment: Agree, good-looking code. I did some performance-testing in case anyone is interested(Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz; 12G RAM). Any Suggestions to do improve?  `$ seq 1 10000000 >input.txt
$ ls -lh input.txt
-rwxrwxrwx 1 dima dima 76M Feb 17 23:09 input.txt

$ time ./sqlite_stdin_batch_transactions.sh 1000 /dev/null
Using batch size 1000
real    0m44.791s
user   0m24.922s
sys     0m19.578s` @codeforester, @anubhava, @tmow
Comment: @Oliver I won't edit it. Next time, think twice before you downvote, especially in areas you don't know very well... only downvote answers you KNOW are broken.
Comment: While I don't agree with @Oliver's comment, I still commend you that you explained *why* you down-voted. This way people can decide whether on not they agree with your comment.
Comment: This is the least user-friendly answer:  `ary && ((${#ary[@]}))` is by no means simple, nor is the printf portion, whereas even novice bash developer can understand https://stackoverflow.com/a/31528581/869951, https://stackoverflow.com/a/41267962/869951 or https://stackoverflow.com/a/53376270/869951
Comment: @gniourf_gniourf I understand you want to "punish" Oliver but doing so you also "punish" other readers who don't understand the cryptic part of your solution.
Answer: While the selected answer works, there is really no need for the separate file handle. Just using the read command on the original handle will function fine.
Here are two examples, one with a string, one with a file:
# Create a dummy file
echo -e "1\n2\n3\n4" > testfile.txt

# Loop through and read two lines at a time
while read -r ONE; do
    read -r TWO
    echo "ONE: $ONE TWO: $TWO"
done < testfile.txt

# Create a dummy variable
STR=$(echo -e "1\n2\n3\n4")

# Loop through and read two lines at a time
while read -r ONE; do
    read -r TWO
    echo "ONE: $ONE TWO: $TWO"
done <<< "$STR"

Running the above as a script would output (the same output for both loops):
ONE: 1 TWO: 2
ONE: 3 TWO: 4
ONE: 1 TWO: 2
ONE: 3 TWO: 4

Comment: Much more simple! cat input-file.txt | xargs -L 10 echo
http://stackoverflow.com/a/53376270/1265306
Answer: Simplest method - pretty self-explanatory. It is similar to the method provided by @Fmstrat, except the second read statement is before the do.
while read first_line; read second_line
do
    echo "$first_line" "$second_line"
done

You can use this by piping multiline input to it:
seq 1 10 | while read first_line; read second_line
do
    echo "$first_line" "$second_line"
done

output:
1 2
3 4
5 6
7 8
9 10

Comment: The syntax seems weird, but `help while` actually mentions command**s**: `while COMMANDS; do COMMANDS; done` with the explanation `Expand and execute COMMANDS as long as the final command in the 'while' COMMANDS has an exit status of zero`.
Comment: @SebMa Yup, I believe so.
Comment: `seq -w 1 100 | while for i in {0..9}; do read $i; done; do echo "$0...$9"; done`
Comment: @Mike-Furlender Just the solution I was looking for :+1:, thanks bro. Can I replace the `;` by `&&` instead : `seq 1 10 | while read first_line && read second_line ...` ?
Comment: @Mike-Furlender Thanks.
Answer: This is harder than it looks. The problem is how to keep the file handle.
The solution is to create another, new file handle which works like stdin (file handle 0) but is independent and then read from that as you need.
#!/bin/bash

# Create dummy input
for i in $(seq 1 10) ; do echo $i >> input-file.txt ; done

# Create new file handle 5
exec 5< input-file.txt

# Now you can use "<&5" to read from this file
while read line1 <&5 ; do
        read line2 <&5
        read line3 <&5
        read line4 <&5

        echo "Four lines: $line1 $line2 $line3 $line4"
done

# Close file handle 5
exec 5<&-

Comment: Readying this again, I also don't know why I explained how to create a new file handle instead of using stdio :-/
Comment: Thanks for this, I used this as the basis for my solution. This works, but the additional file handle is not required. See below for a solution that is similar, but doesn't require the second handle.
Comment: Maybe I misunderstand the problem, but just calling read repeatedly worked fine for me even without the input trickery.
Comment: You don't need to create the file, if you are getting the output from a command.
You can do:
mkfifo fifo;
exec 5<>fifo;
my-output-that-will-be-read >&5;
read line1 <&5;
read line2 <&5;
...
Comment: Much more simple!
cat input-file.txt | xargs -L 10 echo
https://stackoverflow.com/a/53376270/1265306
Comment: @LuísGuilherme Any idea how to do this without a fifo? A fifo is just another entry in my filesystem which I have to clean up; it just makes debugging harder and wastes less disk space.
Comment: Aaron, I've added an answer below. Basically, using zsh's read, or bash's readarray or mapfile
Comment: @naviram That doesn't give you the 10 lines in 10 different BASH variables.
Answer: That is much more simple! :)
cat input-file.txt | xargs -L 10 ./do_something.sh

or
cat input-file.txt | xargs -L 10 echo

Comment: This approach has problems if the input lines have characters meaningful to the shell. E.g. text with a single apostrophe will become an unterminated quote and halt processing.
Comment: the latter example can be abbreviated to `<input-file.txt xargs -L 10`
Comment: in Alpine Linux, it would be: `xargs -n 10` instead. I like this way because you can use it with variables, like `echo "$var" | xargs ...` (not just files).
Comment: Simple, elegant way of chunking lines, exactly what I needed. Thank you!
Answer: I don't think there is a way to do it natively in bash, but one can create a convenient function for doing so:
#
# Reads N lines from input, keeping further lines in the input.
#
# Arguments:
#   $1: number N of lines to read.
#
# Return code:
#   0 if at least one line was read.
#   1 if input is empty.
#
function readlines () {
    local N="$1"
    local line
    local rc="1"

    # Read at most N lines
    for i in $(seq 1 $N)
    do
        # Try reading a single line
        read line
        if [ $? -eq 0 ]
        then
            # Output line
            echo $line
            rc="0"
        else
            break
        fi
    done

    # Return 1 if no lines where read
    return $rc
}

With this one can easily loop over N-line chunks of the data by doing something like
while chunk=$(readlines 10)
do
    echo "$chunk" | ... # Whatever processing
done

In this loop $chunk will contain 10 input lines at each iteration, except for the last one, which will contain the last lines of input, which might be less than 10 but always more than 0.
Comment: I really like this solution, but how do you call it?  How do you pass it a file name?
Comment: The while loop above will read from standard input. If you want to input a file to it just cat it to stdin.
Answer: I came up with something very similar to @albarji's answer, but more concise.
read_n() { for i in $(seq $1); do read || return; echo $REPLY; done; }

while lines="$(read_n 5)"; do
    echo "========= 5 lines below ============"
    echo "$lines"
done < input-file.txt

The read_n function will read $1 lines from stdin (use redirection to make it read from a file, just like the built-in read command). Because the exit code from read is maintained, you can use read_n in a loop as the above example demonstrates.
Comment: Note that this does not output the last 1 to 4 lines, if the number of lines is not a multiple of 5.
Comment: Fails at reading the last lines, or the whole file if it's less than 5 lines long.
Answer: Depending on what you're trying to do, you can just store the previous lines.
LINE_COUNT=0
PREVLINE1=""
PREVLINE2=""
while read LINE
  do LINE_COUNT=$(($LINE_COUNT+1));
    if [[ $LINE_COUNT == 3 ]]; then
       LINE_COUNT=0
       # do whatever you want to do with the 3 lines
    done
    PREVLINE2="$PREVLINE1"
    PREVLINE1="$LINE"
  done
done < $FILE_IN

Answer: Just use a for loop:
for i in $(seq 1 $N) ; do read line ; lines+=$line$'\n' ; done

In bash version 4, you can also use the mapfile command.
Comment: yes, there is no explicit `read N lines` at a time in bash. You have to construct it with concatenation of values. @choroba 's on the right track here, but needs to provide source of input and manage more than one pass of input (reset `line` every N reads). Awk is really designed for such issues (but doesn't have an explicit 'read N lines' function either), you need to manage  the N lines with the `NR` variable in awk. Sed could work too, but would really be ugly, and require a lot of messing around to make N generic and not hardcoded processing. Good luck to all.
Comment: I tried sth like: for i in $(seq 1 4);do read line <101127_2_aa_1.fastq;lines+=$line$'\n';done
but seems didn't work...
Comment: Actually, how to provide input ?
Answer: I know you asked about bash, but I am amazed that this works with zsh
#!/usr/bin/env zsh
cat 3-lines.txt | read -d\4 my_var my_other_var my_third_var

Unfortunately, this doesn't work with bash, at least the versions I tried.
The "magic" here is the -d\4 (this doesn't work in bash), that sets the line delimiter to be the EOT character, which will be found at the end of your cat. or any command that produces output.
If you want to read an array of N items, bash has readarray and mapfile that can read files with N lines and save every line in one position of the array.
EDIT
After some tries, I just found out that this works with bash:
$ read -d# a b
Hello
World
#
$ echo $a $b
Hello World
$

However, I could not make { cat /tmp/file ; echo '#'; } | read -d# a b to work :(
Answer: The echo simulates a file with two lines input, use head -2 before paste if needed:
IFS=\; read A B < <(echo -en "X1 X2\nY1 Y2\n" | paste -s -d\;)

If you want to read lines in a loop and create pairs and lines have only single word in them use:
while read NAME VALUE; do
    echo "$NAME=$VALUE";
done < <(echo -en "M\n1\nN\n2\nO\n3\n" | xargs -L2 echo)

Answer: Here's an alternative way of doing it:
//This will open the file and users can start adding variables.
cat > file
//After finished ctrl + D will close it
cat file|while read line;
do
  //do some stuff here
done

Answer: Awk is a funny way for this case:
~$ cat test.txt
tom
email@example.com
jack
email@example.com
marry
firstname.lastname@example.com
gogo
firstname.lastname@example.com
~$ cat test.txt | awk 'BEGIN{c=1}{a=c;if(a==2){print b" "$0;c=1} if(a==1){b=$0;c=2}}'
tom email@example.com
jack email@example.com
marry email@example.com
gogo email@example.com

Answer: After having looked at all the answers, I think the following is the simplest, ie more scripters would understand it better than any other solution, but only for small number of items:
while read -r var1 && read -r var2; do
    echo "$var1" "$var2"
done < yourfile.txt

The multi-command approach is also excellent, but it is lesser known syntax, although still intuitive:
while read -r var1; read -r var2; do
    echo "$var1" "$var2"
done < yourfile.txt

It has the advantage that you don't need line continuations for larger number of items:
while
    read -r var1
    read -r var2
    ...
    read -r varN
do
    echo "$var1" "$var2"
done < yourfile.txt

The xargs answer posted is also nice in theory, but in practice processing the combined lines is not so obvious. For example one solution I came up with using this technique is:
while read -r var1 var2; do
    echo "$var1" "$var2"
done <<< $(cat yourfile.txt | xargs -L 2 )

but again this uses the lesser known <<< operator. However this approach has the advantage that if your script was initially
while read -r var1; do
    echo "$var1"
done <<< yourfile.txt

then extending it for multiple lines is somewhat natural:
while read -r var1 var2; do
    echo "$var1" "$var2"
done <<< $(cat endpoints.txt | xargs -L 2 )

The straightforward solution
while read -r var1; do
    read -r var2
    echo "$var1" "$var2"
done < yourfile.txt

is the only other one that I would consider among the many given, for its simplicity, but syntactically it is not as expressive; compared to the && version or multi-command version it does not feel as right.
Comment: Your first two examples are not equivalent. To avoid `cat` with `xargs`: `xargs [OPTIONS] < filename`. Anyway, `xargs` is known to be a bad solution: it will break with quotes, so it's certainly something *you don't want to use.*
Comment: @gniourf_gniourf If I have to spend more than a few seconds analysing an expression to understand its meaning, it is not one I want to use or encourage using, that's just my opinion among all the other opinions. Scalability, generality, performance, all have big costs in complexity, so it's important to keep in mind when they are necessary vs nice to have. Maintainability is important too, it is here and now.
Answer: to read n+2 Lines from a file:-
2
4
6
8
.
.
so on
you can try this way:-
cat fileName | awk '!((NR - 0) % 2)'
Answer: Also you can group lines with awk:
$ seq -s ' ' 23 > file

$ cat file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

$ awk '(NR % 6 == 1) {print; for(i=1; i<6 && getline ; i++) { print }; printf "\n"}' RS=' ' ORS=' ' file
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23

Answer: Another option is to use the curly brace command grouping in bash.
{ read line1; read line2; } < test-file.txt

One thing to keep in mind tho is that if you have set -u then this will fail if the file being read has less lines than the number of variables you're attempting to fill. One solution is simply to add  || true to the end of the above line.

Read n lines at a time using Bash


Rationalization of an integer set

Question: Let $X \subseteq \mathbb{N}^2$ be the set $\{(x,y) \, : \, y \text{ is the greatest power of 2 dividing } x\}$. I'm wondering how the set gets when multipled by the non negative rationals, i.e. what is $\mathbb{Q}_{\geq 0}X$?
Comment: "How the set gets"?
Answer: Claim:
$$\mathbb Q_{\ge 0}X = \left\{(x,y)\in\mathbb Q_{>0}^2\mid \frac xy\in 2\mathbb N-1\right\}\cup\{(0,0)\}$$
Proof:
"$\supseteq$":
Clearly $(0,0)= 0\cdot (1,1)\in \mathbb Q_{\ge 0}X$ becuse $(1,1)\in X$. Let $x,y,$ be positive rational numbers such that $k:= \frac xy$ is an odd natural number. Then $(k,1)\in X$ and $y\cdot(k,1)=(x,y)\in\mathbb Q_{\ge 0}X$.
"$\subseteq$": Let $(n,m)\in X$ and $q\in \mathbb Q_{\ge0}$. If $q=0$, then $q\cdot(n,m)=(0,0)$ and we are done.
Otherwise, $q=\frac rs$ for suitable natural numbers $r,s$. Also, we have $m=2^k$ with $k\in\mathbb N_0$ and $n=um$ with $u$ an odd natural number. Note that $q\cdot(n.m)=(x,y)$ with $x=qn$, $y=qm$.
Then $x>0$ and $y>0$ because $q$, $n$ and $m$ are positive.
Moreover, $\frac xy=\frac{n}{m}=u$ is an odd natural number, i.e. an element of $2\mathbb N-1$.$_\blacksquare$
Comment: Thank you! Do you mind giving a short explanation? Or just an intuition?

Rationalization of an integer set


ballerina: passing parameters to client request

Question: Is there a way to pass a variable value to a client request. Following is my code and it works fine when the value is hard coded.
endpoint http:Client gitClientEndpoint {
    url: "https://test.com"
};

function main(string... args) {
    var response = clientEndpoint->get("/users/Alex92");

Instead of hard coding "Alex92" I want to pass it as a string variable.
I tried the following
function main(string... args) {
    string userName = "Alex92";
    var response = clientEndpoint->get("/users/:userName");

But this does not work. Could anyone tell me the correct syntax?
Answer: You can use String concatenation:
var response = clientEndpoint->get("/users/"+userName);

Answer: The root cause of the problem is you are trying to access a defined variable within an immutable.try the stranded string concatenation to resolve the problem.
function main(string... args) {
    string userName = "Alex92";
    var response = clientEndpoint->get("/users/"+userName);


data list to data matrix matlab/R

Question: I have a matrix of data which looks like:
date ticker return

2/1  MSFT   .21

2/1  GOOG   .11

2/1  CSCO   .09

2/2  MSFT   .22

2/2  GOOG   .19

2/2  CSCO   .15

and I want to transfer the structure to something like:
     MSFT   GOOG  CSCO

2/1  .21    .11   .09

2/2  .22    .19   .15

Is there an easy way to make this transfer in Matlab/R, other than run loops to get this?
Comment: Do you just want to print a table, or do you want this in some kind of data structure that you can then use for further purposes? Also, in what form is your matrix of data? A text file?
Answer: You can use the reshape2 library:
library(reshape2)

#sample data
dat <- data.frame(
    date = rep(c("2/1", "2/2"), each = 3)
  , ticker = rep(c("MSFT", "GOOG", "CSCO"), 2)
  , return = runif(6)
)

#Cast the data
> dcast(dat, date ~ ticker, value_var = "return")

  date      CSCO      GOOG       MSFT
1  2/1 0.2555900 0.6212102 0.43078011
2  2/2 0.7092036 0.7013563 0.01225488

Answer: and in matlab:
data as if loaded by textscan:
dates = {'2/1','2/1','2/1','2/2','2/2','2/2'}
sites = {'MSFT','GOOG','CISCO','MSFT','GOOG','CISCO'}
vals = rand(1,6);

reshaped:
[uDate,uiDate,ujDate] = unique(dates);
[uSite,uiSite,ujSite] = unique(sites);
sz = [length(uDate),length(uSite)];
valArray = vals(sub2ind(sz,ujDate,ujSite))
valArray = reshape(valArray,sz);

the value for '2/1' 'GOOG' is now in
valArray(find(strcmpi('2/1',uDate),1), find(strcmpi('GOOG',uSite),1))

not quite as elegant as R, but hey.   MATRIXMULTIPLY!
Comment: BlessedKey, thank you as well. But I think the line: "valArray = reshape(vals,sz);" should be changed to "valArray = reshape(valArray,sz);", right?
Answer: FOR MATLAB CODE, THE CORRECT ONE SHOULD BE:
dates = {'2/1','2/1','2/1','2/2','2/2','2/2'}
sites = {'MSFT','GOOG','CISCO','MSFT','GOOG','CISCO'}
vals = 1:6;

[uDate,uiDate,ujDate] = unique(dates);
[uSite,uiSite,ujSite] = unique(sites);

sz = [length(uDate),length(uSite)];

positionIndex=sub2ind(sz,ujDate,ujSite);

[B,IX] = sort(positionIndex);

valArray = vals(IX);
valArray = reshape(valArray,sz);

Answer: Or in a more general case, if there were missing values:
dates = {'2/1','2/1','2/1','2/2','2/2','2/2'};
sites = {'MSFT','GOOG','CISCO','MSFT','GOOG','CISCO'};
vals = 1:6;
[uDate,uiDate,ujDate] = unique(dates);
[uSite,uiSite,ujSite] = unique(sites);
sz = [length(uDate),length(uSite)];
positionIndex=sub2ind(sz,ujDate,ujSite);
valArray=zeros(length(uDate),length(uSite));
valArray(positionIndex)=vals;
Answer: The above solution for MATLAB won't work, if you have missing data in the original matrix that is hard to check before transformation.
In the DAVE's answer I would replace
valArray = vals(IX);
valArray = reshape(valArray,sz);

with
valArray = nan(sz);
valArray(B) = vals(positionIndex);

Missing values will be replaced by NaN.

R's melt/dcast are so much more elegant. Love it! I wish to have similar tools in MATLAB.

data list to data matrix matlab/R


Modelling zero-inflated proportion data in R using GAMLSS

Question: I am new to the gamlss package and would like to check that I am using the correct family for proportion data (tree species cover after treatment), which is bounded between zero and one. According to the documentation, the correct distribution family for data of this type is BEINF (Beta inflated), since it allows both 0 and 1 values. The data are highly zero-inflated, with 43/82 observations having a zero response, and 3/82 values at 1. I run the following model:
m1 <- gamlss(y ~ x1 + x2,
sigma.formula=~1,
nu.formula=~x1 + x3 + x4,
tau.formula=~x5,
family=BEINF,
data=df)

The mean response values (and SEs) given by:
pred <- predict(m1, type='response', se.fit=T)

seem reasonable.
I am also interested in the probability of obtaining a zero response (i.e. the probability of having no individuals of the target species post-treatment). However, when i try to extract the fitted values of the nu parameter (which I believe to be the probability of obtaining a zero value), using:
prednu <- predict(m1, type="response", what="nu")

I am getting predicted values of the response in the range 0.01-44.6, which I find strange. I have tried this for both the model-fitting data and new data, with the same result. However, when I use family=ZAGA (i.e. zero adjusted Gamma distribution which allows for a response with no upper bound), I get predictions between 0 and 1 for the response for the nu parameter, which seem more reasonable.
I therefore have 3 questions about my approach:

Is BEINF the correct choice of distribution family for zero-inflated proportion data bounded between zero and one, and including both zeros and one values?
Does predict(m1, type="response", what="nu") give the probability of obtaining a zero response?
Why would predict(m1, type="response", what="nu") give values far outside the $[0,1]$ bounded range of the response variable?

We are happy to provide data if that would be helpful.
Any assistance you can provide regarding the correct use of these gamlss functionalities with my dataset would be greatly appreciated.
Kind regards,
PS – This question has been sent to GAMLSS team a week ago but hasn't been answered yet.
Answer: The answer below references the inflated beta GAMLSS documentation (Rigby & Stasinopoulos, 2010, section 10.8.2, page 215). It would seem that your data could be fitted with the inflated beta model.
The response variable for the $\nu$ component of the model is a ratio of probabilities (an odds) given by
$\nu = p_0 / (1-p_0-p_1)$
where $p_0$ is the probability of zero response and $p_1$ the probability of one response. Hence $\nu$ can take values > 0.
The $\tau$ component is given by
$\tau = p_1 / (1-p_0-p_1)$
Using the predicted response values for the $\nu$ and $\tau$ components, the probability of zero response can be computed as
$p_0 = \nu / (1+\nu+\tau)$
Hope this helps.
Answer: I think the odds $\frac{p_0}{1-p_0-p_1}$ are given by $e^{\nu}$ not $\nu$, and similarly for $\frac{p_1}{1-p_0-p_1} = e^{\tau}$!
This means that in the above answer one needs to use the exponentials of $\nu$ and $\tau$:
$p_0 = \frac{e^\nu}{1 + e^{\nu} + e^{\tau}}$
and similarly for $p_1$.


How to implement BroadcastReceiver to do different tasks depends on time interval

Question: My application needs to show some notifications for schedules (like Alarm), based on time interval.
For example:
There are 4 tasks I have setted in my application, like
Task A -> from 10:00 to 13:00
Task B -> from 15:10 to 16:00
Task C -> from 17:00 to 17:30
Task D -> from 20:00 to 23:30

So notification should be shown as
at 10:00 Task A has started
at 13:00 Task A has ended
at 15:10 Task B has started
... and so on.
How can I implement this? Can you please provide some tutorials related to it?
And if there are more than one way, which is the best way to do this?
Answer: Have a look at TimerTask
And there is some code on how to use it:
http://enos.itcollege.ee/~jpoial/docs/tutorial/essential/threads/timer.html
Comment: Thanks for reply. Is this is the only way? Or this is the best way?
Comment: This is not the only way, but I think this is the best way for your requirements
Comment: One big confusion.. When Task A ends, after 2:10 hrs Task B will start, so do I need to create one timer which work between Task A end to Task B start? And Then I have to create another timer which will handle Task B start to Task B end. Am I correct?
Comment: Yes, I think it should be like that


Making machine learning predictions for individual users

Question: Currently a student, I am fairly new to machine learning. I am developing a classification model in python which has ratings history of a 100 users for a specific movie, I have a total of 20,000 rows.
I have split my train and test dataset and have build a few models that achieve decent accuracy.
My problem is: I want to train and test the data for individual customers using their customer_id. For example, while making predictions my model should only train on the rating history of a single user and make predictions based on training on the same data. The user_ids are randomly generated 15-character long including both numeric and text. I tried including the user_id as inputs during training but the model would'nt accept that.
Please help :)
Comment: What's stopping you train 20000/100 models?
Answer: To build on what @SmallChess asked, it seems like you could create a different model for each person. But I question your statement that "my model should only train on the rating history of a single user." No one human being is that unique; I bet you would get much more accurate predictions using the entirety of the data, because information about others' behavior would help you refine what any given person is going to do.
Answer: From your description, I think the problem you're trying to solve is like this (feel free to correct me if I'm wrong):
You have a dataset of 20000 movies, each with 100 user ratings. Now you want to study a particular user, let's name him/her A, with his/her historical ratings and the whole dataset, in order to 'know his/her taste'. Then given any movie in the 20000 list that the user A has never seen/rated, your model will predict a rating or classify it's good or bad.
If this is the case, then
1) Without further info of the movies, such as type, year, director, actor, etc. you'll never have a correct prediction studying on user A's history ONLY.
2) You'll need to one-hot encode your userids so that you can use them as input.
3) What you'll do is something like what Netflix is doing: discover similarities in movies. E.g. if 80% of ppl who rated movie A high also gives a high rating to movie B, then when user A gives same high rate to movie A, he/she should like movie B as well. This may not work in a small dataset since there're so many different kinds of people, while for large datasets, this will give you a good recommendation system since people do share a lot of things in common.


Como inserir variável em html gerado por javascript

Question: O problema que tenho é o seguinte. Tenho um código que gera vários resultados em html para mim. Só que preciso de um detalhe que não consegui implementar. O código é o seguinte:
$('#avaliacoes').append('\
<input type=\'radio\' id=\'cm_star-empty\' name=\'fb\' value\'\'/>

A partir do de um outro código, eu obtenho uma variável resultante de um foreach. O nome dela é resultado[i].Nome
A única coisa que preciso, é inserir essa variável e concatenar com o valor do atributo name da tag input.
Como posso fazer isso usando o append acima?
Answer: O teu HTML tem alguns erros... mas podes fazer isso assim:
var resultado = [{
    Nome: 'Ana'
}, {
    Nome: 'Maria'
}];
var html = resultado.reduce(function(string, pessoa) {
    return string + [
    '
<input type=\'radio\' id=\'cm_star-empty\' name=\'fb_',
    pessoa.Nome,
    '\' value=\'\'/>
'
    ].join('');
}, '');
$('#avaliacoes').append(html);

que vai dar:

<input type="radio" id="cm_star-empty" name="fb_Ana" value="">

<input type="radio" id="cm_star-empty" name="fb_Maria" value="">

jsFiddle: https://jsfiddle.net/d9fycaz2/1
Corrigi a falta de = no value e a falta de
. Se fizeres essa string começar com aspas, em vêz de plicas, a já não precisas de escapar o HTML.
Comment: Tudo certinho, vlw Sergio!
Comment: @DiChrist ótimo. Agora quando olhei para a resposta de novo modifiquei por outra maneira que gosto ainda mais. Assim não vai chamar `$('#avaliacoes')` vezes a mais sem necessidade.
Comment: @Sergio O `return + [...`, o que faz ao certo. Não consigo testar agora mas estou curioso
Comment: @Miguel a função `Array.reduce` precisa que a callback dê retorno. Nessa linha estou a retornar a string acumulada com a nova  que constru-o com uma aray e um `.join('')` no final para concatenar.
Answer: Na minha opinião, evite misturar html com javascrip...

var resultado = [{
  Nome: 'Ana'
}, {
  Nome: 'Maria'
}];
var divClone = null;
var children = null
resultado.forEach(function(pessoa) {
  divClone = $('#divClone').clone();
  children = $(divClone).children();
  children[0].name = 'fb_' + pessoa.Nome;
  divClone[0].children = children;
  divClone[0].id = '';
  $(divClone).removeClass('hide');
  $('#avaliacoes').append(divClone);
});
.hide {
  display: none
}

    <input type='radio' id='cm_star-empty' name="" value="" />

Segue o exemplo no  JSFIDDLE : https://jsfiddle.net/d9fycaz2/7/


Dissecting a cyclic quadrilateral

Question: Given any $n>4$, prove that every cyclic quadrilateral can be dissected into $n$ cyclic quadrilaterals.
I have not made much progress yet.
When I tried to do it for $n=4$, I noticed that it may not be possible to move from $4$ dissections to $5$ or more while maintaining the given conditions.
Answer: Clearly, it is sufficient to show that any cyclic quadrilateral can be dissected into 5,6 or 7 cyclic quadrilaterals.
Dissection in 5: let $ABCD$ be our initial ciclic quadrilateral, with $X=AC\cap BD$. Let $A',B',C',D'$ the images of $A,B,C,D$ through a circular inversion with respect to a circle centered in X with a small radius. The quadrilateral $A'B'C'D'$ is cyclic since the circumcircle of $ABCD$ is mapped into a circle containing $A',B',C',D'$; $AA'B'B$ is cyclic since $XA\cdot XA'=XB'\cdot XB$.
Dissection in 7: cut from ABCD two small cyclic quadrilateral $ABC'D'$,$A'B'CD$, such that $A'B'$ is parallel to $AB$ and $C'D'$ is parallel to $CD$, then dissect $A'B'C'D'$ into 5 cyclic quadrilaterals.
Dissection in 6: cut from ABCD two small cyclic quadrilateral $ABC'D'$,$A'B'CD$, such that $A'B'$ is parallel to $AB$ and $C'D'$ is parallel to $CD$, then connect the circumcenter of $A'B'C'D'$ with the midpoints of the sides, splitting $A'B'C'D'$ into 4 cyclic quadrilaterals.

Dissecting a cyclic quadrilateral


Interaction of Gender and Income categorical variable

Question: I ran the following model, with exam scores in science as my outcome variable, and parental income group divided into 5 groups and a binary gender variable with the results below:
regress test_score i.quantiles_parent_income i.gender_dummy

 Source |       SS           df       MS      Number of obs   =     2,268
-------------+----------------------------------   F(6, 2261)      =    318.19
       Model |  76430.8521         6  12738.4753   Prob > F        =    0.0000
    Residual |    90516.86     2,261  40.0339938   R-squared       =    0.4578
-------------+----------------------------------   Adj R-squared   =    0.4564
       Total |  166947.712     2,267  73.6425726   Root MSE        =    6.3272

--------------------------------------------------------------------------------------------
                   test_score |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
---------------------------+----------------------------------------------------------------
quantiles_parent_income|
                        2  |  -.9545663   .5365921    -1.78   0.075    -2.006831    .0976982
                        3  |   .0265901   .5395947     0.05   0.961    -1.031563    1.084743
                        4  |   5.121439   .5328825     9.61   0.000      4.07645    6.166429
                        5  |   7.491982   .5170866    14.49   0.000     6.477968    8.505996
                           |
              gender_dummy |
                     male  |  -8.225431   .2901021   -28.35   0.000    -8.794325   -7.656537

I then ran an F-test between students whose parents fall in the 2nd quantile, relative to the top 20th percentile:
test i2.quantiles_parent_income== i5.quantiles_parent_income
       F(  1,  2261) =  415.54
            Prob > F =    0.0000

Can I say that a student living in the top 20th percentile scores on average, 7.5 points higher than a student in 2nd quantile, and the result is significant at the 99 significance level. Is it possible to compute how being a male in the top 20th percentile impacts one's test scores in science compared to a female student in the same parental income group?
Answer: You can say that in your data, on average, belonging to the fifth quantile of parental income instead of the second leads to an increase in the score equal to:
7.49 - (-0.95) = 8.44. And this difference was statistically significant at an alpha level of 0.01.
Regarding your second question:
given your model, the difference in score between two people of the opposite gender who are in the same quantile of parental income is given exclusively by the estimate related to gender (males score 8.23 lower than females). Note that this statement holds regardless of what quantile the two people are in (whether they are both in the fifth or both in the second, the male will have, on average, an 8.23 lower score than the female). Now, this estimate was obtained as an average considering all quantiles.
If you want to focus precisely on a quantile (say the fifth) and to study the effect of gender on score specifically for this group of people, I recommend that you perform a stratified analysis: consider only the data of the people who belong to the fifth quantile and repeat the analysis using gender as the only covariate. This will give you the gender specific effect in the fifth quintile subjects.
A possible alternative is to consider the complete dataset, but add the interaction term between gender and quantile of parental income to the covariates. This second option is equally valid, but if you've never used interactions before I recommend that you study the topic first (it's nothing complicated but the interpretation of the estimates becomes slightly more challenging).


Why the warning is showing?

Question: I am doing work on application but this warning is showing when we use api of change password.

This application is modifying the autolayout engine from a background
  thread, which can lead to engine corruption and weird crashes. This
  will cause an exception in a future release.

api is running successfully that password is changed but i am not getting why this warning is coming.
i am using this code for using api:-
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
            NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

     NSURL *url = [NSURL URLWithString:@"http:
xxx.com.api/changepassword"];
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                                   timeoutInterval:60.0];

            [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

            [request addValue:@"*/*" forHTTPHeaderField:@"Accept"];

            [request setHTTPMethod:@"POST"];

            NSString *mapData = [NSString stringWithFormat:@"regOldPassword=%@&memberId=5&newPassword=%@",string1, string2];

            NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

            [request setHTTPBody:postData];

            NSLog(@" Edited data %@", mapData);

            //NSLog(@"email passed id%@",emailstr);

            NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

                if(error == nil)
                {

                    NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                    NSLog(@"Data = %@",text);

                    NSError *error = nil;
                    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

                    UIAlertView * alert1 = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Password Changes Successfully" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                    [alert1 show];

                    if(error!=nil)
                    {

                        NSLog(@"error = %@",error);

                    }

                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self checkUserSuccessfullySaved:json];
                    });
                }
                else
                {
                    UIAlertView * alert1 = [[UIAlertView alloc]initWithTitle:@"Unsuccessful" message:@"Failed to change password please try again" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                    [alert1 show];

                    NSLog(@"Error : %@",error.description);
                }
            }];
            [postDataTask resume];
        }

}

Answer: You shouldn't show alerts from the background thread:
UIAlertView * alert1 = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Password Changes Successfully" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert1 show];

must be dispatched to the main (UI) queue.
dispatch_async(dispatch_get_main_queue(), ^{
   UIAlertView *alert1 = ...
   [alert1 show];
});

Note the stack indices 29 & 28:
[ChangePassword submit:]

method is the original cause of your problem because it shows an alert while being called on a background thread.
Comment: so what is the solution of this problem
Comment: i used this but again the same warning is showing
Comment: The solution is to read up on GCD (Grand Central Dispatch) and use what you learn.

Why the warning is showing?


Passing array from a form to another

Question: I have a custom module that has a form like this :
    /*
 * Sytems settings form for listing skill
 */
function skillbar_form($form, &$form_state) {

    $form['skill1'] = array(
        '#type' => 'textfield',
        '#title' => t('What's your skill ?'),
        '#default_value' => variable_get('skill1'),
        '#description' => t('Enter your skill'),
    );
    $form['skill2'] = array(
        '#type' => 'textfield',
        '#title' => t('What's your second skill'),
        '#default_value' => variable_get('skill2'),
        '#description' => t('Enter your second skill'),
    );

    return(system_settings_form($form));

}

This form will get information from user like (What's your skill ?).
FIRST : i want to redirect user after submiting this form to another form
SECOND : i want to reuse data from first form ("what's yous skill ?") and use variable's from first form to creat second form an let user to add their percentage of skill like : 90 %
Any help would be appreciate it
EDIT :
Comment: Looks like you are looking for a multi step form solution, have a look here for references http://growingventuresolutions.com/blog/drupal-7-multistep-forms-using-variable-functions.html
Comment: did you mean creating multistep form..

check out this http://growingventuresolutions.com/blog/drupal-7-multistep-forms-using-variable-functions.html
Comment: Thank you guys . i've try it and kind of got idea from this but is it possible to show all the information in a table or somthing else after submiting all the form ?
Comment: and let me say that : i want to have two steps . first what's your skill and second what's your percentage of your skill !!!
Answer: You need to use 'rebuild' property of forms here (used in multi-steps form) :
 function skillbar_form($form, &$form_state) {
   if (!empty($form_state['storage']['myvalue'])) {
    drupal_set_message(t("You submitted: @name", array('@name' => $form_state['storage']['myvalue'])));
   }
   $form['skill1'] = array(
    '#type' => 'textfield',
    '#title' => t("What's your skill ?"),
    '#default_value' => variable_get('skill1'),
    '#description' => t("Enter your skill"),
   );
   $form['skill2'] = array(
    '#type' => 'textfield',
    '#title' => t("What's your second skill"),
    '#default_value' => variable_get('skill2'),
    '#description' => t('Enter your second skill'),
   );
   $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
   );
   return $form;
  }

 function skillbar_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  $form_state['storage']['myvalue'] = $form_state['values']['skill1'];
  $form_state['redirect'] = ANY_URL;
 }

Comment: In the submit handler:
$form_state['redirect'] = 'url';
Comment: thx for your answer , ok and after that how to connect them to another form ?
Comment: thx , but i didnt understand it . it's my fault
Comment: I am editing above code for you. Replace 'url' above accordingly.
Comment: ok thx a million and do i need to add another item to hook menu () ?
Comment: Why you need another menu item ?
Comment: when i submit this form i get the message and said : You submitted:"something" in first textfield .
because second form is in another url

Passing array from a form to another


Connect.Exec() not executing (Visual Studio 2010 Addin)

Question: I'm trying to open a form from Visual Studio add-in code, Connect class:
<code>public void Exec(
        string pCommandName,
        vsCommandExecOption pExecuteOption,
        ref object pVarIn,
        ref object pVarOut,
        ref bool pHandled)
    {
        pHandled = false;
        if (pExecuteOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
        {
            if (pCommandName == "VisualStudioSolutionGenerator.Connect.VisualStudioSolutionGenerator")
            {
                Form1 form = new Form1();
                form.Show();
                pHandled = true;
                return;
            }
        }
    }
</code>
This works fine if Form1 is defined in the same assembly, but if it is in another assembly, Exec() will not even be called. I saw a similar question being posted here, but it was not answered.
Anyone has any idea why this is the case?
Thanks
Answer: This is what solved the problem:
I created the addin project named 'VisualStudioSolutionGenerator' the same way on a different machine and got this error when I tried to execute it in debug mode:"The Add-in <addin_name> failed to load or caused an exception ...".
Error code was 80070002, which means some files are missing.So I checked "C:\Users\<user_name>\Documents\Visual Studio 2010\Addins\VisualStudioSolutionGenerator - For Testing.AddIn" (Windows 7 machine) and the Assembly tag in that file pointed to "<addin_project_path>/bin/VisualStudioSolutionGenerator.dll". This file exists, but dlls for other solution projects used by addin project, including the one with 'Form1' were not copied to this folder on build, they are only present in "<addin_project_path>/bin/Debug/" folder.
Changing Assembly tag in 'For Testing' addin file to "<addin_project_path>/bin/Debug/" removed the exception and Connect.Exec() now executes normally.


Can a drummer hit the snare, ride, and crash at the same time?

Question: I'm producing a song and I'm using virtual drums via midi notes to achieve the drum sounds. I want a real drummer to eventually perform this piece so I'm asking you drummers out there if it's practically possible for a drummer to hit the snare, ride, and crash at the same time (this is performed inside a sequence of other "hits" (if that makes any sense), so it isn't a thing performed independently in the piece)..
It doesn't seem possible from an outsider's perspective or if it is possible it doesn't seem to be an easy thing to accomplish (and it may be a problem if it's a too advanced thing to do)..
PS: I've probably gave you insufficient data about my situation (due to a lack of real drumming knowledge) so feel free to ask for more info and I'll try to answer..
Comment: Given that most drummers have only two arms (there are those with fewer), and snare, crash and ride all need to be sticked...
Comment: Are you imagining one stick hitting both the crash and the ride? There exist crash+ride cymbals that combine the ~~worst~~ best of both worlds.
Comment: IMO, nothing essential will be lost from your arrangement palette if you restrict to only one cymbal hit at a time. Either ride, crash/splash/china or hi-hat. But only one. There are some special cases like pedalling high-hats, but they aren't essential for most things.
Comment: I'm with @JohnnyApplesauce on this one… but the only kits that come with crash/rides also cost less than 50 bucks… or pence… & were probably produced in the 60s :P
Answer: I spent the entire 90s being paid (quite handsomely, tyvm ;) to seek & destroy 3-handed-drummer syndrome in midi/sample playback songs & styles for a major instrument manufacturer.
No, a drummer cannot do that & someone, somewhere, will spot if you do it.
On the other hand [pun intended] any half-decent drummer can be riding the ride, flip in a quick crash & be back to the ride before anyone would even notice he'd missed one. The crash will easily cover a fair bit of where the ride would have been, so you don't need it there at the same time.
Unless you are producing 'pure electronic'/sample playback music, where frankly anything goes, then avoid 3-handedness like the plague.
It really does help, when programming drums to actually know how a drummer would do it - even if that drummer is better than you;) Study drummers, they will teach you things about drum programming. You don't have to be able to play yourself… so long as someone can.
Comment: Sorry, cannot resist, " (quite handsomely, tyvm ;) " looks mismatch: https://xkcd.com/541/   ;)
Comment: Anything wrong with using a 'crash' stroke on the ride for that one hit? Works for me...
Comment: @Tim - rides just don't crash properly - they also end up swinging around making a mess of your natty little be-bop swing - ka-ting-ga-ding-a-ding-ga-ding Personally, I use paper-thin crashes, but my ride is like a train wheel.