How to create apt repository on Windows?

Question: We have Windows server (1) with Internet access and Windows server (2) without Internet access in PAN. Also we have Linux machines in PAN (Debian, Ubuntu, ...).
Linux machines must be up to date, but there is no Internet access in PAN. How to download updates to server (1) from official mirrors? Then it will be transfered to server (2) on flash drive. On server (2) there will be HTTP/FTP sever to downloaded files.
In other words,
1) How to download all apt repository data on Windows from apt get repository?
2) How to setup apt repository on Windows with just downloaded from another computer files?
Comment: Maybe duplicate from:
http://serverfault.com/questions/217667/host-a-debian-repository-on-a-windows-web-ftp-server
Answer: I think same steps as Linux machines,
Install HTTP or FTP server (I would use Apache HTTPD), and do a rsync from official mirrors.
Regards


XGBoost vs Python Sklearn gradient boosted trees

Question: I am trying to understand how XGBoost works.  I already understand how gradient boosted trees work on Python sklearn.   What is not clear to me is if XGBoost works the same way, but faster, or if there are fundamental differences between it and the python implementation.
When I read this paper
http://learningsys.org/papers/LearningSys_2015_paper_32.pdf
It looks to me like the end result coming out of XGboost is the same as in the Python implementation, however the main difference is how XGboost finds the best split to make in each regression tree.
Basically, XGBoost gives the same result, but it is faster.
Is this correct, or is there something else I am missing ?
Answer: You are correct, XGBoost ('eXtreme Gradient Boosting') and sklearn's GradientBoost are fundamentally the same as they are both gradient boosting implementations.
However, there are very significant differences under the hood in a practical sense. XGBoost is a lot faster (see http://machinelearningmastery.com/gentle-introduction-xgboost-applied-machine-learning/) than sklearn's. XGBoost is quite memory-efficient and can be parallelized (I think sklearn's cannot do so by default, I don't know exactly about sklearn's memory-efficiency but I am pretty confident it is below XGBoost's).
Having used both, XGBoost's speed is quite impressive and its performance is superior to sklearn's GradientBoosting.
Comment: Relevant Q&A on Datascience: [Why is xgboost so much faster than sklearn](https://datascience.stackexchange.com/questions/10943/) and here os Stats: [XGBoost Loss function Approximation With Taylor Expansion](https://stats.stackexchange.com/questions/202858)
Comment: There is also a performance difference. Xgboost used second derivatives to find the optimal constant in each terminal node. The standard implementation only uses the first derivative.
Comment: Confirmation to @K88's post, sklearn's [GradientBoostingClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html) does not have a `n_jobs` interface parameter available; parallel processing is not possible internally with sklearn's implementation of the algorithm.
Comment: @Zelazny7 Do you have any references for your statement ?  One would expect that calculating 2nd derivatives would degrade performance.  It also would mean that something besides (any flavor of)  gradient descent was used.
Comment: https://medium.com/towards-data-science/boosting-algorithm-xgboost-4d9ec0207d
Answer: Unlike the Sklearn's gradient boosting, Xgboost does regularization of the tree as well to avoid overfitting and it deals with the missing values efficiently as well. Following link might be helpful to learn xgboost precisely https://www.youtube.com/watch?v=Vly8xGnNiWs
Comment: SkLearn's GBM does regularization via the parameter learning_rate.
Comment: scikit-learn's `HistGradientBoosting[Classifier|Regressor]` classes support NaNs. https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.HistGradientBoostingRegressor.html#sklearn.ensemble.HistGradientBoostingRegressor
Answer: XGboost is implementation of GBDT with randmization(It uses coloumn sampling and row sampling).Row sampling is possible by not using all of the training data for each base model of the GBDT. Instead of using all of the training data for each base-model, we sample a subset of rows and use only those rows of data to build each of the base models. This ensures that there is a lesser chance of overfitting which is a major issue with simple GBDT which XGBoost tries to address using this randomization.


generate qrcode with base64 php html

Question: so I have this PHP code to generate QR code in WordPress but some tax roles required the code to be in base64 so I want to make my code work with Hexadecimal Encode 64 and utf8
any help?
my code
<?php
        $barcodetype = (get_option('plugindistrict_orderbarcodes_barcodetype') == '' ? 'qrcode' : get_option('plugindistrict_orderbarcodes_barcodetype'));

?>

                 <img class="pd_order_barcode" style="margin-top: -155; margin-right: 50; width:20%  " src="https://2tfh7u96zl.execute-api.us-east-1.amazonaws.com/added-jest-tests/barcode?type=<?php echo $barcodetype.'&value='.(($barcodetype == 'qrcode') ? $checkinpath .'Name:Sleep Blue'.'%0A'.'Tax No:302188012300003'.'%0A'.'Bill NO:'.$this->get_formatted_number().'%0A'.'Date-Time:'.$this->get_formatted_date().'%0A'.'Bill Amt With Vat:'.$order->get_total().'%0A'.'Vat Amt:'.$order->get_total_tax(): $order).'&includeText='.(get_option('plugindistrict_orderbarcodes_showtextupc') == 1 ? 'true' : 'false'); ?>" />

``

Comment: What have you tried to make it work? What exactly is not working as expected?
Comment: I want to make the code generate the QR with base64, the  PHP code work without problem just want to add some lines to make  it  generate base64
Comment: Please add all clarification to your question by editing it. If everything works without problem, what is your question?
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: the best way to generate a dynamic QR code and display.
you may use the google API which you don't need to convert into base64 / save the file.
To use this , basically:

https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=http%3A%2F%2Fwww.google.com%2F&choe=UTF-8

300x300 is the size of the QR image you want to generate,
the chl is the url-encoded string you want to change into a QR code, and
the choe is the (optional) encoding.
The link, above, gives more detail, but to use it just have the src of an image point to the manipulated value, like so:

Result.

generate qrcode with base64 php html


Query multiple tables to find duplicate one to one relation (group by multiple column from diffeerent tables)

Question: I have 2 tables
table1:

id
columnA

1
one

2
two

3
one

table2 :

table1_id
columnB

1
row1

2
row2

3
row1

Is it possible to have a single query to fetch me the id from table1 where duplicate value in columnA also has duplicate value in columnB:
Like in this example, id 1 and 3 from table1 has duplicate values in columnA as well as columnB
Comment: Yes sorry typo.
Answer: SELECT GROUP_CONCAT(table1.id)
FROM table1
JOIN table2 ON table1.id = table2.table1_id
GROUP BY table1.columnA, table2.columnB
HAVING COUNT(*) > 1

Answer: If it's ok to have Ids from same group as comma separated column then you can use below query (It will ensure that both table has same number of duplicate ids for a given columnA or columnB value):
Schema (MySQL v5.7)
create table table1 (id int, columnA varchar(20));
insert into table1 values(1,'one');
insert into table1 values(2,'two');
insert into table1 values(3,'one');
create table table2 (table1_id int, columnB varchar(20));
insert into table2 values(1,'one');
insert into table2 values(2,'two');
insert into table2 values(3,'one');

Query #1
select a.ids from
(SELECT GROUP_CONCAT(id) ids
FROM table1
GROUP BY columnA
HAVING COUNT(*) > 1) a
inner join
(SELECT GROUP_CONCAT(table1_id) table1_ids
FROM table2
GROUP BY columnB
HAVING COUNT(*) > 1) b
on a.ids=b.table1_ids;

ids

1,3

View on DB Fiddle
Comment: Thank you. This actually will help me with more complex queries. Already accepted Akina's answer but this helps a lot too.
Comment: No issues. That's more efficient. That's even better answer if number of duplicate items per table is not important to you. If table1 has three rows for one (1,3,4) and table two has two rows for row1 (1,3) and your desired output is (1,3) then Akira's answer is the right one. Best wishes
Comment: @Akina That's what I have explained in my answer and comments. My answer will only generate answer if both table have same set of duplicate ids.


Bazel build command ambiguous stdout/stderr while piped

Question: In a typical Bazel project, running bazel build :main, for example, causes this output in the terminal:
Analyzing: target //:main (0 packages loaded, 0 targets configured)
    currently loading: @bazel_tools//tools/cpp
    Fetching @rules_cc; fetching 5s

But when it's piped to a file (bazel build :main 2>output.txt), the content of output.txt is similar to:
Analyzing: target //:main (0 packages loaded, 0 targets configured)
Analyzing: target //:main (0 packages loaded, 0 targets configured)
Analyzing: target //:main (0 packages loaded, 0 targets configured)
Analyzing: target //:main (0 packages loaded, 0 targets configured)
Analyzing: target //:main (0 packages loaded, 0 targets configured)
Analyzing: target //:main (0 packages loaded, 0 targets configured)
Analyzing: target //:main (0 packages loaded, 0 targets configured)

It is also what I see in the gitlab CI frontend. (Since it has piped the output of the command...).
I've got two questions:
1. How can I capture the details of Analyzing; like what is being fetched now? (i.e. how to capture the exact same outputs?)
2. What does 0 packages loaded mean? What about configuring a target?
Comment: Any idea about the 2nd question? What does `configuring` mean in Bazel?
Answer: I'm not 100% sure this does everything you care about, but I would approach this using the Build Event Protocol, which will either write out a file (see --build_event_binary_file and --build_event_text_file) describing all the actions that were taken by Bazel, or it will open a gRPC connection to a server of your choosing (see --bes_backend) and emit the events there. Trying to parse the stdout/err of the binary definitely doesn't contain all the information you desire.
If there are things missing from the BEP output, I would file a bug against Bazel and ask if they'll add an event for it.
Good luck!
Comment: I'm going to try it. I'll come back soon with the result. Thanks.
Comment: I tried that. Some good info. But still, I don't see what was fetching? (I expect the URLs or something like that.
Comment: If you think there is more information that should be included in the BEP output, I think filing an [issue](https://github.com/bazelbuild/bazel/issues/new) to have it added is probably the best course of action. If you could comment on here with a link to your issue I would love to follow along
Comment: Thanks. I issued that: https://github.com/bazelbuild/bazel/issues/10343
Comment: Any idea about the 2nd question? What does `configuring` mean in Bazel?


NameError while calling another function inside a function

Question: Why am I getting a name error for pays_bill?
error: NameError: name 'pays_bill' is not defined

class Customer:
    def __init__(self,total):
        self.billamt=total

    def pays_bill(self,amount):
        print("maaz  pays bill amount of Rs.",amount)

    def purchases(self):
        discount=(.05*self.billamt)
        amount=(self.billamt-discount)
        pays_bill(self,amount)

x=Customer(1000)
x.purchases()

Comment: You need to use `self.pays_bill(...)`
Comment: thanks a lot brother. really thanks a lot
Answer: This will work fine
class Customer:
    def __init__(self,total):
        self.billamt=total

    def pays_bill(self,amount):
        print("maaz  pays bill amount of Rs.",amount)

    def purchases(self):
        discount=(.05*self.billamt)
        amount=(self.billamt-discount)
        self.pays_bill(amount)

x=Customer(1000)
x.purchases()


Java HashMap containsKey() fails

Question: I have a Java HashMap<String, String>. Firstly I populate this map with 100 known string keys. Next I use multiple callables to add random string keys, two thousand keys in total. I also use multiple callables to call HashMap.containsKey() for the 100 known keys. I execute these callables all concurrently, Why do I see many of these containsKey() calls fail? Surely String implements the hashCode() and equals() methods "properly".
What do I need to do to ensure my 100 known keys are always found within the map?
Comment: Are you *adding* to the map concurrently? Bear in mind that `HashMap` isn't thread-safe. Can you show a short but complete program demonstrating the problem?
Comment: As @JonSkeet says, you cannot modify a `HashMap` from multiple threads concurrently, nor can you read from a `HashMap` while another thread performs an update.  You will either need to wait until the last items have been added before querying the map, or you will need to use a concurrency-safe map.
Comment: @Hector If you're adding the rest of the keys from multiple threads, HashMap will inevitably malfunction.
Comment: Looks like some `Callable`s are performing lookups on your `Map` before all the keys are set.
Comment: Yes, I am adding keys in multiple callables, however the 100 known keys are all added "up front", before I start any of the callables
Comment: Well then, it would be better if you use a proper distribute cache library like ecache or infinispan instead of brewing your own. Or probably use another alternative like Hazelcast.
Comment: Maybe [`ConcurrentHashMap`](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html) (concurrent analog of `HashMap`)?
Comment: Oh dear, my issue is this hashmap is cached across multiple servers ... So making it a concurrency safe map is going to be tricky. The processing requires new keys are added all the time while I also need to be calling contains key
Comment: I am using dynacache on my servers, however just to prove hashmap was easily breakable I brewed my own test. I feel my issue is caching a hashmap of  as a single cache entry within dynacache, where as I should add each of my string keys as a dynacache entry in their own right
Comment: Will concurrentHashMap work when cached in dynacache across multiple nodes?
Answer: All my issues were solved by simply changing my use of HashMap() to ConcurrentHashMap().

Java HashMap containsKey() fails


webpack.ProvidePlugin angular

Question: I am trying to use angular NG6 starter. in its source code, import angular from angular is written almost every js file. So I try this:
 new webpack.ProvidePlugin({
      // $: "jquery",
      // jQuery: "jquery",
      // "window.jQuery": "jquery",
      'angular': 'angular',
    }),

But it can not work. I dont know why, and how to solve this issue.
Comment: Did you run `npm install`?
Answer: Here the solution to the first error message in your screenshot "angular.module is not a function": Angular 1 is not working nicely with webpack without a shim (see https://github.com/webpack/webpack/issues/2049). Try this webpack loader config:
module: {
    loaders: [
        /*
         * Necessary to be able to use angular 1 with webpack as explained in https://github.com/webpack/webpack/issues/2049
         */
        {
            test: require.resolve('angular'),
            loader: 'exports?window.angular'
        },
    ]
},
plugins: [
    new webpack.ProvidePlugin({
        'angular': 'angular',
    }),
],

This should initialize the angular object properly instead of the default action of setting it to an empty object (which does not have a property named module).
Answer: U need to use sth like this:
var app = angular.module('RequiredName', ['ui.router','ui.bootstrap']);
and use this on app file and call your app module like  in the parts of project that u are going to use any function or method implemented in your app.js file in app.factory or app.controller or...

webpack.ProvidePlugin angular


puppet not signing cert or getting new requests

Question: I am not sure how to word the question, so here is the problem:
I have a brand new install of puppet-server and puppet using v2.6.16 and running on 2 nodes (puppet and puppet-agent, respectively) following the steps at http://docs.puppetlabs.com/guides/installation.html for a Linux box (CentOS).
On the puppet[-server] box, I issue puppetca -la and get back:
+ puppet (DB:50:1B:37:47:78:DA:F2:69:28:B7:E2:22:1B:C5:28) (alt names: DNS:puppet, DNS:puppet.abc.com)

(note that puppet-agent is not listed) ... also, no puppet instances are listed with puppet cert list
When signing the box with puppetca --sign puppet, I get:
err: Could not call sign: Could not find certificate request for puppet

Same with puppetca --sign puppet.abc.com
There is a puppet.pem in the private_keys and certs directory.  The certificate_requests directory is empty.  Auto-signing is off.
I'd be happy to supply any additional information and would appreciate any assistance.
The puppet.conf on both machines is as follows, sans comments:
[main]
  logdir = /var/log/puppet
  rundir = /var/run/puppet
  vardir = /var/lib/puppet
  factpath = $vardir/lib/facter
  ssldir = $vardir/ssl
  server = puppet.abc.com
  dns_alt_names = puppet, puppet.abc.com
  pluginsync = true

[agent]
  classfile = $vardir/classes.txt
  localconfig = $vardir/localconfig

[master]
  templatedir = var/lib/puppet/templates

EDIT DUE TO COMMENTS

Master is running
Agent can contact master via hostname
Agent CANNOT telnet to 8140 on master -- master is listening on 0.0.0.0:8140 with iptables and selinux off
May 14 13:40:13 puppet-agent puppet-agent[25920]: (/File[/var/lib/puppet/lib]) Failed to generate additional resources using 'eval_generate': SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
May 14 13:40:13 puppet-agent puppet-agent[25920]: (/File[/var/lib/puppet/lib]) Could not evaluate: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed Could not retrieve file metadata for puppet://puppet.abc.com/plugins: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
May 14 13:40:14 puppet-agent puppet-agent[25920]: Could not retrieve catalog from remote server: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
puppet agent --test yields:
dnsdomainname: Unknown host
info: Retrieving plugin
err: /File[/var/lib/puppet/lib]: Failed to generate additional resources using 'eval_generate': SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
err: /File[/var/lib/puppet/lib]: Could not evaluate: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed Could not retrieve file metadata for puppet://puppet.abc.com/plugins: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
dnsdomainname: Unknown host
err: Could not retrieve catalog from remote server: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
warning: Not using cache on failed catalog
err: Could not retrieve catalog; skipping run
May 14 13:40:14 puppet-agent puppet-agent[25920]: Using cached catalog
netstat produces ruby/puppet in a LISTEN state and the agent in a TIME_WAIT
Comment: My advice, forget about the puppetca commands. That's old stuff and will just confuse the issue. Modern versions of Puppet, such as the one you're using, do everything via `puppet` subcommands, such as `puppet cert`. See `puppet help` for the list of available commands.
Comment: The certs were out of sync ... issuing the following on the agent resolved the issue: find /var/lib/puppet -type f -print0 |xargs -0r rm
Answer: Any open signing requests should be listed in puppet cert list on the master. If they don't show up there, there's no use trying to sign them. Once signed, they disappear from the list and will only show up in puppet cert list --all.
It appears your master is not receiving signing requests from the agent, since your list is empty There is a number of things that could be wrong. Let's start with these:

Is the master running?
Does the hostname 'puppet' or 'puppet.abc.com' resolve from the agent?
Is TCP port 8140 on the master reachable from the agent (try: telnet puppet 8140)?
What does syslog on the agent say?
Try puppet agent --test on the agent, which will attempt to connect to the master and stay in foreground to show the output.
Comment: Adjusted question with results of your comments.  Thanks!
Comment: Resolved the issue with troubleshooting steps above ... giving answer.  Thanks!
Comment: puppet cert is highly depend on DNS (FQDN). So make sure you have proper DNS entry and PTR entry.


How do I trigger an event when a button is clicked on a user profile?

Question: Let's say I want to make a bunch of nodes based on what's in a specific field when someone clicks a button on their user profile.
Is this possible with a custom built module? And if so what hook would I use to display that button on the user profile, and how would I get it to call a custom function on click?
Answer: Yes a custom module could accomplish this. I'd use drupal's form api to create a simple form and output it to a block that you display on user profile pages. The code below should get you started.
Create the form. The hidden element is grabbing the users id from the url.
function my_module_form($form, &$form_state) {
  $form = array();

  $form['uid'] = array(
    '#type' => 'hidden',
    '#value' => arg(1),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  return $form;
}

function my_module_form_submit($form, &$form_state) {
  $uid = $form_state['values']['uid'];
  // do some stuff
}

Now use hook_block_info and hook_block_view to create a new block containing your form.
/**
 * Implementation of hook_block_info().
 */
function my_module_block_info() {
  $blocks['my_module'] = array(
    'info' => t('My Name'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function my_module_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my_module':
      $block['subject'] = t('My Title');
      $my_form = drupal_get_form('my_module_form');
      $block['content'] = drupal_render($my_form);

      break;
  }
  return $block;
}

Here's an article on creating a module in D7 if you are not familiar with how to do that. http://www.justinphelan.com/post/how-write-your-own-module-drupal-7
Answer: Wow, this is a question with many solutions. Some stuff I can quickly think of:
Developers way:

create a custom module: https://www.drupal.org/developing/modules/7
implement hook_menu to create callbacks for your links
implement your logic in the callback functions defined for your entries in hook_menu.
"presentation layer". Depending on the structure of your website and your profiles:
a) Create a block with your links in it, references: block_example, link function
b) Implement a "pseudo field" on fieldable entities (e.g. user, profile2)
c) Use link function in your profile template file e.g. user-profile.tpl.php

extra points might be awarded if you use the link function and your hook menu implementation together with the ajax framework. example.
Site builders way (one way.. there are many):

create a flag
create a rule for flagging items
in that rule implement your logic
optional: undo the flagging (so the user can do this action again)

All of the mentioned solutions will probably require some logic for handling the access and display of that button as well.
(one) developer way, if this button appears on user/id:
<?php
global $user;
if (arg(0) == 'user' && arg(1) == $user->uid && null === arg(2) {
  print l('do something', 'yourcallballback/' . arg(1));
}

site builders way (for the example from above):
usually there's no additional access check required here, you can setup that flag to be global and only clickable once if you want to make sure that it's only available once. for the display part you probably really have to use code to only show that flag if the current user visits his own profile.


Login PHP e MySql gerando erro mysqli_fetch_array()

Question: Bom dia!
Tenho o seguinte código para fazer login no sistema:
<?php

require_once('conexao.php');

// FETCH DATA FROM FORM USING METHOD POST
// IF BUTTON NAME "LOGIN" IS SET
if (isset($_POST['login'])) {

// FETCH DATA FROM INPUT FIELD
$user = mysqli_real_escape_string($conexao, $_POST['usuario']);
$pass = mysqli_real_escape_string($conexao, $_POST['password']);

  // CHECK ALL FIELD HAS BEEN FILLED UP
 if ($user && $pass) {

   // QUERY FROM DATABASE
  $query= mysqli_query($conexao, "SELECT * FROM usuarios WHERE usuario='".$user."'");
  $checkuser= mysqli_num_rows($query);

   // CHECK IF USERNAME EXIST ON DATABASE
  if($checkuser != 1) {

    // I'LL BE SETTING A VARIABLE IF YOUR DOESN'T EXIST
   $error = "Username doesn't exist in our database!";
  }

   // FETCHING PASSWORD IN DATABASE WHERE USERNAME COINCIDES
  while ($row = mysqli_fetch_array($user)) {
   $checkpass= $row['senha'];

    // CHECK IF ENTERED PASSWORD MEETS THE USERNAME PASSWORD
   if ($pass== $checkpass) {

     // IF ALL OKAY SET SESSION
    setcookie("usuario", $user, time()+7200);
    $_SESSION['usuario'] = $user;
    $_SESSION['start'] = time();
    $_SESSION['expire'] = $_SESSION['start'] + (60 * 60 * 60);
    header("Location: ../admin.php");
    exit();
   } else {

     // SET VARIABLE THAT'LL SHOW IF USER PASSWORD IS INCORRECT
    $error = "Incorrect password!";
   }
  }
 } else {

  // SET VARIABLE IF ALL FIELD ARE NOT FILLED UP
 $error = "Please enter a username and password.";
 }
}

?>

Ao tentar logar-se, na página de "login.php", recebo o seguinte erro:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, string given in C:\xampp\htdocs\projetoqa\php\checklogin.php on line 32

Answer: Tente isso:
while ($row = mysqli_fetch_array($query))

O primeiro parâmetro de mysqli_fetch_array() deve ser um resulttypee não uma string, que é a variável $user.
Na sua lógica, coloque tudo que vem depois da checagem do usuário dentro de um else:
if($checkuser != 1) {
    // I'LL BE SETTING A VARIABLE IF YOUR DOESN'T EXIST
    $error = "Username doesn't exist in our database!";
}
else {
    $row = mysqli_fetch_array($query);
        ....

Se não esse código será executado quando o usuário não for encontrado e poderá resultar em erro. E como sua query deve retornar apenas um registro, o while não é necessário.
Comment: @RodrigoBRF nesse caso o correto seria você criar um arquivo onde você checa pela sessão que você criou no processo de login. Se ela estive *vencida* você dá acesso negado. Esse arquivo você tem que incluir em toda página com acesso restrito, no início. Eu geralmente salvo - nesse mesmo arquivo - o horário que o usuário acessou, mas antes checo se já faz mais de 5 minutos - ou o tempo que preferir - que foi acessado, então a sessão é invalidada.
Comment: perfeito! pesquisarei mais à fundo à respeito depois que terminar o resto da programação. obrigado!
Comment: Perfeito! Obrigado pela ajuda! Deu certinho! Outra duvida, não sei se pode ser sanada por aqui mesmo. No meu sistema, caso o usuário troque a url para o lugar que loga, no caso "admin.php", ele consegue acessar sem logar-se. Certo? É algo relacionado com este código aqui? Ou algum outro procedimento?
Answer: Você precisa passar $query para mysqli_fetch_array ao invés de passar a varíavel $user.
Comment: Obrigado amigo! Funcionou com sua dica!


Recarregar após atualização

Question: Estou fazendo uma alteração de status em meu banco de dados usando $.getJSON, está dando certo, mas no retorno preciso atualizar a div onde estão os dados e não estou conseguindo realizar essa tarefa, vejam o código abaixo:

Comment: `.load(URL)` tem um parâmetro obrigatório, uma URL que irá retornar essa lista `li`, `$.getJSON(URL, json, functionSucess)` pelo que entendi, vc quer carregar a lista `li` depois de fazer o 'MarcaItemFoto.php'? 'MarcaItemFoto.php' retorna o que?
Comment: Olá bigown, boa noite, ele me retorna o status da operação, sendo true/false ai trato a mensagem se for um erro, senão gostaria de atualizar a lista.
Answer: Há dois problemas em potencial com o seu código:

Você parece estar tratando somente de condições de erro no callback (função anônima que você passa como parâmetro pro getJSON), mas não condições de sucesso. Além disso, como mencionado por @marcusagm, essa função só será chamada se a requisição tiver sucesso, ainda que a lógica do seu programa não tenha. Se houver um problema com a requisição em si (ex.: timeout, 404 não encontrado, 500 erro interno no servidor, etc) nenhum código será chamado.
Para corrigir isso, sugiro passar também um callback para erros. Se estiver usando uma versão recente do jQuery, o ideal seria:
$.getJSON(url, parametros)
    .done(function(resposta) { /* sucesso */ })
    .fail(function() { /* erro */ });

Se quiser mesmo uma única função pra tratar erro ou sucesso, pode usar o then:
$.getJSON(url, parametros).then(function(resposta) {
    /* sucesso ou erro */
});

As requisições Ajax, como o próprio nome diz, são assíncronas. A chamada de getJSON retorna antes mesmo dela ter sido realizada (e completada). Por isso, qualquer código que você coloque depois dela irá executar antes do Ajax ser feito, não depois.
Qualquer coisa que você queira executar só depois da resposta estar pronta, você deve colocar no callback da requisição. Exemplo:
$.getJSON(url, parametros).done(function(resposta) {
    $el.parents('li').load();
});

(Não sei se era esse seu objetivo com essa linha de código, mas suspeito que seja: recarregar só depois do Ajax estar pronto)

P.S. Na pergunta você também diz que está fazendo uma "alteração de status", certo? Nesse caso, a melhor prática seria não utilizar um HTTP GET para isso, mas sim um POST. Exemplo:
$.post(url, parametros, "json").done(function(resposta) {
    $el.parents('li').load();
});

Comment: Lembrando que a função load não carrega os dados diretamente. É necessário de tratar a atualização para cada parte, seja retornando a lista em html no retorno da requisição e atualizar usando a função html(). Ou retornar um JSON e tratar logo em seguida adicionando o html
Answer: Voçê está fazendo a requisição e em caso de sucesso tratou apenas para erro.
$.getJSON('MarcaItemFoto.php', {IdProduto: IdProduto, IdProdutoFoto: IdProdutoFoto},  function(resposta){
  // Aqui você deve tratar se realmente ocorreu um erro ou não.
  // Esta funcão é utilizada caso a requisição retorne um status de sucesso.
  // Aqui você tambem deve tratar os casos de sucesso, como atualizar a lista de que precisa.
});

O Load faz outra requisição Ajax veja os parametros na documentação
$el.parents('li').load('caminho/para/retornar/o/html/atualizado');

Recomendo tratar tambem quando a requisição retornar um código de erro não esperado usando a função fail() do jquery. Ficaria assim:
$.getJSON('MarcaItemFoto.php', {IdProduto: IdProduto, IdProdutoFoto: IdProdutoFoto},  function(resposta){
   // Ação após obter resultado com código de sucesso
}).fail(
  function () {
    // Ação após obter resultado com código de erro
  }
);

Answer: A solução para o meu problema, foi isso:
$.post(url, parametros, "json").done(function(resposta) {
    $el.parents('li').load();
});

Dica dada pelo mgibsonbr.
Obrigado.

Recarregar após atualização


When is the radius of convergence of the product of two complex power series twice the radius of convergence of the product of the radii

Question: Proving that the product has a larger radius then the product isn't too bad using the nth root test, but another practice question I have asks for examples of power series $\sum a_kz^k$ with radius of convergence $R_a$ and $\sum b_kz^k$ with radius of convergence $R_b$ such that $\sum a_k b_kz^k$ has twice the radius of the products, i.e. $R_{ab}=2R_aR_b$.
I'm not interested in the answer so much as how you approach these problems. I tend to be bad at thinking up examples, especially since I haven't computed many radii of convergence. Would the ratio test be useful to think about?
Answer: To approach this problem, you need to know how exact the radius of convergence is related to the terms of the Taylor series. The result you need is the Cauchy-Hadamard theorem: https://en.wikipedia.org/wiki/Cauchy%E2%80%93Hadamard_theorem.
Edit: Using the theorem, we have
\begin{align*}
\frac{1}{R_a} &= \lim \sup \lvert a_n \rvert^{\frac{1}{n}} \\
\frac{1}{R_b} &= \lim \sup \lvert b_n \rvert^{\frac{1}{n}} \\
\frac{1}{R_{ab}} &= \lim \sup \lvert a_n b_n \rvert^{\frac{1}{n}}
\end{align*}
so can you think of a two sequences such that the lim sup of the product is half the product of the lim sup? Perhaps you can use the standard trick of staggering terms of the sequence, e.g.
$$ 0, 1, 0, 1, 0, 1, \ldots $$


Strange behaviour of "Call was rejected by callee." exception with Excel

Question: I have an application that includes data exporting to Excel. And it works fine on most computers. However, there're two that throw

Call was rejected by callee. (Exception from HRESULT: 0x80010001 (RPC_E_CALL_REJECTED))

when I try to open Worksheet with get_item(). The funny thing is, when I set up breakpoints and execute everything string by string there are no exceptions whatsoever. Everything works fine and smooth. But in normal working behaviour, it just gives this exception.
MyApp = new Excel.Application();
MyApp.Visible = false;
string FileFullPath = Path.GetFullPath("Resources/Excel/FullMonthlyAct.xls");
MyBook = MyApp.Workbooks.Open(FileFullPath);
MySheet = (Excel.Worksheet)MyBook.Worksheets.get_Item(1);
Excel.Range excelCell = MySheet.Cells[1, 1] as Excel.Range;

UPDATE:
It's not a duplicate of the mentioned questions. There, most of the answers tell to check Office activation/installation/file assosiation. And as I've found out with the help of Hans Passant, i get this error simply because Excel can't load the workbook in time.
UPDATE: Solved
Not the most elegant solution maybe, but it's possible to just wait till Excel opens the workbook as described in https://stackoverflow.com/a/54126361/1442373 by Joost.
Comment: It is the error you'll get back from Excel when you slam it with too much work to do.  Running this code in a worker thread is a typical reason.  So sure, slowing it down with a debugger or running it on a fast machine are ways to avoid it.  That is one gawdawful horribly miserable duplicate, google "office imessagefilter" to find the code you need to tell it to keep waiting.
Comment: I confirm that this is NOT a duplicate question.  I had the error 1 times out of 3, running the same script on the same machine.  Once I did put a 5-second wait after the workbook.Open command, it worked all the time.
Comment: Check my response to the other question (including a code sample to wait for Excel to be ready before continuing): https://stackoverflow.com/a/54126361/1442373
Answer: Your applicaton will work on all machines that have excel installed and properly activated. It is not working on those machines because they might not have activated microsoft excel properly. You need to make sure it and the problem will be resolved.


Trying to calculate weighted average by Year/Month in DAX

Question: I have a table with the following rows:

and I am trying to do a weighted average by Product and ReceiptYearMonth of CaseQuantity
I have created the following DAX measure to try to create the weighted average:
SumX Test = sumx(Query1,
          Query1[CaseQuantity] /
          calculate(
              sum(Query1[CaseQuantity]), ALL(Query1[RecadvLineId])
          )
       )

but that just returns the following:

i.e. the measure returns 4.00 for 201702 because there are 4 rows in the table for 201702. It returns 2.00 for 201703 because there are 2 rows for it. At this stage I think they should be returning 1.00 for each YearMonth.
Can anyone explain what I am doing wrong here ?
Answer: I'm not certain I follow your weighting methodology, but is this what you're looking for?
SumX Test = SUM(Query1[CaseQuantity])/CALCULATE(SUMX(Query1,Query1[CaseQuantity]),ALL(Query1[RecadvLineId]))

It gives me this:

and this, if I add the RecadvLineId to the table:


What should our logo and site design look like?

Question: Again, taken from the SO suggested list, but this does seem like a good question.
Anyone have any ideas?
Comment: I hate trying to come up with "branding" for these kinds of econ projects. We could so with generic stock market, dollar sign type stuff, but that would just perpetuate the myth that economics is mostly about money. Alternatively, we could go with some supply and demand inspired branding (or similar), but how to make that look visually exciting? Perhaps a question on the graphic design SE is in order : ).
Comment: Do you know if there are any guidelines for the logo/site design or is it pretty much just "anything goes"?
Comment: To my understanding we merely make suggestions, SE has final authority, so the guidelines would be best distilled as "whatever they want". :)
Comment: added the tag..
Comment: Interesting. I thought stacks didn't get custom design and logo until they graduated from public beta. At least that is the impression I get from scrolling through the main list of all stack exchange sites.
Comment: I believe the question is meant to solicit ideas so that prior to exiting beta we have an idea. I stole it from the list of "good meta questions" from SE.
Comment: @JasonNichols Ah. Ok. Although my beloved _history.se_ still has default logo and styling; it's been in beta for 3 years. This is not uncommon - Biology and Chemistry have also been in beta for years. Chances are we'll need to dig this post up in 2018. But ah! Let's make hay while the sun shines.
Comment: @LateralFractal good news - [Chemistry.SE is graduating](http://meta.chemistry.stackexchange.com/q/484/25). Some sites can hit graduation within much shorter time periods - it's all about building the community
Answer: I think the feel of the design is more important than specifics. I'd like an air of weightiness, seriousness, sobriety, intellect, the Enlightenment tradition.
Particular design elements might include some foundational equations, a stylised chart of intersecting supply & demand curves.
Oh, and maybe a picture of David Ricardo stood at the top of Everest in a t-shirt and tennis shoes (hat-tip David Friedman)
Comment: So maybe a serif font, some doric columns... Here's a simple stab in the rough direction that came to mind (not designed by me!): https://0.s3.envato.com/files/29734380/Column%20Logo%20Preview.jpg
Answer: I would love the design to incorporate the Mainline Economists Mural at Universidad Francisco Marroquín.
Answer: A illustrated bookshelf of the most important books in economic thought could work: Wikipedia has a decent list but I suggest confining ourselves to deceased authors.


Toda classe precisa ter obrigatoriamente um construtor

Question: Sei que é uma duvida de principiante, mas preciso sanar essa dúvida. Pesquisei pela internet e nem sempre os sites entram em "acordo".
Toda classe precisa ter construtor ?
Exemplo:
Posso fazer a classe aluno e não ter construtor e os métodos cadastrar(nome, idade, rm) sendo esse método responsável por fornecer os valores para as propriedades da classe (nome, idade, rm) e o método desativar(id_aluno).
Ao meu ver isso é mais prático no momento de instanciar a classe. Se for apenas desativar o aluno apenas chamada desativar().
Pois se fizer o construtor recebendo as propriedades da classe todo momento que for acessar algum método dela terei que passar todos os valores (nome, idade, rm), mesmo que se para apenas desativar().
Estou pensando errado?  qual a melhor prática?
Comment: Fui tão guela pra responder, que até esqueci de verificar se já tinha a resposta. Tenho que concordar que é a mesma pergunta, praticamente
Answer:
Toda classe precisa ter construtor?

Não. Em PHP, classes podem ser declaradas sem a definação de um construtor. Entretanto:

"Classes que tem um método construtor chamam esse método cada vez que um objeto novo é criado, então é apropriado para qualquer inicialização que o objeto possa vir a precisar antes de ser usado."
  PHP: Construtores e Destrutores

Sendo assim, é recomendado que use o construtor para inicializar os atributos que estão vinculados de forma comum a todos os métodos da classe.
Caso o atributo seja específico para um método, inicialize-o no momento da invocação do próprio método.

(...)
  Pois se fizer o construtor recebendo as propriedades da classe todo
  momento que for acessar algum método dela terei que passar todos os
  valores (nome, idade, rm), mesmo que se para apenas desativar().

Não entendi plenamente sua afirmação. É importante compreender que sempre que uma classe é instanciada com atributos inicializados pelo construtor, essas propriedades estarão disponíveis para qualquer método do objeto até ele ser destruído.
Comment: Na minha " afirmação" eu me refiro quando há vários alunos cadastrados no banco de dados.  Esses são exibidos numa lista.  Então escolho um aluno qualquer p desativar.  Mas se a classe aluno tenha os atributos no construtor todo momrnto terei q passar esses valores,  daí não sei é não vejo lógica de ter q passar esses valores a todo momento
Answer: Não, não precisa.
O construtor serve simplesmente para incializar atributos da classe.
A classe stdClass por exemplo não possui o método __construct.
Em alguns casos, é melhor ter um construtor do que ter que utilizar métodos do tipo mutator e accessor.
Exemplo com construtor:
class Aluno
{
   protected $nome;

   protected $idade;

   public function __construct($nome, $idade)
   {
       $this->nome = $nome;

       $this->idade = $idade;
   }
}

Exemplo sem construtor:
class Aluno
{
   protected $nome;
   protected $idade;

   public function setNome($nome)
   {
      $this->nome = $nome;

   }

   public function setIdade($idade)
   {
      $this->idade = $idade;
   }

}


Proof that $\mathbb{R}^3$ minus $z$-axis is a star domain

Question: How can I prove that $\mathbb{R}^3$ minus $z$-axis is a star domain?
Due to conditions for star domain, I think I have to prove that the set is simply connected or convex.
I have found a family of closed curves that surround $z$-axis.
How can I conclude?
Answer: $\Bbb R^3$ without $z$-axis is not a star domain.
Given any $(x,y,z)\in\Bbb R^3$ with $x\neq 0$ or $y\neq 0$, consider $(-x,-y,z)$. This is a different point, but the line from $(x,y,z)$ to $(-x,-y,z)$ goes through $(0,0,z)$, which lies on the $z$-axis.
Answer: This is false. $\Bbb{R}^3$ minus the whole $z$-axis is not a star domain:
Proof: Let $v = (x, y, z)$ be any point not on the $z$-axis. Then either $x \neq 0$ or $y \neq 0$. Hence either $-x \neq x$ or $-y \neq y$. And so $-v = (-x, -y, -z)$ is different from $v$ but still not on the $z$-axis. However, now the line segment $\ell(t) = tv + (1 - t)(-v), 0 \leq t \leq 1$ from $v$ to $-v$ includes the origin (which is on the $z$-axis) as you can see by plugging $t = 0.5$ in $\ell(t)$. This is contrary to what is required for a star domain.
Comment: How can I consider a restriction of $\mathbb{R}^3$ that is a star-domain?
Comment: What do you mean by a "restriction"? Could you ask that as a new question with more details?
Answer: The set you are considering is not even simply connected, and there is a very simple way of proving this. Consider the cylindrical coordinates
$$
x=r\cos \phi, \quad y=r\sin \phi, \quad z=z.$$
The differential form
$$\omega=\frac{xdy-ydx}{x^2+y^2},$$
which can be written in cylindrical coordinates as $\omega=d\phi$, is defined on the domain in consideration, that is $\mathbb R^3\setminus\{z\text{ axis }\}$, and is manifestly closed, BUT it is not exact; this means that there are closed curves $\gamma$ such that
$$
\oint_\gamma \omega \ne 0.$$
One such curve is the circle $C=\{(\cos \phi, \sin \phi, 0)\}$; indeed, using the representation in cylindrical coordinates, we immediately see that
$$
\oint_C \omega = \int_0^{2\pi} d\phi = 2\pi\ne 0.$$
Thus, the domain cannot be simply connected, let alone star shaped.


How to make a project where I'm a collaborator invisible on my Github?

Question: There is a project on Github where I'm a collaborator, and I want to make it invisible to people who visit my Github page. How can I do it?
Answer: Your GitHub page reflects the project visibility.
You would need to ask the project maintainer to change the project visibility to private


Statistical test for comparing species diversity based on frequency at two points

Question: I am trying to quantify similarity between these two locations taking into account species frequency:

Chicago
    Blue Jay: 0.79
    American Crow: 0.25
    Blackpoll Warbler: 0.04
Houston
    American Crow: 0.6
    Great-tailed Grackle: 0.34
    Blue Jay: 0.3

What is the best statistical method to use?  Is it Shannon-Wiener Index?
Answer: I'm not sure about if this should be ans answer or a long comment, but I hope it can be helpful.
My first thought is that if you are going to compare only two points, you will have only one measure of distance, and a single measure is only meaningful if it can be compared with something else. Then, you need to use a measure that had been used for other locations.
Anyway, if you are going to measure distances between more than two locations (or samples, or times), you can get meaningful comparisons even using a distance nobody used before (e.g. you might be able to show that location A is close to location B and location C is very different from locations A and B).
I'm not a specialist in your field but I think Shannon-Wiener Index isn't useful for your goal. Shannon-Wiener Index is a measure of diversity, and by using it you will see if both locations have the same diversity or different diversities, but beware that two locations can have the same Shannon-Wiener Index if they have the same proportions of different species (e.g. location A with 100% blue jay and nothing else has exactly the same diversity than location B with 100% american crow and nothing else, in spite that proportions can't hardly be more different).
Your proportions are normalized histograms or profiles, that is, lists of proportions that sum 1. To compare such histograms, it may be useful to resort to correspondence analysis and use chi-squared distance.
Anyway, I'm not a specialist in correspondence analysis nor in ecology and I can't tell if use of chi-squared distance in your field is common.
Comment: thank you for your thoughts.  I am comparing thousands of points like this, so I am looking for a distance measurement.  I started with Euclidean distance between the communities and this seems to work fairly well when I combine it in a correlation matrix.  Your explanation of Shannon-Wiener index was helpful--not what I needed.


Python não é tão "inteligente" para operações redundantes

Question: Ao contrário de muitos casos em c++, o Python aparentemente não é tão inteligente para otimizar operações redundantes, mesmo entre constantes.
Eu fiz um benchmark simples para testar math.cos dentro e fora de um loop.
Neste primeiro caso, eu faço Python calcular cos(3) 10 milhões de vezes:
from datetime import *
from math import *

ini = datetime.now()
for a in range(10000000):
    x = cos(0)
fim = datetime.now()
print(fim - ini)

O resultado é 0:00:01.360958.
Agora, apenas substituindo x = cos(0) por x = 1 (ou apenas colocando cos(0) em uma variável fora do loop), o tempo fica 3 vezes mais rápido: 0:00:00.429995
Ora, se a operação cos(0) sempre gera uma constante (1), por que o Python não otimiza a execução com um cache, evitando assim a repetição da mesma operação cos constantemente?
Uma das filosofias do Python é facilitar a vida do programador. Mas neste caso o que está acontecendo é exatamente o oposto.
Comment: Na verdade, o Python sempre busca ser simples para o desenvolvedor resolver o problema, a performance nunca foi o foco. Se você precisa de algo mais rápido, cogite mudar a linguagem.  Perceba que mesmo chamando uma função com retorno constante o tempo de execução será praticamente o mesmo. É o tempo que o Python leva para resolver 10.000.000 de chamadas. Não tem relação direta com o cálculo do cosseno.
Comment: Para deixar claro, embora eu tenha comentado que a pergunta partiu de uma premissa errada, julgo ser uma pergunta perfeitamente dentro dos padrões do site e muito bem-vinda, pois essa provavelmente é a dúvida de várias outras pessoas. Com isso, não concordo com os votos negativos.
Answer:
Uma das filosofias do Python é facilitar a vida do programador

Está respondido. Isto é o oposto do que está preocupado. Talvez seja questão de interpretação do texto. Pelo menos eu não consigo imaginar como a falta de uma otimização seja um dificultador para o programador. Eu até entendo o desejo, mas isto não bate com a filosofia de Python. Cada um pode tentar interpretar o texto como quiser, mas a maioria das pessoas sabem que facilidade e otimização são coisas diferentes.
Quem quer performance, eficiência, abstração de custo zero, essas coisas é C++. C, Rust também, claro. Python nunca teve essas coisas como base para decidir nada do que fazer. Se a performance é o desejado escolha outra linguagem. Olha que facilidade.
Porém, você fez o teste no C++? E fez corretamente? testar é complicado. Eu não garanto que ele seja otimizado lá. É possível, e até provável, mas sem testar eu não garanto. E se é para otimizar mesmo isto deveria ser custo near zero porque todo o laço é inútil e basta fazer x = 1 e mais nada, mata todo o loop, ou nem isso porque depois a variável nem é usada. Na verdade este código nem faz sentido. Inclusive a forma de medir também não é das mais adequadas.
Mas no final é uma questão de ninguém ter decidido fazer a otimização. Talvez porque poderia deixar a compilação mais lenta, ou por outro motivo. Pode ser que alguém ainda o faça, pode ser que você abra um issue e alguém faça, pode ser que você queria fazer e entregar para review da comunidade e a melhoria seja aplicada.
Answer: "Tornar a vida do programador mais fácil" não é exatamente uma coisa objetiva. Apesar disso, é o que a linguagem faz sim - mas "tornar a vida do programador mais fácil" não é sempre e em todos os casos "rodar todo o código existente da forma mais otimizada possível".
Inclusive, é sabido, e dito em quase todo material introdutório de Python que na verdade, ao usar Python, você está sim fazendo um trade de performance por facilidade de escrever o código.
E essa diferença de performance está ligada ao mesmo motivo principal dele não tentar curto-circuitar a chamada ao cos: Python é uma linguagem dinâmica - o que significa que as coisas são definidas em tempo de execução.
Esse exemplo que você passou não fica tão ruim. Na máquina virtual Python ele executa os opcodes 10_000_000 para o trecho do for, e mais a chamada a cos e retorno do valor explicitamente. Só que isso  isso cabe no cache L1 do processador - se o cos fosse uma função que, mesmo determinística, usasse mais memória do que cabe no L1, esse tempo seria muito, muito pior.
O principal motivo é que ao fazer a chamada a cos, a linguagem não tem como saber que a função cos na passada 1 milhão e 2 do laço é a mesma que estava lá na passada 1 milhão e 1.
Perceba que é possível que seu código seja assim:
from datetime import *
from math import *
import random

ini = datetime.now()
for a in range(10000000):
    x = cos(0)
    if random.randint(0, 1_000_000) == 0:
          cos = sin

E pronto, em algum ponto, a função chamada passa a ser outra - como é tudo checado em tempo de execução, a linguagem simplesmente vai sempre chamar a função correta na linha x = cos(0). Código desse tipo não é comum, mas mesmo assim, é da premissa da linguagem que esse tipo de código tem que funcionar.
Já acompanhei muitas discussões por e-mail entre os desenvolvedores de Python, de casos de otimizações que não podem ser implementadas no cPython - a implementação de referência da linguagem - por conta de não poderem passar por cima de uma possível alteração nos objetos entre duas etapas da execução. E estou falando de otimizações bem menos ingênuas do que essa que você pressupôs que deveria existir, com a sua pergunta.
Voltando a essa otimização específica, em C, C++ (e outras linguagens estáticas) é possível mudar a função chamada por um nome, mas isso não é comum, e vai envolver uma sintaxe diferente - tipo, chamar a função no endereço apontado pelo ponteiro de função tal. Daí é bem mais simples otimizar - mas mesmo em C, acho que isso não seria otimizado por padrão - por que o compilador não pode simplesmente supor que a função chamada é determinística (isso é, sempre vai retornar o mesmo valor para o mesmo valor de entrada).
Alias, no caso do cos em C, a única forma que o compilador "sabe" que pode trocar cos(0) por uma constante, é por que isso está marcado explicitamente, em algum ponto - ou no compilador, ou eco-sistema da biblioteca do sistema que culmina no arquivo math.h. Em Python, cos, sin e outras funções do tipo não são usadas o bastante [*] para terem esse status especial, mas o compilador faz sim otimizações parecidas para expressões estáticas colocadas no código - se você, numa linha de Python escreve a = 2 ** 64 - o valor de 2 elevado a 64 é calculado em tempo de compilação, e essa linha vai carregar uma constante que é inserida no arquivo .pyc pré compilado. Meu teste aqui com C fez o mesmo para a saída da função cos.
Qualquer compilador que fizesse isso pra uma função arbitrária estaria tornando a linguagem inviável de ser usada na prática (vamos supor que seja o código para monitorar se a porta de um cofre está aberta, e chama a função do sensor - o cofre passa quase o tempo todo fechado, mas se quando ele for aberto o compilador tivesse assumido que ela o retorno da checagem seria "fechado", seria impossível ter esse programa)
Dito isso - o Python tem mecanismos para permitir que o programador possa explicitamente transformar uma função em algo com "cache" - e isso ele faz criando um novo objeto chamável, dinamicamente em tempo de execução, sem nenhuma regra especial - no caso, como apontado na resposta do Fernando Savio, a função functools.lru_cache pode ser usada para decorar uma função - e nesse caso o programador indica pra linguagem: "olha, pra essa função aqui, para os mesmos valores de entrada, pode usar sempre os mesmos valores de saída".
Agora, por fim, sim, se você quer esse tipo de otimização automática, e quer programar em Python, você ainda pode ter tudo - usando o Pypy - pypy é uma outra implementação de Python, que implementa otimização de compilação "just in time" (JIT) - aí sim, quando o runtime do pypy perceber que está num loop chamando a mesma função várias vezes, ele vai compilar todo o código dentro da função para código nativo, e isso vai ser executado muito mais rapidamente - e se em qualquer momento dentro do mesmo loop, a execução tomar um rumo diferente (tipo - o sensor detectou a porta do cofre aberta, ou o nome de variável cos agora aponta para outra função), ele reverte para execução normal.  E o motivo disso não ser o "padrão" na implementação do Python é simplesmente que não foi feito - otimização nesse nível de complexidade custa muito caro (em termos de homens hora), e mesmo com empresas como o Google, RedHat, IBM e Intel patrocinando ou dispostas a patrocinar alguns milhões de dólares em otimização do Python padrão, ainda não foi feito por falta de pessoas que conheçam o suficiente o Python e possam interagir com a comunidade, para faze-lo.  Mas sim, é possível que em vários anos, por conta de esforços desse tipo, tenhamos execução JIT também na implementação de referência.
[*] - então se você realmente for precisar da performance "full" da CPU para cálculos de sin e cos, e estiver programando em Python, a recomendação é que os seus números, com os quais você vai fazer as contas, estejam encapsulados em objetos especiais que fazem esse tipo de operação usando código nativo - por exemplo, a biblioteca NumPy, ou alguma biblioteca de OpenGL ou gráficos 3d, se o uso for para renderização de imagens, por exemplo.  cos nativo em Python tem que "embrulhar"  a resposta do código de máquina que calcula cos num objeto float - que tem todo o dinamismo que o Python precisa - essa operação é centenas de vezes mais custosa do que simplesmente armazenar na memória o numero de 8 bytes em ponto flutuante resultante da operação nativa.
Answer: As filosofias do Python são 19, e nenhuma delas diz que é para facilitar a vida do programador.
Uma delas diz:

Explícito é melhor do que implícito.

Dito isso, você como programador capaz de notar que o interpretador não faz cache dos últimos resultados de um cosseno, poderia utilizar o decorator lru_cache do módulo functools que serve justamente para isso, pois LRU significa Last Recent Used, que é justamente o que você quer que ele faça. Voltando novamente para o mantra:

Explícito é melhor do que implícito.
Comment: Na verdade, "facilitar a vida do programador" não tem nada a ver com o não-problema que foi colocado.
Comment: ela nao está cobrindo tudo oq ue tem que cobrir, mas ajuda sim - traz um dos argumentos de por que essa dúvida não é muito pertinente.
Uma reposta completa e compreensiva a essa pergunta seria quase um livro - então, se cada um que tocar aqui colocar um ou dois argumentos, todo mundo contribuiu.
Comment: Desculpa @jsbueno não entendi tua colocação.
Comment: é que "ser mais fácil pra programadores" é bastante subjetivo - mas não remete de forma nenhuma a 'adivinhar coisas pra ser o mais rápido possível'. Sua resposta está legal, mas trata essa colocação da pergunta como se fosse verdadeira.
Por que, na verdade, as frases do zen of Python são meio anedóticas - é claro que uma das premissas da linguagem é tornar as coisas mais fáceis para programadores. Só que "inventar caches instantaneos só por que sim" não tem relação com isso.
Comment: Pois é, eu fiquei pensando também se não fui grosseiro... No fim não sei se a resposta acrescenta alguma coisa à comunidade fora falar de lru_cache.
Comment: Na verdade, essa pergunta demandaria mesmo uma consideração sobre a natureza da linguagem, que é dinâmica, e por isso não faz cache de nada - e depois, passar por cpython ser a implementação de referencia, e ai sim, apontar que o pypy tem JIT e faz o que ele está querendo.
Comment: Verdade... Vou apagar a resposta visto que não ajuda.


vsftp on Azure VM - filezilla reports private ip sent by server in passive mode

Question: I'm setting up a secure FTP server on an Ubuntu 16.04 machine on Azure. It's FTP over TLS, with anonymous access disabled.
Trying to use the server using Filezilla works fine - authentication, transfer, directory listing - everything... except I get the following warning from Filezilla:

Server sent passive reply with unroutable address. Using server
  address instead.

Sure, that makes sense - the VM has a private IP address, and in passive mode, it sends that private IP address to the client. The solution - add the following to vsftp.conf (this is an example, not the actual configuration):
pasv_enable=YES
port_enable=YES
#The VM allows connections to ports 12345 & 12346 - remember, this is an example
pasv_min_port=12345
pasv_max_port=12346
#The VM's domain name
pasv_address=myftpservervm.cloudapp.net
#Make vsftp resolve myftpservervm.cloudapp.net and send that IP address to clients
pasv_addr_resolve=YES

Then I restart vsftp, and... nothing happens. I still get these:

Server sent passive reply with unroutable address. Using server
  address instead.

I even tried setting pasv_address to the exact (external) IP address of the server (with and without pasv_addr_resolve=YES) and the result is the same.
Am I missing something?
I'm using vsftpd 3.0.3 (from the Ubuntu repo) with Filezilla 3.24.0 on Ubuntu 16.04 x64
Edit:
Apparently vsftp sends an IP address of 0.0.0.0 when entering passive mode. This issue seems relevant.
Answer: I test in my lab, at first I met the same problem as you. I checked as the following steps:
1.netstat -ant I get the following result
tcp6       0      0 172.17.1.4:21           22.214.171.124:10979    TIME_WAIT

Based on my experience, ftp should be listening on tcp not tcp6 on Azure VM
2.I try to change the configuration file /etc/vsftpd.conf.
listen=yes
listen_ipv6=no

Then I restart ftp service and check by using netstat -ant
tcp        0      0 0.0.0.0:21              0.0.0.0:*               LISTEN

Test by using Filezilla.

Notes: You should open ports 20,21,12345-12346 on Azure NSG(Inbound rule)
Answer: You need just a minor modification. Edit /etc/vsftpd.conf or whatever the config file might be, and do this change:
pasv_address=public_ip_of_aws_instance_not_hostname_or_private_ip

Save the file, restart the vsftpd service and check again!
Be sure that hose passive ports are in the tcp allow list in your Security Groups (you can configure those from your AWS EC2 Dashboard).
Comment: That's exactly what I did. I tried both the external IP, and the domain name (with `pasv_addr_resolve=YES`). It produced the same result.


question about division

Question: The question is from the following two problems:

Let $x$ and $y$ be positive integers such that $3x+7y$ is divisible by $11$. Which of the following must also be divisible by $11$?
  A. $4x+6y$  B. $x+y+5$  C. $9x+4y$  D. $4x-9y$  E. $x+y-1$
If $x,y$ and $z$ are positive integers such that $4x-5y+2z$ is divisible by $13$, then which one of the following must also be divisible by $13$?
  A. $x+13y-z$ B. $6x-10y-z$ C.$x-y-2z$ D.$-7x+12y+3z$ E. $-5x+3y-4z$

One way I know is that one can substitute some specific number to rule out the wrong answers. Or alternatively, one can try the properties of congruence(addition and subtraction), which I think is not easy to figure out the steps. Just as for the second problem, how on earth can one figure out one needs to add
$$-39x\equiv 0\pmod{13}$$
$$65y\equiv 0\pmod{13}$$
$$13z\equiv 0\pmod{13}$$
to
$$4x-5y+2z\equiv 0\pmod{13}$$
and then divides by $5$
in order to get the answer
$$-7x+12y+3z\equiv 0\pmod{13}?$$
So, here is my question:

Is there a general method (which might be also quick) to solve this kind of problems?
Comment: This looks like an old GRE question!
Comment: You have a typo in the statement of the second problem (made apparent by your answer); it should be "$4x-5y+2z$ divisible by $13$", not $4x+5y+2z$. In the latter case, no answer is guaranteed.
Comment: @Arturo: Corrected. Thanks.
Answer: If $N|Ax+By$ implies $N|Cx+Dy$ then also $N|CAx+CBy$ and $N|CAx + DAy$, hence $N|(AD-BC)y$ and so $N|AD-BC$. For example, in the first question answer $C$, $7 \cdot 4 + 3 \cdot 9 = 55$ is divisible by $11$.
Another way of looking at that is that $(C,D)$ must be some multiple of $(A,B)$. So $C/A = D/B$, which can be tested via $CB=AD$.
If you have more than two variables, say $N|Ax+By+Cz$ implies $N|Dx+Ey+Fz$ then the same method gives $A/D=B/E=C/F$ and so $AE=BD$ and $BF=CE$. Try it on the second question.
Comment: +1 Very nice. Essentially $(C,D)$ must be 'orthogonal' to the same set of vectors in $\mathbf{Z}_{11}^2$ as $(3,7)$ is, so these two need to be linearly dependent.
Answer: Hint $\  \mathbb F = \mathbb Z/11\:$ & $\:\mathbb Z/13\,$ are fields, so $\rm\,\mathbb F^{\:\!n}$ is a vector space, hence lines through the origin are uniquely determined by any non-origin point on the line. To find such a point, pick an easily invertible coefficient $c$ of the equation and scale the equation by $c^{-1}$ so the coefficient becomes $1$.
E.g. $\rm\ \color{#c00}4x -5y + 2z = 0\:$ over $\rm\:\mathbb Z/13.\:$ We look for an  easy invertible coef, e.g. one dividing $13\pm1,\,$ e.g.  $\,\color{#c00}4\cdot 3 = 13- 1 = -1,\,$ so scaling by $\,4^{-1} = - 3$ yields $\rm\: x +2y - 6z = 0,\,$ so $\rm\,x = -2y+6z.\,$  Picking "simple" values for $\rm\:y,z\:,\:$ say $\rm\:y=0,\:z=2\:$ yields $\rm\:x=-1,\:$ which lies only on the line  $\rm\:(D)\ -7x +12y+3z = 0.$
This method is both general and quick - esp. quick when there is an easily invertible coefficient dividing modulus $\pm 1\:$ (which occurs frequently for small moduli by the law of small numbers).
Answer: There are general methods, and in this case there is even a quick one. But in general the "specific numbers" strategy you mentioned is  well-suited for this kind of test, in which you have to solve too many too easy problems in too little time.
Below is my strategy.  Real multiple choice test survivors can undoubtedly supply better ones.
For the first problem, I would find some particular numbers $x$ and $y$, not both $0$,  such that $3x+7y \equiv 0 \pmod{11}$.  My immediate choice is the no thinking $x=7$, $y=-3$.   This quickly kills all possibilities except D. (I might kill B and E by using $x=y=0$.)
For the second problem, same thing.  Let $x=4$, $y=5$, $z=0$. The $z=0$ is to forget about $z$. Got unlucky, D and E are still alive.  So pick $x=0$, $y=2$, $z=5$. That kills E.
As to general methods, for linear algebra reasons, if we know that $ax+by\equiv 0\pmod{p}$, where $p$ is prime, we cannot have $cx+dy \equiv 0 \pmod{p}$, with the  unless $ad-cb \equiv 0\pmod{p}$. With some care, the idea can be extended to non-prime moduli.  So a few quick determinant calculations modulo $11$ also  give the answer to the first problem. (The constant terms in B and E kill these as choices, so we needn't bother with them.)
In the second problem, since any variable could be set to $0$, there cannot be a solution unless all $2$ variable problems obtained by setting one variable to $0$ have a solution. This brings us back to calculations like those in the preceding paragraph. But to rule out some possibilities, we may have to do more than one determinant calculation.
My preference is substitution rather than determinant calculations. From the point of view of arithmetic, they are of equal difficulty, indeed identical.  But substitution is something you have better intuition about, it is "theory-free."
Added: In the $3x+7y$ problem, I immediately jumped to using $x=7$, $y=-3$.  We could replace $7$ by $-4$, and use $x=3$, $y=4$. We could in addition replace $3$ by $-8$, obtaining $(-8x)+(-4y)$, which is equivalent to $2x+y$, and we can use $x=1$, $y=-2$. These changes make the subsequent arithmetic simpler. Should we "invest" in such simplifications?  It depends on how comfortable
we are with mental arithmetic.  My gut reaction is not to invest, I could make a minus sign error, and blow everything.  Act, don't think, and go on to the next question.
Comment: Your comment on "linear algebra reasons" only works for $m$ prime. In general, you need $ad-cb$ prime with $m$.
Comment: @lhf: Thanks. Answer modified.
Answer: This is what I would do:
If $3x+7y$ is divisible by $11$, then $3x + 7y\equiv 0\pmod{11}$, so $3x\equiv -7y = 4y\pmod{11}$. Multiplying through by $4$, we get $12x \equiv 16y\pmod{11}$, which simplifies to $x\equiv 5y\pmod{11}$.
Then one can plug into the congruences: $4x+6y \equiv 26y\equiv 3y\pmod{11}$; $x+y+5\equiv 6y+5\pmod{11}$; $9x+4y\equiv 49y\equiv 5y\pmod{11}$; $4x-9y\equiv 11y\equiv 0\pmod{11}$; and $x+y-1\equiv 6y-1\pmod{11}$. Clearly, the answer is D.
For the second one, from $4x-5y+2z\equiv 0\mod{13}$ we have $4x\equiv 5y-2z\pmod{13}$; multiplying through by $-3$ we get
$$-12x \equiv -15y+6z\pmod{13}$$
which is equivalent to $x \equiv -2y+6z\pmod{13}$.
Plugging into the different possibilities, we have:
$$\begin{align*}
\text{A. }&& x+13y - z &\equiv -2y+5z\pmod{13}\\
\text{B. }&& 6x-10y-z &\equiv 4y +9z\pmod{13}\\
\text{C. }&& x-y-2z &\equiv -3y+4z\pmod{13}\\
\text{D. }&&-7x+12y+3z &\equiv 26y -39z \equiv 0\pmod{13}\\
\text{E. }&& -5x+3y-4z &\equiv 13y-34z \equiv 5z\pmod{13},
\end{align*}$$
so again, the answer is D.

Alternatively.
Once you have $x-5y\equiv 0\pmod{11}$ in the first problem, multiply by a suitable $k$ to try to match the coefficient of $x$ in the alternatives, until you get a match:

For $4x+6y$, multiply $x-5y$ by $4$ to get $4x-20y \equiv 4x+9y$, not equal.
For $x+y+5$, not equal.
For $9x+4y$, multiply $x-5y$ by $9$ to get $9x-45y \equiv 9x-y$; not equal.
For $4x-9y$, multiply $x-5y$ by $4$ to get $4x - 20y \equiv 4x -9y$; equal. This is the answer.

For the second one, again, from $x+2y-6z\equiv 0$, we try to match the coefficient of $x$ in each:

Multiply by $1$ to try to get $x+13y-z$; no luck.
Multiply by $6$ to try to get $6x-10y-z$; we get $6x+12y-36z\equiv 6x+12y-3z$; no luck.
Multipy by $1$ to try to get $x-y-2z$; no luck.
Multiply by $-7$ to try to get $-7x+12y+3z$; we get $-7x-14y+42z \equiv -7x -y+3z \equiv -7x+12y+3z$. Equal, so this is the answer.

question about division


Prove that if $5^n$ begins with $1$, then $2^{n+1}$ also begins with $1$

Question:
Prove that if $5^n$ begins with $1$, then $2^{n+1}$ also begins with $1$ where $n$ is a positive integer.

In order for a positive integer $k$ to begin with a $1$, we need $10^m \leq k < 2 \cdot 10^m$ for some positive integer $m$. Thus since $5^n$ begins with a $1$, we have $10^m \leq 5^n < 2 \cdot 10^m$ for some positive integer $m$. Then multiplying by $\dfrac{2^{n+1}}{5^n}$ we get $10^m \cdot \dfrac{2^{n+1}}{5^n} \leq 2^{n+1} < 10^m \cdot \dfrac{2^{n+2}}{5^n}$, but I didn't see how this helped.
Comment: Note that $ 2^{n+1}= \frac{2\cdot{10}^n}{5^n}$.
Answer: First, note that the inequalities must be strict, as we cannot have $5^n = 10^m$ for natural numbers $n,m$. Since $10^m = 2^m5^m$, your last equation becomes
$$2^{n+m+1}5^{m-n} < 2^{n+1} < 2^{n+m+2}5^{m-n}$$
$$\implies 2^{1+2n}10^{m-n} < 2^{n+1} < 2\cdot 2^{1+2n}10^{m-n}$$
Dividing each term by $2^{1+2n}$ gives us
$$10^{m-n} < 2^{-n} < 2\cdot 10^{m-n} $$
Taking the reciprocal of each term,
$$10^{n-m} > 2^n > \frac 1 2 10^{n-m} $$
Finally, multiplying by $2$ gives us
$$2\cdot 10^{n-m} > 2^{n+1} > 10^{n-m}$$
Answer: Note that:
$$2\cdot10^n=5^n\cdot 2^{n+1}$$
If $5^n$ begins with $1$ then
$$10^m<5^n<2\cdot10^m\to10^m< \frac{2\cdot10^n}{2^{n+1}}<2\cdot10^m$$
what give us
$$2^{n+1}< 2\cdot 10^{n-m}\text{ and } 2^{n+1}>10^{n-m}\Leftrightarrow 10^{n-m}<2^{n+1}<2\cdot 10^{n-m}$$
Answer: $10^m < 5^n < 2*10^m$ [Note: equality can not hold as $5^n$ has no factor of $2$.]
$10^m < \frac {10^n}{2^n} < 2*10^m$
$1 < \frac {10^{n-m}}{2^n} < 2$
$2^n <  10^{n-m} < 2^{n+ 1}$
So $10^{k} < 2^{n+1}$ for $k = n-m$.
...
And $2^m5^m < 5^n < 2^{m+1} 5^m$
$2^{n+1}5^m < 2^{n-m + 1}5^n$
$2^{n+ 1} < 2^{n-m+1}5^{n-m}$
$2^{n+1} < 2*10^{n-m}$
So $2^{n+1} < 2*10^k$ for $k = n-m$
So $10^k < 2^{n+1}< 2* 10^k$.
So $2^{n+1}$ has a first digit of $1$.


How to choose the number of nodes in layer recurrent networks?

Question: When using NNs for estimation purpose, we have three layers: input, output and hidden layer, and we must choose the number of nodes for every layer.
Is there a method or rule of thumb to choose the correct number of nodes?
Answer: The input layer must be as large as the number of inputs you have. e.g. if your input is made up of 64 bits, then your input layer should be 64 large (note: instead of using 0s and 1s as inputs you might be better off using -0.5 and 0.5 as inputs).
The output layer must be as large as the output you want.  If you want a simple discrimination, e.g. after rounding, 1 if the input is an element of a set and 0 otherwise, then your output size should be 1.
If you want the output to vote on the membership of the input in one of many sets, then you might want the output size to be the number of sets that the input can be an element of.  e.g. if the input can be either a red car, a blue car or a white car, then you might want the output size to be 3.  The Neural Network will map the input to the set represented by the output node with the highest value.
The above is the simple part of the answer.  Estimating the size of the middle layer is harder.
Some rule of thumbs include (which I personally do not subscribe to - as does the author of this reference:

some number between the number of input neurons and the number of output neurons;
not more than twice the number of input neurons; and
the number of principal components required to capture about 90% of the data.

In my opinion, I would choose the something close to the smallest number that allows me to generalise well on the test data but not too much larger.  This will help the NN to converge faster and generalise enough without training to become too specific in its discrimination.
Other references you might wish to look into are as follows:
1 - also suggests whether and how many input layers you need; and
2 - another answer available in stack-overflow regarding the same question.


Is there a way to share DTO models between .net core services and legacy .net framework code?

Question: I have an existing codebase written in .Net 4.5.x. I'm trying to create some new .Net Core services with the aim of eventually migrating the codebase to .Net Core piecemeal. I'd like the option to (eventually) deploy these services to small Linux servers, so I've targeted the first of them at .Net Core rather than the .Net Framework.
All of the existing code should communicate with the new services via standard REST endpoints. Since it's all REST, all that will actually go over the wire is JSON. No problems there.
I'm hoping to avoid some code reuse by having some shared Model projects which both the legacy and new services can utilize. I know this would be possible if the new services were .Net Core projects targeted at the .Net Framework, but I'm hoping there's a way to have a middle layer support legacy .Net Framework code and new .Net Core targeted code.
Is this possible, or is my only option to have the DTO classes duplicated in two projects until everything can eventually be ported over? Alternatively, am I architecting this all wrong in the first place and should I actively want dto classes on both ends?
Comment: Possible duplicate of [.net core classlibrary calling .net framework class library](http://stackoverflow.com/questions/37608032/net-core-classlibrary-calling-net-framework-class-library)
Answer: If I get it correct, your goal is to have an application (client/web/service) that should be able to run across platforms (Windows/Linux/MacOS).Therefore, the best choice in hand is to use .NET Core as its run-time (CoreCLR).
In my experience, I never hand to write heavy weight DTO those are platform specific. So my suggestion would be to look at your desk and isolate DTOs those are platform specific and find an alternative or choose a alternate for that.
Answer: You can use Shared Projects to host your DTO classes and reference that project in both the .Net Core and 4.5.x projects.
You can have a look at this link if you're not familiar with shared projects http://www.c-sharpcorner.com/UploadFile/7ca517/shared-project-an-impressive-features-of-visual-studio-201/  or just do a quick search and you'll find lots of information.
Essentially, shared projects allow you to reference/share code files across multiple projects instead of referencing their binaries/assemblies
Comment: Hrm, I tried this, but the Shared Project menu isn't available when adding references to my Asp.Net Core project. I checked and it doesn't show up with a standard ASP.Net MVC project either, though it is available for use by a standard class library project. I'm not sure if that's as intended (because it can only be shared to certain project types and/or frameworks), or if it's a bug in VS.
Comment: Haven't tried it on Asp.net, but if it's not working you can have one shared project with your DTO then 2 class libraries (one for .net core and the other for 4.5) that just reference the shared projects, and then you reference those into you asp.net and other projects targeting either .net core or 4.5


Using only once and start from beginning again

Question: Here is what I am trying to accomplish:
I have 500 usernames in my database. For each username in my database, I want to start from the first username, and call a function 10 times.
So example,

username1 - function called.
username2- function called.
username3- function called.
username4- function called.
username5- function called.
username6- function called.
username7- function called.
username8- function called.
username9- function called.
username10- function called.

Now we left off at username10, if I wanted to continue from username10 another day, how can I do this? I know you can add a new column to the database saying used and set it to '1' but, what if I did all 500, and want to start back over from username1 again? How can I do this?
Also when I am calling a function for each username, how can I log the process like above into a iframe?
Answer: If you want to use the "used" column method, here's how you set every user to unused:
UPDATE `mytable` SET `used`=0;

I don't know what you mean by "log it to an iframe", but you could log all of the operations to a file, with fwrite - here's the documentation.
Edit:
Select all entries from table that have `checked`=0. For each of these entries
    Execute the functions you need to execute
    Set `checked`=1

When you want to start over
Set `checked`=0 for all entires. Execute code above.

Comment: Yes, I know but what if I want to use them again and start back over from username1?
Comment: @dustin: Then I suppose when `SELECT id FROM users WHERE used=0` returns no records you can run the UPDATE statement that @vladh supplied to start over.


linear transformation $T: M_{5}(\mathbb{C}) \to M_{5}(\mathbb{C})$ that for any invertible matrix $A \in M_{5}(\mathbb{C})$,$rank(T(A))=4$

Question:
linear transformation $T: M_{5}(\mathbb{C}) \to M_{5}(\mathbb{C})$ that for any invertible matrix $A \in M_{5}(\mathbb{C})$,$rank(T(A))=4$,does T exist?

I guess no.here is some result I've proved:
consider dimension of Img(T(A))+Img(T(B)) for some invertible matrix A,B,then $Im(T(A))=Im(T(B))$ or $Img(T(A))+Img(T(B))=\mathbb{C}^5$
but i can go no further.
Comment: To be clear, you are interested in the rank of $T(A)$ not the rank of $T$, correct?  For the former, what if $T(A)=A \begin{bmatrix}  I_4 &\mathbf 0  \\  \mathbf 0 &  0\end{bmatrix}$?
Comment: @user8675309 you are right. that's the example i want.Thanks a lot.
Answer: For a linear transformation to be invertible it must be bijective. Since the rank of the transformation is $4$ the image of the transformation is four dimensional over $\mathbb{C}$. However since $M_5(\mathbb{C})$ has more than four dimensions such a bijection cannot exist. This is because the nullspace is non-zero (ie nullity is greater than zero), so $T$ cannot be injective and therefore not bijective.
Comment: It is the rank of $T(A)$ (a particular matrix in the image of $T$) rather than the rank of $T$ (the transformation over matrices) that is meant to be $4$.
Comment: This is not really relevant.


Find the latest version of a document stored in MongoDB - GridFs

Question: I'm planning to use MongoDB GridFs to store different types of flat files, scripts etc. One of the benefits using GridFs is that it creates new document on every insert and thus can be used for versioning purposes using custom meta data etc.
However, how to ensure the fetched document is the latest document from GridFS ?
Appreciate any suggestions.
Answer: For any given criteria, GridFS always brings the latest version with findOne.
You can test it. Have lots of files with same 'filename' field. Then pass filename to findOne, you will get the latest one.
Alternatively, you can sort on the uploadDate to get all versions.
<code>db.files.find({'filename':'abc.pdf'}).sort({'uploadDate':-1})
</code>
Comment: I can not reproduce your statement that findOne() returns the latest one. From my point of view it returns the oldest one... I'm using spring-data-mongodb 1.5.0.RELEASE...
Comment: Sorry I am not familiar with spring-data-mongodb but the you can use mongo client REPL to test this.


Como juntar vários dicionários em Python?

Question: Em algumas linguagens, é possível unir objetos/array em um só.
Por exemplo, em PHP, eu posso unir vários arrays assim:
$userInfo = ['name' => 'Wallace']
$jobInfo = ['job' => 'Developer']
$ageInfo = ['age' => '26']

$info = array_merge($userInfo, $jobInfo, $ageInfo)

Isso retornaria:
['name' => 'Wallace', 'job' => 'Developer', 'age' => '26']

E em Python? Como faço?
Se eu tenho os seguintes dicionários, como posso uni-los em um só?
a = {"A" : 1}
b = {"B" : 2}
c = {"C": 3}

Nota: Pensei em usar o for já, mas fiz a pergunta no sentido de achar uma solução mais simples do que isso.
Answer: Como demonstrado nesta resposta do SOen, pode-se usar
z = {}
z.update(a)
z.update(b)
z.update(c)

Ou algo como:
def merge_dicts(*dict_args):
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result

merge_dicts(a, b, c)

A partir do 3.5 (PEP 448) foi proposto isto
z = {**a, **b}

Comment: E eu quebrando a cabeça tentando fazer isso no Python 2.7. Ainda bem que você avisou que é a partir do 3.5.
Answer: Você pode utilizar o método update para atualizar um determinado dicionário já existente ou criar um novo e atualizar ele.
>>> a = {"A" : 1}
>>> b = {"B" : 2}
>>> c = {"C": 3}
>>> c.update(a)
>>> c.update(b)
>>> c
{'A': 1, 'C': 3, 'B': 2}

Usando um novo dicionário:
>>> novo = {}
>>> novo.update(a)
>>> novo.update(b)
>>> novo.update(c)
>>> novo
{'A': 1, 'C': 3, 'B': 2}

Answer: Pode usar o update, então temos:
a = {"A" : 1}
b = {"B" : 2}
c = {"C": 3}
abc = {}

abc.update(a)
abc.update(b)
abc.update(c)
print(abc) # {'A': 1, 'B': 2, 'C': 3}

Visto que os dicionários não estão contidos na mesma coleção (lista, tuple etc...), acho que a melhor maneira é assim


Monitor keyboard state without program focus

Question: I would like to invoke a thread within my program that constantly watches the keyboard and if a certain key is pressed then tell me (system.out).
The problem is that the KeyListener interface must have focus for it to return keystate.
http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
Is there a different way to determine the state of the keys on the keyboard?
My aim is to see that the user pressed ctrl+n, if so, update the system clipboard text to something.
CODE:
class KeyboardWatcher extends Thread
{
    boolean flag = false;
    public void run()
    {
        while(!flag)
        {
            if (shift & n are pressed)
            {
                StringSelection stringSelection = new StringSelection("Clip Text");
                Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
                clpbrd.setContents(stringSelection, null);
                flag = true;
            }
        }
        return;
    }
}

Answer: This is not possible without Java Native Interface. You will need a keyboard hook at the OS API level. There are many available solutions you could reuse. Look at this for one such example.


A book asks me to prove a statement but I think it is false

Question: The problem below is from Cupillari's Nuts and Bolts of Proofs.

Prove the following statement:
Let $a$ and $b$ be two relatively prime numbers. If there exists an
  $m$ such that $(a/b)^m$ is an integer, then $b=1$.

My question is: Is the statement true?
I believe the statement is false because there exists an $m$ such that $(a/b)^m$ is an integer, and yet $b$ does not have to be $1$. For example, let $m=0$. In this case, $(a/b)^0=1$ is an integer as long as $b \neq 0$.
So I think the statement is false, but I am confused because the solution at the back of the book provides a proof that the statement is true.
Comment: Presumably the problem meant that $m>0$ and $m$ is an integer.  It's not true if $m<0$ either, since $(\frac{1}{2})^{-1}$ is an integer.
Comment: (Actually, it's true for rational $m>0$, not just integer $m$.)
Comment: @thomas Thank you! This gives me some confidence to fill in gaps in other incomplete problem statements I might encounter.
Comment: I think Cupillari should have said "positive integer".
Answer: Your counterexample is valid. But the statement is true if $m$ is required to be a positive natural number or positive integer.
Alternatively, note it's not if true $m$ is required to be negative.
In my opinion, it seems like you were supposed to assume $m>0$.
Answer: This statement is true under certain conditions. You must assume $b \neq 0$. If $(a,b)=1$, you can easily show that $(a^n, b^n) = 1$. This means that $(a/b)^n = a^n / b^n$ is never an integer unless there exists $n$ such that $b^n = \pm 1$, but that means $b = \pm 1$.
The case where $a = 0$ and $|b| > 1$ must be excluded because then $(a,b) > 1$.
Hope that helps,


Inline css clip-path not respected on Chrome

Question: I am making some animation and graphics libraries to work with html. For some things clipping is needed and since the elements are generated dynamically, clip-path (mostly polygon) is added dynamicaly in elements'a style property :
el.style.clipPath = 'polygon(..)';
Firefox (76) works just fine, however Chrome (83) (and Opera as well) dont respect the clip-path property (on chrome element inspect it is not even shown on element's style properties as present)
It was supposed to be a bug in Chrome prior to v.64 but wherever I looked it says latest chrome (and webkit browsers in general) have full support for clip-path and polygon in particular.
Note: It is not an issue to test with url of svg path to be used a clip mask, but I would like to avoid svg, I would like to keep it pure html/css (however if i rememeber correctly not even svg inline url works with chrome when I was pulling my hair trying to figure out why it doesnt work as expected).
I have also tried adding with browser prefix (ie el.style.WebkitClipPath = 'polygon(..)') but nothing changed.
Test example should display a triangle (doesnt work on Chrome, at least my latest Chrome 83.0.4103.61 64bit windows):

var test = document.getElementById('test');
test.style.clipPath = 'border-box polygon(0px 0px, 200px 100px, 0px 200px)';
#test{
  position:relative;
  width: 200px;
  height:200px;
  background: #ff0000;
  padding: 0;
  margin: 0;
  border: 2px solid #00ff00;
  box-sizing: border-box;
  overflow: hidden;
}

What am I missing? Does chrome support clip-path with polygon, or not?
Comment: share the code .
Comment: @TemaniAfif added test example. See it on chrome, at least it doesnt work on mine
Comment: remove border-box, it's not needed
Comment: Are you saying that this is the problem? Because according to spec this is supposd to work, and border-box IS needed for my case
Comment: what do you expect when using border-box? you have no border, no padding, no margin, so it's not needed
Comment: @TemaniAfif, indeed if i remove border-box it works on chrome, but this is a bug, isnt it?
Comment: @TemaniAfif My use case has elements WITH borders and I want to clip with borders
Comment: share your full use case then ...
Comment: @TemaniAfif  Updated. The case is simply elements with border and `box-sizing` of `border-box`. If `border-box` is removed from `clipPath` then it works, but the spec says otherwise, in any case a box model is assumed when applying `clip-path` and I want to make it explicit. So this is a chrome bug as I see it.
Comment: even if you set the property using CSS it won't work. Either a bug or something has changed in the Spec
Comment: @TemaniAfif, indeed it doesnt work either way (have tried all ways), if a box-model (what is called `geometry-box`) is added to clip-path. But this is a missing feature that the spec according to latest MDN supports
Answer: To sum up the comments by @TemaniAfif in an answer so it stays:
If border-box is removed from clip-path, eg:
test.style.clipPath = 'polygon(..)';
then it works in Chrome too. However as per the latest spec on MDN, the following is valid combination and should be supported (support for Chrome on that page is green as grass):

/* Box and shape values combined */
clip-path: padding-box circle(50px at 0 100px);

The clip-path assumes a box model anyway, and it is imperative in certain cases that user sets the assumed box-model, for clipping, explicitly, so that is why combined values are supported. But it seems it is not so for Chrome (and Opera as far as I have tested).
So this is only a workaround untill full support of the feature is provided.


countForFetchRequest returning 1 for empty table

Question: I am executing a 'countForFetchRequest' and it is always returning 1 more count than the number of records in my table.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"TESTDATA" inManagedObjectContext:self.managedObjectContext]];

NSError *error = nil;
NSUInteger count = [self.managedObjectContext countForFetchRequest:request error:&error];
if(count == NSNotFound) {
    // Handle error
}

return count;

That returns 1 when my table is empty.  Returns 4 if my table has 3 rows.
sqlite> select count(*) from ZTESTDATA;
0
sqlite>

Any ideas on what I am doing wrong?
Comment: Have all objects been saved?
Comment: Have you tried removing all objects directly before getting the entity's count?
Comment: @Kraken, yes I remove all (actually remove the database and recreate), then count comes back as zero.  I then relaunch the app and the count is one more than it should be.  Regardless the raw sql query I perform always has the right count, seems like my core data query is messed up.
Comment: You should try a fetch request and see what object is there in the database. Maybe one of your query inserted something and you didn't noticed.
Comment: You really shouldn't be looking at a core data SQLite file directly with the SQLite tools.  Try executing that fetch request to see what this extra object is.
Comment: Are you able to open the db directly and browse it with **SQLite Database Browser**? To reach your app navigate to *~/Library/Application Support/iPhone Simulator*.
Answer: Count is always accurate but it counts both what is in memory (not saved yet) and what is on disk.
As others have suggested, do a fetch instead of a count and print out what Core Data finds and you will find your answer.
Comment: I think fetchRequest.includesPendingChanges = false will do the work


How to communicate between two different android apps

Question: I have a Notification started in the system bar by one application(Notification Manager), how can i remove/stop it from another application ? Can i use a broadcast receiver ? Will that work ?
Description:
Application A and B is installed. Application B is installed without the launcher option, so it is visible only in settings/apps (so the app is not started). Now App A has to start a service in App B.. Is this possible?
Comment: Duplicate question

http://stackoverflow.com/questions/1617925/how-do-two-android-applications-talk-to-each-other

http://stackoverflow.com/questions/4638939/android-communication-between-two-applications
Comment: A tcp ip connection over  localhost is allways a option
Comment: @sherif No, that would be completely unnecessary. The android SDK includes many ways for applications to communicate.
Answer: Hopefully something like this will help
http://developer.android.com/reference/android/app/NotificationManager.html


behavior of exponential integral $ E_{1}(x) $ near $ x=0 $

Question: is it possible to prove that in the
$$ \lim_{x \to 0^+} E_{1}(x)
   = \lim_{x \to 0^+} \int_{0}^{\infty} dt \frac{e^{-xt}}{t}
   = c +1/x+O(x)$$
what would be the constant $c$?
EDIT: this was my fault it should read $ \int_{1}^{\infty} dt \frac{e^{-xt}}{t}
   = c +1/x+O(x)$
in the limit $ t \to 0 $
Comment: Isn't there a typo? Your integral is never defined, since $\frac 1t$ is not integrable around $0$.
Comment: @Etienne OP meant for the lower limit to be $1$ not $0$.
Comment: OK, this looks better...
Answer: First, put $u=xt$ to get
$$E_1(x)=\int_x^\infty \frac{e^{-u}}{u}\, du\, ,$$
and then integrate by parts. This gives
$$E_1(x)=-\log(x) e^{-x} +\int_x^\infty \log(u) e^{-u}\, du$$
Since $\log(u)e^{-u}$ is integrable on $(0,\infty)$, the integral in the right-hand side tends to $c=\int_0^\infty \log(u) e^{-u} du$ as $x\to 0$. Moreover, integrating by parts again we get
\begin{eqnarray}
\int_x^\infty \log(u)e^{-u}du-c&=&\int_0^x \log(u)e^{-u} du\\
&=&(x\log(x)-x)e^{-x}+\int_0^x (u\log(u)-u)e^{-u}du\\
&=&O(x\log(x))\, ,
\end{eqnarray}
so that $\int_x^\infty \log(u)e^{-u}du=c+O(x\log(x))$. Finally, since $e^{-x}=1+O(x)$ we also have $\log(x)e^{-x}=\log(x)+O(x\log(x))$. Altogether, this gives
$$E_1(x)=-\log(x)+c +O(x\log(x))\, ,$$
with $c=\int_0^\infty \log(u) e^{-u} du $.
Comment: In fact, $\int_0^\infty \log(u)e^{-u}du=-\gamma\equiv -0.577$, where $\gamma$ is the Euler-Mascheroni constant. This integral appear on the wiki page for $\gamma$.


Errors when Taxonomy is chosen in node's Term Reference field

Question: I have created a vocabulary called "Recipes" with several terms underneath (Appetizers, Dinner, etc). I also have a content type called "Recipe" with a Term Reference field for the Recipes vocabulary.
When a term (let's say Appetizers) does not yet have a node referencing it via that Term Reference field, the term's page shows up fine (albeit without any node content). However, when I choose one of those terms on a Recipe node via that Term Reference field, the term's page shows three error messages and various elements of the page (such as the footer and the nav bar) are not displayed. The errors are:

Notice: Undefined property: stdClass::$type in _node_extract_type()
(line 379 of /home/mysite/public_html/modules/node/node.module).
Notice: Undefined property: stdClass::$nid in node_build_content() (line 1417 of /home/mysite/public_html/modules/node/node.module).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7721 of
/home/mysite/public_html/includes/common.inc).

I upgraded from 7.24 to 7.26, but that did not fix the issue. Google has not been particularly helpful. Does anyone here have any feedback on what might cause this issue? FYI, I also added a Term Reference field for the built-in "Tags" vocabulary, and the same issues occurred.
Answer: This EntityMalformedException: Missing bundle property on entity of type node errors seems to rear its ugly head in a lot of different contexts.
In my case it was a configuration of the view that showed the related nodes that had a couple of filters set wrong.
I had a relationship to related articles, but then in the filter section, Relationship was set to "Do not use a relationship" instead of using the related article. Setting the correct setting on the filter fixed the issue.


How to customize the very first page of the manual?

Question: By default, the first page that doxygen generates, in Rich Text Format (RTF) with below states:
TITLE

AUTHOR
Version
CREATEDATE

I want to customize this. I've tried the following, but it customizes the section after the index, rather than the very first page of the document:
/*!
 * @mainpage My Project
 * @version 0.91
 * @author Jack Vance, 2010.
 * CreateDate 2010-06-26
 */

Answer: No need to modify the template. After generating the rtf, in MS Word, select all->right click->Update Fields
Comment: but the AUTHOR field for rtf  is in the extension file (RTF_EXTENSIONS_FILE)
Answer: From the documentation:

For RTF output, you can generate the default style sheet file (see RTF_STYLESHEET_FILE) using:
doxygen -w rtf rtfstyle.cfg

You should then be able to edit the stylesheet to change the output the way you want.
Comment: Thats good enough for me: apparently its *impossible* to alter the front page of the Rich Text Format (RTF) output, without altering the style sheet.
Answer: in Doxygen 1.18.11, creating the style sheet didn't allow me to specify the author.  For that, I had to create and modify the "extensions file" via:
doxygen -e rtf extensionsFile


If substring in string, remove it through the end from string

Question: I'm trying to figure out how to do the following with javascript:
If a substring is in the string, remove from the beginning of the substring till the end of the string from the string.
For example (pseudocode):
var mySub = 'Foo'
var myString = 'testingFooMiscText'
var myString2 = 'testingMisctext'

var myStringEdit = //myString - (Foo till end myString)
var myString2Edit = myString2 //(cause no Foo in it)

Comment: So should the edited "testingFooMiscText" end up as "testing" or as "FooMiscText"?
Comment: @dmr To clarify, you would want `'testing'` from `myString`, correct?
Comment: So, if 'Foo' is in the string, you want to truncate the string starting at Foo? Is that what you're asking?
Comment: @Charmander is correct. I want to end up with `'testing'`
Comment: A super awesome tidbit for indexOf: Use ~ as invert: if(~index)
str = str.substr(index) -awesome read: http://timmywillison.com/pres/operators/#bitwise-operators - check out preceding slides for more context.
Answer: var index = str.indexOf(str1);
if(index != -1)
    str = str.substr(index)

Answer: If I understand what you're asking, you'll want to do this:
function replaceIfSubstring(original, substr) {
    var idx = original.indexOf(substr);
    if (idx != -1) {
        return original.substr(idx);
    } else {
        return original;
    }
}

Comment: +1 Only truncates if substring in original, else returns original.
Answer: If you want "testingFooMiscText" to end up as "testing", use
word = word.substring(0, word.indexOf("Foo"));

If you want "testingFooMiscText" to end up as "FooMiscText", use
word = word.substring(word.indexOf("Foo"));

You may need a +/- 1 after the indexOf() to adjust the start/end of the string
Answer: myString.substring(0, myString.indexOf(mySub))

Comment: However, mySub might not be in myString...so then the substring function won't work.
Comment: This doesn't return the original string if the substring isn't found. I believe that's what the OP wants.
Comment: Put it inside an if statement. Here is a question on checking to see if a string contains another. [link](http://stackoverflow.com/questions/1789945/javascript-string-contains)
Comment: Fair enough, @FishBasketGordo.
Answer: var newString = mystring.substring(mystring.indexOf(mySub));

Answer: This should do the trick.
var myString = 'testingFooMiscText'
myString.substring(myString.indexOf('Foo'))  //FooMiscText
myString.substring(myString.indexOf('Bar'))  //testingFooMiscText

Answer: I used following code to eliminate fakefile from file Name and it worked.
function confsel()
{
    val = document.frm1.fileA.value;
    value of val comes like C:\fakepath\fileName
    var n = val.includes("fakepath");
    if(n)
    {
        val=val.substring(12);
    }
}