Fazer com que getopt ignore primeiro argumento

Question: Estou criando um PHP CLI, e queria rodar mais ou menos assim
php console.php comando -a foo -b bar -d

Porém com a função getopt não consigo passar o comando se não a função buga e não recebo nenhum dos outros argumentos. Preciso setar um parâmetro padrão como -c:
php console.php -c comando -a foo -b bar -d

Alguém sabe algum método para "parsear" os argumentos ignorando o primeiro?
PS: Também preciso pegar o primeiro argumento, pra saber qual comando deve ser executado.
Código: (github link)
public function run() {

  $command = $this->getCommand();

  if (is_null($command)) return FALSE;
  $optcll = $command->getOptionCollection();
  $opts = $optcll->dump();

  // LINHA QUE PEGO OS ARGUMENTOS DO COMANDO
  $args = getopt($opts['options'], $opts['longopts']);

  return $command->execute($this, $args);

}

Comment: Qual é o código e `console.php`?
Comment: Aquilo ali é só exemplo, é a instanciação de uma classe que executa o código de outras classes e etc... O problema é a função `getopt` que estou usando pra pegar os parâmetros passados. https://github.com/KaduAmaral/CMP/blob/master/CMP/Console.php#L37
Comment: O código está público no repositório: https://github.com/KaduAmaral/CMP
Comment: A solução precisa ser necessariamente utilizando `getopt`?
Comment: Veja se neste post algo é aproveitável: https://stackoverflow.com/a/34536611/1377664
Comment: Não muito, preciso de um _workaround_ pro PHP. Sei que o console do Symfony faz algo parecido com o que quero... Mas valeu pelo link @Dvdsamm
Answer: Não sei se satisfaz suas necessidades, mas existe a biblioteca docopt para PHP.
Com ela, basta você escrever a documentação dos seus comandos que a biblioteca se encarrega de tratar as entradas, entregando a você um objeto com as informações fornecidas pelo usuário. Por exemplo, considerando o seu exemplo, poderíamos fazer:
<?php

$doc = <<<DOC
Descrição da aplicação.

Usage:
  console.php comando [-a A] [-b B] [-d]
  console.php (-h | --help)
  console.php --version

Options:
  -h --help     Exibe a mensagem de ajuda.
  --version     Exibe a versão.
  -a A          Valor de A.
  -b B          Valor de B.
  -d            Define como D.
DOC;

require('vendor/autoload.php');

$args = Docopt::handle($doc, array('version'=>'0.1.0'));

foreach ($args as $k => $v)
{
    echo $k.': '.json_encode($v).PHP_EOL;
}

Assim, pode-se exibir a mensagem de ajuda com o comando:
$ php console.php -h

Descrição da aplicação.

Usage:
  console.php comando [-a A] [-b B] [-d]
  console.php (-h | --help)
  console.php --version

Options:
  -h --help     Exibe a mensagem de ajuda.
  --version     Exibe a versão.
  -a A          Valor de A.
  -b B          Valor de B.
  -d            Define como D.

Exibir a versão com o comando:
$ php console.php --version

0.1.0

Ou executar os comandos previstos em Usage:
$ php console.php comando

comando: true
-a: null
-b: null
-d: false
--help: false
--version: false

Como defini as opções como opcionais e não os informei, ficaram definidos como null aqueles que possuem valor, como -a e -b, e como false os que são flags, como -d. Ao informar os valores, fica:
$ php console.php comando -a foo -b bar -d

comando: true
-a: "foo"
-b: "bar"
-d: true
--help: false
--version: false

Comment: Ainda estou estudando como se usa a função `getopt` para dizer se é possível fazer da maneira que tentou e como fazer. Atualizo a resposta assim que for possível.
Comment: Show de bola, pelo visto vai me atender perfeitamente, precisarei fazer alguns ajustes no código, mas assim que testar aviso...
Comment: Implementei aqui, ficou perfeito, valeu!


Improper integral: why $\int_0^1(x^2+ x^{1/3})^{-1}\,dx$ is convergent and not $\int \frac{1}{x^2}\,dx$ ???

Question: How do I show that $\int_0^1(x^2+ x^{1/3})^{-1}\,dx$ converges? I assume you show it on $(0,1]$. Can't seem to get my head around why this would be true.
Comment: For positive $x$ we have $\frac{1}{x^2+x^{1/3}}\lt \frac{1}{x^{1/3}}$, and $\frac{1}{x^{1/3}}$ blows up "slowly" as $x$ approaches $0$ from the right.
Comment: I understand now, thanks a lot!
Comment: You are welcome.
Answer: For positive $x$ we have $\frac{1}{x^2+x^{1/3}}\lt \frac{1}{x^{1/3}}$, and $\frac{1}{x^{1/3}}$ blows up "slowly" as $x$ approaches $0$ from the right.
More formally, we show that the improper integral
$$\int_0^1 \frac{dx}{x^{1/3}}$$
converges, by calculating
$$\lim_{x\to 0^+}\int_0^1\frac{dx}{x^{1/3}}.$$
The integral is equal to $\frac{3}{2}(1-\epsilon^{2/3})$, and approaches $\frac{3}{2}$ as $\epsilon$ approaches $0$ from the right.
It follows by Comparison that $\int_0^1 \frac{dx}{x^2+x^{1/3}}$ converges.
As to $\int_0^1 \frac{dx}{x^2}$, we calculate $\int_\epsilon^1 \frac{dx}{x^2}$. The integral is $\frac{1}{\epsilon}-1$, and blows up as $\epsilon$ approaches $0$ from the right.


Identify which button was pressed from HTML in WSGI-Python (without any framework like flask and Django)?

Question: I  am implementing web-application in core python using WSGI, python3, and apache2. Now I need to detect which button was pressed based on some value or id of a button in python WSGI file
Please suggest the code which I can place in the WSGI file.
Python Code:
def application(environ, start_response):
    if environ['REQUEST_METHOD'] == 'POST':
    post_env = environ.copy()
    post_env['QUERY_STRING'] = ''
    post = cgi.FieldStorage(fp=environ['wsgi.input'],
        environ=post_env,
        keep_blank_values=True
    )
    html =  page_header + content + page_footer
    start_response('200 OK', [('Content-Type', 'text/html')])
return [html.encode('utf-8')]

HTML CODE:

    <form method="post">
        <button id="button1">Button1</button>
        <input type="text"></input> Status
        <button id="button2">Button2</button>
        <input type="text"></input> Status2
    </form>

I expected the code something life
if "button1":
    "Some code"
if "button2":
    "some code"
Answer: I have used AJAX to send data from HTML to WSGI
HTML CODE:
$.ajax(
{
    type: "POST",
    url: "https://link/sample/",
    data: {'param1':"Generate",'param2':htmlTDES},
    success: function (html)
    {alert("AJAX PASS");},
    error: function(request, ajaxOptions, thrownError)
    {
        alert(thrownError);
    }
});

WSGI CODE:
if environ['REQUEST_METHOD'] == 'POST':
    post_env = environ.copy()
    post_env['QUERY_STRING'] = ''
    post = cgi.FieldStorage(
        fp=environ['wsgi.input'],
        environ=post_env,
        keep_blank_values=True
    )
    name = post.getvalue('param1')
    htmlTDES = post.getvalue('param2')
    if name=="Generate":
        Genrate_function()
    html =  page_header + content + page_footer
    start_response('200 OK', [('Content-Type', 'text/html')]
return [output.encode('utf-8')]


How to React Context api typescript setting?

Question: I am changing the app.js file to app.tsx.
Currently, the value has the following error.
app.tsx

import React, { createContext, useState } from "react";
import SelectPage from "./pages/select/select";
import ResultPage from "./pages/result/result";
import { Route, Routes } from "react-router-dom";

export const GlobalContext = createContext(null);

function App() {
  const [checkCrypto, setCheckCrypto] = useState([]);
  const [start, setStart] = useState(false);

  const value = {
    checkCrypto,
    setCheckCrypto,
    start,
    setStart,
  };

  return (
    <>
      <GlobalContext.Provider value={value}>
        <Routes>
          <Route path="/" element={<SelectPage />} />
          <Route path="/result" element={<ResultPage />} />
        </Routes>
      </GlobalContext.Provider>
    </>
  );
}

export default App;

As I changed it like the code below, it was solved, but I want to find another way.
export const GlobalContext:any = createContext(null);

What type should I apply to solve the problem?
Comment: https://github.com/typescript-cheatsheets/react#context
Answer: I solved it like this.
interface AppContextInterface {
  checkCrypto: number[];
  start: boolean;
}

export const GlobalContext = createContext<AppContextInterface | null>(null);

function App() {
  const [checkCrypto, setCheckCrypto] = useState([]);
  const [start, setStart] = useState(false);

  const value = {
    checkCrypto,
    setCheckCrypto,
    start,
    setStart,
  };

  return (
    <>
      <GlobalContext.Provider value={value}>
        <Routes>
          <Route path="/" element={<SelectPage />} />
          <Route path="/result" element={<ResultPage />} />
        </Routes>
      </GlobalContext.Provider>
    </>
  );
}

export default App;

Answer: Based on the code you've shown, this should work.
If you visit the TypeScript playground link and hover over value on line 14, you can see the type that you need to use as the generic for createContext.
TS Playground
export const GlobalContext = createContext<{
  checkCrypto: number[];
  setCheckCrypto: React.Dispatch<React.SetStateAction<number[]>>;
  start: boolean;
  setStart: React.Dispatch<React.SetStateAction<boolean>>;
}>(undefined as any);

function App() {
  const [checkCrypto, setCheckCrypto] = useState<number[]>([]);
  const [start, setStart] = useState(false);

  const value = {
    checkCrypto,
    setCheckCrypto,
    start,
    setStart,
  };

// ...


Um único ArrayObject para apresentação e alteração

Question: Olá, estou me aventurando em Angular 8, e me deparei com um impasse, eu obtenho o seguinte obj array de um serviço:
this.productsService.getProducts().subscribe(
      (products: Product[]) => {
         this.productsToShow = products;
         this.productsToEdit = products;
         // ja tentei fazer = [...products], etc
      });

e sempre que eu edito o formulário do objeto productsToEdit, automaticamente a grid de exibição é modificada, na grid existe um ngfor e sendo exibido da maneira convencional {{ element.atributo }}, existe algum jeito de "congelar" a exibição?
Comment: Não ficou nada clara sua pergunta!
Answer: O problema parece ser que vc ta esta copiando a mesma referencia, tenta assim:
this.productsToShow = {...products};
this.productsToEdit =Object.assign({}, products);

Ou pra ter totalmente outro objeto:
 this.productsToShow =JSON.parse(JSON.stringify(products));

Comment: era exatamente isso, estava pesquisando como o javascript funciona, e aprendo cada dia mais com ela, obrigado


I can't delete or hide Displaying all results in woocomerce

Question: Adding to CSS did nothing, adding snippets from php below also.
<code>CSS:
.woocommerce-result-count {
display: none;
}```

Snippets:
```removeaction ('woocommercebeforeshoploop', 'woocommerceresultcount', 20);```
</code>
Answer: Override woocommerce default styling like so:
<code>.archive .woocommerce-result-count {
    display: none !important;
}
</code>


Chained string replace in .NET

Question: Given: a base64 string
When: Foo is called
Then: Foo returns the input string with the following character replacements ('A' => '_', 'B' => '-', 'C' => '+') and does it as fast as possible
I compared several algorithms to determine which version of Foo is faster. The results point towards plain-old string.Replace, which is quite surprising. I would have expected the Regex to take an initial hit for compiling, but then blaze through and outperform string.Replace which creates three copies of the string per invocation of Foo.
I'd like to check if anybody else can confirm these findings or come up with an explanation of why the winner outperformed the rest.
I ran Foo 100k times with these algorithms and the result is the TimeSpan, measured with StopWatch on a debug build, after finishing execution:
00:00:00.0500790 <=== string.Replace [1]
00:00:00.0699696 <=== StringBuilder.Append [2]
00:00:00.0988960 <=== StringBuilder.Replace [3]
00:00:00.7440135 <=== Regex [4]

[1]:
Foo(string input)
{
  return input.Replace("A", "_").Replace("B", "-").Replace("C", "+");
}

[2]:
Foo(string input)
{
    var sb = new StringBuilder(input.Length);
    foreach (var x in input)
    {
        if (x == 'A')
        {
            sb.Append('_');
        }
        else if (x == 'B')
        {
            sb.Append('-');
        }
        else if (x == 'C')
        {
            sb.Append('+');
        }
        else
        {
            sb.Append(x);
        }
    }
    return sb.ToString();
}

[3]:
Foo(string input)
{
  return new StringBuilder(input, input.Length).Replace("A", "_").Replace("B", "-").Replace("C", "+").ToString()
}

[4]:
static readonly Regex charsRegex = new Regex(@"[ABC]", RegexOptions.Compiled);
Foo(string input)
{
  charsRegex.Replace(input, delegate (Match m)
    {
        var value = m.Value;
        if (value == "A")
        {
            return "_";
        }
        else if (value == "B")
        {
            return "-";
        }
        else if (value == "C")
        {
            return "+";
        }

        return value;
    });
}

Comment: Also, is this compiled with, or without debugging information and optimization? I would expect the chained replace to be optimized by the compiler to do it in place since there are no intermediate variables. So while you get a new string returned, it doesn't necessarily create a string, replace all of one, return new string, replace all of another... but only an ILDump could tell
Comment: StringBuilder will be faster than string.Replace if you replace more characters. Also, the new Roslyn compiler in Visual Studio 2015 can optimize the executable much better than the JIT compilation.
Comment: Note that your Regex code specified IgnoreCase, while the other solutions don't. Have you tried the regex without it? Or alternate, tried the others case-insensitively (which might require x2 the calls)
Comment: Yeah, that's actually not supposed to be there. Edited
Comment: So the timings are for code *without* the IgnoreCase? Could you verify that the other snippets match the ones that you timed? It might send people guessing in the wrong direction.
Comment: Also, how did you time? Were you using `StopWatch`?
Answer: I would like to suggest another implementations.
public /*unsafe*/ static string Foo(string text)
{
    char[] a = text.ToCharArray();
    for(int i = 0; i < a.Length; i++)
        switch(a[i])
        {
        case 'A': a[i] = '_'; break;
        case 'B': a[i] = '-'; break;
        case 'C': a[i] = '+'; break;
        }
    return new string(a);
}

OR
public /*unsafe*/ static string Foo(string text)
{
    char[] a = new char[text.Length];
    for(int i = 0; i < text.Length; i++)
    {
        char c=text[i];
        switch(c)
        {
        case 'A': a[i] = '_'; break;
        case 'B': a[i] = '-'; break;
        case 'C': a[i] = '+'; break;
        default: a[i] = c; break;
        }
    }
    return new string(a);
}

If you allow unsafe code and uncomment unsafe, this could be even faster then [1].
[1] wins because it's all native, although 3 loops though the data
[2] many index checks and current index increases
[3] multiple loops thru the same data, many index checks, but inplace replacement possible)
[4] last, because overhead of the state-machine, and calling the replacement method. Plus string compares, but not char compares.
Comment: The switch statement can be simplified to `if ( a[i] <= 'C' && a[i] >= 'A' ) a[i] = "_-+"[a[i] - 'A'];` because the switch statement will most likely be compiled to if else blocks for such small number of cases.
Answer: It seems to me that the regex is simply far more complicated.
String.Replace calls directly into Win32 and probably does a pointer based string manipulation preventing fragmentation etc. (difficult to be sure - but it doesnt do this in managed code). If I fire up ILSpy I see that RegEx.Replace does a lot of bounds checking, then does a Match, then uses StringBuilder to carry out the results of the call to your delegate.
Answer: If we check the implementation for the methods you specify, we'll end up with nothing surprising.
Regex.Replace includes pattern matching and a lot of string concatenations which results in an overhead. While the plain old String.Replace use C++ implementation directly(comstring.cpp file) which is low-level and most probably  very optimized.
Answer: Yeah I was surprised by what You found as well... Not that Regex is the slowest, that was expected... but that chained String.Replaceperformed as well as StringBuilder.
I did some checking of my own I compared same [1] as you did but I modified [2] to get it as close to bare bone implementation as I could O(n).
[1]
    static string Foo(string input)
    {
        string result = input.Replace("A", "_");
        result = result.Replace("B", "-");
        result = result.Replace("C", "+");
        return result;
    }

[2]
    static string Foo2(string input)
    {
        var length = input.Length;
        var sb = new char[length];
        for (int i = 0; i < length; i++)
        {
            switch (input[i])
            {
                case 'A':
                    sb[i] = '_';
                    break;
                case 'B':
                    sb[i] = '-';
                    break;
                case 'C':
                    sb[i] = '+';
                    break;
                default:
                    sb[i] = input[i];
                    break;
            }
        }
        return sb.ToString();
    }

My test string is of above 7 million characters in length (7230872, Lorem Ipsum).
So we can notice several points:

Execution of these two methods is extremely fast (55ms vs 51ms aprox) As such activity of other processes and CPU availability play significant role in end result. I executed these two methods 100 times and summed all execution times and got aprox 5500ms for Foo vs 5100 for Foo2.
Foo method goes through whole string at the least 3 times (maybe more, not sure). Foo2 method on the other hand looks like it is only going through string once... But that is not true... it goes through it at the least twice... input.Length goes through it as well (to count number of characters). Thanks PhillipH
As you try replacing more and more characters difference between Foo and Foo2 becomes more apparent. With 15 char replacements Foo executes in aprox 240ms and Foo2 in about 60ms.

So... In conclusion... No magic here, it just executes extremely fast... :)
Comment: String.Length does not iterate over the string. Other languages use a null terminator which does require iteration, but nulls embedded in a .net string are valid characters, so the length is not found via iteration to a terminator. See http://stackoverflow.com/questions/717801/is-string-length-in-c-sharp-net-instant-variable for a discussion of this. Becasue strings are immutable, once created, their length cannot be changed so it does not need to be dynamically calculated.

Chained string replace in .NET


WPF - Como criar um mecanismo para disponibilizar a aplicação para teste durante x dias?

Question: bom dia
Estou criando uma aplicação em WCF e gostaria de ajuda ou direcionamento no seguinte ponto:
Preciso disponibilizar a aplicação para qualquer um baixar e testar a mesma, tipo um teste durante 30 dias e depois restringir o acesso.
Como posso criar um mecanismo destes em WPF ?
Agradeço desde já a atenção e ajuda de todos.
Answer: Acho que você precisaria do seguinte:

Salvar a data de instalação (Seja em um localDB ou no registro)
Identificar a data atual

Se você for fazer por data, você deverá se preocupar muito com relação a restrição, pois se o usuário mudar a data pode dar problema, e se você pegar a data de um WebService você obrigará que o usuário esteja conectado.
Fiz uma coisa semelhante um tempo atrás, porém não me preocupei muito em relação ao controle de data, fiz o seguinte:
O usuário poderá utilizar durante 30 dias ou X Utilizações (inicializações).
Ao iniciar o sistema, verifico se já passou a data, caso não tenha passado verifico se já passou as utilizações. Salvo as utilizações em um contador em um localDB junto com as informações do app.
Esta foi a melhor maneira, e a mais rápida que eu encontrei para fazer algo semelhante ao que você está querendo.


How to fill missing json keys with key and null value?

Question: For example, I`m doing a ETL with json file, and sometimes some jsons keys don't come with this file, so I need to fill the missing key and value with the missing key and null as the value.
This is a example of json file:
"data" :{
"data_info" :{
"version" :value ,
"data_name" : value ,
"data_number" : value ,
"package_name" : value
}

Here is the scenario where the missing fields came:
"data" :{
"data_info" :{
"data_name" : value ,
"package_name" : value
}

And here what I was thinking to do:
"data" :{
"data_info" :{
"version" :null ,
"data_name" : value ,
"data_number" : null ,
"package_name" : value
}

I`m using apache beam with python SDK, and tried this, but without success...
def fill_missing_keys(data):

  data = json.loads(data['metadata'])
  data = {'data': {'data_info': data.get("data_name", None)   {'version': data.get("version", None) , 'data_name': data.get("version", None)... }

  return data

Answer: You need to call get() on the nested dictionary.
data = {
    'data': {
        'data_info': {
            'data_name': data['data']['data_info'].get('data_name'),
            'version': data['data']['data_info'].get('version'),
            'data_number': data['data']['data_info'].get('data_number'),
            'package_name': data['data']['data_info'].get('package_name')
        }
    }
}

When using .get() the result defaults to None, it's not necessary to specify it explicitly.
A less verbose method would be to provide a default dictionary and use the .update() method to merge the values from the JSON into it.
data = {
    'data': {
        'data_info': {
            'data_name': None,
            'version': None,
            'data_number': None,
            'package_name': None
        }.update(data['data']['data_info'])
    }
}

Comment: perhaps also include the default value ```None```?  i.e.  ```....get('data_name', None)```?
Comment: That's the default default value when using `.get()`.


How to Schedule a node "Promoted to front page"?

Question: I am looking for a way to schedule "Promoted To home page" nodes to appear after a particular time.
When user creates a new node and checks "Promoted To home page", it should not appear immediately on publish on the homepage.
Then need a scheduler which set "Promoted To home page" nodes to appear on front page.
The node will published and visible if accessed directly or seen in other section.
Comment: Could you give a more detailed description of the steps the user takes in this scenario. (e.g. Is published checked or unchecked when creating the node?
Comment: @undersound  published can be checked or unchecked at the time of creation as I can make a conditional check in the script to show published checked only.
Answer: You can do this using the Rules module in combination with the "Rules Scheduler" (a submodule of it). After you enable these 2 modules, create a Rules Component and a Rule. Here is a blueprint of doing so:

Create a Rules Component which accepts "node" as a parameter, and which has a Rules Action to set the node to "published".
Create a Rule like so:

Rules Event: Before saving a new node.
Rules Actions: (1) set the node to "unpublished" (to be sure it is not "published" when the node is saved) and (2) schedule the Rules Component created in the previous step.

Note: From the comment below this answer (which states "The node will remain Published all the time.") it doesn't seem to apply for the question here, but using a similar approach you could also schedule another Rules Component to mark it unpublished again later on, eg X days after the node gets published. In that case, you use Rules Event "After updating an existing node", combined with a Rules Condition to check if the update changed "unpublished" to "published".
Comment: Thanks for the reponse. The node will remain Published all the time. The only case is to show on homepage after a certain time.


Forecasting day-ahead electricity prices using a linear time series regression

Question: I have a dataset of hourly day-ahead electricity prices and hourly forecasted day-ahead demand (from governmental agency) in the Norwegian price area NO2. I am trying to use the forecasted day-ahead demand to predict the next 24-hour electricity prices for each day (cross validation using a rolling window) with a linear model. However, I am having trouble implementing the exogenous predictor (day-ahead demand) in this model without getting an error.
I have tried lagging the predictor, which looks like this:
# rolling window
NO2 <- NO2 %>%
  filter(datetime > as.POSIXct("2023-01-01 00:00:00"))
NO2_stretch <- NO2 %>%
  stretch_tsibble(.init = 48, .step = 24) %>% # initial training set of size 48 (two days), step = 24 as the training set should expand one day for each forecast iteration
  filter(.id !=max(.id)) # remove the last one as there will be no more observations to test
NO2_stretch # te "id" column corresponds to which row in the cross validation that we are in

# Estimate the linear models for each window
fit_cv <- NO2_stretch %>%
  model(TSLM(no2_price ~ lag(no2_load, 24) + season())) # get a forecast for each day with an increasing training set

# can pipe this rolling window into forecast in the usual way to produce one step ahead forecasts from all models
fc_cv <- fit_cv %>%
  forecast(h="1 day")

# Cross-validated accuracy
fc_cv %>%  accuracy(NO2_actual)

The forecast function gives me this error:
Error: Problem with `mutate()` input `TSLM(no2_price ~ no2_load + season())`.
x object 'no2_load' not found
  Unable to compute required variables from provided `new_data`.
  Does your model require extra variables to produce forecasts?
ℹ Input `TSLM(no2_price ~ no2_load + season())` is `(function (object, ...) ...`.

Any help on this would be highly appreciated, let me know if I can clarify this further.
Answer: At the moment you will need to provide a dataset containing the future values of no2_load to the forecast() function.
For example:
NO2_stretch_future <- NO2_stretch %>%
  new_data(n = 24) %>%
  mutate(no2_load = NA_real_)
fc_cv <- fit_cv %>%
  forecast(new_data = NO2_stretch_future)

I haven't been able to test this code since you haven't provided a minimally reproducible example (MRE). Providing a MRE makes is easier for me to quickly and accurately answer your question.


Cálculo de porcentagem PHP e salvar no Banco

Question: Estou tentando fazer um cálculo antes de enviar pro Banco de Dados:
    <?php
session_start();
require_once 'config/init.php';
require 'config/check.php';
?>

<?php

require 'config/conexao.php';

try {
    $PDO = new PDO( 'mysql:host=' . MYSQL_HOST . ';dbname=' . MYSQL_DB_NAME, MYSQL_USER, MYSQL_PASSWORD, array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8' ) );
} catch ( PDOException $e ) {
    echo 'Erro ao conectar com o MySQL: ' . $e->getMessage();
}

$descricao          = $_POST ['descricao'];
$fornecedor         = $_POST ['fornecedor'];
$custo              = $_POST ['custo'];
$margemlucro        = $_POST ['margemlucro'];
$estoque            = $_POST ['estoque'];

$custo1 = $_POST ['custo'];
$margemlucro1 = $_POST ['margemlucro'];
$precofinal = $custo1 + ($custo1 / 100 * $margemlucro1);

$sql = "INSERT INTO produtosservicos (descricao, fornecedor, custo, margemlucro, precofinal, estoque) VALUES
                                     (:descricao, :fornecedor, :custo, :margemlucro, :precofinal, :estoque)";

$stmt = $PDO->prepare($sql);

$stmt->bindParam(':descricao', $_POST['descricao'], PDO::PARAM_STR);
$stmt->bindParam(':fornecedor', $_POST['fornecedor'], PDO::PARAM_STR);
$stmt->bindParam(':custo', $_POST['custo'], PDO::PARAM_STR);
$stmt->bindParam(':margemlucro', $_POST['margemlucro'], PDO::PARAM_STR);
$stmt->bindParam(':precofinal', $precofinal);
$stmt->bindParam(':estoque', $_POST['estoque'], PDO::PARAM_STR);

$stmt->execute($stmt);

echo "";

?>

O cálculo ocorre, mas não salva no banco e nem dá erro. O que posso estar fazendo de errado? Se eu tiro o campo do cálculo, ele salva normalmente. Já troquei no banco para int, decimal e por fim deixei mesmo como varchar.
Atualização: Encontrei o erro [28-Jan-2019 18:03:11 UTC] PHP Warning:  PDOStatement::execute() expects parameter 1 to be array, object given in ******* on line 39
. Ainda não resolvi o problema.
Comment: E novamente você **omitiu** informações do erro como acabei de comentar. Você tem certeza que colocou na pergunta exatamente o trecho que possui o erro? Pergunto porque o erro claramente está reclamando que você passou um objeto como parâmetro para `PDOStatement::execute()`, mas no trecho que colocou na pergunta nem parâmetro tem nesta chamada.
Comment: Negativaram provavelmente porque sua pergunta não é clara. Você achou o erro, mas ainda não adicionou na pergunta. Você até colocou nos comentários a mensagem, mas omitiu as partes mais importantes: nome do arquivo e linha do erro. Poderia [edit] a pergunta e adicionar todos os detalhes que possui do problema até agora?
Comment: `$stmt->execute()` retornou `true`?
Comment: `expects parameter 1 to be array, object given in...` o código estava mandando pra index automático, não tinha visto o erro.
Comment: Pelo que to vendo, tu ta passando tudo como string no banco, este é um valor que nem sequer precisa ser armazenado, ele pode ser calculado pelo banco no retorno
Comment: Pensei em dar a opção de mudança, caso necessário. Por isso, to armazenando tudo. O que me recomenda, @bruno101 ?
Comment: Tem gente que tem prazer em dar downvote, não entendo...
Comment: Feito, @AndersonCarlosWoss.
Comment: Editei novamente a pergunta, tentando não omitir nenhum tipo de informação, peço por gentileza que avalie. Grato.
Answer: $stmt->bindParam(':precofinal', $_POST['precofinal'], PDO::PARAM_STR);

Tu não tem um $_POST['precofinal'].
Aconselho a trocar os valores do banco, deixar tudo como string não é uma boa pratica, este valor, por exemplo, poderia ser calculado e retornado pelo próprio banco e n~;ao pela aplicação.
Comment: Tens alguma referência para estudo, por favor? O $_POST passou mesmo, acabei não vendo, mas mesmo corrigindo, o erro persiste.
Answer: Recomendo ler novamente as documentações das funções que está utilizando: execute, bindParam.
O método PDOStatement::execute() espera um parâmetro do tipo array, que é opcional, mas você passa como parâmetro $stmt. Você basicamente chamou um método do objeto e passou ele mesmo como parâmetro - isso dificilmente fará sentido.
Como já atribuiu os valores com bindParam, não precisa passar parâmetros para o execute:
$stmt->execute();

Lendo a documentação verá que o método possui retorno. Não o ignore.
Comment: A sua informação foi útil e resolveu meu problema. Por fim, gostaria de colocar o código final, para informação. Como devo proceder?
Comment: @CyberPlague Não necessita, basta sinalizar como útil a resposta utilizando o **✓**
Comment: Obrigado pelo apoio. Só lamento pela minha falta de compreensão no desenvolvimento da questão, fico triste pelo downvote. Espero acertar estas questões. Abraço.


Posicionar texto em TextViews e EditTexts com uma imagem como background?

Question: Criei um app simples o qual possui apenas um TextView e um EditText:

Como podem ver mudei o background de ambos, até aí nenhum problema:

O problema aparece quando insiro textos, pois os mesmos ficam mal posicionados no layout tanto do TextView quanto do EditText:

Até mesmo de maneiras diferentes...
Enfim, já tentei algumas formas para solucionar isso, inclusive selecionar outros alinhamentos, mas nada do comportamento mudar:

Gostaria que me informassem como fazer para que as caixas de textos ajam de forma similar a que exibirei:

Fiz um nine-patch com a imagem presente na aplicação:

Porém já na preview do layout estranhei porque apareceu bugada:

No resultado final no android emulator, foi diferente, mas igualmente ruim:

A imagem original possui as seguintes dimensões => 714x627... Fiz uma regra de 3, pois queria que a mesma tivesse 100 de largura.
Coloquei no layout_width 100 e no layout_heigth 88.
O valor equivalente a 100 em altura, deu 87 e uns quebrados, pois fiz regra de 3, aproximei para 88. Mesmo assim, não deveria apresentar algo esdrúxulo assim...
A solução foi diminuir o tamanho da imagem e importar novamente para o android studio, aproveitei para colocar 2 pixels de largura e altura extras para não haver nenhum corte.
Comment: Não devia ter editado a pergunta com a solução, mas sim colocado como resposta.
Answer: A forma de conseguir esse comportamento é a imagem de background ser um nine-patch bitmap.
Um Nine-patch é um bitmap que o Android redimensionará automaticamente para incluir o conteúdo da View à qual foi atribuído como background.
Ele é um PNG normal(a imagem usada como background) com uma borda extra de 1 pixel de espessura onde é definida a zona ajustável e a zona onde o conteúdo é colocado.

Fonte: Canvas and Drawables - Nine-patch.
Comment: A delimitações de margem e talz é até fácil de fazer, porém a imagem distorce completamente
Comment: diminuí o tamanho para o que eu setei no textview e resultou. obg!!!
Comment: Pode pôr a imagem na sua pergunta? Gostaria de tentar fazer com que ela não distorça.
Answer: Você vai ter que dar um padding de, por exemplo, 10 DP no editText.
android:padding="10dp"

Para centralizar, é só usar no xm ltambém um:
android:gravity"center"

Para quebrar linha em determinado número de caracteres, você terá de fazer isso via Java e adicionar um \n na string para quebrar a linha. Essa resposta o ajudará.


Como consigo evitar erros intermitentes de cors com requisicões axios e vue.js?

Question: Tenho uma aplicação desenvolvida em Vue.js que realiza requisições através do axios para uma api desenvolvida em Node.js com express. Meu problema é que em 3% das requisições o CORS é bloqueado travando a aplicação. Alguém sabe como evitar esse erro?
Obs1. Analizando os headers das requisições com erro. Retorna apenas um Network Error,
Segue o header da requisição
<code>OPTIONS /coleta undefined
Host: xxx.xxxxxx.xxx
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0
Accept: */*
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Referer: https://xxx.xxxxxxx.xxx/
Origin: https://xxx.xxxxxx.xxx
Connection: keep-alive
</code>
Segue o erro apresentado no console:
<code>> Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxx.xxxxxx.xxxx/xxxxxxxx. (Reason: CORS request did not succeed).
Uncaught (in promise) Error: Network Error
    exports createError.js:16
    onerror xhr.js:84
createError.js:16
</code>
Obs2. O erro pode ocorrer em qualquer requisição da aplicação de forma aleatória, na maioria das vezes a requisição funcionam normalmente, o erro é apenas em algumas poucas requisições. O que me leva a crer que o problema não é com o código da api Node.js com express que está devidamente configurando com a biblioteca npm cors.
Obs3. A aplicação esta hospedada na AWS. O front no S3 com distribuição do CloudFront e o backend em uma instância do LightSail. Problema na distribuição do CloudFront não é, que o erro ocorre também com os testes no localhost realizado a requisição.
Agradeço a atenção.
Answer: Depois de corrigir o código e verificar que exatamente mesmo erro ocorria desligando o wifi, também o ping da conexão local, descobri que em alguns momentos a rede local apresentava intermitências, o que faz o axios responder com erro de conexão em alguns momentos.
Para contornar o problema configurei o timeout de 15seg para todas as requisições com o axios, tratei o erro da forma adequada e ajustei o load com a biblioteca NProgress. Agora o sistema ficou ok.
Achei muito estranho pouca literatura sobre o problema tanto em foruns nacionais e internacionais, o que antes de encontrar o problema me fez até reconfigurar o serviço em outros servidores.
Mas no fim deu certo!


How to make a macro file recognize TABs of first macro file js variable?

Question: I am a beginner, trying to pass a imacros variable into JavaScript, but it failed. I run FF 55.0.3 on Win 7 32 bit, imacros ver. v8.9.7
I have 2 iim scripts that I call from JS, the first one runs only once.
The first one do some tasks on 2 URLs on 2 TABS, back and forth, when it finishes its task, js call the the second iim file, the second iim file should work on those opened 2 TABs as well,
But second macro script does not remember the TAB 1, to go back and do some work.
When first macro finishes its task, ends on TAB T=1, so the second macro starts to work on TAB 1, and it goes to TAB 2 even though TAB 2 was first opened from first macro file.
But when it should go back to TAB 1, it won't, so the first macro file do not carry tabs memory to second macro, and I have no idea how to do so.
(no new TAB on second macro file).
I have tried this in the second macro file:
SET MyTB 1
TAB T={{MyTB}}

and in JS file
 iimPlay("MyMacro-1");
var retcode;
retcode = iimPlay("MyMacro-1")

SET !MyTB
PROMPT {{!MyTB}}

if (retcode > 0) {
retcode = iimPlay("MyMacro-2")
}
iimDisplay (retcode);
for (var i=0;i<=9;i++) {
iimPlay("MyMacro-2");
}

but I get error on line with this code: SET !MyTB.
I am not sure this is the right approach in JS to make it work, but I have to try it.
Answer: OK,
I made it work, it was not needed to have it on js file,
I had have the variable in macrofile 2, now it is working.
Comment: Welcome to Stack Overflow! If you figured it out, you can mark your own answer as accepted, so the question does not appear as unanswered to others. You might also consider elaborating a bit more on the solution in your answer so that others who might be facing a similar situation know what to do.


NSURL returning nil

Question: I dont know why but when I am calling the following URL
it gives me BAD REQUEST - INVALID URL, although this URL is working fine on safari browser and other browsers as well
http://www.ysl.com/wx/shop-product/women/top-handles#{"ytosQuery":"true","department":"handbags_tophandle_w","gender":"D","brand":"","macro":"","micro":"","season":"A,P,E","color":"","size":"","site":"","section":"","sortRule":"","yurirulename":"searchwithdepartment","microcolor":"","agerange":"","macroMarchio":"","page":"2","productsPerPage":"50","modelnames":"","look":"","washtype":"","fabric":"","prints":"","suggestion":"false","suggestionValue":"","material":"","occasion":"","weight":"","gal

I am using following code:
NSString *str = [NSString stringWithFormat:@"%@",[payload stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];

NSString* webStringURL = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

webStringURL = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *payload = [NSURL URLWithString:webStringURL];

Any Help Guys? What is that I am doing wrong?
Comment: `{` isn't legal in a URL.  In fact is that JSON?
Answer: Don't use stringByReplacingPercentEscapesUsingEncoding: on the hole URL, but just on the GET parameters.
Now http:// will also be escaped, thus becoming http%3A%2F%2F which is not valid as an URL.
Comment: You shouldn't be using either of those methods at all.  The first one removes escape sequences (but there aren't any), and the second one tries to add them back everywhere.  The right way to encode URL data is described at https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/WorkingwithURLEncoding/WorkingwithURLEncoding.html on Apple's developer website.  You'll also need to (__bridge CFStringRef) your NSStrings and (__bridge_transfer NSString *) them on the way back for ARC.
Comment: if you see, I am also addingpercentescape again in the whole URL.
Comment: You should not, on the parameters should be escaped.

NSURL returning nil


Inheritance and Destructors in C#

Question: According to this, it states that Destructors cannot be inherited or overloaded. In my case, for all subclasses, the destructors will be identical. Is this pretty much telling me that I must define the same destructor in each sub class. There is no way that I can declare the destructor in the base class and have the handle the destruction? Say I have something like this:
class A
{
    ~A()
    {
        SomethingA();
    }

}

class B : A
{

}

B b = new B();

When B is destroyed, its destructor wont be called?
Comment: Better read up on destructors and why _not_ to use them. I suspect you don't need one at all.
Comment: That's a different question. I'd encourage you to post it as such, but it's been asked so frequently already... long story short: On garbage collection, but that may occur *much* later or *not at all*.
Comment: Seems like something that would be easy enough to test. Do you have examples where the destructor for `b` isn't being run?
Comment: @Yuck Well this leads me to possibly another dumb question... "When does the destructors actually get called? Is it on garbage collection, when the variable falls out of scope?
Answer:
According to this, it states that Destructors cannot be inherited or overloaded.

Correct. Destructors are not inheritable members, and are not virtual and so cannot be overridden. They always have the same signature so they cannot be overloaded.

In my case, for all subclasses, the destructors will be identical.

The fact that you are asking such a basic question is telling me that you should not be implementing a destructor in the first place. Implementing a destructor correctly is one of the hardest things to do in C# in all but the most trivial cases. Why do you believe that you need to implement a destructor?

Is this pretty much telling me that I must define the same destructor in each sub class?

No, not at all. How did you arrive at that conclusion from the fact that destructors are not inherited?

There is no way that I can declare the destructor in the base class and have the handle the destruction?

Sure, that's a sensible thing to do, provided that you're bent on implementing a destructor in the first place.

When B is destroyed, its destructor won't be called?

That is incorrect.
It occurs to me that it would have taken you a lot less time to try it yourself than to ask the question here and wait for a response.

When does the destructors actually get called? Is it on garbage collection, when the variable falls out of scope?

My earlier conjecture is correct. You definitely should not be implementing a destructor until you deeply understand the entire garbage collection process. The fact that you believe that variables are collected when they fall out of scope, for example, indicates that you don't understand this deeply enough to write a correct destructor.
When an object is determined to be unreachable from a gc root by the collector, and the object has a finalizer that has not been suppressed then the object is promoted to the next generation by placing it on the finalization queue for servicing by the finalizer thread. If not, its memory is reclaimed.
When the finalizer thread gets around to running, it runs all the destructors of the object. (Destructors will run in order from most derived to least derived.) After that process the object then may or may not be unreachable and finalization may or may not be suppressed. If the object is determined to be unreachable then the whole process starts again.
I cannot emphasize enough how well you need to understand the GC process in order to do this correctly. When you write a destructor it runs in an environment where nothing makes sense. All the references in the object might be to objects that are only rooted by the finalizer queue; normally all references are to live things. References might be to objects that are already finalized. Destructors run on a different thread. Destructors run even if the constructor failed, so the object might not even be constructed properly. Fields of non-atomic value types may be only partially written -- it is entirely possible for a double field to have only four of its bytes set by the constructor when the thread is aborted; the finalizer will see that partially-written field. Destructors run even if the object was placed in an inconsistent state by an aborted transaction. And so on.  You have to be extremely defensive when writing a destructor.
This answer might also help:
When should I create a destructor?
Comment: Hey Eric, I've flagged your answer as rude and if you read it again, I think you'll agree. Perhaps you were having a bad day?  :)  OP seems to be coming from C++ which would make this question very reasonable.
Comment: What do you mean "references may be to dead things".  All object references are guaranteed to point to valid .net objects; if any of the objects to which one has direct or indirect references override Finalize and have not suppressed finalization, it's likely that they may have run or be scheduled to run, but as long as an object is registered for finalization, neither it nor any object to which it holds a direct or indirect reference can be removed from memory.  The biggest difficulty with finalization is probably the unknown threading context.
Comment: An object should not make any assumptions about the state of finalizable objects whose code one does not control, but if Class1 and Class2 are both in the same assembly, and Object1 (of type Class1) holds a reference to Object2 (of Class2) and accesses it within its finalizer, it must be prepared for the possibility that Object2 may have already been finalized, or may be pending finalization.  If any references to Object2 have been exposed externally, it must also allow for the possibility that external live references to Object2 may still exist.  Subject to those constraints, however, ...
Comment: ...it's perfectly possible and reasonable for objects to have finalizers that coordinate with each other.  It took awhile for me to understand how a GC cycle divides objects into those which have roots other than the finalization mechanism, those which are registered for finalization but have no *other* roots, and those which have no rooted references at all, and to understand that finalization does not disturb an object in any way except for calling a Finalize (which will only disturb an object in ways it's explicitly programmed to do).
Comment: @Seth: I stand by the answer. I never said the question was unreasonable. The answer is accurate and helpful.
Comment: What does something not being virtual have to do with it not being able to be overloaded? Or did you mean to say overridden?
Comment: @supercat: Good point. Let me clarify. Suppose you have two unrooted finalizable objects that mutually reference each other. The GC considers them garbage and puts them on the finalizer queue, so they are still (barely) alive. After the finalizer of the first one runs, the second finalizer is code running in an object that refers to the first object, an object that is barely alive and has already been finalized. It seems dangerous for the second object to make any assumption about the first at this point.
Answer: It's not a destructor in C#.  It's known as a Finializer; and when it is called is non-deterministic.  You actually can't count on it to be called at all.
Finalizers are used as a last resort to clean up unmanaged resources.  You should look into the Dispose pattern.
Comment: Technically the C# spec calls it a destructor. (Personally I think that's a misleading name and it should be called finalizer even in the C# spec)
Comment: I second the notion of using IDisposable in most of these situations
Comment: @CodeInChaos: I agree, but we're stuck with it now.
Comment: Even Eric Lippert [laments](http://blogs.msdn.com/b/ericlippert/archive/2010/01/21/what-s-the-difference-between-a-destructor-and-a-finalizer.aspx) that it's called a destructor in the spec.
Comment: Stating "It's not a destructor in C#" is not helping.
Comment: A "destructor" is a C# construct which overrides Finalize() with a method that wraps the supplied bit of code and calls Base.Finalize().  The term "destructor" adds nothing but confusion, and the C# construct adds no discernable value over simply not forbidding overrides of `Object.Finalize`, but the term is what it is, and there is no other term that refers precisely to the syntactic entity which is written using destructor sequence, nor to the silly wrapper code which is generated by that syntax.
Answer: The finalizer you defined in A will be called when an instance of B is destroyed.
If you define a finalizer in both A and B, the most specific finalizer (B) will run first, then the least specific (A).
Answer: I've been doing .NET programming for close to a decade. The only time I implemented a finalizer, it ended up being a cause for a memory leak and nothing else. You almost never need them.
Comment: I've found them very occasionally helpful for debug versions of software.  E.g, `~MyClass() {if (this.Oops) Debug.Fail("Oops");}`
Comment: This is not an answer to the question. And just because you may have been working on projects that don't often have unmanaged resources doesn't mean that's the case for everyone using .Net. I would agree that the vast majority of C# objects don't need finalizers, but there are still many cases where they are necessary to prevent resource leaks (or deadlock, etc.) when something unexpected happens that prevents an object from being disposed normally.
Answer: A quick console app can help test this sort of thing.
using System;

class A
{
    ~A() => Console.WriteLine("~A");
}

class B : A
{
    ~B() => Console.WriteLine("~B");
}

public class Program
{
    public static void Main() => new B();
}

The output might be...
~B
~A

Answer: If you define a destructor for B, it will be called, followed by A's. See the example at the bottom of the link you provided.
Answer: Well, I don't know about destructors, but you have other useful methods for cleanup like Finalize() and Dispose() from IDisposable.
Comment: @Tudor: Unfortunately, the makers of C# decided that since people, if allowed to do so, would probably override `Object.Finalize()` rather than using the spiffy C# destructor syntax, it was necessary to forbid overriding `Object.Finalize()`.  Seems silly to me, but I didn't write the language spec.
Comment: A C# destructor and the `Finalize` are pretty much equivalent.
Comment: Yes, the destructor implicitly calls Finalize(), but since this is a method of object, its behavior relative to inheritance/override is much more clear.

Inheritance and Destructors in C#


Clustering Algorithm for labeled data

Question: This is more of a theoretical/solving an argument sort of question.
Assuming I have a bunch of data point with 11 features I consider relevant about each point and 2 "labels": one is a boolean label ( 0 or 1), one is a continuous "label" (thought I'm not sure the word label really applies here).
What I want to do is basically: Find a way to predict both of these labels as accurately as possible. Find the features which influence these labels the most (even if by finding said features I'm unable to find a strong equation for actually predicting the labels).
Also, of note would be the fact that, although I care about both labels, predicting the second would automatically mean I predict the first and predicting the first is enough to "solve" the problem in most cases.
With me until now? Ok, perfect.
Someone suggested to me that this would be a perfect scenario to apply clustering algorithms, but I'm not quite sure why. I was under the impression that clustering, generally speaking, is used to label unlabeled data (I have labeled data here) and for actually making predictions on unlabeled data a regression (be it with a SVM, a NN or w/e) or classification type algorithm is what can be used.
The only situation in which I could see clustering being used here is to turn the continuous label into a fixed number of labels.
Is there another situation in which a clustering algorithm can be applied to this sort of problem? Are there ways to use clustering algorithms to predict already existing labels or figure out if there is even a relation at all between a given label and a feature? Can clustering algorithms be used to filter out irrelevant features?
Comment: My suggestion would be to use some-kind of machine learning algorithm on the second label. Then you can deduce the first label from the results you got for the second label. Why do you want to use a clustering algorithm?
Comment: I don't. As I said, I have this type of data and someone "suggested" using a clustering algorithm. I'm quite falbargasted by the fact that he did so since, to my knowledge, clustering algorithm are, by defintion, used for labeling data (which Is either not fully labeled or not labeled at all).
Comment: Clustering algorithm can be used on labelled-data. It can be seen as a special case of categorization, where specifically you categorize data that are 'near' each other in some way. The reason you might choose such a special case is either because you have no labels and can't use more general methods, or because you know that the should be clustered is some way and you want to make sure the algorithm tries to find those clusters.
Comment: Whoever suggested clustering here, probably just played buzzword bingo...
Answer: Clustering algorithms will always perform much much worse compared to classification methods.
If you have labels, use classification or regression instead of clustering!
The reason is simple:
The clustering does not know which problem to solve, and there may well be more than one. You have no control over it solving anything related to your task.
For example, you might want to predict of a user will buy the product (classification) or the amount of money/time he spends on your site (regression). A clustering algorithm, since it does no know what you are interested in, may consider it more important to cluster your users by the weekday the, first visited your site... which may be a very good clustering, yet essentially useless for your business.

Clustering Algorithm for labeled data


Subsetting table under conditions shiny

Question: Hi am building an application to select a dataset given several sliders input. In order to get the multiple subset i am using a for loop that it does no work. It suppose to show me in the table all the combinations that satisfy the conditions given from the sliders but as you can eventhough i ask for brand to be under a certain value is still in the table. Please if anybody can help. The code and the requested file is below:
UI.R
    library(shiny)

    attributes <- unique(dataset_with_key[,2])
    len <- length(attributes)

    shinyUI (pageWithSidebar (
      headerPanel("Testing"),
      sidebarPanel(
        lapply(1:2, function(i){

          sliderInput(paste("weight",i,sep="_"),
                      paste("Select attribute levels :", attributes[i]),
                      min = 0,
                      max = 1,
                      step=0.05,
                      # round=-2,
                      value = c(0,1))
        }),
        selectInput("variable", "Variable:",
                    unique(dataset_with_key[,1]))
      )
      , mainPanel(
        tabsetPanel(
          tabPanel("Restrictions", h3("Analysis"),
                   tableOutput("values2"),
                   tableOutput("values")
          ),
          tabPanel("Information",textOutput("text1"))
        )
      )
    ))

SERVER.R

library(shiny)

attributes <- unique(dataset_with_key$Attribute)
tempf <- dataset_with_key$key
shinyServer( function(input,output){

  final <- reactive(function(){
    tempf <- dataset_with_key

    for (i in 1:2){
      tempcond <- dataset_with_key[round(tempf$Primary_Weights,2) <=
                                     round( eval(parse(text = paste0(paste('input$weight', i, sep='_'),"[2]"))),2)
                                   & round(tempf$Primary_Weights,2) >=
                                     round(eval(parse(text = paste0(paste('input$weight', i, sep='_'),"[1]"))),2)
                                   & tempf$Attribute==attributes[i],]

      tempf <- dataset_with_key[dataset_with_key$key %in% tempcond$key,]

    }
    tempf
  })

  output$values <- renderTable ({
    final()

  })

  output$text1 <- renderText({
    paste("your command output is  ",typeof(final),"Number Of Combinations",length(unique(final()$key)))
  })
})

and a sample of the dataset:
structure(list(combination = structure(c(47L, 47L, 47L, 47L,
47L, 47L, 47L, 47L, 47L, 47L, 47L, 47L, 47L, 47L, 47L, 47L, 47L,
47L, 47L, 47L, 47L, 47L, 47L, 47L, 47L, 47L, 47L, 58L, 58L, 58L,
58L, 58L, 58L, 58L, 58L, 58L, 58L, 58L, 58L, 58L, 58L, 58L, 58L,
58L, 58L, 58L, 58L, 58L, 58L, 58L, 58L, 58L, 58L, 58L, 58L, 58L,
58L, 58L, 58L, 69L, 69L, 69L, 69L, 69L, 69L, 69L, 69L, 69L, 69L,
69L, 69L, 69L, 69L, 69L, 69L, 69L, 69L, 69L, 69L, 69L, 69L, 69L,
69L, 69L, 69L, 69L, 69L, 69L, 69L, 69L, 69L, 80L, 80L, 80L, 80L,
80L, 80L, 80L, 80L, 80L, 80L), .Label = c("Comb_1", "Comb_10",
"Comb_100", "Comb_101", "Comb_102", "Comb_103", "Comb_104", "Comb_105",
"Comb_106", "Comb_107", "Comb_108", "Comb_109", "Comb_11", "Comb_110",
"Comb_111", "Comb_112", "Comb_12", "Comb_13", "Comb_14", "Comb_15",
"Comb_16", "Comb_17", "Comb_18", "Comb_19", "Comb_2", "Comb_20",
"Comb_21", "Comb_22", "Comb_23", "Comb_24", "Comb_25", "Comb_26",
"Comb_27", "Comb_28", "Comb_29", "Comb_3", "Comb_30", "Comb_31",
"Comb_32", "Comb_33", "Comb_34", "Comb_35", "Comb_36", "Comb_37",
"Comb_38", "Comb_39", "Comb_4", "Comb_40", "Comb_41", "Comb_42",
"Comb_43", "Comb_44", "Comb_45", "Comb_46", "Comb_47", "Comb_48",
"Comb_49", "Comb_5", "Comb_50", "Comb_51", "Comb_52", "Comb_53",
"Comb_54", "Comb_55", "Comb_56", "Comb_57", "Comb_58", "Comb_59",
"Comb_6", "Comb_60", "Comb_61", "Comb_62", "Comb_63", "Comb_64",
"Comb_65", "Comb_66", "Comb_67", "Comb_68", "Comb_69", "Comb_7",
"Comb_70", "Comb_71", "Comb_72", "Comb_73", "Comb_74", "Comb_75",
"Comb_76", "Comb_77", "Comb_78", "Comb_79", "Comb_8", "Comb_80",
"Comb_81", "Comb_82", "Comb_83", "Comb_84", "Comb_85", "Comb_86",
"Comb_87", "Comb_88", "Comb_89", "Comb_9", "Comb_90", "Comb_91",
"Comb_92", "Comb_93", "Comb_94", "Comb_95", "Comb_96", "Comb_97",
"Comb_98", "Comb_99"), class = "factor"), Attribute = structure(c(5L,
6L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 9L, 10L, 1L, 2L, 4L, 5L,
6L, 11L, 12L, 8L, 1L, 2L, 4L, 5L, 6L, 11L, 12L, 8L, 1L, 2L, 4L,
5L, 6L, 11L, 12L, 8L, 1L, 2L, 4L, 5L, 6L, 11L, 12L, 8L, 1L, 2L,
4L, 5L, 6L, 11L, 8L, 10L, 1L, 2L, 4L, 5L, 6L, 11L, 8L, 10L, 1L,
2L, 4L, 5L, 6L, 11L, 8L, 10L, 1L, 2L, 4L, 5L, 6L, 11L, 8L, 10L,
1L, 2L, 4L, 5L, 6L, 12L, 8L, 1L, 2L, 4L), .Label = c("Brand",
"Camera", "Colour", "Connectivity", "Display_Size", "Input_Method",
"mg_brand", "mg_color", "mg_opersystem", "mg_price2", "Operating_System",
"Price_Bucket"), class = "factor"), Primary_Weights = c(0.0165760131,
0, 0, 0.4382099557, 0.0715554519, 0.4354625906, 0, 0.0135417213,
0, 0.0412302804, 0, 0.416657648, 0.0731228557, 0.410532306, 0.0175337476,
0.0132847392, 0.0280221081, 0.0408465955, 0, 0.5417733265, 0.0142395741,
0.3523226007, 0.0126580754, 0.0130543718, 0.0305692407, 0.0353828109,
0, 0.4599561851, 0.1349562691, 0, 0.0273273821, 0.1398679705,
0.037837, 0.0304305572, 0.1696246359, 0.4688031055, 0.1442811929,
0, 0.0237889734, 0.115486818, 0.0423853165, 0.0448927516, 0.1603618421,
0.5177030547, 0.136576526, 0, 0.0194930818, 0.0936183616, 0.0461031421,
0.0510339776, 0.1354718562, 0.5981180958, 0.1120119023, 0, 0.0244608866,
0.073904943, 0.0374447237, 0.0442274822, 0.1098319663, 0.490429186,
0.1686263243, 0, 0.0253375776, 0.1033618908, 0.0449793998, 0.1672656215,
0, 0.5603062011, 0.1229685727, 0, 0.0209758487, 0.0972089602,
0.0524026324, 0.1461377849, 0, 0.6166255117, 0.0392621558, 0,
0.0243300602, 0.1207420923, 0.05097111, 0.1480690699, 0, 0.7103228618,
0.0267168423, 0, 0.0190666225, 0.0903017086, 0.0384278705, 0.1122011799,
0.0029629144, 0.4839247401, 0.1457474446, 0, 0.027824948, 0.1166001084,
0.0354318356, 0.1904709234, 0.5993858379, 0.0823854869, 0), vif = c(6L,
6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 7L, 7L, 7L), pvalue = c(0.6, 0.6, 0.6, 0.7, 0.7, 0.7, 0.7,
0.7, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.9,
0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6,
0.6, 0.6, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8,
0.8, 0.8, 0.8, 0.8, 0.8, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9,
0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.7, 0.7, 0.7, 0.7, 0.7,
0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.9, 0.9,
0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6,
0.7, 0.7, 0.7), key = structure(c(209L, 209L, 209L, 214L, 214L,
214L, 214L, 214L, 214L, 214L, 214L, 219L, 219L, 219L, 219L, 219L,
219L, 219L, 219L, 224L, 224L, 224L, 224L, 224L, 224L, 224L, 224L,
253L, 253L, 253L, 253L, 253L, 253L, 253L, 253L, 258L, 258L, 258L,
258L, 258L, 258L, 258L, 258L, 263L, 263L, 263L, 263L, 263L, 263L,
263L, 263L, 268L, 268L, 268L, 268L, 268L, 268L, 268L, 268L, 297L,
297L, 297L, 297L, 297L, 297L, 297L, 297L, 302L, 302L, 302L, 302L,
302L, 302L, 302L, 302L, 307L, 307L, 307L, 307L, 307L, 307L, 307L,
307L, 312L, 312L, 312L, 312L, 312L, 312L, 312L, 312L, 341L, 341L,
341L, 341L, 341L, 341L, 341L, 346L, 346L, 346L), .Label = c("Comb_10060.6",
"Comb_10070.7", "Comb_10080.8", "Comb_10090.9", "Comb_10160.6",
"Comb_10170.7", "Comb_10180.8", "Comb_10190.9", "Comb_10260.6",
"Comb_10270.7", "Comb_10280.8", "Comb_10290.9", "Comb_10360.6",
"Comb_10370.7", "Comb_10380.8", "Comb_10390.9", "Comb_10460.6",
"Comb_10470.7", "Comb_10480.8", "Comb_10490.9", "Comb_10560.6",
"Comb_10570.7", "Comb_10580.8", "Comb_10590.9", "Comb_1060.6",
"Comb_10660.6", "Comb_10670.7", "Comb_10680.8", "Comb_10690.9",
"Comb_1070.7", "Comb_10760.6", "Comb_10770.7", "Comb_10780.8",
"Comb_10790.9", "Comb_1080.8", "Comb_10860.6", "Comb_10870.7",
"Comb_10880.8", "Comb_10890.9", "Comb_1090.9", "Comb_10960.6",
"Comb_10970.7", "Comb_10980.8", "Comb_10990.9", "Comb_11060.6",
"Comb_11070.7", "Comb_11080.8", "Comb_11090.9", "Comb_11160.6",
"Comb_11170.7", "Comb_11180.8", "Comb_11190.9", "Comb_11260.6",
"Comb_11270.7", "Comb_11280.8", "Comb_11290.9", "Comb_1160.6",
"Comb_1170.7", "Comb_1180.8", "Comb_1190.9", "Comb_1260.6", "Comb_1270.7",
"Comb_1280.8", "Comb_1290.9", "Comb_1360.6", "Comb_1370.7", "Comb_1380.8",
"Comb_1390.9", "Comb_1460.6", "Comb_1470.7", "Comb_1480.8", "Comb_1490.9",
"Comb_1560.6", "Comb_1570.7", "Comb_1580.8", "Comb_1590.9", "Comb_160.6",
"Comb_1660.6", "Comb_1670.7", "Comb_1680.8", "Comb_1690.9", "Comb_170.7",
"Comb_1760.6", "Comb_1770.7", "Comb_1780.8", "Comb_1790.9", "Comb_180.8",
"Comb_1860.6", "Comb_1870.7", "Comb_1880.8", "Comb_1890.9", "Comb_190.9",
"Comb_1960.6", "Comb_1970.7", "Comb_1980.8", "Comb_1990.9", "Comb_2060.6",
"Comb_2070.7", "Comb_2080.8", "Comb_2090.9", "Comb_2160.6", "Comb_2170.7",
"Comb_2180.8", "Comb_2190.9", "Comb_2260.6", "Comb_2270.7", "Comb_2280.8",
"Comb_2290.9", "Comb_2360.6", "Comb_2370.7", "Comb_2380.8", "Comb_2390.9",
"Comb_2460.6", "Comb_2470.7", "Comb_2480.8", "Comb_2490.9", "Comb_2560.6",
"Comb_2570.7", "Comb_2580.8", "Comb_2590.9", "Comb_260.6", "Comb_2660.6",
"Comb_2670.7", "Comb_2680.8", "Comb_2690.9", "Comb_270.7", "Comb_2760.6",
"Comb_2770.7", "Comb_2780.8", "Comb_2790.9", "Comb_280.8", "Comb_2860.6",
"Comb_2870.7", "Comb_2880.8", "Comb_2890.9", "Comb_290.9", "Comb_2960.6",
"Comb_2970.7", "Comb_2980.8", "Comb_2990.9", "Comb_3060.6", "Comb_3070.7",
"Comb_3080.8", "Comb_3090.9", "Comb_3160.6", "Comb_3170.7", "Comb_3180.8",
"Comb_3190.9", "Comb_3260.6", "Comb_3270.7", "Comb_3280.8", "Comb_3290.9",
"Comb_3360.6", "Comb_3370.7", "Comb_3380.8", "Comb_3390.9", "Comb_3460.6",
"Comb_3470.7", "Comb_3480.8", "Comb_3490.9", "Comb_3560.6", "Comb_3570.7",
"Comb_3580.8", "Comb_3590.9", "Comb_360.6", "Comb_3660.6", "Comb_3670.7",
"Comb_3680.8", "Comb_3690.9", "Comb_370.7", "Comb_3760.6", "Comb_3770.7",
"Comb_3780.8", "Comb_3790.9", "Comb_380.8", "Comb_3860.6", "Comb_3870.7",
"Comb_3880.8", "Comb_3890.9", "Comb_390.9", "Comb_3960.6", "Comb_3970.7",
"Comb_3980.8", "Comb_3990.9", "Comb_4060.6", "Comb_4070.7", "Comb_4080.8",
"Comb_4090.9", "Comb_4160.6", "Comb_4170.7", "Comb_4180.8", "Comb_4190.9",
"Comb_4260.6", "Comb_4270.7", "Comb_4280.8", "Comb_4290.9", "Comb_4360.6",
"Comb_4370.7", "Comb_4380.8", "Comb_4390.9", "Comb_4460.6", "Comb_4470.7",
"Comb_4480.8", "Comb_4490.9", "Comb_4560.6", "Comb_4570.7", "Comb_4580.8",
"Comb_4590.9", "Comb_460.6", "Comb_4660.6", "Comb_4670.7", "Comb_4680.8",
"Comb_4690.9", "Comb_470.7", "Comb_4760.6", "Comb_4770.7", "Comb_4780.8",
"Comb_4790.9", "Comb_480.8", "Comb_4860.6", "Comb_4870.7", "Comb_4880.8",
"Comb_4890.9", "Comb_490.9", "Comb_4960.6", "Comb_4970.7", "Comb_4980.8",
"Comb_4990.9", "Comb_5060.6", "Comb_5070.7", "Comb_5080.8", "Comb_5090.9",
"Comb_5160.6", "Comb_5170.7", "Comb_5180.8", "Comb_5190.9", "Comb_5260.6",
"Comb_5270.7", "Comb_5280.8", "Comb_5290.9", "Comb_5360.6", "Comb_5370.7",
"Comb_5380.8", "Comb_5390.9", "Comb_5460.6", "Comb_5470.7", "Comb_5480.8",
"Comb_5490.9", "Comb_5560.6", "Comb_5570.7", "Comb_5580.8", "Comb_5590.9",
"Comb_560.6", "Comb_5660.6", "Comb_5670.7", "Comb_5680.8", "Comb_5690.9",
"Comb_570.7", "Comb_5760.6", "Comb_5770.7", "Comb_5780.8", "Comb_5790.9",
"Comb_580.8", "Comb_5860.6", "Comb_5870.7", "Comb_5880.8", "Comb_5890.9",
"Comb_590.9", "Comb_5960.6", "Comb_5970.7", "Comb_5980.8", "Comb_5990.9",
"Comb_6060.6", "Comb_6070.7", "Comb_6080.8", "Comb_6090.9", "Comb_6160.6",
"Comb_6170.7", "Comb_6180.8", "Comb_6190.9", "Comb_6260.6", "Comb_6270.7",
"Comb_6280.8", "Comb_6290.9", "Comb_6360.6", "Comb_6370.7", "Comb_6380.8",
"Comb_6390.9", "Comb_6460.6", "Comb_6470.7", "Comb_6480.8", "Comb_6490.9",
"Comb_6560.6", "Comb_6570.7", "Comb_6580.8", "Comb_6590.9", "Comb_660.6",
"Comb_6660.6", "Comb_6670.7", "Comb_6680.8", "Comb_6690.9", "Comb_670.7",
"Comb_6760.6", "Comb_6770.7", "Comb_6780.8", "Comb_6790.9", "Comb_680.8",
"Comb_6860.6", "Comb_6870.7", "Comb_6880.8", "Comb_6890.9", "Comb_690.9",
"Comb_6960.6", "Comb_6970.7", "Comb_6980.8", "Comb_6990.9", "Comb_7060.6",
"Comb_7070.7", "Comb_7080.8", "Comb_7090.9", "Comb_7160.6", "Comb_7170.7",
"Comb_7180.8", "Comb_7190.9", "Comb_7260.6", "Comb_7270.7", "Comb_7280.8",
"Comb_7290.9", "Comb_7360.6", "Comb_7370.7", "Comb_7380.8", "Comb_7390.9",
"Comb_7460.6", "Comb_7470.7", "Comb_7480.8", "Comb_7490.9", "Comb_7560.6",
"Comb_7570.7", "Comb_7580.8", "Comb_7590.9", "Comb_760.6", "Comb_7660.6",
"Comb_7670.7", "Comb_7680.8", "Comb_7690.9", "Comb_770.7", "Comb_7760.6",
"Comb_7770.7", "Comb_7780.8", "Comb_7790.9", "Comb_780.8", "Comb_7860.6",
"Comb_7870.7", "Comb_7880.8", "Comb_7890.9", "Comb_790.9", "Comb_7960.6",
"Comb_7970.7", "Comb_7980.8", "Comb_7990.9", "Comb_8060.6", "Comb_8070.7",
"Comb_8080.8", "Comb_8090.9", "Comb_8160.6", "Comb_8170.7", "Comb_8180.8",
"Comb_8190.9", "Comb_8260.6", "Comb_8270.7", "Comb_8280.8", "Comb_8290.9",
"Comb_8360.6", "Comb_8370.7", "Comb_8380.8", "Comb_8390.9", "Comb_8460.6",
"Comb_8470.7", "Comb_8480.8", "Comb_8490.9", "Comb_8560.6", "Comb_8570.7",
"Comb_8580.8", "Comb_8590.9", "Comb_860.6", "Comb_8660.6", "Comb_8670.7",
"Comb_8680.8", "Comb_8690.9", "Comb_870.7", "Comb_8760.6", "Comb_8770.7",
"Comb_8780.8", "Comb_8790.9", "Comb_880.8", "Comb_8860.6", "Comb_8870.7",
"Comb_8880.8", "Comb_8890.9", "Comb_890.9", "Comb_8960.6", "Comb_8970.7",
"Comb_8980.8", "Comb_8990.9", "Comb_9060.6", "Comb_9070.7", "Comb_9080.8",
"Comb_9090.9", "Comb_9160.6", "Comb_9170.7", "Comb_9180.8", "Comb_9190.9",
"Comb_9260.6", "Comb_9270.7", "Comb_9280.8", "Comb_9290.9", "Comb_9360.6",
"Comb_9370.7", "Comb_9380.8", "Comb_9390.9", "Comb_9460.6", "Comb_9470.7",
"Comb_9480.8", "Comb_9490.9", "Comb_9560.6", "Comb_9570.7", "Comb_9580.8",
"Comb_9590.9", "Comb_960.6", "Comb_9660.6", "Comb_9670.7", "Comb_9680.8",
"Comb_9690.9", "Comb_970.7", "Comb_9760.6", "Comb_9770.7", "Comb_9780.8",
"Comb_9790.9", "Comb_980.8", "Comb_9860.6", "Comb_9870.7", "Comb_9880.8",
"Comb_9890.9", "Comb_990.9", "Comb_9960.6", "Comb_9970.7", "Comb_9980.8",
"Comb_9990.9"), class = "factor")), .Names = c("combination",
"Attribute", "Primary_Weights", "vif", "pvalue", "key"), row.names = 100:200, class = "data.frame")

Thank you very much in advance!
Answer: First of all, it's usually not a good idea to use eval. What you were trying to accomplish with
eval(parse(text = paste0(paste('input$weight', i, sep='_'),"[2]")))

could be done with
text = input[[paste0("weight", i, sep='_')]][2]

instead. But i think your real problem is that in the loop, you do nothing to combine the results of the iteration. You completely reassign tempf each time.
Consider changing
#tempf <- dataset_with_key
tempf <- dataset_with_key[0,]

to create an empty data frame. Then inside your look loop, change
#tempf <- dataset_with_key[dataset_with_key$key %in% tempcond$key,]
tempf <- cbind(tempf, dataset_with_key[dataset_with_key$key %in% tempcond$key,])

Note that I don't actually run shiny myself so I wasn't able to verify this works, but i'm guessing it will at least get you a lot closer to solving the problem.
Comment: MrFlick , concering the first comment you are absolutelly right and thank you very much. But concerning the second the change is not wroking because with the cbind i will always add columns and it not updates. The point with this code is that every time checks which combinations belong in the initial dataset after selecting the ones that the slider criteria satisfy. I think my problem here has to do with the reactive and observe environment but i can not figure it out.

Subsetting table under conditions shiny


Show that $4\cos\frac\pi5\cdot\sin\frac\pi{10}=1$

Question: We have to prove this identity : $$4\cos\frac\pi5\cdot\sin\frac\pi{10}=1$$
The book's hint is we somehow find out that $\displaystyle1+2\left(\cos\frac\pi5-\cos\frac{2\pi}5\right)$ equals something (from the geometry of a regular pentagon) and the result follows. But I can neither see why the book's hint is true nor how it could yield a result for the original problem. So could you help me proving it either by the book's hint or another way?
Comment: Thank you for the trigonometric answers but could you use a complex number approach?
Answer: Given $\displaystyle 2\cos \frac{\pi}{5}\cdot \sin \frac{\pi}{10}\;,$ Now  Let $\displaystyle \frac{\pi}{10} = \theta \;,$ and using $$ 2\sin A\cdot \cos A = \sin 2A$$
Then $$\displaystyle 2\cos 2\theta \cdot \sin \theta=\frac{2\cos 2\theta\cdot \sin \theta \cdot \cos \theta}{\cos \theta} = \frac{2\sin 2\theta \cdot \cos 2\theta}{2\cos \theta} =\frac{\sin 4\theta}{2\cos \theta}$$
So we get $$\displaystyle \frac{\sin 4 \theta}{2\cos \theta} = \frac{\sin \left(\frac{4\pi}{10}\right)}{2\cos \frac{\pi}{10}} = \frac{\cos \frac{\pi}{10}}{2\cos \frac{\pi}{10}} = \frac{1}{2}$$
Bcz  $$\displaystyle \sin \frac{4\pi}{10} = \sin  \left(\frac{\pi}{2}-\frac{\pi}{10}\right) = \cos \frac{\pi}{10}$$
Comment: Why is $\sin(\theta)\cdot\cos(\theta) = \sin(2\theta)$ between 2nd and 3rd term?
Comment: You get the much needed $\frac{1}{2}$ that way, because the solution is $\frac{1}{2}$, not 1 ;)
Comment: Thanks  Inuyaki I have edited it.
Answer: Using Werner Formula, $$2\cos36^\circ\sin18^\circ=\sin54^\circ-\sin18^\circ=\cos36^\circ-\cos72^\circ$$
Now see Proving trigonometric equation $\cos(36^\circ) - \cos(72^\circ) = 1/2$
Answer: HINT:
Notice $$LHS=2\cos \frac{\pi}{5}\sin\frac{\pi}{10}$$
$$=2\cos 36^\circ \sin18^\circ$$  Setting the values of $\cos 36^\circ$ & $\sin 18^\circ$
$$=2\left(\frac{\sqrt 5+1}{4}\right)\left(\frac{\sqrt 5-1}{4}\right)$$
$$=\frac{(\sqrt 5+1)(\sqrt 5-1)}{8}$$
$$=\frac{(\sqrt 5)^2-1^2}{8}$$ $$=\frac{5-1}{8}=\frac{1}{2}$$
Comment: Why is this a HINT ?   I have nothing left to solve on my own.


Dispaly DataFrame in Jupyter Notebook along with other attributes

Question: If I just construct a pandas DataFrame in a Jupyter notebook, then the output looks nice:
frame = pd.DataFrame({'a': [1,2,3]})
frame

However, if I make my own class whose repr is a pandas.DataFrame, then that formatting is lost:
class Foo:
    def __init__(self, frame, bar):
        self.frame = frame
        self.bar = bar

    def __repr__(self):
        return repr(self.frame)

How can I define the repr of my class Foo, such that when I display it in a Jupyter Notebook, it'll look just like it would if it was a pandas.DataFrame?
Comment: did you see this answer
https://stackoverflow.com/questions/26873127/show-dataframe-as-table-in-ipython-notebook
Comment: yes but I can't just return `HTML(df2.to_html())` from `__repr__`, as `__repr__` needs to return a string
Answer: You can add a repr_html() method that incorporates what @Atanas Atanasov was suggesting.
class Foo:
    def __init__(self, frame, bar):
        self.frame = frame
        self.bar = bar

    def __repr__(self):
        return repr(self.frame)

    def _repr_html_(self):
        return frame.to_html()

Below first shows what the OP report and then shows the addition of repr_html() in the bottom Foo class definition ([4] and [5]) fixes it:

It's like what Pandas uses for _repr_html_ in it's style.py where it says at the top it is the "Module for applying conditional formatting to DataFrames and Series".

The Details
The key resource you seek for guidance in making your class integrate well with Jupyter is covered under items like _repr_html_l and/or _repr_mimebundle_ in the 'Integrating your objects with IPython' section in the documentation.
I dug around in the Pandas code and it looked like it would be here where the `repr_html() is defined for Pandas rendering if dataframes. At the top there it says 'Module for applying conditional formatting to DataFrames and Series.'
See example of use of _repr_mimebundle_ here to make a custom class display latex in a Jupyter notebook rendering.
This answer uses the related _repr_html_() to make a custom class to control how an SVG object is rendered in the running .ipynb file so it remains interactive from scripted details embedded in its encoding file.


Limit of the ratio of a nowhere differentiable function to a polynomial

Question: Let $f(x)$ be a continuous function that—

maps the closed interval [0, 1] to [0, 1],
equals 0 at 0,
does not equal 0 anywhere except at 0, and
is nowhere differentiable on its domain.

Let $g(x)$ be a polynomial that—

maps the closed interval [0, 1] to [0, 1],
bounds $f$ from above, and
equals 0 at 0.

My question is: Does the limit $\lim_{x\to 0^+} f(x)/g(x)$ exist?  If not, what are the weakest conditions required on $f$ for the limit to exist?
I know that by L'Hôpital's rule, the limit exists when $f(x)$ is differentiable on some interval $(0, \epsilon)$, but I don't know whether the limit still exists in this case when $f$ is not required to be differentiable.  This question is neither homework nor a self-study assignment, nor is this coursework.
Answer: Let $w(x):[0,1]\to [1/2,1]$ be continuous and nowhere differentiable. Define
$$v(x)=\frac{x}{2}+\frac{x}{4}\sin (\ln x),$$
for $x\in (0,1],$ with $v(0)=0.$ Then $v$ is differentiable on $(0,1]$ and $v$ is continuous on $[0,1].$ Note that $x/4\le v(x)\le 3x/4.$
Set $f(x) = v(x)w(x)$ and $g(x)=x.$ Then $f,g$ satisfy the given conditions. The only condition that's not immediately clear is that $f$ is nowhere differentiable. To verify it, let $x\in (0,1]$ and suppose $f'(x)$ exists. Then $(f/v)'(x)$ exists, i.e., $w'(x)$ exists. That's a contradiction. To check $x=0,$ observe
$$\frac{f(x)}{x} = w(x)\left(\frac{1}{2}+\frac{1}{4}\sin (\ln x)\right).$$
As $x\to 0^+,$ $w(x)\to w(0)\ne 0,$ and the factor on the right oscillates between $1/4$ and $3/4.$ This oscillation shows $f'(0)$ fails to exist. Thus $f$ is nowhere differentiable, and of course this also shows $\lim_{x\to 0^+} f(x)/g(x)$ fails to exist.
Comment: Thank you for the example.  Can you find an example where the limit does not exist even if $f$ is Lipschitz continuous?  (I know a Lipschitz continuous function is differentiable almost everywhere, but not whether it can be differentiable except on a _dense_ set of measure zero or whether $f$ is differentiable on (0, $\epsilon$) whenever it is Lipschitz continuous on [0, 1].)
Comment: Take $f(x)=v(x)$ where $v(x)$ is as above, and $g(x)=x.$ Check that $v'(x)$ is bounded, hence $v$ is Lipschitz.


show that if $S$(finite) spans $V$(finite), (but not basis) then $S$ can be reduced to a basis for $V$ by removing appropriate vectors from $S$

Question: $\mathbf{\text{Problem} \ 18:}$ Suppose that $S$ be a nonempty finite set of vectors in a finite dimensional space $V$. Use $\mathbf{problem \ 16}$ to show that if $S$ spans $V$, but is not a basis for $V$, then $S$ can be reduced to a basis for $V$ by removing appropriate vectors from $S$.
$\mathbf{\text{Problem} \ 16:}$
Show that $S = \{x^4, x^4-x^3, x^4-x^3 + x^2, x^4-x^3 + x^2 -x, x^3-1\}$ is a basis for $P_4$. Also, write $P = 1+2x-3x^2+x^3$ as a linear combination of the vectors from this basis.
OK, I already was able to show $16$ by forming a matrix out of each vector and getting a $\text{determinant} = -1$, then row reducing it and solving with $P$ to get a linear combination, but I am having trouble figuring out $18$, and how I'm supposed to "use" $\text{problem} \ 16$ to show what it wants.
It looks like its saying show that if $S$ spans $V$, but is not a basis for $V$ (I'm guessing this only means it's not $LI$), then $S$ can be reduced to a basis for $V$ (I'm guessing somehow make the set $LI$) by removing appropriate vectors from $S$ (I'm also lost on this part, how does one remove appropriate vectors to make a basis? what rules must I follow?)
and how do I apply $\text{problem} \ 16$ to these things I'm supposed to do which looks like it must be in a general proof?
Answer: Hint:  Show that if $S$ is linearly dependent then some vector in $S$ is a linear combination of the other vectors in $S$ (assume you have a dependence relation and pick the first vector with a nonzero coefficient).  Show that removing this vector from $S$ does not change the span.
Without a specific vector space $V$ I'm not sure how problem 16 is supposed to apply directly.  Maybe they just meant for you to be motivated by how you solved 16.
Comment: when you say "(assume you have a dependence relation and pick the first vector with a nonzero coefficient)" how can I pick the "first vector" while showing it in a general sense? do you mean something like: assume v = k1v1 + k2v2 +...+ knvn, with k1 =/= 0, k2...kn = 0, then remove this vector and show it spans? I actually don't even see how this still spans, forgive me if I'm forgetting something obvious right now..
Comment: Lets say your basis is $\{v_1, \ldots, v_n\}$.  Assume you have an expression $k_1v_1 + \cdots + k_nv_n = 0$ such that not all $k_i$ are zero.  Choose any $i$ such that $k_i \neq 0$ (first, last, or whatever.  All that matters is that there's *some* such $i$) and write $v_i = \frac{1}{k_i}(-k_1v_1 - \cdots - k_{i - 1}v_{i - 1} - k_{i + 1}v_{i + 1} - \cdots - k_nv_n)$.  Now you need to show that anything spanned by $\{v_1, \ldots, v_n\}$ is also spanned by $\{v_1, \ldots, v_{i - 1}, v_{i + 1}, \ldots, v_n\}$.  Do this by substituting in the above expression for $v_i$.
Comment: which above expression exactly?


VPN Error - Enable GRE protocol

Question: I am trying to setup a VPN on my small home network (windows 2003).  My home Vista machine is returning me Error 806 and is saying something about enabling the GRE protocol.
I have one nic inside my windows 2003 machine.  It has a static ip of 192.168.1.110
Things I have done

I was able to setup the VPN through the Configure Your Server Wizard.
I have enabled port 1723 through my router.

When I try to run Windows Firewall for Win2k3 I get a nice message telling me that Windows Firewall cannot run because another program or service is running that might use the network address translation component (Ipnat.sys)
I then went into Routing and Remote Access and from there I am completely lost.
Any help would be greatly appreciated.  I was having some bad luck with Google other than finding this great site.
Answer: In addition to TCP port 1723, you're going to need to enable IP protocol 47 to pass through your router/firewall -- this is for GRE, and could be the source of the error.
Can you describe your network further?  You have a windows 2003 box w/ one NIC, so it sounds like it's connected directly to your router which is performing nat and has firewalling capability (which is what you've enabled port 1723 to be forwarded through)?  Is this about right?
Additionally, is there any security software (i.e., a suite with a personal firewall) installed on the box that may be interfering with the windows firewall?
Comment: 1) That is correct, the windows server is connected to my router
2) Currently no other security software installed, I also disabled my firewall on my vista machine to take out that variable for now.
Answer: There are quite a few things to setup.  Here is the site I used as a reference when I setup mine.
http://www.howtonetworking.com/VPN/2003vpn11.htm
Answer: Not every router supports the GRE protocol.  You might want to check first to see if it's something your hardware/current firmware version can support.

VPN Error - Enable GRE protocol


Best way to set up data architecture

Question: I have a system where (to start) I have three types of data I need to store. I'm familiar with relational databases so I'm going to describe it in those terms. The Author table just has a couple columns like a primary key, and a few text fields (it's info about an author). Location has a similar structure to Author, but it's for different data (info about locations). Article is basically what links the two together. It has some regular text data, but also has foreign keys to both Author and Location (it's an Article written by Author about Location).
I've played with two ideas for how to represent this in Drupal. First with the Field API creating content types. The main problem here is that I'm not sure how to set it up so that Article has the proper relations to Author and Location.
The second approach I'm considering is using the Entity API module, but I'm not really very familiar with the module. However, I am very comfortable using hook_schema() to set up the tables and relationships. From there, I'm not sure if Entity API has much useful in the way of making the data manageable like a content type or if I'd have to write that all by hand to begin with.
Am I looking at this all wrong? What is the drupal way?
Answer: There are quite a few possibilities to deal with this.
To get an overview:

The advantage of custom entities is that they don't come with all the overhead that nodes have. They're especially well suited for storing and managing completely custom data that you might not even want to display and you have full control over them (their data structure, workflows, UI). The commerce project for example defines own entities for orders, products, line items and so on.
Nodes are still the main content pieces. They provide various features that you don't yet get for free with custom entities, like revisioning and comments. Various additional modules focus on nodes. In short, you get a ton of features, but have to live with the overhead that comes with them. Every additional data structure you need is a field, living in it's own table, and so on.
Entity API provides a lot of features for custom entities, for example CRUD and allows you to easily integrate with various important tools like Views and Rules. It's definitely worth to rely on it, see http://www.trellon.com/content/blog/creating-own-entities-entity-api for a nice introduction.
To connect entities (Hint: nodes are entities as well), you can for example use  Entity reference (simple, directed relationship) or Relation (flexible, unidirectional relation between entities which is an fieldable entity on it's own).

Some specific tips based on that:

Article sounds like a perfect use case to use nodes/a content type to me. People need an UI to create them, you might need revisions, maybe comments, they need to be displayed, probably want nice aliases (Pathauto) for them and so on.
Author; Here you have a bunch of options. Nodes have an author by default, the user that created them. Users can have fields as well and can have a public profile, so your authors could actually be users. Especially if your authors are going to be the uses which will create the articles on your site themself. If not, then this might not be a perfect match because changing the author of a node requires administrative permissions. If not, you could either use another content type if you think that makes sense or create a custom entity.
Location: The traditional answer are certainly taxonomies. They're still a good match to categorize content, provide a number of possibly useful features out of the box, like hierarchy (so you could do do Country > State > City), auto-create new locations from a autocomplete widget and a list of nodes attached to them. And, they're fieldable entities too (surprise!), so you can store additional information for them as well.

So, to me it sounds like the default entities provided by Drupal core are a pretty good match for your data.
Comment: I think that might be a bit too simplistic for Location. But perhaps I don't know enough about taxonomies. Can you still have meta-data associated with a specific taxonomy? Things like images, descriptions, etc.
Comment: The key is that all three need to be independent of the others in addition to the specified relationships. With that, simple content types might be the best solution given things like Entity reference (that seems perfect actually).
Comment: Yes, you can add fields (including images) to taxonomy terms, and a description actually exists by default. But you could of course also create a Location entity type and connect those using an entity reference.

Best way to set up data architecture


strip out everything out side of  and random text in html

Question: I am trying to strip data out of a web page using a c# http module. I just want raw text and images. How can I strip everything else out?
private static Regex reg = new Regex(@"<img src=\t????????");

public override void Write(byte[] buffer, int offset, int count)
    {
      byte[] data = new byte[count];
      Buffer.BlockCopy(buffer, offset, data, 0, count);
      string html = System.Text.Encoding.Default.GetString(buffer);

      html = reg.Replace(html, string.Empty);

      byte[] outdata = System.Text.Encoding.Default.GetBytes(html);
      _sink.Write(outdata, 0, outdata.GetLength(0));
    }

Comment: @Blender - An HTML parser would be a better choice.
Comment: @user719825 - Comments are not answers.
Comment: [obligatory](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)
Comment: Yeah, I know it's not an exact duplicate, but the accepted answer still answers this one: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454
Comment: that thread is spammed to high hell. Any other solutions, such as which XMl parser to use???
Comment: We're not spamming you. Read the responses to the linked questions to see *why* you don't parse HTML/XML with regex. @Oded, I don't even know a bit of C#, and in Python, there's only an XML parser :P
Comment: @user719825 This is a Q&A site, *not* a forum. Using `???` won't speed up getting a *good* answer.
Comment: @Blender - Fair enough. Most XML parsers will choke on good HTML unless it was specifically written as XML.
Comment: @Oded: Really? I thought HTML was a subset of XML, so an XML parser would parse HTML also. I'd better read up on that...
Comment: @Blender, HTML does is often not valid XML. Consider the simple case of ``, which is perfectly legal for browsers, but for it to be valid XML, would need a closing. ``.
Comment: Im using htmlagilitypack now, but I can only get it to load via an actual page. How would I take the data in a buffer (before the page renders on the browser?)
Comment: @Blender: You're probably thinking of XHTML, which is the other way around (XHTML is a subset of XML).
Comment: @MerlynMorgan-Graham: Yep, that's what my `` says. *Successful question subject diversion!*
Comment: Lol :)  @user719825: Don't use an XML parser unless you want to verify standard conformance, and are sure all your documents (should) be valid XHTML: See the difference between SGML-based HTML and XML-based HTML here - http://en.wikipedia.org/wiki/HTML#SGML-based_versus_XML-based_HTML
Answer: Use an HTML parser, such as the HtmlAgilityPack.
Comment: Im using that now, but I can only get it to load via an actual page. How would I take the data in a buffer (before the page renders on the browser?)
Comment: Is there a `Render` method you could override? (Can't remember if that's just for `Page`s or not).