XML Feed invalid in drupal 7

Question: Am trying to create xml feed through views feed generation to get the node content values. I have mapped the fields and i am getting the feed also, but a single space while generating feed in front of the xml feed. i.e before tag "<?xml" I am getting one single space. So that my feed page it's showing white space in Firefox and I can find the space in chrome browser. Is there config issue will be there or any thing else? Can anyone give me solution for this?
Comment: Could it be a space in a views related template, or a ?> in a custom module of yours?
Comment: Or a space at the beginning of the settings.php
Answer: I wrote a detailed description about this problem and a possible debugging solution here: https://drupal.org/node/1275042#comment-7814971
In my case, Views Slideshow was problematic, I just created a tiny patch for that:
https://drupal.org/node/2078689#comment-7815015

For convenience, I'm copying my post linked above:

As merlinofchaos said, this really has nothing to do with Views. The
  "fix" in #6 is NOT actually a fix...
In my case, I had two whitespaces in front of the <?xml tag, so the
  RSS feed started like this: "  <?xml". I never thought I will find the
  source of the problem with such an ugly solution, but this is quick
  and works - it's really dirty, so use it only on a local development
  copy, do NOT test it on a production site:
  https://drupal.org/node/175137#comment-1526410
  in includes/module.inc file, in the module_load_all() function, after the
  drupal_load('module', $module);, soyarma suggests you to put in the
  following line temporarily: print $module.'|'; This way you'll get a
  list of your modules in the beginning of the output separated by the
  pipe (|) character. When there are unnecessary whitespaces before the
  module's name and the pipe character, then you just found the buggy
  module.
For example, in my case, Views Slideshow was the source of the problem:
views_bulk_operations|views_content|  views_slideshow|views_slideshow_cycle (this is just the end of the huge list)
As you can see, there are two spaces before views_slideshow. This is
  where I should start searching for the source of the problem. I found
  it in views_slideshow/theme/views_slideshow.theme.inc: the code starts
  with two whitespaces, and the PHP block is just after that: "  <?php"
  You can also see it here:
http://drupalcode.org/project/views_slideshow.git/blob/d9fd60c20add43a7b...
And YESSS, after deleting the two spaces, http://validator.w3.org/
  congratulated me that my RSS feed is valid. Thank you, soyarma!
Don't forget to revert the changes in module.inc (don't ever hurt the
  core's code! :) ), and delete the print $module.'|'; line.
I'll report an issue to the Views Slideshow's queue, and I hope that
  this helped someone.
====
  EDIT:
  I reported the bug to the issue queue, and also created a patch, see #2078689: Unnecessary two whitespaces before the PHP code
  block in views_slideshow.theme.inc, which can cause RSS feeds to get
  invalid.

XML Feed invalid in drupal 7


Steinitz exchange lemma - basis

Question: I've read on the internet this definition of Steinitz exchange lemma:

Steinitz exchange lemma
Let $S = \{v_1, \ldots , v_m\}$ satisfy $\mathrm{Span}(S) = V$ and let $T = \{w_1, \ldots , w_k\}$ be linearly independent.
Then

$k \le m$ and
after possibly reordering the set $S$, we have
$\mathrm{Span}(\{w_1, \ldots , w_k, v_{k+1}, \ldots , v_m\}) = V$

However,my teacher gave us a slightly different definition: she said that $\{w_1,\ldots,w_k,v_{k+1},\ldots,v_m\}$ doesn't only span $V$, but is also a basis. Is that system really linearly independent or did she make a mistake?
Comment: What your teacher said is true if and only if $S$ is supposed to be a basis.
Answer: It is basically true, if $S$ is a basis:

Suppose $(v_1,\dots, v_i, \dots,v_n)$ is basis of $V$ and $w = \lambda_1 v_1 + \dots + \lambda_n v_n$, where some $\lambda_i \neq 0$. Then $(v_1,\dots, v_{i-1}, w,\dots, v_{i+1}, \dots, v_n)$ is a basis of $V$.

Of course you can use this fact again and again to "replace" multiple vectors, like so:

Suppose the set $B$ is a basis of $V$ and $A$ is a linearly independent subset of $V$. Then $|A|\leq |B|$ and there is a subset $B'$ of $B$, s.t. $B'\cup A$ is basis of $V$.

(I avoided listing the elements of $A$ and $B$, so that I not have to talk about "reordering" elements)

Steinitz exchange lemma - basis


Erro em tempo de execução '13'

Question: Estou criando uma macro para apagar  os valores da celula que contem #N/D, mas ele me da apresenta (Erro em tempo de execução '13')
Quando coloco #N/A o codigo funciona.
Alguem pode me ajudar a solucionar o problema?
 Private Sub CommandButton1_Click()
'percorre da linha 2 até a última preenchida em A
   For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
    'se em B for #N/D
    If Cells(i, 2) = "#N/D" Then
    'apaga conteúdo de A
    Cells(i, 2).ClearContents
    End If
  'próxima linha
 Next i

End Sub

Comment: Você pode formata o texto de sua pergunta para que possa ficar melhor de entender.
Comment: @DoutorStephenStrange ficou melhor ?
Comment: Ficou muito Show!!!
Comment: @DoutorStephenStrange  o excel nao aceita #N/D  como um valor, quando faço a execução do codigo ele me apresenta um erro chamado:
" Erro em tempo de execução '13' "
Mas se mudo o #N/D para qualquer outro texto exemplo #N/A ele aceita.
Comment: Velho é não entendo de vba mais, calma aguem vem te ajudar o, pt.stackoverflow.com tem muitas pessoa que podem fazer isso.
Answer: Você pode utilizar a função isNA()
Código
'percorre da linha 2 até a última preenchida em A
   For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
    'se em B for #N/D
    If WorksheetFunction.IsNA(Cells(i, 2)) Then
    'apaga conteúdo de A
    Cells(i, 1).ClearContents
    End If
  'próxima linha
 Next i

Erro
Este erro ocorre porque #N/D não é uma String, mas sim uma variável de erro. Por isso a função isNA() é usada. Porém, #N/D pode ser procurado com funções simples de procura de String, como o .Find
Outro modo
É realizado utilizando a função CVerr()
'percorre da linha 2 até a última preenchida em A
For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
    'se em B houver erro
    If IsError(Cells(i, 2)) Then
        'Se em B for #N/D
        If Cells(i, 2) = CVErr(xlErrNA) Then
            'apaga conteúdo de A
            Cells(i, 1).ClearContents
        End If
    End If
    'próxima linha
Next i

Erro em tempo de execução '13'


np.polyfit how to get lists into a 2D array for y input

Question: I generated latitude, longitude, and altitude data for a satellite orbit. Now, I want to do a polynomial fit for my data in order to interpolate. numpy.polyfit() will only take a 2D array for the y-coordinate that contains one dataset per column.
Right now longitude and altitude are in two separate lists and I need to combine them into a 2D array. I have tried np.matrix([lon] [alt]) but I get an error:
TypeError: list indices must be integers, not list
Inputs:
Lat: [-22.0, -50.5, -5.8, 45.2, 32.7]

Lon: [-66.6, 21.3, 90.1, 147.4, -115.7]

Alt: [368752.8, 371184.4, 357834.7, 375131.8, 375643.8]

Desired Output:
lonAlt_2D_array = ([-66.6, 21.3, 90.1, 147.4, -115.7] [368752.8, 371184.4, 357834.7, 375131.8, 375643.8])

fit = np.polyfit(lat, lonAlt_2D_array, 2)    #not sure if 2 is correct degree

Full Code:
'''
Satellite Orbit Propagation Function
'''

def orbitPropandcoordTrans(propNum, orbitPineapple_J2000time, _ecc, _inc, _raan, _arg_pe, _meananom, meanMotion):

        '''
        Create original orbit and run for 100 propagations (in total one whole orbit)
        in order to get xyz and time for each propagation step.
        The end goal is to plot the lat, lon, & alt data to see if it matches ISS groundtrace.
        '''
        import orbital
        from orbital import earth, KeplerianElements, plot
        import matplotlib.pyplot as plt
        import numpy as np
        from astropy import time
        from astropy.time import TimeDelta, Time
        from astropy import units as u
        from astropy import coordinates as coord

    'Calculate Avg. Period from Mean Motion'
    _avgPeriod = 86400 / meanMotion
    print('_avgPeriod', _avgPeriod)

    'Generate Orbit'
    orbitPineapple = KeplerianElements.with_period(_avgPeriod, body=earth, e=_ecc, i=(np.deg2rad(_inc)), raan=(np.deg2rad(_raan)), arg_pe=(np.deg2rad(_arg_pe)), M0=(np.deg2rad(_meananom))) #ref_epoch=
    plot(orbitPineapple)
    plt.show()

    'Propagate Orbit and retrieve xyz'
    myOrbitX = []         #X Coordinate for propagated orbit step
    myOrbitY = []         #Y Coordinate for propagated orbit step
    myOrbitZ = []         #Z Coordinate for propagated orbit step
    myOrbitTime = []      #Time for each propagated orbit step
    #propNum = 100        #Number of propagations and Mean Anomaly size (one orbit 2pi/propNum)

    for i in range(propNum):
        orbitPineapple.propagate_anomaly_by(M=(2.0*np.pi/propNum)) #Propagate the orbit by the Mean Anomaly
        myOrbitX.append(orbitPineapple.r.x)                        #x vals
        myOrbitY.append(orbitPineapple.r.y)                        #y vals
        myOrbitZ.append(orbitPineapple.r.z)                        #z vals
        myOrbitTime.append(orbitPineapple_J2000time)               #J2000 time vals
        #myOrbitJ2000Time.append(orbitPineapple.t)
        #plot(orbitPineapple)

    'Getting the correct J2000 Time'
    times = [orbitPineapple_J2000time] * propNum
    #print('times',times)
    #print('')

    myOrbitJ2000Time = [] #J2000 times
    for i in range(propNum):
        myOrbitJ2000Time.append(times[i] + i)

    '''Because the myOrbitTime is only the time between each step to be the sum of itself plus
    all the previous times. And then I need to convert that time from seconds after J2000 to UTC.'''
    myT = [] #UTC time list

    for i in range(propNum):
        myT.append((Time(2000, format='jyear') + TimeDelta(myOrbitTime[i]*u.s)).iso) #Convert time from J2000 to UTC
    #print('UTC Time List Length:', len(myT))
    #print('UTC Times:', myT)

    '''Now I have xyz and time for each propagation step and need to convert the coordinates from
    ECI to Lat, Lon, & Alt'''
    #now = []     #UTC time at each propagation step
    xyz =[]      #Xyz coordinates from OrbitalPy initial orbit propagation
    cartrep = [] #Cartesian Representation
    gcrs = []    #Geocentric Celestial Reference System/Geocentric Equatorial Inertial, the default coord system of OrbitalPy
    itrs =[]     #International Terrestrial Reference System coordinates
    lat = []     #Longitude of the location, for the default ellipsoid
    lon = []     #Longitude of the location, for the default ellipsoid
    alt = []     #Height of the location, for the default ellipsoid

    for i in range(propNum):
        xyz = (myOrbitX[i], myOrbitY[i], myOrbitZ[i])                   #Xyz coord for each prop. step
        #now = time.Time(myT[i])                                         #UTC time at each propagation step
        cartrep = coord.CartesianRepresentation(*xyz, unit=u.m)         #Add units of [m] to xyz
        gcrs = coord.GCRS(cartrep, obstime=time.Time(myT[i]))           #Let AstroPy know xyz is in GCRS
        itrs = gcrs.transform_to(coord.ITRS(obstime=time.Time(myT[i]))) #Convert GCRS to ITRS
        loc = coord.EarthLocation(*itrs.cartesian.xyz)                  #Get lat/lon/height from ITRS
        lat.append(loc.lat.value)                                       #Create latitude list
        lon.append(loc.lon.value)                                       #Create longitude list
        alt.append(loc.height.value)

    print('Lat:')
    print(lat)
    print('Lon:')
    print(lon)
    print('Alt:')
    print(alt)

    lonAlt_2D_array = np.matrix([lon] [alt])

    fit = np.polyfit(lat, lonAlt_2D_array, 2)

orbitPropandcoordTrans(5, 20027712.00, 0.000939, 51.5777, 172.5018, 323.1066, 173.4358, 15.68522506)
Comment: `np.array([Lat, Lon])`
Comment: That does work to convert the lists into an array. However, I am now getting an error for np.polyfit() `TypeError: expected x and y to have same length` and `len(lonAlt_2D_array)` = 2 and shape = (2,5). Length needs to be 5 to match x (lat).
Answer: It turns  out lonAltMatrix = [list(a) for a in zip(lon, alt)] works to create a 5x2 matrix.
For np.polyfit() the number of rows for the y-coordinate must match the length of the x-coordinate.


Advice on using geolocation to determine which page to display

Question: I was looking for a little friendly advice on a project I'm working on.  It is built using PHP and HTML5.
I am working on an eCommerce site for stores that are located in Texas.  The company is thinking about offering different a different pricing structure to customers within Texas as opposed to those outside of Texas.
The way I have come up to do this is to use geolocation to get the users location and check it against the geographical center of Texas.  If the distance is less than 450 miles show one page, or, if the distance is greater, show another.  I know this would not be the exact border of the state, and I think that is OK.
The only problem I have come up with this idea so far is that a user could deny the location check.  How does it work on Google when you type in restaurants in the search and it gives you local places without asking for permission?
Do you guys have any other suggestions?  In the searching I have done, I haven't found any other ideas that seem to fit.
Thanks.
Answer: People who wish to do this generally use a GeoIP library which can tell you where the users IP is coming from.  Note that this does not tell you where the user is physically.  You can opt to use one of these too however you must know that anyone could be from TX if they were using a proxy based in TX.  You would have to have some strict checking on orders to make sure that people were not spoofing their location with a proxy and placing orders that would be shipped outside of TX.
What would happen if your customer resided inside TX borders but for some reason their ISP was routing them through a router in Oklahoma or New Mexico.  To your GeoIP it would look like they are from out of state.
The best solution (but not the best user experience) would be to ask a potential customer for their location.  If they provide a location use that, if they don't fall back to the GeoIP.  Always update the pricing for the product during checkout if you detect they are from out of state but provide an in-state address.  Chances are they are from TX but the GeoIP does not think they are.
MaxMind - http://www.maxmind.com/en/geolocation_landing
These guys offer both a free and paid solution.  I have used both and can tell you that the paid solution is well worth the cost vs the inaccuracies you will get when using the free version.


how to change the ftp passive mode ip address for haproxy work as reserve proxy?

Question: I have an ftp server in LAN, address is 192.168.1.11
I used haproxy is because lots of other service need it
I put haproxy on my 192.168.1.1 the same machine of our soft-route(ubuntu 14.04)
My haproxy config is:
frontend ao3-ftp
bind ftp.ao3.com.au:21
bind ftp.ao3.com.au:20
bind ftp.ao3.com.au:5000-5100
default_backend myftp

 backend myftp
server server1 192.168.1.11

when the client use the ftp service they find the problem of the iternal ip address can not connected:
Status: Connected, waiting for welcome message...
Reply: 220-FileZilla Server version 0.9.41 beta
Reply: 220 Hi welcome to Ao3 ftp Server
Reply: 200 Don't care
Command: USER ingram
Reply: 331 Password required for ingram
Command: PASS ***********
Reply: 230 Logged on
Command: SYST
Reply: 215 UNIX emulated by FileZilla
Command: FEAT
Reply: 211-Features:
Reply: MDTM
Reply: REST STREAM
Reply: SIZE
Reply: MLST type*;size*;modify*
Reply: MLSD
Reply: UTF8
Reply: CLNT
Reply: MFMT
Reply: 211 End
Command: PWD
Reply: 257 "/" is current directory.
Status: Current path is /
Command: TYPE I
Reply: 200 Type set to I
Command: PASV
Reply: 227 Entering Passive Mode (192,168,1,11,19,144) ---here the problem
Error: Server returned unroutable private IP address in PASV reply

You can see the ip address is still my internal web ip address, so the the outside company client can not tranfer the data since it can not find this ip address. Does haproxy supply some way to change their interal ip address to outside ip address? Does iptables can do it?
Answer: Simply have the FileZilla FTP server announce the correct external ip-address used by HA-proxy, which is something you can configure in Options --> Passive Mode Settings
Normally the Linux kernel uses helper modules that scan the clear text FTP command channel for the PASV response to dynamically change that to the correct NAT response and/or to dynamically open the related network port in iptables, but I don't know if HA-proxy has such a FTP protocol helper.


Can RAID be accidentally configured twice?

Question: I am renting a server from Hetzner, which had 2x 8TB disks. I believe they were listed as RAID 1 (though can't find anything to confirm that anymore), which I would have assumed would have given me 16 TB usable space as RAID 1. I then ran this script, which sets up RAID and logical volumes.
The end result, however, is a single (logical) disk of ~ 8TB. Could it be that RAID 1 mirroring is being done twice? If so, how would I confirm this hypothesis?
Here is lsblk:
lsblk
NAME            MAJ:MIN RM  SIZE RO TYPE  MOUNTPOINTS
sda               8:0    0  7.3T  0 disk
├─sda1            8:1    0    1M  0 part
└─sda2            8:2    0  7.3T  0 part
  └─md127         9:127  0  7.3T  0 raid1
    └─vg0-root0 254:0    0  6.9T  0 lvm   /nix/store
                                          /
sdb               8:16   0  7.3T  0 disk
├─sdb1            8:17   0    1M  0 part
└─sdb2            8:18   0  7.3T  0 part
  └─md127         9:127  0  7.3T  0 raid1
    └─vg0-root0 254:0    0  6.9T  0 lvm   /nix/store
                                          /

fdisk -l:
fdisk -l
Disk /dev/sdb: 7.28 TiB, 8001563222016 bytes, 15628053168 sectors
Disk model: HGST HUH721008AL
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: gpt
Disk identifier: 0D66DC9A-41E1-44B0-AF57-EDF422A7B4C4

Device     Start         End     Sectors  Size Type
/dev/sdb1   2048        4095        2048    1M BIOS boot
/dev/sdb2   4096 15628052479 15628048384  7.3T Linux filesystem

Disk /dev/sda: 7.28 TiB, 8001563222016 bytes, 15628053168 sectors
Disk model: HGST HUH721008AL
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: gpt
Disk identifier: 1FE75135-DDF0-4DF7-B79D-4890D594D12A

Device     Start         End     Sectors  Size Type
/dev/sda1   2048        4095        2048    1M BIOS boot
/dev/sda2   4096 15628052479 15628048384  7.3T Linux filesystem

Disk /dev/md127: 7.28 TiB, 8001425506304 bytes, 15627784192 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/mapper/vg0-root0: 6.91 TiB, 7601349722112 bytes, 14846386176 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

df -h:
df -h
Filesystem                Size      Used Available Use% Mounted on
devtmpfs                  6.3G      4.0K      6.3G   0% /dev
tmpfs                    62.9G     16.0K     62.9G   0% /dev/shm
tmpfs                    31.4G      6.1M     31.4G   0% /run
tmpfs                    62.9G    456.0K     62.9G   0% /run/wrappers
/dev/disk/by-uuid/fa8731e9-00e6-44fa-aa0f-f86ce2a1ca03
                          6.9T      1.6T      5.0T  24% /
/dev/disk/by-uuid/fa8731e9-00e6-44fa-aa0f-f86ce2a1ca03
                          6.9T      1.6T      5.0T  24% /nix/store
tmpfs                    12.6G     12.0K     12.6G   0% /run/user/0
tmpfs                    12.6G         0     12.6G   0% /run/user/1005

And udevadm info --query=all --name=/dev/sda
Comment: You made an incorrect assumption. Raid 1 is mirroring and two 8 TB disks mirrored will result in 8 TB of useable space, not 16 TB. (All data is duplicated and stored twice.) - To get 16TB of useable space out of two 8 TB disks you need raid level zero , striping
Answer: Raid 1 = Mirror so 8TB usbale space with 2x 8TB Drives.
What you want is Raid Level 0, which is striping, giving you the 16TB of both drives as one logical device.


How do I disable the taxonomy term page?

Question: I would like to disable the taxonomy/term/1 page that list the nodes using that taxonomy term. I have found some modules for older Drupal versions, but I haven't found quite what I'm looking for in Drupal 8.
Is there a configuration setting I am missing? Can I use a hook to disable the taxonomy term page, or does this require a module?
Comment: only for one term or for all the vocabulary?
Comment: All terms in a vocabulary - and all terms period. We don't want to enable exploring the site via Taxonomy Term pages.
Comment: in this case check my answer and you will find your solution.
Answer: A lightweight solution is to simply edit the taxonomy term view :
/admin/structure/views/view/taxonomy_term
... and restrict the access.
Comment: Why not disabling this view all together?
Comment: it is the best solution. you saved me a lot of time and energy. thanks.
Comment: Simple and easy without needing to install anything. This should be the selected answer!!!
Comment: When you use this solution, and you make use of the taxonomy menu module (drupal/taxonomy_menu), there will be no menu items in the menu.
Answer: The Rabbit Hole module can help you in this task

Rabbit Hole is a module that adds the ability to control what should
  happen when an entity is being viewed at its own page.

You need to enable the Rabbit Hole and Rabbit Hole taxonomy submodule and then in the admin/structure/taxonomy/manage/YOUR_VOCABULARY page you will see the Rabbit Hole Options.
Comment: it doesn't help in this issue! I just want to prevent drupal from listing nodes in taxonomy page.
Comment: @shekoufeh your problem is different from the problem asked in the question.
Answer:
Add a Content revision: ID filter. Set the operator to Is equal to, and input -1
Click Add in the No results behavior options box and add Response status code
Select 404 (Not Found) as the status code to return and add it
Save the view

Step 1 adds a filter that will always fail, because revision ids are positive integers, thus never equal -1. This will make the query always return with no results.
Steps 2 and 3 make Drupal return a proper 404 HTTP code when no results are returned from the query.


Why was this change of variables made in this system of differential equations?

Question: I'm trying to understand an example from my notes. I'm given a system of linear differential equations as follows
$$x'=2x-y$$
$$y'=2x-2$$
The notes solve these by making the change of variables $$u=x-1$$$$v=y-2$$ to give
$$u'=2u-v$$
$$v'=2u$$
and this then gives a system of the form $y'=Ay$ which is solveable with the methods given. My question is: how do you know to make this particular choice of variables to change to? I don't see the logical jump in making $u=x-1$ and $v=y-2$. What am I missing?
Comment: $x=x(t)$, $y=y(t)$ (pretty clear from the context).
Comment: The equilibrium point (where the right-hand sides are both zero) is $(x,y)=(1,2)$, and the change of variables moves the equilibrium to the the origin of the coordinate system: $(u,v)=(0,0)$.
Comment: What is $x'$? $y'$ is $dy/dx$ clearly. What about $x'$. It is a little unclear?
Comment: Are $x$ and $y$ functions of another variable ? Please, clarify.
Answer: If you look at the second equation, you see that there is an opportunity to get rid of the constant.
That can always be helpful to simplify a DEQ.
If we made $x=u+1$, we have for the second equation:
$$2(u+1) - 2 = 2u.$$
Hence $u = x - 1$. However, now that we did that, it creates a new constant that we would like to remove in the first equation as:
$$2(u + 1) - y = 2u -y + 2$$
What can be done to get rid of the $2$ term?
What if we wrote:
$$ 2u -(v+2) + 2 \implies y = v+2 \implies v = y - 2$$
Also, from the substitutions themselves, we have $u' = x', v' = y'$ and our new system becomes:
$$u'=2u-v \\ v'=2u$$
By the way, it is interesting to note that if you look at the phase portraits, this was shifting the critical point of the original system $(x , y) = (1,2)$ to $(u, v) = (0,0)$. Notice that the phase portraits are identical in both cases (see the following pre and post phase portraits):

It is now easier to solve the shifted system and then to shift those answers using the original transformations. We have:
$$u(t) = c_1 e^t (\sin t+\cos t)-c_2 e^t \sin t \\ v(t) = 2 c_1 e^t \sin t + c_2 e^t (\cos t- \sin t)$$
Using the shift transformations ($u = x - 1, v = y - 2$) for the original system, we have:
$$x(t) = c_1 e^t (\sin t+\cos t) -c_2 e^t \sin t+1 \\ y(t) = 2 c_1 e^t \sin t+ c_2 e^t (\cos t-\sin t) + 2$$
Comment: To the rescue, Amzoti!


MySql - Inserir vários produtos em um pedido

Question: Tenho uma tabela de pedido no mysql, onde nela deve ser informado o valor total do pedido, a data, id do cliente, e os produtos que foram comprados. O problema que esses produtos é da tabela produto. Gostaria de saber como faço para inserir esses vários produtos com o comando sql? Inserir apenas um produto eu sei de boas. Vou usar isso em uma aplicação Web C#, onde o cliente seleciona os produtos em um grid e confirma o pedido.
Comment: Olá @Vanderson, Seja bem-vindo ao StackOverflow-pt. Dê uma conferida neste link: http://pt.stackoverflow.com/help/how-to-ask. Tente incluir o máximo de informações possíveis em suas perguntas. Nesse caso, talvez detalhar a forma que o seu banco de dados foi mapeado.
Answer: Vanderson, suponhamos que essa seja sua tabela compras com as seguintes colunas:
id, total_pedido, data, id_cliente

Você teria que ter uma tabela pedido_detalhes que tivesse as seguintes colunas:
idproduto, idcompra

Sendo assim, sempre que fosse inserido uma "compra", ela iria gerar um ID que seria salvo junto a todos os produtos comprados na tabela pedido_detalhes.
Comment: Entendi amigo, vlw mesmo pela ajuda.
Comment: Amigo teria como mostrar como ficaria o código sql para essa inserção ? Pq fazer a inserção simples eu consigo de boas: insert into pedido (valorPedido, dataPedido, id_cliente) values (2000, '2016-02-23 00:00:00', 1). Mas como ficaria esse sql para funcionar com a tabela pedido_detalhes?


CHECK: Let $p$ be a prime number and let a $\in \mathbb{Z}$. Show that $p\mid a^p+a(p-1)!$

Question: Let $p$ be a prime number and let $a \in\mathbb{Z}$. Show that $p\mid a^p+a(p-1)!$.
$p\mid a^p+a(p-1)!$ if $p\mid a^p$ and $p\mid a(p-1)!$.
$\gcd(p,(p-1)!)=1$ $\implies$ $ p \nmid (p-1)!$ so $p\mid a$ $\implies$ $p\mid a^p$
Hence, $p\mid a^p+a(p-1)!$.
Is this correct?
Comment: No. It's Fermat meets Wilson.
Comment: It is not correct. Certainly if $p$ divides $a$, then $p$ divides your sum. But you are asked to show that $p$ divides your sum for **all** $a$.
Answer: First of all your assumption about if $p | A+B$, then $p|A$ and $p|B$ is incorrect. For example, with $p=7$ we have $7|(4+3)$ but it doesn't divide $4$ and $3$.
You need to use two results: Fermat's little theorem and Wilson's theorem.
Fermat says: For $a \in \mathbb{Z}$, we have $a^p \equiv a \pmod{p}$.
Wilson says: For prime $p$, $(p-1)! \equiv -1 \pmod{p}$.
Both are standard results. Using them we get
\begin{align*}
a^p+a(p-1)! & \equiv a+a(-1) \pmod{p}\\
& \equiv 0 \pmod{p}.
\end{align*}


Config React Router v6.14

Question: I have problem about config React-Router v6.14 is how to get param from url to component. I had tried  reading React-router documentation about createBrowserRouter and useParams but I didn't understood and how to set up it. I had tried set up via code in this. Is this possible to do this?
import { createBrowserRouter, useParams } from "react-router-dom";
import DefaultLayout from "../layout/DefaultLayout";
import FormAuth from "../pages/auth/Auth";
import NotFound404 from "../pages/notfound404/NotFound404";

const GetParam: any = () => {
  let { authPath } = useParams<string>();
  return authPath;
};

export const router = createBrowserRouter([
  {
    path: "/",
    element: <DefaultLayout />,
  },
  {
    path: "/:authPath",
    element: <FormAuth name={GetParam()} />,
  },
  {
    path: "*",
    element: <NotFound404 />,
  },
]);

Answer: The useParams hook, like all React hooks, can only be called from React functions and custom React hooks. You have a couple options available to you.

The FormAuth component should use useParams directly to access the authPath route path parameter.
const FormAuth = () => {
  const { authPath } = useParams();
  const name = authPath;

  ...
};

Create a wrapper component that can read the authPath route parameter and pass that value as the name prop to FormAuth.
const FormauthWrapper = () => {
  const { authPath } = useParams();
  return <FormAuth name={authParam} />;
};

export const router = createBrowserRouter([
  {
    path: "/",
    element: <DefaultLayout />,
  },
  {
    path: "/:authPath",
    element: <FormAuthWrapper />,
  },
  {
    path: "*",
    element: <NotFound404 />,
  },
]);

Answer: You are almost there, You have to use useParams on the given route, in your case, in FormAuth.
When you redirect "/anypath" the component will call useParams and get the params.
Answer: I suggest you just render the FormAuth element on the given path (you don't need to have an additional function in your routes file) and in the component, you can get the parameter using the useParams hook. In your case you can use it like this:
const { authPath } = useParams();

authPath will be either undefined (if no value is provided) or the value itself.

Config React Router v6.14


Proof verification: $\forall \epsilon\in\Bbb{Q^{+}}\exists x\in\Bbb{Q^{+}}(x^2<2<(x+\epsilon)^2)$

Question: Proof: (by contradiction) Suppose $\lnot(\forall \epsilon\in\Bbb{Q^{+}}\exists x\in\Bbb{Q^{+}}(x^2<2 \land 2<(x+\epsilon)^2))$, which is equivalent to the following propositions:
\begin{align}
&\Longleftrightarrow \exists\epsilon\in \Bbb{Q^+}(\lnot\exists x\in\Bbb{Q^+}(x^2<2 \land 2<(x+\epsilon)^2))\\
&\Longleftrightarrow \exists\epsilon\in\Bbb{Q^+}\forall x\in\Bbb{Q^+}(x^2\geq2\lor 2\geq (x+\epsilon)^2)\\
&\Longleftrightarrow \exists\epsilon\in\Bbb{Q^+}\forall x\in\Bbb{Q^+}(x^2<2\Rightarrow 2\geq (x+\epsilon)^2)\\
&\Longleftrightarrow \exists\epsilon\in\Bbb{Q^+}\forall x\in\Bbb{Q^+}(x^2<2\Rightarrow 2> (x+\epsilon)^2), &\text{Since $\lnot\exists q\in\Bbb{Q^+}, q^2=2$.}
\end{align}
We compute for $x$, to examine the inequality $(x+\epsilon)^2<2$ such that $x^2<2$, closer. Note that the inequality $(x+\epsilon)^2<2$ $\Longleftrightarrow$ $(x+\epsilon)^{2}-2<0$ is satisfied if and only if $\vert\epsilon^{2}+2\epsilon\vert <\vert x^{2}-2\vert$. By property of absolute values, we have
\begin{align}
-(x^2-2)<\epsilon^2 +2\epsilon<x^2-2\\
-(x^2-2<\epsilon^2+2\epsilon)\qquad \land\qquad \epsilon^2+2\epsilon<x^2-2\\
x^2-2>\epsilon^2+2\epsilon\qquad \land\qquad\epsilon^2+2\epsilon+2<x\\
x^2>\epsilon^2+2\epsilon+2\qquad \land\qquad x^2>\epsilon^2+2\epsilon+2\\
x>\sqrt{\epsilon^2+2\epsilon+2}
\end{align}
But $x,\epsilon\in\Bbb{Q^+}$ implies that $\epsilon^2+2\epsilon+2>2\Longrightarrow \sqrt{\epsilon^2+2\epsilon+2}>\sqrt{2}$. Thus, by transitivity of order in $\Bbb{Q}$, $\sqrt{2}<\sqrt{\epsilon^2+2\epsilon+2}<x$. Therefore, a contradiction.
Comment: Quite a few useful techniques may be found here https://math.stackexchange.com/questions/2069310/need-help-with-proof-for-dedekind-cuts-on-mathbbq/
Answer: Your proof looks fine.
I would have done it as follows. If $n\in\mathbb N$,$$\left\lfloor2^n\sqrt2\right\rfloor<2^n\sqrt2<\left\lfloor2^n\sqrt2\right\rfloor+1$$and therefore$$\frac{\left\lfloor2^n\sqrt2\right\rfloor}{2^n}<\sqrt2<\frac{\left\lfloor2^n\sqrt2\right\rfloor}{2^n}+2^{-n}.$$So, given $\varepsilon\in\mathbb{Q}^+$, I would choose $n\in\mathbb N$ such that $2^{-n}<\varepsilon$ and choose $x=2^{-n}\left\lfloor2^n\sqrt2\right\rfloor$.
Comment: @TheLastCipher What you were trying to prove was that we can always find rational numbes $x$ and $y$ such that $x<\sqrt2<y$ and that $x$ and $y$ are arbitrarily close. So, I condered the sequences of rational numbers$$\left(\frac{\left\lfloor2^n\sqrt2\right\rfloor}{2^n}\right)_{n\in\mathbb N}\text{ and }\left(\frac{\left\lfloor2^n\sqrt2\right\rfloor}{2^n}+2^{-n}\right)_{n\in\mathbb N},$$both of which converge to $\sqrt2$, one from below and the other one from above.
Comment: cool proof! thank you! Can you teach me how I could possibly arrive at a proof like yours, independently? Like the general strategy you used.
Comment: thank you again! :)


Android custom ListView item with two buttons and TextView

Question: I have a ListView with elements like this:
ListView item
This is my component tree:
Component Tree
I will change those two buttons with images, but how I could make that TextView would fill whole width? Because now it has a width specified in dp.
Comment: put your code here please
Comment: please post your code here
Comment: why would you place textView in seperate linearLayout????
Comment: `how I could make that TextView would fill whole width?` Ever heard of `match_parent`?
Comment: @Lukenzo use weight for that
Comment: add "android:layout_weight=1"
Comment: @sree `match_parent` works also in RelativeLayouts.
Comment: @Lukenzo Please see my answer below.
Comment: @FerdousAhamed Thank you, works like a charm!
Answer: No need to use extra LinearLayout.
Try this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:background="#e0e0e0">

    <Button
        android:id="@+id/deleteEexerciseBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Delete"/>

    <Button
        android:id="@+id/editEexerciseBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/deleteEexerciseBtn"
        android:text="Edit"/>

    <TextView
        android:id="@+id/exerciseName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@id/editEexerciseBtn"
        android:layout_marginRight="8dp"
        android:layout_centerVertical="true"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="This is a Large text with fill width"
        android:textSize="14sp"
        android:textColor="#000000"/>

</RelativeLayout>

OUTPUT
Answer: You have to set android:width="match_parent" for your TextView.
However, you could also solve this with setting layout_weight attribute for each LinearLayout and it will split your views evenly according to your weight value.
Read here more: Layout weight
Another option is to use RelativeLayout only, where you have free-hands on designing and placing your views within one single Layout.
Answer:     <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_centerVertical="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="Text view"
        android:textSize="20sp" />
    <Button
        android:id="@+id/deleteBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="DELETE" />
    <Button
        android:id="@+id/editBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/deleteBtn"
        android:text="EDIT" />
</RelativeLayout>

Comment: **Try this one**


Jquery prependTo but after

Question: I need to prepend h1 to #columns but after #left_column, now it is before it. Here is the code:

Answer: .appendTo('#left_column') is the obvious suggestion, but will append before the column is closed (cheers Rory, in comments).
If you want it to go after the column, use .after('#left_column').
Comment: This is incorrect - it will place the `h1` inside the `#left_column` element, not after it.
Comment: Like this $('h1').appendTo('#left_column').after('#left_column'); ?
Comment: Ok, it is working, here is the result - $('h1').insertAfter('#left_column');

Jquery prependTo but after


How to pass the array from a method to another method using interface

Question: Quero criar um programa que use interfaces para criar uma classe vetor com nome e tamanho e tenha os métodos abaixo:
<>
+DefinirNomeTamanhoVetor
+PreencherVetorCriadoInformandoPosicaoValor
+OrdenarVetor
+ExibirVetor

Não consigo passar o vetor de um método para usando a interface.

Segue a classe do Vetor:
package aula06Cencapsulamentotreino;
import java.util.Arrays;
public class Vetor implements InterfaceControladora {
<code>private int posicaovetor = 0;
private int tamanhovetor = 0;
private String nomevetor = "";

/**
 * @return the nome
 */
public String getNome() {
    return nomevetor;
}

/**
 * @param nome the nome to set
 */
public void setNome(String nome) {
    this.nomevetor = nome;
}

/**
 * @param posicao
 * @param tamanho
 */
public Vetor(int posicao, int tamanho) {
    super();
    this.posicaovetor = posicao;
    this.tamanhovetor = tamanho;
    this.nomevetor = nomevetor;
}

/**
 * @return the posicao
 */
private int getPosicao() {
    return posicaovetor;
}

/**
 * @param posicao the posicao to set
 */
private void setPosicao(int posicao) {
    this.posicaovetor = posicao;
}

/**
 * @return the tamanho
 */
private int getTamanho() {
    return tamanhovetor;
}

/**
 * @param tamanho the tamanho to set
 */
private void setTamanho(int tamanho) {
    this.tamanhovetor = tamanho;
}

@Override
public void metodoDefinicaoVetor(String nomevetor, int tamanhovetor) {
    // TODO Auto-generated method stub
    setNome(nomevetor);
    setTamanho(tamanhovetor);
    int v[] = new int[getTamanho()];
    Arrays.fill(v, 0);
    System.out.println("Nome do vetor = " + getNome());
    // Impressão dos valores dentro da posição do vetor.
    for (int i = 0; i < v.length; i++) { //
        System.out.printf(" " + v[i]);
    }
    System.out.println("");
}

@Override
public void metodoPreencimentoVetor() {
    // TODO Auto-generated method stub

}

/*
 * @Override public void metodoOrdenacaoVetor() { // TODO Auto-generated method
 * stub int v[] = new int [getTamanho()]; Arrays.sort(v); }
 *
 * @Override public void metodoBuscarValorVetor() { // TODO Auto-generated
 * method stub
 *
 * }
 */
</code>
}
Não consigo passar o vetor metodoDefinicaoVetor para o metodoPreencimentoVetor

Como posso fazer isso com este programa?
Posso por links do git com meu programa aqui?
Comment: Não entendi a pergunta. Antes de a clarificar, leia um pouco sobre SOLID e Design Pattern talvez o ajude na reformulação.
Comment: Segue o Main para entende o que preciso: package aula06Cencapsulamentotreino;

import java.io.ObjectInputStream.GetField;

public class ProgramaPrincipal {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  // Instanciando e criando um vetor com nome e tamanho via construtor.
  Vetor vetor1 = new Vetor("vetorcriado01", 5);
  // Definindo o nome e tamanho do novo vetor
  vetor1.metodoDefinicaoVetor("vetorcriado02", 3);
  vetor1.metodoPreencimentoVetor();
//vetor1.metodoOrdenacaoVetor();

 }
}
Comment: Importante você [edit] sua pergunta e explicar de maneira objetiva e pontual a dificuldade encontrada, acompanhada de um [mcve] do problema e tentativa de solução. Para aproveitar melhor o site, entender e evitar fechamentos e negativações vale a pena ler o [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/70).
Answer: Se precisa usar interface, basta adicionar a interface como parâmetro do seu método. Todas os objetos das classes que implementarem a sua interface poderão ser passadas como parâmetro.
Uma outra forma é declarar o seu "v[]" como uma váriavel fora do método metodoDefinicaoVetor e acessar ela diretamente de dentro do metodoPreencimentoVetor.
<code>    @Override
public void metodoDefinicaoVetor(String nomevetor, int tamanhovetor) {
    // TODO Auto-generated method stub
    setNome(nomevetor);
    setTamanho(tamanhovetor);
    v[] = new int[getTamanho()]; // declara o "int v[]" fora desse método. Aqui faz somente a inicilização dele.
    Arrays.fill(v, 0);
    System.out.println("Nome do vetor = " + getNome());
    // Impressão dos valores dentro da posição do vetor.
    for (int i = 0; i < v.length; i++) { //
        System.out.printf(" " + v[i]);
    }
    System.out.println("");
}

@Override
public void metodoPreencimentoVetor() {
    // TODO Auto-generated method stub

}
</code>
Comment: Melhorei a pergunta e postei o programa inteiro para facilitar... a ideia é usar o vetor criado no método de preenchimento para operações, busca e ordenação. [https://pt.stackoverflow.com/questions/473266/como-associar-um-vetor-%c3%a1-uma-vari%c3%a1vel-para-usar-entre-m%c3%a9todos]


How to compare two non-linear models with different dependent variables?

Question: I have two different dependent variables (Y1 and Y2). Both of them are ordered variables, but for Y1, it has 7 categories, while for Y2, it has 6 categories.
Now, I am using probit model to analyze the two dependent variable, employing the same set of independent variables. I am just wondering if it is possible to compare the two models?
Thanks in advance.
Comment: What aspects would you like to compare?  What are you hoping the comparison means?
Comment: What we usually call "model comparison" is about comparing models for the same dependent variable. Hence, @whuber's question.
Comment: Thanks! As for the comparisons, I am just trying to compare the model quality.
Answer: If Y1 and Y2 are just two different categories tiering of the exact same ultimate dependent variable Y; then I suspect some comparison of the two models may make some sense.  If on the other hand Y1 and Y2 are two entirely different dependent variables (not only differentiated by the number of categories), then your question does not make sense.  And, the straight answer is that those two models are simply not comparable.
Assuming that Y1 and Y2 are essentially derived from the exact same variable, you could compare the quality and the fit of the models using standard Goodness-of-fit measures for Probit model, and observe which categorie segmentation gave you better result.  Or for the purpose of model parsimony, did increasing your number of categories from 6 to 7 was materially worth it from both an explanatory and statistical significance standpoint.  This can be an interesting process, and you could test additional segmentation cuts of this same model structure using for instance fewer categories (like 4 or 5) and more categories (8, 9, etc.).  Selecting the proper number of categories is based on both art and science (statistical significance of the difference between the various categories, etc.).


Email marketing in Drupal 7

Question: I have a site with articles which has an RSS feeds.
I 'd like visitors to be able to subscribe to those articles using their email.
They ll give their email and then new articles will be sent to their email.
I m using feedburner to email right now, but I dont like it at all.
How this can be done in using Drupal modules and an SMTP server?
What technology is stackexchange.com using for the email notifications?
Answer: See Messaging and Notifications framework.
Comment: How do you compare those modules with http://drupal.org/project/simplenews ?
Comment: simplenews is really for only sending newsletters or custom admin messages to subscribed users. With the messaging and notifications framework, users can subscribe themselves to new content and automatically be notified by the site. It is a bit more complex to set up but contains much more features than i have explained.
Answer: Here is a module for an SMTP Email Relay Service Elastic Email: Elastic Email.

Email marketing in Drupal 7


Check if table has two values if so then

Question: I have a table called "link-relations"
and the structure is "id, user_id, link_id"
now i need to check for a record if there is a user_id of "2" and link_id of "1"
something like:
if (!mysql_query("SELECT * FROM links_relations WHERE (link_id, user_id)
VALUES     ('".$link['id']."', '".$user['id']."')")){
   //dosomething
}else{
   //do something else!
}

pxl help!
thanks in advance!
Answer: First, you need to need to explore the MySQL Documentation to learn the syntax.
The correct syntax for something like that is this:
SELECT * FROM `link_relations` WHERE `link_id` = '1' AND `user_id` = '2'

Don't rely on copy/pasting these answers. Please go read the documentation!
http://dev.mysql.com/doc/
To setup your script, if would look more like this:
$result = mysql_query("SELECT * FROM `link_relations` WHERE `link_id` = '1' AND `user_id` = '2'");
if ($result) {
    // Query did not throw an error. Now see if there are results
    $rows = mysql_fetch_all();
    $numRows = count($rows);

} else {
    // Error!
}

Also note that the use of mysql_ functions should end now. It is deprecated and going away.
http://php.net/manual/en/function.mysql-query.php
Answer: You can use next code:
$sql = "SELECT `id` FROM `links_relations` WHERE `link_id`=1 AND `user_id`=2";
$q = mysql_query($sql);
if ($q and mysql_num_rows($q)>0) {
    // you have required record in the table
}

But you really need to read MySQL documentation.


Use Kotlin field from Java project problem

Question: I would like to use Koin library from Java. According to this tutorial, Koin modules can be written in Kotlin even using Java in the rest of a project.
https://insert-koin.io/docs/quickstart/android-java/
I use also @JvmField annotation for the module field because in the source code of this tutorial it is used
https://github.com/InsertKoinIO/koin/blob/master/quickstart/getting-started-koin-android/app/src/main/kotlin/org/koin/sample/AppModule.kt
In my project I use koinInjector which is a list of modules
import org.koin.android.java.KoinAndroidApplication;
import org.koin.core.KoinApplication;

import static org.koin.core.context.DefaultContextExtKt.startKoin;
import static com.x.y.KoinInjectorKt.koinInjector;

public class App extends Singleton {
    @Override
    public void onCreate() {
        super.onCreate();
        KoinApplication koin = KoinAndroidApplication
                .create(this)
                .modules(koinInjector);
        startKoin(koin);
    }
}

KoinInjector.kt:
@JvmField
val koinInjector: List<Module> = listOf(
        localDbModule,
)

But during build I get the error:
error: cannot find symbol
import static com.x.y.KoinInjectorKt.koinInjector;
                               ^
  symbol:   class KoinInjectorKt
  location: package com.x.y

Comment: What is the file name of kotlin file where `koinInjector` is declared?
Comment: `KoinInjector` . Whereas the name `KoinInjectorKt` in import was generated automatically
Comment: Perhaps a (subtle) difference in build scripts? Could you include your `build.gradle` file?
Answer: I had to add
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.10"
to build.gradle and
apply plugin: 'kotlin-android' to build.gradle (app)`
Now it works.
Thanks @Jeroen Steenbeeke for your comment
Answer: Try to replace the code with -
import org.koin.android.java.KoinAndroidApplication;
import org.koin.core.KoinApplication;

import static org.koin.core.context.DefaultContextExtKt.startKoin;
import static com.x.y.KoinInjectorKt.koinInjector;

public class App extends Singleton {
 @Override
 public void onCreate() {
    super.onCreate();
    KoinApplication koin = KoinAndroidApplication
            .create(this)
            .modules(listOf(localDbModule));
    startKoin(koin);
   }
}

Answer: remove this import
'import static com.x.y.KoinInjectorKt.koinInjector;'
and write your code like this
public class App extends Singleton {
@Override
public void onCreate() {
    super.onCreate();
    List<Module> list = new ArrayList<Module>();
    list.add(localDbModule);
    KoinApplication koin = KoinAndroidApplication
            .create(this)
            .modules(list);
    startKoin(koin);
 }
}


Is it true that if $x^2$ > $y^2$, then $x<y^2$?

Question: I need to write a proof, and my method of proof requires the following:

If $x^2 > y^2$, then $x < y^2$.

But I can't find it as a theorem or postulate or anything anywhere. If it helps, both x and y would be positive numbers. I was wondering if this is true, or if it's just my wishful thinking.
Comment: That's simply not true. Let x=10, y=1. Your statement doesn't hold in general.
Comment: What are you actually trying to prove? If this statement is absolutely required for your theorem to be true, then your theorem is necessarily false. My guess is therefore that there's another way to complete your proof.
Comment: $x^{2} > y^{2} \implies \left(~\left\vert\, x\,\right\vert < - \left\vert\, y\,\right\vert \ \mbox{or}\ \left\vert\, x\,\right\vert > \left\vert\, y\,\right\vert~\right)$.
Comment: *Real* positive numbers?
Comment: Thank you @Dargscisyhp!

and yes @Bernard
Comment: @MichaelLee that i is less than or equal to the effective annual rate which is less than or equal to e^i - 1

It was just an idea I had (which was obviously wrong)
Comment: Well, no, your conjecture isn't necessarily wrong at all. You're just going about it the wrong way. You're trying to show that $i \leq \left(1+\frac{i}{n}\right)^n-1 \leq e^i-1$ for all $n \geq 1$?
Comment: yes, and i >= 0

We were trying to work out the left hand side of the inequality first
Comment: To me, this is most intuitive if we use calculus. We know that $i = \left(1+\frac{i}{n}\right)^n-1$ when $i = 0$, and if we can just show that $\left(1+\frac{i}{n}\right)^n-1$ increases faster than $i$ for all $i \geq 0$, then we know that $i \leq \left(1+\frac{i}{n}\right)^n-1$.
Answer: The statement is not true as written.
For instance, $2^2 > 1^2$, but $2>1$.
Generally, it is usually a good idea to test out conjectures such as these on many different sets of inputs. If you choose a variety of $x$ and $y$ to try, it's very likely that you will come across a counterexample.


Why is each observation in a sample considered a random variable in linear regression?

Question: I have the following excerpt in my statistics textbook:

I am confused by the sentence: "Another way statisticians treat this model is that, assume $X_1...X_n$ are random variables, we make inferences conditional on their observed values."
Aren't $X_1...X_n$ simply observations of a random variable, $X$? For example let's say I have a random variable $X$ is a persons weight and random variable $Y$ is a persons blood pressure. Then $(X_1, Y_1)$ are an observation of those RVs. How could $X_1$ be a RV?
Maybe its an RV if that specific persons weight (person associated with $X_1$) is sampled multiple times?
Comment: In my understanding you are correct. $X_1 \dots X_n$ are *observations* of random variable $X$.
Comment: Hi, there are blind and visually impaired users of this
site who interact with it using screen readers. The screen
readers can't handle the equation in your screenshot.
Please edit the post to include the equation as LaTeX. If
it helps, we have some
[resources on using LaTeX on Cross Validated](https://stats.meta.stackexchange.com/a/1605/155836).
Answer:
Aren't $X_1...X_n$ simply observations of a random variable, $X$?

NO.  But this is a good question, as this certainly mystifies many ...  and intuitive language such as observations of a random variable isn't really that helpful.
First, you need to understand what is a random variable, see some of the many posts discussing this:

What is the difference between a realisation of a random variable and random variable itself?

What is meant by a "random variable"?

(site search will give more). A random variable is a function. And, a mathematical function have only one value.  So it does not make mathematical sense to speak of $X_1, X_2, \dotsc, X_n$ being different values of (or realizations of) one random variable $X$.
Each $X_i$ must be defined as a random variable itself. In terms of your example, where $X$ is a person's weight, and there is a sample of $n$ persons, then $X_1$ is weight of first person in sample, $X_2$ is weight of second person in sample, and so on.
Maybe not that central to your question, but you say confused by also

we make inferences conditional on their observed values

For that, see the following posts,

What is the difference between conditioning on regressors vs. treating them as fixed?

What are the differences between stochastic and fixed regressors in linear regression model?
Comment: Hi thank you for the answer. Could you maybe explain what X1...Xn could be in terms of my example of weight and blood pressure?


watchkit - how to use my numbers with an image

Question: i have following code:
for(int i = 0; i < 4; i++){
    NSMutableString *Row = [NSMutableString new];
    for(int j = 0; j < 4; j++){
        [Row appendString:[NSString stringWithFormat:@"%d", numbers[j][i]]];
    }
    NSLog(@"%@\n", Row);
}

with this i get the following output:
6473
7354
9835
6475
i have 16 images in groups on my WKInterfaceController and now i want to display an image for each number . for example, a 4 = image4.png, 8 = image8.png.
first line is: image6 image 4 image7 and image3 and so on.
how can i get there?
Answer: You need to set the image on  instance of your imageView (WKInterfaceImage)
yourimageView.setImage(UIImage(named: "image name string"));

The above code of yours just give the imageName as per your approach. If there are multiple WKInterfaceImage objects in your storyboard then you need to make outlets for each of them and then set the image accordingly. Since WatchKit do not support Collection outlets so you need to make outlet for every WKInterfaceObject. You can set the image from Inspector to if image is supposed to be same always for a particular object.


Custom content in auto generated menu

Question: I have been working on a website that contains a main dropdown menu generated by Drupal (7.28). Is there any way I can add a link to it between the other links that shows content generated by me in the dropdown? So instead of: fetch pages, fetch something else (defined by me).
Thanks in advance =]
Answer: Every module on your site can be found in the list on /admin/structure/menu.
just click 'list links' and then 'add link' to add a link to a menu.
Comment: Does this also enable me to generate my own content in the dropdown using PHP?

Custom content in auto generated menu


Gerar sequence para campo

Question: É possivel eu criar um sequence sem mudar o campo para id?
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.DocumentoNumero);

Usando este exemplo, gostaria de manter um sequence para DocumentoNumero, mas ao mesmo tempo tenho id que já esta fazendo isto e preciso mantê-lo desta forma.
Comment: qual o objectivo do documentoNumero? é ser igual ao id?
Comment: Não, o id segue gerando em sequencia para cada documento..
O DocumentoNumero não será unico, apenas deve gerar uma sequencia quando solicitado ou caso ele seja gravado como null
Comment: http://stackoverflow.com/questions/8990319/have-a-custom-setter-on-property-for-ef-code-first-model-entity

nao percebi bem, queres ter controlo sobre o "set" dessa propriedade. da uma olhada neste link
Answer: https://stackoverflow.com/questions/8990319/have-a-custom-setter-on-property-for-ef-code-first-model-entity
codigo tirado desse link.
private string documentoNumero;
     public string DocumentoNumero
     {
          get { return documentoNumero; }
          set
          {
               // aqui podes por a logica do campo jobTitle = value
          }
     }

Comment: quase isso, na verdade se tivesse alguma forma de criar um sequence (via nhibernate) sem vincular ao campo, para ser chamado pela aplicação apenas quando necessário já seria suficiente. A idéia seria manter a integridade dessa informação, no caso de varios usuarios acessarem ao mesmo tempo
Comment: http://nhibernate.info/doc/howto/various/creating-a-custom-id-generator-for-nhibernate.html
Answer: Faz tempo já, mas vou deixar aqui como resolvi para minha atender à necessidade:
    protected void SetSequence(string sequenceName, int value)
    {
        string sqlQuery = string.Empty;

        if (value == 0)
            sqlQuery = $"SELECT setval('{sequenceName}', 1, false);"; // o próximo nextval() retornara {value} (1)
        else
            sqlQuery = $"SELECT setval('{sequenceName}', {value}, true);"; // o próximo nextval() retornara {value}+1

        Session.CreateSQLQuery(sqlQuery).ExecuteUpdate();
    }

Gerar sequence para campo


Method changes a parameter array's value, unless the parameter is set to nil?

Question: Here is a method I've been testing in the rails console.
def self.increment_index_array(index_array, sizes_array, last_index)
    index_array[last_index] += 1
    for i in (last_index).downto(0)
        if index_array[i] == sizes_array[i]
            if i == 0
                index_array = nil
                return index_array
            end
            index_array[i] = 0
            index_array[i-1] += 1
        else
            break
        end
    end
    return index_array
end

I've been defining an index_array variable on the console and passing it to the method.  The method is destructive on the index_array variable.  Calling the method returns the incremented array, but also changes the variable value in the scope outside of the method (the console), which is desired.  However, when I set the array to nil inside the method this change isn't reflected in the exterior scope.  Why is this?  Is there a way to make the variable nil in the exterior scope?
An example console session:
1.9.1 :191 > index = [64, 2, 3]
 => [64, 2, 3]
1.9.1 :192 > sizes = [65, 3, 5]
 => [65, 3, 5]
1.9.1 :193 > increment_index_array(index, sizes, 2)
 => [64, 2, 4]
1.9.1 :194 > index
 => [64, 2, 4]
1.9.1 :195 > increment_index_array(index, sizes, 2)
 => nil
1.9.1 :196 > index
 => [65, 0, 0]

Comment: I'm guessing the variable is acting as a pointer.  When I use the [] operator I'm dereferencing it and changing the values in memory, but a straight up assignment to nil is just creating a null-pointer, whereas the pointer in the exterior scope is still pointing to the array in memory.
Answer: Ruby is a pass-by-value "everything is an object" language. Arrays are objects. When you use an array as an argument to a function, you are actually passing the reference to that array, which is mutable.
When performing an assignment, you are actually creating another reference and storing the value of that reference in the given scope.
If you want to change the type of the argument, you will have to do the assignment in the calling scope.  Ruby has no symbol table alias functionality.


Can't make works socket.io with my handshake

Question: I don't understand where is my problem.
When I put this:
io = require('socket.io').listen(server).of("/");

I my handshake looks like running fine, but all my socket.io's event (like connection) never works.
And when I when i put this
io = require('socket.io').listen(server);

I got this :

TypeError: Object # has no method 'authorization'

If I remove my handshake, all the socket.io's will works, but i need it :/
Here my app.js
 const express = require('express')
    , app  = express()
    , http = require('http')
    , ejs = require('ejs')
    , server = http.createServer(app)
    , port = process.env.PORT || 1337
    , io = require('socket.io').listen(server).of("/")
    ;

module.exports = { app: app, server: server };
// Grab "cookie" and "connect" from express
var connect = require('express/node_modules/connect')
var cookie = require('express/node_modules/cookie')
var connectes =[];

app.configure(function(){
    this.use("/public", express.static(__dirname + '/public'));
    this.use(express.cookieParser());
    this.use(express.json());
    this.use(express.urlencoded());
    this.sessionStore = new express.session.MemoryStore({ reapInterval: 60000 * 10 });
    this.use(express.session({
        "secret": "some private string",
        "store":  this.sessionStore
    }));
});
app.engine('html', ejs.renderFile);

app.set('views', __dirname + '/views');

app.get('/', [requireLogin], function(request, response) {
    var pseudo = request.session.pseudo;
    response.render('index.ejs.html',{connectes:connectes});
});

app.get('/login', function(request, response) {
    response.render('login.ejs.html');
});

app.post("/login", function(req, res){
    if (req.param("user") != "") {
        req.session.pseudo = req.param("user");
        //socket.set('pseudo',req.param("user"));
        connectes.push(req.param("user"));
        res.render('index.ejs.html',{connectes:connectes});
    }else{
        res.render('login.ejs.html');
    }
});

const parseCookie = require('connect').utils.parseCookie;
io.authorization(function (handshakeData, callback) {
    var cookies = cookie.parse(handshakeData.headers.cookie);
    console.log(cookie);
});

io.on('connection', function(socket){
    console.log("This never appear in log :/");
    socket.on('login',function(user,callback){
        var pseudoValide = true;
        for (var i = 0; i < connectes.length; i++) {
            if(connectes[i]==user.pseudo){
                pseudoValide = false;
                callback(true);
            }
        }
        if (pseudoValide) {
            socket.set('pseudo',user.pseudo);
            pseudo = user.pseudo;
            socket.broadcast.emit('newuser', pseudo);
            socket.broadcast.emit('nvluseronline', pseudo);
            connectes.push(pseudo);
            callback(false,pseudo);
        }
    });
    socket.on('message',function(message){
        messageUser = message.message;
        socket.get('pseudo',function(error, pseudo){
            io.sockets.emit('nouveauMessage',{pseudo:pseudo,message:messageUser});
        })
    });
    socket.on('disconnect',function(){
        socket.get('pseudo',function(error, pseudo){
            connectes = unset(connectes, pseudo);
            io.sockets.emit('nvldisc', pseudo);
        })

    });
});

function unset(array, value){
    var output=[];
    var index = array.indexOf(value)
    {
        var j = 0;
        for(var i in array)
        {
            if (i!=index)
            {
                output[j]=array[i];
                j++;
            }
        }
        return output;
    }
}

/** Middleware  */
function requireLogin (req, res, next) {
    if (req.session.pseudo) {
        console.log(req.session.pseudo);
        next();
    }else{
        res.redirect("/login");
    }
}

if (!module.parent) {
  server.listen(port, function () {
    console.log('Listening', this.address());
  })
}

Like you can see i'm a beginner lost !
Thank you guys !
Answer: You should read the documentation on authorization carefully. authorization method only exists for namespaces. When doing global authorization, you have to do:
io.configure(function (){
  io.set('authorization', function (handshakeData, callback) {
    callback(null, true); // error first callback style
  });
});

It'll work fine if you have .of("/") as server endpoint, but it is a namespace. Without namespaces you would have to use above method.
Comment: Thank you guy, I understand where was my mistake and now all works perfectly ! :)


$\operatorname{Im} T^t \,\dot+\, \ker T = V$

Question: Let T be sqaure matrix and regarded as a linear operator on a finite dimensional vector space V such that $T^2 = 0$.

Then is $\operatorname{Im} T^t \,\dot+\, \ker T = V$ obvious? If so, why is it so? ($\dot+$ denotes direct sum )

Addtional Question

$dim(kerT∩kerT^t) =\dim \ker T+\dim\ker\ T^t−\dim(\ker T\dot+\ker T^t)$
Comment: For the additional question, if the sum is direct (as you denoted), then the left hand side is $0$ by definition. But, you probably meant this $\dim(V+W) = \dim V + \dim W - \dim(V\cap W)$. To prove it, write a basis for $V\cap W$ and expand it to bases for $V$ and $W$. It is basically inclusion-exclusion principle.
Comment: @Ennar Could you refer me anylink for the full proof? I am right now digging my undergraduate linear algbera textbook, still can't find one.
Comment: Beverlie, take a look at [this answer](https://math.stackexchange.com/a/500521/122131).
Answer: The rank-nullity theorem tells you, that $$dim (Ker(T)) + dim(Im(T))=dim (V)$$
But
 $$dim(Im(T))=rank(T)=rank(T^t)=dim(Im(T^t))$$
Thus, $dim(Im(T^t))+dim(Ker(T))=dim(V)$. Hence, you are left to check that $Im(T^t)\cap Ker(T)=\{0\}.$ This follows from the following computation. Let $v\in Ker(T)$ and $w\in Im(T^t)$, then we have $u\in V$ such that $T^t u=w$ and we get
$$ \langle v, w\rangle = \langle v, T^t u \rangle = \langle T v , u\rangle = \langle 0, u\rangle =0$$
Therefore, $Im(T^t)$ and $Ker(T)$ are orthogonal to each other and have trivial intersection.
This dimension formula can be obtained in the following way (as Ennar in his comment suggested): Let $X$ be a vector space and $V,W\subseteq X$ finite dimensional subvector spaces. First pick a basis $(u_i)_{1\leq i \leq l} $ of the vector space $V\cap W$. You can extend this basis to a basis $(u_1, \dots , u_l, v_1, \dots, v_m)$ of $V$. On the other hand, you can also extend this to a basis $(u_1, \dots, u_l, w_1, \dots, w_m)$ of $W$. Note that $(u_1, \dots u_l, v_1, \dots, v_n, w_1, \dots, w_m)$ forms a basis of $V+W$ (check this). Now we get
$$ dim(V+W)= l + n + m = (l+m) + (l+n) - l = dim(V) + dim(W) - dim(V\cap W). $$
This implies
$$ dim(V \cap W) = dim(V)+ dim(W) - dim(V+W). $$
Comment: could you give me a hint for the additional quesiton in OP?
Comment: I was trying to see why $Rank(T) = Rank(T^{t})$ ?
Comment: @BAYMAX It is a standard fact from linear algebra. Namely the row rank of a matrix is equal to the column rank. This question might help you https://math.stackexchange.com/questions/332908/looking-for-an-intuitive-explanation-why-the-row-rank-is-equal-to-the-column-ran?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa


Date time formats: October not correctly written in German

Question: I created a time format in Drupal administration (admin/config/regional/date-time) with the following settings in EN/ DE:
<code>DE: d. F Y -> 05. October 2016
EN: dS F Y -> 05th October 2016
</code>
The problem is that "October" is written in German like "Oktober" ("k" instead of "c"). The strange thing is that the translation works fine with every other month ("May" for example becomes "Mai" in German) but just the October is written wrong. This appears to be an issue no matter where the date field is rendered, in views or node detail page.
Additionally this seems to be an issue with the PHP date format as it the same problem when using date('d. F Y', $timestamp). Can anyone give me a hint how to solve this issue?
Comment: If I check google translate, 'Oktober' is the right German translation for 'October'. Anyways, if you still want to change the German translation, you can just go to translation interface in Configuration, search the string there and then correct the translation.
Comment: Yes, "Oktober" is the correct translation but the date format is giving "October". The translation is not from interface but from date format but I can really change the translation in interface translation. I do not get why it is like that but ok... thank you
Answer: The name of the month can be change via interface translation - see comment of Drupaler


Problemas com limites de largura da banda

Question: Tenho um site hospedado em um servidor (Kinghsot). Esse mesmo site, teve esse mês (de 01/fev até 16/fev) cerca de 2700 visitas, de acordo com o Google Analytics. O que acontece, é que isso gerou de tráfego mensal (até o dia 16) de quase 22GB, isso está normal?
Eu estava conferindo as estatísticas do servidor, e vi que os arquivos .JS estão com muitos hits, conforme imagem:

Pensei que talvez, poderia ser algum plugin, mas dei uma conferida e não há nada suspeito.
Lista de plugins que eu uso:

Admin Menu Editor
CloudFlare
Disqus Comment System
Facebook Comments
Google AdSense
Master Slider Pro
Relevanssi
Shareaholic | share buttons, analytics, related content
Simple Image Sizes
Templatera
TinyMCE Advanced
WPBakery Visual Composer (Artbees Modified Version)
Yoast SEO

Imagem com os dados de tráfego:
Comment: Cara, tenta dar uma otimizada nos seus scripts, pelo menos de acordo com o tamamnho...
Pode tentar usar o PageSpeed (https://developers.google.com/speed/pagespeed/) para avaliar as melhorias.

Em relação aos hits, acredito que possa ser algum plugin do seu próprio tema do WP.
Answer: Em média, cada visualização está consumindo pouco mais de 8 Mega para 2700 visualizações consumirem 22GB. Parece condizente com o conteúdo do seu site?
Para melhorar isso, o jeito é otimizar mesmo (reduzir imagens, páginas, simplificar opções, etc).
Comment: Obrigado, vou verificar e ver se é isso. Instalar um plugin para otimizar as imagens.


Uniqueness of high-dimensional derivative [Zorich's book]

Question: I was reading the definition of the high-dimensional derivative from Zorich's book and I'd like to ask a question about the uniqueness of high-dimensional derivative.

Definition 1. A function $f:E\to \mathbb{R}^n$ defined on a set $E\subset \mathbb{R}^m$is differentiable at the point $x\in E$,
which is a limit of $E$, if  $$f(x+h)-f(x)=L(x)h+\alpha(x;h), \quad \quad \quad(1)$$ where
$L(x):\mathbb{R}^{m}\to \mathbb{R}^n$ is a function that is linear in
$h$ and $\alpha(x;h)=o(h)$ as $h\to 0, x+h\in E$.
The linear function $L(x):\mathbb{R}^m\to \mathbb{R}^n$ in $(1)$ is
called the  differential of the function $f:E\to
 \mathbb{R}^n$ at the point $x\in E$.

Claim. If $E\subset \mathbb{R}^m$ and $f:E\to\mathbb{R}^n$ is differentiable at the point $x\in E$, which is a limit point of $E$, then the differential of $f$ at the point $x\in E$ is unique.
Proof. Let's assume there are $A,B:\mathbb{R}^m\to \mathbb{R}^n$ linear mappings such that
$$f(x+h)-f(x)=Ah+\alpha(x;h) \quad \text{and} \quad f(x+h)-f(x)=Bh+\beta(x;h),$$ where $\alpha(x;h)=o(h)$ and $\beta(x;h)=o(h)$ as $h\to 0, x+h\in E$.
Remark. Here the base is $h\to 0, x+h\in E$. The elements of this base are $B_{\delta}:=\{h\in \mathbb{R}^m: 0\leq \lVert h\rVert<\delta, x+h\in E\}$ for $\delta>0$. Indeed, it satisfies to the definition of base.
Let $C:=A-B$, then $C:\mathbb{R}^m\to \mathbb{R}^n$ is a linear mapping also. Then it is not difficult to show that $$\lim \limits_{\substack{h\to 0 \\ x+h\in E}} \frac{\lVert Ch\rVert}{\lVert h\rVert}=0.$$
Let $y$ be a nonzero vector in $\mathbb{R}^m$. If we can show that $\lim \limits_{\substack{\mathbb{R}\ni t\to 0 \\ x+ty\in E}} \frac{\lVert C(ty)\rVert}{\lVert ty\rVert}=0,$ then we are done. Indeed, in that case it follows that $\lVert Cy\rVert=0$ for all $y\neq 0$, which implies that $Cy=0$ for all $y$ and hence $Ay=By$. Therefore, linear mappings $A$ and $B$ are equal.
Question. How to prove that if $\lim \limits_{\substack{h\to 0 \\ x+h\in E}} \frac{\lVert Ch\rVert}{\lVert h\rVert}=0$, then $\lim \limits_{\substack{\mathbb{R}\ni t\to 0 \\ x+ty\in E}} \frac{\lVert C(ty)\rVert}{\lVert ty\rVert}=0$ ??
It is certainly true if $x$ is an interior point of $E$ but it does not look correct to me because we claim that $x$ is the limit point of $E$. Let me try to explain why do I think so.
Let $\varepsilon>0$ be given. Take $\delta_0=\frac{\delta}{\lVert y\rVert}>0$, where $\delta>0$ comes from the first limit. Then for any $t\in \mathbb{R}$ such that $0<|t|<\delta_0,\ x+ty\in E$ we'll get that $\frac{\lVert C(ty)\rVert}{\lVert ty\rVert}<\varepsilon$. It seems that we are done but how do we know that such $t$ exists?
I mean how do we know that $\{t\in \mathbb{R}: 0<|t|<\delta_0, x+ty\in E\}\neq \varnothing$?
Thank you so much for your help!
Comment: This question has been raised [here](https://math.stackexchange.com/questions/3598676) and although it remains unanswered, it might be useful to you.
Comment: If you take $E$ a hyperplane and $y$ a normal vector then your limit looks odd: the function has an empty domain. Can't you let $E$ be open? He deserves it :)
Comment: @blamethelag, which limit are you talking about?
Comment: @ZFR the second one in your **Question**.
Comment: @kabenyuk, many thanks for your link! But let me ask you a few questions: **1)** if we define differentiability as Zorich did, then we ran into some trouble as a non-uniqueness of differential. Having many differentials at one point is a meaningless, right? **2)** Am I right that it is better to change the definition into the case when $E$ is open set or $x$ is an interior point of $E$? Thank you!
Comment: @kabenyuk **3)** Also if we define the differentiablity in the way as Zorich did for functions $f:E\to \mathbb{R}$ with $E\subset \mathbb{R}$, then it is not an issue. I mean in that case, the differential is still unique.
Answer: Such a $t$ does not necessarily exist. You can take a hyperplane $E$ passing through the origin $ x = 0$ and $y$ any vector which spans a line which is not included in the hyperplane $E$. In this case one has
$$ x + ty \not \in E \quad  \forall t \in \mathbb R_0. $$
In this case we do not have unicity of the differential. Indeed consider $f = k \in \mathbb R$ constant on $E$.  Then $$ f(x + h) - f(x) = 0.$$
Hence it follows that any linear map $L_x : \mathbb R^m \to \mathbb R : h \mapsto L_x(h)$ whose restriction to the hyperplane $E$ is equal to $0$ satisfies the definition of differentiability.

Your example is showing that if we assume that the function $f:E\to \mathbb R^n$ is differentiable at the point $x\in E$, where $x$ is a limit point of E, then differential of f at $x$ may not be unique, right?

Yes. However if the limit point $x$ happens to be an interior point then we do have unicity.

To avoid this ambiguity one needs to assume that x is an interior point of E or E is an open set, right?

Not really. Asking that $x$ be an interior point garanties the unicity. But this is not needed in order to have unicity. Indeed it is possible ins some cases for $x$ to be a limit point, $x$ not an interior point and still have  unicity. That is, $x$ being an interior point is a sufficient condition but not needed.
Example
Let $E = [0,1]^2 \subset \mathbb R^2$ and $f = k \in \mathbb R$ be constant on $E$. Define
$$ L_x = 0 : \mathbb R^2 \rightarrow \mathbb R$$
Then for all $x  + h = h \in E$
$$f(x+h)-f(x) - L(x)h = 0 = o(h),$$
so $f$ is differentiable at $x = 0$. To prove the unicity suppose there are other linear maps $A,B$ satisfying the definition then let $C = A-B$ and we have
$$ \lim_{h\to 0, x + h \in E} \frac{\Vert Ch \Vert}{\Vert h \Vert} = 0.$$
Let $y_1 = (1,0), y_2 = (0,1) \in E$. Then for all $0 < t < 1$ we have
$ x + ty_i \in E$ hence we have
$$ \lim_{t \to 0 , t > 0 }  \frac{\Vert C(ty_i) \Vert}{\Vert ty_i \Vert} = 0.$$
In particular we deduce that $$ A(y_i) = B(y_i).$$
Since the two linear maps $A$ and $B$ coincide on a basis of the vector space $\mathbb R^2$ it follows that $$ A = B.$$

If we consider one-dimensional case, i.e. f:E→R where E⊂R and f is differentiable at x∈E, then in that setting we always have unicity of differential even x is a limit point of E, right? I think the subtle difference here is that in R we have only one direction

If we adapt our proof to the case where $E$ is of dimension one then yes that's the general idea. However for the case where $E \subset \mathbb R$ there is a much simpler argument to prove the unicity. Indeed there are linear maps $L_1,L_2$ and $\alpha_i(x;h) = o(h)$ such that
$$ f(x + h) - f(x) = L_i(x)h + \alpha_i(x;h)$$
then
$$ \lim_{h\to 0} \frac{f(x+h)-f(x)}{h} = L_i(x) $$
so $L_1 = L_2$ by unicity of the limit.
Comment: @ZFR I've edited my answer to address your comments.
Comment: @ZFR Yes working over open sets is easier. This makes everything easier because when $x$ is in the interior you can approach $x$ from any direction. This gives you a lot a freedom in proofs so everything becomes easier. The fact the unicity of the derivative follows from this makes it even more practical to work over open sets. In fact most textbooks restrict themselves to open sets. Answer to **3)** is now in the edited post.
Comment: Let me ask you a few questions: **1)** Your example is showing that if we assume that the function $f:E\to \mathbb{R}^n$ is differentiable at the point $x\in E$, where $x$ is a limit point of $E$, then differential of $f$ at $x$ may not be unique, right? **2)** To avoid this ambiguity one needs to assume that $x$ is an interior point of $E$ or $E$ is an open set, right?
Comment: P.S. By the way your example is exactly the same as in the link which @kabenyuk provided.
Comment: Thanks a lot! This is a really good answer which I'll accept! But let me ask you two more questions: **3)** If we consider one-dimensional case, i.e. $f:E\to \mathbb{R}$ where $E\subset \mathbb{R}$ and $f$ is differentiable at $x\in E$, then in that setting we always have unicity of differential even $x$ is a limit point of $E$, right? I think the subtle difference here is that in $\mathbb{R}$ we have only one direction.
Comment: **4)** However, in general case I think it is better to consider when $E$ is open set. Your examples have shown that if $x$ is a limit point of $E$, we may have unicity and may not. That is why it is meaningful to take $E\subset \mathbb{R}^m$ to be an open set. Right?
Comment: That was a really good and deep explanantion! Thank you so much for such a detailed answer! +1


How do I create a configuration sync folder?

Question: I've inherited a Drupal 8 site but it has no config_HASH folder with it which means that the majority of admin paths throw an exception.
How do I generate a new configuration folder based on the current site?
Comment: Open your settings.php file and at the end there is the 'sync' variable. Create that directory in your files directory and use drush to clear cache. Although if that site is some old version of Drupal where the config was still presen on the file system and not in the database then I guess you will have to dump the active config from db table and parse it into yml files manually.
Comment: What version of Drupal 8 do you use?
What is set for $config_directories in settings.php?
(grep config_directories settings.php)
Answer: To generate a new config folder do the following:
In settings.php add the following line:
<code>$config_directories['sync'] = 'dest/to/config-sync';
</code>
This is relative to your docroot or index.php file.  My permission were set in a way that drupal could create this directory but you may have to create your own.  Next you will want to populate your sync directory with active config. Run
<code>drush cex -y
</code>
Now your active config can be version controlled and deployed to your other environments. Remember to make a database backup first before importing config.


Error of Bias-Corrected Kurtosis Estimators

Question: Background
I've found two different bias-corrected estimators for the kurtosis.
The first one is used in various software packages, such as MATLAB, and is called bias-corrected in the respective documentations:
$k_0 = \frac{n-1}{(n-2) (n-3)}\left((n+1) \frac{\frac{1}{n} \sum\limits_{i=1}^n (x_i-\overline{x})^4}{\left(\frac{1}{n} \sum\limits_{i=1}^n (x_i-\overline{x})^2\right)^2}-3 (n-1)\right)+3.$
The second one can be found in Harald Cramér's book Mathematical Methods of Statistics on page 352 and is also the result of using the HStatistic function from the mathStatica package for Mathematica. It is said to be unbiased:
,
where $m_i$ is the sample central moment: $m_r = \frac{1}{n} \sum\limits_{i=1}^n (x_i - \overline{x})^r.$
Simulation Results
With both of these estimators being bias-corrected, the average of each of the kurtosis estimates from multiple independent trials should reflect the population kurtosis quite well.
I've tried to test this assumption in Mathematica.
For the first test, I've used the standard normal distribution and averaged the kurtosis estimates of 100,000 independent trials:

As expected, the average of the kurtosis estimates reflect the population kurtosis quite well. However, when performing the same test with another distribution (in this case the chi-squared distribution with one degree of freedom) the estimates are extremely off:

Question
Can someone provide an explanation why the averages of the bias-corrected kurtosis estimates ($k_0$ and $h_4$) are that off in my simulation?
I'm especially surprised by the error of $h_4$, an estimate that is said to be unbiased.
Comment: As you have noted in your answer below, $h_4$ is an unbiased estimator of the 4th central moment ... not of population kurtosis. General unbiased estimators of ratios of moments do not usually exist ... but can be found for products of moments. This is because products of moments are symmetric functions, while ratios are not.
Answer: I figured it out by myself.
Unfortunately, I made a mistake during my experiments: I overlooked the fact that the kurtosis is defined as
$\operatorname{Kurt}[X] = \frac{\operatorname{E}[(X-\mu)^4]}{(\operatorname{E}[(X-\mu)^2])^2},$
i.e., the fourth central moment divided by the square of the second central moment (notation taken from Wikipedia). In my original question, I erroneously mistook the unbiased estimator for the fourth central moment, $\frac{m_2^2 (9-6 n) n^2+m_4 \left(n^3-2 n^2+3 n\right) n}{(n-3) (n-2) (n-1) n}$, as an unbiased estimator for the kurtosis (and completely neglected the division by the squared second central moment).
Furthermore, there doesn't seem to be a general unbiased sample kurtosis estimator. The bias depends on the shape of the distribution. Here is a nice overview of different sample kurtosis estimators that also compares their relative performance.


What concentration $\kappa \in [0, \infty)$ maximizes the entropy of the von Mises-Fisher distribution?

Question: I'd like to prove what concentration parameter $\kappa \in [0, \infty)$ maximizes the (differential) entropy of a von-Mises Fisher Distribution.
The differential entropy of of a von Mises-Fisher distribution $vMF(\mu, \kappa)$ is:
$$-\log C_D(\kappa) - \kappa A_D(\kappa)$$
where

$C_D(\kappa) = \frac{\kappa^{D/2 - 1}}{(2 \pi)^{D/2} I_{D/2 - 1}(\kappa)}$
$A_D(\kappa) = \frac{I_{D/2}(\kappa)}{I_{D/2 - 1}(\kappa)}$
$I_v$ denotes the modified Bessel function of the first kind at order $v$

My intuition is that $\kappa=0$ maximizes the entropy. But how do I show this? I'm having trouble calculating first and second order stationary points because of the Bessel functions.
Comment: Shouldn't it be the lowest possible $\kappa$?
Comment: This is a special case of a general result: the entropy among all distributions on a space of finite volume is maximized by the uniform distribution.  Thus, it shouldn't be necessary to use any of the particulars about Bessel functions.  Use the Calculus of Variations to show the log density must be almost surely zero.
Comment: That's my guess too, yes. I wrote my intuition is that $\kappa = 0$ maximizes the entropy but I'm having trouble deriving this. Do you know how to show this? I rephrased to sharpen what specifically I'm asking.
Comment: You could plug the expression into an automatic differentiator and see if you can show that the differential entropy is monotonic wrt $\kappa$.
Comment: @whuber yes, $p$ should have been $D$. My apologies. There's no need to use "??"
Answer: This post presents an elementary but highly general demonstration that avoids any considerations of Bessel functions.  (You need to know some basic derivatives of real functions of one variable, as presented in the first section, and only the simplest properties of integrals -- linearity and positivity--; no integrals will need to be evaluated.)
Calculus preliminaries
Observe that the function defined on $(0,\infty)$ (and extended to $0$ via continuity) as
$$u(x) = x\log x$$
is strictly convex because $u^{\prime\prime}(x) = 1/x$ is everywhere positive. Because whenever $x\gt 0$ also $1+x\gt 0,$ Jensen's Inequality implies
$$\frac{1+x}{2} \log\left(\frac{1+x}{2}\right) = u\left(\frac{1+x}{2}\right) \lt \frac{1}{2}u(1) + \frac{1}{2}u(x) = \frac{1}{2}u(x).$$
Next, $u(x) \ge x-1$ for all $x \ge 0$ because
$$\frac{\mathrm d}{\mathrm d x}(u(x) - (x-1)) = \log x$$
has a unique zero at $x=1,$ which must be the point of the global minimum, and
$$u(1) - (1-1) = 1\log(1) - 0 = 0$$
is its minimal value, QED.
A general result
Let $\Omega$ be a measure space and $\mu$ be a finite measure on $\Omega.$  Divide $\mu$ by $\mu(\Omega)$ to normalize it.
Suppose that $f$ is a density function with respect to $\mu$ for which $\int_\Omega f\,\mathrm d\mu = 1:$ that is, $f$ is a probability density.  We are interested in the functional
$$H[f] = \int_\Omega f \log f \,\mathrm d\mu,$$
the negative of the entropy.  The preceding inequality shows that $H$ is nonnegative since
$$H[f] = H[f] + 1 - 1 = H[f] + \int_\Omega (f\log f -  f + 1)\,\mathrm d\mu\ge \int_\Omega 0 \,\mathrm d\mu = 0.$$
Moreover, the constant function $1$ attains this minimum because
$$H[1] = \int_\Omega 1 \log 1\,\mathrm d\mu = \int_\Omega 0 \,\mathrm d\mu = 0.$$
What was the effect of the initial normalization of $\mu$?  It did two things:

All integrals were multiplied by $1/\mu(\Omega).$

All density functions had to be multiplied by $\mu(\Omega)$ to compensate for (1).

The first effect will not change the fact that $0$ is the lower bound of $H,$ while the second effect changes $H$ to
$$\begin{aligned}
H[\mu(\Omega)f] &= \int_\Omega \mu(\Omega) f \log(\mu(\Omega) f)\,\mathrm d\mu\\
&= \mu(\Omega) \int_\Omega f \log f\,\mathrm d\mu + \mu(\Omega)\log(\mu(\Omega))\int_\Omega f\,\mathrm d\mu\\
&= \mu(\Omega) H[f] + \mu(\Omega)\log(\mu(\Omega))
\end{aligned}$$
because $\int_\Omega f\,\mathrm d\mu = 1.$  This constant additive change will not alter the order relationship between $H[1]$ and $H[f]$ -- it only changes the value of the lower bound.
(It is instructive to compare this to the analysis at https://stats.stackexchange.com/a/415436/919 which concerns probability distributions on a non-finite measure space.  There, the analog of changing the measure is to rescale the variable.)
We conclude

On a space $\Omega$ of finite measure, the entropy $-H[f]$ is maximized among probability densities $f$ for the constant probability density $f = 1/\mu(\Omega)$ (attaining the minimum value $\mu(\Omega)\log\mu(\Omega)$).

Solution to the problem
A von-Mises Fisher distribution in $D$ (Euclidean) dimensions is an isotropic Normal distribution conditioned on the unit sphere.  (The parameter $1/\kappa$ uniformly scales that distribution.)  Applying the preceding result to the induced Lebesgue measure $\mu$ on the sphere shows that the entropy is maximized by the uniform distribution on the sphere.  That is the distribution corresponding to $\kappa = 0,$ QED.
Comment: This is amazing - thank you!! Indeed a general result, and one that also nicely answers my question :)
Comment: Sensible (although I didn't expect it until you mentioned it) that there is the possibility of a non-zero minimum entropy. (+1)
Comment: @Galen That gave me some trouble ;-).  I initially solved this by observing that the map $f\to(1+f)/2$ on the normalized space is a contraction on the complete metric space $\mathcal L^1(\Omega,\mu),$ which therefore has a unique stationary point, but I also needed this map to *increase* the entropy.  What I find interesting is that by normalizing the space we guarantee the differential entropy always is nonnegative and is zero only for the uniform distribution. In this fashion the differential entropy on such spaces becomes almost as nice as the entropy on discrete spaces.
Comment: @Galen Yes.  My resource for that is Rosenlicht's [Introduction to Analysis](https://www.maa.org/press/maa-reviews/introduction-to-analysis).  (It, along with Spivak's [Calculus on Manifolds](https://en.wikipedia.org/wiki/Calculus_on_Manifolds_(book)), was the textbook for my first college math course.)
Comment: @Galen I can't find it on my shelves right now, but likely the first part of Chapter VIII on fixed point theorems is what I was recalling.
Comment: @whuber That's clever. Is that via [BFPT](https://en.wikipedia.org/wiki/Banach_fixed-point_theorem)?
Comment: @whuber I have Rosenlicht's book beside me at this very moment! Relevant passages?
Comment: @whuber Thanks! Got it! Page 170 of chapter VIII.


Adicionar uma classe "active" no link de acordo com a página acessada?

Question: Estou montando um tema para WordPress, e preciso adicionar uma classe active nas âncoras, o funcionamento é o seguinte:
Eu recupero a URI da página atual e comparo com o texto/valor contido dentro da âncora que é trazida automaticamente pela função wp_list_pages( 'title_li=' ) do próprio WP. Se a condição retornar true, ele adiciona a classe active, segue o código completo.
HTML:

        <?php wp_list_pages( 'title_li=' ); ?>

JavaScript:
var uri = window.location.pathname.substring(1);
var sidebar = $('.sidebar.manual');
uri.replace('/', '');

sidebar.find('.sidebar.list li > a').each(function() {
    var linkValueTreated = $(this).text().split(' ').join('-').toLowerCase();
    if (uri == linkValueTreated || uri == '') {
        if (uri == '') uri = linkValueTreated;
        $(this).text(linkValueTreated).attr('class', 'active');
    }
});

Answer: O WordPress já faz isso. Ele adiciona a classe .current_menu_item na opção que corresponde a página atual. Então basta você usar algo assim:
add_filter('nav_menu_css_class' , 'my_special_nav_class' , 10 , 2);
function my_special_nav_class($classes, $item){
    if( in_array('current-menu-item', $classes) ){
        $classes[] = 'active ';
    }
    return $classes;
}

Answer: Depois de várias tentativas finalmente consegui fazer os links funcionarem. O grande problema na realidade era que eu não estava conseguindo alterar o estado da variável uri, devido ao fato dos tipos primitivos em JavaScript serem imutáveis.
Por esse motivo, o interpretador fazia o replace dela (que posteriormente foi substituído pelo split & join), porém, descartava a modificação, e a variável voltava a seu estado inicial. Segue a minha solução abaixo:
var sidebar = $( '.sidebar.manual' );
sidebar.find( '.sidebar.list li > a' ).each(function() {
    var uri = window.location.pathname.substring( 1 );

    // Armazena em uma variável o estado (já modificado) da variável "uri".
    var uriTreated = uri.split( '/' ).join( '' );

    // Trata o valor dentro de cada item da lista
    // referenciando-as como se fossem ID's.
    var linkValueTreated = $( this ).text().split( ' ' ).join( '-' ).toLowerCase();

    // Se estiver acessando a HOME (devido ao fato da URI retornar "/"
    // e a variável "uriTreated" tratar isso removendo a "/" por "")
    // adicione a variável "uriTreated" um valor referenciando
    // a ID da lista trazida pelo WordPress.
    if ( uriTreated == '' ) uriTreated = 'bem-vindo';

    // Se a URI for igual ao nome do item da lista
    // adicione uma classe "active" no link que é
    // referenciado por $( this )
    if ( uriTreated == linkValueTreated ) {
        $( this ).attr( 'class', 'active' );
    }
});


Vector space span by one-to-one function

Question: Consider $f$ be a one-to-one function from $\Bbb R$ to $\Bbb R.$ the question

Can $f$ form a basis?

if so , $V=\text{span}_{\Bbb Q}(f)$ would be $1$-dimensional vector space. Notice that basis does not contain $0.$ So, we can take $f(x)=e^x$, from example. Is that right ?
Comment: "Can $f$ form a basis?" doesn't make sense until a vector space containing $f$ as an element is specified.
Comment: @AndrewD.Hwang, thank for your comment and your right. I think I should ask like that . Is there a 1-dimensional vector that spans by a one-to-one function? Is it clear now ?
Answer: Yes. More generally, any nonzero singleton in any vector space forms a basis of some subspace.


Cant return an element in react-native

Question: In my new react native app, I can't write the following code.
  renderContent = () => {
    let content = null;

    content = <View><Text>HI</Text></View>;
    return content;
 }

I use this inside the render() like this.
render() {
  {this.renderContent}
}

It gives me the following error.
Functions are not valid as a React child. This may happen if you return a Component instead of  from render. Or maybe you meant to call this function rather than return it.
my RN version is 59. I used this pattern successfully in version 54. What am I doing wrong here?
Comment: should do `render(){ return this.renderContent() }`
Answer: You have to follow this format:
render(){
    return this.renderContent()
}

{something} is for jsx. For example for this:
return(
    <View>{something}</View>
)

Cant return an element in react-native


Rescale x-Axis in surf plot

Question: I have a 1024 by 100 matrix. When I use the function surf it plots the data with axis limit 0 to 1024 for x, 0 to 100 for y and the entries of the matrix as z values (as expected).
Now I want to keep everything in the plot the same, except for the x axis limits: I want to have them from 400 to 1000 i.e. I want to rescale the x axis. I don't want to start at the 400th entry and stop at the 1000th. I want to have the first entry to correstpond to 400 and the last one to 1000th. In other words change only the labels of the x axis to go from 400 to 1000 and not from 0 to 1024. Is there a simple way to do that or do I need to use meshgrid?
Comment: Can you try to shorten all that to a sentence and an image? You can set the axes properties easily and use the function `axes` for limits. what of that are you having trouble with?
Comment: When I use axis([Xmin Xmax Ymin Ymax Zmin Zmax]) it plots only the entries between these limits. I just want to change my x axis to have 400 as beginning and 1000 as max value.
Comment: Can you describe the difference between "only show this values" and "not show the other values"? I am not sure if I get it. Do you want to change the `xlabel` and `xtick`?
Comment: The numbers on my x axis should not be going from 0 to 1024 but from 400 to 1000. I could do it in paint but I am looking for a more adequate way to do it.
Comment: I can't upload an image for some reason. I get "Failed to upload image; an error occured at imgur".
Comment: I am not sure about the quote. Which part of the post does it refer to? I can't find it.
Comment: So you want the data to be from  0 to 1024, but the axis labels only to label part of it? Or you want only the data from 400 to 1000 be shown? Its not very clear what you need
Comment: I want all the data. X values should go from 400 to 1000 i.e. first value in the plot should have the label 400 instead of 0 and the last one should have 1000 instead of 1024.
Comment: I hope this link works: https://ibb.co/dRwDQe
I want the plot to stay exactly as it is, just change the x axis labels
Comment: So, coming back to my first comment: What is your problem with changing axis proerties? a quick google to "change x labels matlab" gives [a nice tutorial](https://uk.mathworks.com/help/matlab/creating_plots/change-tick-marks-and-tick-labels-of-graph-1.html). Why does that not work?
Comment: I tried using different Xticks but I end up with the ticks between the 400th and 1000th entry only. So from 0 to 400 I have no x axis labels and then I have them up to 1000. That's not what I want. I want to replace the x labels and keep everything the way it is. Can I do this with Tick values (and not manually for every single one)?
Comment: Yes, read the tutorial. You want to chagne `xticklabels` but not `xticks`
Comment: I get an error "Undefined function 'xticks' for input arguments of type 'double'." Probably because it's a surf plot and not a normal 2d plot?
Comment: Read the link. If you do not want to, then you will not get the answer. Good luck.
Comment: The link doesn't really help as I get an error when I try to do what the article says. It would probably work for a 2d plot but not for my case.
Comment: Thanks for your effort. obchardon answered the question allready. Good luck mate.
Answer: You probably want something like this:
%Example data
[X,Y] = meshgrid(1:0.1:8,1:0.1:8);
Z = sin(X)+cos(Y);
%Example plot
surf(X,Y,Z)

%We change the XTick Labels
xt = get(gca,'XTick'); %get the actual xtick value
xl = arrayfun(@num2str, linspace(400,1000,length(xt)), 'Uniform', false).';
set(gca,'XTickLabel',xl) %set the news xtick labels.

With set(gca,'XTickLabel',your_cell_of_string) you can change the actual XTickLabel with some news string, xl and xt must have the same size.
Comment: @Rosen: changing the `XTickLabels` is not necessary if you pass the right `X` and `Y` arrays to `surf`. Read the docs to `surf`.
Comment: It's just how I get my data. I have 1024 pixels on a detector and from the first to the last I get light with wavelength between 400 and 1000 nm. So after 100 measurements I get one big 1000X1024 matrix in the format the detector gives it. Then I just use surf(matrix) without defining X, Y mesh. Can you link the docs describing how to do it directly - without making X,Y arrays?

Rescale x-Axis in surf plot