hook_menu() items created in a custom module don't retain the active-trail of the parent tab

Question: So I have a custom module that is adding 3 menu items (a main tab, and 2 sub-tabs). When navigating to the main tab (url: /casereports) the default_local_task is displayed as expected and both menu items (Case Reports and Jobs Completed) are active as expected. Everything is working fine except that when I click on the second tab (Jobs Created), the main tab (Case Reports) loses it's active status.  I can't seem to figure out what I am missing here and why it is not picking up it's parent and the active-trail.  Any ideas?
function casereports_menu() {
  $items = array();

  $items['casereports'] = array(
    'title' => t('Case Reports'),
    'page callback' =>'drupal_get_form',
    'page arguments' => array('casereports_completed'),
    'access arguments' => array('access content'),
    'menu_name' => 'features'
  );
  $items['casereports/default'] = array(
    'title' => t('Jobs Completed'),
    'type' => MENU_DEFAULT_LOCAL_TASK
  );
  $items['casereports/created'] = array(
    'title' => t('Jobs Created'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('casereports_created'),
    'access arguments' => array('access content'),
    'type' => MENU_LOCAL_TASK
  );
  return $items;
}

Comment: Try removing `menu_name => 'features'` from the second tab
Comment: Does 'casereports' item have 'type' => MENU_LOCAL_TASK ? ie., Is case-reports menu item itself a tab or not ?
Comment: @Sharan That part of it is already correct. The problem has something to do with using a custom menu.
Comment: @JamesK I just wanted to know if "casereports" is a tab in itself or just a normal menu.
Comment: @Sharan the 'casereports/default' item makes it both
Comment: @JamesK tried removing menu_name with no effect. I'm wondering if it is a bug at this point.  I believe I have everything setup correctly.
Comment: @Sharan JamesK is correct.  'casereports' serves as the parent.  'casereports/default' inherits from 'casereports'
Comment: @JamesK so you are thinking this could be due to the fact that "features" is a custom menu?
Comment: @kevindeleon Sorry to ask this, but did you flush the menu cache after making the change?
Comment: @JamesK No worries.  It's a good question, but yes I did.
Comment: Why is 'menu_name' => 'features' being specified on the MENU_LOCAL_TASK but not on the MENU_DEFAULT_LOCAL_TASK?
Comment: @amateurbarista Actually that has been removed if you see my reply to JamesK above, however, it has no effect either way.  I added it originally in case it was needed to know the parent item, but I know now that it actually doesn't need to be there...I will edit my code to reflect this.
Answer: OK...so this basically ended up being more of an Open Atrium issue than anything else.  Due to the fact that Open Atrium relies heavily on Features and Context, the style sheet was setup to deal with the classes added by those modules.  Drupal's implementation of active-trail and active classes was working fine, however the theme's 'active' styles weren't setup to work without the classes added by the Context module.
I could either a) add a Context for the menu item added via my module (which is the route I took), or I could have (b) modified the CSS for the theme by adding a custom stylesheet.
Thanks for all the help guys, but I am embarrassed to say that in the end, it was just a bit of a theme problem from the Open Atrium install.
Answer: I really can't tell why is this happening, but I can give suggestions for finding out why is it happening. The best way to start would be by checking the menu_router database table to verify what is the difference between the MENU_DEFAULT_LOCAL_TASK and the MENU_LOCAL_TASK items in the database. If that does not uncover any clues, then I would start looking at the theming layer for answers. I would start by using Firebug to see what is the name of the active tab CSS class for the MENU_DEFAULT_LOCAL_TASK item, then search Drupal core for that class. Once I found the function that is outputting the active tab CSS class, I would pepper it with breakpoints (or debug statements if not using a debugger), and see what makes it giggles, so to speak. This process should give you enough information to know why is the MENU_LOCAL_TASK not being marked as active.
Comment: I actually have done some of what you said, and already determined that they are using the same tab_parent and tab_root...so that is correct.  Maybe you are right...I need to start looking into the theming layer.  I'll report back what I find.
Comment: So I did find that the parent tab is receiving the classes .active-trail and .active when the default tab is chosen (Jobs Completed).  However, when 'Jobs Created' is chosen, the parent tab 'Case Reports' only receives the class .active-trail.  The css for the the theme is only targeting parent tabs with the .active class. So I could just tweak the css, but it still interests me why it's not receiving both classes. Themeing maybe, or is it a bug in the core?
Comment: I am going to go ahead and throw the bounty points your way since your answer got me thinking down the correct path.  It wasn't the "correct" answer so to speak, but it definitely got me moving in the right direction.
Comment: Yup, that was the purpose of my answer, not to serve as a definitive, conclusive answer, but as a path to finding one. Glad to know it helped ;)


Generalizar uma função de dropdown Javascript?

Question: Olá, estou com uma certa dificuldade de generalizar uma função de dropdown, imagino que eu esteja fazendo algo bem errado, procurei sobre em fóruns e não achei a resposta por isso vou abrir esse tópico.
Meu código HTML está assim, há vários botões com as mesmas classes porém eu quero que cada um faça um dropdown somente para o seu respectivo menu:

Ferramentas

  Action
  Another action
  Something else here

O CSS assim:
.sb-dropdown-menu{
    display: none;
}
.sb-dropdown-menu.dropdown-active{
    display: block;
}

E o JavaScript assim:
$('.sb-dropdown-toggler').each(function () {
    $(this).click(function (e){
      e.preventDefault();
      $(this + ' .sb-dropdown-menu').toggleClass("dropdown-active");
    });
  });

Minha intensão é fazer com que o submenu de cada botão seja ativado somente pelo seu "pai", é possível fazer isso do modo que estou fazendo? Tenho que adicionar ou retirar algo? Tentei de diversas maneiras e não consegui, eu imagino que eu tenha que adicionar um ID para cada um mas não sei como fazer isso, agradeço a ajuda de quem puder
Comment: Qual a relação do link com o dropdown?
Comment: São irmãos (estão na mesma div, separadas dos outros), é sempre um após o outro....
Comment: E você tem vários desses blocos em sequência? Geralmente se usa listas para isso. De qualquer maneira, sua função deve funcionar minimamente se você usar `$(this).next('.sb-dropdown-menu')`, em vez de `$(this + ' .sb-dropdown-menu')` que está errado.
Comment: Era exatamente isso @bfavaretto, obrigado!
Comment: Legal que resolveu!
Answer: O JavaScript abaixo deve atender aos eventos sobre o alvo:
$('.sb-dropdown-toggler').click(function (e) {
    e.preventDefault();
    $(this).next().toggleClass("dropdown-active");
});

Não testado, estou no celular. Dá uma olhada: https://www.w3schools.com/jquery/jquery_ref_traversing.asp


Script to make 1 random layer visible within each group [Photoshop cc2018]

Question: I'm trying to make a script that would at random select and show a single layer from all groups on Photoshop and export the result as a png.
I found this script here that seems to work:

function Visible() {
  var Grps = app.activeDocument.layerSets; // loops through all groups
  for(var i = 0; i < Grps.length; i++){
    var tmp = app.activeDocument.layerSets[i].layers.length;
    app.activeDocument.layerSets[i].visible=true;
    var groupChildArr = app.activeDocument.layerSets[i].layers;
    var randLays = Math.floor(Math.random() * tmp);
    groupChildArr[randLays].visible = true;
    Save();
  }
  Revert();
}

function Save() {
  var outFolder = app.activeDocument; // psd name
  var outPath = outFolder.path;
  var fName = "PNG";   // define folder name
  var f = new Folder(outPath + "/" + fName);
  if ( ! f.exists ) {
    f.create()
  }
  var saveFile = new File(outPath + "/" + fName +"/" + "Pattern_" +  num + ".png");
  pngSaveOptions = new PNGSaveOptions();
  pngSaveOptions.interlaced = false;
  app.activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}

function Revert(){
  var idslct = charIDToTypeID( "slct" );
  var desc300 = new ActionDescriptor();
  var idnull = charIDToTypeID( "null" );
  var ref163 = new ActionReference();
  var idSnpS = charIDToTypeID( "SnpS" );
  ref163.putName( idSnpS, "test.psd" );
  desc300.putReference( idnull, ref163 );
  executeAction( idslct, desc300, DialogModes.NO );
}

var count = prompt("How many patterns you want","");
for (var x=0 ; x<count;x++){
  var num = x+1;
  Visible();
}
Share

Except it gives me an error 8800: General Photoshop error occurred. This functionality may not be available in this version of Photoshop.
Line: 36
-> executeAction( idslct, desc300, DialogModes.NO );
Is there smth I can do to make it work as that would greatly help speed up my work process.
Thank you.
Answer: Without seeing what your PSD looks like, it's hard to tell. However, I think the code is failing on the revert function.
Try this instead:
function Revert()
{
  // =======================================================
  var idRvrt = charIDToTypeID( "Rvrt" );
  executeAction( idRvrt, undefined, DialogModes.NO );
}


OS library Python - Localizando Diretórios

Question: Estou aprendendo como localizar diretórios em Python e me deparei com o seguite código:
import os

dir_path = os.path.dirname(os.path.realpath(__file__))
print(dir_path)

cwd = os.getcwd()
print(cwd)

Por que na linguagem Python usa-se __file__ para se referir ao arquivo atual?
Como esse comando se relaciona com toda a sintaxe?
Qual a desvantagem em usar os.getcwd()?
Answer:
Você só obteve o mesmo retorno nos dois casos porque está executando o script diretamente, no mesmo diretório de trabalho.
Faça o teste você mesmo, coloque esse script em algum outro diretório. Abra um prompt no desktop e execute o script a partir desse local de trabalho, por exemplo:
py C:\meus-scripts\script-do-arduin.py

A saída será:
C:\meus-scripts
C:\Users\Arduin\Desktop

Ou seja, não é a mesma coisa.
os.getcwd retorna uma string representando o diretório de trabalho atual, por isso deve-se tomar um certo cuidado ao utilizar os.chdir(). Já __file__ contém o path do arquivo no qual o módulo foi carregado (se este for carregado a partir de um arquivo).
Answer: a expressão file é uma variável "mágica" que retorna uma string contendo o nome do arquivo atual.
as expressões da linha 3 e 6 são apenas formas diferentes de resolver o mesmo problema, a desvantagem da linha 3 é que você está executando 2 métodos e na linha 6 somente 1.
Comment: Não são a mesma coisa.


ArchLinux multi home not responding on one interface

Question: I have a bunch of kit in a DC running through Cisco ASAs - this isn't really working out as it relies on us creating, paying and waiting for tickets concerning out network config.
I've been and installed a couple of R230s running pfSense, along with a couple of new switches.
The idea was to have the 2 (4) firewalls running side by side whilst we decide exactly how we want ruling to work on our pf boxes.
To test this out, on one of my servers I have the following config.

enp3s0f0:
IP: 10.66.82.16/24
GW: 10.66.82.1

enp4s0f0
IP: 10.44.50.100/24
GW: 10.44.50.250
Now, with either one of these disabled, things work as I expect - ie:

enp3s0f0 enabled, enp4s0f0 disabled:

I can connect to the ASA VPN, and SSH (or otherwise connect to running apps)

enp3s0f0 disabled, enp4s0f0 enabled:

I can connect to the pfSense VPN, and SSH (or otherwise connect to running apps)

enp3s0f0 enabled, enp4s0f0 enabled:

If I connect to the pfSense VPN, I can connect via 10.44.50.100.
    Disconnecting from above, and connecting to the Cisco VPN, I can't connect to 10.66.82.16.

In all instances where I get no connection, it times out and is not rejected.
When both enabled, the routes (appear) to be correctly added;
default via 10.44.50.250 dev enp4s0f0  proto static
default via 10.66.82.1 dev enp3s0f0  proto static
10.44.50.0/24 dev enp4s0f0  proto kernel  scope link  src 10.44.50.100
10.66.82.0/24 dev enp3s0f0  proto kernel  scope link  src 10.66.82.16

I literally have no idea where to head from here, most stuff I've read about seems to identify ip_forwarding as the issue - I've tried this but don't think it relates to my setup on account of being two discrete network cards.
Any help will go a looooong way!
Thanks!
Dave.
Answer: EXAMPLE WITH NETCTL
eth0 fixed / gateway: 10.18.100.1 fixed ip: 10.18.100.102
wlan0 dhcp / gateway: 10.18.110.1 fixed ip: 10.18.110.104 associated to wlan0's mac address
cat /etc/netctl/home-network

Description='Static Ethernet Connection'
Interface=net0
Connection=ethernet
IP=static
Address=('10.18.100.102/24')
Gateway='10.18.100.1'
DNS=('22.214.171.124 18.104.22.168')

echo "123 rtac87u" >> /etc/iproute2/rt_tables

cat /etc/netctl/home-wireless

Description='WPA-PSK'
Interface=wlan0
Connection=wireless
Security=wpa
IP=dhcp
ESSID=ASUS5G1
#wpa_passphrase ASUS5G1 my-long-clear-text-psk
Key=\"string-generated-by-wpa_passphrase
ExecUpPost="ip route add default via 10.18.110.1 dev wlan0 table rtac87u; ip rule add from 10.18.110.104 table rtac87u"

netctl reenable home-network

netctl reenable home-wireless

netctl restart home-network

netctl restart home-wireless


Adding Rows to a Local DataSource for API Testing

Question: I want to use my Local Data Table as a dynamic source that I can add an unknown set of rows into. Is that doable?
The goal is to just attach it as a driver to the loop that needed to load data from an excel sheet that contains a subset of our master data variables.
(200 possible test variables but for testing a specific section of the code we only need to twiddle 3 bits.
I could use an array, but this needs to be maintainable by untrained UFT testers when I'm gone. Easiest way is to create the list on the fly depending on the content of the data driver sheet.
Comment: I can't find a tag for uft-api (to differentiate from uft-gui testing.)  Thoughts?
Comment: Maybe I don't fully understand your question but can't you just ask the testers to update the Excel file and load it into your datatable at runtime?
Comment: Check my [**answer**](http://stackoverflow.com/a/37706073/1652222) for similar question. You may have to edit SQL part to suit your needs.
Comment: Sorry -- Been flat out trying to get ready for deployment.  Finally found a way to work it, but had to create a "blank" localDataTable long enough that it could support changes to every single data element on the form (197). Then, as I read in one of the 349 already written driver sheets, I capture the parameter names (column headings) from the excel with out headers, and store them in the local table. When I hit a blank heading, I set my total rows for the parameters.  Thanks for the feedback! Zac - We have a library of excel sheets for regression testing. Touching them isn't an option.
Answer: You can attach dynamic an excel file, or you can use a step to populate a local data source.
In my case, I have one step called "Lookup" than load some registers from a web grid and populate the local data source of "Detail" step.
<code>For Iterator = 1 To TestArgs("LookupIterations") Step 1
    If Browser("AWAT").Page("W").Frame("ipsToolbar").WebElement(getGridXpath(Iterator,3)).Exist(1) Then
        DataTable.GetSheet("Detail").SetCurrentRow Iterator
        Datatable("RowId","Detail") = Iterator
        Datatable("FromType","Detail") = Browser("Water (AWAT) | IPS").Page("Water (AWAT) | IPS").Frame("ipsToolbar").WebElement(getGridXpath(Iterator,3)).GetROProperty("outertext")
        Datatable("FromID","Detail") = Browser("Water (AWAT) | IPS").Page("Water (AWAT) | IPS").Frame("ipsToolbar").WebElement(getGridXpath(Iterator,4)).GetROProperty("outertext")
        Datatable("ToType","Detail") = Browser("Water (AWAT) | IPS").Page("Water (AWAT) | IPS").Frame("ipsToolbar").WebElement(getGridXpath(Iterator,5)).GetROProperty("outertext")
        Datatable("ToID","Detail") = Browser("Water (AWAT) | IPS").Page("Water (AWAT) | IPS").Frame("ipsToolbar").WebElement(getGridXpath(Iterator,6)).GetROProperty("outertext")
    Else
        Iterator = TestArgs("LookupIterations") + 1
    End If
Next
</code>


What is the dual function of the $f(x) = \sum_i x_i \ln(x_i)$?

Question:
I have always assumed that the dual of  $$f(x) = \sum_i x_i \ln(x_i),
 x \in \Delta^N$$ is $$f(y) =  \ln(\sum_i e^{y_i}), y \in
 \mathbb{R}^N$$ (and vice versa, the other direcion is extremely well
  known)

However, in MM Optimization Algorithms by Kenneth Lange, it writes:

However, notice the domain is $x \in \mathbb{R}^m$

Can anyone please confirm the dual of neg entropy function $$f(x) =
 \sum_i x_i \ln(x_i), x \in \Delta^N$$
References are much appreciated
Answer: You are both correct. There are two conjugate pairs:
$$
\begin{align*}
f(x) &= \begin{cases} \sum_i x_i \ln(x_i) & \text{if } x \in \Delta^N \\ \infty & \text{else}\end{cases} \\
f^*(y) &=  \log\left(\sum_i e^{y_i}\right)
\end{align*}
$$
and
$$
\begin{align*}
g(x) &= \begin{cases} \sum_i x_i \ln(x_i) & \text{if } x \in \mathbb{R}^n_+ \\ \infty & \text{else}\end{cases} \\
g^*(y) &=  \sum_i e^{y_i-1}
\end{align*}
$$
See, e.g., Table 1.


Need ideas to change a key's name of JSON Object on RUBY

Question: i am finding a method to change a key's name of json object that is a hash on ruby like below
source
{ "a" => "b", "b" => "bb" }

result
{ "c" => "b", "b" => "bb" }

got a nice idea ?
Comment: http://stackoverflow.com/questions/9603567/change-all-key-names-of-json-object-in-ruby
Answer: If you need this functionality frequently, you can extend the Ruby Hash class.
Implementation would vary from ruby version to version, but roughly something like this:
class Hash
  module ClassMethods
    def self.replace_key(old_key, new_key)
     self[new_key] = self[old_key]
     self.delete(old_key)
    end
  end
end

Basically, creating a new key,value pair in the Hash using the new key and old value. Then deleting the original pair.
Note: Operations like this on large hashes are inadvisable from a performance perspective.
Answer: source = { "a" => "b", "b" => "bb", "c" => "lol" }
PATTERN = { "a" => "c", "c" => "e" }
source.inject({}) do |new_hash, (k, v)|
  key = PATTERN[k] || k
  new_hash[key] = v
  new_hash
end
#=> { "c" => "b", "b" => "bb", "e" => "lol" }

Answer: If you are serializing ActiveRecord or ActiveModel object, you can overwrite as_json method of the class. Like so:
class Foo < ActiveRecord::Base
  def as_json(options = { })
     super((options.select {|k,v| k.to_s != "a" }).merge("c" => options["a"]))
  end
end


How to implement built-in sum() of the class?

Question: The built-in function sum() applied to a dictionary returns the sum of its keys:
>>> sum({1: 0, 2: 10})
3

I'd like to create a subclass of the dictionary, say SubDict, and override some function to return the sum of its values, i.e.
>>> sum(SubDict((1, 0), (2, 10))
10

Which function do I need to override to achieve this functionality?
This is a general question, how to implement the built-in sum() function to a class, not just in this particular case.
Comment: It's worth noting that there was actually a brief discussion on python-ideas of adding a "summation protocol"—a method that classes could override to change how they're summed—as part of a larger discussion of making `sum` work better for flattening lists of lists and the list. Pretty much nobody thought it was a good idea. The original author of the `sum` builtin specifically wanted it to only work on sequences of numbers, period, and the only reason it works on any iterable over anything addable is that there was no good way to restrict it back in Python 2.0.
Comment: thanks for this comment. I thought there would be some kind of ______sum______ method, since there's ______abs______ and the built-in abs() uses it.
Comment: In general, only low-level functionality that couldn't be efficiently built on top of something else gets a dunder-method protocol. [Data model](http://docs.python.org/3.3/reference/datamodel.html) has a complete list of all such methods used by Python itself or its builtins; there are a few more specified by other modules like `pickle`.
Answer: sum is effectively implemented like this:
def sum(sequence, start=0):
    for value in sequence:
        start = start + value
    return start

So, you can't override sum directly… but if you can override the way for value in … works on your sequence,* or the way + works on your values, that will affect sum automatically. Of course either one will have side effects—you'll be affecting any iteration of your sequence, or any addition of your values, not just the ones inside sum.
To override iteration, you need to provide a __iter__ method that returns an appropriate iterator. To override addition, you need to provide a __add__ method.

But really, why are you trying to "override sum"? Why not just write a new function that does what you want? You can add code that special-cases your type(s) and then falls back to the builtin sum otherwise. If you want to make it more "open", you can use PEP 443 single-dispatch to make it easy to register new types to be special-cased. I think that's what you really want here.

* As agf points out in the comments, despite the parameter being called sequence, it actually takes any iterable. Which is a good thing, because dictionaries aren't sequences…
Comment: Overriding `+` wouldn't cause a `dict` to sum by values. Also, `sum` doesn't require a sequence, it requires an iterable. You've also got `start = 0` both in the args and in the function body.
Comment: @agf: But overriding `iter` _would_. And the parameters are explicitly named `sequence` and `start`. See the docstring, etc.
Answer: You can just do:
In [1]: sum({1:0,2:10}.values())
Out[1]: 10

If you want to implement a subclass who's sum will be the sum of values, just override the __iter__ method:
In [21]: class MyDict(dict):
   ....:     def __iter__(self):
   ....:         for value in self.values():
   ....:             yield value
   ....:

In [22]: d = MyDict({1:0,2:10})

In [23]: sum(d)
Out[23]: 10

But then you wont be able to do:
for key in d:
    print d[key]

Because the __iter__ function will return values... You'll always have to use the keys() function:
for key in d.keys():
    print d[key]

Better solution would be to add a sum method:
In [24]: class MyDict(dict):
   ....:     def sum(self):
   ....:         return sum(self.values())
   ....:

In [25]: d = MyDict({1:0,2:10})

In [26]: d.sum()
Out[26]: 10

Comment: Doesn't answer his question of how to do this in general.
Comment: thus, the summary is that it's impossible to "override" sum() of the dict, since the overriding of __iter__ destroys the dict behaviour of the subclass. Aside from having to iterate the subclass of dict the other way, through __iter__ I would also change the results of the built-in enumerate() and for sure some other functions. Did I miss anything?
Comment: Probably :) There are many things that rely upon the fact that the dictionary will iterate through it's keys. :-/ But you can always add a `sum` method (I'll update the example).
Comment: @MaxLi: Well, it doesn't destroy _all_ of the dict behavior of the subclass, just the iterating-means-iterating-keys behavior (like `enumerate`, and `list`, and `max, and using it in a comprehension, and .…). If that's not what you want… then don't do it.
Comment: Actually I find the dictionary with modified `__iter__` quite elegant! It's complementary to the normal dictionary. While most problems are perhaps better off with a normal key-iterable dictionary, others would likely benefit from a value-iterable dictionary.


ASP.NET Core Route attributes available in entire controller class

Question: Is there a way to make attributes specified in the route available in the whole class? For instance, consider this Controller:
[Route("api/store/{storeId}/[controller]")]
public class BookController
{
    [HttpGet("{id:int:min(1)}")]
    public async Task<IActionResult> GetBookById(int storeId, int id)
    {
    }
}

And this request:
/api/store/4/book/1

Inside the GetBookById method, the storeId variable is correctly populated with 4 and the id variable with 1. However, instead of having to pass the storeId variable in every method of the BookController, is there a way to do something like this:
[Route("api/store/{storeId}/[controller]")]
public class BookController
{
    private int storeId;

    [HttpGet("{id:int:min(1)}")]
    public async Task<IActionResult> GetBookById(int id)
    {
        //use value of storeId here
    }
}

Answer: If the controller inherits from Controller class then you can override OnActionExecuting method, if the controller inherits from ControllerBase you need to implement IActionFilter interface to make it work
[Route("api/store/{storeId}/[controller]")]
public class BookController : ControllerBase, IActionFilter
{
    private int storeId;

    [HttpGet("{id:int:min(1)}")]
    public async Task<IActionResult> GetBookById(int id)
    {
        // use value of storeId here
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        //empty
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        string value = context.RouteData.Values["storeId"].ToString();
        int.TryParse(value, out storeId);
    }
}

Or there is a better solution for this using [FromRoute] attribute on a controller property (as desribed here)
[Route("api/store/{storeId}/[controller]")]
public class BookController : ControllerBase
{
    [FromRoute(Name = "storeId")]
    public int StoreId { get; set; }

    [HttpGet("{id:int:min(1)}")]
    public async Task<IActionResult> GetBookById(int id)
    {
        // use value of storeId here
    }
}


How to find an asp.net client is disconnected immediately

Question: I'm aware of Response.IsClientConnected but in my scenario it has a great lag. Code:
// sample code for sending a dynamic file in chuncks

long bytesSent = 0;

while (continueSending)
   {
      if (!AskReceiverToContinue())
         break;

      if (!Response.IsClientConnected)
         break;

     // Your suggestion goes here... :)

      try
      {
         Response.OutputStream.Write(buffer, 0, buffer.Length);
         bytesSent += buffer.Length;
      }
      Catch
      {  // To my experience, this is more reliable than Response.IsClientConnected
         continueSending = false;
      }
   }

The problem is the actual received bytes by client is very smaller in amount than my bytesSent. It seems when a client gets disconnected my program finds out the situation with a great lag (and continue increasing bytesSent) and this is because ASP.NET tells me the situation (client is disconnected) late.
Is there any reliable method for finding out when a client has been disconnected (real-time) ?
Comment: Just curious: why do you care for such thing?
Comment: @Shadow: And most power users refuse to install that activeX es
Comment: Because it's more fair to charge my clients traffic-basely. But it seems I cannot move to such a solution !
Comment: you can if you use a client that explicitly connects over tcp/ip, meaning a progam the user would've to download. Your plan isn't possible via a webpage.
Comment: What about Java or Flash? They might have better control over such things. Some websites giving access to big files even ask the client to install activeX control.
Answer: You are transfering over HTTP, aren't you? If yes, there is no way due to the statelessness of the HTTP protocol. Only thing you have to help you is the timeout, which you are already using.
Comment: Yes, I'm using HTTP. As I know, there's a underlying `TCP` connection. Why ASP.NET doesn't update `IsClientConnected` as soon as the `TCP` connection is closed ? Can I access the native handle or something like that ?
Comment: I guess they are estimating it given the users speed over time.
Comment: Even if this were possible, it wouldn't change a thing as the TCP connection would only be closed if the client timed out. If the client doesn't tell you that he is gone, you have no chance of seeing it bar a timeout.
Comment: Then how rapidshare.com counts the users traffic ?


Showing set is undecidable with Turing Machines

Question: I'm given the set $T = \{\langle M, w\rangle : M $ is a Turing Machine that accepts $w$ reversed whenever it accepts $w \}$ and I want to show it's undecidable but recognizable. (I'm using the bracket notation to denote the encoding of the TM and input string)
Given that I know the set $A = \{\langle M,w\rangle : M \text{ accepts } w \}$ is undecidable but recognizable, I'm trying to show that $A$ reduces to $T$.
I start by assuming that $T$ is decided by a Turing Machine $R$ and then attempt to construct a new Turing Machine, $S$, that will decide $A$ by using $R$ as a subroutine.
To construct this new machine $S$, I will run $R$ on input $\langle M,w\rangle$. If $R$ accepts, then $\langle M,w\rangle$ is in $A$. However, $R$ rejecting doesn't necessarily mean that $\langle M,w\rangle$ isn't in $A$, since $M$ might reject $w$ reversed but accept $w$. So now I'm confused on how to actually construct the reduction. Any help would be great
Answer: Suppose T is decided by R.
Construct the following machine H.
$H(<A>, x):$
1)  Create the following machine $< M >:$
$\quad\quad M(w):$
$\quad\quad\quad  A(x)$
$\quad\quad\quad accept$
2) if $R(<M, w>)$ accepts then
$\quad\quad accept$  (since A(x) halts)
$\;\;\;$else
$\quad\quad reject$  (since A(x) loops)
Note that $<M>$ is constructed to accept all w if and only if A(x) halts.
In that case, $<M>$ certainly accepts w and reverse(w).
So $<M, w>$ is in T if and only if A(x) halts.
If R is a decider, then H would be a decider for the Halting problem.
So, T must be undecidable.
Now, construct the recognizer for T:
$R(<M, w>):$
$\quad$ if M(w) accepts and M(reverse(w)) accepts then
$\quad\quad$ accept
$\quad$ else
$\quad\quad$ reject
Note that if either M(w) or M(reverse(w)) rejects or loops then R will reject or loop.
So, R is a recognizer for T.


Most useful piano exercises to memorize for playing by ear?

Question: I'm not talented at all but I consider myself very dedicated and with a good ability to learn and memorize new material through my hands (not ears)
I'm playing the piano on my own for 2 years, practicing mainly from sheets. Lately I decided I want to focus on pop genre, the songs I hear on the radio, which I want to be able to cover on my own without sheets one day. (At the moment I'm not even close to the level of players I see on YouTube.)
How can I apply my memorizing skills in order to help me be a better pop player and achieve my goal of playing by ear? I feel like I'm far from there. I haven't found a good way to memorize piano notes or memorize and recognize intervals unfortunately, since those are more related to hearing rather than muscle memory which I'm better at. Will memorizing songs with common patterns help me? Will memorizing many chord progressions, cadences and scales be the best I can do to improve? Should I insist more on intervals recognition?
I have around 1 hour a day for practicing and I want to make the most out of it in order to play by ear one day. I would really love to hear your suggestions for me.
Comment: My experience is that I have no problems to play easy pop songs just by ear. But for more difficult pieces you need a lot of technical practice that the fingers know what scales or licks they have to play. But I need all: the ear, the muscle memory and the chord progression.
Answer: Muscle memory and playing by ear are very much related. You probably don't want to just memorize songs or chord progressions because that won't help you in the long run. Instead, try to figure out songs by ear. This is the main exercise, but it gets easier with every song you work on because you're making a link with what you hear to where your fingers go.
You need to familiarize yourself with the sounds and develop muscle memory. Before you press a certain note you'll already know what it's supposed to sound like in your head. That way you can play anything you hear instantly or jam alongside with someone as they play. It's the same as whistling and humming. But in order to do this you should build a solid foundation first:

Practice scales / arpeggios. Do this alongside figuring songs out by ear, or you'll just get bored. The reason for practicing scales is mainly just knowing what the pattern is (what black/white notes need to be pressed for that given key). Everything you hear around you on a day-to-day basis is in a different key. You need to get to the point where the patterns of scales and their associated diatonic chords are ingrained in your head. What makes it easy is that all major keys work exactly the same, they're just higher/lower pitches of the same sound of "do re mi fa so la ti do". and minor is just a mode of major, so first learn major and then you just shift it to get to minor. you'll see what I mean later.
Figure out songs by ear. This is the most important part. Start with nursery rhymes / baby songs as those are the easiest. So "row row row your boat" or "twinkle twinkle little star" or whatever other songs you've heard in your childhood, "amazing grace", etc. Don't use sheet music for these. Just try to pick them out by ear. Especially the melody. Once you've found the melody try to figure out what scale you're in based on the practice you did with 1.
Add chords to the nursery rhymes. You'll find that the I IV V chords (primary triads) are the most often used followed by the vi ii and iii chords. (assuming we're talking about a song in the Major key). The roman numerals that I just wrote are the diatonic chords of the scales, if you don't know what those are and how to find them from the scales, do some research. You'll be playing those chords in your left hand, whereas the melody is in your right hand.
Try to play the nursery rhyme in any key. You should eventually be able to play "Row row row your boat" for example, in all 12 major keys both the melody and its chords.
You can transpose any major song to the key of C major to make it easier for you to experiment with what chords sound best. So know how to play all the nursery rhymes in the key of C major for example. You can then practice with songs in minor keys.

The nursery rhymes / practicing scales/arpeggios then becomes the "foundation" of your muscle memory and ear training. Keep adding more and more songs. Just keep a piece of paper with all the songs you've figured out by ear. The more you do this you'll find that you don't even need to keep a piece of paper anymore because you'll be able to play whatever you hear instantly.
You'll then be surprised that pop songs aren't that much harder than nursery rhymes. It's pretty much all the same. You just add chords to melodies in whatever key you're in. By practicing playing songs by ear, the more you'll do it, you'll develop muscle memory to the point where your fingers will go directly to what you are hearing in your head both for melody and harmony.
Answer: I try to do exactly what foreyez says. I'm still working on this. The biggest problem to me seems when I play e.g. pieces by Bach that I've learnt only by muscle memory or ear and I'm making the same mistakes or get completely lost as I didn't know what I was playing 60 years ago. Nobody told me then how to analyze the chords or the form.
Today I make a lot of own finger studies for trills or turnarounds,  scales and arpeggios.
There are a few points I'd like to add:

Work out the form of a piece or song.
Write down the chords on a leadsheet.
Make a mind map (motifs and chords, graphic notation)
use lyrics of other songs and poems to associate the music to their form (e.g. Ave Maria *)
take the motifs or chord progression and improvise on it, play with these elements by reassembling these elements.
what I often do is playing one hand full harmony and the other in 8va just to internalize the process of the melody and the chords.

or I play both voices in one hand (so I can better see and hear the counterpoint)
playing it very slowly like a choral - always minding what I play

The greatest benefits for understanding and memorizing to me is transposing a piece first in C adding Roman numbers and playing it in all kind of keys (circle of fifths)
*) eg. what I did with this little prelude by Bach (WTC 924:
(original):

my version:


Finding the confidence level and number of successes?

Question: Given that the sample size is $1500$ and the confidence interval of $p$ is $(0.050, 0.083)$. Find the confidence level and the number of successes.
I have so far that $E=Z_{1-\alpha/2}∗\sqrt{(p∗({p-1}))/n}$
Where $p$ is the center of the given interval, so $p = (0.050+0.083)/2 = 0.0665$
Also, the error $E$ as the difference of the midpoint and the endpoint of the interval so $E=0.0665-0.050=0.0165$
Plugging this into the equation I got that
$0.0165=Z_{1-\alpha/2}*\sqrt{((0.0665)(1-0.0665))/1500}$
Solving for $Z_{1-\alpha/2}$ gives $Z_{1-\alpha/2}=2.56$ and since $Z_{2.96} = 0.99$
$Z_{1-\alpha/2} = 0.01$
Is what I have so far right? If so, how do I find the number of successes? Is it just to multiply 0.99 by the number of trials?
So that way I would get $1500*0.99=1485$ ?
Comment: Quick question, why is $p$ the center of the confidence interval?
Comment: I assume since the ends of the confidence intervals are $p \pm E$ ? I'm not certain though
Answer: Because $p = X/n,$ we have $X = np = 1500(.0665) = 99.75 \approx 100.$
To check everything, let's start from $n = 1500$ and $X = 100$ and
see what the formula for a 99% CI gives (when your derived values
are plugged in):
$$ p \pm 2.576\sqrt{\frac{p(1-p)}{n}}.$$
It becomes $(0.050, 0.083),$ which agrees with the initial 99% CI
(computations using R as a calculator below).
<code> x = 100; n = 1500; k = qnorm(.995); pm = c(-1,1); p = x/n; p
 ## 0.06666667
 p + pm*k*sqrt(p*(1-p)/n)
 ## 0.05007675 0.08325658
</code>
Note: This is supposing you are using the 'traditional' CI given
in the displayed expression above. A more accurate 'Agresti' (or
'Plus-4') interval uses $n^+ = n+4$ and $p^+ = (X + 2)/n^+$,
substituting $n^+$ for $n$ and $p^+$ for $p$ in the same
expression. However, the adjustment for the Agrest-style interval
is negligible when $n$ is a large as 1500. Also, the Agresti-style
CI works best for 95% CI's.
Comment: Thanks so much for your answer! This was very helpful!


How to make p-table reset with default sorting in primeng?

Question: I am loading the data from API. The data is huge so I am using the lazyloading.
On the page load I am sorting the table by giving the input in the HTML template like below, it is working fine

But my page has the reset button also, So if the user clicks the button I am trying to reset it default.
So in my component code I used the below code
this.dataTable.reset();

The problem is I am trying to sort the table. So I used the following code,
this.dataTable.reset();
this.dataTable.sortField = 'id';
this.dataTable.sortOrder = 1;

using the above code the table gets sorted and the problem is API is calling 3 times. So I am trying to implement the sort on the table reset. So I tried the below code,
this.dataTable.reset({'sortField':'id',sortOrder: 1});

But I am getting the error. How can I do it?
Answer: The problem is that the sortField and sortOrder are setters and trigger loading.
you can hack it for example this way.
this.dataTable.lazy = false;
this.dataTable.reset();
this.dataTable._sortOrder = 1;
this.dataTable.lazy = true;
// calls the endpoint
this.dataTable.sortField = 'id';

But of course your onLazyLoad method can check if $event.sortField is set or not and return.
I'd choose the 2nd option since that is not a hack just a validation. The point is that the sortField must be set at last just like in you example.
Answer: I tried the answer provided by @tano, but the default sort ('id') was not being maintained.
this.dataTable.lazy = false;
this.dataTable.reset();
this.dataTable._sortOrder = 1;
this.dataTable._sortField = 'id';
this.dataTable.lazy = true;
// calls the endpoint
this.dataTable.sortSingle();


I want to create version for every build in visual studio

Question: So whenever i deploy the changes on server I need to clear the cache on my local system browser to reflect the changes on website. to prevent this in javascript we give version to each and every file so we dont need to clear cache to reflect changes,

Example: source/file.js?V2

Here we are working with react js(asp.net core Visual studio 2019) with every publish visual  studio 2019 generate the following file
ClientApp(consist of build,js(Bundled JS) css(Bundled css) file)
runtimes
ru-ru
DLLs(application and third party dll)
So how can we give version to every build or file so we don't need to clear cache whenever changes are deployed on server
we working with
react js,asp.net core visual studio 2019
Answer: Doing that per build doesn't make a lot of sense. What makes more sense it invalidate it if the file was changed. For that people usually append a hash to the url, i.e. ~/js/app.js?v=<hashhere>.
ASP.NET Core comes with a tag helper which adds and calculates the hash for you, called asp-append-version.

Every time the file is changed, the hashes changes and will result in a different src url, forcing the browser to load it from the server rather than caching it


determine solution of the form $ \ u(x,t)=g(\frac{x}{t}) \ $ to $ \ u_t+uu_x=0 \ $

Question: The below transition has been made as starting point to this problem
$$0=u_t+uu_x=\frac{1}{t} g' (g-\frac{x}{t})$$
How $\frac{1}{t} g' (g-\frac{x}{t})$ was derived ? I don't understand it.

This is the example 1.13  from the textbook (p.19 http://people.uncw.edu/hermanr/pde1/PDEbook/PDE_Main.pdf)
Answer: Okay so you start with $u_t + u u_x$ and you force your function $u(x,t)$ to look like $g(\frac{x}{t})$ i.e. $u(x,t) = g(\frac{x}{t})$ like you said. Now in our differential equation we have a $u_t$ and a $u_x$ so lets compute those in terms of our new function $g$.
$$u_t \equiv \frac{\partial}{\partial t}u(x,t) = \frac{\partial}{\partial t}g(\tfrac{x}{t}) = \frac{\partial (\tfrac{x}{t})}{\partial t}\frac{\partial g(\tfrac{x}{t})}{\partial (\tfrac{x}{t})} = -\frac{xg'}{t^2}$$
Now lets compute $u_x$
$$u_x \equiv \frac{\partial }{\partial x}u(x,t) = \frac{\partial}{\partial x}g(\tfrac{x}{t}) = \frac{\partial (\tfrac{x}{t})}{\partial x}\frac{\partial g(\tfrac{x}{t})}{\partial (\tfrac{x}{t})} = \frac{g'}{t}.$$
So now lets plug these back into our differential equation to obtain
$$u_t + uu_x = -\frac{xg'}{t^2} + g\frac{g'}{t} = \frac{g'}{t}\left(g - \frac{x}{t}\right).$$


Como adicionar onClick no botão "Desenhar Forma" do Google Maps Api?

Question: Eu gostaria de adicionar o evento "onClick" no "Desenhar Forma" do "Drawing Controller" do google maps api v3.
Não consegui achar na documentação e não tem como clicar com o botão direito no botão para verificar se possui um "id".
Alguém saberia como fazer isto?
Answer: Basta você pegar a forma, apontando sua variável.
Por exemplo, digamos que você tenha um ponteiro de localização.
Você chama a variável dele e insere um evento com:
marker.addListener('click', function() {
    //código de ações aqui...
});
Aconselho a você iterar nos pontos ou objetos que você quer ter ações. Cria uma função para isto de cara, pois depois você verá que será necessário em escala maior.
Comment: No caso eu posso fazer o seguinte:

- Verificar o getMode do drawing, Caso o botão clicado do drawing for 'polygon' ele faz algo.
Funciona assim?
Comment: Pode sim, mas precisa achar alguma referência do tipo


Is hook_init the right hook I should use in my case?

Question: If I want to override a certain page with drupal_set_title() is hook_init the right hook to use?
Same thing with adding a js script on a certain page with drupal_add_js() is hook_init the right hook as well?
Comment: I don't understand what the title is meant to say.
Comment: If the page is controlled with Page manager you can set whatever title you want in the UI.
Answer: It really depends on what you want to achieve... If you want to alter several pages the page title module might be better suited. Using a combination of this module and your own could lead to your code in hook_init() being overwritten. But it does not have to happen.
The more modules you have, the later you want to interfere with everything as more modules might try altering your outputs. So in those cases hook_init might not be the right place.
If you want to add JavaScript to your own custom module you might also add it in the module.info file. This usually works better with aggregations.
Update:
You could use any page hook, for instance hook_view() like this:
mymodule_view($node, $view_mode) {
  if($node->nid == 1) { // Act only if this node id (nid) is requested
     drupal_set_title("title");
     ...
  }
}

Comment: I am trying to alter the title of only one page. A module for that is kind of overkill.
Comment: As for the js the problem with module.info is the same concern I have for hook_init. It initializes on every page when I only need the js to be included on one page.
Comment: see my updated answer.
Comment: So another follow up with your comment. So using drupal_add_js does not work with aggregation? Same thing with drupal_add_css?
Comment: I've had situation where it didn't... However if it only affects one page, it should not be such an issue. To maximize performance you could minify it if you require this.
Comment: I didn't realized this should've been two separate questions. Sorry about that. So hook_init is alright for adding js I will just use strpos and $_SERVER to target specific page?
Comment: Add your js/css as a new question and someone with more experience might help you on those ones. I can't tell for sure. Good luck.
Answer: Using a hook or a module for altering the page title of a single page is IMHO overkill.
When I want to override the title or some other feature on a specific page, I usually use the override feature of the Drupal template system.
For instance, to override the node template for node/42, I create node--42.tpl.php by copying the default node.tpl.php (this is the D7 naming convention), place the copy in my theme's templates/ directory, and then edit it to hold any modifications (including $title) that I want to make to that particular page.
Remember to flush caches to see the effect when you're overriding a template!


Sampling from an arbitrary distribution on Polish spaces

Question: Let $U\sim \text{Unif}(0,1)$, and let $\mu \in \mathcal{P}(\mathbb{R})$ be an arbitrary probability measure on $\mathbb{R}$. Then from $\mu$, we can derive an associated CDF $F(x) = \mu((-\infty,x])$. We consider the following inverse of $F$:
$$F^{-1}(u) = \inf\{x \in \mathbb{R}: F(x) \geq u\}.$$
Then it's easy to show that $F^{-1}(U)\sim \mu$. In other words, $F^{-1}(U)$ is a sample of a random variable distributed like $\mu$.
Is there a similar construction when we now assume that $\mu \in \mathcal{P}(S)$ is a probability distribution on some arbitrary Polish space $S$? That is, does there exist a random element $X$ taking values in some other Polish space $T$ and a mapping $\psi: \mathcal{P}(S) \to (T \to S)$ from probability measures on $S$ to measurable functions from $T$ to $S$ such that $\psi(\mu)(X)\sim \mu$ for all $\mu \in \mathcal{P}(S)$?
I would be interested in proofs that such a mapping exists (or even more interesting, doesn't), but it would be absolutely amazing if the proof was constructive. I'd also be interested in references to the literature where this problem may have already been addressed. Thank you!
Comment: I believe this could be relevant: https://en.wikipedia.org/wiki/Pushforward_measure
Comment: @nomen True, we can rephrase the question in terms of pushforward measures. The question then becomes whether there exists a Polish space $T$ and a measure $\mu \in \mathcal{P}(T)$ such that the image of pushforward measures $f \mapsto f_*\mu$ over the space of measurable functions $f$ from $T$ to $S$ is $\mathcal{P}(S)$. This might be easier to parse for people more accustomed to analysis than probability, but I'm still not sure how to solve the problem.
Answer: By "measurable", here, I presume you mean "Borel measurable" and that your probability measures are all Borel probability measures. If so, the answer is yes. In fact, you can always take $\ X\sim \text{Unif}(0,1)\ $.
Here's a theorem I proved in Differential Games with No Information, SIAM J. Control Optim., 15(2), p.242 (Theorem 5.1):

If $\ S\ $ is a complete separable metric space and $\ \mu\ $ a Borel probability measure on $\ S\ $, then there exists a Borel measurable function $\ \phi:(0,1)\rightarrow S\ $ which has $\ \mu\ $ as its distribution with respect to Lebesgue measure on $\ (0,1)\ $. That is, $\ \text{m}(\{\alpha\in(0,1); \phi(\alpha)\in A\})=$$\,\mu(A)\ $ for any Borel subset $\ A\ $ of $\ S\ $.

Here, I have replaced the symbols "$Z$" and "$\Pi$" which originally appeared in my statement of the theorem with "$S$" and "$\mu$", respectively.
All the heavy lifting in the theorem's proof comes from Section 1.2, The Isomorphism Theorem, in K.R.Parthasarathy, Probability Measures on Metric Spaces.  The key results from this book are Theorem 2.8, from which it follows that either $\ S\ $ is countable or has the same cardinality as $\ \mathbb{R}\ $, and the isomorphism theorem itself (Theorem 2.14).  The latter implies that when $\ S\ $ has the same cardinality as $\ \mathbb{R}\ $, there exists a Borel measurable bijection $\ \zeta:\mathbb{R}\rightarrow S\ $ such that $\ \zeta^{-1}\ $ is Borel measurable. Thus, if $\ \mu\ $ is a Borel probability measure on $\ S\ $, then $\ \mu_\mathbb{R}(A)=$$\mu(\zeta(A))\ $ defines a Borel probability measure on $\ \mathbb{R}\ $, and you already know that if $\ F\ $ is the distribution function of $\ \mu_\mathbb{R}\ $ then  $\ F^{-1}(X)\sim\mu_\mathbb{R}\ $ (where $\ X\sim \text{Unif}(0,1)\ $). It then follows that $\ \zeta    F^{-1}(X)\sim\mu\ $.
The proof of the theorem for the case when $\ S\ $ is countable is straightforward.
Comment: Thank you! This was exactly what I was looking for!


How to get XKCD font working in matplotlib

Question: I've followed through this post.
I'm trying to reproduce the example from here
This is how mine looks

This is how it should look

The code is on that page and at the end of this post
System that I'm using
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:    14.04
Codename:   trusty

Python version that I'm using
3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]

Matplotlib version
import matplotlib
matplotlib.__version__
Out[37]: '1.5.1'

Humorsans font installed on system
This shows that I have installed the font
$ fc-list | grep "Humo"
/usr/share/fonts/Humor-Sans-1.0.ttf: Humor Sans:style=Regular
/home/vco/.fonts/Humor-Sans-1.0.ttf: Humor Sans:style=Regular

Matplotlib backend that I'm using
Here is the back end that I'm using
  plt.get_backend()
  Out[42]: 'TkAgg'

Output error
I've followed the instructions from a post here;
Error from python output:
/home/vco/anaconda/envs/math_general/lib/python3.5/site-packages/matplotlib/font_manager.py:1288:
UserWarning: findfont: Font family ['Humor Sans', 'Comic Sans MS'] not
found. Falling back to Bitstream Vera Sans

  (prop.get_family(), self.defaultFamily[fontext]))

/home/vco/anaconda/envs/math_general/lib/python3.5/site-packages/matplotlib/font_manager.py:1298:
  UserWarning: findfont: Could not match :family=Bitstream Vera
  Sans:style=normal:variant=normal:weight=400:stretch=normal:size=medium.
  Returning /usr/share/matplotlib/mpl-data/fonts/ttf/cmtt10.ttf UserWarning)

I also tried to move the downloaded Humorsans font to
/usr/share/matplotlib/mpl-data/fonts/ttf

But still got the following error
/home/vco/anaconda/envs/math_general/lib/python3.5/site-packages/matplotlib/font_manager.py:1288: UserWarning: findfont: Font family ['Humor Sans', 'Comic Sans MS'] not found. Falling back to Bitstream Vera Sans
  (prop.get_family(), self.defaultFamily[fontext]))
/home/vco/anaconda/envs/math_general/lib/python3.5/site-packages/matplotlib/font_manager.py:1298: UserWarning: findfont: Could not match :family=Bitstream Vera Sans:style=normal:variant=normal:weight=400:stretch=normal:size=medium. Returning /usr/share/matplotlib/mpl-data/fonts/ttf/cmtt10.ttf
  UserWarning)
/home/vco/anaconda/envs/math_general/lib/python3.5/site-packages/matplotlib/font_manager.py:1298: UserWarning: findfont: Could not match :family=Bitstream Vera Sans:style=normal:variant=normal:weight=400:stretch=normal:size=large. Returning /usr/share/matplotlib/mpl-data/fonts/ttf/cmtt10.ttf
  UserWarning)

code
from matplotlib import pyplot as plt
import numpy as np

plt.xkcd()

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.xticks([])
plt.yticks([])
ax.set_ylim([-30, 10])

data = np.ones(100)
data[70:] -= np.arange(30)

plt.annotate(
    'THE DAY I REALIZED\nI COULD COOK BACON\nWHENEVER I WANTED',
    xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))

plt.plot(data)

plt.xlabel('time')
plt.ylabel('my overall health')

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.bar([-0.125, 1.0-0.125], [0, 100], 0.25)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.set_xticks([0, 1])
ax.set_xlim([-0.5, 1.5])
ax.set_ylim([0, 110])
ax.set_xticklabels(['CONFIRMED BY\nEXPERIMENT', 'REFUTED BY\nEXPERIMENT'])
plt.yticks([])

plt.title("CLAIMS OF SUPERNATURAL POWERS")

plt.show()

Comment: @MartinThoma no I haven't solved this, maybe it'll be added to the millennium prize problems
Comment: Check the answer [here](http://stackoverflow.com/questions/19663986/getting-xkcd-plots-using-matplotlib/22812176#22812176).
Comment: @lincolnfrias what, the one which is the first thing I reference in the post? I've looked ;)
Comment: Oops, sorry. I pointed to that because in my case, removing the matplolib cache in .config solved the problem.
Comment: @lincolnfrias "in my case..." < what is this referring to ? You've tested the code that I've posted on a similar setup or is this a different thing you're referring to? Cheers
Comment: Not the same setup and code, but also on Ubuntu (16.04).
Comment: @lincolnfrias so you have different setup, code, and a different version of Ubuntu. Can you let me know what I'm expected to do with the information you've given please?
Comment: In home directory I have a .config folder containing a matplotlib folder. There I removed the file fontList.cache. In other setups people have instead a separate .matplotlib folder (in the first level of their home, not inside the .config). This is detailed in the answer (and the commentaries to it) to the post I linked above.
Comment: @lincolnfrias please read my post, specifically the part "I've followed through this post" that links what you're referencing. If you have a working solution then please post it with code and system setup, otherwise these comments are useless.
Comment: Did you finally solve it?
Comment: @baxx, could there be another cache where matplotlib is looking apart from the ~/.config/matplotlib, ~/.cache/matplotlib or ~/.matplotlib?
Comment: @thoroc I'm not sure at the moment, I've not looked at this for a long time
Answer: With matplotlib==3.4.3 I had to do:
import shutil
import matplotlib

shutil.rmtree(matplotlib.get_cachedir())

Comment: This worked for me (Python 3.10, Ubuntu 22.04, matplotlib 3.6.2). I had to restart the notebook kernel (and remember to remove the lines that deleted the cache so they don't run again) for it to take effect.
Answer: Try deleting Matplotlib cache and see if it works (i.e., rm -r ~/.cache/matplotlib).
In my case it solved the problem:
user@host:~$ ./xkcd.py
/home/user/.pyenv/versions/3.7.1/lib/python3.7/site-packages/matplotlib/font_manager.py:1241:
UserWarning: findfont: Font family ['xkcd', 'Humor Sans', 'Comic Sans MS'] not found.
Falling back to DejaVu Sans. (prop.get_family(), self.defaultFamily[fontext]))
user@host:~$ rm -r ~/.cache/matplotlib
user@host:~$ ./xkcd.py
user@host:~$

Comment: This worked for me (Python 3.10, Ubuntu 22.04, matplotlib 3.6.2). I had to restart the notebook kernel for it to take effect.
Answer: If you still see an error after installing HumorSans font, I advise running:
import matplotlib
matplotlib.font_manager._rebuild()

It will rebuild the font cache.
Comment: This gives an error in matplotlib 3.6.2
Comment: What's the error message?
Comment: I get: "AttributeError: module 'matplotlib.font_manager' has no attribute '_rebuild'"
Comment: Possible solution [here](https://stackoverflow.com/a/70647041/3275464)


desenhar um quadrado com laços de repetição em portugol

Question: Olá! estou aprendendo portugol para fins academicos e estou com um probleminha... preciso desenhar um quadrados com asteriscos porém não estou conseguindo desenhar a parte inferior e a direita, está saindo assim
esté é o meu código
programa
{

    funcao inicio()
    {
        inteiro contador,asteriscos, coluna = 0
        leia(asteriscos)
            se(asteriscos < 2){
                escreva("*")
            }senao{
                para(contador = 0; contador < asteriscos; contador++){
                    escreva("*")
                    escreva(" ")
            }enquanto(coluna < contador){
                escreva("\n*")
                coluna++
            }
}
}
}

deveria estar saindo assim(caso o número fosse 4)
Comment: Já tentou fazer um [teste de mesa](https://pt.stackoverflow.com/q/220474/100416)? Vai ficar mais fácil de entender o que está acontecendo
Comment: pior que sim, estou usando a ferramenta da IDE para fazer, mas mesmo assim estou me matando nesse programinha.
Answer: programa
{
    funcao desenhaQuadrado(inteiro valor, cadeia simbolo){
        inteiro linha, coluna

        para(linha = 1; linha <= valor; linha++){
            se(linha == 1 ou linha == valor){
                para(coluna = 1; coluna <= valor; coluna++){
                    escreva(simbolo, " ")
                }

            }
            senao{
                para(coluna = 1; coluna <= valor; coluna++){
                    se(coluna == 1 ou coluna == valor){
                        escreva(simbolo, " ")
                    }
                    senao{
                        escreva("  ")
                    }
                }
            }
            escreva("\n")
        }

    }

    funcao inicio()
    {
        escreva("Desenha quadrado na  tela\n-----------------------\n")

        inteiro valor
        cadeia simbolo

        escreva("Qual tamanho seu quadrado terá? ")
        leia(valor)

        escreva("\nQual simbolo usar para desenhar seu quadrado? ")
        leia(simbolo)

        escreva("\nUm quadrado de " + valor + " linha(s) e " + valor + " coluna(s)\n" )

        desenhaQuadrado(valor, simbolo)
    }
}

obeservações: O uso da função não é obrigatório. Usei ela aqui pois reaproveitei um exercício que eu ja tinha feito e que usava função. Essa variáveis são passadas na função desenhaQuadrado(valor, simbolo)
Vamos à explicação: o usuário determina o tamanho do quadrado através de uma entrada que é salva na variável valor e também determina o símbolo com o qual o quadrado será desenhado, este valor é salvo na variável simbolo do tipo cadeia.
Essa variáveis são passadas na função desenhaQuadrado(valor, simbolo). Dentro da função eu declarei ainda duas variáveis : linha e coluna que vão servir para desenhar o quadrado através de um loop. Para construir o quadrado é necessário ter um loop que controla o número de linhas e dentro desse loop existirá uma outra estrutura de repetição responsável pelas colunas.
Exemplo:
Digamos que usuário digite 3 e o símbolo é *. Será um quadrado de 3 linhas e 3 colunas. Para este exemplo vamos desconsiderar o uso das estruturas de decisão dentro do loop. A função desenhaQuadrado fica assim:
funcao desenhaQuadrado(inteiro valor, cadeia simbolo){
        inteiro linha, coluna

        para(linha = 1; linha <= valor; linha++){
            para(coluna = 1; coluna <= valor; coluna++){
                escreva(simbolo, " ")
            }

            escreva("\n")
        }

    }

primeira execução
valor = 3
simbolo = *
começa primeiro loop
linha = 1
começa segundo loop
coluna = 1
output : *
segundo loop
coluna = 2
output = * *
segundo loop
coluna = 3
output = * * *
segundo loop
coluna = 4 (coluna é maior que valor então o loop para)
fim do segundo loop
quebra linha
fim da primeira execução
segunda execução
valor = 3
simbolo = *
começa primeiro loop
linha = 2
começa segundo loop
coluna = 1
output : * * *
         *

segundo loop
coluna = 2
output = * * *
         * *

segundo loop
coluna = 3
output = * * *
         * * *

segundo loop
coluna = 4 (coluna é maior que valor então o loop para)
fim do segundo loop
quebra linha
fim da segunda execução
terceira execução
valor = 3
simbolo = *
começa primeiro loop
linha = 3
começa segundo loop
coluna = 1
output : * * *
         * * *
         *

segundo loop
coluna = 2
output = * * *
         * * *
         * *

segundo loop
coluna = 3
output = * * *
         * * *
         * * *

segundo loop
coluna = 4 (coluna é maior que valor então o loop para)
fim do segundo loop
quebra linha
fim da terceira execução
Quarta execução
valor = 3
simbolo = *
primeiro loop
linha = 4 (loop para pois linha é maior que valor)
Fim da quarta execução
output = * * *
         * * *
         * * *

o uso das estruturas de decisão
essa estruturas são usadas para decidir o seguinte:
na primeira e última linha : todas as colunas devem ser preenchidas com o símbolo *.
nas outras linhas: somente a primeira e a última coluna são prenchidas como símbolo *.
Dessa forma o output ficaria :
output = * * *
         *   *
         * * *

espero ter ajudado.
Answer: Consegui resolver o código usando laços de repetição e se.
Usei as variáveis quadrado, contador, contador2, contador3, espaco, contador4 todas do tipo inteiro.
Escreval(" Qual o tamanho do seu quadrado?")
leia(quadrado)
espaco <- (quadrado*2)-4
medida <- quadrado-2
para contador de 1 ate quadrado faca
escreva("* ")
 se contador = quadrado entao
 escreval(" ")
  para contador2 de 1 ate medida faca
    se contador = quadrado entao
       escreva("* ")
       se quadrado > 2 entao
          para contador4 de 1 ate espaco faca
             escreva(" ")
          fimpara
       fimse
       escreval("* ")
    fimse
     se contador2 = medida entao
        para contador3 de 1 ate quadrado faca
        escreva("* ")
        fimpara
     fimse
 fimse

fimpara
fimalgoritmo


Proving the differentiability of the following function of two variables

Question: I have the following problem of two variables differentiability:
$f(x,y)=xy\frac{x^2-y^2}{x^2+y^2}$
The value of function at $(0,0)$ is $0$.I have proved that the function is continuous at $(0,0)$. Also, both of the partial derivatives exists and equal to zero. But, I am not able to prove the differentiability of the above Function. I know that the continuous partial derivatives means that the function is differentiable but isn't the existence of partial derivatives proves continuity of partial derivatives. Because, I have obtained the partial derivatives using the limit definition. I think the equality of both partial derivatives means the continuity of them. I am really confused in this problem. Please help and give me set of advice while checking the differentiability of two variables function. Thanks in advance.
Answer: The easiest way to show differentiability is to use the definition.
Denote $v:=(x,y)$ and note that $|x^2 - y^2|\le \min\{x^2, y^2\} \le ||v||^2$ and $||v||=(x^2 + y^2)^\frac{1}{2} \ge \max\{|x|, |y|\}$
Then
$$\left| \frac{f(v)-f(0)}{||v-0||} \right| = \left|\frac{xy(x^2-y^2)}{||v||^{3}}\right| \le \left|\frac{xy||v||^{2}}{||v||^{3}}\right|=\frac{|xy|}{||v||}\le \frac{|xy|}{\max\{|x|,|y|\}} $$
which tends to $0$ if $v$ does .
Answer: By definition $f(x,y)$ is differentiable in $(a,b)$ if there are $\varepsilon_1$ and $\varepsilon_2$ such that
$$f(x,y)-f(a,b)=f_x(a,b)(x-a)+f_y(a,b)(y-b)+\varepsilon_1(x,y)(x-a)+\varepsilon_2(x,y)(y-b)$$
where $\displaystyle\lim_{(x,y)\to(a,b)}\varepsilon_1(x,y)=0$ and $\displaystyle\lim_{(x,y)\to(a,b)}\varepsilon_2(x,y)=0$. For $(a,b)=(0,0)$ the let $\varepsilon_1(x,y)=y\dfrac{x^2}{x^2+y^2}$ and $\varepsilon_2(x,y)=x\dfrac{-y^2}{x^2+y^2}$.
Comment: Thanks for your answer. my teacher told us to check the continuity of partial derivatives to check the differentiability.  What is $\varepsilon(x,y)$ here?. Is it partial derivatives?
Comment: Have you another formula for differentiability?
Comment: Is this way of checking differentiability is universal? Can we apply it in most of the situation?
Comment: Yes. It's universal. Another equivalent definition is
$$f(x_0+h,y_0+k)-f(x_0,y_0) = \dfrac{\partial f}{\partial x}(x_0,y_0)h+\dfrac{\partial f}{\partial y}(x_0,y_0)+\epsilon(h,k) \sqrt{h^2+k^2}$$
_I think the equality of both partial derivatives means the continuity of them_, do you mean $f_x=f_y$ implies continuity of them?
Comment: there is a factor $k$ missing  at $f_y$ in your formula in the comment.
Comment: Yes, it dropped. thanks


Task.Run travando dentro de um "tick" (Forms.Timer)

Question: Em minha aplicação, criei um "Timer" (System.Windows.Forms) que é executado a cada 1 segundo. No evento "tick", coloquei um await Task.Run.
Por algum motivo o tick para de executar depois de um tempo (pois ele não imprime a data e hora no console).
Class x {
    public Timer timer {get; set;}

    public void f()
    {
        timer = new Timer();
        timer.Tick += new EventHandler(this.tick);
        timer.Enabled = false;
        timer.Interval = 1000;
        timer.Start();
    }

    private async void tick(object sender, EventArgs e)
    {
        this.status = ProcessoStatus.TRABALHANDO;
        this.timer.Stop();

        try
        {
            await Task.Run(() => this.processo());
        }
        catch
        {}

        this.timer.Start();
        this.status = ProcessoStatus.OCIOSO;
    }

    public void processo()
    {
        Console.WriteLine(DateTime.Now);
    }
}

Comment: Só por curiosidade, se tu usar um `System.Threading.Timer` não dá o mesmo efeito? Nesse caso ele já faria em outra `thread` até.
Comment: Ele chega a executar algumas vezes ou trava na primeira?
Comment: Define "para de executar". Executa uma vez até ao fim e depois nao executa mais? Encrava (deadlock) na primeira execução? Em que linha? Se remover o `await Task.Run` o problema desaparece? O que faz o método `processo()`? Esta pergunta necessita de mais detalhes.
Comment: A cada 1 segundo, o tick "escreve" a data e hora em um listview (no exemplo eu coloquei no console para exemplificar). Se eu deixar o programa aberto por um tempo (indeterminado) a hora não fica mudando no listview.

Quanto a usar o Threading.Timer, eu não sei. Posso pesquisar. Eu preciso que o timer apenas execute quando o método "processo" termine. Por isso eu coloquei um "start"/"stop" ali. Para ele não sobrepor as execuções.
Answer: Entendo o que está tentando fazer, porém o System.Windows.Forms.Timer simplesmente não foi criado para isso. Essa citação, direto do MSDN:

The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.

Ou, em português:

O componente do Windows Forms Timer é single-threaded e está limitado a uma precisão de 55 milissegundos. Se precisar de um timer de vários threads com maior precisão, use o Timer classe na namespace System.Timers.

Nesse caso, sugiro que utilize o System.Timers.Timer, sendo possível usá-lo tanto em WinForms quanto qualquer outro instante.


How to make a reset form button without type 'markup'?

Question: My situation:
I built a form with FAPI. I display the results in a table like this:
function grap_contact_repository_form_submit($form, &$form_state) {
  ...
  $form_state['results_table'] = array('#markup' => grap_contact_repository($matches));
  $form_state['rebuild'] = TRUE;
}

The grap_contact_repository function returns a theme_table.
My problem:
Because of the results_table that already uses a #markup type, I can't build a reset button for my form using '#type' => 'markup' too. (Because all the results table will be clickable too).
I'm looking for an alternative to make this button work. I tried this:
$form['clear'] = array(
  '#type'       => 'button',
  '#value'      => 'Réinitialiser',
  '#attributes' => array('onclick' => 'this.form.reset();'),
);

or this: (http://www.blue-bag.com/blog/drupal-form-api-reset-button)
  $form['reset'] = array(
    '#type' => 'button',
    '#button_type' => 'reset',
    '#value' => 'Réinitialiser',
    '#validate' => array(),
    '#attributes' => array(
      'onclick' => 'this.form.reset(); return false;',
    ),
  );

But it doesn't work. The onclick works if I put another JavaScript like alert. I have nothing in my JS errors console.
Does someone have an idea to make it work?
Thanks a lot :-)
Answer:
Type should be reset, not button.
http://www.w3schools.com/tags/att_button_type.asp

You right, there is no such type. I was able to get this working with 2 submit buttons and return false (similar to your original implementation).
function drupalform_form($form, &$form_state) {

  $form['name']=array(
    '#type'=>'textfield',
    '#title'=>t('Enter your name'),
    '#description'=>t('Your first name goes here')
    );

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

  $form['reset_button'] = array(
    '#type' => 'submit',
    '#value' => 'Reset',
    '#validate' => array(),
    '#attributes' => array(
        'onclick' => 'this.form.reset(); return false;',
        ),
      );

  return $form;
}

If it still doesn't work there is this alternative solution: How to reset specific form elements
Comment: No. Do you see any "reset" in #type attribute? https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#type
Answer: I found out that I had to do this in jQuery as I thought. But if I want all the form to be reset, means all the fields values to "", the .reset() method isn't enough. I had to set all the values to "" and empty my results table manually like this:
$form['reset'] = array(
'#type' => 'button',
'#button_type' => 'reset',
'#value' => 'Réinitialiser',
'#validate' => array(),
'#attributes' => array(
  'onclick' => 'jQuery("#edit-categories, #edit-contextes, #edit-organismes, #edit-fonctions").val("");
                jQuery(".history-results tr").remove();',
  ),
);


Convert from Manual, to Group Policy Based Software Deployment

Question: We are in the process of upgrading our domain environment from Windows 200, to Windows 2008 R2 (sigh of relief). When the upgrade is completed, we would like to move to using GPO software deployment.
The question I has is regarding how to manage moving hundreds of machines that have all had software manually installed, into GPO deployment. Will the software try and re-install? Will the client extension detect that they software is installed, and not attempt to re-install?
Comment: This is pretty loaded. Best advice: setup a test machine and actually try it.  You'll spend far less time doing simple tests compared to searching for the actual behavior on this one.  Depending on the software you are trying to deploy you may want to look into other options as well.  For instance if you are trying to deploy Office maybe AppV/SoftGrid would be a better alternative.
Answer: You can decide what action takes place inside the GPO settings. You can even set the GPO to remove the software if the policy is no longer active. My advice would be to test heavily using gpresult and then slowly roll your GPOs out. Remember you're going to see quite a bit of network traffic once the settings take place initially. I'd expect 50-70% success, expect to do a lot of manual troubleshooting on machines to see why the policy did not take effect.
Case in point: It's not as smooth sailing as MS would like you to think.


Are there examples of explicitly-notated, precise, nontrivial polytempo before Ives and Nancarrow?

Question: Polytempo refers to the simultaneous use of two or more distinct tempi in a piece of
music. Polyrhythm can be viewed as a special case of polytempo; any polyrhythm can be written as a temporary tempo change.
For this post, an instance of polytempo is "trivial" if one or both of the following is true
for the entirety of the polytemporal section:

Measure onsets always coincide in all tempi (as would happen with 3/4 at 90 bpm against 2/4 at 60 bpm).
There are only two tempi and the ratio between them (or its reciprocal) reduces to 2:1,
3:2, or 4:3.

(Note that these conditions are unrelated to meter.)
An instance of polytempo is "precise" if the relationship between the different tempi is
specified exactly.
As far as I am aware, Charles Ives's Symphony no. 4 is the earliest work featuring
polytempo that is both nontrivial and precise. (The polytempo in Ives's Central Park in
the Dark is not precisely indicated.) Conlon Nancarrow would fully explore polytempo a
few decades later. Are there any examples of explicitly-notated, precise, nontrivial polytempo before Ives? Or by composers other
than Ives before Nancarrow?
Comment: 6/8 and 2/4 both have two beats per measure, so if 6/8 and 2/4 have different b.p.m. then the measures have different durations.  Perhaps 3/4 and 2/4 would be a better example.
Comment: Donald Byrd's page on the [extremes of conventional music notation](https://homes.luddy.indiana.edu/donbyrd/CMNExtremes.htm) simply cites Gardner Read's *Modern Rhythmic Notation* (1978) when it discusses polymeter.  From the description, Read's book does appear to contain examples, so it might be worth perusing it if you have access to it;  but there may not be much specifically talking about polytempo.
Comment: @phoog You're right. Thanks for pointing that out.
Comment: @MichaelSeifert I have the book. It discusses polytempo only in passing; there's no dedicated section for the topic. But it's a great resource for polymeter.
Answer: The first piece that comes to mind is Johannes Ockeghem's missa prolationum.  This piece is entirely written on mensural canons: different parts sing the same notes at different speeds.  As the example in the Wikipedia article shows, the first Kyrie is a double mensural canon.  There are two written parts, each of which is sung by two voices, the ratio of their tempi being 2:3.  The slower voice of one part is effectively as fast as the faster voice of the other part, more or less as though one is in 3/2 and the other in 6/4 with the measures having the same duration, so you could say that the ratios are 4:6:6:9.
Another piece that comes to mind, but which may not satisfy the requirements of the question, is the Act 1 finale of Mozart's Don Giovanni, which begins as a minuet in 3/4.  While that continues, one group of instruments begins playing another dance in 2/4, and then a third group switches to a fast 3/8.  The quarter note of the 2/4 and the dotted quarter of the 3/8 are equal to the quarter note of the 3/4, so the measures have different lengths.  I almost did not include this example because it's three different meters at one tempo, so arguably not polytempo, but I decided to mention it because you say that polyrhythm is a subset of polytempo, and this polymeter does result in polyrhythm.
Comment: The Missa meets the criteria. I'm more interested in examples after modern metric notation came into being, but it seems there aren't any.
Answer: Ives is the first obvious one - although relatively unknown at the time, so others came up with the same idea independently, rather than being influenced by him.
However - you could include just about all African drumming - abeit not notated.
Comment: I downvoted because this doesn't provide any new information.
Comment: It talks of travelers here, could that include notated music as well https://www.britannica.com/art/African-music ?


Proving the Identity Theorem for single variable real function

Question: I'm trying to prove a version of the Identity Theorem for single variable real functions:

Let $J\subset I \subset \mathbb{R}$ be non-empty, open intervals. Show that, if functions $f, g: I \to \mathbb{R}$ are real analytic on the interval $I$ such that $$f(x)=g(x) \ \forall x \in J,$$ then $$f(x)=g(x) \ \forall x \in I.$$

I have read this question, but unfortunately I'm only a beginner in real analysis and I don't know anything about topology etc, so the answer for that question goes over my head.
My idea for proving this was to expand the set for which the functions are equal step by step. Let $J=\left]a,b\right[$ and $I=\left]c,d\right[$. First, consider the function $f-g$ at the point $a$. To the right of $a$, the function $f-g$ must be zero, and using the power series expansion for $f-g$, one can conclude that $f-g$ must also be zero left of $a$, but only for some distance $\delta_1>0$ as given by the analyticity of $f$ and $g$. Now just repeat at each new endpoint until the set $I$ is reached.
However, what guarantees that the sequence $\{\delta_i\}$ doesn't approach zero too fast? Too fast in the sense that the endpoint of $I$ is never reached using this method. Is there a way to restrict the size of $\delta_i$ or is this approach simply not viable?
Comment: Look at the set of points $x$ such that the functions coincide on $(x,b)$. Find a contradiction if the *infimum* of this set is not $c$.
Comment: If $f$ is analytic on $[A,B]$ then for every $x_0 \in [A,B]$ it is given by a power series on $x \in [A,B],|x-x_0| < r(x_0)$, check that $r(x_0)$ is continuous in $x_0$ so that $\inf_{x_0\in [A,B]} r(x_0)$ needs to be $> 0$. Thus equality of $f,g$ on one of those disks implies equality everywhere else.
Answer: The hypotheses of your statement are stronger than necessary and I think that potentially obscures why the theorem holds, so let me outline (the missing details are easy to fill in) the following:
If $\sum_{n=0}^{\infty}a_nx^n$ and $\sum_{n=0}^{\infty}b_nx^n$ are two real power series with positive radius of convergence and they coincide on a zero sequence $(x_n)_n\in\left(\mathbb{R}\setminus\{0\}\right)^{\mathbb{N}}$, then they are equal.
To prove this, denote $f_0(x)=\sum_{n=0}^{\infty}a_nx^n$ and $g_0(x)=\sum_{n=0}^{\infty}b_nx^n$. Since power series are continuous in their radius of convergence, we obtain
$$a_0=f_0(0)=\lim_{n\rightarrow\infty}f_0(x_n)=\lim_{n\rightarrow\infty}g_0(x_n)=g_0(0)=b_0.$$
Now, we define
$$f_1(x)=\begin{cases}\frac{f_0(x)-a_0}{x},&x\neq0\\a_1,&x=0\end{cases},\qquad g_1(x)=\begin{cases}\frac{g_0(x)-b_0}{x},&x\neq0\\b_1,&x=0\end{cases}.$$
Note that $f_1$ and $g_1$ are still power series with the same radius of convergence as $f_0$ and $g_0$ respectively. Note furthermore that they still coincide on the same sequence $(x_n)_n$ (and also that this is the step where it is crucial that the sequence $(x_n)_n$ takes values in $\mathbb{R}\setminus\{0\}$). The same calculation as above now yields $a_1=b_1$. Continuing the process inductively yields $a_n=b_n$ for all $n\in\mathbb{N}$, which is the desired statement.
The statement you are trying to prove is just a (if necessary local) application of this. As a bonus, the above theorem also holds for complex power series and the proof is virtually the same.


Writing video to file works correctly for about 5 seconds on iPad 3, then fails

Question: I am creating this app that is a camera. Because it is being created for iOS 9, I have to test it on an old device. In that case an iPad 3. The app works perfectly on a new iPad Pro 9.7 but fails to write video after a while on iPad 3.
What happens is, the app starts writing frames fine but suddenly fails.
I am using this method to store each frame:
- (void)writeToFileFrame:(CIImage *) finalImage
          withSampleTime:(CMSampleTimingInfo)sampleTime
                 andSize:(CGSize)size
{

  if (!_assetWriter) {
    if (![self initializeAssetWriter]) {
      return;
    }
  }

  // convert CIImage to CMSampleBufferRef and save
  CGRect extent = [finalImage extent];
  CGFloat width = CGRectGetWidth(extent);
  CGFloat height  = CGRectGetHeight(extent);

  if ((width == 0) && (height == 0)) return;

  NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                           [NSDictionary dictionary], (id)kCVPixelBufferIOSurfacePropertiesKey,
                           @(YES), kCVPixelBufferCGImageCompatibilityKey,
                           @(YES), kCVPixelBufferCGBitmapContextCompatibilityKey,
                           kCVImageBufferYCbCrMatrix_ITU_R_601_4, kCVImageBufferYCbCrMatrixKey,
                           kCVImageBufferColorPrimaries_ITU_R_709_2, kCVImageBufferColorPrimariesKey, nil];

  // Initialize the video input if this is not done yet
  if (!_readyToWriteVideo) {
    _readyToWriteVideo = [self setupAssetWriterVideoInputWithSize:size];
  }

  CVPixelBufferRef pixelBuffer = NULL;

  CVPixelBufferCreate(kCFAllocatorSystemDefault, width, height, kCVPixelFormatType_32BGRA, (__bridge CFDictionaryRef) options, &pixelBuffer);

  CVPixelBufferLockBaseAddress( pixelBuffer, 0 );
  [_ciContext render:finalImage toCVPixelBuffer:pixelBuffer];
  CVPixelBufferUnlockBaseAddress( pixelBuffer, 0 );

  CMVideoFormatDescriptionRef videoInfo = NULL;
  CMVideoFormatDescriptionCreateForImageBuffer(kCFAllocatorDefault, pixelBuffer, &videoInfo);

  CMSampleBufferRef oBuf;
  OSStatus status = CMSampleBufferCreateForImageBuffer(kCFAllocatorDefault, pixelBuffer, true, NULL, NULL, videoInfo, &sampleTime, &oBuf);
  CVPixelBufferRelease(pixelBuffer);
  CFRelease(videoInfo);

  if (status != noErr) {
    NSLog(@"error creating CMSampleBufferCreateForImageBuffer");
    CFRelease(oBuf);
    return;
  }

  // Write video data to file only when all the inputs are ready
  if ([self inputsReadyToWriteToFile]) {
    if (_assetWriter.error) {
      NSLog(@"%@",[_assetWriter.error localizedDescription]);
      return;
    }
    [self writeSampleBuffer:oBuf ofType:AVMediaTypeVideo];
  }

  CFRelease(oBuf);

}

- (void)writeSampleBuffer:(CMSampleBufferRef)sampleBuffer ofType:(NSString *)mediaType
{
  if ( _assetWriter.status == AVAssetWriterStatusUnknown ) {
    NSLog(@"unknown state");
    // If the asset writer status is unknown, implies writing hasn't started yet, hence start writing with start time as the buffer's presentation timestamp
    if ([_assetWriter startWriting]) {
      [_assetWriter startSessionAtSourceTime:CMSampleBufferGetPresentationTimeStamp(sampleBuffer)];
    } else {
          // error
     }
  }

  if ( _assetWriter.status == AVAssetWriterStatusWriting ) {
    // If the asset writer status is writing, append sample buffer to its corresponding asset writer input
    if (mediaType == AVMediaTypeVideo) {
      if (_assetWriterVideoInput.readyForMoreMediaData) {
        if (![_assetWriterVideoInput appendSampleBuffer:sampleBuffer]) {
          NSLog(@"error: %@", [_assetWriter.error localizedFailureReason]); //Ⓐ
        }
      }
    }
    else if (mediaType == AVMediaTypeAudio) {
      if (_assetWriterAudioInput.readyForMoreMediaData) {
        if (![_assetWriterAudioInput appendSampleBuffer:sampleBuffer]) {
                      // error
        }
      }
    }
  }

  if ( _assetWriter.status == AVAssetWriterStatusFailed ) {
    NSLog(@"error");
  }

}

This works fine on iPad Pro 9.7 but on iPad 3 it hits line Ⓐ, failing miserably, after writing frames correctly for about 5 seconds.
Fails with error -536870211, that is obviously an unknown error.
I have checked the apps for leaks and there is none.
Any ideas?
NOTE: I have discovered now that the problems only shows if I am writing frames from the rear camera (HD). If I switch to the front camera VGA (640x480) it works fine. So it has to do with memory allocations but I have checked that with instruments and the app is using about 12 MB of memory and this value is more or less constant. No leaks.
Comment: I have no idea. :) But I do have an iPad 3. In comparison to iPad Pro, it is: (1) grossly underpowered [frame-dropping issue?] (2) highly limited as to RAM memory (3) single-core [threading issue?] (4) 32-bit [bitness issue?]
Comment: ok I agree but if the app is compatible with iOS 9 it will have to run on iPad 3.
Answer: That error is kIOReturnNoMemory
Memory can't be allocated (0xe00002bd).Value: 0xe00002bd (-536870211)

so it sounds like you're using too much memory. You need to make sure that you're retaining as few sample buffers and their derivatives for as short a period of time as possible.
The Instruments app memory and GPU tools and Xcode's memory gauges should be helpful too.
Comment: I googled 536870211 which vindicated my belief that dealing with memory constraints is one of the hardest parts of video processing. Also, the iPad3  was notoriously short of memory.
Comment: Brilliant! First of all I have to thank Apple with all my hate. Like I always say, XCode is a piece of flaming crap that should be terminated and Apple has to show some love for developers. What kind of sick development team decide to throw "unknown error" if the error is known? Second I say that I am allocating just ONE sample buffer. Third, I would like to ask you how did you discover that? It may be useful in the future. THANKS.
Comment: sorry bothering you again, but looking at my code do you see something I can do to minimize memory allocation? thanks
Comment: can you create a runnable project?


CG shader, control Z-Write per fragment?

Question: Is it somehow possible to control for each fragment whether or not depth shall be written to the depth buffer?
I want my object to be depth tested properly (therefore I need to output accurate depth per fragment for testing), but I want only some of the fragments to write to the buffer.
Any way to do that?
Answer: Render a pass that doesn't write to the color bufffer.  Use clip/discard as you please.
Render another pass that writes to the color and not depth buffer.


print(f"...:")-statement too long - break it into multiple lines without messing up the format

Question: I have a console program with formatted output. to always get the same length of the printout, I have a rather complex formatted print output.
print(f"\n{WHITE_BG}{64*'-'}")
print(f"\nDirektvergleich{9*' '}{RED}{players[0].name}{4*' '}{GREEN}vs.{4*' '}{RED}{players[1].name}{CLEAR}\n")
print(f"""{15*'~'}{' '}{YELLOW}Gesamt{CLEAR}:{' '}{players[0].name}{' '}{GREEN}{int(player1_direct_wins)}{(int(4-len(player1_direct_wins)))*' '}-{(int(4-len(player1_direct_losses)))*' '}{int(player1_direct_losses)}{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-len(players[1].name))*'~'}\n""")
print(f"""{15*'~'}{' '}{YELLOW}Trend{CLEAR}:{'  '}{players[0].name}{' '}{GREEN}{int(player1_trend_wins)}{(int(4-len(player1_trend_wins)))*' '}-{(int(4-len(player1_trend_losses)))*' '}{int(player1_trend_losses)}{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-len(players[1].name))*'~'}""")
print(f"\n{WHITE_BG}{64*'-'}")

This leads to the following output in my windows cmd

For readibility purpose, I tried to make the print over multiple lines, therefore I found on stackoverflow the idea to start with triple quotes. But when I cut this print(f"...") statement in the middle, I mess up my formatting.
Example:
print(f"\n{WHITE_BG}{64*'-'}") #als String einspeisen?!
print(f"\nDirektvergleich{9*' '}{RED}{players[0].name}{4*' '}{GREEN}vs.{4*' '}{RED}{players[1].name}{CLEAR}\n")
print(f"""{15*'~'}{' '}{YELLOW}Gesamt{CLEAR}:{' '}{players[0].name}{' '}{GREEN}{int(player1_direct_wins)}{(int(4-len(player1_direct_wins)))*' '}-
    {(int(4-len(player1_direct_losses)))*' '}{int(player1_direct_losses)}{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-len(players[1].name))*'~'}\n""")
print(f"""{15*'~'}{' '}{YELLOW}Trend{CLEAR}:{'  '}{players[0].name}{' '}{GREEN}{int(player1_trend_wins)}{(int(4-len(player1_trend_wins)))*' '}-
    {(int(4-len(player1_trend_losses)))*' '}{int(player1_trend_losses)}{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-len(players[1].name))*'~'}""")
print(f"\n{WHITE_BG}{64*'-'}")

leads to...

can anyone point me in the right direction how to format my output in the displayed way, but without having this absurd long line length.
Thank you guys in advance!
Answer: Triple quoted strings preserve newline characters, so they are indeed not what you want here. Now when it finds two adjacent strings, the Python parser automagically concatenates them into a single string, i.e.:
s = "foo" "bar"

is equivalent to
s = "foobar"

And this works if you put your strings within parens:
s = ("foo" "bar")

in which case you can put each string on its own line as well:
s = (
    "foo"
    "bar"
    )

This also applies to "fstrings" so what you want is something like:
print((
    f"{15*'~'}{' '}{YELLOW}Gesamt{CLEAR}:{' '}{players[0].name}{' '}{GREEN} "
    f"{int(player1_direct_wins)}{(int(4-len(player1_direct_wins)))*' '}-"
    f"{(int(4-len(player1_direct_losses)))*' '}{int(player1_direct_losses)}"
    f"{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-"
    f"len(players[1].name))*'~'}\n"
    ))

That being said, I'd rather use intermediate variables than trying to cram such complex expressions in a fstring.
Comment: Nope, I mean doing all the computations like `int(4-len(player1_direct_wins))` outside the fstring (assigning the results to intermediate variables) so the fstring only contains references to variables and no complex expressions. This will make your code much more readable and maintainable (and possibly more testable too).
Comment: thank you, this worked! if you talk about intermediate variables, would you mean putting something like
`f"{15*'~'}{' '}{YELLOW}Gesamt{CLEAR}:{' '}{players[0].name}{' '}{GREEN} "`
inside a variable and then just concat them in the final printout?
Comment: okay, got it. one thing more to do for this little program :-) thank you again!
Comment: And thanks @toby-speight for fixing my spelling mistakes.


HP device manager can not save (Print color as gray) option

Question: '
whenever I change this value to Off and reopen the application, it turns back to On,
this only happens with this specific option
I tried reinstalling hplip, but it did not solve the issue
Answer: <code>lpoptions -o HPPJLColorAsGray=off
</code>
Comment: Welcome to Stack Overflow!  A few notes on your answer to hopefully help in the future.  **(1)** It could be improved with additional supporting information, but I wouldn't recommend it in this case (see #3). You can find more information in [How do I write a good answer?](/help/how-to-answer) - *"Brevity is acceptable, but fuller explanations are better."*  It might be helpful to review some highly upvoted answers as examples to follow
Comment: **(2)** Check out [How do I format my posts using Markdown or HTML?](/help/formatting) and the [Markdown help](/editing-help) for tips on making your future answers more readable.
Comment: **(3)** In this case, it doesn't matter much, because your answer just called attention to the face that the *question* that was originally asked isn't on-topic here, since it's not a *programming* question. As a result it was (correctly) closed and will probably be automatically deleted shortly. This is why the [help](/help/how-to-answer) recommends that you, *"Save yourself some frustration and avoid trying to answer questions which ... are not about programming"*.  We don't want you to waste your time! If you have programming expertise, look for good *programming* questions here to answer.
Comment: And if not, we have some other sites where your command-line expertise can be useful, including [Super User](//superuser.com), [Unix & Linux](//unix.stackexchange.com), and potentially [Ask Ubuntu](//askubuntu.com)
Comment: I know this is a lot to take in when you are brand new here, and there's no problem with that.  It's why I spend time trying to provide guidance in comments for new users. ;-)  Again, Welcome!


How can I transfer votes to nodes selected from an entity reference list?

Question: I create a form where users can submit their opinion and votes about nodes that they select from an entity referenced list.
How can I assign the votes to the entities that apoear on this list?
eg.
"Review" content type are completed by auth users.
In "review" form there are 2 fields "class" and "teacher" where the user can select from an list of nodes "class" and "teacher" content types. After the user select the "class" and "teacher" then must vote (voteapi & rate) and complete an opinion (textarea) about the nodes he selects.
Answer: Use the Inline Entity form, which allows you to set a view with the list of nodes and modify them directly (you would set the voting in the voted node e.g., the class or teacher, in your example).
The plan is for you to set up the Review content type with a Entity Reference field. This will allow you reference a View where you can set up your Class and Teacher Nodes.
You need the following Modules: Five Star and Voting Api (Which you already have) Views, Entity API, Inline Entity Form.
The way I understand your process is as follows:

You have a set of classes and a teachers
You intend to make available a set of these classes and teachers to a different content type (this is review), to generate votes for that class and/or teacher
The number of classes/teachers available for that review to emit a vote from is unspecified (may be all or a subset of them)

To go about this you need to have the following:

Voting fields in class and teacher content types
Create a Entity Reference View which displays the list of nodes you need (one for each, selecting their respective content types).
Add a Entity Reference field in the review content type with the Inline entity form - multiple values widget.
While setting the field:

Check Allow users to add existing nodes, so that they can select the class/teacher from your current list.
Select in Entity Selection: Views: Filter by an entity reference view
Select in View used to select the entities the view you would prefer for that field (teacher or class)

You should be able to add the classes/teachers you want to vote for. Also, you can control the entities shown by the view (so you could add context filters). Be mindful of setting the votes so you can vote while editing.
Comment: From what I see it generate the entire node/add form inside. Or it is an way to add just the voting stars widget in "inline entity form" and the user don't have an edit button of the node.
Comment: I edited the question for greater detail.


Qual o formato desta hora?

Question: Qual o formato desta data e hora em PHP 7.2?
2019-05-13T10:00:00.000Z

Por exemplo, a data hora 2019-01-01 10:00:00 tem o formato Y-m-d H:i:s.
Comment: Por favor, não polua a comunidade com perguntas repetidas. Se já perguntou, tenha paciência que cedo ou tarde alguém responderá. Se em dois dias ninguém responder, há a opção de [oferecer recompensa](https://pt.meta.stackoverflow.com/q/2621/5878) pela resposta. Se tem pressa para resolver o problema, talvez o site não seja o melhor lugar.
Answer: Bom a pergunta ficou meio confusa, caso queria formatar essa data utilize a pergunta já respondida: Formatar Data, Hora e Fuso no PHP.
Mas caso gostaria de saber o formato desta data, você poderia dar uma olhada na documentação do PHP 7 sobre DateTime.
DateTime implements DateTimeInterface {

       const string DateTimeInterface::ATOM = "Y-m-d\TH:i:sP" ;
       const string DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T" ;
       const string DateTimeInterface::ISO8601 = "Y-m-d\TH:i:sO" ;
       const string DateTimeInterface::RFC822 = "D, d M y H:i:s O" ;
       const string DateTimeInterface::RFC850 = "l, d-M-y H:i:s T" ;
       const string DateTimeInterface::RFC1036 = "D, d M y H:i:s O" ;
       const string DateTimeInterface::RFC1123 = "D, d M Y H:i:s O" ;
       const string DateTimeInterface::RFC2822 = "D, d M Y H:i:s O" ;
       const string DateTimeInterface::RFC3339 = "Y-m-d\TH:i:sP" ;
       const string DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP" ;
       const string DateTimeInterface::RSS = "D, d M Y H:i:s O" ;
       const string DateTimeInterface::W3C = "Y-m-d\TH:i:sP" ;

O trecho acima é referente a classe DateTime, para mais detalhes veja os seguintes tópicos.

Classe DateTime
Exemplos de Datas

Talvez o seu seja um desses: DATE_ATOM | DATE_ISO8601 | DATE_RFC3339_EXTENDED | DATE_W3C, mas eu não tenho certeza, de qualquer forma espero ter ajudado :).
Comment: Esse formato (`2019-05-13T10:00:00.000Z`) é definido pela [**norma ISO 8601**](https://en.wikipedia.org/wiki/ISO_8601). Só que a constante `DateTime::ISO8601` não considera a fração de segundo. A que mais se aproxima do formato em questão é `DATE_RFC3339_EXTENDED`, mas sei lá pq ela não funciona, [veja aqui](https://ideone.com/hUZZtv). Uma maneira de resolver é o que sugeri em https://pt.stackoverflow.com/a/356609/112052

Qual o formato desta hora?