Using the digits 1, 3, 4, 5, 6, and 7, with no repetition of digits, how many three digit odd numbers greater than 300 can you form?

Question: We have three digits.
The first digit cannot be 1, because that would mean that the number would be lower than 300. That means that for the first digit, there are 5 possible cases.
The second digit can be any number in the set, and because one number has already been used, there are 5 possible cases for the second digit.
The third digit must be odd, and because there are both 4 numbers remaining in the set and 4 odd numbers in the set, there are 4 possible cases for the third digit.
(5 possible cases) * (5 possible cases) * (4 possible cases) == 100 possible cases.
Apparently this approach is completely wrong. Can someone please explain to me why my approach is wrong, provide the correct approach, and then explain why the correct approach is the correct approach?
Comment: You need to consider the parity of the two leading digits.  If they are, say, $4,6$ then you have $4$ odd digits to choose from for the units place.  But if they are $3,1$ then you only have two odd digits for the units place.
Comment: Might be easier to start from the units place, though of course you still have to separate the case where the units digit is $1$ from the other possibilitlies.
Answer: You are forgetting that the choice of the first and second digit might limit the choice for the third digit.
Let's elaborate:
The first digits can be any of the five digits greater than $1$.
IF the first digit is $4$ or $6$, then we have $4$ possible odd digits left for the last digit. Then we have a total of four numbers for the second digits left.
This makes $2\cdot 4\cdot 4=32$ possible combinations.
Now, if the first digit is one of $3,5,7$ then we only have three odd digits left for the third, and again four digits for the middle one.
This makes $3\cdot 3\cdot 4 = 36$ possible combinations.
In total we have $32+36=68$ combinations.
Answer: An alternative is to calculate all three digits number greater than $300$ and then subtract the even numbers from these.
The number of all three digits number greater than $300$ is $5\times 5\times 4=100$. The number of three digits number greater than $300$ that are even is $4\times 4\times 2=32$. Therefore the number of three digits odd number greater than $300$ is $100-32=68$. Here I use the fact that the even numbers are both greater than $3$ so regardless of the rightmost digit we only have $4$ choice for leftmost digit.
Answer: Alternative approach:
The rightmost digit must either specifically be $(1)$, or it must specifically be in $\{3,5,7\}$.
$\underline{\text{Case 1: Rightmost digit is} ~(1)}$
Then the other two digits can be any $2$ from $\{3,4,5,6,7\},$ in any order.
The enumeration is $\binom{5}{2} \times 2! = 20.$
$\underline{\text{Case 2: Rightmost digit is in} ~\{3,5,7\}}$
Here, there is a shortcut.
If the leftmost digit was permitted to be $1$, then the enumeration would be $3$ times the enumeration in Case 1.
Therefore, the starter enumeration for Case 2 is $60$.
From this, it is necessary to deduct the number of ways of forming a number in Case 2, where the leftmost digit is $1$.
With the leftmost digit $= 1$, and $3$ choices for the rightmost digit, there are then $4$ choices for the middle digit.  Therefore, the number of ways that Case 2 can be satisfied with a $1$ in the leftmost digit is $3 \times 4 = 12$.
Therefore, the computation for Case 2 is $60 - 12 = 48.$

Final computation: $20 + 48 = 68$.
Answer: Leave out $1$ for the moment, and choosing from units to hundreds, we get
$U\;\, T\; H$
$3\cdot 5\cdot 4 = 60$
But any  one of the $3 U's\quad XOR\quad 5T's$ can be replaced by $1$
thus ans = $60+3+5 = 68$


How to get columnSpan working in QtQuick GridLayout?

Question: I am trying to create a simple layouting example using QtQuick Layouts.
My goal is to display a layout using GridLayout where I have 3 columns, the first one using 60% of the space, the second and third using 20% each, for a total of 100%.
I would expect the following to give me the expected results, but for some reason it doesn't:
Window
{
    width: 1920
    height: 1080
    visible: true

    GridLayout
    {
        width: parent.width
        height: parent.height
        columns: 5

        Rectangle
        {
            color: "red"

            Layout.fillHeight: true
            Layout.fillWidth: true
            Layout.columnSpan: 3
        }

        Rectangle
        {
            color: "green"

            Layout.fillHeight: true
            Layout.fillWidth: true
        }

        Rectangle
        {
            color: "blue"

            Layout.fillHeight: true
            Layout.fillWidth: true
        }
    }
}

Running the above example gives me the following result, each column using a third of the available space:

What I've tried, without luck:

Removing the explicit columns property for the GridLayout
Specifying an explicit row count for the GridLayout using the rows property
Specifying explicit column and row properties for the rectangles
Specifying explicit columnSpan and rowSpan for all rectangles
Fiddling with the number of columns specified for the GridLayout
Removing the Layout.fillWidth attached properties

What am I doing wrong?
Answer: I think you're looking for Layout.preferredWidth. When combined with fillWidth: true this acts as a "stretch factor", meaning it becomes relative to the preferred widths of other items in the layout.  I just used the percentage values you gave, but any numbers in the same proportions would work (eg. 6, 2, 2).
Window
{
    width: 1920
    height: 1080
    visible: true

    GridLayout
    {
        width: parent.width
        height: parent.height
        columns: 3

        Rectangle
        {
            color: "red"

            Layout.fillHeight: true
            Layout.fillWidth: true
            Layout.preferredWidth: 60
        }

        Rectangle
        {
            color: "green"

            Layout.fillHeight: true
            Layout.fillWidth: true
            Layout.preferredWidth: 20
        }

        Rectangle
        {
            color: "blue"

            Layout.fillHeight: true
            Layout.fillWidth: true
            Layout.preferredWidth: 20
        }
    }
}

(If you specifically wanted to use columnsSpan for some reason, please explain.)
Comment: @Znurre You're welcome! Well a column span would only come into play when you have multiple rows. Then a column on one row could span multiple columns of the other row(s). Though with the way GridLayout wraps things, this can be tricky to lock down (not at all like QGridLayout unlike the docs claim). There's the `Grid` QML positioner type, but it has no column/row span capabilities (ridiculously).  For more precise control you're pretty much stuck with anchors or a custom layout engine.
Comment: Thank you. I am still curious as to why `columnSpan` does not work the way I imagine it to work though.
Comment: There's an example using column/row spans [here](https://stackoverflow.com/questions/34027727/how-can-i-create-a-qml-gridlayout-with-items-of-proportionate-sizes) you may find useful.  Though it's overly complicated for the result IMHO, which is why I didn't refer to it earlier.
Comment: Also you don't actually need a grid layout for your particular example since just a RowLayout would do (and work the same way). But I assume you're expanding this to multiple rows... :)
Comment: Thank you very much! :) I am indeed used to the way `QGridLayout` works, and the documentation does not do much to help in this matter.


Confusion with finding the range on complex number functions

Question: The question is about finding the range and domain of $f(z)=e^z$, and I have read the solution and the reason why many times but I just don't understand it. My professor simply taught domain and range with real numbers and gave us complex number question which I don't exactly know how to do, so here's the answer:

The complex exponential function has natural domain $\mathbb{C}$; hence $f$ has natural domain $\mathbb{C}$. If $z=x+iy$ with $x, y∈\mathbb{R}$ then $e^z=e^x e^{iy} = e^x(\cos y+i\sin y)$. Since $e^x$ can take any positive value, and $y$ can take any value in $\mathbb{R}$ including all those in $(−π, π]$ then $f(z)$ can take any non zero modulus and all arguments. Hence $f(z)$ has the range $\mathbb{C}\setminus\{0\}$.

I think I have a clear understanding on most of it other than the reason why the range would be $\mathbb{C}\setminus\{0\}$. Could you also please tell me a way to find the range for all complex functions too? That would make my life so much easier!
Comment: For *all* ? That's quite a lot...The way or adguing above is nice, and every singl;e case must be dealt with separatedly.
Comment: Did you mean $f(z)=e^z$?  To see that this has a range of $\mathbb C-\{0\}$, just use polar coordinates (as described).  And you can't be serious about "a way to find the range for all complex functions"...there are an awful lot of functions.
Answer: $e^x > 0$, view it as the non-zero radius.
$e^{iy}$ is a point on the unit circle, it decides the direction.
Given any non-zero point, find the radius $r$ and the angle $\theta$, we can solve $e^x=r$ and let $y$ be $\theta$.
There is no solution for $e^xe^{iy}=0$, since $e^x$ and $e^{iy}$ are non-zero, we can divide them by their multiplicative inverses and get a contradiction of $1=0$.


Configuring mq websphere 7 with .net

Question: I am trying to connect to a remote queue using c#.
I tried many ways to connect to the remote queue but it always fails with common errors like: MQRC_CHANNEL_CONFIG_ERROR or MQRC_HOST_NOT_AVAILABLE.
What I am doing is this:
        string channel = "QM_TEST.SVRCONN";
        string hostname = "<serverIp>";
        string queueName = "QM_TEST";
        string port = 1414;

        props.Add(MQC.HOST_NAME_PROPERTY, hostname);
        props.Add(MQC.CHANNEL_PROPERTY, channel);
        props.Add(MQC.PORT_PROPERTY, port );
        props.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);

        MQQueueManager mqQueue = new MQQueueManager(queueName, props);

I have tried changing this but all failed.
I think that my problem is the server configurations..
can you point me to a full guide to how to configure a server and connect to it with .net?
My problem is connecting to a REMOTE server using .net and not to a local server.
Thank you!
Answer: The problem was that the CCSID between the client and the server were different.
http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/index.jsp?topic=%2Fcom.ibm.mq.csqzaf.doc%2Fcs12480_.htm
On the client side I had to put
Environment.SetEnvironmentVariable("MQCCSID", "437");

Thats why I got:
MQRC_CHANNEL_CONFIG_ERROR

Answer: I'm guessing the problem (or at least a problem) is here:
MQQueue mqQueue = new MQQueueManager(queueName, props);

This should be
queueManager = new MQQueueManager(queueManagerName, properties);

If you have installed the WebSphere MQ client to the default location, there are many sample programs under the following directory:
C:\Program Files (x86)\IBM\WebSphere MQ\tools\dotnet\samples\cs\base\

There are a number of sample programs there for various tasks.  If you have the latest V7.1 client installed then you will see the following programs:
SimpleAsyncPut
SimpleClientAutoReconnectGet
SimpleClientAutoReconnectPut
SimpleGet
SimpleMessageProperties
SimplePublish
SimplePut
SimpleReadAhead
SimpleSharingConversation
SimpleSubscribe
SimpleXAGet
SimpleXAPut

There are also WCF and XMS samples.
If you need the client code, please see my response to another SO question here for links.
Update:
Here's the normal diagnostic process.

If the WMQ components were installed by relocating libraries or classes from somewhere else, perform an install using the full vendor-supplied client media.  This includes troubleshooting utilities such as trace, dspmqver, etc.  It also resolves any library or class mismatch issues.
Use the pre-compiled client programs to test the connection.  The amqsputc, amqsgetc and amqsbcgc programs require the MQSERVER environment variable as described here.  The Q program from SupportPac MA01 is a separate download but has the advantage of NOT requiring any environment variables, CCDT files or other dependencies.
If the sample programs fail, check the QMgr's error logs at [WMQ install]/qmgrs/[QMgr name]/errors/AMQERR01.LOG for messages.  Also check for FDC files and errors in [WMQ install]/errors.
If no errors on the QMgr side, attempt the connection again while using a client-side trace as described here and here.

Most client problems are resolved through installation of the full WMQ client as supplied by IBM. (Conversely that implies most people are installing by grabbing DLL or JAR files.)  If the problem persists, error log inspection on the QMgr and client side usually reveals the underlying cause.  If these do not work then tracing usually diagnoses the remaining issues.
UPDATE 2:
Per the error messages posted at MQSeries.net, the channel has a security exit set.  A security exit is external code that the channel calls out to when starting a channel.  There is no way to know what the exit expects or does without having access to the code or docs of the exit.  If the exit is written in-house, you'll need to talk to the programmer to figure out what it requires. If the exit is a commercial product then you will need to get the documentation for it.
Alternatively, alter the channel so that SCYEXIT is blank to disable the exit.
The data posted at MQSeries.net was as follows:
MQ9575: DCE Security: failed to get the user's login name.

EXPLANATION:

System call 192.168.50.55 to get the login name of the user running WebSphere
MQ client application process 5 failed with error value -1. This occurred in
security exit function create_cred. The exit will now attempt to open channel
using the DCE default login context.
ACTION:
If you wish to run using the DCE default login context take no action. If you
wish to run using the user's login name as the DCE security exit principal
examine the documentation for the operating system on which you are running MQ
clients and reconfigure the operating system as necessary to allow the
192.168.50.55 call to succeed.

Note that it states the call is failing in the security exit.
Comment: sorry about the typing error I just copied parts of the code.
I don't believe its a code error because when I used the samples and the console of mq it still doesn't work.
It gives me: MQRC_CHANNEL_CONFIG_ERROR

how should I configure the server?
Comment: How did you install the .Net classes?  If they were installed with a WMQ Server, it is necessary to select the WMQ client components during the install. Also, the QMgr must have the channel specified and a running listener on the port specified. You can test this using the `amqsputc` program in `C:\Program Files (x86)\IBM\WebSphere MQ\tools\c\Samples\Bin`.  You can also test using the Q program from SupportPac MA01 http://ibm.co/SupptPacMA01  If these work then you have a code issue.  If not then its a config issue.
Comment: Hi, thanks for the help.
It still doesn't work with the same error - CONFIG_ERROR

**What config error can it be?**
I saw that MQRC_CHANNEL_CONFIG_ERROR
is [one of these](http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/index.jsp?topic=%2Fcom.ibm.mq.amqzao.doc%2Ffm20910_.htm) but how do I solve these problems? and how do I know which one is it..
Comment: When you say "it still doesn't work" I don't know what "it" is.  The .Net code?  Did you try using the pre-compiled, stand-alone Q program from SupportPac MA01 and is that what is now giving you the errors? Since Q takes all necessary parms from the command line, it eliminates issues such as client.ini file, environment vars or code problems. If that gives you the errors then usually it's a QMgr or client installation issue. I'm about to leave for an international flight. I'll check back when I can. Hopefully, Shashi will sign on soon and join the conversation.
Comment: Hi, yes I did try it with q.
I really think it is a configuration error on the server side because one my local computer I am able to connect and add messages to a queue.

I Get this errors in the queue manager server side:

AMQ9575: DCE Security: failed to get the user's login name.

Configuring mq websphere 7 with .net


Migrate taxonomy with depth

Question: I need to migrate a CSV file of 3000 Taxonomy terms with depth of 5 levels deep.
This is a small sample of the CSV comma-separated values file.
About Us
About Us, Our Programs
About Us, Our History, Timeline
Mission
Mission, Community

I want these values to be inserted into a Vocabulary, It should have the depth and it should ignore parent terms it has already created. It should look just like this in Drupal
About Us
-Our Programs
-Our History
--Timeline
Mission
-Community

I created a simple migrate yml file that can do this but I had to restructure
the CSV file a lot and it is too much manual work. Can regex or something search
for the comma delimiter and make the term after a comma a child of the term in
front of it? And can it skip or ignore parent terms it already created? Here is my migration and csv file.
id: vocab
label: Migrate terms from the source CSV to taxonomy terms
migration_group: migrated_terms
source:
   plugin: csv
   path: 'public://csv/vocab.csv'
   header_row_count: 1
   keys:
      - uuid
   column_names:
     0:
       uuid: UUID
     1:
       vid: VID
     2:
       name: NAME
     3:
       parent: PARENT
destination:
   plugin: entity:taxonomy_term
process:
   vid: vid
   name: name
   parent:
      plugin: migration
      migration: vocab
      source: parent

csv file
"uuid","vid","name","parent"
"100","myvocab","About Us"
"101","myvocab","Our Programs","100"
"102","myvocab","Our History","100"
"103","myvocab","Mission"
"104","myvocab","Community","103"

Answer: Have a look at the example in web/core/modules/taxonomy/migrations/d7_taxonomy_term.yml
It sets a term parent_id by looking it up in the same migration:
  parent_id:
    -
      plugin: skip_on_empty
      method: process
      source: parent
    -
      plugin: migration_lookup
      migration: d7_taxonomy_term
  parent:
    plugin: default_value
    default_value: 0
    source: '@parent_id'

For your case you only need to change the migration name:
    plugin: migration_lookup
    migration: vocab

You can use the Migrate Devel module to inspect the migrations while working on them.

Migrate taxonomy with depth


ListAgg and other column selection

Question: I am trying to get the output for below query
select
    listagg((REGEXP_SUBSTR(ABC, '[^:]+$')),';') AS Unit , (select 'XYZ' from dual)
from
    MNO
where
    BATCH in (select BATCH from PQR
              where TYPE like 'Emp'
                and ORG like 'XYZ')

It works fine if I remove (select 'XYZ' from dual), but I need both Unit as well as Org information.
The current query results in an error

ORA-00937: not a single group function

Regards
Answer: Don't use sub-query.
select listagg((REGEXP_SUBSTR(ABC, '[^:]+$')),';') AS Unit ,
       'XYZ'
  from MNO
 where BATCH in (select BATCH from PQR where TYPE = 'Emp' and ORG = 'XYZ')

Answer: Try selecting just the string literal 'XYZ' instead of using the subquery:
SELECT
    LISTAGG(REGEXP_SUBSTR(ABC, '[^:]+$'), ';') AS Unit,
    'XYZ'
FROM MNO m
WHERE EXISTS (SELECT 1 FROM PQR p WHERE p.BATCH = m.BATCH AND
                                        TYPE = 'Emp' AND ORG = 'XYZ');

Note: The logic of the WHERE subquery is not clear.  It is not clear whether you want to find Emp anywhere in the  Type column or you want an exact match.  For the latter, use WHERE ... TYPE LIKE '%Emp%', and similar for ORG.
Comment: Do you want `TYPE LIKE '%Emp%'` or `TYPE = 'EMP'` ?
Comment: That part I figured it in actual query and have corrected it accordingly
Answer: Seems you need an aggregation for organization within a select statement containing join such as
SELECT p.org, LISTAGG((REGEXP_SUBSTR(m.abc, '[^:]+$')), ';') AS Unit
  FROM MNO m
  JOIN PQR p
    ON m.batch = p.batch
 WHERE p.type LIKE '%Emp%' -- you may replace with 'Emp%' or '%Emp' or 'Emp'
   AND p.org LIKE '%XYZ%' -- you may replace with 'XYZ%' or '%XYZ' or 'XYZ'
 GROUP BY p.org

ListAgg and other column selection


Site está exibindo posts do dia 2 de maio, porém, alguns acessam as notícias atualizadas normalmente

Question: Administro o site www.atodahora.com.br - Desde o dia 7 de maio, às 12h, no meu escritório, visualizo ele como se a data fosse 2 de maio. Não vejo nada além disso. Isso ocorre com outras conexões. Acontece que em outros locais, boa parte das pessoas visualizam o site como deixei pela última vez. No dia 2 de maio, a notícia de destaque é sobre o SAMU. já no dia 7, é sobre o Rio Claro FC. Fiz os procedimentos de limpeza de cache e redirecionamento de DNS na minha conexão, mas nada, não atualiza. Outro exemplo é que quem acessa o dia 7 normalmente, quando tenta pelo Edge, acessa o do SAMU e a notícia do Rio Claro dá erro 404. Não consigo achar se o problema é do servidor de internet, hospedagem ou mesmo no Wordpress. Alguém já enfrentou esse tipo de situação?

[
Comment: O que eu percebi é que seu site muda de acordo com ter `www` ou não. Isso pode dar uma pista de onde procurar o problema. Muito provavelmente são dois WP com dados diferentes. Fez alguma migração recente? Além disso, seus DNSs estão fora de sincronismo, então está acontecendo um "sorteio" de quem vai ver o que. O DNS sozinho não seria capaz de mudar os conteúdos. O fato de ter dois servidores sim.
Comment: Seus registros A apontam para estes endereços 184.108.40.206 e 18.104.22.168, cada um está mostrando um conteúdo. Isto é um problema ou de configuração errada, ou se for proposital, falta de sincronismo nos 2 servidores.
Answer: No seu DNS
Coloque o sem www com o IP do conteudo mais actual
A @ IP

o www coloque antes assim
CNAME www atodahora.com.br

Isto faz com que o www.atodahora.com.br seja um alias do atodahora.com.br


What is half of a medal?

Question: I see on http://www.nbcolympics.com/medals :

Why is there 0.5 of a medal?
Answer: A recent blog post by Daniel Marcelino seems to indicate what I had suspected.  A half of a medal (for statistical purposes) is awarded if an event has a "tie" for the Gold, Silver, or Bronze.
From Daniel's Blog…

Yep, that's right; one can get half a medal by tying for a placement.
Comment: This makes sense to me, except that the IOC doesn't seem to treat things this way (their medal lists are always whole numbers).  But this may be how NBC is treating it.
Comment: I doubt that's right. Canada's Penny Oleksiak won a gold medal in 100m swimming tied with an American and Canada's got one gold medal, not 0.5.
Comment: @Goldorak84 for statistical purposes, I believe it is correct.

What is half of a medal?


How to create a Content Type that reuses data from existing Content Type?

Question: I have a specific use case that does not seem to be covered by existing Drupal 7 modules. I need to be able to create a "content type" that is created by choosing from a list of existing content.
Use Case:
A company that trains new pilots needs two content types:
Type 1: Schedule a training flight.
Type 2: Post training flight details.
Type 1 has the following fields:
(flight_id,trainer_name, plane_name, new_pilot_name, date, airport, flight_status)
IMPORTANT:
Type 2 is created when an admin clicks on the flight_id from a list of scheduled flights.
Type 2 is required to contain the following data/fields:
(content from type 1, trainer_notes, new_pilot_grade)
Comment: I'm not sure I get you: "I need to be able to create a "content type" that is created by choosing from a list of existing content" ? Or do you need to create a content instance? If the latter then I don't see why Entity Reference cannot do the job for you. And do you want to edit the fields from content type 1 in content type 2?
Comment: If this is for drupal 7 please add the tag. My answer is only for drupal 7
Comment: Which Drupal version are you using 7 or 8?
Comment: Do you found a solution?
Comment: @AdrianCidAlmaguer Yes. I use entity reference and choose from a specific content type. The user then has to select from a dropdown list. It is not a two step solution, but it is useful enough to meet use case requirements.

Your answer was helpful.
Comment: I'm glad to help you. Good luck in your projects ;-)
Answer: You can use Entity reference:

Provides a field type that can reference arbitrary entities:

A generic entity reference field
Four widgets:

Two implemented on top of the Options module (Select and Radios/Checkboxes),
Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)

And the Inline Entity Form module:

Provides a widget for inline management (creation, modification,
  removal) of referenced entities. The primary use case is the parent ->
  children one (product display -> products, order -> line items, etc.),
  where the child entities are never managed outside the parent form.
  Existing entities can also be referenced.

Others similar modules to Inline Entity Form:
Entityreference Autocreate

A deliberately simple way to invent nodes on the fly in order to refer to them via entityreference.

References dialog (beta2 release only)

This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog.

Autocreate Node Reference

Autocreate Node Reference adds a node reference field and automatically creates the referred node by cloning a template node.

Node Reference Create

Node Reference Create is an enhancement to the nodereference
  autocomplete widget that allows users to reference non-existent nodes.

Entity connect (rc5 release only)

It will help you to improve the User Experience for creation of new entities or edition of linked entities on your entity reference fields.
The "add a new" button will enable you to add / create a new entity. The first form will be cached then the new form will be generated. Once the new form is completed and saved the user will return to the original form.

EDIT: The module most used is Inline Entity Form, but it doesn't works with the Automatic Nodetitles module, but I know that Entity connect works fine with it. In addition with Entity connect you can edit existing entities. In my case I prefer Entity connect.
Comment: Wow, interesting "list"! Maybe you should add some guidances in your answer to help decide which one to go for in which situations (and also indicate modules that do not have an official D7 release yet, which I often use as a criterium to reduce such list).
Comment: @Pierre.Vriens I've added additional information. But feel free to edit the answer.
Answer: You can use the field node References module
With it you can add the content types you want as fields in your new content type and then use views to display it.


iTMSTransporter upload ipa to iTunes Connect Success but choose in TestFlight Failed

Question: As I see the link upload ipa to testflight,then refer the example,
/usr/local/itms/bin/iTMSTransporter \
-m upload -jwt ex**** \
-asc_provider Apple \
-v eXtreme \
-assetFile /Users/jappleseed/Downloads/MyApp.ipa \
-distribution DeveloperId \
-primaryBundleId com.apple.contentdelivery.theFruitStand

but I got the error message, why it happened?

ERROR: The '-assetFile' option cannot specify a file with an extension of '.ipa' when -distribution is set to 'DeveloperId'.

then I try this command, make the .ipa to .zip,
 /usr/local/itms/bin/iTMSTransporter \
-m upload -jwt ex**** \
-asc_provider Apple \
-v eXtreme \
-assetFile /Users/jappleseed/Downloads/MyApp.zip \
-distribution DeveloperId \
-primaryBundleId com.apple.contentdelivery.theFruitStand

then it show success, but I can not found the ipa in iTunes Connect, as iTunes Connect not showing my uploaded IPA.

Package Summary:
1 packages were uploaded successfully.

Face this situation, then I try this command again, and upload.itmsp contains [metadata.xml, Myapp.ipa].
/usr/local/itms/bin/iTMSTransporter \
-m upload -jwt ex**** \
-asc_provider Apple \
-v eXtreme \
-f /Users/jappleseed/Downloads/upload.itmsp/ \
-distribution DeveloperId \
-primaryBundleId com.apple.contentdelivery.theFruitStand

it also told me success message, and I can see the build version in iTunes connect, but I can not choose the version in TestFlight, then I can not do more.

1 packages were uploaded successfully:
/Users/jappleseed/Downloads/upload.itmsp/
Answer: Use username/password authentication (-m username -p yourpassword) instead of JWT. This solved the issue for me.
Comment: yes, I had found it work for me, just not add the comment, but thanks again.


Different ways to represent functions other than Laurent and Fourier series?

Question: In the book "A Course of modern analysis", examples of expanding functions in terms of inverse factorials was given, I am not sure in today's math what subject would that come under but besides the followings : power series ( Taylor Series, Laurent Series ), expansions in terms of theta functions, expanding a function in terms of another function (powers of, inverse factorial etc.), Fourier series, infinite Products (Complex analysis) and partial fractions (Weisenstein series), what other ways of representing functions have been studied? is there a comprehensive list of representation of functions  and the motivation behind each method?
For example , power series are relatively easy to work with and establish the domain of convergence e.g. for $ \sin , e^x \text {etc.}$ but infinite product representation makes it trivial to see all the zeroes of $\sin, \cos \text etc. $
Also if anyone can point out the subject that they are studied under would be great.
Thank you
Comment: Perhaps you should say first of all, what functions you are talking about. I guess from your post that you mean functions from $\mathbb{R}$ to $\mathbb{R}$ or $\mathbb{C}$ to $\mathbb{C}$, but you should say so explicitly. A function is just a map between sets, so your question is waaay to broad as stated at the moment. Also, this has nothing to do with representation theory.
Comment: @Alex B.: AFAIK harmonic analysis does.
Comment: @Alex B : Yes, I should have been more explicit, but in this case I am hoping to get more than I ask for, if there are other functions besides the ones from $\mathbb R\rightarrow\mathbb R $ or $\mathbb C\rightarrow\mathbb C $ ( what ever they might be ) it would be intresting to know about ( kind of fishing for information that I don't know that I don't know hoping someone might point to something new and intersting when they are not restricted by more explicit requirements of the question).
Answer: You can add the following to your list of representations

Continued fractions. See Jones & Thron or Lorentzen's books
Integral representations (Mellin–Barnes, etc). See the ECM entry
Exponentials.  See Knoebel's paper Exponentials reiterated
Nested radicals. See Schuske & Thron's Infinite radicals in the complex plane
Rational or polynomial approximation (e.g Padé approximants)

I guess the general topic is studied under Complex Analysis, Asymptotic Analysis, Harmonic Analysis.  AFAIK, there is no single book which covers all representations.
Comment: Also wavelets.${}$
Answer: There are literally dozens of ways to represent "arbitrary" (given or unknown) functions $f$ in terms of "special" functions. Each of these ways responds to the particular geometrical situation at hand, to ways of encoding the available information about $f$, to a-priori-conditions that $f$ must fulfill, etc. The special functions used in each particular case are "taken from a catalogue", they are well understood and usually have an algebraically describable behavior with respect to the natural operations (differentiation, shifts, rotations, etc.) present in the given environment.
Answer: This may not be exactly what you are looking for, but in physics a common example of this shows up in quantum mechanics.
The time-independent schroedinger equation in one dimension is:
$ - k \frac{\partial^2 \psi}{\partial x^2} + V(x) \psi = E \psi $
which is essentially an eigenvalue problem for the differential operator
$ - k \frac{\partial^2}{\partial x^2} + V(x) $
where $k$ is a parameter and $V(x)$ is a given function to describe a given physical situation (in physics terms it is the potential of the system).
What happens is that (for suitable $V(x)$) if one imposes a boundary condition on $\psi$, such as $\psi$ must be zero at infinity, then one finds that the eigenvalues of the above operator form a discrete set $\lbrace E_n \rbrace$, and the corresponding eigenfunctions $\lbrace \psi_n(x) \rbrace $ form a complete set for $L^2(\mathbb{R})$. (complete here means that any function can be decomposed as a series $\sum a_n \psi_n$ much like a fourier series).
In fact, if $V(x)$ is taken to be the infinite square well potential ( http://en.wikipedia.org/wiki/Infinite_square_well ) one gets that
$\psi_n(x) = \sin(n \pi x / L)$
and that the $\psi_n$ form a complete set is just the statement that functions can be decomposed into a fourier series. At any rate, one way to think of this whole thing is that by choosing different $V(x)$'s you can generate some fairly weird looking complete sets. For example take a look at the eigenstates portion of:
http://en.wikipedia.org/wiki/Quantum_harmonic_oscillator
Here $\psi_n = (-1)^n e^{x^2} \frac{d^n}{dx^n} \left( e^{-x^2} \right) $ forms a complete set.
Also I believe the study of this kind of problem falls under Functional Analysis.
Answer: To add to Sandeep's list, one can (formally) expand a given function $f(x)$ in terms of a basis function $g(x)$ through the so-called (Lagrange-)Bürmann series.
If in addition to the two previously mentioned functions, you are given an expansion point $a$, and the assumption that $g^{\prime}(x)$ is nonzero over some interval containing $a$, such that $g(x)-g(a)$ is monotonic as $x$ increases over said interval, you can obtain the Bürmann series of $f(x)$ with respect to basis function $g(x)$ and expansion point $x=a$ is
$$f(x)=f(a)+\sum_{k=1}^{\infty} \frac{\beta_k(a)}{k!}(g(x)-g(a))^k$$
where the $\beta_k(x)$ satisfy the recursion
$$\beta_0(x)=f(x),\qquad \beta_k(x)=\frac1{g^{\prime}(x)}\frac{\mathrm d}{\mathrm dx}\beta_{k-1}(x)$$
The series may or may not converge, of course; you're on your own to check the convergence of this expansion.
In addition, one can also consider a continued fraction analog of the Bürmann series:
$$f(x)=f(a)+\cfrac{g(x)-g(a)}{\varphi_1(x)+\cfrac{g(x)-g(a)}{\varphi_2(x)+\cdots}}$$
where the $\varphi_k(x)$ satisfy the recursion
$$\varphi_0(x)=f(x),\qquad p_{-2}(x)=p_{-1}(x)=0,\qquad p_k(x)=p_{k-2}(x)+\varphi_k(x),\qquad \varphi_k(x)=k\frac{g^{\prime}(x)}{\frac{\mathrm d}{\mathrm dx}p_{k-1}(x)}$$
Items 3 and 4 (along with Taylor series and continued fractions) in Sandeep's list can be unified under the heading "continued function representations".


Monitoring routes, hops

Question: we're using Nagios and SmokePing to monitor our systems. In case of problems between our office and a hosting facility we can see risen round trip times and packet losses but have no clue what's the cause of the problem.
I have seen that there's SmokeTrace (http://oss.oetiker.ch/smokeping/doc/smoketrace.en.html) that allows trace routes from within SmokePing.
At best there was a tool that monitors routes and records them for later reference constantly.
Does anyboy know about such a tool/plugin, preferred open source?
Thanks!
Clarification:
I would like to have access to a traceroute result or something like that at a later point in time when I get aware that there was a problem.
Answer: Nagios has a plugin for that.
Comment: If I don't get it wrong this plugin does nothing more than tracerouting a given host/IP and grep if there was at least once an answer indicated by a "ms" response time. I don't think that this solves my problem.
Comment: It's a script you can easily edit.  For example, perhaps you know your preferred route.  Instead of grepping the latency, you could grep for your preferred route, and raise an alert if it changes.  You don't even need Nagios to use this script.  You can just use cron to run the script and do something with the output.  I'm not sure if this is going to help you solve your problem - from your question it sounds like you just want to know when the route changes so you can do further manual checks to trace the problem.
Answer: Try scripting around the MTR command in unix/linux

Monitoring routes, hops


How to convert elements of a column to a list in pandas

Question: I have a dataframe df like
A B     C
1 2 {'id':1}
3 3 {'id':2}
5 4 {'id':3}

I want an output like this.
A B     C
1 2  [{'id':1}]
3 3  [{'id':2}]
5 4  [{'id':3}]

Any  help please. Thanks
Answer: Try with
df['C'] = df['C'].apply(lambda x : [x])


Bash File names will not append to file from script

Question: Hello I am trying to get all files with Jane's name to a separate file called oldFiles.txt.  In a directory called "data" I am reading from a list of file names from a file called list.txt, from which I put all the file names containing the name Jane into the files variable.  Then I'm trying to test the files variable with the files in list.txt to ensure they are in the file system, then append the all the files containing jane to the oldFiles.txt file(which will be in the scripts directory), after it tests to make sure the item within the files variable passes.
#!/bin/bash

> oldFiles.txt
files= grep " jane " ../data/list.txt | cut -d' ' -f 3
if test -e ~data/$files; then
  for file in $files; do
    if test -e ~/scripts/$file; then
      echo $file>> oldFiles.txt
    else
      echo "no files"
    fi
  done
fi

The above code gets the desired files and displays them correctly, as well as creates the oldFiles.txt file, but when I open the file after running the script I find that nothing was appended to the file. I tried changing the file assignment to a pointer instead files= grep " jane " ../data/list.txt | cut -d' ' -f 3   --->   files=$(grep " jane " ../data/list.txt) to see if that would help by just capturing raw data to write to file, but then the error comes up "too many arguments on line 5" which is the 1st if test statement. The only way I get the script to work semi-properly is when I do ./findJane.sh > oldFiles.txt on the shell command line, which is me essentially manually creating the file. How would I go about this so that I create oldFiles.txt and append to the oldFiles.txt all within the script?
Comment: and possibly a `/` in `if test -e ~/data/$files; then` (unless you are operating on user *data* rather than the *data/* directory within your own home directory)
Comment: Paste your script at https://shellcheck.net for validation/recommendation, Use Moar Quotes... Also the `for` loop should not be in the `if` clause/statement afaict.
Comment: `test` only accept one argument at a time, so if you feed it more input then that would cause an error, at least on this side. `test -e foo bar baz more`  prints `bash: test: too many arguments`, Mind you `$files` contains a list of lines/strings that contains `jane` , which leads us back to *Also the for loop should not be in the if clause/statement* and https://shellcheck.net ...
Comment: I think you might need a space between `$file` and `>>`: `echo $file >> oldFiles.txt`
Comment: `$file>>` is valid, but should have a space just to keep it clean. I might be good to use `-f` rather than `-e` if you're testing for if something is a regular file. I think Mark's right, based on the inner test you're missing a slash. And also your assignment to `$files` is not command substitution, it's a syntax error (the other version you tried is how you need to do that). And — quotes.
Comment: Well, right now `$files` contains nothing, because it's just assigning files to an empty string and then running the grep|cut. But if that's fixed, then @Jetchisel is right. I don't know why my Shellcheck plugin didn't warn my about that, but the CLI does, I completely overlooked it at first.
Comment: If this is really the pasted code of your program, you don't set the variable `files`. It is set as an environment variable inside the grep subprocess (`files=  grep ....`) runs _grep_  as a process with the environment variable `files` set to an empty string; you can verify this by doing i.e. `files=   printenv files`.
Answer: The biggest problem you have is matching names like "jane" or "Jane's", etc. while not matching "Janes". grep provides the options -i (case insensitive match) and -w (whole-word match) which can tailor your search to what you appear to want without having to use the kludge (" jane ") of appending spaces before an after your search term. (to properly do that you would use [[:space:]]jane[[:space:]])
You also have the problem of what is your "script dir" if you call your script from a directory other than the one containing your script, such as calling your script from your $HOME directory with bash script/findJane.sh. In that case your script will attempt to append to $HOME/oldFiles.txt. The positional parameter $0 always contains the full pathname to the current script being run, so you can capture the script directory no matter where you call the script from with:
dirname "$0"

You are using bash, so store all the filenames resulting from your grep command in an array, not some general variable (especially since your use of " jane " suggests that your filenames contain whitespace)
You can make your script much more flexible if you take the information of your input file (e.g list.txt), the term to search for (e.g. "jane"), the location where to check for existence of the files (e.g. $HOME/data) and the output filename to append the names to (e.g. "oldFile.txt") as command line [positonal] parameters. You can give each default values so it behaves as you currently desire without providing any arguments.
Even with the additional scripting flexibility of taking the command line arguments, the script actually has fewer lines simply filling an array using mapfile (synonymous with readarray) and then looping over the contents of the array. You also avoid the additional subshell for dirname with a simple parameter expansion and test whether the path component is empty -- to replace with '.', up to you.
If I've understood your goal correctly, you can put all the pieces together with:
#!/bin/bash

# positional parameters
src="${1:-../data/list.txt}"  # 1st param - input (default: ../data/list.txt)
term="${2:-jane}"             # 2nd param - search term (default: jane)
data="${3:-$HOME/data}"       # 3rd param - file location (defaut: ../data)
outfn="${4:-oldFiles.txt}"    # 4th param - output (default: oldFiles.txt)

# save the path to the current script in script
script="$(dirname "$0")"

# if outfn not given, prepend path to script to outfn to output
# in script directory (if script called from elsewhere)
[ -z "$4" ] && outfn="$script/$outfn"

# split names w/term into array
# using the -iw option for case-insensitive whole-word match
mapfile -t files < <(grep -iw "$term" "$src" | cut -d' ' -f 3)

# loop over files array
for ((i=0; i<${#files[@]}; i++)); do
  # test existence of file in data directory, redirect name to outfn
  [ -e "$data/${files[i]}" ] && printf "%s\n" "${files[i]}" >> "$outfn"
done

(note: test expression and [ expression ] are synonymous, use what you like, though you may find [ expression ] a bit more readable)
(further note: "Janes" being plural is not considered the same as the singular -- adjust the grep expression as desired)
Example Use/Output
As was pointed out in the comment, without a sample of your input file, we cannot provide an exact test to confirm your desired behavior.
Let me know if you have questions.
Comment: In your solution, each element in `files` contains a word with _jane_ as a substring (case-insensitively). In the OPs selection algorithm, he takes the 3rd word from those lines which contain somewhere _jane_ after a space. This is a completely different approach. Since we don't know how the input file actually looks like, we can't say which is the right way to extract the filename. At least from the use of `cut` by the OP, we can conclude that the lines contain some other information aside of the filename.
Comment: @user1934428 that is a good point -- I looked over that, I'll get that taken care of. But as you point out -- without seeing the input file -- we are largely guessing. Thank you for catching that, I just went with what the original had.
Answer: As far as I can tell, this is what you're going for. This is totally a community effort based on the comments, catching your bugs. Obviously credit to Mark and Jetchisel for finding most of the issues. Notable changes:

Fixed $files to use command substitution
Fixed path to data/$file, assuming you have a directory at ~/data full of files
Fixed the test to not test for a string of files, but just the single file (also using -f to make sure it's a regular file)
Using double brackets — you could also use double quotes instead, but you explicitly have a Bash shebang so there's no harm in using Bash syntax
Adding a second message about not matching files, because there are two possible cases there; you may need to adapt depending on the output you're looking for
Removed the initial empty redirection — if you need to ensure that the file is clear before the rest of the script, then it should be added back, but if not, it's not doing any useful work
Changed the shebang to make sure you're using the user's preferred Bash, and added set -e because you should always add set -e

#!/usr/bin/env bash
set -e

files=$(grep " jane " ../data/list.txt | cut -d' ' -f 3)
for file in $files; do
    if [[ -f $HOME/data/$file ]]; then
        if [[ -f $HOME/scripts/$file ]]; then
            echo "$file" >> oldFiles.txt
        else
            echo "no matching file"
        fi
    else
        echo "no files"
    fi
done

Comment: This solution assumes, that there is no matching file with a space in the filename. I think it is worth pointing this out explictly, although it follows implicitly from the broken code the OP posted. However, given the many errors in the OP''s code, I'm not sure whether the OP is really aware of this restriction.


How can I get the stop position in mplayer when I quit?

Question: If I have a script that plays a file using mplayer and I stop the playback half way through, is there a way to store the playback position where it stopped?
Answer: Try this
its quick and dirty but gives me the seconds of the played song after mplayer exited
mplayer your.mp3 | tr [:cntrl:] '\n' | bbe -e "s/\x0a\x5b\x4a//" | tail -n 4 | head -n 1 | cut -d ':' -f 2 | cut -d '(' -f 1
Comment: I'm not sure why there was a down-vote on this answer. The approach here is probably the only way to get the playback position when mplayer was stopped. This will not work if mplayer is abnormally terminated though.
Answer: It should be noted that this does almost the same thing as 0800peter's answer but without the need to install bbe. Essentially, this is a rewrite of that answer with a friendly interface. This answer also accounts for the event that mplayer is prematurely terminated (as in with pkill mplayer).
#!/bin/bash

# desc: Runs mplayer to play input file and returns seconds of playback when stopped
# input:
#   arg1: path to audio file
#   arg2: pass either [seconds|timestamp]; default timestamp
# output: returns the timestamp or total seconds elapsed when playback stopped
#   (ie. when mplayer terminated)
playAudioFile() {
    audioFile="$1"

    # if you need to modify mplayer switches, do so on the next line
    stopPos=$(mplayer "$audioFile" 2> /dev/null | tr [:cntrl:] '\n' | grep -P "A: +\d+\.\d\b" | tail -n1)

    # decide what to display
    if [ "$2" == "seconds" ]; then
        retval=$(awk '{print $2}' <<< "$stopPos")
    else
        retval=$(awk '{print $3}'  <<< "$stopPos" | tr -d '()')
    fi

    echo "$retval"
}

#example usage
path="$1"
stopPosition=$(playAudioFile "$path")
echo "$stopPosition"

My script, as it is, accepts the path to an audio file and when mplayer terminates (normally or abnormally), a timestamp or seconds elapsed is returned. If you opt to receive a timestamp, note that the timestamp will not have a placeholder for any unit with a value zero. In other words, 00:00:07.3 would be returned as 07.3 and 00:10:01.2 would be returned as 10:01.2

What if I want to send mplayer to the background?
If you want to be able to start mplayer and send it to the background and still be able to query for this information, you might want to take a look at a bash script I wrote for tracking playback status information. That script incorporates two functions called getElapsedTimestamp and getElapsedSeconds, both of which return the playback time even if mplayer has already terminated. To use these functions, the media file must be started with my playMediaFile function. This function can be called like this to start mplayer and send to background ...
playMediaFile "path/to/your/file" &


How to select text with javascript that's not already in a div/span

Question: I am using the typing effect shown at https://www.w3schools.com/howto/howto_js_typewriter.asp. However, I want to change it a bit by making the word "effect!" text blue.
The problem is, I don't know how to select text that is not wrapped in an html element like a span/div already. I don't think javascript/css can select individual characters so I tried injecting a  tag during in the if statement but the browser seems to automatically close any span tag left open. Not sure where to go from here.
Original code from W3

var i = 0;
var txt = 'Lorem ipsum typing effect!'; /* The text */
var speed = 50; /* The speed/duration of the effect in milliseconds */

function typeWriter() {
  if (i < txt.length) {
    document.getElementById("demo").innerHTML += txt.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  }
}

My code
var i = 0;
var txt = 'Lorem ipsum typing effect!'; /* The text */
var speed = 50; /* The speed/duration of the effect in milliseconds */

function typeWriter() {
  if (i < txt.length) {
    document.getElementById("demo").innerHTML += txt.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  if (i == 20) {
    document.getElementById("demo").innerHTML += '';
  if (i == 26) {
    document.getElementById("demo").innerHTML += '';
}

I would like to get "Lorem ipsum typing effect!" with "effect!" wrapped in a span so I can change that text to blue. i.e. "Lorem ipsum typing effect!"
Comment: Great first question.  I would point you in the direction of looking at regex patterns for string manipulation. For example Great first question.  I would point you in the direction of looking at regex patterns for string manipulation.  Regex101.com is a great resource.  You could do something like this: `const result = ("Lorem ipsum typing effect!").replace(/(.+)(effect)(.+)/gm, `\1\2\3`);`
Answer: Use replace to find and swap the entire string you're looking for. This will not be visible until the entire word is visible though.
if (i == 26) {
    var txt = document.getElementById("demo").innerHTML;
    txt.replace("effect!", "effect!");
    document.getElementById("demo").innerHTML = txt
}

If you want it "as you go", you need to wrap the span around each character when i is between 20 and 26 as part of adding it to he DIV.
document.getElementById("demo").innerHTML += "" + txt.charAt(i) + "";

Answer: You need to do some manipulation with the txt variable before injecting it into the innerHTML. Here's the complete code.

 <!DOCTYPE html>

Typewriter

    <button onclick="typeWriter()">Click me</button>


Flutter scrollable TabBarView in Column without predefined size

Question: I want to have a screen with a widget at the top followed by a TabBar. I want that everything is inside a SingleChildScrollView so that the whole screen can be scrolled (not only content of a single tab).
--------------------
|      Widget      |
--------------------
|      TabBar      |
--------------------
|                  |
|                  |
|    TabBarView    |
|                  |
|                  |
--------------------

I had a look at similar questions but they did not help with what I am trying to achieve:
How to add a tab inside a column widget on flutter
Make TabBarView take up all remaining space
I cannot set a fixed height as I don't know it (tab bar content).
My approach which is not working:
class TestScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Test'),
      ),
      body: SingleChildScrollView(
        child: DefaultTabController(
          length: 2,
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text('My Top Widget'),
              ),
              TabBar(
                tabs: [
                  Tab(child: Text('Available')),
                  Tab(child: Text('Taken')),
                ],
              ),
              TabBarView(
                children: [
                  Center(child: Text('1')),
                  Center(child: Text('2')),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

I get the following error:
Horizontal viewport was given unbounded height.

Viewports expand in the cross axis to fill their container and constrain their children to match their extent in the cross axis. In this case, a horizontal viewport was given an unlimited amount of vertical space in which to expand.
The relevant error-causing widget was:
  TabBarView file:///home/kay/Code/emat/frontend/lib/ui/TestScreen.dart:26:15

How it should be in the end:
Comment: may be try this https://stackoverflow.com/questions/50433885/sliverappbar-with-tabbar/50853287#50853287 @xooback
Answer: I finally solved this issue. I had a look at how slivers work and chose to use them. I can suggest this video as an introduction and the online docs for further reading.
Here is my approach now:
class TestScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Test'),
      ),
        body: DefaultTabController(
          length: 2,
          child: NestedScrollView(
            scrollDirection: Axis.vertical,
            headerSliverBuilder: (context, innerBoxIsScrolled) => [
              SliverToBoxAdapter( //headerSilverBuilder only accepts slivers
                child: Column(
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Text('My Top Widget'),
                    ),
                    TabBar(
                      tabs: [
                        Tab(child: Text('Available')),
                        Tab(child: Text('Taken')),
                      ],
                    ),
                  ],
                ),
              ),
            ],
            body: TabBarView(
              children: [
                // I wrapped large widgets in the SingleChildScrollView
                SingleChildScrollView(
                  child: Text('1')/*Very large widget*/,
                ),
                Text('2'),
              ],
            ),
          ),
        ),
    );
  }
}

Comment: But this makes the top widget go up to the top of the screen and eventually disappear even if there is little to no data in TabBarViews.
Comment: Could be that this solution is outdated by now. I haven't touched flutter in a while and cannot guarantee that this solution is still valid...


How can I point to an internal anchor using core menu?

Question: We have a navigation menu created using Drupal's built-in menu system. One of our menu items has the path set to "node/100770#digital-anchor," but when the menu is rendered, it strips off everything to the right of the node ID. I've tried this suggestion (using a named id), but the issue isn't that the browser is ignoring everything the node id; it's that Drupal is actually stripping off everything after the id when the menu is rendered. If I look at the rendered source in the browser, it just isn't there.
How can we point to an internal anchor (or named element, if you believe that anchors are deprecated) using the default menu?
Answer: I don't think you can do that through the UI.
However, you should be able to specifify it with menu_link_save() in a module, for example in a hook_install() implementation. See the options key.
Looking at url(), something like 'fragment' => 'digital-anchor' should do the trick.
Comment: I should have added that I'm extremely new to Drupal! I have no idea where I would do something like this.
Answer: Check out the l() function built into core.
The function is l($text, $path, $options = array()); in that options array you can specify an associative array of HTML attributes to apply to the anchor tag (the array index is "attributes").
Answer: I have come across this before. I think it is to do with this issue, in the end I had to create some of my own theme functions to allow it.


create custom colormap with custom limits and smooth color transition in matlab

Question: I want to convert any number 0<=f<=1 to a rbg code given by four categories green, yellow, orange and red. I can achieve that with the following function:
function [rgb,myColor]=colorCode(f)
cm = [0 1 0;1 1 0;255/255 153/255 51/255;1 0 0];
colorID = max(1, sum(f > [0:1/length(cm(:,1)):1]));
myColor = cm(colorID, :);
rgb = uint8(myColor*255+0.5);

Now, I will like to do 2 improvements to this:
1.- Above code will divide the interval [0,1] in four equal parts, that is:
[0,0.25]>green
[0.25,0.5]>yellow
[0.5,0.75]>orange
[0.75,1]>red

But I will like to define custom intervals, for instance:
[0,0.3]>green
[0.3,0.5]>yellow
[0.5,0.7]>orange
[0.7,1]>red

2.- I would like that the transition between color intervals to be more smooth. Right now, between 0.25 and 0.26 color changes suddenly from green to yellow. The idea would be to go from green to green-yellow-ish to yellow-green-ish to yellow, and the analogous for the other transitions. I now I have to add more rows to the cm colormap matrix, but I have no idea how....
Comment: Possible duplicate of [How to create a custom colormap programmatically?](https://stackoverflow.com/questions/17230837/how-to-create-a-custom-colormap-programmatically)
Comment: Thanks, between your comments I could make it to work. I'll post the solution
Comment: Possibly related: [Control colorbar scale in MATLAB](https://stackoverflow.com/q/54675647/8239061) which also links to very related posts.
Comment: You can create a custom colormap using [this answer](https://stackoverflow.com/a/54676842/8239061) (see the **Bonus** section) with the [`interp1`](https://www.mathworks.com/help/matlab/ref/interp1.html) function.  I realize this isn't a complete answer to your question.
Comment: on the off chance this is just a one-off effort and you don't want to do it programmatically, you can try [this](http://www.ece.northwestern.edu/local-apps/matlabhelp/techdoc/ref/colormapeditor.html)
Answer: function [rgb,myColor]=colorCode(f)
n=length(f);
switch n
    case 1
        cm = [0 1 0;1 1 0;255/255 128/255 0/255;1 0 0;1 0 0];
        x=[0 0.3 0.5 0.7 1];
        cm = interp1(x,cm, linspace(0, 1, 255));
        colorID = max(1, sum(f > [0:1/length(cm(:,1)):1]));
        myColor = cm(colorID, :); % returns your color
        rgb = uint8(myColor*255+0.5);
    otherwise
        rgb=zeros(n,3);
        myColor=rgb;
        for i=1:n
            [rgb(i,:),myColor(i,:)]=colorCode(f(i));
        end
end


Boas práticas para evitar exibição de página quebrada?

Question: Problema:
Desenvolvi um site que ao ser carregado é exibido com alguns bugs, como imagens exibidas no lugar de uma outra que não foi carregada a tempo, formulários totalmente bugados e sem estilização nenhuma.
Alternativa:
Pressionar "F5", porém um usuário leigo, não vai imaginar que a página será recarregada corretamente após esta função, resultando na perda de confiança ou até mesmo a evasão do próprio.
Pergunta:
O que poderia ser feito afim de evitar que a página fosse exibida com quebras de marcação, ou estilização incompleta?
OBS:
O HTML está bem aplicado de forma semântica e a chamada do arquivo CSS externo está logo após o title.
Acredito que criando um loading em php ou js na tela pra que dispare a página somente após ser totalmente carregada já soluciona meu problema, mas estou disposto e aberto à novas soluções.
Comment: Cara, cria um simples loader em JS e você resolve o problema.
Se suas imagens possuem um tamanho padrão, ou agrupamentos padrão, defina classes css com altura e largura definidos e depois só aplica a classe na imagem... poupa código. Ex:
``
Answer: Seu layout é feito por imagens?
Se sim, uma das maneiras de contornar esse redimensionamento enquanto as imagens vão sendo carregadas é predefinir o tamanho das imagens.
Isso permite que o browser já reserve o espaço exato para a imagem. Além disso, se alguma imagem por ventura não vier a carregar, não irá atrapalhar o resto do layout (pelo menos o espaço que ela deveria ocupar o browser se encarregará de preencher, nem que seja com um X de erro).
Ao invés de apenas:

Especificar também width e height:

Uma desvantagem é ter que ficar marcando as tags img com estes atributos; mas ora pode ser necessário.
Answer: O primeiro passo é identificar o problema. Existe um motivo pelo qual as imagens ou o CSS não carrega de forma correta. O posicionamento do CSS não esta diretamente ligado ao problema. O que pode estar acontecendo é o servidor encontrar problemas durante a transmissão dos arquivos.
Existe também a possibilidade de atualizar a página de forma automatica utilizando JavaScript quando a mesma terminar de carregar, porém isso não garante que as imagens carreguem. Neste caso seria necessario também o uso de cookies para saber quando é  a segunda vez que a página esta sendo carregada.
Já em relação ao script em PHP, isso não ira resolver seu problema. O que é possivel ser feito é a utilização de lazy loading ou late loading, que basicamente você carrega o recurso após a página ter sido carregada por completo. Com isso é possivel identificar quando um recurso não foi carregado de forma correta e tentar carregar o mesmo novamente. O problema é que isso gera problemas de performance quando o site possuir muitos recursos. Neste caso é possivel implementar um script PHP para auxiliar no processo, porém é totalmente possivel ser feito em JavaScript.
Uma solução mais estética seria definir todos os elementos com altura e largura fixas no CSS, dessa forma quando um elemento não carregar não ira causar grandes problemas de formação. Isso não se aplica caso o CSS não carregar.
Answer: Exibir o html após carregar  - Js
body.onload=function(){document.getElementsByTagName('body').style.display='none';};
window.onload=function(){document.getElementsByTagName('body').style.display='block';};

Loader em PHP não vai te atender, porque PHP é server-side.. ou seja, ele vai renderizar sua página e após isto, que o navegador vai fazer o download do site, ou seja, depois do php trabalhar é que você vai baixar imagens, que é aonde o erro ocorre...
Definir tamanho de cada imagem também é uma boa, preserva o espaço alocado antes de baixar...
Definir tamanhos padrão de imagem ajuda.
Uma lida em responsividade, também ajuda.


WebMethod para criar Documento de Venda com edição de parametros nas linhas do documento

Question: Bom Dia,
Estamos a desenvolver um webservice / metodo que cria documentos de venda.
No cabeçalho eu consigo passar os valores todos aos parametros do cabeçalho.
Mas nas linhas como consigo fazer o mesmo?
Por exemplo, se quiser alterar a descrição do artigo, ou a taxa de iva, ou se quiser passar valores a campos do utilizador... como faço?
No exemplo seguinte não consigo....
Alguma ajuda ou sugestão? Obrigado.
public string SalesDocument(string sTransactionID, string sInstance, string sCompanyCode, string sUsername, string sPassword, string xml)

{
        string sNrDoc = "";
        string sResp = string.Empty;

        var Lista = new StdBELista();
        try
        {

            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(xml);
            var trans = new StdBETransaccao();
            var vTipoPlataforma = new EnumTipoPlataforma();
            var DocVenda = new GcpBEDocumentoVenda();
            var CDUPrimavera = new StdBECampos();

            string sExtDocNumber = string.Empty;
            string sSONumber = string.Empty;
            string sTipoDoc = string.Empty;
            string sEntidade = string.Empty;
            string sTipoEntidade = string.Empty;
            string sSerie = string.Empty;
            string sMoeda = string.Empty;
            string sCN = string.Empty;
            string sCNOriginalDocNumber = string.Empty;
            string sCondPag = string.Empty;
            string sModoPag = string.Empty;
            string sNumberLines = string.Empty;
            string sComments = string.Empty;
            string sShippingAddress1 = string.Empty;
            string sShippingAddress2 = string.Empty;
            string sShippingCity = string.Empty;
            string sShippingPostalCode = string.Empty;
            string sShippingPostalCodeCity = string.Empty;
            string sShippingCountry = string.Empty;

            int iNrLines = 0;
            string sArtigo = string.Empty;
            string sDescricao = string.Empty;
            int sCodIva;
            double sPrecoUnit;
            double sQuantidade;
            string sUnidade;
            double sDescontoLinha;
            string sObs = string.Empty;

            string dataXML;

            DateTime dDataDoc;

            int codigoInteracao;
            string strSql = "";
            string strQuantos = "";

            StdBELista qyrConsultaCodigo = new StdBELista();

            vTipoPlataforma = EnumTipoPlataforma.tpProfissional;

            ErpBS motor = new ErpBS();
            motor = DaMotorInicializado(vTipoPlataforma, sCompanyCode, sUsername, sPassword, trans, sInstance);

            var plataforma = DaPlataformaInicializada(sCompanyCode, sUsername, sPassword, sInstance);

            strQuantos = "select count(CDU_Codigo) as Total from TDU_web_moneris";
            qyrConsultaCodigo = motor.Consulta(strQuantos);
            codigoInteracao = qyrConsultaCodigo.Valor("Total") + 1;

            XmlNodeList xnList = xDoc.GetElementsByTagName("DocHeader");

            sExtDocNumber = xnList[0]["ExternalDocNumber"].InnerXml;
            sSONumber = xnList[0]["SONumber"].InnerXml;
            sTipoDoc = xnList[0]["DocCode"].InnerXml;
            sEntidade = xnList[0]["ClientCode"].InnerXml;
            sTipoEntidade = "C";
            sSerie = xnList[0]["Serie"].InnerXml;
            dataXML = xnList[0]["Date"].InnerXml;
            dDataDoc = DateTime.Parse(dataXML);
            sMoeda = xnList[0]["Currency"].InnerXml;
            sCN = xnList[0]["CN"].InnerXml;
            sCNOriginalDocNumber = xnList[0]["CNOriginalDocNumber"].InnerXml;
            sModoPag = xnList[0]["PaymentMethod"].InnerXml;
            sCondPag = xnList[0]["PaymentTerm"].InnerXml;
            sNumberLines = xnList[0]["NumberOfLines"].InnerXml;
            sComments = xnList[0]["Comments"].InnerXml;
            sShippingAddress1 = xnList[0]["ShippingAddress1"].InnerXml;
            sShippingAddress2 = xnList[0]["ShippingAddress2"].InnerXml;
            sShippingCity = xnList[0]["ShippingCity"].InnerXml;
            sShippingPostalCode = xnList[0]["ShippingPostalCode"].InnerXml;
            sShippingPostalCodeCity = xnList[0]["ShippingPostalCodeCity"].InnerXml;
            sShippingCountry = xnList[0]["ShippingCountry"].InnerXml;

            //bool bErro = false;
           //string sIsAlive = IsAlive(sInstance, sCompanyCode, sUsername, sPassword);

            //if (sIsAlive == "000")
            //{
            //    sResp = sTransactionID;
            //}
            //else
            //{
            //    sResp = sTransactionID + "#" + sIsAlive;
            //    bErro = true;
            //}

            //if (motor.Comercial.Vendas.ExisteReferencia("000",sTipoDoc,sSerie,sEntidade,sExtDocNumber))
            //{
            //    bErro = true;
            //    sResp += "#200";

            //}

            CDUPrimavera.set_Item("CDU_ExternalDocNumber", sExtDocNumber);

            DocVenda.set_Referencia(sSONumber);
            DocVenda.set_Tipodoc(ref sTipoDoc);
            DocVenda.set_Entidade(ref sEntidade);
            DocVenda.set_TipoEntidade(ref sTipoEntidade);
            DocVenda.set_Serie(ref sSerie);
            DocVenda.set_DataDoc(ref dDataDoc);
            DocVenda.set_Moeda(sMoeda);

            CDUPrimavera.set_Item("CDU_CN", sCN);
            CDUPrimavera.set_Item("CDU_CNOrigDocNumber", sCNOriginalDocNumber);

            DocVenda.set_ModoPag(ref sModoPag);
            DocVenda.set_CondPag(ref sCondPag);

            motor.Comercial.Vendas.PreencheDadosRelacionados(ref DocVenda);

            CDUPrimavera.set_Item("CDU_TotalLines", sNumberLines);

            DocVenda.set_Observacoes(sComments);
            DocVenda.set_MoradaFac(sShippingAddress1);
            DocVenda.set_Morada2Fac (sShippingAddress2);
            DocVenda.set_LocalidadeFac(sShippingCity);
            DocVenda.set_CodigoPostalFac(sShippingPostalCode);
            DocVenda.set_CodigoPostalFac(sShippingPostalCodeCity);
            DocVenda.set_PaisFac(sShippingCountry);

            DocVenda.set_CamposUtil(CDUPrimavera);

            XmlNodeList xnListLinhas = xDoc.GetElementsByTagName("Line");
            foreach (XmlNode oNo in xnListLinhas)
            {

                sArtigo = oNo["ItemCode"].InnerXml;
                sCodIva = Int32.Parse(oNo["VatCode"].InnerXml);
                sPrecoUnit = double.Parse(oNo["UnitPrice"].InnerXml);
                sQuantidade = double.Parse(oNo["Quantity"].InnerXml);
                sUnidade = oNo["Unit"].InnerXml;
                sDescontoLinha = double.Parse(oNo["Discount"].InnerXml);

                motor.Comercial.Vendas.AdicionaLinha(DocVenda, sArtigo, sQuantidade, "", "", sPrecoUnit, sDescontoLinha, "", sQuantidade, 0, 0, 0, 0, 0, 0, false, false, 0);

                //Aqui os parametros a passar são fixos, não me permite alterar a descrição ou a taxa de iva, etc....

            }
            motor.Comercial.Vendas.Actualiza(DocVenda, "", "");

            string qNumDoc = "select max(numdoc) as Ndoc from CabecDoc where TipoDoc = '" + sTipoDoc + "' and Serie = '" + sSerie + "'";

            Lista = motor.Consulta(qNumDoc);
            sNrDoc = Lista.Valor("Ndoc").ToString();
            string sDocPDF = "";
            sDocPDF = @Server.MapPath("~/Files/Documentos/") + sCompanyCode + "_" + sNrDoc + "_" + sSerie + ".pdf";

            motor.Comercial.Vendas.ImprimeDocumento(sTipoDoc, sSerie, int.Parse(sNrDoc), "000", 1, "", false, sDocPDF, 1);

            System.IO.FileStream dd = System.IO.File.OpenRead(sDocPDF);
            byte[] Bytes = new byte[dd.Length];
            dd.Read(Bytes, 0, Bytes.Length);

            strSql = "Insert into TDU_web_moneris values('" + codigoInteracao + "','" + sInstance + "','" + sCompanyCode + "','" + sUsername + "','" + sPassword + "','" + xml + "','" + DateTime.Now + "','" + Bytes + "')";
            plataforma.ExecSql.ExecutaXMLSqlServer(strSql);

            motor.FechaEmpresaTrabalho();
            plataforma.FechaPlataforma();

            return sResp;

        }
        catch (Exception ex)
        {
            using (StreamWriter writer = new StreamWriter(Server.MapPath("~/Files/Logs/") + DateTime.Now.ToString("yyyy-MM-dd hh_mm_ss") + ".txt", true))
            {
                writer.WriteLine("SalesDoc Method - Error: " + ex.Message);
                writer.WriteLine(ex.Message.ToString());
            }

            return sResp;
        }
        finally
        {

        }

    }

Answer: Para isso basta editar a última linha adicionada ao objeto DocVenda, ainda dentro do ciclo foreach (onde está a adicionar as linhas, uma-a-uma) e alterar o valor das propriedades que quiser:
// ...
foreach (XmlNode oNo in xnListLinhas)
{
    sArtigo = oNo["ItemCode"].InnerXml;
    sCodIva = Int32.Parse(oNo["VatCode"].InnerXml);
    sPrecoUnit = double.Parse(oNo["UnitPrice"].InnerXml);
    sQuantidade = double.Parse(oNo["Quantity"].InnerXml);
    sUnidade = oNo["Unit"].InnerXml;
    sDescontoLinha = double.Parse(oNo["Discount"].InnerXml);

    motor.Comercial.Vendas.AdicionaLinha(DocVenda, sArtigo, sQuantidade, "", "", sPrecoUnit, sDescontoLinha, "", sQuantidade, 0, 0, 0, 0, 0, 0, false, false, 0);

    GcpBELinhaDocumentoVenda linhaVenda = venda.get_Linhas()[venda.get_Linhas().NumItens];

    linhaVenda.set_Descricao("teste");
    linhaVenda.set_TaxaIva(21);
    linhaVenda.get_CamposUtil().get_Item("CDU_Teste").Valor = "olá mundo!";
}
// ...


For which $1\le p\le\infty$ does $u$ belong to $W^{1,p}(\Omega)$?

Question: Hi could anyone help with a solution for problem 7 Evans PDE chapter 5?

I think it is basically about checking which $p$ allows
$$\int_{\Omega} |u|^p dx+\int_{\Omega}|Du|^p dx<\infty$$
?
But I tend to generate messy output as I always do...
Please help...
Answer: You first have to check that $u$ has a weak derivative.
You have an obvious candidate for the weak gradient (just take the gradient separately in the four pieces), and you just have to check that it works.
You might also have a theorem that saves you from calculations at this point, having a weak derivative should still be checked somehow.
Then you have explicit formulas for $u$ and $\nabla u$.
Observe that $|u|$ and $|\nabla u|$ are bounded (actually they are both bounded by $1$).
You either find an upper bound for the integrals you have or just state that $u\in L^p(\Omega)$ and $|\nabla u|\in L^p(\Omega)$.
For $p=\infty$ the norm does not have an integral representation, so you have to resort to the second one.
If you do the integrals, you don't have to do them explicitly and messily; a very rough estimate will suffice.
Can you finish with these ideas?

Checking weak differentiability:
If you know that the pointwise minimum of two $W^{1,p}$ functions is again in $W^{1,p}$, you can use that.
You can also do it by hand.
In the four pieces (where $u$ is defined), it is easy to calculate the strong gradient $\nabla u$.
It takes the four values $(\pm1,0)$ and $(0,\pm1)$.
Now you have $\nabla u$ defined almost everywhere.
You will just have to check that for any $\eta\in C_0^\infty(U)$ you have
$$
\int_Uu\nabla\eta=\int_U\eta\nabla u.
$$
Comment: Step 1, I have worked out $Du=v=1$ for the first term, and $v=-1$ for the rest of the 3 terms. By inspection that $u$ is clearly bounded by 1. But, I am not sure what you meant in your second last paragraph...could you illustrate the idea more explicitly? I am inexperienced of writing this sort of thing in full mathematics sentences...
Comment: @math101, you have a function $u\in L^1$ that has a weak gradient $Du\in L^1$. (Note that the weak gradient is vector valued, so $Du=1$ does not make sense. In the first piece $DU=(-1,0)$.) Since $u\in L^p$ and $Du\in L^p$, then by definition of the Sobolev space, $u\in W^{1,p}$. This holds for any $p$, so $u\in W^{1,p}$ for all $p\in[1,\infty]$.
Comment: Yes I just realised $\mathbb{R}^2$, so the next 3 pieces should all be $Du=(1,0). The rest of your comment also make sense to me now. Appreciate that...
Comment: By the way, I have another vector calculus type question urgently need some help but no one answer, http://math.stackexchange.com/questions/1355970/a-vector-calculus-problem-when-coping-with-problem-9-chapter-5-evans   but never mind if you are not interested
Comment: @math101, no, the weak gradient is different in the four pieces. It's values are (-1,0), (1,0), (0,-1) and (0,1), in the order of the definition. I don't have the time to look into your other question now (it did look like a fine question, though). I might have a look later, but I won't promise anything now.
Comment: okay...I think I am lost, so how did you get those three different...feel free to answer any of my question at any time of your convenience, if you wish. It is almost 2am here, will be back in the next 10 hours...
Comment: @math101, I was just calculating the gradient in the usual (classical, strong, whatever you call it) way in each of the components. In the third component we have $u(x)=1-x_2$ so $\nabla u(x)=(0,-1)$. The others are similar.
Comment: llmavirta, I was silly enough...trying to plug things into the weak derivative definition (formula) $\int_U u\phi'dx=-\int_0^2 v\phi dx$. So, to compute the weak derivative here, all I need is $Du=v?$
Comment: sorry, i wasn't able to get name display property here...
Comment: @math101, it seems that you should perhaps ask a separate question about the weak derivative (for this function or another one and link here if needed). A complete answer would not be very short, so I would prefer not to include it here. I added some details to the end of my answer.
Comment: I am not sure what separate question I need, this is currently the only question relates to weak derivative. What bothering me now are my other unanswered questions…
Comment: @math101, if the thing is clear, then there is no need for a new question. I hope my answer was of help to you. :)
Comment: Your answer seems neat…But I am struggling with some other bugs so I will check again later :-)
Comment: Actually, I am looking at https://sunlimingbit.wordpress.com/2012/11/25/one-example-related-to-weak-derivative-2/  a bit confused when it reached the last line...
Comment: @math101, the blog post seems well explained and clear. The blog shows that the function defined in the last equation indeed satisfies the definition of weak partial derivative in (1). If this needs further clarification, I would suggest asking a new question and explaining in detail what is it that confuses you. This comment discussion is getting quite long.
Comment: I still have some confusion in the posted answer found in the blog, could you check my newly posted question http://math.stackexchange.com/questions/1358450/computing-weak-derivatives-on-an-open-square?
Comment: @math101, that looks like a good question. I might look into that if I have the time; I only had the time to read and vote now.
Comment: i have ticked your answer. By the way, have you got a moment to look at my other post last night?
Comment: @math101, I did give it a look, but I might not have the time to write a solution, as it may take a while to do so properly.


como usar a função LPAD com à COUNT?

Question: Apenas para exemplificação:
Estou tentando fazer um select em que sera adicionado um zero à esquerda caso o número for menor que 10.
Exemplos:
SELECT COUNT(1);

Retorna => 1
SELECT LPAD(1, 2, 0);

Retorna => 01
SELECT LPAD(COUNT(1), 2, 0);

Retorna => BLOB
Como faço para usar a função LPAD com à COUNT, ou alguma que faça algo similar?
Comment: Testei seu código no meu servidor e funcionou, qual a versão do seu `MySQL`?
Comment: Estranho, para mim sempre retorna "blob". A versão do mysql aqui é: 5.6.39-cll-lve
Comment: Testei em outro servidor e retornou corretamente também, só para informação a versão desse servidor é `5.6.39-83.1`.
Answer: Depois de pesquisar um pouco, descobrir que isso pode ser um bug gerado pelo Drive. Assim, o problema que estava ocorrendo comigo, não necessariamente acontecerá em outros computadores.
Para corrigir isso, e ter o valor esperado em meu select, basta que eu faça um casting deste blob.
SELECT CAST(LPAD(COUNT(1), 2, 0) AS CHAR(2));

Retorna => 01

como usar a função LPAD com à COUNT?


event.target.blur() not working

Question: I have a series of Bootstrap buttons like this:
<button :disabled="page === lastPage" type="button" class="btn btn-default" @click="getPage(lastPage)">

</button>

But the first line of the getPage method does not work:
event.target.blur();

Which is very strange, because I have another button in another component, on which event.taget.blur() works perfectly:
<button class="btn btn-default pull-right" @click="show()" type="button">Batch

</button>

Does anyone know why this might be?
EDIT: I think it's when I click inside the SPAN that the blur doesn't work.
EDIT: oh well I solved it - I also need event.target.parentNode.blur() as well.
Comment: If you solved it, write an official answer and mark it as such.  It will give more clarity to those with similar issues and you'll score some points for it.  :)
Answer: You likely want to use
event.currentTarget.blur()

That will always be the element you attached the event listener to where as event.target is the element the event originated from.
Comment: Simple answer and nice supplementary comment!
Answer: I would consider using
if (document.activeElement != document.body) {
    document.activeElement.blur()
}

rather than navigating through nodes as it is less prone to error if the mark up changes.
Answer: In this case, because the button contains a span, sometimes the user was clicking on the button itself, and sometimes on the span within. Hence, to reliably blur the button I needed:
event.target.blur();
event.target.parentNode.blur();

Comment: You likely want `event.currentTarget.blur()`, `currentTarget` is always the element with the listener added.
Comment: Added the answer.
Comment: @BillCriswell even better. If you want, add this as the answer and I will accept.
Comment: It works even two parents up `event.target.parentNode.parentNode.blur()`, nice!

event.target.blur() not working


PDF of sum of ordered weighted exponential RVs

Question: Let $X_{(1)}, X_{(2)}, ..., X_{(N)}$ be the order statistics of an iid exponential RVs with parameter $\lambda$, where $X_{(1)} \geq X_{(2)} \geq ...\geq X_{(N)}$. Any hints on how to find the PDF of
$\sum_{i = 1}^{M} \frac{X_{(i)}}{M}$?
where $M\leq N$.
P.S. the PDF of the $n$th order statistics $X_{(n)}, n = 1, ..., N$ is given as
${f_{{X_{(n)}}}}\left( {{x_n}} \right) = \frac{{N!\lambda }}{{\left( {n - 1} \right)!(N - n)!}}{e^{ - \lambda {x_n}\left( {1 + N - n} \right)}}{\left( {1 - {e^{ - \lambda {x_n}}}} \right)^{n - 1}}$
and the joint PDF of the first (best) $M$th order statistics ${{X_{(1)}},...,{X_{(M)}}}$ is
${f_{{X_{(1)}},...,{X_{(M)}}}}\left( {{x_1},...,{x_M}} \right) = \frac{\lambda ^M{N!}}{{(N - M)!}}{\left( {1 - {e^{ - \lambda {x_M}}}} \right)^{N - M}}\prod\limits_{j = 1}^M {{e^{ - \lambda {x_j}}}} $
Comment: Since neither numerator nor denominator in your sum changes with $i$, both terms can be taken out the front of the sum, and then the $M$ in the denominator will be cancelled by $\sum^M 1$. Please check your question says what you mean.
Comment: Just checking whether this is self study (e.g., homework)? In which case please add [self-study] tag so answers can be tailored appropriately.
Comment: @Glen_b I suspect the OP meant to write $X_{(i)}$ instead of $X_{(M)}$, but let's see how he responds.
Comment: @Alecos I hold a similar suspicion, but we can't tell for sure.
Comment: @Glen_b Sorry for the typo. The question reads correctly now.
Comment: @Alecos Sorry for the typo. The question reads correctly now.
Comment: another indication: you need the joint pdf of $X_{(1)},\ldots,X_{(M)}$ and not of $X_{(n)}$ by itself.
Comment: Can you post the PDF of the $n$th order statistic $X_{(n)}$? I normally approach addition problems using convolution integrals, and in some cases there is a closed form solution that allows you to construct an induction formula.
Comment: @tristan It is not a homework, i.e. a given question that I seek answer for. Do I still need to add [self-study]? Also, the question is updated with the PDF of the $n$th order statistics and as you can see they are dependent.
Comment: @Xi'an Yes, I want to divide by $M$ not $i$. Also, I updated the question with the joint PDF of ${{X_{(1)}},...,{X_{(M)}}}$.
Comment: The expression for the joint PDF lacks the critical information that $0 \le x_1 \le x_2 \le \cdots \le x_M $; for all other possible values, the PDF is zero.
Comment: @whuber actually the assumption here is that $X_{(1)} \geq X_{(2)} \geq ... X_{(N)}$. The question is updated to be more clear
Comment: @Noor you don't have to add self-study if it's not homework, it just looked homework-y and you asked for hints. Good edits, I'll hopefully take a look later this evening.
Comment: My ordering was a hint at a simpler way to solve the problem.
Comment: Will have to wait till the morning. Taking me longer to work out than I thought!
Answer: Apologies: The following answer is not complete and may contain inaccuracies (although I have tried to identify potential problem areas). I do not have time due to work commitments to see this through to the end but thought given the amount I have already done it would be foolish not to post it in case it is of some help. Best of luck solving this, hopefully @whuber has something up his sleeve.

Here is how I would attempt to solve the problem:
As pointed out, the $X_{(i)}$ are not independent, since they must be ordered, so a simple convolution does not work. We will work with your ordering and hopefully @whuber will point out how much simpler it is with the alternative ordering and how to apply the results from one ordering to the other.
We must therefore calculate the PDF of $Y = \frac{1}{M}\sum_{i=1}^{M}{X_{(i)}}$ by first considering the CDF of $Y$:
$$
F_Y(y)=\Pr(Y\le y)=\int_0^\infty{\cdots\int_0^\infty{f_{X_{(1)},\ldots,X_{(M)}}(x_{(1)},\ldots,x_{(M)})I(x_{(1)}+x_{(2)}+\ldots+x_{(M)}\le yM)dx_{(1)}}\ldots dx_{(M)}}
$$
Where $I(\cdot)$ is an indicator function taking the value $1$ if the inequality holds and $0$ otherwise.
For now I think it is acceptable to integrate only over $x_{(1)}$ to $x_{(M)}$ but it may ultimately be necessary to integrate over all $N$.
Now $f_{X_{(1)},\ldots,X_{(M)}}(x_{(1)},\ldots,x_{(M)})$ is the formula you give above or zero if the $x_{(i)}$ are not ordered. To avoid making separate case statements we add another indicator function:
$$
F_Y(y)=\int_0^\infty{\cdots\int_0^\infty{f_{X_{(1)},\ldots,X_{(M)}}(x_{(1)},\ldots,x_{(M)})I\left(\sum_{i=1}^M{x_{(i)}}\le yM\right)I(x_{(1)}\ge x_{(2)}\ge \ldots \ge x_{(M)})dx_{(1)}}\ldots dx_{(M)}}
$$
Now we work on adjusting the integral limits in such a way to exclude the values of $x_{(i)}$ for which the indicator functions give $0$. Firstly we take the indicator function for the ordering. It will take the value $0$ if $x_{(1)}<x_{(2)}$ so we adjust the integral limits for $x_{(1)}$ to be $(x_{(2)},\infty)$. Likewise the limits for $x_{(2)}$ become $(x_{(3)},\infty)$ and so on. The limits for $x_{(M)}$ are a tricky one because if $M<N$ then a lower limit of $0$ is clearly problematic. I'll park this issue for now if you don't mind!
The other indicator function will set our upper limits. For $x_{(i)}, i=1,\ldots,M-1$ we have the inequality $x_{(i)} \le yM - \sum_{j=i+1}^M{x_{(j)}}$ and for $x_{(M)}$ the upper limit is simply $yM$. In fact, I think you can make it even simpler and use the inequality of $x_{(i)} \le yM - x_{(i+1)}$ and devolve the issue of maintaining the larger inequality "up the food chain" as it were.
Our final integral looks like this:
$$
F_Y(y)=\int_0^{yM}{\int_{x_{(M)}}^{yM-x_{(M)}}{\cdots\int_{x_{(2)}}^{yM-x_{(2)}}{f_{X_{(1)},\ldots,X_{(M)}}(x_{(1)},\ldots,x_{(M)})dx_{(1)}}\ldots dx_{(M-1)}}dx_{(M)}}
$$
Now consider that many of the terms in $f_{X_{(1)},\ldots,X_{(M)}}(x_{(1)},\ldots,x_{(M)})$ can actually be pulled out of the integral or at least distributed in such a way to make it less scary:
$$
F_Y(y)=\frac{\lambda^M N!}{(N-M)!}\int_0^{yM}{(1-e^{-\lambda x_{(M)}})^{N-M}e^{-\lambda x_{(M)}}\int_{x_{(M)}}^{yM-x_{(M)}}{e^{-\lambda x_{(M-1)}}\cdots\int_{x_{(2)}}^{yM-x_{(2)}}{e^{-\lambda x_{(1)}} dx_{(1)}}\ldots dx_{(M-1)}}dx_{(M)}}
$$
(You may want to check whether the limits on the product might actually be $i=1,\ldots,M-1$ and I have assumed you mean $x_{(i)}$ instead of $x_i$ throughout).
The first integral is solved as follows:
$$
\int_{x_{(2)}}^{yM-x_{(2)}}{e^{-\lambda x_{(1)}} dx_{(1)}} = \left[-\frac{e^{-\lambda x_{(1)}}}{\lambda}\right]_{x_{(2)}}^{yM-x_{(2)}} = \frac{e^{-\lambda x_{(2)}}-e^{-\lambda (yM-x_{(2)})}}{\lambda}
$$
Leaving us with:
$$
F_Y(y)=\frac{\lambda^M N!}{(N-M)!}\int_0^{yM}{(1-e^{-\lambda x_{(M)}})^{N-M}e^{-\lambda x_{(M)}}\int_{x_{(M)}}^{yM-x_{(M)}}{e^{-\lambda x_{(M-1)}}\cdots \int_{x_{(3)}}^{yM-x_{(3)}}{e^{-\lambda x_{(2)}}\frac{e^{-\lambda x_{(2)}}-e^{-\lambda (yM-x_{(2)})}}{\lambda}dx_{(2)}}\ldots dx_{(M-1)}}dx_{(M)}}
$$
We can then simplify the innermost integrand:
$$
e^{-\lambda x_{(2)}}\frac{e^{-\lambda x_{(2)}}-e^{-\lambda (yM-x_{(2)})}}{\lambda} = \frac{e^{-2\lambda x_{(2)}}-e^{-\lambda yM}}{\lambda}
$$
This integral can also be solved explicitly and so on.
As I said above, sorry the answer is not complete. Hopefully after doing a couple of further integrations you could use induction to finish the job.
Comment: Thanks @tristan so much for your help and your time. It is appreciated. I will build on what you have started and I will report the answer here when I am done.


Construction of derivative for a mixer

Question: I have two streams, $S_1$ and $S_2$, mixing together into one outlet stream $S_3$.  The flow rate of $S_1$ is $Q_1$, $S_2$ is $Q_2=kQ_1$, mixing into $S_3$ with flow rate $Q_3$.  Each stream has a property $G$ which mixes linearly with $Q$.  $G_1$ is a function of $Q_1$ and $G_2$ is a function of $Q_2$.  I am trying to find $\frac{dG_3}{dQ_3}$ as a function of $\frac{dG_1}{dQ_1}$ and $\frac{dG_2}{dQ_2}$.
Here is one approach I have tried:
$Q_3 = Q_1+Q_2 = Q_1(1+k)$
$G_3 = \frac{G_1Q_1+G_2Q_2}{Q_1+Q_2} = \frac{G_1+kG_2}{1+k}$
$\frac{dG_3}{dQ_3} = \frac{dG_3}{dQ_1}\frac{dQ_1}{dQ_3}$
$ = \left(\frac1{1+k}\frac{dG_1}{dQ_1}+\frac{k}{1+k}\frac{dG_2}{dQ_1}\right) \left(\frac1{1+k}\right)$
$ = \left(\frac1{1+k}\frac{dG_1}{dQ_1}+\frac{k^2}{1+k}\frac{dG_2}{dQ_2}\right) \left(\frac1{1+k}\right)$
$ = \frac1{(1+k)^2}\left(\frac{dG_1}{dQ_1}+k^2\frac{dG_2}{dQ_2}\right)$
This would be fine, except that there is one major issue it does not encapsulate:
If $G_1$ and $G_2$ are constant, the above formula gives $\frac{dG_3}{dQ_3} = 0$.  But this is not true as if I mix $S_1$ and $S_2$ in different proportions I get a different $G_3$, $\frac{dG_3}{dQ_3}$ is non-zero. Also I expect if $k=0$ (only $S_1$ feeds $S_3$), then $\frac{dG_3}{dQ_3}$ should be $0$, and also should be $0$ when only $S_2$ feeds $S_3$ (ie. $Q_1=0$).  But between those two extremes $\frac{dG_3}{dQ_3}$ should be non-zero.
So somehow I have to build in the perturbation of $k$ into this formulation to get the correct formula for $\frac{dG_3}{dQ_3}$.
Answer: This reminds me of similar problems I did in Differential Equations, and from looking at your math, it seems correct.
As for the issues you bring up, in the case of:

"If $G_1$ and $G_2$ are constant, the above formula gives $\frac{dG_3}{dQ_3} =0$... If I mix $S_1$ and $S_2$ in different proportions I get a different $G_3$, $\frac{dG_3}{dQ_3}$ is non-zero."

Both of these statements being simultaneously true is not a contradiction. If $G_1$ and $G_2$ are constants, the derivative will be zero, but unless the streams stop all together, $G_1$ and $G_2$ cannot be constants, since they rely on the flow rate.
The second statement is mostly true, but I think potentially you're getting the meaning of proportion and flow rate mixed up. $S_1$ and $S_2$ are being mixed at all, implies that both streams must have some flow rate (ie $Q_1\neq 0$ and $Q_2\neq 0$).Thus, the only time $\frac{dG_3}{dQ_3} =0$ is when at least one of the streams isn't flowing at all.
Also notice that when $k=0, \frac{dG_3}{dQ_3} = \frac{dG_1}{dQ_1}$, which doesn't necessarily mean $\frac{dG_3}{dQ_3} = 0$.
Your math above your paragraph all looks right to me. Hope this helps some.
Comment: Yes $G_1$ and $G_2$ are in general functions of $Q_1$ and $Q_2$ respectively, but I was just taking a special case where those functions are in fact constant as a special case to consider.  My formula for $\frac{dG_3}{dQ_3}$ must still be able to cater for this case, and so must be able to generate a non-zero value even when $\frac{dG_1}{dQ_1}$ and $\frac{dG_2}{dQ_2}$ are zero.  Also it must cater for the special extreme cases where either streams $S_1$ or $S_2$ do not exist ($k=0$ or $Q_1=0$)

Construction of derivative for a mixer


Get the identifier of a specific notification when it is tapped in the notification center or tapped when it first appears

Question: I am trying to use the userNotificationCenter(_:didReceive:withCompletionHandler:) method (in Swift 4) to handle when a notification is tapped by the user. However, I would like to know the identifier of the specific notification that was tapped, and I have not been able to find a way to do this. Any suggestions?
Comment: You can use UNNotificationResponse's  actionIdentifier property. In case you notification has only one action defined, this is fine, if it has more than one action you need to use the category in order to detect the valid identifier.
Answer: Turns out all I had to do was this:
<code>let identifier = response.notification.request.identifier
</code>
Thanks for the response though!


Expectation of $\mathbb{E}(Tr(X^T A X))$ and $Var(Tr(X^T A X))$?

Question: What is the expectation: $\mathbb{E}(Tr(X^T A X))$ and $Var(Tr(X^T A X))$
when $X_{i,j} \sim N(\mu, \sigma^2)$ and $X \in \mathbb{R}^{n \times k}$ where $n>k$  and $A$ is a given p.s.d matrix (not random)?
Answer: Since trace is linear,
$$[\text{Tr}(X^TAX)]=[\text{Tr}(AXX^T)]=\text{Tr}([AXX^T])=\text{Tr}(A[XX^T])$$
should help you towards the solution.
Comment: Thanks for the comment. Are there any expectation results for gram matrices formed through random matrix $X$? Would like to know of the variance term as well and onwards towards the solution.