text:
Q: Google sign in issue: "failed message=12500" I m trying to migrate google sign in from one account to another in my android app. I have add the package name and sha1 key into new account and then also added the"google-services.json" file. But every time i m running it, it shows me "failed message=12500".
I have tried everything, looked at all the solutions everywhere.
When i use the old account and old "google-services.json" file it works but as soon i tried to migrate to new account it doesn't work. The crazy thing about this is that i m using other services as well like firebase notification, phone authentication and remote config they all work perfectly fine in the new account, but not google sign.

A: This did the trick:
Add application logo, Application Homepage link and Application Privacy Policy link. To add both link you can just copy and paste from Authorized domains section from "oAuth consent screen", for example: your-app-abc123.firebaseapp.com
This is a must step for migrating or adding a new app, because i spent hours and hours and with no results and only this thing helped me out.


text:
Q: Maximum of N iid random random variables with Gumbel distribution I know that the maximum of iid random variables has Gumbel distribution. For example, this is true when iid random variables have Exponential distribution.
Does this hold when iid random variables have Gumbel distribution themselves?
Let's say there are $N$ iid random variables with distribution $X_n\sim Gumbel(\mu, \beta),~n=1,...,N$. What is the distribution of $\text{max}_n~X_n$? If it is also a Gumbel distribution, say $Gumbel(\mu_{\text{max}}, \beta_{\text{max}})$, how are parameters $\mu_{\text{max}}$ and $\beta_{\text{max}}$ related to $\mu$ and $\beta$?
I tried to find an answer in multiple textbooks, but could not find anything.

A:
Does this hold when iid random variables have Gumbel distribution themselves?

Yes, due to the condition "iid".

 Without the condition "iid", that's not true.  You may consult this question for details.

The CDF of $X_i \sim {\rm Gumbel}(\mu,\beta)$ is
$$ F_i(x) = \exp(-\exp((\mu - x)/\beta)).$$
Then the CDF for $Y_n = \max_{i = 1,\dots,n} X_i$ is
$$\begin{aligned}
F_Y(y) &= \prod_{i=1}^n P(X_i \le y) \\
&= \prod_{i=1}^n F_i(y) \\
&= \exp(-n\exp((\mu-y)/\beta)) \\
&= \exp(-\exp((\mu+\beta \ln n-y)/\beta))
\end{aligned}$$
Therefore, $Y_n \sim {\rm Gumbel}(\mu+\beta\ln n, \beta)$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UI and server integration, how do they interact with changing inputs? I'm new to R Shiny and definitely not an R expert. I have struggles with the server function,
context:
I created an R script which does calculations depending on several user inputs, the first inputs affecting slightly the second ones. To then take all the inputs and feed them into a function.
I'm not sure how to use the server function.
More if the inputs are changing over time depending on user feedback.
This is an easy example:
include_banana <- TRUE #default
include_apples <- TRUE #default
product_list <- data.frame("Product" = c("Apple", "Banana", "Pear", "Tomato"), "Quantities" = c(2,4,5,1), "Price"=c(0.5, 0.7, 1, 0.2))

ui <- fluidPage(theme = shinytheme("yeti"),
                  tabPanel("Shopping list",
                           mainPanel(
                             tabsetPanel(
                               tabPanel("Banana?",
                                        br(),
                                        helpText("Choose"),
                                        checkboxInput("include_banana", "Do you want bananas?", TRUE, 300),
                                        tableOutput("shoppinglist"),
                                        br(),
                                        br(),
                                        actionButton("Confirm1", "Confirm"),
                               ),
                               tabPanel("Apple?",
                                        br(),
                                        helpText("Choose"),
                                        checkboxInput("include_apples", "Do you want apples?", TRUE, 300),
                                        tableOutput("shoppinglist"),
                                        br(),
                                        br(),
                                        actionButton("Confirm2", "Confirm"),
                               ),
                               tabPanel("Product list", DT::dataTableOutput("product_list")),
                               tabPanel("Price", DT::dataTableOutput("prices")),
                               )
                           )
                  )

) # fluidPage

Which is straightforward in the example:

*

*I have a given product list with quantities and prices.

*I give the user a shopping list (the product list without prices & quantities) and ask the user first if he/she wants bananas. If true, it remains, if false, we will take the bananas away in the next table. (Confirm with action button)

*I give the user the updated shopping list (with or without bananas), and do the same for apples. Needs to be confirmed by an action button. Table doesn't change right away, but only in the next tab.

*Shopping list tab with bananas and apples filtered out if the case

*List of prices, or what you are going to spent based on the product list table and what is filtered out.

And as you can see, I'm completely lost in the server:
I hope this example helps me to understand better the mechanics between ui and server
server <- function(input, output, session) {

  values <- reactiveValues()

  output$shoppinglist <- renderTable(product_list)

  # Bananas
  observeEvent(input$Confirm1, {

    output$bananas <- renderText({input$include_banana})
    values$shoppinglist <- product_list[,1][product_list$Product != "Bananas" & input$include_banana == FALSE,]

  })

  # Apples
  observeEvent(input$Confirm2, {

    output$apples <- renderText({input$include_apples})
    values$product_list  <- product_list[,1][product_list$Product != "Apples" & input$include_apples == FALSE, 1]

  })

  output$shoppinglist <- renderTable( values$productlist )

  output$prices <- renderTable(product_list$Quantities * product_list$Price)

}

Thanks again


text:
Q: Limit of exponential of sines and cosines The task is to calculate
$$\lim_{x\rightarrow \infty} e^{x \ln (\sin(1/x)+\cos(1/\sqrt x)}.$$
Since $\lim_{u\rightarrow 1}\ln u\approx u-1$, the original limit can be rewritten as
$$
\lim_{x\rightarrow \infty} e^{x  (\sin (1/x)+\cos ((1/\sqrt{x})-1)} = \lim_{x\rightarrow \infty} e^{x (1/x -1 -1 )} = e.
$$
However, the solution manual says $\sqrt{e}$ is the correct answer. Can you help me figure out why? Thank you.

A: Use Maclaurin's expansions:

*

*$\sin\frac1x=\frac 1 x+o\bigl(\frac 1x\bigr)$,

*$\cos \frac1{\sqrt x}=1-\frac1{2x}+o\bigl(\frac 1x\bigr)$ (from MacLaurin's expansion at order $2$ and substitution).

We deduce that the expansion of the exponent is
\begin{align}x \ln \biggl(\sin\Bigl(\frac{1}{x}\Bigr)+\cos\biggl(\frac{1}{\sqrt x}\biggr)\biggr)
&=x\biggl(\ln\Bigl(\frac1x+1-\frac1{2x}+o\Bigl(\frac 1x\Big)\biggr)=x\biggl(\ln\Bigl(1+\frac1{2x}+o\Bigl(\frac 1x\Bigr)\Bigr)\biggr)\\
&=x\biggl(\frac1{2x}+o\Bigl(\frac 1x\Big)\biggr)=\frac12+o(1).
\end{align}
Is it clear now?


text:
Q: Clash between bibentry and hyperref with bibstyle elsart-harv I'm using the bibentry package for inserting my bibitems into a CV without printing the bibliography. This works just fine until I load hyperref. Then I get the error message Lonely \item--perhaps a missing list environment. There is supposed to be a workaround (see here), which I included as deactivated in the code below. When using it, I still get the error message. Is there another solution (no biblatex please) or am I not using the workaround correctly?
\begin{filecontents}{\jobname.bib}
@Book{elvis,
    author = "Elvis Presley",
    title = "Turn Me One More Time",
    publisher = "Jail House Books",
    year = 1963,
}
\end{filecontents}
\documentclass{article}
%\makeatletter
%\let\saved@bibitem\@bibitem
%\makeatother
\usepackage{bibentry}
\nobibliography*
\usepackage{hyperref}
\begin{document}
\bibentry{elvis}
%\bibliographystyle{plain}           % works fine
\bibliographystyle{elsart-harv}     % gives an error
\nobibliography{\jobname}       % comment out when using the workaround
%\begingroup
%\makeatletter
%\let\@bibitem\saved@bibitem
%\nobibliography{\jobname}
%\endgroup
\end{document}

EDIT:  Turns out, the problem is not just about bibentry and hyperref. For your convenience I replaced my actual bib-style elsart-harv with plain. It didn't come to my mind that the style could be the crux of this matter, but it obviously is.

A: This seems simpler:
\begin{filecontents}{\jobname.bib}
@Book{elvis,
    author = "Elvis Presley",
    title = "Turn Me One More Time",
    publisher = "Jail House Books",
    year = 1963,
}
\end{filecontents}
\documentclass{article}
\bibliographystyle{plain}

\usepackage{bibentry}
\makeatletter\let\saved@bibitem\@bibitem\makeatother
\usepackage{hyperref}
\makeatletter\let\@bibitem\saved@bibitem\makeatother

\begin{document}
\nobibliography*
\bibentry{elvis}
\nobibliography{\jobname}
\end{document}

The following shows how to integrate elsarticle-harv.bst
\begin{filecontents}{\jobname.bib}
@Book{elvis,
    author = "Elvis Presley",
    title = "Turn Me One More Time",
    publisher = "Jail House Books",
    year = 1963,
}
\end{filecontents}
\documentclass{article}
\usepackage{natbib}
\bibliographystyle{elsarticle-harv}

\usepackage{bibentry}
\makeatletter\let\saved@bibitem\@bibitem\makeatother
\usepackage{hyperref}
\makeatletter\let\@bibitem\saved@bibitem\makeatother

\begin{document}
\nobibliography*
\bibentry{elvis}
\nobibliography{\jobname}       % comment out when using the workaround
\end{document}


text:
Q: Altering table after generating CRUD code gives error in yii I have a table with 2 fields and generated CRUD which is working well. I added to 2 more fields to that table and applied required changes in model, controller and view. But yii shows error for the newly added fields saying that those attributes are not defined.
This is my model code:
class Product extends CActiveRecord
{

    public function tableName()
    {
        return 'product';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, subTitle, image, shortDesc, longDesc, seo_title, focus_keywords, meta_desc, meta_url, created, updated', 'required'),
            array('status', 'numerical', 'integerOnly'=>true),
            array('title, subTitle, image', 'length', 'max'=>128),
            array('seo_title, focus_keywords, meta_desc, meta_url', 'length', 'max'=>255),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, title, subTitle, image, shortDesc, longDesc, status, seo_title, focus_keywords, meta_desc, meta_url, created, updated', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'title' => 'Title',
            'subTitle' => 'Sub Title',
            'image' => 'Image',
            'shortDesc' => 'Short Desc',
            'longDesc' => 'Long Desc',
            'status' => 'Status',
            'seo_title' => 'Seo Title',
            'focus_keywords' => 'Focus Keywords',
            'meta_desc' => 'Meta Desc',
            'meta_url' => 'Meta Url',
            'created' => 'Created',
            'updated' => 'Updated',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('title',$this->title,true);
        $criteria->compare('subTitle',$this->subTitle,true);
        $criteria->compare('image',$this->image,true);
        $criteria->compare('shortDesc',$this->shortDesc,true);
        $criteria->compare('longDesc',$this->longDesc,true);
        $criteria->compare('status',$this->status);
        $criteria->compare('seo_title',$this->seo_title,true);
        $criteria->compare('focus_keywords',$this->focus_keywords,true);
        $criteria->compare('meta_desc',$this->meta_desc,true);
        $criteria->compare('meta_url',$this->meta_url,true);
        $criteria->compare('created',$this->created,true);
        $criteria->compare('updated',$this->updated,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Product the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
}

A: Clear Yii cache (protected/runtime)


text:
Q: SQL insert null value when join delivers no result I have three tables
articleoffer_test_u
   id | randomId    | articleOfferId | TestBegin  | ArticleId
   1  | 12345678    | 38             | 2021-12-08 | 74
   2  | 12345679    | 1              | 2021-12-08 | 1
   3  | 12345677    | 1              | 2021-12-08 | 1

articleoffer_feature_test_u
   ArticleOfferTestId | FeatureId
   1                  | EXAMPLE1
   1                  | EXAMPLE2
   1                  | EXAMPLE3
   2                  | EXAMPLE1
   2                  | EXAMPLE3
   3                  | EXAMPLE3
   3                  | EXAMPLE2

featurealias
   Id | FeatureId      | ArticleShortName | FeatureAlias
   1  | EXAMPLE1       | ART1             | EXAMPLE1_E
   2  | EXAMPLE1       | ART2             | EXAMPLE1_J
   2  | EXAMPLE2       | ART1             | EXAMPLE2_E

I use this query
SELECT amtu.FeatureId, ptu.testBegin
    FROM articleoffer_test_u ptu, articleoffer_feature_test_u amtu
    WHERE ptu.RandomId="12345678" AND ptu.ArticleId=74 AND ptu.articleOfferId=38
    AND ptu.id=amtu.ArticleofferTestId AND amtu.FeatureId IN ("EXAMPLE1", "EXAMPLE2", "EXAMPLE3")

and get this result
 FeatureId      | TestBegin
 EXAMPLE1       | 2021-12-08
 EXAMPLE2       | 2021-12-08
 EXAMPLE3       | 2021-12-08

what I want is a result like this
 FeatureId      | FeatureAlias   | TestBegin
 EXAMPLE1       | EXAMPLE1_E     | 2021-12-08
 EXAMPLE2       | EXAMPLE2_E     | 2021-12-08
 EXAMPLE3       | NULL           | 2021-12-08

I tried this query
SELECT amtu.FeatureId, ptu.testBegin, featureAlias.FeatureAlias
    FROM articleoffer_test_u ptu, articleoffer_feature_test_u amtu
    INNER JOIN featureAlias ON featureAlias.FeatureId = amtu.FeatureId AND featureAlias.ArticleShortName = "ART1"
    WHERE ptu.RandomId="12345678" AND ptu.ArticleId=74 AND ptu.articleOfferId=38
    AND ptu.id=amtu.ArticleofferTestId AND amtu.FeatureId IN ("EXAMPLE1", "EXAMPLE2", "EXAMPLE3");

and get this result where EXAMPLE3 is missing
 FeatureId      | FeatureAlias   | TestBegin
 EXAMPLE1       | EXAMPLE1_E     | 2021-12-08
 EXAMPLE2       | EXAMPLE2_E     | 2021-12-08

The reason for this is that there is no featureAlias for EXAMPLE3. Is there a possibility to use a join and insert null for the featureAlias value? If no, does anyone know a different approach for solving the problem?

A: Left Join does that automatically:
SELECT amtu.FeatureId,
       ptu.testBegin,
       featureAlias.FeatureAlias
FROM   articleoffer_test_u ptu
       INNER JOIN articleoffer_feature_test_u amtu
               ON ptu.id = amtu.ArticleofferTestId
       LEFT JOIN featureAlias
              ON featureAlias.FeatureId = amtu.FeatureId
                 AND featureAlias.ArticleShortName = 'EXMP1'
WHERE  ptu.RandomId = '12345678'
       AND ptu.ArticleId = 74
       AND ptu.articleOfferId = 38
       AND amtu.FeatureId IN ( 'EXAMPLE1', 'EXAMPLE2', 'EXAMPLE3' );


text:
Q: TypeError : Property does not exist on type I am using a type script for the react project. I have defined the type for all values, but prop.option?I can't get the value of the name. Please tell me the answer.
type PropTypes = {
  option?: OptionType[]
}

type OptionType = {
  id?: number
  name?: string
  price: number
  quantity: number
}

function OrderItemPCForm(props: PropTypes) {

  console.log('===>', props.option?.name)
return(<div>...</div>)}

Property 'name' does not exist on type 'OptionType[]'.

A: Your problem was you defined option as an array (not an object)
option?: OptionType[]

so that when you try to access values from
console.log('===>', props.option?.name)

It will throw an error because you try to get name from option object which is not defined
It has 2 ways to fix
The first one is you should remove an array definition on option
type PropTypes = {
  option?: OptionType //removed `[]`
}

The second fix can be
console.log('===>', props.option[index].name) //index can be populated from a loop

But it also depends on your intention which type you want to achieve (an array or an object on option)


text:
Q: Sharp Gaussian upper bounds on Heat Kernel I am looking for references (with proof) for the following statement:

Let $(M, g)$ be a Riemannian manifold with bounded curvature and let $p_t(x , y)$ be the heat kernel of $M$. Let $K$ be compact in $M \times M$ such that $K$ is disjoint
  from the cut locus and let $T>0$. Then there exist constants $c, C > 0
$ (depending on $(M, g)$, $K$ and $T$) such that  $$\frac{c}{t^{n/2}}
e^{-\frac{1}{4t}d(x, y)^2} \leq p_t(x, y) \leq \frac{C}{t^{n/2}}
e^{-\frac{1}{4t}d(x, y)^2}$$ uniformly for all $t \in (0, T]$ and $(x,y) \in K$.

There are many variants of this theorem in the literature: Either with a different power of $t$ in the denominator on the right-hand-side, or with a denominator greater than $4t$ in the exponent, but valid for all points in $M\times M$ (also for cutpoints) or for all times (papers and books by Grigor'yan, Davies and many others).
The only source for this exact statement (sort of) I could find was the paper "Diffusion processes and Riemannian Geometry" by Molchanov, where the proof is based on stochastic analysis (which is hard for me to understand), and also he just writes
$$p_t(x, y) \sim \frac{J(x, y)^{-1/2}}{4\pi t^{n/2}} e^{-\frac{1}{4t}d(x, y)^2}$$
($J(x, y)$ is the Jacobian determinant of the Riemannian exponential map), but never explains what the symbol $\sim$ actually means. And since I do not understand the proof properly, I am not even sure that it is supposed to mean what I wrote above.
Also it would be nice (for me) to have a proof that does not rely on stochastic analysis.

/Edit: This is an answer to Fabrice Boudoin's Post which is too long for a comment. The problem is the following: Berline-Getzler-Vergne and Berger-Gauduchon-Mazét proof that the asymptotic heat kernel expansion satisfies
$$ \Bigl| p_t(x, y) - (4\pi t)^{-n/2}e^{-\frac{1}{4t}d(x, y)^2}\sum_{j=0}^N t^j \Phi_j(x, y)\Bigr| \leq C_{K, N}t^{-n/2 +N+1}$$
for all $N$, uniformly on compact sets $K$ disjoint from the cut locus. However, this does not imply the statement that I am looking for.
The statement that I mean would be implied by the statement that
$$ \Bigl| \frac{p_t(x, y)}{(4\pi t)^{-n/2}e^{-\frac{1}{4t}d(x, y)^2}} -\sum_{j=0}^N t^j \Phi_j(x, y)\Bigr| \leq C_{K, N}t^{N+1}.$$
Chavel has this statement, but his proof relies on Lemma 1 on page 152, which is wrong (and he does not include a proof anyways). For the proof, it is refered to Berger-Gauduchon-Mazet, who do not prove Lemma 1 (which is not surprising as it is wrong...). The Book of Hsu you mentioned does contain the statement, but he just refers to Chavel for a proof.

A: If $\mathbb{M}$ is a compact manifold, the bounds you are interested in are a consequence of the Minakshisundaram-Pleijel expansion
$p_t(x,y)\sim_{t \to 0} \frac{e^{-\frac{d^2(x,y)}{4t}}}{(4\pi t)^{n/2}}\sum_{k=0}^{+\infty} u_k(x,y)t^k $
which holds uniformly on compact sets of $\mathbb{M}\times \mathbb{M} -C_{\mathbb{M}}$ where
$C_\mathbb{M}=\{ (x,y), x\text{ is in the cut-locus of }y\}$
A non-probabilistic proof of it relies on the parametrix method.
A classical reference is Chapter 6 in Chavel:Eigenvalues in Riemannian geometry. You will find the uniform asymptotic in small times page 154. Another reference is Chapter 1 in Berline-Getzler-Vergne: Heat kernels and Dirac operators.
If the manifold is non-compact, an additional  cutoff argument is needed to obtain the uniform expansion. The quick one I know uses probability. It may be found in Chapter 5 of the book by Hsu: Stochastic analysis on manifolds.
Edit.
As you  noted, there is a mistake  in the proof by Chavel (interestingly this mistake seems to originate from Donnelly which is cited in Chavel)... As far as I can see now, the proof by Chavel can be fixed to only give the estimate
$\left| p_t(x,y)- \frac{e^{-\frac{d^2(x,y)}{4t}}}{(4\pi t)^{n/2}}\sum_{k=0}^{N} u_k(x,y)t^k \right| \le C_{K,N}t^{N+1-n/2}  e^{-\frac{d^2(x,y)}{(4+\varepsilon)t}}$
However we can prove by probability methods  that
$\left| p_t(x,y)- \frac{e^{-\frac{d^2(x,y)}{4t}}}{(4\pi t)^{n/2}}\sum_{k=0}^{N} u_k(x,y)t^k \right| \le C_{K,N}t^{N+1-n/2}  e^{-\frac{d^2(x,y)}{4t}}$
So you get the bounds you are interested in. Observe that no curvature conditions are needed.
If you want  references, the result by Molchanov was reproved and generalized by Robert Azencott in this paper, by Jean-Michel Bismut in this book , and in this paper by Gerard Ben Arous. A more recent reference is this paper. You can have a look to the references.
A last comment is that if you assume that Ricci is bounded from below by -K, then we have on any compact subset of $\mathbb{M}\times\mathbb{M}$ and $t \in [0,T]$,
$p_t(x,y)\ge \frac{C}{t^{n/2}} e^{-\frac{d^2(x,y)}{4t}}$
This is a consequence of the parabolic Harnack inequality (no probability here !). You can see the proof on my blog, see the last proposition.


text:
Q: Multiple Rows update in foreach loop my SQL table
table->requirement

id        label_name      label_value      requirement_id
103         budget         5000                 4
104       specialist      dentist               4
105       treatment       clinic                4
106       expertise       criminal              5
107       charges          5100                 5

i am trying to update label_value in this this table by mysql-php.
i have tried this code in php but it is working.
foreach ($data as $columnName => $colValue) {
    echo   $subQuery .= "UPDATE `$tableName` SET `label_value`='$colValue' where (`label_name`='$columnName' AND `requirement_id`='$id')";
    mysql_query($subQuery);
    }

GETTING OUTPUT-

UPDATE requirement SET label_value='Physician' where (label_name='specialist' AND requirement_id='2')
UPDATE requirement SET label_value='Physician' where (label_name='specialist' AND requirement_id='2')
UPDATE requirement SET label_value='On Your Home' where (label_name='Appointment' AND requirement_id='2')

I don't know this is correct or not but i need to update this table in form. please help me out of this.

A: You need to remove . from  .= "UPDATE because it will concatenate your query.
For first itration of loop it will generate
UPDATE `$tableName` SET `label_value`='$colValue' where (`label_name`='$columnName' AND `requirement_id`='$id'

This query works But for second itration it will generate
UPDATE `$tableName` SET `label_value`='$colValue' where (`label_name`='$columnName' AND `requirement_id`='$id' UPDATE `$tableName` SET `label_value`='$colValue' where (`label_name`='$columnName' AND `requirement_id`='$id'

This is wrong syntax.
Just Use
foreach ($data as $columnName => $colValue) {
    echo   $subQuery = "UPDATE `$tableName` SET `label_value`='$colValue' where (`label_name`='$columnName' AND `requirement_id`='$id')";
    mysql_query($subQuery);
    }

Try to learn mysqli or pdo because mysql is depricated
Also learn mysqli_multi_query


text:
Q: Piping foreach powershell exchange permissions I am trying to list all my exchange users default calendar permissions.
I have build my command like this:
 Get-EXOMailbox -RecipientTypeDetails userMailbox -ResultSize Unlimited | foreach {Get-EXOMailboxFolderPermission -identity $_.UserPrincipalName -user Default}

It Works just fine but what I need is calendar permissions
and when I try to add ':\calendar' to my code it throws an error:

Get-EXOMailboxFolderPermission : A positional parameter cannot be found that accepts argument ':\calendar'.

Get-exoMailbox -RecipientTypeDetails userMailbox -ResultSize Unlimited | foreach {Get-exoMailboxFolderPermission -identity $_.UserPrincipalName:\calendar -user Default}

I have tried putting:\calendar and $_.UserPrincipalName  in to '' or "" but no luck.


text:
Q: Please enable low-rep users to easily breakout up and down votes on their own questions I know once you get a certain amount of reputation, you can see the total up and down votes for questions. Well, my proposal is to always be able to see this on your own questions and answers. You can see it by going to your user page anyway, so why not make it possible to do by simply clicking on the number of votes (like you can when you have the rep)?

A: That sounds reasonable. The author of a post has the most to gain from seeing the breakdown.
The rep limitation for requesting split votes is primarily to moderate the additional load on the server. If you let users view the vote breakdown on just their own posts (questions and answers), the additional load would be negligible.

A: We already get complaints from people when they see one of their questions was downvoted with no comment explaining why.
Allowing new users who are not used to the system to immediately see that their post is getting downvotes even when it's overall positive will only amplify that effect.
Further, downvotes are relatively rare.  It's certainly more interesting on meta to have this information, but on SO most users are content to upvote the good answers, leave the poor answers alone, and only downvote wrong answers.
Lastly, a downvote doesn't tell you anything.  It could be a bad vote - and even if it was valid you're still at a loss as to why your post was considered bad enough to get a downvote.  A lot of downvotes are probably improperly cast - as the recent up/down voting ratio limit is intended to help with.

*

*How will having the vote split available to all users really going to improve SO in any measurable way?

*What useful or actionable information does the vote split provide that the overall vote value does not provide?

It's only a "nice to have" or "navel gazing" feature, and one that would simply cause more complaints if given to everyone, even if restricted to their own posts.  Yes, they can see that information now, but they have to look for it, and learn about the system to get there.  With this feature it's easy to find (lots of people confused about it at first when they stumbled on it by missing the up or down vote button), and actually not intuitive.  If someone intends to vote something up, thinks they hit the upvote button, and suddenly gets the split view it's only going to confuse them, especially as a new user.

A: This is now possible. See here:
VoteCounts: bookmarklet to display up/down votes even for rep less than 1000

A: It was decided a reputation requirement was needed for performance reasons, as showing the individual votes requires a query in the votes table (counting them) instead of just fetching the score field in the post's entry.
Now I personally think this is ridiculous; such a query would require a fraction of the time needed to perform all the operations of - for example - a single, uncached page view. And users with less than 1,000 rep can view pages, can't they?

A: I still think it's an ability you should earn.
(at least to do it the easy point and click way)

A:
why not make it possible to do by simply clicking on the number of votes(like you can when you have the rep)?

It was actually arbitrarily placed as a bonus for 1k rep to make the long slog to 2k seem a little more pleasant since there's a stepping stone in the middle.
Since it's really part of the game, I doubt that's going to change.  You can see the up/down for all questions in the data dump, or if you are impatient go to the user's page for the person that posted it and check out their reputation graph for upvotes and downvotes in that post.


text:
Q: Error while deleting file through c# code I am trying to delete image from my application the code for this is:
File.Delete(filePath);
But I'm getting an exception:
Access to the path 'D:\my project\Upload\photo_calender.jpg' is denied.
The image is available in the director.
Please give me some suggestion as to how to handle this.
Thanks & Regards,
Munish

A: I assumes you have all the necessary ACL for deleting the file and suspect that; the file would be in *read_only* mode, which would cause the particular exception.
Try setting the mode file programmatically with:

File.SetAttributes(fileName, FileAttributes.Normal);
File.Delete(fileName);

A: Did you close all handles to this file before trying to delete it? It might be the cause of this exception, too.

A: You need to be sure that the credentials your process is run under have enough privileges to access the target directory and delete the file. And of course you need to clear R/O flag if any.


text:
Q: How to compute the magnitude of each complex number in an array? I'm attempting to test a program that calculates the discrete Fourier transform of a signal, namely a sine wave. To test it, I need to plot my results. However, the result is an array of size N (currently at 400) and is filled with complex numbers of the form z = x + iy. So I know that to test it I need to plot these results, and that to do this I need to plot |z|. Here's my program:
program DFT
implicit none
integer :: k, N, x, y, j, r, l, istat, p
integer, parameter :: dp = selected_real_kind(15,300)
real, allocatable,dimension(:) :: h
complex, allocatable, dimension(:) :: rst
complex, dimension(:,:), allocatable :: W
real(kind=dp) :: pi
p = 2*pi
!open file to write results to
open(unit=100, file="dft.dat", status='replace')

N = 400
!allocate arrays as length N, apart from W (NxN)
allocate(h(N))
allocate(rst(N))
allocate(W(-N/2:N/2,1:N))

pi = 3.14159265359
!loop to create the sample containing array
do k=1,N
  h(k) = sin((2*pi*k)/N)
end do

!loop to fill the product matrix with values
do j = -N/2,N/2
do k = 1, N

    W(j,k) = EXP((2.0_dp*pi*cmplx(0.0_dp,1.0_dp)*j*k)/N)

end do
end do
!use of matmul command to multiply matrices
rst = matmul(W,h)
print *, h, w
write(100,*) rst

end program

So my question is how do I take the magnitude of all the individual complex numbers in the array?

A: The ABS intrinsic function returns the magnitude of a complex number in Fortran. It is an elemental function as well, so for an array of type complex simply ABS( array ) will return a real array with the same kind as the original containing the results you want.


text:
Q: How to get model element for textnode in ckeditor 5 I want to show a special popup which allows an user to edit a specific custom attribute, if the user double clicks on an element of a specific type.
Let us for example say for the a element, but I would prefer a solution which works on all custom text nodes.
I have this code:
this.listenTo(viewDocument,'click',(event,data) => {
const viewElement=data.target;
...
}
And that gives me the view element the user clicked on. But I can't find out how to map this view element to an model element, in order to allow me to update/change/set my custom attribute.
There is editor.editing.mapper.toModelElement but that don't work for text elements such as a.
As an alternative, is there a method which allows me to set a custom attribute/property directly on the view, in a way that still get it stored in the model so it don't disappear.


text:
Q: elasticsearch/logstash regex - get the value after a specific key There is a problem I struggle with for a while:
I have data in a json format:
"documentsList": [{
        "commandScn": "108058599",
        "commandCommitScn": "108058600",
        "commandSequence": "0",
        "commandType": "UPDATE",
        "commandTimestamp": "2017-08-22 14:37:53+03:000",
        "objectDBName": "DEV2",
        "objectSchemaName": "YISHAIN",
        "objectId": "CUSTOMERS",
        "changedFieldsList": [{
                "fieldId": "CUSTOMER_ID",
                "fieldType": "NUMBER",
                "fieldValue": "17",
                "fieldChanged": "N"
            }, {
                "fieldId": "CUSTOMER_FIRST_NAME",
                "fieldType": "VARCHAR2",
                "fieldValue": "Daniel",
                "fieldChanged": "N"
            }, {
                "fieldId": "CUSTOMER_LAST_NAME",
                "fieldType": "VARCHAR2",
                "fieldValue": "Washington",
                "fieldChanged": "N"
            }, {
                "fieldId": "CUSTOMER_COUNTRY",
                "fieldType": "VARCHAR2",
                "fieldValue": "France",
                "fieldChanged": "N"
            }, {
                "fieldId": "CUSTOMER_CITY",
                "fieldType": "VARCHAR2",
                "fieldValue": "La Roche-sur-Yon",
                "fieldChanged": "N"
            }
        }]
}]

What I want is to fetch the values of the fields: fieldId, fieldType, fieldValue, fieldChanged etc. I want to aggregate by these terms afterwards in kibana 5.6.
My questions are:
How can I tell grok to fetch everything after a word (because I want the values of the keys, not the leys themselves)?
Does elasticsearch support lookbehind? if so - can anyone give me an example of how to accomplish this?
If elastic's regex doesn't support it, how can I get this done?
If I need to use regex, what will be the why to get the values? What if I had to do that without lookbehind and these methods (javascript regex)?
Thanks!
EDIT:
This is not like this question: How to parse json in logstash /grok from a text file line?
because I want to use regex and not json filters.


text:
Q: Percentage Rows from Mysql in codeigniter Here is my model code that gets percentage of all questions in table (questions)
$public function ques()
{
   #get all question count
   $query= $this->db->query("SELECT * FROM questions");
   $result = $query->result_array();
   $count = count($result);

   $limit = ($count/100)*50;

   # select only limited question which set with $limit
   $query= $this->db->get("Questions" , $limit);
   $result = $query->result_array();
   return $result;
}

There are four columns :
1. ques_id
2. question
3. exam_id
4. chapter
What I need that to get no of rows of each chapter and get percentage rows rather than to count all the questions only and returning result as shown in code. Thank you


text:
Q: Wrong type argument to increment In the following dummy example, I get a warning and I don't understand how I can get rid of it without explicitly define a pointer with int *_str = (int*)str:
#include <stdlib.h>
#include <stdint.h>

void foo(void *str, int c, size_t n) {
    for (size_t i = 0; i < n; i++)
        *((int*)str++) = c;
}

Here is what I get in gcc:
gcc -c -std=c99 -Wpointer-arith test.c
test.c: In function 'mymemset':
test.c:7:20: warning: wrong type argument to increment [-Wpointer-arith]
         *((int*)str++) = c;
                    ^

What's wrong with my code?
NOTE
I know this question is quite similar to this one, but it doesn't explain why I cannot do it and why I get an error.

A: str is a pointer to void. Since void is well, void, and has no size, how could the poor compiler possibly understand what you mean by str++?
str++ is supposed to make str point to the next object, but since the type void cannot be the type of any object str++ is meaningless.
Though you cast to int *, ++ is more "binding" (the word "precedence" confuses here) than the cast.

A: You felt into a X-Y problem because you misunderstood what *((int*)str++) = c is supposed to do. So your question is not about void arithmetic, but a lvalue post-increment.
Let's put the void issue apart for a while and consider int64_t and int32_t which have a size of 8 and 4 on a 32-bit architecture byte addressable. In short, two types with a different size.
If you want to cast int32_t* into int64_t*, assign to it a value and post increment the pointer it, you may have written as follow (inspirated from your example):
int32_t* p = &value;
*((int64_t*)p++) = 42;

According to the operator precedence the order execution is:

*

*Take p

*Save it for post-increment as a int32_t*

*Cast it to int64_t*

*Dereference it and assign 42 as a int64_t

*Post increment p

This example builds perfectly, but it is not doing what you think it does. What to want is to post-increment the cast pointer. So you need one more parenthesis:
*(((int64_t*)p)++) = 42;

This time, you will get an error because ((int64_t*)p) is considered as a lvalue and thus it cannot be modified.
In this particular case you absolutely need a third variable to do the trick.
This is exactly the same with your void pointer.


text:
Q: Get number of milliseconds for a localised date, taking into account daylight savings I have data in Google BigQuery that looks like this:

sample_date_time_UTC     time_zone       milliseconds_between_samples
--------                 ---------       ----------------------------
2019-03-31 01:06:03 UTC  Europe/Paris    60000
2019-03-31 01:16:03 UTC  Europe/Paris    60000
...

Data samples are expected at regular intervals, indicated by the value of the milliseconds_between_samples field:
The time_zone is a string that represents a Google Cloud Supported Timezone Value

I'm then checking the ratio of the actual number of samples compared to the expected number over any particular day, for any single day range (expressed as a local date, for the given time_zone):
with data as
  (
    select
      -- convert sample_date_time_UTC to equivalent local datetime for the timezone
      DATETIME(sample_date_time_UTC,time_zone) as localised_sample_date_time,
      milliseconds_between_samples
    from  `mytable`
    where sample_date_time between '2019-03-31 00:00:00.000000+01:00' and '2019-04-01 00:00:00.000000+02:00'
  )

select date(localised_sample_date_time) as localised_date, count(*)/(86400000/avg(milliseconds_between_samples)) as ratio_of_daily_sample_count_to_expected
from data
group by localised_date
order by localised_date

The problem is that this has a bug, as I've hardcoded the expected number of milliseconds in a day to 86400000. This is incorrect, as when daylight saving begins in the specified time_zone (Europe/Paris), a day is 1hr shorter. When daylight saving ends, the day is 1hr longer.
So, the query above is incorrect. It queries data for 31st March of this year in the Europe/Paris timezone (which is when daylight saving started in that timezone). The milliseconds in that day should be 82800000.
Within the query, how can I get the correct number of milliseconds for the specified localised_date?
Update:
I tried doing this to see what it returns:
select DATETIME_DIFF(DATETIME('2019-04-01 00:00:00.000000+02:00', 'Europe/Paris'), DATETIME('2019-03-31 00:00:00.000000+01:00', 'Europe/Paris'), MILLISECOND)

That didn't work - I get 86400000

A: You can get the difference in milliseconds for the two timestamps by removing the +01:00 and +02:00. Note that this gives the difference between the timestamps in UTC: 90000000, which is not the same as the actual milliseconds that passed.
You can do something like this to get the milliseconds for one day:
select 86400000 + (86400000 - DATETIME_DIFF(DATETIME('2019-04-01 00:00:00.000000', 'Europe/Paris'), DATETIME('2019-03-31 00:00:00.000000', 'Europe/Paris'), MILLISECOND))

A: Thanks @Juta, for the hint on using UTC times for the calculation. As I'm grouping my data for each day by a localised date, I figured out that I can work out milliseconds for each day by getting the beginning and end datetime (in UTC), for my 'localised' date, using the following logic:
-- get UTC start datetime for localised date
-- get UTC end datetime for localised date

-- this then gives the milliseconds for that localised date:
datetime_diff(utc_end_datetime, utc_start_datetime, MILLISECOND);

So, my full query becomes:
with daily_sample_count as (
  with data as
    (
      select
        -- get the date in the local timezone, for sample_date_time_UTC
        DATE(sample_date_time_UTC,time_zone) as localised_date,
        milliseconds_between_samples
      from  `mytable`
      where sample_date_time between '2019-03-31 00:00:00.000000+01:00' and '2019-04-01 00:00:00.000000+02:00'
    )

  select
    localised_date,
    count(*) as daily_record_count,
    avg(milliseconds_between_samples) as daily_avg_millis_between_samples,
    datetime(timestamp(localised_date, time_zone)) as utc_start_datetime,
    datetime(timestamp(date_add(localised_date, interval 1 day), time_zone)) as utc_end_datetime
  from data
)

select
  localised_date,
  -- apply calculation for ratio_of_daily_sample_count_to_expected
  -- based on the actual vs expected number of samples for the day
  -- no. of milliseconds in the day changes, when transitioning in/out of daylight saving - so we calculate milliseconds in the day
  daily_record_count/(datetime_diff(utc_end_datetime, utc_start_datetime, MILLISECOND)/daily_avg_millis_between_samples) as ratio_of_daily_sample_count_to_expected
from
  daily_sample_count


text:
Q: Order by LOCATE MySql I'm trying to retrieve the data set by locating a string based on its occurrence, check the below query -
select name, LOCATE('test', name)
from afkapi_dev.articles
where name like '%test%'
order by LOCATE('test', name) ASC

The result set is -

Result set is perfectly fine, but the issue here is the ordering.
Can anyone explain why "testing" is listed above "test low" and also suggest a way to make this happen.
Thank you

A: You seem to be asking to do further sorting on name. For multiple level sorting, you can specify different columns/expressions in ORDER BY clause, separated by comma, with respective sorting order [ASC or DESC]
Also, you can alias the LOCATE(..) expression in the SELECT clause, and reuse that in the ORDER BY. This should prevent re-computation of LOCATE(..) values.
select name, LOCATE('test', name) AS location
from afkapi_dev.articles
where name like '%test%'
order by location ASC, name ASC


text:
Q: Norm in a Vector Space A vector space with norm $\parallel\cdot\parallel$ Satisfy for two vectors the following
$\parallel x+y\parallel=\parallel x\parallel +\parallel y\parallel$
i need to proof the fallowing statement
$\parallel \alpha x+\beta y\parallel=\alpha\parallel x\parallel +\beta\parallel y\parallel$
for all $\alpha\geq0$ and $\beta\geq0$, and also this norm it's not necessary induced by an inner product
The fact that
$\alpha\parallel x\parallel +\beta\parallel y\parallel\geq\parallel \alpha x + \beta y\parallel$
it's clear because the property of the norm, what i can't proof it's the fact that
$\alpha\parallel x\parallel +\beta\parallel y\parallel\leq\parallel \alpha x + \beta y\parallel$
i will appreciate any help.

A: I have changed $\alpha, \beta$ to $a,b$. Assume without loss of generality that $b\leq a$. Then $\left\Vert ax+by\right\Vert =\left\Vert
a(x+y)+(b-a)y\right\Vert \geq a\left\Vert x+y\right\Vert -(a-b)\left\Vert
y\right\Vert =a(\left\Vert x\right\Vert +\left\Vert y\right\Vert
)-(a-b)\left\Vert y\right\Vert $
$=a\left\Vert x\right\Vert +b\left\Vert y\right\Vert $ and $\left\Vert
ax+by\right\Vert \leq a\left\Vert x\right\Vert +b\left\Vert y\right\Vert $.

A: To show that the norm is induced by an inner product you can show that the norm satisfies the parallelogram law and then use the polarization identity to recover the norm.


text:
Q: How to check for 404 links from a site that is on a host file with PHP? I will try to describe my issue as detailed as I can.
There is one live site at the moment, lets say http://example.com
I have one test site on a live server ,and I have modify my PC's hosts file as follows:
xx.xx.xx.xx example.com
xx.xx.xx.xx www.example.com

When I visit the example.com URL, I see my test website .
However I have read some tutorials on how to check with curl if a URL returns 404 error etc.
I am trying to check some URLS with curl in PHP , in order to see which URLS return 404 error.
I have tried a lot different code samples, however they do not seem to work . Is there any way to make the curl to watch the test site, instead of the live one? I am trying to add header as curlopt , however it does not seem to see this URL.
Any ideas?


text:
Q: NHibernate non-unique child collection to load eagerly (one-to-many or many-to-many)
*

*when I use one-to-many relations, I keep getting:

collection is not associated with any session

errors when loading eagerly, and not getting any children if I load lazily.

*when using many-to-many, I get unnecessary and wrong joins.
The data scheme is like this:

Item:

*

*int ID (PK)

*string Name

*int StorageId (FK Storage, non-unique usage)

Storage  (ignored in mapping):

*

*int ID (PK)

*

*string Name

TransporterToStorage (contains info, not only link table):

*

*int ID (PK)

*

*int StorageId (FK Storage)

*int TransporterId (FK Transporter)

*string TransportLineName

Transporter (ignored in mapping):

*

*int ID (PK)

*

*string Name

Item shall be represented by a C# / NHibernate class, with an additional collection property TransportersToStorage, containing 0-n entries. Due to performance reasons, I want to map only the Item.StorageId to the TransporterToStorage.StorageId and ignore the Storage table, which holds the primary key for both.
<bag name="TransportersToStorages" ... >
<key property-ref="StorageId" unique="false" ... />
<one-to-many class="TransporterToStorage" column="StorageId" ... />
</bag>

one-to-many seems to violate some NHibernate rules, because equal TransporterToStorage entries can belong to multiple Items. This is probably the cause of the:

collection is not associated with any session

error on eager loading.
The specific query is like (quick pseudo HQL, but actually done with Criteria):
select Item inner join fetch TransporterToStorage tts
where tts.TransporterId = :p1 and tts.StorageId in (:p2, :p3, :p4)

Can many-to-many or a similar association be done with only one join in the SQL sent to the database?
What is best to map this?
The child collection shall be loaded lazily by default (meaning: not at all), and eagerly in the given case.

A: I suspect a session management problem here, I suspect your session is closed BEFORE you access your lazy/eager loaded children. You might need to change the way you manage your sessions or load parent/children into a DTO and return this from your method.
Without knowing more about the way you are handling sessions a more definitive answer is difficult.


text:
Q: Python, trying to run a program from the command prompt I am trying to run a program from the command prompt in windows. I am having some issues. The code is below:
commandString = "'C:\Program Files\WebShot\webshotcmd.exe' //url '" + columns[3] + "' //out '"+columns[1]+"~"+columns[2]+".jpg'"
os.system(commandString)
time.sleep(10)

So with the single quotes I get "The filename, directory name, or volume label syntax is incorrect." If I replace the single quotes with \" then it says something to the effect of "'C:\Program' is not a valid executable."
I realize it is a syntax error, but I am not quite sure how to fix this....
column[3] contains a full url copy pasted from a web browser (so it should be url encoded). column[1] will only contain numbers and periods. column[2] contains some text, double quotes and colons are replaced. Mentioning just in case...
Thanks!

A: *

*Windows requires double quotes in this situation, and you used single quotes.

*Use the subprocess module rather than os.system, which is more robust and avoids calling the shell directly, making you not have to worry about confusing escaping issues.

*Dont use + to put together long strings. Use string formatting (string %s" % (formatting,)), which is more readable, efficient, and idiomatic.

*In this case, don't form a long string as a shell command anyhow, make a list and pass it to subprocess.call.

*As best as I can tell you are escaping your forward slash but not your backslashes, which is backwards. A string literal with // has both slashes in the string it makes. In any event, rather than either you should use the os.path module which avoids any confusion from parsing escapes and often makes scripts more portable.

A: Use the subprocess module for calling system commands. Also ,try removing the single quotes and use double quotes.


text:
Q: Use callKit to show call history in UI iOS I am trying to use the CallKit in my VoIP App to show the call history in UI iOS.
But I can not find any tutorial to how use CallKit and write code in VoIP App.

A: If you are trying to make a VoIP app which uses CallKit I recommend starting by reviewing Apple's sample code app, Speakerbox, which demonstrates using CallKit.
There is no API for an app to query or read from the device's Recents list (aka call history records). But if an app uses CallKit, its calls will be included in the Recents list.


text:
Q: Extract img inside description tag of xml file using Beautifulsoup I am doing parsing. I want to get the image inside the description tag. I am using urllib and BeautifulSoup. I can get the image which is inside the separate tag but I can't get the image inside the description tag in encoded format.
Xml code
<item>
         <title>Kidnapped NDC member and political activist tells his story</title>
         <link>http://www.yementimes.com/en/1724/news/3065</link>
         <description>
'I kept telling them that they would never break me and that the change we demanded in 2011 would come whether they wanted it or not'

</description>

views.py
for q in b.findAll('item'):
            d={}
            d['desc']=strip_tags(q.description.string).strip('&nbsp')
            if q.guid:
                d['link']=q.guid.string
            else:
                d['link']=strip_tags(q.comments)
            d['title']=q.title.string
            for r in q.findAll('enclosure'):
                d['image']=r['url']
            arr.append(d)

Can anyone please give me an idea to do it..
This is what I have done it to parse image inside the separate tag...
I tried to get if it is inside description but I can't.

A: You can try to extract all content from <description>, create a new BeautifulSoup object with it and search for src attribute of first  element:
from bs4 import BeautifulSoup
import sys
import html.parser

h = html.parser.HTMLParser()

soup = BeautifulSoup(open(sys.argv[1], 'r'), 'html')
for i in soup.find_all('item'):
    d = BeautifulSoup(h.unescape(i.description.string))
    print(d.img['src'])

Run it like:
python3 script.py xmlfile

That yields:
http://www.yementimes.com/images/thumbnails/cms-thumb-000003081.jpg


text: Q: I want to use Foursquare to look up an address for a company or venue name Can the venues API do this?  I am not trying to find what is close to a venue, but instead want to use the address from the Foursquare system.


text:
Q: PHP object operator "->" being read as PHP end "?>" I have this PHP written for editing records in SQL. I have an almost identical page for editing other records on another table that works just fine.
Here is my code:
<?php

$con=mysqli_connect("localhost","----","----","mitchpol_gigs");

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$adds['v_venue'] = $con->/*Text-Start*/real_escape_string($_POST['v_venue']);
$adds['v_url'] = $con->real_escape_string($_POST['v_url']);
$adds['v_address'] = $con->real_escape_string($_POST['v_address']);

$sql = "
UPDATE `venues`
SET v_venue='". $adds['v_venue']. "', v_url='". $adds['v_url']. "', v_address='". $adds['v_address']. "'
WHERE v_id='$_POST[v_id]'";

if ($con->query($sql) === TRUE) {
    echo "Venue edited successfully.

    Input summary:

Edited: ID" . $_POST['v_id'] . "

Venue: " . $_POST['v_venue'] . "

URL: " . $_POST['v_url'] . "

Address: " . $_POST['v_address'] . "

";
    } else {
        echo 'Error: '. $con->error . '
';
        }

include 'venueedit.php';
?>

Instead of executing the code the page returns with all the text from where I have noted in the code "Text-Start" to the end of the document.
This is the error that I get:
PHP Parse error:  syntax error, unexpected '$con' (T_VARIABLE) in (path)insertvenuesedit.php on line 1
It's as if the "->" is recognized as the end of the code in place of "?>".
My file is definitely a .php and not .html.
I read to make sure short_open_tag is off in my php.ini file. It is.
I'm wondering if there is another php.ini variable that could cause this?
EDIT - PROBLEM SOLVED but curious about solution.
Turns out it was an issue in my editor. I'm using notepad++. I copy and pasted my code from another page and made the few edits I needed to apply it to this situation. The code was displaying as I posted it above but after closing the file and re-openeing it displayed all my code on one line. After spacing everything appropriately the code works just fine.
In other words ?php $con=mysqli_connect was posting as php$con=mysqli_connect with no space between ?php and $con.
Anybody run into that kind of thing using notepad++?

A: Your PHP is not being parsed. That -> operator happens to be the first greater-than sign after the start, so the browser sees an invalid HTML tag, followed by everything that comes after it. If you had chosen to View Source in the browser, you would see all the PHP there.


text:
Q: activate python virtual environment with chef I have a python virtual environment setup and I would like to activate the virtual environment using a chef recipe.
I'm trying to run a script resource
script "Start Virtual Enviroment" do
  interpreter "bash"
  code <<-EOH
  source /path/to/virtual_environment/bin/activate
  EOH
end

when I run the recipe chef does not throw any errors but the virtual environment does not start
I am expecting the command prompt to change..
 (virtual_environment)[root@po-12-3 to]#

When I run the command without a chef recipe it works
source /path/to/virtual_environment/bin/activate

I would like to avoid using a large third party cookbook like python_pip
any help is appreciated

A: Sourcing the activate script does activate the virtual environment, but only for the duration of that shell. That is to say, the virtual environment is activated on line 4 of your script and deactivated on line 5.
If you want to use the virtual environment, try something like:
script "Start Virtual Enviroment" do
  interpreter "bash"
  code <<-EOH
  source /path/to/virtual_environment/bin/activate
  python /path/to/my/python/program.py
  EOH
end


text:
Q: How to identify lists and libraries that were created by all user other than the default list available in a site I have requirement where i have to display all lists and libraries that were created by the users in a sharepoint site. I could do this easily but the problem is i dont want to display the default lists and libraries that are created automatically when a site is created.

A: The best option is probably to loop through all Lists and Libraries and compare the Created/Author properties of the SPList to the SPWeb. If the list is more than X minutes never than the site or by another user then it's probably user created. It's not fool proff, but especially if you have custom site definitions/templates then it's the only option.


text:
Q: Will Windows 8.1 upgrade key work with new install After I upgrade to windows 8.1 from Microsoft store, if I retrieved the key using any key finding tools, will it be a new key, and will it work with new installation of windows 8.1?

A: yes the key will work, but you need to do some hacks.
You must install Windows 8.1 from a clean 8.1 ISO with a generic key, insert your key and apply the old MediaBootInstall trick from Windows 7.


text:
Q: Best way to vanish a ProgressBar once a thread ends I have an indeterminate ProgressBar spinning while a thread is doing some OCR computation, and I want the bar to be set to View.GONE once the thread concludes. However, I'm not sure the best way to register when the thread ends for this purpose. Obviously, I can't just set it to View.GONE inside the thread at the end, or else I'm touching views improperly.
Not really sure if any code is required, since the question is very general, but am happy to provide if requested

A: As it's not possible to update Views from outside the UI thread, you should use the post() method:
progressBar.post(new Runnable() {
    progressBar.setVisibility(View.GONE);
});

A: For the record, here's the code that worked for me:
spinner.post(new Runnable() {
    public void run(){
        spinner.setVisibility(View.GONE);
}});


text:
Q: It is possible to scroll a CollectionView with mouse click or scroll wheel on UWP I'm using a CollectionView in my application and I wan't that CollectionView can be scrolled by the mouse click and/or scroll wheel.
I'm using Xamarin 4.4 and if it's possible, I need to do this with MVVM pattern.
There is the definition of my CollectionView
CollectionView v = new CollectionView()
            {
                SelectionMode = SelectionMode.Single,
                ItemsLayout = new GridItemsLayout(ItemsLayoutOrientation.Horizontal),
                HeightRequest = 60,
                HorizontalScrollBarVisibility = ScrollBarVisibility.Always,
                VerticalScrollBarVisibility = ScrollBarVisibility.Never,
                FlowDirection = FlowDirection.LeftToRight,
            };

Thank's for your help !


text:
Q: Toggle-Animation only above certain window-width I want to use a Toggle-Event, but only when the window is wider than a certain size. The DIV should be visible all the time though.
My solution kind of works, but the if-statement doesn't trigger anymore, once I resize the window.
Any hints?
Here's the link:
http://jsfiddle.net/mihaene/wMrjc/

A: Ok, assuming that I have figured out your problem I just post my solution: http://jsfiddle.net/5bxLS/
var toggleOn = false;
var toggleState = 0;
function slideIn() {
     toggleState = 1;
     $("#slider").stop().animate({bottom: "-20px"}, 300);
};
function slideOut() {
    toggleState = 0;
    $("#slider").stop().animate({bottom: "-180px"}, 300) ;
};
function setToggle() {
    if(!toggleOn) {
        $('#slider').toggle(slideIn, slideOut);
        toggleOn = true;
    }
};
function clearToggle() {
    if(toggleOn) {
        if(toggleState === 1)
            $('#slider').click();
        $('#slider').off('click');
        toggleOn = false;
    }
};
function evalToggle() {
    if ($(window).width() > 500)
        setToggle();
    else
        clearToggle();
};
    //Apparently this does not work in webkit based browsers...
/*$(window).resize(evalToggle);
evalToggle();*/
    //But this works:
    $(window).resize(evalToggle).resize();

In order to stop the toggling you will have to unbind the event (which is click event in this case). The click event is also the one that executes the toggling. I build my solution in a way that toggling can be enabled in the beginning (depending on the window size).
Additionally I've made a smooth transition if the toggle state was set to on if the window is made smaller.
Hope this was the one you were searching for!


text:
Q: How can I add a watermark to a PDF using pypdf? I'm currently implementing codes using pypdf to change texts in pdf like this.
I was wondering if there are ways to add new transparent watermark or texts in the existing pdf content.
from pypdf import PdfReader, PdfWriter

reader = PdfReader(pdf_path)
writer = PdfWriter()
for page in reader.pages:
    texts = page.extract_text()
    new_text = texts.replace("text", "test")

# TODO : add watermark and change texts

with open("new.pdf", "wb") as output:
    writer.write(output)

A: I'm the maintainer of pypdf and PyPDF2. Please use pypdf in future.
pypdf does not provide a way to change texts in a PDF.
However, you can add a watermark: https://pypdf.readthedocs.io/en/latest/user/add-watermark.html#watermark-underlay
from pathlib import Path
from typing import Union, Literal, List

from pypdf import PdfWriter, PdfReader

def watermark(
    content_pdf: Path,
    stamp_pdf: Path,
    pdf_result: Path,
    page_indices: Union[Literal["ALL"], List[int]] = "ALL",
):
    reader = PdfReader(content_pdf)
    if page_indices == "ALL":
        page_indices = list(range(0, len(reader.pages)))

    writer = PdfWriter()
    for index in page_indices:
        content_page = reader.pages[index]
        mediabox = content_page.mediabox

        # You need to load it again, as the last time it was overwritten
        reader_stamp = PdfReader(stamp_pdf)
        image_page = reader_stamp.pages[0]

        image_page.merge_page(content_page)
        image_page.mediabox = mediabox
        writer.add_page(image_page)

    with open(pdf_result, "wb") as fp:
        writer.write(fp)


text:
Q: stabilizer of an induced character Suppose $K\trianglelefteq N\trianglelefteq G$ are finite groups (where $K$ isn't necessarily normal in $G$), and suppose $\chi\in\mathrm{Irr}(N)$ is induced from $\mu\in\mathrm{Irr}(K)$. Let $V=\langle n\in N:\chi(n)\neq 0\rangle\trianglelefteq N$. Then it seems to me that the stabilizer of $\chi$ in $G$ can be computed as
$$\mathrm{Stab}_G(\chi)=N\cdot \mathrm{Stab}_{N_G(V)}(\mu_V),$$
where $N_G(V)$ is the normalizer of $V$ in $G$ and $\mu_V$ is the restriction of $\mu$ to $V$. Is this correct?
Is there a better way to find the stabilizer in $G$ than finding $V$ and its normalizer, etc? I know that by Frobenius reciprocity I need to find the $g\in G$ for which $\langle \chi^g,\chi\rangle_G=\langle \chi^g_K,\mu\rangle_K\neq 0$, but I'm not sure how to decompose the restriction $\chi^g_K$ (maybe Mackey's restriction formula can be adjusted?). Thanks for help.


text: Q: Что нужно учить для Бека сайтов? Итак, если не сложно, то мне нужен список того что нужно учить для бекенда (пометочка, я уже изучаю python), в направлении веб разработки. Что вообще нужно знать чтобы сделать хотя-бы одностраничник. И если вы будете милосердны, замолвите словечко о фронте. Спасибо, благодаря вам в мире состоялся программист.


text:
Q: Apache2 redirect domain missing slash with tonger path I try to redirect a domain (old.com) to a new domain (www.new.com)
When I type http://old.com/test/ in a browser, I am redirected to http://www.new.comtest/.
Here is my configuration.
The site is served with django using mod wsgi.
Any idea?
// old
<VirtualHost *:80>
    ServerName old.com
    Redirect permanent / http://www.new.com
</VirtualHost>

// new without www
<VirtualHost *:80>
    ServerName new.com
    Redirect permanent / http://www.new.com
</VirtualHost>

// new with www
<VirtualHost *:80>
    ServerName www.new.com
    WSGIScriptAlias / var/www/index.wsgi
</VirtualHost>

A: In principle I believe that should work. The only thing I can see which is different with how I do such redirection in mod_wsgi express is that I have a trailing slash on the target:
<VirtualHost *:8000>
ServerName grumpy-old-man.com
Redirect permanent / http://www.grumpy-old-man.com:8000/
</VirtualHost>

So try adding that trailing slash.
Also be aware you should also be using:
WSGIScriptAlias / /var/www/index.wsgi

and not:
WSGIScriptAlias / var/www/index.wsgi

The target WSGI script should be an absolute path. I don't think it would be guaranteed to work if you leave the leading slash off.


text:
Q: How to compute the dimension of a vector space? Let $V$ be a vector space of dimension $n$. How to compute the dimension of the vector space $V \otimes V \otimes \Lambda^2 V + V \otimes \Lambda^2 V \otimes V +  \Lambda^2 V \otimes V \otimes V$?
We have $\dim \Lambda^2 V = n(n-1)/2$ and $\dim V \otimes V \otimes \Lambda^2 V = n^3  (n-1)/2$. Similarly, the other two summands both have dimension $n^3 (n-1)/2$. But there are some intersection of the summands. What is the dimension of $V \otimes V \otimes \Lambda^2 V + V \otimes \Lambda^2 V \otimes V +  \Lambda^2 V \otimes V \otimes V$? Thank you very much.


text:
Q: How do i use detection from yolov4 for drawing bounding box? Traceback (most recent call last):
  File "D:\vehicle detection and counting\FinalProject\tensorflow-yolov4-tflite-master\run.py", line 8, in <module>
    d.Counting(video_path='videos/hw.mp4',output_path='output/hw.mp4',skip_frames=20,confidence_tresh=0.27)
  File "D:\vehicle detection and counting\FinalProject\tensorflow-yolov4-tflite-master\Count.py", line 154, in Counting
    confidence = scores[class_id]
IndexError: index 1329146 is out of bounds for axis 0 with size 71

The code segment throwing the error is
image_data = image_data[np.newaxis, ...].astype(np.float32)
pred_bbox = self.model.predict(image_data)

for out in pred_bbox:
    for detection in out:
        # print(len(detection))
        scores = detection[5:]
        print()
        class_id = np.argmax(scores)
        print(class_id)
        confidence = scores[class_id]
        print(confidence)

How do I get bbox and class from the prediction ?
the link I used to build my model is https://github.com/hunglc007/tensorflow-yolov4-tflite
and weights are used from darknet


text:
Q: How to disable an input box by clicking a button using vue js 2.0 How can I  disable an input box via clicking a button and toggling it using vuejs 2.0

A: You can bind disabled, see an example:

new Vue({

  el: '#app',
  data: {
    isDisabled: false
  }

})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">

  <input type="text" :disabled="isDisabled">
  <button @click="isDisabled = !isDisabled">Click</button>

</div>


text:
Q: EXTJS grid rendering I'm having difficulty rendering my EXTJS grid that rides on top of a django app.  The grid is only displayed some of the time.  When the grid is supposed to be displayed it works.  When the grid is not supposed to be displayed I get a "ct is not defined" error from extjs-core.    I researched this error and it seems it occurs when my
 is not defined.  The div is defined inside a grid.html that is only loaded some of the time.
These are my files.
view_main.js - I define all of my objects here inside Ext.onReady.
Ext.onReady(function(){
 var grid = new Ext.grid.GridPanel({
  border: false,
  //...
 }
grid.render('my-grid')  // comment this out and "ct is not defined" goes away
// but the grid never renders in grid.html

base.html - my base django file that my templates extend.  This file also loads my view_main.js file.

grid.html - the grid html file that gets rendered inside an EXTJS TabPanel.

I don't want to even attempt to render my grid unless grid.html is being displayed.  But the grid doesn't work unless I put grid.render inside of view_main.js
If I try to put the render script inside grid.html the I get "grid is not defined error"

How can I only render the grid when grid.html is loaded?

A: If you're just trying to avoid that error, try checking for the existence of 'my-grid',
Ext.onReady(function() {
    if( (Ext.get('my-grid')) !== null)
    {
        grid.render('my-grid');
    }
});


text:
Q: How does interfaces with construct signatures work? I am having some trouble working out how defining constructors in interfaces work. I might be totally misunderstanding something. But I have searched for answers for a good while and I can not find anything related to this.
How do I implement the following interface in a TypeScript class:
interface MyInterface {
    new ( ... ) : MyInterface;
}

Anders Hejlsberg creates an interface containing something similar to this in this video (at around 14 minutes). But for the life of me I can not implement this in a class.
I am probably misunderstanding something, what am I not getting?
EDIT:
To clarify. With "new ( ... )" I meant "anything". My problem is that I can not get even the most basic version of this working:
interface MyInterface {
    new () : MyInterface;
}

class test implements MyInterface {
    constructor () { }
}

This is not compiling for me I get "Class 'test' declares interface 'MyInterface' but does not implement it: Type 'MyInterface' requires a construct signature, but Type 'test' lacks one" when trying to compile it.
EDIT:
So after researching this a bit more given the feedback.
interface MyInterface {
    new () : MyInterface;
}

class test implements MyInterface {
    constructor () => test { return this; }
}

Is not valid TypeScript and this does not solve the problem. You can not define the return type of the constructor. It will return "test".  The signature of the following:
    class test {
        constructor () { }
    }
Seems to be "new () => test" (obtained by hovering over "class" in the online editor with just that code pasted in). And this is what we would want and what i thought it would be.
Can anyone provide an example of this or something similar where it is actually compiling?
EDIT (again...):
So I might have come up with an idea as to why it is possible to define this in an interface but not possible to implement in a TypeScript class.The following works:
var MyClass = (function () {
    function MyClass() { }
    return MyClass;
})();

interface MyInterface {
    new () : MyInterface;
}

var testFunction = (foo: MyInterface) : void =>  { }
var bar = new MyClass();
testFunction(bar);

So is this only a feature of TypeScript that lets you interface javascript? Or is it possible to implement it in TypeScript without having to implement the class using javascript?

A: On my search for the exact same question I went looking how the TypeScript-Team did that...
They are declaring an interface and afterwards a variable with a name matching exactly the interface-name. This is also the way to type static functions.
Example from lib.d.ts:
interface Object {
    toString(): string;
    toLocaleString(): string;
    // ... rest ...
}
declare var Object: {
    new (value?: any): Object;
    (): any;
    (value: any): any;
    // ... rest ...
}

I tried that and it works like charm.

A: From a design perspective, it isn't usual to specify the constructor requirements in an interface. The interface should describe the operations you can perform on an object. Different classes that implement the interface should be allowed to require different constructor parameters if they need to.
For example, if I had an interface:
interface ISimplePersistence {
    load(id: number) : string;
    save(id: number, data: string): void;
}

I might have implementations for storing the data as a cookie, which needs no constructor parameters, and a version that stores the data in a database, which needs a connection string as a constructor parameter.
If you are still want to define constructors in an interface, there is a dirty way to do this, which I used to answer this question:
Interfaces with construct signatures not type checking

A:
Construct signatures in interfaces are not implementable in classes; they're only for defining existing JS APIs that define a 'new'-able function. Here's an example involving interfaces new signatures that does work:
interface ComesFromString {
    name: string;
}

interface StringConstructable {
    new(n: string): ComesFromString;
}

class MadeFromString implements ComesFromString {
    constructor (public name: string) {
        console.log('ctor invoked');
    }
}

function makeObj(n: StringConstructable) {
    return new n('hello!');
}

console.log(makeObj(MadeFromString).name);

This creates an actual constraint for what you can invoke makeObj with:
class Other implements ComesFromString {
    constructor (public name: string, count: number) {
    }
}

makeObj(Other); // Error! Other's constructor doesn't match StringConstructable

A: Well, an interface with a construct signature is not meant to be implemented by any class(at first glance this might look weird for guys with C#/Java background like me but give it a chance). It is slightly different.
For a moment, think of it as an interface with a call signature(like a @FunctionalInterface in the Java world). Its purpose is to describe a function type...kind of. The described signature is supposed to be satisfied by a function object...but not just any high-level function or a method. It should be a function that knows how to construct an object, a function that gets called when the new keyword is used.
So an interface with a construct signature defines the signature of a constructor! The constructor of your class that should comply with the signature defined in the interface(think of it as the constructor implements the interface). It is like a factory!
Here is a short snippet of code that tries to demonstrate the most common usage:
interface ClassicInterface { // old school interface like in C#/Java
    method1();
    ...
    methodN();
}

interface Factory { //knows how to construct an object
    // NOTE: pay attention to the return type
    new (myNumberParam: number, myStringParam: string): ClassicInterface
}

class MyImplementation implements ClassicInterface {
    // The constructor looks like the signature described in Factory
    constructor(num: number, s: string) { } // obviously returns an instance of ClassicInterface
    method1() {}
    ...
    methodN() {}
}

class MyOtherImplementation implements ClassicInterface {
    // The constructor looks like the signature described in Factory
    constructor(n: number, s: string) { } // obviously returns an instance of ClassicInterface
    method1() {}
    ...
    methodN() {}
}

// And here is the polymorphism of construction
function instantiateClassicInterface(ctor: Factory, myNumberParam: number, myStringParam: string): ClassicInterface {
    return new ctor(myNumberParam, myStringParam);
}

// And this is how we do it
let iWantTheFirstImpl = instantiateClassicInterface(MyImplementation, 3.14, "smile");
let iWantTheSecondImpl = instantiateClassicInterface(MyOtherImplementation, 42, "vafli");

A: From the official documentation

This is because when a class implements an interface, only the instance side of the class is checked. Since the constructor sits in the static side, it is not included in this check.
Instead, you would need to work with the static side of the class directly. In this example, we define two interfaces, ClockConstructor for the constructor and ClockInterface for the instance methods. Then, for convenience, we define a constructor function createClock that creates instances of the type that is passed to it:

interface ClockConstructor {
  new (hour: number, minute: number): ClockInterface;
}

interface ClockInterface {
  tick(): void;
}

function createClock(
  ctor: ClockConstructor,
  hour: number,
  minute: number
): ClockInterface {
  return new ctor(hour, minute);
}

class DigitalClock implements ClockInterface {
  constructor(h: number, m: number) {}
  tick() {
    console.log("beep beep");
  }
}

class AnalogClock implements ClockInterface {
  constructor(h: number, m: number) {}
  tick() {
    console.log("tick tock");
  }
}

let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);

A: To achieve the intended behaviour you could use Decorators, even though that is probably not what they are supposed to be used for.
This
interface MyInterface {
    new ();
}

function MyInterfaceDecorator(constructor: MyInterface) {
}

@MyInterfaceDecorator
class TestClass {
    constructor () { }
}

compiles without a problem. In contrast, the following definition for TestClass
// error TS2345: Argument of type 'typeof TestClass' is not assignable to parameter of type 'MyInterface'.
@MyInterfaceDecorator
class TestClass {
    constructor (arg: string) { }
}

will not compile.

A: To expand on Nils' answer, you can also make a generic new-able function with the same technique:
interface MyArrayConstructor {
    <T>(...elements: Array<T>): MyArrayInstance<T>
    new <T> (...elements: Array<T>): MyArrayInstance<T>
}

// "Typecast" not the function itself, but another symbol,
// so that the body of myArray will also benefit from
// type-checking:
export const MyArray = myArray as MyArrayConstructor

interface MyArrayInstance<T> {
    push(...args: Array<T>): number
    slice(from?: number, to?:number): Array<T>
}

function myArray(...elements: Array<T>): MyArrayInstance<T> {
  return {
    push(...args) { ... },
    slice(from?: number, to?: number) { ... }
  }
}

A: you can use type instead
class SomeClass {
    constructor(param1: string, param2: number) {
    }
}

type Params = new (param1: string, param2: number) => SomeClass
type ConstructParams = ConstructorParameters<Params> // [string, number]


text:
Q: Django redirecting to a different view in another app There are many similar questions to mine on Stack Overflow, but none which solve my problem.
I have a class-based view which accepts files, and once a valid file is found, I would like the website to redirect the user to a template inside a different app, passing in some parameters.
I've seen others put an extra path in 'urlpatterns' and get the view from there. But doing this only makes a GET signal on my command prompt, but not actually changing the web url.
views.py
from django.shortcuts import render, redirect   # used to render templates
from django.http import JsonResponse
from django.views import View

from .forms import UploadForm
from .models import FileUpload

class UploadView(View):
    def get(self, request):
        files_list = FileUpload.objects.all()
        return render(self.request, 'upload/upload.html', {'csv_files': files_list})

def post(self, request):
    form = UploadForm(self.request.POST, self.request.FILES)
    if form.is_valid():
        csv_file = form.save()
        data = {'is_valid': True,
                'name': csv_file.file.name,
                'url': csv_file.file.url,
                'date': csv_file.uploaded_at}
        # REDIRECT USER TO VIEW PASSING 'data' IN CONTEXT
        return redirect('graph:chart', file_url=csv_file.file.url)
    else:
        data = {'is_valid': False}
    return JsonResponse(data)

urls.py
from django.urls import path
from . import views

app_name = "upload"

urlpatterns = [
    path('', views.UploadView.as_view(), name='drag_and_drop'),
]

urls.py (of other app)
from django.urls import path
from . import views

app_name = "graph"

urlpatterns = [
    path('', views.page, name='chart'),
]

A: You can specify an app name and use exactly the redirect shortcut as you started:
https://docs.djangoproject.com/en/2.1/topics/http/urls/#naming-url-patterns
in the other app urls.py define app_name = 'other_app', and then use redirect('other_app:url_name', parameter1=p1, parameter2 = p2)
you can name easily your parameters either using path (Django >=2.0) or url (re_path for Django >=2.0), for instance:

from django.urls import path

from . import views

urlpatterns = [
    path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
    re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
]


text:
Q: When designing a directory structure should filenames include folder names? Suppose I have two directories: house-1 and house-2. Each house directory needs to have files describing its windows and doors.
I am trying to understand how to name the files and directories. My current two options are:
house-1
    windows.txt
    doors.txt
house-2
    windows.txt
    doors.txt

or
house-1
    house-1-windows.txt
    house-1-doors.txt
house-2
    house-2-windows.txt
    house-2-doors.txt

I can see advantages and disadvantages to both of them and am trying to decide which is the better option (or if something else is better too). What should I consider when designing a filename structure such as this?

A: Although you ask "from a developers perspective" I think there are considerations outside that narrow constraint:

*

*If the files are only going to be maintained by future developers, then your first option is great. It is clear and unambiguous.

*But if you are going to need to email files to and from business analysts or other outside parties, I would adopt your second approach. The directory structure is not going to survive the email processing, and you could end up with lots of doors.txt files in your inbox, with no idea which house they belong to.

As a developer, I would be happy with the second option so long as the directory nesting was only a couple of layers deep. I might get a tad tetchy if the file name ended up something like usa.newyorkstate.newyork.manhattan.32ndstreet.218a.suite34.doors.txt


text:
Q: How to enable hocr font info in tesseract 4? I'm using tessseract 4 on ubuntu 16.04.
so when using hocr feature  in tesseract and after activating font info in hocr config file (hocr_font_info 1) I'm still not getting " x_font "info.
Is there any other way to enable font info in tesseract4?


text:
Q: obtain the low pass signal and its magnitude spectrum also to plot the inphase and quadrature components of x(t) and the envelope of x(t)[MATLAB] Unable to obtain the low pass signal and its magnitude spectrum .also to plot the inphase and quadrature components of x(t) and the envelope of x(t).
i have attached the question along too.
what is the mistake of the code,i have defined function.still its not working.
    df=0.5;
ts=0.001;
fs=1/ts;
t=-2:0.001:2;
fo=200;
x=sinc(100*t).*cos(400*pi*t);
plot(t,x);
xlabel('time');
ylabel('x(t)');
y=fftseq(x,ts,df);%calling the function fftseq
N=length(y);
f=([0:N-1]-N/2)*fs/N; % generate frequency vector for plot
y=fftshift(y);        % swap lower and upper spectrum halves

plot(f, abs(y));
xlabel('frequency');
ylabel('x(f)');
axis([-500 500]);

xl=loweq(x,ts,fo);%calling the function loweq
plot(abs(x1));
figure
I = real(x1);%real part
Q = imag(x1);%imaginary part
plot(I);
plot(Q);
function xl=loweq(x,ts,f0)
% xl=loweq(x,ts,f0)
%LOWEQ returns the lowpass equivalent of the signal x
% f0 is the center frequency.
% ts is the sampling interval
t=[0:ts:ts*(length(x)-1)];
z=hilbert(x);
xl=z.*exp(-j*2*pi*f0*t);
end

function [M,m,df]=fftseq(m,ts,df)
% [M,m,df]=fftseq(m,ts,df)
% [M,m,df]=fftseq(m,ts)
%FFTSEQ generates M, the FFT of the sequence m.
% The sequence is zero-padded to meet the required frequency resolution df.
% ts is the sampling interval. The output df is the final frequency resolution.
% Output m is the zero-padded version of input m. M is the FFT.
fs=1/ts;
if nargin == 2
n1=0;
else
n1=fs/df;[enter image description here][1]
end
n2=length(m);
n=2^(max(nextpow2(n1),nextpow2(n2)));
M=fft(m,n);
m=[m,zeros(1,n-n2)];
df=fs/n;
end

A: The fft function returns a spectrum corresponding to frequencies between 0 and fs with the upper half of the spectrum (between fs/2 and fs) being a symmetry of the lower half for real-valued signals. That upper half of the spectrum is often also represented as negative frequencies between -f2/2 and 0 (such that the whole spectrum is shown between -fs/2 and fs/2). To plot the spectrum using this convention, you need to swap the upper and lower halves of the result, and generate corresponding frequency vector for the x-axis:
N=length(y);
f=([0:N-1]-N/2)*fs/N; % generate frequency vector for plot
y=fftshift(y);        % swap lower and upper spectrum halves

plot(f, abs(y));
xlabel('frequency');
ylabel('x(f)');
axis([-500 500]);


text:
Q: Projections of lines in $\mathbb{R}^n$ to the torus $\mathbb{T}^n$ Let $\mathbf{e}\in\mathbb{R}^n$ be a unit vector, $\hat L:=\mathbb{R}\mathbf{e}$ be the line in the direction of $\mathbf{e}$, which projects down to a line $L$ on the torus $\mathbb{T}^n:=\mathbb{R}^n/\mathbb{Z}^n$.
Question 1. Is the following statement true?

*

*The line $L$ is dense on the torus if and only if the components of $e$ are $\mathbb{Q}$-independent.

More generally, we can define

*

*the rank $r(\mathbf{e})$ of $\mathbf{e}$, which is the dimension of the closure $K(\mathbf{e})$ of the line $L$ in $\mathbb{T}^n$.

*the co-rank $z(\mathbf{e})$ of $\mathbf{e}$, which is the $\mathbb{Q}$-dimensions of the space of rational vectors $Z(e)=\{\mathbf{r}\in \mathbb{Q}^n: \mathbf{r}\cdot \mathbf{e} =0\}$.
Question 2. Does it hold that $r(\mathbf{e})+z(\mathbf{e})=n$?
Thanks!

A: Consider the flow $\hat\phi_t(x)=x+te$ of $R^n$, it commutes with the action of $Z^n$ and define a flow $\phi_t$ on $R$. Let $p:R^n\rightarrow T^n$ be the covering map, $L$ is the orbit of $p(0)$ by $\phi_t$.
Now we can apply the results of Yves Carriere on Riemannian flow or the results of Marina Ratner on unipotent flows which says that there exists a closed subgroup $H$ of $T^n$ such that $p(H(0))$ is closed in $R^n$ and the orbit of $p(0)$ by $\phi_t$ is a dense subset of $p(H(0))$.
Suppose that $H$ is distinct of $R^n$ and its a $l$-vector subspace $l<n$, since $p(H(0))$ is closed, there exists $u_1,..,u_l\in H$ with integral coordinates such that $(u_1,..,u_l)$ is a base of $H$, we can write $e=a_1u_1+..a_lu_l$. Since the coordinates of $u_i$ are integers  the coordinates of $x$ are elements of the $Q$-vector space generated by $a_1,..,a_l$ since $l<n$. We deduce that they are $Q$-linearly dependent. Contradiction.
https://en.wikipedia.org/wiki/Ratner%27s_theorems
Carriere Yves, Flot Riemanniens.
in "Structures transverses des feuilletages", Asterisque, 116
(1984),31-52


text:
Q: getting parent in self referential model Based on http://guides.rubyonrails.org/association_basics.html#self-joins
I created a self join model called Category
rails g model Category name parent_id:integer

I altered the model category.rb as below
Class Category < ActiveRecord::Base
  has_many :sub_categories, class_name: "Category", foreign_key: "parent_id"
  belongs_to :parent_category, class_name: "Category"
end

Now in console I'm creating two records of Category as
a = Category.create(name: "Animal")
b = Category.create(name: "Dog")

a.sub_categories << b
a.save

Now
a.sub_categories # returns Dog

however
b.parent_category # returns nil

How do I get parent_category return the single parent record correctly?
Also if I do b.parent_category = a
I get the following error
ActiveModel::MissingAttributeError: can't write unknown attribute 'parent_category_id'

A: You need to modify the association parent_category.
There you have to specify the foreign key.
belongs_to :parent_category, class_name: "Category", foreign_key: 'parent_id'


text:
Q: Functionapp With Custom Runtime Image, Use ACR Admin Credentials in ARM Template I'm in the process of migrating our functionapps to custom runtime containers. I'm doing this through ARM templates.
I've got to the point where I can do this, however, in order to get it to work, I have to manually open the Deployment Center and hit save after provisioning, otherwise the functionapp cannot pull down from the ACR (and the logs say there's an auth error).

2022-10-10T22:25:29.055Z INFO  - Recycling container because of AppSettingsChange and isMainSite = True
2022-10-10T22:25:32.116Z ERROR - DockerApiException: Docker API responded with status code=InternalServerError, response={"message":"Get https://redacted.azurecr.io/v2/redacted/manifests/preview: unauthorized: authentication required, visit https://aka.ms/acr/authorization for more information."}

As soon as I click save (I don't even change anything) it pulls down and deploys correctly.
Whilst I don't need to reprovision often, this manual step is a pain and I want to fix it, what do I need to add to my ARM template to facilitate this?
The relevent section of the ARM template is:
{
      "type": "Microsoft.Web/sites",
      "apiVersion": "2022-03-01",
      "name": "[parameters('functionAppName')]",
      "location": "[parameters('location')]",
      "kind": "functionapp,linux,container",
      "identity": {
        "type": "SystemAssigned"
      },
      "dependsOn": [
        "[variables('appServicePlanResourceId')]",
        "[variables('deploymentStorageAccountId')]",
        "[variables('networkResourceId')]",
        "[resourceId('microsoft.insights/components', parameters('functionAppName'))]"
      ],
      "tags": {
        "Product": "[variables('productTag')]",
        "Environment": "[parameters('environmentTag')]"
      },
      "properties": {
        "ftpsState": "FtpsOnly",
        "httpsOnly": true,
        "reserved": true,
        "serverFarmId": "[variables('appServicePlanResourceId')]",
        "siteConfig": {
          "appSettings": [
            {
              "name": "AzureWebJobsStorage",
              "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', parameters('deploymentStorageAccountName'), ';EndpointSuffix=', environment().suffixes.storage, ';AccountKey=',listKeys(variables('deploymentStorageAccountId'), '2019-06-01').keys[0].value)]"
            },
            {
              "name": "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING",
              "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', parameters('deploymentStorageAccountName'), ';EndpointSuffix=', environment().suffixes.storage, ';AccountKey=',listKeys(variables('deploymentStorageAccountId'), '2019-06-01').keys[0].value)]"
            },
            {
              "name": "WEBSITE_CONTENTSHARE",
              "value": "[toLower(parameters('functionAppName'))]"
            },
            {
              "name": "FUNCTIONS_EXTENSION_VERSION",
              "value": "~3"
            },
            {
              "name": "APPLICATIONINSIGHTS_CONNECTION_STRING",
              "value": "[concat('InstrumentationKey=', reference(resourceId('Microsoft.Insights/components', parameters('functionAppName')), '2020-02-02-preview').instrumentationKey)]"
            },
            {
              "name": "FUNCTIONS_WORKER_RUNTIME",
              "value": "dotnet"
            },
            {
              "name": "EventGridTopicEndpoint",
              "value": "[reference(variables('eventGridTopicId')).endpoint]"
            },
            {
              "name": "EventGridTopicAccessKey",
              "value": "[listKeys(variables('eventGridTopicId'), '2020-06-01').key1]"
            },
            {
              "name": "WEBSITE_DNS_SERVER",
              "value": "redacted"
            },
            {
              "name": "WEBSITE_VNET_ROUTE_ALL",
              "value": 1
            },
            {
              "name": "WEBSITES_ENABLE_APP_SERVICE_STORAGE",
              "value": "false"
            }
          ],
          "linuxFxVersion": "[parameters('linuxFxVersion')]",
          "acrUseManagedIdentityCreds": false
        }
      },
      "resources": [
        {
          "type": "networkConfig",
          "apiVersion": "2019-08-01",
          "name": "virtualNetwork",
          "dependsOn": [ "[variables('functionAppResourceId')]" ],
          "properties": {
            "subnetResourceId": "[variables('subnetResourceId')]",
            "isSwift": true
          }
        }
      ]
    }

[parameters('linuxFxVersion')] evaluates to DOCKER|redacted.azurecr.io/redacted:preview

Every answer that I've found so far requires either adding config options with docker usernames and passwords, or using a managed identity, neither of which is what we want.

A: You need to add an RBAC assignment to your ACR instance granting the system-assigned identity of your function app the AcrPull role.
The alternative is using admin credentials.
When you hit "Save" in the deployment center, it's using one of those two methods -- it's retrieving the admin credentials from the ACR and applying them to the app service. It's not doing anything special, it's doing exactly what you can do yourself.
I recommend using managed identities instead. You can even create a single user-assigned identity and share it across multiple function apps, if you really want to.

A: Reference a secret in a key vault:
"adminPassword": {
    "reference": {
        "keyVault": {
        "id": "/subscriptions/<SubscriptionID>/resourceGroups/mykeyvaultdeploymentrg/providers/Microsoft.KeyVault/vaults/<KeyVaultName>"
        },
        "secretName": "vmAdminPassword"
    }
}

A: So with hints taken from the other two answers and from here, I've devised two solutions.
Using Service Principal Role

*

*Add "acrUseManagedIdentityCreds": true to the siteConfig in my ARM template

*Assign the AcrPull role to the service principal of the functionapp (I've not tested this snippet because perms weren't set-up quite right and it's too late for me to ask someone to change them)

"resources": [
        {
          "type": "Microsoft.Authorization/roleAssignments",
          "apiVersion": "2018-09-01-preview",
          "name": "[guid(resourceGroup().id)]",
          "dependsOn": [
            "[parameters('functionAppName')]"
          ],
          "properties": {
            "roleDefinitionId": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', '7f951dda-4ed3-4680-a7ca-43fe172d538d')]",
            "principalId": "[reference(resourceId('Microsoft.Web/sites', parameters('functionAppName')), '2022-03-01').identity.principalId]"
          }
        }
]

Getting Admin Creds with Reference

*

*Add these variables to my template:

"registryName": "containerRegName",
    "registrySubscriptionId": "container-reg-sub-id",
    "registryResourceGroup": "container-reg-rg",
    "registryResourceId": "[resourceId(variables('registrySubscriptionId'), variables('registryResourceGroup'), 'Microsoft.ContainerRegistry/registries', variables('registryName'))]"
  },

*Then add these configuration options to my appsettings:

{
    "name": "DOCKER_REGISTRY_SERVER_URL",
    "value": "[reference(variables('registryResourceId'), '2019-05-01').loginServer]"
},
{
    "name": "DOCKER_REGISTRY_SERVER_USERNAME",
    "value": "[listCredentials(variables('registryResourceId'), '2019-05-01').username]"
},
{
    "name":  "DOCKER_REGISTRY_SERVER_PASSWORD",
    "value": "[listCredentials(variables('registryResourceId'), '2019-05-01').passwords[0].value]"
}


text:
Q: How to convert json data to html nested lists What is a good algorithm to convert this json data:
json_data = [
  {"text": "One", "indent": 0},
  {"text": "Two", "indent": 0},
  {"text": "Alpha", "indent": 1},
  {"text": "I", "indent": 2},
  {"text": "II", "indent": 2},
  {"text": "Three", "indent": 0}
]

To this html nested lists:

 One

 Two

 Alpha

 I

 II

 Three

Solutions in python or javascript would be great.

A: I went through it on my own, here is a python solution
json_data = [
  {"text": "One", "indent": 0},
  {"text": "Two", "indent": 0},
  {"text": "Alpha", "indent": 1},
  {"text": "I", "indent": 2},
  {"text": "II", "indent": 3},
  {"text": "Three", "indent": 1}
]

for idx, data in enumerate(json_data):
    if idx == 0:
        html = '
'
        prev_indent = data['indent']
    if idx == len(json_data) - 1:
        html += '
%s
' % data['text']
        html += '

' * data['indent']
        html += '
'
        break

    next_indent = json_data[idx+1]['indent']
    indent = data['indent']
    if indent == next_indent:
        html += '
%s
' % data['text']
    elif indent < next_indent:
        html += '
%s
' % data['text']
    else: # indent > next_indent
        html += ('
%s
' % data['text']) + ('

' * (indent - next_indent))

    prev_indent = data['indent']

print(html)