Laravel 5.3 - Merge array based on 2 matching keys?

Question: Given the following two arrays, how can they be merged efficiently to result in the third array?
productData
$productData =
[
  {
    "product_id": 4,
    "type": "electronic",
    "name": "monitor",
    "specs": {
      "HDMI": true,
      "VGA": false
    }
  },
  {
    "product_id": 5,
    "type": "electronic",
    "name": "HDMI cable",
    "specs": {
      "length": "3ft"
    }
  },
  {
    "product_id": 6,
    "type": "kitchen",
    "name": "spoon"
  }
]

products
$products =
{
  "products": 3,
  "per_page": 10,
  "current_page": 1,
  "data": [
    {
      "id": 4,
      "product_type": "electronic",
      "product_id": 6
    },
    {
      "id": 6,
      "type": "electronic",
      "product_id": 5
    },
    {
      "id": 9,
      "type": "kitchen",
      "product_id": 4
    }
  ]
}

productsFinal ($productData merged into $products - based on matching combo of product_id/product_id and type/product_type)
$productsFinal =
{
  "products": 3,
  "per_page": 10,
  "current_page": 1,
  "data": [
    {
      "id": 4,
      "product_type": "electronic",
      "product_id": 6,

      // How to merge product data and wrap with "data" key
      "data": {
        "product_id": 6,
        "type": "kitchen",
        "name": "spoon"
      }

    },
    {
      "id": 6,
      "type": "electronic",
      "product_id": 5,

      // How to merge product data and wrap in "data" key
      "data": {
        "product_id": 5,
        "type": "electronic",
        "name": "HDMI cable",
        "specs": {
          "length": "3ft"
        }
      }
    },
    {
      "id": 9,
      "type": "kitchen",
      "product_id": 4,

      // How to merge product data and wrap in "data" key
      "data": {
        "product_id": 6,
        "type": "kitchen",
        "name": "spoon"
      }
    }
  ]
}

I tried different things for the outcome in a foreach loop but still cannot get it to render as intended:
foreach($productData as $productDataItem) {
  // when $productDataItem.product_id == $product.product_id && $productDataItem.type == $product.product_type
  // move the matching $productDataItem object into matching $product object, wrapped in a new "data" key
}

Comment: This is not PHP code here. What have you tried to solve this yourself?
Comment: It is in PHP (Laravel) where I have this issue, that is what a laravel collection outputs. I tried a few different ways, but wasn't able to accomplish the format of the third array, and it is taking me way too long to implement. That's why I posted the question under `php/laravel`, as someone who knows laravel may know how to do this.
Comment: Are you trying to make a JSON response for an API? If yes, I may have a solution.
Answer: I don't know Laravel too well. However you can join your data objects quite easily:
<?php
$productData = json_decode('[
  {
    "product_id": 4,
    "type": "electronic",
    "name": "monitor",
    "specs": {
      "HDMI": true,
      "VGA": false
    }
  },
  {
    "product_id": 5,
    "type": "electronic",
    "name": "HDMI cable",
    "specs": {
      "length": "3ft"
    }
  },
  {
    "product_id": 6,
    "type": "kitchen",
    "name": "spoon"
  }
]');

$products = json_decode('{
  "products": 3,
  "per_page": 10,
  "current_page": 1,
  "data": [
    {
      "id": 4,
      "type": "electronic",
      "product_id": 6
    },
    {
      "id": 6,
      "type": "electronic",
      "product_id": 5
    },
    {
      "id": 9,
      "type": "kitchen",
      "product_id": 4
    }
  ]
}');

// combine both data objects

foreach($products->data As &$p) {
    foreach($productData As $d) {
        if(property_exists($p, "product_id") && property_exists($d, "product_id") && property_exists($p, "type") && property_exists($d, "type")) {
            if($p->product_id==$d->product_id && $p->type==$d->type) {
                //$p = (object) array_merge((array) $p, (array) $d);
                $p->data = $d; // updated answer
                continue;
            }
        }
    }
}

echo("
");
echo json_encode($products, JSON_PRETTY_PRINT);

?>

You can test the code here: http://sandbox.onlinephpfunctions.com/code/98a50c35ee32c30f0d2be1661f7afb5895174cbe
Update: http://sandbox.onlinephpfunctions.com/code/aeebfdcf4f4db5e960260e931982570cfed19e0e
Comment: Thank you for this, it is really close to the final output, but I really am trying to get the exact syntax in `$productsFinal` (my final output), outputted from your sandbox to match the final output. Currently there are 2 differences, the `"data": [` and the fact that it adds the index to each product. Any idea how to change your logic to match `$productsFinal`?
Answer: I would suggest to check this package dingo/api. I assume you want to display some kind of JSON response. Take a look at Transformers. You can do something like this :
<?php
namespace App\Http\Transformers;
use App\Http\Controllers\ProductData;
use League\Fractal\TransformerAbstract;

class ProductsDataTransformer extends TransformerAbstract
{
    /**
     * Turn this item object into a generic array
     *
     * @return array
     */
    public function transform(ProductData $productdata)
    {
        return [
            'id' => $productdata->id,
            'product_type' => $productdata->product_type,
            'product /*or data*/' => Product::find($productdata->product_id),
        ];
    }

}

This would find the product by it's ID and look like this :
{
  "id": 4,
  "product_type": "electronic",
  "product" {
    "product_id": 6,
    "type": "kitchen",
    "name": "spoon"
  },
},

You can then also create a transformer for Product to take care of your specs attribute to do the same thing.


Fourier Transform of $1/(\pi\cdot t)$ by Duality

Question: I'm asked to prove using "duality property" the Fourier transform of
$$\frac{1}{\pi t} = -j sgn(f)$$
I have the proof steps but I'm quit not understanding it:

multiply by $j = \frac{j}{j(\pi t)}$
$j2\pi x(-w)$
$2j\pi(-0.5+U(-w))$

multiplying by $2$ and factoring $- sgn$ gives:
$$-j( 1-2U(-w))= -j*sgn (f)$$
*correction: ignore the above steps as they are confusing, consider this answer:
prove $$\frac{1}{πt} ↔ -j sgn(f)$$
Using the duality theorem which state:
If $x(t) ↔ X(f)$
then  $X(t) ↔ x(-f)$
Let $x(t) = \frac{1}{πt}$ and $X(t) = -j sgn(f)$
Then by duality theorem:
$-j sgn(t) ↔ - \frac{1}{πf}$
Calculating Fourier Transform of $–jsgn(t)$:
$\mathcal{F}[-j sgn(t) ]= -j \mathcal{F}[sgn(t)]$
Fourier transform of $sgn(t)$ is :
$\mathcal{F}[sgn(t)] = \frac{1}{πfj}$
Thus
$\frac{1}{πt} ↔ -j* \frac{1}{jπf} =  - \frac{1}{πf}$
Therefore if we apply the duality again on this result we ge
$\frac{1}{πt}  = -j sgn(f)$
Comment: It is hard to understand your steps above. Adding more words about what you are doing in each step would help. Also what do you mean by "multiply by $j=j/j(πt)$"? You should also add the notation you are using, as it is not clear what $U$, $x$ etc. are here.
Comment: @dustin could you add text edit to my post please again since I don't know how to do it.
Answer: The duality property is the statement that if
$$\mathcal{F}(h(t)) = H(\omega)$$
then
$$\mathcal{F}(H(t)) = h(-\omega)$$
To use the duality property to prove the statement you need to show that
$$\mathcal{F}\left(i~\text{sign}(t)\right) = -\frac{1}{\omega\pi}$$
This can be done by a direct computation of $\mathcal{F}\left(i~\text{sign}(t)\right)$. To do this note that
$$\frac{d}{dx} \text{sign} (x) = 2\delta(x)$$
and by using the property
$$ \mathcal{F}\left(\frac{dg(x)}{dx}\right) = 2\pi i\omega \mathcal{F}(g(x))$$
togeather with $\mathcal{F}(\delta) = 1$ the result follows (I have used the convention $\mathcal{F}(g) \equiv \int g(x)e^{-2\pi i \omega} dx$ above).
Comment: Thank you for clarification, I know that the above steps are confusing, I didn't wrote those steps that's why I didn't understand it, getting hint by your solution I came up with the proof using another properties because I didn't really get the rest of your steps. I have edited my post you can check it.


Minimum of the functional $F[f]=\int_0^1 f'(x)^2dx-\log \left(f\left(\frac{1}{2}\right)\right)$

Question: I have to find a minimum, if exists, for the functional
$$F[f]=\int_0^1 f'(x)^2dx-\log \left(f\left(\frac{1}{2}\right)\right)$$
On the space
$$f\in H^1((0,1)):\ f\ge 0,\ \int_0^1 f(x)\ dx=1$$
(this may not be the best choice, if you have a better ides for the functional space be free to suggest).
At first I tried with the Euler-Lagragne equation with the lagrange multipliers, which gave me the differential equation
$$2f''(x)=\lambda+\frac{\delta_{1/2}(x)}{f(1/2)}\qquad \text{ in } D'((0,1))$$
with Neumann boundary conditions:
$$f'(0)=0,\qquad f'(1)=0$$
Is there a way to solve it (analitically or numerically)?
Does it make sense that the solution becomes a kind of spline?
Comment: What's $v$ in $\int_0^1 f'(v)dx$?
Comment: It's a typo, my fault
Comment: Well, then yes, the solution becomes a spline. Why not?
Comment: Ok, it is great to have something that does not contradict intuition ahahah.
Comment: What about solvability?
Answer: This $\delta$ on the rhs can be translated to a jump in $f'$ at $1/2$:
$$
f'(x) = f'(0)+ \int_0^x f''(t) =  \lambda x+
\begin{cases}
0 & \text{ if } x<1/2\\
\frac1{f(1/2)} & \text{ if } x > 1/2.
\end{cases}
$$
This can be made rigorous using smooth test function and integration by parts on $(0,1/2)$ and $(1/2,1)$.
Then $f$ is a quadratic polynomial on $(0,1/2)$ and $(1/2,1)$, continuous, with prescribed jump of $f'$ at $1/2$. This should make it possible to solve for $f$.


Taking the "semi definite" integral of a function with Heaviside step function

Question: $$\int_0^tH(\tau-2)(e^{-2(\tau-2)}-e^{-3(\tau-2)})\,d\tau$$
As I understand it, I can't just set the lower boundary to $2$, because this is a semi definite integral, because of the upper boundary being the variable $t$.
However, that makes the expression I get look way more ugly than if I could let the lower boundary be set to $2$.
When I input this into Mathematica, I get the expression:
$$\frac{1}{6}\left(1+2e^{6-3t}-3e^{4-2t}\right)H(t-2)$$
Which is the integral with the lower boundary set to $2$, but the factor $H(t-2)$ stays.
Answer: Well, if $t>2$, you just do the integral. If $t<2$, the integral is zero. A convenient way to write this is the step function.
Comment: To add to this, the $H(t - 2)$ in the solution isn't quite the same as the $H(\tau - 2)$ in the problem.  (For one thing, the variable is different.)  So it's not that that factor somehow stays.  It's just that the answer behaves differently depending on how $t$ compares with $2$, which is different from (although related to) that the function in the problem behaves differently depending on how $\tau$ compares with $2$.


When using a view in "Unformatted list" format with inline fields, how can I most cleanly add a break between the fields?

Question: I have a view like this:

Field A (Inline)
Field B (Inline)
Field C (Inline)
Field D

I would like it to display like this:

Field A label: value Field B label: value
Field C label: value
Field D

Obviously, I need to create a break after the value for Field B.  However, what is the best way to do this?  CSS in my stylesheet?  Rewrite the HTML  for the display of Field B?  Add a "Custom text" field within the view?  It seems like there must be a simpler way...
I hardly ever work with themes so I'm at a loss of how to best address even this basic formatting issue.
EDIT: I've realized that a solution that makes the view label inline but not the whole field would also work, but I don't know how to do this...
Comment: Your ideas seem all very sound to me. You can `clear:right` field B's wrapper, you can put a `` in a Custom Text. What stops you from implementing one of these ?
Comment: Nothing is stopping me from implementing one of these.  I was just wondering what is the cleanest, most easily maintainable way to do this.  For example, I didn't even know "custom text" existed until yesterday, so I figured I would ask to see if there was a way that was better than what I already knew.
Comment: As much as possible, I stick to CSS. If I cannot achieve what I want, I try to rewrite the fields via UI. If it's not enough, I go for the template files to customize further. This way of thinking is pretty common and I think you'll be safe adopting it.
Comment: http://drupal.stackexchange.com/questions/32277/how-can-i-concatenate-two-fields-in-a-view
Answer: I would say CSS is the better route because it separates your content from your layout just as CSS does with respect to HTML.  Also, if you decide to change your layout later on, CSS will most probably be easier (and more obvious) to change than some fake data in a view forcing that is forcing/hardcoding your layout.
Answer: You can create a custom layout with Panels module then use that layout inside your view by choosing Panel Fields as rows style and assigning your fields to different regions of the layout.
Comment: This is quite an interesting solution that I hadn't thought of.  Thanks!
Comment: This is also very useful when you work with Features module and you want your views look the same everywhere.


trigger each element individually on scroll with GSAP Scrolltrigger

Question: I am working with GSAP/Scrolltrigger and I want to change the border-radius of a div on scroll (scrub). It works but somehow it resets and loops when the next element with the same trigger class enters and I can't find the solution, what am I missing?

gsap.utils.toArray(".bgcolor").forEach(function(elem) {

const $section = $(".bgcolor");

radiusChange = gsap.fromTo($section, { borderRadius: "1rem" },{ borderRadius: "5rem" })

  ScrollTrigger.create({
    trigger: elem,
    start: "top 75%",
    scrub: true,
    animation: radiusChange,
    markers: true,
  });

});
* {margin:0;}

.spacer {
  position:relative;
  width:100%;
  height:100vh;
  background:black;
}

.content {
  padding:100px 0;
}

.bgcolor {
  height: 200px;
  margin-bottom:40px;
  background:lightblue;
}
<link href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

I also tried it by coding it the following way but that also doesn't seem to work because now it doesn't trigger the startpoint and immidiatly triggers the last rem number.

const borderradius = gsap.utils.toArray('.borderradius');
borderradius.forEach(radius => {

  radiusChange = gsap.fromTo(borderradius, { borderRadius: "0rem" },{ borderRadius: "5rem" })

  gsap.to(radius, {
    scrollTrigger: {
      trigger: radius,
      scrub: true,
      animation: radiusChange,
    }
  })
});
* {margin:0;}

.spacer {
  position:relative;
  width:100%;
  height:100vh;
  background:black;
}

.content {
  padding:100px 0;
}

.borderradius {
  height: 200px;
  background:lightblue;
  margin-bottom:40px;
}
<link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

Answer: I found the solution, I wasn't far off, here is the solution:
gsap.utils.toArray(".bgcolor").forEach(function(elem) {
const $section = $(elem);
const radiusChange = gsap.fromTo($section, { borderRadius: "1rem" },{ borderRadius: "5rem" });

  ScrollTrigger.create({
    trigger: elem,
    start: "top 75%",
    scrub: true,
    animation: radiusChange,
    markers: true,
  });
});


Como utilizar JSON

Question: Eu tenho um link de uma API (https://api.tibiadata.com/v2/characters/Norkx.json)
queria saber se tem como eu pegar
"name":"Norkx",
"sex":"female",
"vocation":"Royal Paladin",
"level":407,
"world":"Inabra"
e imprimir em HTML?
Comment: Olá tibiano, pode fazer em JavaScript https://stackoverflow.com/a/35970894
Answer: Você pode resolver este problema utilizando requisições ajax, e utilizar a biblioteca javascript jQuery.
Vou exemplificar como montar uma tabela com essa api que você mostrou:

//este é um exemplo de ajax sendo chamado ao clickar em um botao qualquer do seu html.

//ele pega o id do botao, e no click desse botao ele começa a função ajax
$('#btncnes').click(function(){
  $.ajax({
    //aqui a url do seu servelet, no caso eu "usei um servelet publico"
    url: 'https://api.tibiadata.com/v2/characters/Norkx.json',
    //o tipo do metodo GET,POST, PUT, DELETE
    type: 'GET',
    dataType: 'jsonp',
    //caso de certo o que fazer:
    success: function(data) {
      console.log('retorno do server');
        console.log(data);
        var tr =
        "
"+
         ""+data.characters.data.name+"	"+
         ""+data.characters.data.sex+"	"+
         ""+data.characters.data.vocation+"	"+
         ""+data.characters.data.level+"	"+
         ""+data.characters.data.word+"	"+
        "
";

        //id do tbody da tabela
        $("#tbodyMain").append(tr);

    }
  });
});

  name
  sex
  vocation
  level
  word

<button type='button' id='btncnes' >CARREGAR</button>

o EXEMPLO não funciona para esta api pois ela esta bloqueando o acesso, mas é assim que você pega o retorno dos dados dessa api:
success: function(data) {
  console.log('retorno do server');
    //todos
    console.log(data);
    //somente o nome data.characters.data.name
    //somente o sex data.characters.data.sex
    //somente o vocation data.characters.data.vocation
    //somente o level data.characters.data.level
    //somente o word data.characters.data.word

}

Desta maneira você pega os dados que voce falou do json
Exmplicação de como trabalhar com JSON

Essa é a imagem do retorno de uma requisição utilizando postman
se a variável de retorno se chama dados por exemplo:
dados irá retornar todo o objecto. se quiser somente characters use data.characters e se quiser o nome use data.characters.name e por ai vai...
se for um array ai você precisa usar data.characters.name[indice do array]
o mesmo código utilizando outra url de uma API publica:

//este é um exemplo de ajax sendo chamado ao clickar em um botao qualquer do seu html.

//ele pega o id do botao, e no click desse botao ele começa a função ajax
$('#btncnes').click(function(){
  $.ajax({
    //aqui a url do seu servelet, no caso eu "usei um servelet publico"
    url: 'http://www.json-generator.com/api/json/get/cdYItaXpvm?indent=2',
    //o tipo do metodo GET,POST, PUT, DELETE
    type: 'GET',
    dataType: 'jsonp',
    //caso de certo o que fazer:
    success: function(data) {
      console.log('retorno do server');

        var tr =
        "
"+
         ""+data[0].email+"	"+
         ""+data[0].picture+"	"+
         ""+data[0].phone+"	"+
         ""+data[0].address+"	"+
         ""+data[0].company+"	"+
        "
";

        //id do tbody da tabela
        $("#tbodyMain").append(tr);

    }
  });
});

  email
  picture
  phone
  address
  company

<button type='button' id='btncnes' >CARREGAR</button>
Comment: entao nem tem como eu utilizar essa api ?
Comment: Rafael, se você estiver dentro do dominio 'tibiadata' sim, caso ao contrario não, pois o cors não está habilitado
Comment: Pensei que era uma api publica e eu conseguiria retirar alguma informação dela.
Comment: pior que não cara, fiz uma edição usando o mesmo código só que pra uma api publica
Comment: A API é pública sim, o problema aqui é [CORS](https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Controle_Acesso_CORS). É mais ou menos assim: você tem um cliente (seu navegador) que está acessando um site (stackoverflow) e faz uma requisição para um segundo servidor (API do Tibia). Para que isso funcione é necessário que o servidor do Tibia permita isso através do CORS.

Como utilizar JSON


Get term name for page title from term id passed in the contextual filter?

Question: What is the correct method of getting term name in the page title field if I have passed the term id in contextual filter.
I have added the Content: Has taxonomy term ID contextual filter in views, I have tried to overwrite the page title be provide "%1" but that also provides term id as the "filter value type" contains term ID.
One way to achieve this using the "global php" field in the header and getting the term ID from the argument as "arg(1)", and getting the term name from the term ID and than setting page title using "drupal_set_title($term_name)".
Comment: How did you give the override option? It works fine that way..
Comment: Thanks for reply, but I have tried that by providing "%1" in override title link, and it is than displaying the term id but I require the term name.
Comment: could you take a screenshot of the views config screen and post it in the question.
Comment: @MohammedShameem Added :)
Comment: you should try removing the % from the path and make the path just product-category
Comment: @MohammedShameem - I have tried it as you have adviced but than it renders the hard coded value "product-category"
Comment: what have you given for filter value type
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/10829/discussion-between-ankit-agrawal-and-mohammed-shameem)
Answer: Answers Updated:
try this hook, hook_view_pre_render()

This hook is called right before the render process. The query has
  been executed, and the pre_render() phase has already happened for
  handlers, so all data should be available.

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'your_view_name') {
     $term = taxonomy_term_load(arg('arg_position_in_url'));
     $title = $term->name;
     $view->build_info['title'] = $title;
  }
}

Comment: Thanks Arpit, I have mentioned this solution in the question. This is definitely one of the possible solution, but I am trying to see If we can have some better solution.
Comment: check with updated answer
Comment: @ankit please did that work for you? or you got better way to do this, please share if so
Comment: I am waiting to see if we can some better alternative, otherwise this is definitely one to go with.
Answer: Got the solution:
The mistake I was doing was selecting the "Display all results for the specified field" for the "When the filter value is NOT in the URL" field of contextual filter, Instead I was supposed to do the following for this field:

Check "Provide default value".
Select Type: "Taxonomy term ID from URL"
Select checkbox: "Load default filter from term page"

and rest everything as mentioned in the question.


Why are my parser types not picked up in my elastic index?

Question: I'm using fluent-bit to forward logs to an elastic db. All my fields are being indexed in elastic under the default string type but I want some fields indexed as numbers.
I've attempted to set the types in my fluent-bit config by adding a types entry to both the docker parser and the json parser (not sure which one is being used here, these are container logs from a k8s cluster):
[PARSER]
Name   json
Format json
Time_Key time
Time_Format %d/%b/%Y:%H:%M:%S %z
Types my_float_field:float my_integer_field:integer

[PARSER]
Name        docker
Format      json
Time_Key    time
Time_Format %Y-%m-%dT%H:%M:%S.%L
Time_Keep   On
Types my_float_field:float my_integer_field:integer

But these fields continue to appear as string types in fresh elastic indexes under the ids log_processed.my_float_field and log_processed.my_integer_field. I'm sure I'm doing something obviously wrong but I can see what.
Any pointers would be greatly appreciated.
Answer: Use Elasticsearch index templates.
AFAIK the JSON parser plugin doesn't support "Type" parameter. It keeps the original JSON data types, so if my_float_field and my_integer_field contain quoted values, JSON parser will interpret them as strings as well. See this example from the docs:

A simple configuration that can be found in the default parsers
  configuration file, is the entry to parse Docker log files (when the
  tail input plugin is used):
[PARSER]
    Name        docker
    Format      json
    Time_Key    time
    Time_Format %Y-%m-%dT%H:%M:%S %z

The following log entry is a valid content for the parser defined
  above:
{"key1": 12345, "key2": "abc", "time": "2006-07-28T13:22:04Z"}

After processing, it internal representation will be:
[1154103724, {"key1"=>12345, "key2"=>"abc"}]

If you are using Logstash format in Elasticsearch output plugin, you can define an Elasticsearch index template containing the desired type mapping. The template will be applied to each newly created index (not to existing indices). The format changed in Elasticsearch 7, so be sure to check the correct documentation version. For the 7.7 version:
PUT _template/template_1
{
  "index_patterns": ["fluent-bit-*"],
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "properties": {
      "my_float_field": {
        "type": "float"
      },
      "my_integer_field": {
        "type": "integer"
      }
    }
  }
}


Change Form Elements Depending On Selected Option

Question: I have seen several sites where there is a form, starting with a dropdown box, and depending on the box chosen there is different form elements, for example, let's say I wanted to make an uploader script, the dropdown box might hold:
Upload
Delete

And is Upload is selected I would want a browse file element, while with Delete selcted maybe only the name should be imputted into a text field. How can I make it do so? I plan on using php for it and using the echo syntax to create the html for the forms, but is ther a way to have, for example an if statment, that changes the other form elements that show based on the option selected.
I have seen people use jQuery for it, but I can ONLY use PHP ad HTML for my project.
Answer: This isn't a direct solution but if you intend on carrying out this task exclusively with php/html then you should consider setting up a system such as this in the php file which serves the page.
<?php

/*Check to see if the user has submitted the form*/
if(isset($_POST['action']))
    $action = $_POST['action'];

/*If no action has been sent from the client side, generate form*/
if(!isset($action)){ ?>
    <form name="test" action="example.php" method="POST">
        <select name="action">
            <option value="update">Update</option>
            <option value="delete">delete</option>
        </select>
    </form>
<?}

/* if update action, load file dialog*/
elseif($action == "update"){?>

<?}

/*Default to delete*/
else{?>

    <input name="fileName" value="<? echo $FILE_NAME; ?>" />
<?}
?>

Essentially you're going to have to handle both page serving and form processing within the one page, using the value from the form select element to determine which blocks of HTML need to be loaded. Note that you will still have to provide a submit button for the form in order to trigger the action since there's no javascript events.
I want to distance myself from this solution as I know of it only through experiencing the Dunning Kruger effect and I'm sure the lack of client side involvement will be frowned upon by most.
Answer: Im no expert, but i guess since PHP is a Server-Side Scripting Language, there is no way to do this purely in php, other than to reload the page evertime you switch the dropdown option. Maybe you could accomplish it with frames (but who wants to use those?).
Comment: I know it's pssible with PHP without refreashing, I just don't know how to do it. Since I'm using PHP to write the html coding, via the echo syntax, I belive there should be a way to check the value of an already existing field, that's basically what I'm trying to find out.
Comment: the problem is that once the page is loaded, there is now way - at least not known to me - to let php check for a value. Im pretty sure, that you have to use a Client-Side script (Jquery, Javascript or Ajax) to accomplish this. But as i said i might be proven wrong here
Comment: then idk, I might not be able to complete my task. I can try to see if there's some way to enable javascript on my host
Comment: this would make your life so much easier. There are so many possibilties by using Jquery, Ajax etc.
Comment: @D3_JMultiply - You don't need to enable javascript on the host - it runs on the client.  See my answer for details.
Answer: You can't do what you want in purely server-side code without some sort of submission from the browser to trigger the check.  PHP code runs on the server and returns the page to the browser.  Once the page has left the server there's nothing PHP can do to it.
Sites I've seen that do this kind of thing on the server-side reload usually have an initial page where you choose the action you want, and then load the form for the chosen action.  That's really all you can do without some kind of javascript on the client side.
If you can use javascript then you have many more options:

Trigger a reload of the form when the drop-down box is changed.
Send an ajax request when the drop-down box is changed and dynamically add the HTML returned by the server to the form.
Send fields for all options in the original page, and use the change event on the drop-down to show/hide the relevant fields.

Based on your comments to other answers there seems to be some confusion as to the role of javascript in the application.  The server doesn't need to know about Javascript, or even JQuery.  The server runs your PHP code to build the HTML for your page.  The HTML can reference CSS stylesheets, images, Javascript files, etc, which, as far as the server is concerned, are just static files requested by the browser.  Once the client browser gets the javascript file from the server it can execute it and enable whatever dynmiac page behaviour is intended.  There is no Javascript code in your server-side application.  The application is just a bunch of PHP files, with a collection of other static files to support the generated HTML.
Comment: Thank you for clearing that up, a little, I understand that it's not server-sided, I guess I'm just not able to explain the reason behind why.  I can use javascript and such I guess, but I was hoping not to, for a few different reasons.

One reason: I know almost 0 javascript
Two Reason: the client requested that if possible not to use them, idky.
Answer: jQuery is just a pre-written javascript subset, are you not allowed to use javascript? if you can not use it, then your ability for dynamic pages diminishes greatly.
AJAX uses javascript as well and is the solution I use to load dynamic content. do you need examples or a way to do this without javascript.
Comment: Javascript is executed on the user's computer ... and all browsers support it from what i know.
Comment: I'm not alowed to use anything except PHP and HTML, I mean I could but for the purpose of what I'm doing, which isn't really important, it would not work, I have to host the files on a specific host, whicch doesn't have support for javascript/pearl/just about anything else.

I'm hoping there is a way to do this without javascript, I've seen pages that use purely PHP I just don't know the code behind it.
Comment: JavaScript is a client-side script. You don't need server-side support for it to work.


Not able to go back to previous page while using Router in Reactjs

Question: I am new to Reactjs.So I am making a basic website where there will be a link to Home page, a link to privacy policy and a link to Terms and conditions.
Below is the code for App.js
import React from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";
import PrivacyPolicy from './components/PrivacyPolicy';
import TermsAndConditions from './components/TermsAndConditions';
import Home from './components/Home';
import Footer from './components/Footer';
import Header from './components/Header';
import ReactDOM from 'react-dom';

function App() {

  return (

    <Router>

              <Link to="/">Home</Link>

              <Link to="/privacy-policy">PrivacyPolicy</Link>

              <Link to="/terms-and-conditions">TermsAndConditions</Link>

        {/* A <Switch> looks through its children <Route>s and
            renders the first one that matches the current URL. */}

        <Switch>

          <Route path="/privacy-policy">
            <PrivacyPolicy />
          </Route>
          <Route path="/terms-and-conditions">
            <TermsAndConditions />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>

    </Router>

  );

}

export default App;

Below is the code for Privacy Policy page that is privacypolicy.js
import React from 'react';
import ReactDOM from 'react-dom';

function PrivacyPolicy() {

    const element =  (

            {"some text"}

    );
    ReactDOM.render(element,document.getElementById('root'));
}

export default PrivacyPolicy;

Now The code for Terms and conditions page
import React from 'react';

function TermsAndConditions() {
    return (

            {"some text."}

    );
}

export default TermsAndConditions;

Now the problem is whenever I go to privacy policy page by clicking on the link on home page I am able to go to privacy policy page and now when press the back button in chrome the link changes to home page but the page is not refreshed it is still showing the privacy policy content while in case of terms and conditions I am able to come back.
Please help
Answer: Update your Privacy Policy to:
import React from 'react';

function PrivacyPolicy() {
    return (

            {"some text"}

    );
}

export default PrivacyPolicy;

Comment: ohh so sorry I should have mentioned that. Actually Whenever I am clicking on the privacy policy link it is getting rendered on the same page (home page) . I want it to be rendered on other page.
Comment: in simple words whenever I am clicking privacy policy link the text in privacy policy page is rendered on the same page below the three links I want it to be rendered in a whole new page


Verifying an isometric map

Question: Let $(X,d)$ be a metric space. Take a fixed $a \in X$. Consider for every $x \in X$ the function $f_{x}:X \rightarrow \mathbb{R}:y \mapsto f_{x}(x)=d(x,y)-d(a,y)$.
Now it is clear that $f_{x}$ is continuous and bounded for every $x \in X$. I have to show that $d_{\infty}(f_{x},f_{x'})=d(x,x')$, where $d_{\infty}$ denotes the metric $d_{\infty}(f,g)= \sup \{|f(x)-g(x)|$ where $x \in X \}$   (where $f$ and $g$ must be continuous and bounded).
So far I have: $d_{\infty}(f_{x},f_{x'})= \sup \{|f_{x}(y)-f_{x'}(y)|$ where $y \in X\}= \sup \{|(d(x,y)-d(a,y))-(d(x',y)-d(a,y))| \}=\sup \{|d(x,y)-d(x',y)| \}=...$ $=d(x,x')$. I guess I can't just skip the dots because I feel something is missing in the argument. I don't think the triangle inequality on itself is sufficient? Any help? Thank you.
Answer: Fix $x,x'$ we have
$$ d_\infty (f_x,f_x')=sup\{|d(x,y)-d(a,y)-d(x',y)+d(a,y)|y\in X\}=sup\{|d(x,y)-d(x',y)|y\in X\}$$
Now by the triangle inequality $d(x,x')\geq |d(x,y)-d(x',y)|$ (1) we conclude that $d_\infty(f_x,f_x')\leq d(x,x')$ (2) But for $y=x$ we have $d(x,x')=|d(x,x)-d(x',x)|$ (3) and so we have $d_\infty(f_x,f_x')\geq d(x,x')$ which completes the proof.
(1) by the triangle inequality $d(x,x')+d(x',y)\geq d(x,y)$ and $d(x,x')+d(x,y)\geq d(x',y)$ this two gives $d(x,x')\geq |d(x,y)-d(x',y)|$
(2) here I use the fact that if every element of the set is bounded (in our case by $d(x,x')$) then so is the supremum.
(3) If one of the elements is bigger than $d(x,x')$ then so is the supremum.
Comment: (It should be $d(x,x')+d(x',y) \geq d(x,y)$ and $d(x,x')+d(x,y) \geq d(x',y)$ at $(1)$.)

Verifying an isometric map


$arccsc(\csc(2\pi/3))$. What's the value?

Question: I tried to solve this problem using $f^{-1}(f(x))=x$. However, the range of Arccsc is greater or equal to $-1/2\pi$ and less or equal to $1/2 \pi$. And, apparently, $2\pi/3$ is not in the range. How do I solve this problem not using a calculator?
Answer: Let $y={\rm arccsc}(\csc(2\pi/3))$.  This means
$$\csc y=\csc(2\pi/3)\ ,\qquad -\pi/2\le y\le\pi/2\ .$$
Now $\csc t=\csc(\pi-t)$ provided $t$ is not a multiple of $\pi$, so this can be written
$$\csc y=\csc(\pi/3)\ ,\qquad -\pi/2\le y\le\pi/2\ ,$$
and the answer is $y=\pi/3$.
Comment: Another one. Sec^-1(sec210). Using your way, I get secy=sec 210. The answer's 150. How's that answer obtained? sec 210=sec (pi*1=30). But how can it be 150?
Comment: Same way.  You will need to know the conventional range for $\sec^{-1}$, usually $0$ to $\pi$ excluding $\pi/2$, but check what you have been told, because some sources may do it differently.  The relevant identities for $\sec$ are $\sec(-t)=\sec t$ and $\sec(2\pi-t)=\sec t$.
Answer: The cosecant function is not 1-1, so you restrict it to $(-\pi/2, \pi/2)$ to make it 1-1 (this is the "principal branch").  You only get $f^{-1}\circ f(x)$ for $x\in (-\pi/2, \pi/2)$.
Answer: By definition the identity
$$ \sin ^{-1} x = \csc^{-1} {1/x} $$
we have
$$csc^{-1}(\csc(2\pi/3)) = \sin^{-1}(1/\csc(2\pi/3))=\sin^{-1}(\sin (2\pi/3))$$
$$=2 \pi/3, \pi- 2 \pi/3,... $$
i.e.,
$$ \pi/3, 2 \pi/3$$
plus for co-terminal angles add $2 \pi$
$$ 7 \pi/3, 8\pi/3$$
etc. lying in quadrants 1,2 only.


JSF/XHTML/CSS 'tableview' of divs

Question: I am currently trying to iterate over a list which will generate a
(...)
 for each value. These divs will be represented as 'blocks' (as shown in the image below). Problem is, I need them to align as in a row (so the new row starts at the lowest point of the previous).

This would be no problem when using a container div per row, like so:

(...)

(...)

(...)

(...)

(...)

(...)

Though I would prefer not to use container divs, as I would need to use certain logic inside my <ui:repeat>(...)</ui:repeat> to add

 on every third entry.
I'm posting this under JSF too, because I'm hoping that JSF (or PrimeFaces or Tomahawk) has an appropriate solution. Though, if a simple CSS-trick would suffice, that would be perfect.
Hopefully you'll be able to help me out with this one.
Note: a solution using tables won't help me, as I would face the same issue using
(...)
 as with my described container div above.
Comment: Is there a semantic reason to not use tables? This is easily possible with the combination `` and ``. Otherwise you really can't nicely go around a container div to represent a row.
Comment: is changing outer divs to span an option?
Comment: Unbelievable how easy this was and that I completely forgot about ``. This was indeed the tag I've been searching for. I would accept this as the answer if not posted as a comment.
Answer: Is there a semantic reason to not use tables? This is easily possible with the combination <h:panelGrid> and <c:forEach>.
<h:panelGrid columns="3">
    <c:forEach items="#{bean.items}" var="item">
        <h:panelGroup>#{item}</h:panelGroup>
    </c:forEach>
</h:panelGrid>

It works that way because <c:forEach> runs during view build time and effectively generates physically multiple <h:panelGroup> components so that they properly end up each as a cell of the <h:panelGrid>. It wouldn't have worked when using <ui:repeat>, because that runs during view render time only and effectively ends up as a single cell of the <h:panelGrid> during view build time.
If there's a strong and valid semantic reason to not use tables, then you really can't nicely go around a container
 to represent a row.

    <ui:repeat value="#{bean.items}" var="item" varStatus="loop">
        <h:outputText value="</div><div>" escape="false" rendered="#{not loop.first and loop.index % 3 == 0}" />

#{item}

    </ui:repeat>

See also:

JSTL in JSF2 Facelets... makes sense?
JSF 2 ui:repeat: group every n items inside a div

JSF/XHTML/CSS 'tableview' of divs


Unable to lock entry:

Question: Entry was automatically empty once I moved to another page. How do I maintain the state of Entry so that it will only change/empty when I want?
page1.xaml:
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="NSF_app.setting">
  <StackLayout BackgroundColor="White" Padding="20"
    VerticalOptions="Center" HorizontalOptions="Fill">
    <Entry x:Name="UserEntry"
    VerticalOptions="CenterAndExpand"
    InputTransparent="True" IsEnabled="False" IsReadOnly="True"/>
    <Button Text="read_Only" Clicked="Reado_OnClicked"/>
    <Button Text="Remove" Clicked="remove_OnClicked"/>
  </StackLayout>

page1.xaml.cs:
namespace NSF_app
{
    public partial class page1
    {
        public static string EntryValue = "";
        public page1()
        {
            InitializeComponent();
        }
        private void Reado_OnClicked(object sender, EventArgs e)
        {
            UserEntry.IsReadOnly = true;
            UserEntry.InputTransparent = true;
            UserEntry.IsEnabled = false;
        }

        private void remove_OnClicked(object sender, EventArgs e)
        {
            UserEntry.IsReadOnly = false;
            UserEntry.InputTransparent = false;
            UserEntry.IsEnabled = true;
        }
    }

}

Answer: I test with the code below. The entry is enabled at first time and then i click the remove to input the text "hello". After that i would navigate to another page. When i click the back button to back to the Page1, the "hello" text would still in the entry.
App.xaml.cs:
  public App()
    {
        InitializeComponent();

        MainPage = new NavigationPage(new Page1());
    }

Page1.xaml.cs:
 public Page1()
    {
        InitializeComponent();
    }
    public static string EntryValue = "";
    private void Reado_OnClicked(object sender, EventArgs e)
    {
        UserEntry.IsReadOnly = true;
        UserEntry.InputTransparent = true;
        UserEntry.IsEnabled = false;
    }

    private void remove_OnClicked(object sender, EventArgs e)
    {
        UserEntry.IsReadOnly = false;
        UserEntry.InputTransparent = false;
        UserEntry.IsEnabled = true;
    }

    async void Button_Clicked(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new MainPage());
    }

Updated:
A easy way is two define the property in your AppShell.
AppShell.xaml.cs:
 public partial class AppShell : Xamarin.Forms.Shell
{
    public ICommand LogoutCommand => new Command(async () => await NavigationEvent());
    public string EntryValue { get; set; }
    async Task NavigationEvent()
    {
        await Shell.Current.GoToAsync("page1");
    }

    public AppShell()
    {
        InitializeComponent();
        Routing.RegisterRoute("page1", typeof(Page1));
        this.BindingContext = this;
    }
}

Xaml:
  <ContentPage.Content>
    <StackLayout
        Padding="20"
        BackgroundColor="White"
        HorizontalOptions="Fill"
        VerticalOptions="Center">
        <Entry
            x:Name="UserEntry"
            InputTransparent="True"
            IsEnabled="False"
            IsReadOnly="True"
            Text="{Binding EntryValue}"
            TextChanged="UserEntry_TextChanged"
            VerticalOptions="CenterAndExpand" />
        <Button Clicked="Reado_OnClicked" Text="read_Only" />
        <Button Clicked="remove_OnClicked" Text="Remove" />
    </StackLayout>
</ContentPage.Content>

Code Behind:
  public Page1()
    {
        InitializeComponent();
        UserEntry.Text = new AppShell().EntryValue;
    }

    private void Reado_OnClicked(object sender, EventArgs e)
    {
        UserEntry.IsReadOnly = true;
        UserEntry.InputTransparent = true;
        UserEntry.IsEnabled = false;
    }

    private void remove_OnClicked(object sender, EventArgs e)
    {
        UserEntry.IsReadOnly = false;
        UserEntry.InputTransparent = false;
        UserEntry.IsEnabled = true;
    }

    private void UserEntry_TextChanged(object sender, TextChangedEventArgs e)
    {
        new AppShell().EntryValue = UserEntry.Text;
    }

Comment: You could check the screenshot: https://imgur.com/CUovugV
Comment: The Idea was great but, navigate using navigation.push async will affect my required output. my concept is here - https://imgur.com/a/O2awoJa - when I use back button the lable was emptied.
Comment: ohhh, you used the shell menu item? I would check it again and feedback ASAP.
Comment: @BalaVelan I have updated the reply. You could check the screenshot. https://imgur.com/xt1e5mb
Comment: https://imgur.com/a/ciTObQo  - If exit from the app and open the app, that entry again emptied. Is it posible to make the entry lock ,even we exit from the app.
Comment: If you want to save the data when you close the app, you could save it in the database or file in the device. When you open the app, load the data again.
Comment: You could check the sample code for the sqlite database. https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/todo/

Unable to lock entry:


Extract specific JSON keys and convert to CSV in Python

Question: I'm converting several JSON files into a CSV using the following code below, it works as intended, but it converts all of the data in the JSON file. Instead, I want it to do the following:

Load JSON file [done]
Extract certain nested data in the JSON file [wip]
Convert to CSV [done]

Current Code
import json, pandas
from flatten_json import flatten
# Enter the path to the JSON and the filename without appending '.json'
file_path = r'C:\Path\To\file_name'
# Open and load the JSON file
dic = json.load(open(file_path + '.json', 'r', encoding='utf-8', errors='ignore'))
# Flatten and convert to a data frame
dic_flattened = (flatten(d, '.') for d in dic)
df = pandas.DataFrame(dic_flattened)
# Export to CSV in the same directory with the original file name
export_csv = df.to_csv (file_path + r'.csv', sep=',', encoding='utf-8', index=None, header=True)

In the example at the bottom, I only want everything under the following keys: created, emails, and identities. The rest is useless information (such as statusCode) or it's duplicated under a different key name (such as profile and userInfo).
I know it requires a for loop and if statement to specify the key names later on, but not sure the best way to implement it. This is what I have so far when I want to test it:
Attempted Code
import json, pandas
from flatten_json import flatten
# Enter the path to the JSON and the filename without appending '.json'
file_path = r'C:\Path\To\file_name'
# Open and load the JSON file
json_file = open(file_path + '.json', 'r', encoding='utf-8', errors='ignore')
dic = json.load(json_file)
# List keys to extract
key_list = ['created', 'emails', 'identities']
for d in dic:
    #print(d['identities']) #Print all 'identities'
    #if 'identities' in d: #Check if 'identities' exists
    if key_list in d:
        # Flatten and convert to a data frame
        #dic_flattened = (flatten(d, '.') for d in dic)
        #df = pandas.DataFrame(dic_flattened)
    else:
        # Skip
# Export to CSV in the same directory with the original file name
        #export_csv = df.to_csv (file_path + r'.csv', sep=',', encoding='utf-8', index=None, header=True)

Is this the right logic?
file_name.json Example
[
    {
        "callId": "abc123",
        "errorCode": 0,
        "apiVersion": 2,
        "statusCode": 200,
        "statusReason": "OK",
        "time": "2020-12-14T12:00:32.744Z",
        "registeredTimestamp": 1417731582000,
        "UID": "_guid_abc123==",
        "created": "2014-12-04T22:19:42.894Z",
        "createdTimestamp": 1417731582000,
        "data": {},
        "preferences": {},
        "emails": {
            "verified": [],
            "unverified": []
        },
        "identities": [
            {
                "provider": "facebook",
                "providerUID": "123",
                "allowsLogin": true,
                "isLoginIdentity": true,
                "isExpiredSession": true,
                "lastUpdated": "2014-12-04T22:26:37.002Z",
                "lastUpdatedTimestamp": 1417731997002,
                "oldestDataUpdated": "2014-12-04T22:26:37.002Z",
                "oldestDataUpdatedTimestamp": 1417731997002,
                "firstName": "John",
                "lastName": "Doe",
                "nickname": "John Doe",
                "profileURL": "https://www.facebook.com/John.Doe",
                "age": 30,
                "birthDay": 31,
                "birthMonth": 12,
                "birthYear": 1969,
                "city": "City, State",
                "education": [
                    {
                        "school": "High School Name",
                        "schoolType": "High School",
                        "degree": null,
                        "startYear": 0,
                        "fieldOfStudy": null,
                        "endYear": 0
                    }
                ],
                "educationLevel": "High School",
                "followersCount": 0,
                "gender": "m",
                "hometown": "City, State",
                "languages": "English",
                "locale": "en_US",
                "name": "John Doe",
                "photoURL": "https://graph.facebook.com/123/picture?type=large",
                "timezone": "-8",
                "thumbnailURL": "https://graph.facebook.com/123/picture?type=square",
                "username": "john.doe",
                "verified": "true",
                "work": [
                    {
                        "companyID": null,
                        "isCurrent": null,
                        "endDate": null,
                        "company": "Company Name",
                        "industry": null,
                        "title": "Company Title",
                        "companySize": null,
                        "startDate": "2010-12-31T00:00:00"
                    }
                ]
            }
        ],
        "isActive": true,
        "isLockedOut": false,
        "isRegistered": true,
        "isVerified": false,
        "lastLogin": "2014-12-04T22:26:33.002Z",
        "lastLoginTimestamp": 1417731993000,
        "lastUpdated": "2014-12-04T22:19:42.769Z",
        "lastUpdatedTimestamp": 1417731582769,
        "loginProvider": "facebook",
        "loginIDs": {
            "emails": [],
            "unverifiedEmails": []
        },
        "rbaPolicy": {
            "riskPolicyLocked": false
        },
        "oldestDataUpdated": "2014-12-04T22:19:42.894Z",
        "oldestDataUpdatedTimestamp": 1417731582894
        "registered": "2014-12-04T22:19:42.956Z",
        "regSource": "",
        "socialProviders": "facebook"
    }
]

Comment: So basically, assuming you have `key_list = ['created', 'emails', 'identities']`, just add this line: `dic = [{k:d[k] for k in key_list} for d in dic]`. and then keep the rest of your original script as-is, assuming it was all working.
Comment: Note, `dic` is a pretty bad name for a `list`
Comment: To me it seems like you should filter out the data that you need up front, right after you load your json, right before `dic_flattened = (flatten(d, '.') for d in dic)`, and then just do the exact same thing.
Answer: As mentioned by juanpa.arrivillaga, I simply need to add the following line after the key_list:
json_list = [{k:d[k] for k in key_list} for d in json_list]

This is the full working code:
import json, pandas
from flatten_json import flatten

# Enter the path to the JSON and the filename without appending '.json'
file_path = r'C:\Path\To\file_name'

# Open and load the JSON file
json_list = json.load(open(file_path + '.json', 'r', encoding='utf-8', errors='ignore'))

# Extract data from the defined key names
key_list = ['created', 'emails', 'identities']
json_list = [{k:d[k] for k in key_list} for d in json_list]

# Flatten and convert to a data frame
json_list_flattened = (flatten(d, '.') for d in json_list)
df = pandas.DataFrame(json_list_flattened)

# Export to CSV in the same directory with the original file name
export_csv = df.to_csv (file_path + r'.csv', sep=',', encoding='utf-8', index=None, header=True)


Display node with specific revision

Question: I am trying to load a node using the revisioning module to display an unpublished piece of content, by passing a version ID to node_load(). We also use the i18n module which may or may not have an affect on what I am trying to achieve. We are looking to implement a "preview" of a page which may be sent out to departments that do not have a user account of any sort (We do not want to create a login for this). The preview page is requested with the version &vid=12345 and a &preview URL parameter.
At the moment, if the specific revision is not published, the preview page will load the currently published content instead of the version we are passing to node_load().
I have tried to create a preview user with view unpublished permissions, but this does not work (still loads the published content).
Is it possible to prevent the fallback and load the specific revision?
UPDATE:
Thank you for the renewed interest. So we are using the "entity_translation module" and have extended this to include the preview functionality. This allows a page URL to be called with the node id and version id. These are both passed to node_load.
The node is then displayed via calls to $output = _revisioning_view($node); and finally drupal_deliver_page($output);
Comment: I think you'll need to provide some more information about how your preview page works to answer the problem. There's nothing in the `node_load()` or its function dependencies that restrict loading by the user role. Without clarity on how this preview page works, you can't get to the core of what you're asking.
Comment: It would help if you could share a bit more of your code.  Particularly whatever menu item you are using (or altering) to create this preview function.  Likely you'll need to come up with a custom route and permissions to by-pass the security system since Drupal's default behavior will be to prevent this behaviors just like this (since it opens unpublished content to non-authenticated users).
Comment: Are you by any chance using workbench moderation module?
Comment: I've added more notes. @googletorp no, we're not using the workbench moderation module.
Answer: If you are doing this by custom method try below code to get published revision id.
$query = db_select('node_revision','nr');
$query->join('node','n','n.nid=nr.nid');
$query->fields('nr',array('vid','status','nid'));
$query->condition('nr.status',1,'=');
$query->condition('nr.nid',$nid,'=');
$result = $query->orderby('vid','DESC')->range(0,1)->execute()->fetchAll();

Pass $nid in condition, here you will get the latest published revision ID.
Then load node as

entity_revision_load('node', $result->vid)

This will load particular revision id with content type.
Here you will get all node data related to that revision id.
Hope this helps.
Comment: The node already loads correctly with `node_load(node_id, version_id)`. The last call that our preview template makes is to `drupal_deliver_page($output)` where `$output` is created via a call to `_revisioning_view($node)`.
Comment: Is it possibe to change your output call to node_load(node_id, version_id) or with the above answer?
Comment: So change `$output = _revisioning_view($node)` to `$output = entity_revision_load('node', $result->vid)`. It still loads the node, but the wrong revision. I am thinking that something after `drupal_deliver_page` is rolling back to the published revision rather than the one I am after.

Display node with specific revision


pylint allow variable names that start / end with X_ / _X

Question: I am getting a pylint error, specifically C0103.
How can I allow any variable names that start with X_ (for example), or end with _X.
For example, I want lint to ignore names like train_X or y_test etc
Answer: Pylint does allow custom variable names via regular expressions, so you could use the following command to define your own pattern rule:
<code>pylint --variable-rgx='(?:X_)?[a-z_][a-z0-9_]*(?:_X)?' example.py
</code>
Comment: how can I implement this in .pylintrc? I put it in [MASTER] good_names_rgxs= '(?:X_)?[a-z_][a-z0-9_]*(?:_X)?' but still getting the same message


Question about tangent and slope

Question: Given the graph of $y=-e^{-x}$ and that there is a tangent to the graph that crosses the x axis at $(-4,0)$ determine the slope of that line.
So this seems like a simple question but I don't know why I'm racking my brain for this. I know I need to know the $(x,y)$ cordinate of where the line touches the graph, but I have no idea how to find it.
I do know that once I find the coordinates, I can simply differentiate $y=-e^{-x}$ and find the slope of the tangent line.
Comment: Well $y$ is never $0$, it just gets closer and closer to $0$. You can take a look at the graph, it never touches the $x$ axis: https://www.wolframalpha.com/input/?i=y+%3D+-e%5E-x
Comment: @DaneBouchie how would that help
Comment: That doesn't help because (-4,0) is the x-intersection of the $tangent$ line
Comment: I think there actually might be some ambiguity in whether the "that" in the problem statement is "the graph" or "a tangent."  I think the intended reading is the tangent.
Comment: Ah, so to answer your question... Just use the point-slope form, and use the derivative as the slope: $y-y_0 = m(x-x_0)$, then solve for $y$.
Answer: A point on the graph would look like $(x, -e^{-x})$. So the slope of the line passing through $(-4,0)$ and $(x, -e^{-x})$ would be
$$m=\frac{-e^{-x}}{x+4}$$
And we want this line to be tangent to $-e^{-x}$ at  $(x, -e^{-x})$ so we want $m = e^{-x}$. So we need to solve this:
$$e^{-x} =\frac{-e^{-x}}{x+4} $$
Hence $x+4 = -1$ or $x = -5$. And so the slope would be $e^{5}$.
Comment: Its $x+4$ not $x-4$
Comment: Thanks, I rewrote the -4 as a 4 and the typo carried through. I fixed it now.
Comment: no problem. Always happy to help :)
Answer: Let the point of tangency be $(a,e^{-a})$. Then the tangent line has slope $-e^{-a}$.
But the tangent line goes through $(a,e^{-a})$ and $(-4,0)$, so it has slope $\dfrac{e^{-a}-0}{a-(-4)}$.
Set the two expressions for slope equal to each other, and solve for $a$.
Answer: It sounds like you are comfortable with finding a tangent line given a point on the graph, so here is an idea:
The tangent line at $(a, f(a))$ will have the form (point-slope or one of those names)
$$y - f(a) = e^{-a}(x-a)$$
Can you find a value of $a$ so that this tangent line has the required intercept?
Comment: I originally thought of doing that like this:

$y-0=\left(\frac{d}{dx}-e^{-x}\right)(x+4)$
Comment: Two comments.  1: to be specific, on the right it is $\frac{d}{dx}(-e^{-x})$, the $(x+4)$ is excluded from the derivative of course.  2: On the left, $f(a)$ is still just $f(a)$, but $y$ is $0$ because the point on the tangent line is $(-4,0)$.
Comment: Gosh sorry I wrote so hastily.  It is important to keep the $a$ and the $x$ straight.  $a$ is the $x-$value where the tangent line is.. tangent.  $x$ is the value along the tangent line.  Therefore it is important as in my answer that the "slope" is $e^{-a}$ and the linear part is $(x+4)$  Does this help at all?
Answer: Let's call the slope of our line $m$.
We know that for some value of x,
$$f'(x) = e^{-x} = m$$
Expressing our line in point-slope form:
$$y-0 = m(x+4)$$
Substituting:
$$y= m(x+4)$$
$$y = e^{-x}(x+4)$$
Also, note that the point of tangency can be expressed as $(x, -e^{-x})$
Using this:
$$-e^{-x} = e^{-x}(x+4)$$
Solving for $x$, we get that $$x = -5$$
Therefore, the slope of our line is:
$$f'(-5) = e^5$$

Question about tangent and slope


How to return an async arrow function?

Question: I'm using React with Redux and have the following code:
hooks.js:
import { useDispatch } from 'react-redux';
import { checkCookieOne, checkCookieTwo } from './thunk';
...
export function useValidateCookieEffect() {
    const dispatch = useDispatch();
    React.useEffect(() => {
        dispatch(checkCookieOne());
        dispatch(checkCookieTwo());
    }, [dispatch]);
}

And in my thunk file:
export function checkCookieOne() {
    return async dispatch => {
        const hasCookie = Boolean(window.localStorage.getItem('cookieOne') || false);
        dispatch(store.actions.toggleCookieOneValue(hasCookie));
    };
}

export function checkCookieTwo() {
    return async dispatch => {
        const hasCookie = Boolean(window.localStorage.getItem('cookieTwo') || false);
        dispatch(store.actions.toggleCookieTwoValue(hasCookie));
    };
}

And to make it a bit more readable, I wanted to consolidate the code into single line returns.
So, from:
export function checkCookieOne() {
    return async dispatch => {
        const hasCookie = Boolean(window.localStorage.getItem('cookieOne') || false);
        dispatch(store.actions.toggleCookieOneValue(hasCookie));
    };
}

to something like this (my attempt) - bearing in mind that dispatch isn't declared in this file, it's only declared in hooks.js:
export async function checkCookieOne() => dispatch(store.actions.toggleCookieOneValue(checkGivenCookieExists('cookieOne')));

But that's invalid syntax. It complains about the arrow function, saying:

'{' or ';' expected.

How can I make this into a one line return?
export function checkCookieOne() { return async dispatch => dispatch(store.actions.toggleCookieOneValue(checkGivenCookieExists('cookieOne'))); }

This works but it's not exactly what I was looking for
Answer: Try this
let checkCookieOne = async () => dispatch(store.actions.toggleMyCookieValue(checkGivenCookieExists('cookieOne')));

export checkCookieOne;

// Or maybe...

export let checkCookieOne = async () => dispatch(store.actions.toggleMyCookieValue(checkGivenCookieExists('cookieOne')));

How to return an async arrow function?


Airflow to interact with BigQuery outside of the DAG not using BigQueryOperators

Question: I'm struggling to find a solution for the following problem on Airflow:
I have on BQ a table with a list of products (that is incremented on a regular basis). And each product has a differect project on BigQuery/GoogleCloud. Let's say:

PRODUCT | ID | PROJECT_ID | PARAM_1 | PARAM_2

My current pipe on Jenkins uses a for loop to build parallel DAGs for each product and works very well.
As I was translating to a Airflow DAG I was able to achieve the following:
<code>...
product_params = {
    'Product1': {
        'project_id': 'product-1',
        'color': 'Blue'
    },
    'Product2': {
        'project_id': 'product-2',
        'color': 'Red'
    },...
}

my_dag = DAG(
    'My_Default_DAG',
    schedule_interval='@once',
    default_args=default_args
    )

dag_tasks = {}

with firebase_dag as dag:
    for product_name, p_params in product_params.items():
        query_params = {
            'product_name': product_name,
            'product_project': product_params['project_id'],
            'color': product_params['color'],
            'event_date': '2019-12-01',
            'event_date_suffix': '20191201'
        }

        dag_tasks[game] = {}

        dag_tasks[game]['step_1'] = BigQueryOperator(
                task_id="{0}_step_1".format(product_name),
                bql='sql_folder/step-1.sql',
                use_legacy_sql=False,
                destination_dataset_table="{0}.prod_dataset.step1Table_{1}".format(product_params['project_id'], query_params['event_date_suffix']),
                write_disposition='WRITE_TRUNCATE',
                params=query_params
            )
       ### following steps...
</code>
Ideally I would like to query my product params directly on BigQuery. And I already have a developed python lib for that on a bitbucket, with a bunch of other methods that is extensively used by Jenkins.
Is there any way I could import that lib to airflow and use it in my dags?
Otherwise, is there any other way I could build methods that interacts with bigquery other than by BigQueryOperators?
Answer: Yes you can use your library in DAGs and use it with PythonOperator.
Comment: What is the best way to import my own libraries? I am using Cloud Composer.
Answer: You can install your own Python libraries in Composer from a private repository or from a local file.
It is advisable that you test your PyPI packages locally in an Airflow worker container before deploying to production, as custom packages might cause conflicts with dependencies that Airflow requires.
Comment: Nice @Javier Bóbeda. I will look into that. Thanks
Comment: Hi @Roghen! Did it worked out for you? Please mark it as correct solution if it did, in this way we can help people from the community in the future.


Iterando um string dentro do for

Question: Como o for consegue pegar a string de trás pra frente utilizando len com -1 -1 -1?
nome = 'felipe'
for c in range(len(nome)-1, -1, -1):
    print(nome[c], c)

Comment: Bem-vindo ao [pt.so]! Você colocou uma imagem do código e/ou mensagem de erro. Apesar de parecer uma boa ideia, não é! Um dos motivos é que se alguém quiser responder a pergunta, não pode copiar o código e alterar algo dentro. Clique no link [edit] e **coloque o código/erro como texto**. Veja mais sobre isso nesses links - [Manual de como NÃO fazer perguntas](https://pt.meta.stackoverflow.com/a/5485/3774), [Postar mensagem de erro como imagem](https://pt.meta.stackoverflow.com/q/7816/3774)
Answer: Basta ver a documentação de range. Mas basicamente, um range possui 3 valores:

valor inicial
valor final
passo

Sendo que o valor inicial é incluso e o final não (por exemplo, para um range com valor inicial 1, valor final 5 e passo 1, os valores que ele inclui seriam 1, 2, 3 e 4).
E para criar um range, você pode passar 1, 2 ou 3 parâmetros. Ex:

range(7): com apenas um parâmetro, este passa a ser o valor final. O valor inicial é setado para zero e o passo será 1. Portanto, este range abrange os valores 0, 1, 2, 3, 4, 5 e 6.
range(2, 7): com dois parâmetros, estes passam a ser o valor inicial e final. O passo é setado para 1. Portanto, este range abrange os valores 2, 3, 4, 5 e 6.
range(1, 7, 2): com três parâmetros, estes passam a ser o valor inicial, final e o passo. Portanto, este range abrange os valores 1, 3 e 5 (o passo define que os valores pulam de 2 em 2, e lembre-se que o valor final - o 7 - não é incluso).

Só que um range também pode estar em ordem decrescente, mas para isso o passo precisa ser negativo. Por exemplo, range(5, -1, -1) possui o valor inicial 5, valor final -1 e passo -1, por isso ele inclui os valores 5, 4, 3, 2, 1 e 0, nesta ordem.
No caso do seu código, o valor inicial é len(nome) - 1, ou seja, o tamanho da string nome (len(nome)) subtraído de 1 (portanto, 5). Ou seja, primeiro será pego o caractere da posição 5 (que é o último, já que a primeira posição é zero), depois da posição 4, e assim por diante.

Apenas para constar, também seria possível fazer o mesmo usando enumerate (para obter os elementos e seus respectivos índices) juntamente com reversed para inverter a ordem:
nome = 'felipe'
for indice, caractere in reversed(list(enumerate(nome))):
    print(caractere, indice)

Por fim, não deixe de ver também outras formas de inverter uma string.
Comment: @FelipeSoares `nome` é uma string com 6 caracteres, então `len(nome)` é 6, e portanto `len(nome) - 1` é 5. Então o range criado é `range(5, -1, -1)`, ou seja, vai de 5 até -1 (sendo que o -1 não é incluso, por isso ele para no zero), e o passo é -1, ou seja, ele percorre os valores 5, 4, 3, 2, 1 e 0, nesta ordem
Comment: Então quer dizer que o len(nome) - 1 sera o 5 ? e vai até o 0 porque o -1 não é incluido,  daí ele vai voltar uma casa com -1 ? eu também notei que o len(nome) conta como 6 então é por isso que coloca o -1 pra ficar 5 que na verdade esse 5 vai de 0 a 4?
Comment: Cara! eu acho que entendi, muito obrigado! você me ajudou bastante!
Answer: A função "len()" é um builtin do python ele retorna o tamanho  da string ( direto ao assunto vem internamente na linguagem)
>>> len("felipe")
6

Para manipular strings pode usar o slice usado para fatiar strings, listas, tuplas..
string = "python"

string[start,stop,step]
#start : inicia em uma dada posição
#stop : para em uma posição
#step : pule

###############

string[1:4]
p | y | t | h | o | n
0 | 1 | 2 | 3 | 4 | 5
string[1:4]
'yth'

#iniciei no indice 1 até a posição 4
#então cortei a string de acordo com a posição

string[0:6:1]
'python'

string[0:6:2] #iniciei na posição 0 até 6 e foi indicado que pule 2 em 2 posição
'pto'

para inverter basta seguir o inverso da posição:
string[::1]# nao foi adicionado o inicio nem onde deve parar mas o pula foi indicado 1 em 1
'python'
string[::-1]# negativo inverta
'nohtyp'

for indice in nome[::-1]:
  print(indice)

e
p
i
l
e
f

for indice in nome[::1]:
  print(indice)
f
e
l
i
p
e

Comment: Obrigado irmão!

Iterando um string dentro do for


how do I map this?

Question: I am sure I am stupid (which some arrogant clerk at my bank just explained to me) but I don´t get how to map this:
lets say I have a table tbl_products with a ID column
and a tbl_language with a ID column
and my problem: a tbl_product_texts without any id of its own but a product_id and a language_id (and a lot of texts in a couple of languages)
do I have to add a ID column to my table (which is ugly) or can nhibernate keep track of that in private somehow and is this kind of datamodel conceptually wrong or something?
Answer: If your trying what I think your trying then You set up a many-to-many mapping between tbl_Products and tbl_language. In the mapping just let nHibernate know which table serves as the link, nHibernate is clever enough to work it out.
https://www.hibernate.org/hib_docs/nhibernate/html/collections.html
So in the Products mapping (presuming you want a collection of Languages):
<bag name="nameOfLanguageCollection" table="tbl_product_texts">
  <key column="productID" /> <-- Name of ProductID col in tbl_product_texts
  <many-to-many class="LanguageClass" column="language_id" />  <-- name of languageid in   tbl_product_texts
</bag>

I think that's right. Can't check now.
Answer: Product has a one-to-many relationship with ProductText, so you would model Text as a collection on your Products class. You tbl_products_text should have a primary key. You don't state what database you're using but my approach would be to use a surrogate primary key (identifier) and a unique constraint on product_id, language_id. You do not need to take that step to get NHibernate working if you're not managing the texts in your application.
A first pass at your Product class would look like:
public class Product
{
    public IList<ProductText> ProductTexts { get; set; }
    public string GetTextForLanguage(int languageId) { ... }
}

Comment: thats what I did; added a primary key to the product_text table but it feels somewhat ugly since it is only there for nhibernate

how do I map this?


Samba username mapping not working as desired

Question: I have the following username mapping in Samba:
master = johndoe user2 user3
regular = user5 user6
restricted = johndoe user8 user9

By default, Samba will always map johndoe to the last entry in username.map, that is restricted.
Any idea how to map johndoe to multiple entries? I need this, because there are some shares where not all users have access, but some users (like johndoe) must have access.
Answer: You cannot map a user to multiple entries. Samba would take your user (johndoe) and match it to 'master' on the first line, but it wouldn't stop there, it would try the second line and then the third, where it would find 'johndoe' again and map it to 'restricted', this would replace the originally found 'master'.
You could use 'vfs_acl_xattr' and use 'setfacl' to set the permissions for users without the usermapping.


Modal Cadence Options

Question: I understand that when playing in a mode, the cadences are quite different from tonal cadences. For example, in the Phrygian mode a cadence would be IV - iii (or II - i if we're renumbering the chords).
Q: What are all of the cadence options for all of the major modes?
Comment: Possible duplicate of [Cadences for Modes](https://music.stackexchange.com/questions/42552/cadences-for-modes), which is your own question.  (I've never seen a user make a duplicate of his / her own question before)
Comment: https://music.meta.stackexchange.com/questions/3289/do-we-accept-duplicates-of-questions-that-are-posted-by-the-same-user
Answer: Our three major modes are Ionian, Lydian, and Mixolydian. The Roman numerals for these are:
<code>Ionian
I  ii  iii  IV  V  vi  vii°

Lydian
I  II  iii ♯iv° V  vi  vii

Mixolydian
I  ii  iii° IV  v  vi ♭VII
</code>
You'll notice that both Ionian and Lydian have a major V chord, meaning that the standard cadence of V–I is possible in these two major modes. (Whether it's the most common, I can't answer.) Perhaps due to Mixolydian's minor v chord, the ♭VII is often substituted as a dominant, resulting in a ♭VII–I cadence.
If we generalize it to all modes, it seems that the hierarchy of cadential harmony goes something like:

V where possible (Ionian, Lydian)
♭II where possible (Phrygian) (maybe there's something to be said about tritone substitutions here?)
♭VII where possible (Dorian, Mixolydian, Aeolian, sometimes Phrygian)

The only mode missing here is Locrian, which many (myself included) don't even consider an adequate mode based on the diminished tonic triad.
Comment: If someone is curious about Locrian harmony, this question goes into more detail about it: https://music.stackexchange.com/q/32420/7222
Comment: Yeah, I know. One thing we can do is point to answers like this when we can.
Comment: @Dom That answer looks like Patrx2...he is sorely missed!
Comment: Ah yes, the Inadequate Mode. It has so few possibilities, yet I just can't master it.
Comment: Thanks for the answer Richard. If that's the strategy, would chord subs for those cadential chords also be suitable? For example, ii for Dorian since the ii is a sub for VII since they share many notes? bvii for Phrygian? vii for Lydian? ii for Mixolydian? ii dim for Aeolian?
Comment: @AreelXocha Locrian has a lot of applications when it comes to certain pop genres today (trap, for example). The trap genres tends to use minor modes mainly, but the Locrian works as well.
Comment: I wonder if part of the preference is to have the penultimate chord always major? That is the case for `V`, `bII`, and `bVII`.
Comment: @Richard - In Locrian, we have a II major chord available.  We can write a II-i(omit 5th) cadence.  Or we can write a V-i(omit 5th), since Locrian also has a major V chord, although it is a tritone above the tonic and not P5.  Locrian's diatonic chords are i°, II, iii, iv, V, VI, and vii.
Comment: @MichaelCurtis - No.  He/she also said the ♭VII is Dorian, Aeolian, Mixolydian, and sometimes Phrygian.  This means we can write a vii-i in Phrygian mode.
Comment: Dom's link also gives us vii-i(omit 5th) in Locrian.  Which choice in Locrian seem the best: V-i(omit 5th), vii-i(omit 5th), or II-i(omit 5th)?

Modal Cadence Options


How to migrate from MySQL to PostgreSQL

Question: I need to know how to migrate my Drupal 6 database from MySQL to PostgreSQL. I also like to hear first hand experience tales about actual migrations.
P.S. I found this drupal-mysql2pgsql.pl migration script which apparently does the job but I could not make use of it due to the fact that I dont' know how to make " passwordless account in both databases". There is also this guide (in Thai) which adds credentials to database connection lines in the script. But it did not help either, as I could not connect to Postgresql. I know very little about Postgresql and may have had some silly mistake. Any through explanation/tutorial on this would be much appreciated.
Answer: Module DBTNG Migrator will do it.
Comment: The module is for Drupal 7.
Answer: If you're using Drupal 7, there's a sandbox project called Portable Databse Dump that purports to allow you to dump a Drupal site from one database backend to another.
Comment: Unfortunately I'm using Drupal 6.
Answer: I have an experience with both postgres and mysql sites under high load, and I don't think migration can be done for performance reasons. Both engines are good, and final success depends on ability of your DB admins to tune up DB installation for specific site.
Another point: to boost performance, you choose tools to minimize need in DB queries (boost/memcache/varnish), so you end up with relatively low weight of DB processing.
Answer: Check all of the modules that you use or ever may want to use on your site.  Not all contrib modules are database agnostic.  I can't think of any off the top of my head, but I have run into modules that use MySQL-only functions.
Comment: Do you think the effort to migrate to Postgresql worth at all?
Comment: I don't consider the risk of a module not working with PostgreSQL worth taking when working on projects for a client.
Comment: Assuming that all modules work in Postgresql, will you suggest the migration, performance-wise?
Comment: Because of this complication, we don't deploy it, so I don't have real-world metrics to compare to.

How to migrate from MySQL to PostgreSQL


Questions about split() and for each loops

Question: I am given a file that looks like this with many more lines that I am giving.
4
5 r begin
20 wr Dark tunnel

I have created a class to handle each part of the line that I am trying to split using the split() operation. To do this I am splitting based off of spaces, but for example in the 3rd line that says "Dark tunnel" I am splitting this apart as well, but need it to read as "Dark tunnel".
The other question that I have is with the for each loop, I want to perform the same operation on each line, except for the first line that is just the number 4, where I need to multiply that by itself minus 1 (4 * (4-1))
I created a class that takes the split line and assigns each part that is split. I have also made the for each loop, but as of now it performs the same operation on every line including the first one.
class point:
    def __init__(self, val, route, title):
        self.value = val
        self.route = route
        self.title = title

Want to properly split the lines, and perform a different operation on the first than the rest.
Comment: `str.split(None,3)` should avoid to split the last item
Answer: For split, you could do:
parts = s.split()
val, route, title = parts[0], parts[1], ' '.join(parts[2:])

For the for loop, you could do:
for index, line in enumerate(lines):
    if index == 0:
        result = int(line)*(int(line)-1)
    else:
        # do something else

All together:
for index, line in enumerate(lines):
    if index == 0:
        result = int(line)*(int(line)-1)
    else:
        parts = line.split()
        val, route, title = parts[0], parts[1], ' '.join(parts[2:])
        p = point(val, route, title)


How do I get decimals values without rounding them off

Question: How do I add two numbers and retain their decimal places in the final answer? Below is the code to do this but it does not work.
import re
cnt=0
s=0
l1= []
with open('C://Users/S/Documents/ok5.txt') as f:
    for i in f:
        if i.startswith('X-DSPAM-Confidence:'):
            x = re.findall('\d*?\.\d+',i)
            l1.append(x)
            cnt+=1

for i in range(0,len(l1)):
    j = float(i)
    s += j

print(l1)
print(s)

The output I get is:
[['0.5454'], ['0.5677']]
1.0

But, when I try the simple code below it gives the right answer:
a = 0.5454
b = 0.5677
c = float(a+b)
print(c)

The output for this is:
1.1131

Comment: `float(i)` is not the number you wanted to add.
Comment: Perhaps you meant `j = float(l1[i])`.  Or make for loop `for i in li:`
Answer: I think you want to do this instead:
import re
cnt=0
s=0
l1= []
with open('C://Users/S/Documents/ok5.txt') as f:
    for i in f:
        if i.startswith('X-DSPAM-Confidence:'):
            x = re.findall('\d*?\.\d+',i)
            l1.append(x)
            s += float(x[0]) # You could just add it here, which improves time complexity
            cnt+=1
print(l1)
print(s)


How to fix error caused by separating the angularjs code from the html code?

Question: I am setting up the app.js file in my angular application but i am getting n error in the console. I have all the files following the each other as recommended and icluded. How do i solve this error "

Error: "[$compile:tpload] http://errors.angularjs.org/1.6.9/$compile/tpload?p0=main.html&p1=404&p2=Not%20Found"?

Below is the code i am using.

<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap  /4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="content/css/main.css">

var app = angular.module('Travelapp', ["ngRoute"]);
app.config(function($routeProvider){
    $routeProvider
    .when("/",{
      templateUrl: "main.html",
      controller: "mainController"
    })
    .otherwise({
      template: "
Request error

Error in your request, Could not be handled
"
    });
});

app.controller("mainController", function($scope){
});

Comment: is the main.html exist?
Comment: Did you put (place) your `main.html` file and your **angular module (Travelapp)** file in the same folder ?
Comment: @MaksymPetrenko thanks for the answer it was being cused by missing main.html
Comment: Added it as answer
Answer: The error says that your main.html "Not Found".
The cause of it can be that this file does not  exist


$g(x)=x^2f(x)$ differentiable at $0$ given $|f(x)|\leq M$

Question: Let $|f(x)|\leq M$ for an $M>0$ and all $x\in \mathbb{R}$. Let $g(x)=x^2f(x)$ for all $x\in \mathbb{R}$. I need to show that $g$ is differentiable at $0$.
With the definition of differentiability I got $\lim_{h \to 0} \frac{g(0+h)-g(0)}{h}$ = $\lim_{h \to 0} \frac{h^2f(h)}{h}$ = $\lim_{h \to 0} hf(h)$.
I also know that $f(h)$ is bounded by $M$, so as $h$ goes to $0$, $hf(h)$ also goes to 0. (Correct?)
I do however not know if $f(h)$ is continous or differentiable, is this a prerequisite?
Comment: "I do however not know if f(h) is continous or differentiable, is this a prerequisite?" ---- No, it's enough, that $f$ is bounded. The limit exists then independtly of other properties of $f$.
Comment: $hf(h)$ is bounded by $|h|\cdot |f(h)|\leq M|h|$, so you can conclude what?
Answer: This looks fine to me. And no, we don't need any more niceness conditions on $f$. Boundedness is enough. Any function squeezed between $Mx^2$ and $-Mx^2$ (which is what $g(x)$ is), no matter how discontinuous it otherwise is, will be differentiable at $x = 0$. That is what you have proven, after all.
If you really want a nit-pick, you could be a bit more explicit about how $f$ being bounded by $M$ implies that $hf(h)\to 0$. Whether that's actually necessary (and if so, in how much detail), depends on your teacher / professor / TA, since deciding whether you've demonstrated the skill you need to demonstrate on tests and assignments is ultimately up to them.
Comment: To give you a small idea: if _I_ were correcting this on a test that I had administered, and it were a 5-point exercise, I might've deducted half a point, or I might not, depending on how I feel, and on whether all other students glossed over it like you did (at which point it's my teaching which should get point deductions instead). But you'd definitely get full score if this were a 2-point exercise.


IIS7 Error 500 - Out of Ideas

Question: I'm getting a 500.19 error in IIS7 for a site I've set up locally. I've given IIS_IUSRS and even Everyone full control on the directory and reinstalled ASP.NET in IIS. I can't request any files - images etc, and I've spent so long looking for solutions and I'm not sure what else to try.
Comment: What is full error when you view the site on the server? (Or with remote errors disabled)
Comment: What does the eventviewer log?
Answer: That error does not necessarily have anything to do with permissions. Have you viewed the details of the error?
Here's some info that should help: 500.19 is usually related to configuration errors.
http://blogs.iis.net/webtopics/archive/2010/03/08/troubleshooting-http-500-19-errors-in-iis-7.aspx
Comment: Thanks, but there's nothing there I haven't tried.

IIS7 Error 500 - Out of Ideas


To find a limit involving integral

Question: How to find the following limit : $\lim _{x \to \infty} \dfrac 1 x \int_0^x \dfrac {dt}{1+x^2 \cos^2 t}$ ? I am not even sure whether the limit exists or not .  I tried applying L'Hospital , but then in the numerator we have differentiation under integration, and the derivative comes out to be lot messier than the original integral. Please help . Thanks in advance
Comment: https://en.wikipedia.org/wiki/Leibniz_integral_rule
Answer: Let
$$F(x)=\frac {1}{x} \int_0^x \dfrac {dt}{1+x^2 \cos^2 t}$$
Then for $n\in\mathbb{Z}$, since $\cos^2(t)$ is $\pi$-periodic,
\begin{align*}
F(n\pi)
&=
\frac {1}{n\pi} \sum_{k=0}^{n-1}\int_{k\pi}^{(k+1)\pi} \dfrac {dt}{1+(n\pi)^2 \cos^2 t}\\
&=\frac {1}{n\pi} \sum_{k=0}^{n-1}\int_{0}^{\pi} \dfrac {dt}{1+(n\pi)^2 \cos^2 t}
=\frac {1}{\pi} \int_{0}^{\pi} \dfrac {dt}{1+(n\pi)^2 \cos^2 t}\\
&=\frac{1}{\sqrt{1+n^2\pi^2}}.
\end{align*}
which goes to zero as $n\to +\infty$.
Note that if $0<n\pi\leq x< (n+1)\pi$ then
$$0\leq F(x)\leq \frac {1}{n\pi} \int_0^{(n+1)\pi} \dfrac {dt}{1+(n\pi)^2 \cos^2 t}=F(n\pi)+\frac {1}{n\pi} \int_{0}^{\pi} \dfrac {dt}{1+(n\pi)^2 \cos^2 t}.$$
Can you take it from here?
Comment: @RobertZ :  Ok , but then you are evaluating the limit on the particular sequence $x_n = n\pi \to \infty $ ... the required limit would be equal to the limit evaluated on this sequence if we already knew the limit exists ... how do you ensure that the limit exists ?
Comment: @misao See my edited answer again.
Comment: @Robert Z : $\int \dfrac {dt }{1+x^2\cos^2 t}= \dfrac {arctan (\dfrac{\tan t}{\sqrt{x^2+1}})}{\sqrt{x^2+1}}$ + constant ... right  ( Found from Wolfram Alpha ) ? Then shouldn't your $F(n\pi)$ be $0$ ?
Comment: @Robert Z : So $F(x)$ is an increasing function ?
Comment: @misao No, I am not saying that $F$ is increasing (see $(n+1)\pi$ in the upper limit of the integral.
Comment: @Robert Z : ah so only $xF(x)$ is increasing .. that much you are assuming .. but your evaluation of the integral in $F(n\pi)$ is definitely wrong ..
Comment: @misao Let $F(x,y,z)=\frac {1}{x} \int_0^y \dfrac {dt}{1+z^2 \cos^2 t}$ it is clear that since the integrand is positive $F$ is decreasing in $x$ and $z$ and increasing in $y$. Do you agree?
Comment: @Robert Z : you seem to forget that here $x=y=z$ so they are not independent variable ..
Comment: @misao $F(x)>0$ for $x>0$. You are integrating a positive function!  How can it be zero?
Comment: @Robert Z : ah uh , that's true .. a positive continuous function, that makes sense ... then could you please take a look at https://www.wolframalpha.com/input/?i=integration+dt%2F1%2Ba%5E2cos%5E2+t .. and could you tell me how you are evaluating the integral ?
Comment: @misao Let $H(x,y,z)=\frac {1}{x} \int_0^y \dfrac {dt}{1+z^2 \cos^2 t}$ it is clear that since the integrand is positive $H$ is decreasing in $x$ and $z$ and increasing in $y$. Now for $0<n\pi\leq x< (n+1)\pi$,
$$F(x)=H(x,x,x)\leq H(n\pi,x,x)\leq H(n\pi,x,n\pi)\leq H(n\pi,(n+1)\pi,n\pi).$$
Comment: @misao : Wolfram is correct. But the that formula has a problem at $\pi/2$ (which is inside the interval). By symmetry you can take 2 times the integral along $(0,\pi/2)$.
Comment: @Robert Z : Thanks , I got it all
Comment: @misao Well done!
Answer: $$\forall x > 0, \exists n \in \mathbb{N}\ s.t. \ x \in ]2n\pi, 2(n+1)\pi]$$
$$ 0 \leq \frac{1}{x}\int_0^x\frac{dt}{1+x^2\cos^2(t)}  \leq \frac{1}{2n\pi}\int_0^{2(n+1)\pi}\frac{dt}{1+(2n\pi)^2\cos^2(t)}$$
$$ \leq \frac{1}{2n\pi}\sum_{k=0}^n\int_0^{2(k+1)\pi}\frac{dt}{1+(2n\pi)^2\cos^2(t)}$$
$$ \leq \frac{1}{2n\pi}\sum_{k=0}^n\int_0^{2\pi}\frac{dt}{1+(2n\pi)^2\cos^2(t)}$$
$$ \leq \frac{1}{2n\pi}\sum_{k=0}^n4\int_0^{\pi/2}\frac{dt}{1+(2n\pi)^2\cos^2(t)}$$
$$ \leq \frac{2(n+1)}{n\pi}\int_0^{\pi/2}\frac{dt}{1+(2n\pi)^2\cos^2(t)}$$
$$ \leq \frac{2(n+1)}{n\pi}\int_0^{1}\frac{dt}{1+(2n\pi)^2t^2}$$
$$ \leq \frac{2(n+1)}{n\pi}\frac{\pi}{4n\pi} \to 0$$

To find a limit involving integral


MediaRecorder.pause() in android

Question: the pause method added to MediaRecorder in api 24
is there any way to use this in a older api?
here is android studio suggest
but i want use it in older devices
Answer: Simple answer for your question is NO YOU CAN'T
Once you are recording the only possible actions are stop and reset.
So try to save your Call to SDCard after you Stop , and then again start Fresh Record and Stop it. Finally Combine both Audio File into one Audio file.
Record the audio as .wav file and Combine using this way.
Answer: On older platforms there is no MediaRecorder.pause(). The only option is to record few separate files and then concatenate it by yourself with any available library (e.g. try FFmpeg-based). But note that there may be roughness due recorder may insert empty frames at the begin / end of files and concatenated media may contain artifacts like blinking, cracks so on.
Answer: Check out this library.
I have personally used this to add pause and resume functionalities to my android app. It supports all API levels.
Comment: Try to explain what you are suggesting and how to use that. https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers

MediaRecorder.pause() in android


Update a record or insert if it doesn't exists, with locking

Question: I would like to update a record if exists. Thats the easiest part, but that record may not exist, so let's create it first. Pseudocode:
UPDATE x SET y=1 WHERE id=5

if the result of it is 0, then...
a, LOCK TABLE x
b, INSERT INTO...
c, UNLOCK TABLE x

But I cant find a concrete tutorial. I suppose the step A must be "true" if locking was successfull, and "false" if already locked. But its always true, in case of simultenaously running.
(Ps: I know there are replace into and those kind of operations, but this time this is just what I need)
Comment: Use `INSERT INTO ... ON DUPLICATE KEY UPDATE ...`. This is automatically in a transaction so you don't need locking.
Comment: Don't use `LOCK TABLE`, use a transaction.
Answer: Ideally you should use a transaction or INSERT INTO ... ON DUPLICAGTE UPDATE ....
But if you really have to use locking, you have to put both UPDATE and INSERT within the locked region.
LOCK TABLE x;
UPDATE x SET y = 1 WHERE id = 5;
IF FOUND_ROWS() = 0
THEN
    INSERT INTO x (id, y) VALUES (5, 1);
END IF
UNLOCK TABLE x;

Comment: Don't encourage `LOCK TABLE`.  Do encourage (as you did in a Comment) the use of IODKU.
Comment: I've added the recommendation to the answer.


Showing "New content" form on main theme

Question: I'm using drupal 8
I have a page with diferent content types like "beers, wines, etc". I want to let users publish their own content inside this content types, but I want a form in the main theme, no administration theme. How can I do it?
Comment: I believe this is as easy as not allowing that role the permission to use the administration theme.
Answer: In Drupal 8 there is the entityform_block module which gives you the option to display an entity form as a block.
You just need to go to Blocks, select Place block in the region you want and select Entity form.
When you add your from you can select Entity Type + Bundle, where you have to select your content type and also in which pages you what this block being visible.
Keep in mind that using this way, on submit the user will be redirected to the content page but you can write your custom handler using hook_form_alter.
Comment: Hey Ismini, thanks for your answer. I think this is what I need, but I don't find this block type in the list... I am searching for "Entity" and nothing appears... Maybe I need some module to find it?
Comment: Oops yes. you are right! I changed the answer!


Adding a button (UIButton) to a custom tableview cell drawn with drawRect:

Question: I am currently working a on project where I have lots of custom table view cells. Part of the requirements is that the cells be able to expand if their default size can not hold all of the content. If they need to be able to expand I have to add a UIButton to the cell and when it is tapped redraw it in a bigger view where all the data fits. Currently in draw rect I essentially do this:
<code>if([self needsExpansion]) {
    [self addExpansionButton];
}

-(void)addExpansionButton {

    self.accessoryButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.accessoryButton setShowsTouchWhenHighlighted:YES];
UIImage *buttonImage = [UIImage imageNamed:@"blue_arrow_collaps_icon.png"];
[self.accessoryButton setFrame:CGRectMake(280, 82, buttonImage.size.width, buttonImage.size.height)];
[self.accessoryButton setImage:buttonImage forState:UIControlStateNormal];
[self.accessoryButton addTarget:self action:@selector(toggleExpanded) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.accessoryButton];
}
</code>
This works fine, except for when I click anywhere else in the cell the button flickers and disappears. Anyone know how to propertly do this?
Answer: From the UITableViewCell Class Reference:

You have two ways of extending the
  standard UITableViewCell object beyond
  the given styles. To create cells with
  multiple, variously formatted and
  sized strings and images for content,
  you can get the cell's content view
  (through its contentView property) and
  add subviews to it.

Instead of adding the accessory button as a subview of the UITableViewCell, you should add it as a subview of the contentView:
<code>[[self contentView] addSubview:self.accessoryButton];
</code>
Have you worked out the following problem in your design approach?: Let's say one of your cells (let's call it A) determines it needs expansion, so you add a button to it. What happens when the user scrolls through the UITableView? For performance reasons, your UITableView delegate should be using dequeueReusableCellWithIdentifier in tableView:cellForRowAtIndexPath:. So you'll be reusing A to display a different row of the table. Do you really want A to have an accessory button? Probably not, since it's now representing a different object.
You're probably better off doing the cell customization at the UITextViewDelegate. In tableView:cellForRowAtIndexPath:, you can determine if the object being displayed at the row specified needs a button, and if it does add it as a subview to the contentView.
Then again, if your table size is always relatively small (say < 50), you can use this approach Jeremy Hunt Schoenherr suggests.