Prove that $U(n)$ has no nontrivial normal subgroup except $Z(U(n))$.

Question: I've been reading Naive Lie Theory by John Stillwell, and this is the first exercise that has started to feel hopeless. It is exercise 7.5.3. I was trying to use the strategy that was used earlier in the book for proving the simplicity $\mathfrak{sl}(n,\mathbb{C}), \mathfrak{su}(n), \mathfrak{so}(n),$ and $\mathfrak{sp}(n)$, now slightly altered since $\mathfrak{u}(n)$ is not simple. The section is about the Tangent Space Visibility Theorem which states that if $G$ is a path connected Lie group with a discrete center and a nondiscrete normal subgroup $H$, then the tangent space of $H$ at the identity is nontrivial, with the corollary that if $H$ is a nontrivial normal subgroup of $G$, then it's tangent space at the identity is a nontrivial ideal of $G$'s tangent space at the identity. Of course, $Z(U(n))$ is not discrete, so the theorem does not apply; it relies on finding a neighborhood of the identity that contains no elements of $Z(G)$ except the identity. The next paragraph thus may be pointless but I can think of no other approach.
So, assuming this is the correct route, we get a nontrivial (oh, and I've interpreted nontrivial here to mean "nondiscrete and not $U(n)$ itself" since otherwise there are the roots of unity which is a normal subgroup) subgroup $Z(U(n))$ from the ideal spanned by $\mathbb{i}I$, which commutes with every complex matrix and thus its Lie bracket with any skew-Hermitian matrix is $0$ and we can't get any elements not generated by this one dimensional basis. As in the simplicity proofs, I begin with some $X\in\mathfrak{u}(n)$ that is not in the ideal spanned by $\mathbb{i}I$. Let $A=E_{ij}$ be the matrix with all 0 entries except $a_{ij}=1$ and $a_{ji}=-1$ and $B=\tilde E_{ij}$ be the matrix with all 0 entries except $b_{ij}=b_{ji}=1$. Find some $x_{ii}\ne x_{jj}$, which must exist, since otherwise we are in the ideal that is the tangent space of $Z(U(n))$. Compute $[X,E_{ij}]=(x_{ii}-x_{jj})\tilde E_{ij}$ and $[X,\mathbb{i}\tilde E_{ij}]=(x_{ii}-x_{jj})\mathbb{i}E_{ij}$, which gives us basis elements $\mathbb{i}\tilde E_{ij}$ and $E_{ij}$. We can "translate" an $E_{ij}$ to get basis elements at other non-diagonal entries, with $ [E_{ki},E_{ij}]=E_{kj},[E_{ij},E_{j\ell}]=E_{i\ell},[\mathbb{i}\tilde E_{ki},E_{ij}]=\mathbb{i}\tilde E_{kj},$ and $ [E_{ij},\mathbb{i}\tilde E_{j\ell}]=\mathbb{i}\tilde E_{i\ell}$, and something similar can be done if the basis element you start with is $\mathbb{i}\tilde E_{ij}$. We can finally get $n-1$ more basis elements by Lie bracketing $[E_{in},\mathbb{i}\tilde E_{in}]=-2\mathbb{i}(\tilde E_{ii}-\tilde E_{nn})$ as in the simplicity proof for $\mathfrak{su}(n)$ where the trace was required to be 0. Any imaginary scalar matrix would suffice as a final basis element, but I am unsure how to arrive at one, and even if I did, I am unsure how I would apply the section's proof, yet I am do not know how else I could approach this problem if I cannot apply the proof. I'd like any insight on this problem as I feel I've spent too long thinking about it for a textbook exercise, yet it doesn't seem like I'll be able to solve it without help. $U(n)$ has not been talked about as much as the groups with simple ideals, but it was important in the complexification section where it was shown that $\mathfrak{gl}(n,\mathbb{C})=\mathfrak{u}(n)+\mathbb{i}\mathfrak{u}(n)$, though I don't see how this would be relevant.
This is a duplicate of Normal subgroups of $U(n)$, I will note, which is in turn labelled as a duplicate of another problem; however, as the poster of that question notes, it really should not have been labelled a duplicate as the linked question there instead asks about $SU(n)$, which has a simple Lie algebra. So, the first person to ask this question never had it answered. This is my first question here but I hope it meets the criteria. I will appreciate any help but I am looking for an answer within the scope of this book, which focuses exclusively on matrix Lie groups, and so everything written in it uses methods and ideas that are intended to be used with matrix Lie groups. This is my first experience with Lie groups and I may not understand the reasoning behind a more general proof that applies to all Lie groups, namely this one, but cannot be proven with the linear algebra methods of this book.
Answer: The exercise has a typo, I assume, since it directly contradicts Exercise 5.5.2 from the same book. $U(n)$ has a normal subgroup, namely $SU(n)$. I guessed originally that the exercise was to prove that $SU(n)$ has no normal subgroups other than those contained in $Z(SU(n))$, but this is proved earlier in the section.
So I have no idea now what the author wanted to ask. Since $SU(n)$ is a normal subgroup of $U(n)$, the kernel of the determinant map, there are normal subgroups of $U(n)$ containing $SU(n)$ as well.
Comment: Even the updated wording is not completely correct (unless $n$ is prime): any subgroup of the center is normal.
Comment: @JasonDeVito This is absolutely true. Updating...
Comment: Now I read the rest of that section, it's already proved that normal subgroups of $SU(n)$ are central. So I have no idea what the author was asking for.
Comment: Huh. You are right and I had already done that exercise exactly as you said. I had interpreted nontrivial differently than the author usually does, as meaning no proper subgroups that weren't contained in the center, since I noticed the problem was obviously wrong otherwise, but I hadn't considered $SU(n)$ itself, just $Z(SU(n))$. I'll skip this problem then and stop letting it take up space in my mind. I guess my feeling that the problem didn't seem to fit in this section due to having a nondiscrete center was justified. Thank you!


How to use awk to cut out a string ="" in different columns per line

Question: So I have 1000s of lines where it looks like below:

    A="10" B="20" C="20"
    A="10" B="20" C="20"
    A="10" C="20" D="20"
    C="10" D="20" A="20"

I want to pull out all the C="X" , also I may possible need to find what A="X" also at some point.  The above is a shorten sample, but it maybe easily dozens of columns and it is all over the place.
I think awk would be better than cut, but haven't quite figured out the best way to pull that information.
Thanks
Comment: For the `C="X"` example, what should the output look like?
Comment: Can you explain why do you think `awk` is *better* than `cut` here? Have you also searched for other alternatives? Can you show what you have tried so far? Did you at least tried to get familiar with `awk` and even `cut` ?
Comment: I would be ok with C="X" or just "X".
Comment: @hek2mgl - i only know how to use cut with -d and -c , which in this case would be hard since I am not able to determine the column per line.
Answer: It seems like grep will do:
grep -o 'C="[0-9]*"' file

Output:
C="20"
C="20"
C="20"
C="10"

Comment: You just blew my mind, I didn't even think of that path.
Answer: awk '{s="";for (i=1;i<=NF;i++)if($i~/^(A=|C=)\"/)s=s?s FS $i:$i; print s}' file
A="10" C="20"
A="10" C="20"
A="10" C="20"
C="10" A="20"

Comment: I just tried it, works great.  Ah I have a much better understanding of how to pull that type of data!.
Answer: Only a sed implementation is missing. Here it is:
sed -n 's/.*C="*\([0-9]*\)".*/\1/p' file

It returns only the Xs
Comment: Thanks, I will keep this in mind for next time also.
Answer: Here's another awk possibility.
awk '{
     delete a
     for(i=1; i<=NF; ++i)
       a[substr($i, 1, 1)] = int(substr($i, 4))
     print a["A"], a["C"]
}' file

This gathers all the letter/value pairs, storing the values as actual integers (without quotes) in an associative array keyed by the letter. This allows you to print them out any way you want. For example, you can print them in alphabetical order no matter what the original order (although the original order is forgotten).


Geolocation module - how to call abstract class method properly

Question: I'm using the custom module in my project, and it was working fine with Geolocation 1.11 module.
After I've updated Geolocation to 3.7 my custom module stopped working.
What I've found - my custom module was using trait from 'GoogleMapsDisplayTrait.php' and now it is missing in Geolocation. It was like that
class LocationsMapBlock extends BlockBase {

  use GoogleMapsDisplayTrait;

  public function build() {
    return [
      '#theme' => 'locations_map',
      '#attached' => [
        'library' => ['location/map'],
        'drupalSettings' => [
          'geolocation' => [
            'google_map_url' => $this->getGoogleMapsApiUrl(),
          ],
          'locations' => $this->getLocationMapData(),
        ],
      ],
    ];
  }
}

I've found that now most similar class to trait GoogleMapsDisplayTrait) is inside geolocation_google_maps submodule of geolocation module.
But now it's not a trait, but abstract class with the same methods as previous trait was.
abstract class GoogleMapsProviderBase extends MapProviderBase {
...
}

I've tried to add this class:
use Drupal\geolocation_google_maps\GoogleMapsProviderBase;

But now I'm receiving the error
'Error: Call to undefined method Drupal\location\Plugin\Block\LocationsMapBlock::getGoogleMapsApiUrl() in Drupal\location\Plugin\Block\LocationsMapBlock->build() (line 32 of modules/custom/location/src/Plugin/Block/LocationsMapBlock.php).'
My PHP knowledges is to weak to find the solution...
Answer: The undefined function getGoogleMapsApiUrl() is, maybe the file is missing?
Check if the file exists:
/modules/geolocation/modules/geolocation_google_maps/src/GoogleMapsProviderBase.php

Try to install and enable the following modules for a cleaner working with geolocation - specially for the geolocation_google_maps:
geofield
geolocation_geofield
geolocation_google_maps

Try using this call instead of $this->getGoogleMapsApiUrl():
Drupal::service('plugin.manager.geolocation.mapprovider')->getMapProvider('google_maps')->getGoogleMapsApiUrl()


Spring + Hibernate

Question: Bom dia!
Estou estudando Spring MVC, Maven e Hibernate.
Na estrutura do projeto criado com Maven, onde coloco o arquivo applicationContext.xml ?
Obrigado.
Answer: O arquivo pode ficar no diretório WebContent/WEB-INF/.
Outras boas opções são WebContent/WEB-INF/classes/ ou src.

Spring + Hibernate


Formal justification of piecewise definition

Question: Let f be a function from A to C, and let g be a function from B to C, and suppose further f and g agree on the intersection of A and B. There exists a function h, namely the set-theoretic union of f and g, such that h(x)=f(x) if x is in A, and h(x)=g(x) if x is in B. My question is, is this the only function on A union B with this property? In other words, is there formal justification for defining functions piecewise?
Answer: Functions are defined to be equal if they agree on all inputs (and have the same domain and range).  If you prescribe the function's value on all elements of the domain, there can therefore be only one function that takes these values.
Answer: It is the only function that meets the criteria. I don't understand what you mean by "formal justification".


how to sort list of tuples within a list?

Question: I want to sort lists of tuples of mathematical operators (stored as strings) and their index, in order of precedence (*,/,+,-), while retaining their original index. There are thousands of lists of tuples within my list.
E.g.
my_lists = [[(0,'*'),(1,'+'),(2,'-')],[(0,'-'),(1,'*'),(2,'*')],[(0,'+'),(1,'/'),(2,'-')]]

should become:
new_list = [[(0,'*'),(1,'+'),(2,'-')],[(1,'*'),(2,'*'),(0,'-')],[(1,'/'),(0,'+'),(2,'-')]]

I've tried using the 'sorted' built in function and storing the precedence in a dictionary.
priority = {'*': 0, '/': 1, '+': 2, '-': 3}

new_list = [sorted(item, key = priority.get) for item in my_lists]

This produces the same original list.
How do I access just the operator part of the tuple whilst sorting the list of tuples?
Comment: What did you try? Show your approach, and others may help you to get it done, but StackOverflow is not a coding service...
Answer: You are sorting using the whole tuple as key, such as (0, '*'). You have to use the second part of it only (i.e. x[1]):
[sorted(item, key = lambda x: priority.get(x[1])) for item in my_lists]

returns
[[(0, '*'), (1, '+'), (2, '-')],
 [(1, '*'), (2, '*'), (0, '-')],
 [(1, '/'), (0, '+'), (2, '-')]]

Your code didn't throw an error, because priority.get((0, '*')) is legal and returns None, which is perfectly sortable in Python 2.7 and keeps the list in its original order.


What is the actual use of toContain() in expect?

Question: As we all know expect replaced with jest. Some property of expect also changes. One of them is toContain which was known as toInclude. You will find it here : https://github.com/skovhus/jest-codemods/blob/master/src/transformers/expect.js
My problem is when i am trying to use toContain in order to check whether a object match with another object,it showing me error. But earlier with toInclude it was just one line code. So as a replacement of toInclude I find it different,not exact the same.
This array works fine.

expect([2,3,4]).toContain(4);

But when i go with object,this error come up

 expect({
        name : 'Adil',
        age : 23
    }).toContain({
        age : 23
    });

This is the error
Error: expect(object).toContain(value)
Expected object:

{"age": 23, "name": "Adil"}
To contain value:

{"age": 23}

Answer: .toContain is for checking that an item is in an array
If you want to check the value of an object's property then you can use .toHaveProperty - here are the docs
so your example would be
expect({
    name : 'Adil',
    age : 23
}).toHaveProperty('age', 23);

... or to avoid learning another matcher you could just do:
expect({
    name : 'Adil',
    age : 23
}.age).toBe(23);

Comment: Can toHaveProperty() check multiple object? I was unable to do it. So,I used toMatchObject() for that purpose.By the way toMatchObject() is used to match object,not array.How to match array? In previous version,toInclude served both object and array.
Comment: I don't think so but you can always have several expect statements
Comment: Okay mate. What about matching array,any suggestion?
Comment: You can use .toContain for arrays
Answer: From the documentation (highlights from me):

Use .toContain when you want to check that an item is in an array. For testing the items in the array, this uses ===, a strict equality check. .toContain can also check whether a string is a substring of another string.

So in summary, it tests if an array contains some value(s) or if a string contains a given chain of characters.
To test objects like in your example, you can use:
expect({ name : 'Adil', age : 23 }).toHaveProperty('age', 23);

Comment: It's showing
TypeError: Cannot read property 'have' of undefined
Comment: This one works fine.. expect({
    name : 'Adil',
    age : 23
}).toHaveProperty('age', 23);
Answer: Its used when you want to check the existence of an item within an array. Its similar to python's x in [1,2,3]. Note that it will not give you the index of the first occurrence. It will just return a boolean


Navbar buttons not showing on mobile

Question: I have a very simple page which is made of a navigation bar and some buttons. However, these buttons are not showing when I visit the page using a mobile device.
I have checked several threads such as this and this this, but I can't see where is my problem.
Fiddle link
Code:
<!DOCTYPE html>

    <title>Flask Template Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen">

      My API

Test

Endpoints

Information

Hello

Thanks
Answer: You forgot to include to code that shows the collapsible navbar menu:
replace:

  My API

with:

    My API
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>

Navbar buttons not showing on mobile


Is gmtime() affected by daylight savings?

Question: My local time zone is EDT.  I have a time stamp: 29 Aug 2003 04:18:52, which I have converted to a time_t value using mktime(), with tm_isdst set to -1.  The time_t value is 1062145132.  When I run gmtime() with this value, I get 29 Aug 2003 09:18:52.  Looking at the struct tm returned from gmtime(), the value of tm_isdst is 1.  Why isn't this time 08:18:52 instead?  Isn't gmtime supposed to be equivalent to UTC, without any daylight savings dependence?
I have used bash as follows:
<code>date --date=@1062145132
Fri Aug 29 04:18:52 EDT 2003
TZ=UTC date --date=@1062145132
Fri Aug 29 08:18:52 UTC 2003
</code>
The above shows the expected 4 hour difference between EDT and UTC.  Why doesn't gmtime() show the same difference?
Answer: I found my problem.  In between the call gmtime(&tmgmt) and the output of asctime(&tmgmt), I had a call to mktime(&tmgmt).  I had not realized that mktime would possibly change the values in the structure, so that the values I printed out were not those returned from gmtime().


How can I add condition min only 3 character when search on the autocomplete?

Question: My template like this :
<v-autocomplete
        v-model="model"
        :items="items"
        :loading="isLoading"
        :search-input.sync="search"
        chips
        clearable
        hide-details
        hide-selected
        item-text="name"
        item-value="symbol"
        label="Search for a coin..."
        solo
      >

My component like this :
watch: {
    search (val) {
      // Items have already been loaded
      if (this.items.length > 0) return

      this.isLoading = true

      // Lazily load input items
      fetch('https://api.coinmarketcap.com/v2/listings/')
        .then(res => res.json())
        .then(res => {
          this.items = res.data
        })
        .catch(err => {
          console.log(err)
        })
        .finally(() => (this.isLoading = false))
      }
  },

My codepen and demo like this :
https://codepen.io/positivethinking639/pen/GRgGJNN?editors=1010
I try add : if(val.length >= 3) { ... } ,
but there exist error :
[Vue warn]: Error in callback for watcher "search": "TypeError: Cannot read property 'length' of null"

How can I solve this problem?
Answer: I couldn't get the error, when adding the length check like so
watch: {
  ...
  search (val) {
    // Items have already been loaded
    if (this.items.length > 0) return

    if (val.length < 3) return;

    this.isLoading = true

    // Lazily load input items
    fetch('https://api.coinmarketcap.com/v2/listings/')

If you are checking length somewhere else, the Cannot read property 'length' of null error could be fixed by enhancing the expression like this:
if (val && val.length >= 3) { ... }


JQuery Onclick clear action value before submitting

Question: I have a form:
<code><form id="Myform" action="something here" method="post">

...

<input type="image" src="submit.png" id="mysubmit" name="submit" />
</code>
What I need the action value of the form to cleared before it submits.
How could I do that in JQuery?
Comment: Why are you setting an action that you don't want to submit to in the first place?
Comment: Maybe $('#MyForm').attr('action','');
Answer: <code>$("#Myform").submit(function(){
   $(this).attr("action","");
});
</code>
Answer: I think what you are looking for is
<code>$('MyForm').on('submit', function(){
    $(this).attr('method', '');
});
</code>
Comment: onsubmit should be submit & method should be action
Comment: I think it must be `$('#MyForm')`. Do we have `onsubmit` event in jQuery?


What microphone is suitable for recording voice and acoustic guitar?

Question: Recently I've been performing several songs along with my acoustic guitar, so I'd like to record them. At most I've succeeded in recording myself with a phone, but I get this really masked sound.
As far as I know, what should I do to get a better quality than a masked phone sound?

Record both voice and instrument with only a microphone
Get a microphone for voice and connect guitar through audio interface
Comment: Or you could use two microphones...
Comment: I answered this same question, but about piano and voice, here:  https://music.stackexchange.com/questions/55101/how-do-i-record-piano-and-voice-music-to-the-best-of-quality/56106#56106
Answer: If you want to record both voice and acoustic guitar you might want a large diafragm microphone. A good one for a nice price can be the the NT1-A from Rode for example, or the Audio-Technica AT 2035. You have many options around 120-200€.
In my case, I use a L.R.Baggs M1 for my acoustic guitar (mine doesn't have a preamp) and complement the sound with an SE Electronics SE 2200a II, both connected to a Roland Octa-Capture USB interface.
Answer: I believe that if you have the chance to connect your guitar directly to your interface and record your voice separately, that would be the best way to go.
Otherwise, the previous option seems to be the best.
Good luck and please share your experience when ready.
Comment: For sure it seems the best one, but I'm worried about if it may is complex to process the audio output. Thanks for answering!


What happened to Mephisto?

Question: So, since starting working in Ruby I've run across tons of sites (example), SO questions (example), blog posts etc, that point to a "Ruby CMS" called Mephisto, using this address: http://www.mephistoblog.com/
That address is just some guy's blog with the last entry almost 3 years old. Clearly this is a dead project, but from the number of references to it in the wild I can't for the life of me find any information about what it was, why it mattered, and why it died.
Can anyone fill me in?
Lastly, I know this is only 'sort of' a ruby question... if there's a different stack exchange site I should have posted this on please let me know politely and I'll be happy to move it :) Thanks.
Comment: I'm voting to close this question as off-topic because it is not about programming as defined in the [help].
Answer: It was a project mainly maintained by 'technoweenie' (who now works for github). Like many things from the early days of rails, it seems to have just slowly become defunct as people have moved on.
http://techno-weenie.net/2010/6/23/you-can-let-go-now/
Answer: Enki is an heir of Mephisto.  It is still a living project, and many Rails bloggers are using it.  However it is for hackers, and just gives you a very blank slate to work with style-wise.
Answer: You can find a version of Mephisto located right here: https://github.com/mephistorb/mephisto

What happened to Mephisto?


What does this result of calculating $\lim_{n\to\infty}A^n$ mean?

Question: Suppose a matrix $A=\begin{pmatrix}
a & b \\
a & 0
\end{pmatrix}$. I need to calculate $\lim_{n\to\infty}A^n$, so I started doing literally power by power to see a pattern, and this pattern emerges:
$$A^{n+1}=\begin{pmatrix}
(A^n_{1,1}+A^n_{1,2})a & A^n_{1,1}b \\
(A^n_{2,1}+A^n_{2,2})a & A^n_{2,1}b
\end{pmatrix}$$
At $n=\infty$ supposedly $n=n+1$ so I define $\begin{pmatrix}
x & y \\
z & t
\end{pmatrix}$ as $A^n=A^{n+1}$
so we have that
$$
\begin{pmatrix}
x & y \\
z & t
\end{pmatrix}=
\begin{pmatrix}
(x+y)a & xb \\
(z+t)a & zb
\end{pmatrix}
$$
or
$$
\left\{
\begin{aligned}
(x+y)a &= x\\
xb&=y \\
(z+t)a &= z \\
zb&=t
\end{aligned}
\right.
$$
simplifying we get to
$$
\left\{
\begin{aligned}
b+1&=\frac 1a\\
ab+a&=1
\end{aligned}
\right.
$$
Isolating $b$ in the first we have that $b=\frac 1a-1$; substituting on the second:
\begin{align}
a(1/a-1)+a&=1 \\
1-a+a=1 \\
1=1
\end{align}
The problem is I don't understand the result. Does this mean that $\lim_{n\to\infty}A^n$ is defined no matter what values $a$ and $b$ we have? What does it mean?
Comment: @Moo They are integers so they have two posible solutions.
Answer: Let $B:=\lim_{n \to \infty}A^n$ if this limit exists. You noted that such a limit must satisfy $BA=B$, so after some calculations you found $b+1=1/a$. Thus the limit can only exist if $a$ and $b$ satisfy that equation.
You said $a$ and $b$ are integers, and there are two solutions to $b+1=1/a$. In the one case you can calculate $A^2$ and recognize what will happen as you take higher powers of $A$. In the second case, you can look at the determinant of $A$ and note that $\text{det}(A^n)=\text{det}(A)^n$, which will tell you something about whether or not $B$ can exist.


How do I allow full HTML while rendering a view?

Question: Some HTML code like  is stripped out. How can I allow full HTML in a view?
    $options = array(
        'id' => 'area_text_custom',
        'table' => 'views',
        'field' => 'area_text_custom',
        'relationship' => 'none',
        'group_type' => 'none',
        'admin_label' => '',
        'empty' => TRUE,
        'tokenize' => FALSE,
        'content' => "My HTML Code with ",
        'plugin_id' => 'text_custom',

    );
    $view->setHandler('page_1', 'footer', 'area_text_custom', $options);

Answer: I've run into this same problem in the past, and I think your best option is to take care of this from a template.
Create an applicable template for your view (field, row, etc) and define your html in there. The template options/naming conventions aren't as clearly outlined in D8 as they were in D7, but here is the documentation page for Views templates. The comments have some helpful links and naming conventions for different types of templates depending on your needs.
Since it seems like you're trying to add your iFrame to the View's footer, you'd probably want to use the views-view.html.twig template. Naming conventions for this template are:
views-view--foobar--page.html.twig
views-view--page.html.twig
views-view--foobar.html.twig
views-view.html.twig

You'll want to copy /your_site_root/core/modules/views/templates/views-view.html.twig into the templates (or templates/views) folder of your theme. You'll then want to print your custom code inside the  tags of the template.
If you need more flexibility with what gets printed in the template, you can send variables into your template using template_preprocess_views_view.
Answer: I would suggest having your view display "content" of type "teaser" which would then allow you to use a twig template file such as node--content-type--teaser.html.twig.
This way you can add whatever markup you want to the twig file... even iFrames.
If you must have fields, for instance in exposed filters combine, remember you can "force" use fields in views :)


Essential range and integral means

Question: I am looking at the notion of essential range, which is defined for a function $f:(X,\mu)\rightarrow \mathbb{C}$ as the set $R_f$ of points $z\in\mathbb{C}$ satisfying
$$\forall\epsilon>0, \mu(\{x\in X:|z-f(x)|<\epsilon\})>0.$$
I consider the case where $f\in L^{\infty}(\mu)$. In this case, let's consider the set $A_f$ of complex numbers of the form
$$\frac{1}{\mu(E)}\int_E f\ d\mu,$$
where $E$ is a measurable set satisfying $0<\mu(E)<\infty$.
I conjecture that

$A_f$ is included in the convex hull of $R_f$.

I have first proved that $\mu(X-f^{-1}(R_f))=0$, so that each element of $A_f$ is actually a ''mean'' over a set $E\cap f^{-1}(R_f)$, comprised of elements mapped into $R_f$. This convinces me that $A_f$ is included into the convex hull of $R_f$, but I can't manage to prove it. Is there a simple or elegant way to come to the result?
NB: I also proved that $R_f$ is compact with supremum $\|f\|_{\infty}$, may it be useful...
Answer: Let's prove that there exists $\alpha\in R_f$ such that $\alpha\geq A_f$.
Suppose that this does not happen. Let $b=\|f\|_{\infty}$, then $A_f\leq b$. Consider the closed interval $[A_f,b]$. For any $z$ in it, there exists $\varepsilon_z>0$ such that the set $$\{x\in X\big| |z-f(x)|<\varepsilon_z\}=f^{-1}\left(B(z,\varepsilon_z)\right)$$ has measure zero, since any $z\in[A_f,b]$ is not in $R_f$. Then the balls $B(z,\varepsilon_z)$ form an open cover of $[A_f,b]$, which is compact, therefore there exist finitely many $z_1,\dots z_n\in[A_f,b]$ such that the balls $B(z_i,\varepsilon_{z_i})$ cover $[A_f,b]$. Therefore, $$[A_f,b]\subseteq\bigcup_{i=1}^nB(z_i,\varepsilon_{z_i})\Rightarrow f^{-1}\left([A_f,b]\right)\subseteq\bigcup_{i=1}^nf^{-1}\left(B(z_i,\varepsilon_{z_i})\right),$$ from which you see that $f^{-1}\left([A_f,b]\right)$ has measure zero. Therefore, $f(x)<A_f$ almost everywhere, so $$0=A_f-\frac{1}{\mu(E)}\int_Ef\,d\mu=\frac{1}{\mu(E)}\int_E(A_f-f)\,d\mu,$$ and since $A_f-f>0$ almost everywhere, you get a contradiction. So, there exists $z\geq A_f$ such that $z\in R_f$.
If $z=A_f$, you are done. If not, then $z>A_f$, and you can show similarly that there exists $w\leq A_f$ such that $w\in R_f$. If $w=A_f$, you are done; if not, then $w<A_f$ and $A_f$ is a convex combination of $z$ and $w$, so $A_f$ is in the convex hull of $R_f$.
Comment: I think that you can then modify the proof as follows: if $A_f$ is not in the convex hull of $R_f$, then you separate them by a line (this is a theorem of functional analysis), and you proceed as above; show then that $f$ should be on the one side of the line almost everywhere, while $A_f$ is on the other, and that will give a contradiction.
Comment: I actually defined $A_f$ as the set of all ''integral means'', but I understand you take it as a particular integral, that's fine. However, your proof seems to suppose that $f$ is real-valued, but I want to prove it also in the more difficult case where is is complex-valued!
Comment: Right, I see the point, you basically return to the real case by projecting along the normal of a line which strictly separates $R_f$ and the integral.

Essential range and integral means


A question on limits

Question: $$\lim_{x\to\infty} (a^x)/(a^x+1)$$
I want to solve this using only concepts of limits not integration or differentiation, but I am not able to figure out how to start
Comment: It's important to know what $a$ is.
Comment: What about cancelling out $a^x$ ?
Comment: @TedShifrin a>0
Comment: The answers will be different if $a<1$, $a=1$, or $a>1$.
Comment: @TedShifrin So I need to take all the cases
Answer: If $0<a<1$, then as $x \to \infty$,
$$
0<\frac{a^x}{a^x+1}\leq a^x \to 0
$$
If $a>1$, then as $x \to \infty$,
$$
\frac{a^x}{a^x+1}=\frac{1}{1+\frac1{a^x}} \to 1.
$$

A question on limits


Output screen show the totally white , nothing output are comming

Question: i want to get the output on  this code.
when m try to run this code this shows  only a white screen doesn't know why
m putting the code here
// first page  find the code easliy App main page this is.

import React {} from react;
import About from './component/About';
import Navbar from './component/Navbar';
import TextFrom from './component/TextFrom';
import {
  BrowserRouter,
   Router,
   Route,
   Routes,
} from "react-router-dom";

function App() {
  const [mode, setMode] = useState('light');//wheather dark mode is enabled or not
  const [alert, setAlert] = useState({
    msg: "",
    type: ""
  });
  // we define a setalert methode for pass the value//
  const showAlert = (message, type) => {
    setAlert({
      msg: message,
      type: type
    }) //here Alert is a object
    setTimeout(() => {
      setAlert(null);
    }, 1500);

  }
  const toggleMode = () => {
    if (mode === 'light') {
      setMode('dark')
      document.body.style.backgroundColor = '#14142c';
      showAlert("Dark modeis enabled", "success");
      document.title = 'TextUtils-Dark Mode';
      // setInterval(()=>{
      //   document.title="TextUtils is Good"
      // },3000);
      // setInterval(()=>{
      //   document.title="Done By Ali"
      // },1000);
    }
    else {
      setMode('light')
      document.body.style.backgroundColor = 'white';
      showAlert("light mode  is enabled", "success");
      document.title = 'TextUtils-Light Mode';
    }
  }

  return (
    <>
    <BrowserRouter>
    <Router>
      <Navbar title="TextUtils" mode={mode} toggleMode={toggleMode} />
      <Alert alert={alert} />

      <Routes>
        <Route path="/about">
            <About />
          </Route>
          <Route path="/">
            <TextFrom showAlert={showAlert} heading="enter the text value" mode={mode} />
          </Route>
        </Routes>

      </Router>
      </BrowserRouter>
    </>
  );
}

export default App;

//Page seond also m puthing here//
this show only error in this page
import React from 'react'
import { PropTypes } from "prop-types";

export default function Navbar(props) {

  return (

<nav className={`navbar navbar-expand-lg navbar-${props.mode} bg-${props.mode}`}>

    {props.title}
    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Home

          About

          {props.aboutText}

      <form className="d-flex">
        <input className="form-control me-2" type="search" placeholder="Search" aria-label="Search" />
        <button className="btn btn-outline-success" type="submit">Search</button>
      </form>
      <div className={`form-check form-switch text-${props.mode==='light'?'dark':'light'}`}>
      <input className="form-check-input" type="checkbox" id="flexSwitchCheckDefault"onClick={props.toggleMode}/>
      Enable the Dark Mode

  )
}

Navbar.propTypes = { title:PropTypes.string.isRequired,
                    aboutText:PropTypes.string.isRequired

                  }
Navbar.dafaultProps ={
                  title:'Set title  here',
                  aboutText:'about text here '
}

please check the given code don't know why it not working  when m ran this website code in visual studio  then ran successfully  and showed a message in the console. window but when m open the browser then its nothing shows on the browser window.
Answer: You are using react-router wrongly. Have another look at the documentation
https://reactrouter.com/en/main/start/tutorial
I have provided a working example using your code, with some comments about what was incorrect. See here.
https://codesandbox.io/s/zealous-sun-q4ctsh?file=/src/App.js
Comment: still not working same issue is coming  full screen blank
Comment: I can't help you any further, the sandbox I linked worked. You can create a new question or update this one with your new code. Try to include any errors, escpecially any from the web dev console.


How to sign self-compiled Qt dll?

Question: Dlls in Qt official prebuilt are signed with Qt official certificate, but I compiled Qt opensource myself, I'm wondering how can I sign these self-compiled dlls, is it legal to sign these dlls with my own certificate and distribute them?
Answer: You can obtain a code signing certificate from a certificate authority (which will cost you a bit of cash, but it's not too bad) and then sign your custom compiled files with that certificate.
As far as I know that's perfectly legal (but I'm not a lawyer, so don't take my word for it - ask a real lawyer if it's important to you).

How to sign self-compiled Qt dll?


How do I show the publishing date instead of the creation date?

Question: When I create an article and I don't publish it, so I could edit the article later and publish it when it's finished, I notice Drupal shows the creation date, not the publishing date.
Is there a way to change it so the items on the front page show their publishing date and not the creation date? Is there a different field in the database for that functionality?
I am using the Workbench module, which gives draft nodes. If nodes are not published, it will display them in a draft list.
Comment: may be if you create a revision in contentype settings, this way you have a record on every change.
Comment: How to get published date?
Comment: @steniya from the node_revision table I suppose.
Comment: I checked with node, am getting only published date and changed date. If I take changed date, there is a issue. Suppose record "A" is created on Sept 10 and it is published on Sept 15, then I updated the record on Sept 25. It will display the date as Sept 25 but the record got published on Sept 15. How I can display Sept 15?
Comment: would it be acceptable to you to UPDATE the creation date at the time the node becomes published (with the publish-moment being used as creation date)?
Comment: another idea is using a flag and rules, another date field could be needed, flag node on "publish event", store that date, and do not change that date if node is already flagged.
Answer: The Publication Date module adds a field on every node that shows when a node was published.

The Publication Date module adds a "Published on" date for each node, containing the date when it was first published.
Without this, the only dates available for nodes are their created date and changed date, but these are often insufficient to meet the needs of publishing workflows. Sorting nodes by their created date doesn't account for content which is held in draft form for a time while being readied for publication. Sorting nodes by their changed date fails to account for content needing minor corrections after being published.

For nodes published before the module was installed, the module will use the node creation date, as the project page itself says.

For nodes that were published before the installation of this module, we can not know the exact date of publication, so <code>$node->published_at</code> will initially contain the creation date.
Comment: You can use this module for existing nodes. It will look for the right date.
Comment: I have 5000 records which are already created. This module is not applicable to those records. It can use in future. Am right?


Best way to notify UIInterfaceOrientation changes to other viewControllers

Question: I am looking for the best way to notify all the viewControllers of UIInterfaceOrientation changing that is detected in first-viewController added to mainWindow.
Do I have to NSNotification in the controller where these events are detected and other controllers will subscribe to that? Or there is any cleaner way?
Thanks for the help!!!
Comment: Posting an `NSNotification` seems fine to me.
Comment: I read somewhere on stackoverflow that UIDeviceOrientationDidChangeNotification is issued when orientation changes . So I will try that..
Answer: Add UIApplicationDidChangeStatusBarOrientationNotification in viewDidLoad which anyView you wanted to notify  would be better.
Answer: Your UIViewController already get rotation notification messages:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration

and
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

and also
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration

Comment: willRotateToInterfaceOrientation is deprecated.


How to reduce following expression

Question: I have following expression which I'm using in programming, but when value of $N$ and $M$ is very high it's taking long time to give result. Is there any way I can reduce this expression, so that I've to do less number of computations.
$$P = \sum_{i=1}^{R - 1} {N \choose i} \cdot {M \choose {R - i}} \cdot i \cdot (R - i).$$
Comment: Note $k{n\choose k}=n{n-1\choose k-1}$.
Answer: Note that (see Gerry Myerson's comment), for $1\leq i\geq R-1$,
$$\binom{N}{i}=\frac{N}{i}\binom{N-1}{i-1},\quad \binom{M}{R - i}
=\frac{M}{R-i}\binom{M-1}{R - i-1}.$$
Therefore
\begin{align}
\sum_{i=1}^{R - 1} \binom{N}{i} \binom{M}{R - i}  i  (R - i)&=
 NM\sum_{i=1}^{R-1} \binom{N-1}{i-1} \binom{M-1}{R -i-1}\\ &=NM\sum_{k=0}^{R-2} \binom{N-1}{k} \binom{M-1}{(R -2) -k}\\
&=NM\binom{N+M-2}{R-2}
\end{align}
where in the last step we used the Vandermonde's identity.

How to reduce following expression


Create Development Environment out of a Live Production Linux System?

Question: I have an Ubuntu 10.04 LTS server running production and I'd like to create a development and staging server. One option is to install everything the way it's installed on production, but this will take a lot of time to make it an exact mirror of production. Is there a way to "clone" the entire OS while it's running? I'd like to create the dev and staging server in VMWare.
Thanks!
Comment: If you truly have only partial backups and everything running on VMware Workstation, I wish you lots of luck!
Comment: You're not actually running a live production system on VMware Workstation, are you?
Answer: Yes, use VMWare's Converter tool.
Answer: Restore your backup into a fresh VM.
You do have a backup, don't you?
Comment: Then you don't have a backup, you have a bunch of data that might, with a whole pile of effort, might be used to restore service.
Comment: Then why don't you add the rest of our system to the backup? This will not only allow you to clone your system, but you'll also learn what to do in an emergency.
Comment: yes, but only of the data, databases and configurations. As it relies on varnish, nginx, php-fpm, django, mysql etc, I thought it would be a better idea to clone the system.
Answer: Its possible to cold clone (ie boot off a CD, P2V converter tool), such as http://www.vmadmin.co.uk/index.php/resources/38-converter. The vmware support forums are full of useful advise for such activities. I dont know of any 'hot' cloning tools, I would be interested to hear if you find one.
Answer: There's any number of options -- you can rsync the filesystem, dd the underlying block device over the network with netcat, or take a snapshot of the system at the vmware level and duplicate that somewhere else.
However, all of these scenarios suffer from the same basic flaw: it's one-shot deal.  Once you've made the clone, you can't automatically update it to take into account changes in production (well, in theory, the rsync method can be used, but it's finicky and very error prone).  This is why you need to use configuration management, like Puppet, Chef, or cfengine.  These systems allow you to define the exact state you want a system to be in, and the tools will take care of the configuration.  You can then specify "build all these systems the same way", and when you change the master configuration, all the machines will be updated to match the new setup.  Building new machines is then also a breeze, if you need to scale up, deploy a second infrastructure in another location, or whatever else takes your fancy.
Answer: For Linux systems, setting up a dock VM with a basic Linux installation, mounting the VMDK of the prepared empty target VM into the dock, formatting it there, quiescing the source system (read: shut the database down!), rsyncing (use --numeric-id and --exclude /proc/* and /sys/* , use -c if anything could be wrong about the clocks), then chrooting into the target filesystem, making changes required, and reinstalling the boot loader (hint: kill /dev/.udev while in chroot, then populate /dev with MAKEDEV generic), works very fine. grub-legacy would be the preferred boot loader to use (if target fs is ext3, format with -I 128 or things will break horribly! Also, junk device.map always..). If fixing a boot loader from inside chroot sounds far out of your comfort zone, better read up on that topic or leave it be ;)
Further updating of the environment can then be done with partial rsyncs and mysqldumps (acquaint yourself with the --dry-run option to rsync... --exclude is FINICKY)


Nginx 0.7.43 to proxypass a Wordpress site to Apache 2.4 + PHP 5.6

Question: I'm trying to use an existing nginx running on port 80, to proxypass towards Apache serving a Wordpress website.
nginx section added (some commented tests left intentionally, i tried so many versions sorry if it looks wrong):
upstream wordpress {
    server 127.0.0.1:5000;
}

server {
    server_name media.raw-news.net;
    access_log /home/plumi/PLUMI/plumi.app/var/log/wordpress-access.log;
    error_log /home/plumi/PLUMI/plumi.app/var/log/wordpress-error.log;

    #root /usr/local/apache2/htdocs/;

    location / {
        proxy_redirect off;
        proxy_pass http://wordpress;
        proxy_connect_timeout 75;
        proxy_read_timeout 185;
    }

 location ~ .*\\.(php)$ {

  proxy_pass         http://wordpress;
  proxy_redirect     off;

  proxy_set_header   Host             $host;
  proxy_set_header   X-Real-IP        $remote_addr;
  proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;

  client_max_body_size       10m;
  client_body_buffer_size    128k;

  proxy_connect_timeout      90;
  proxy_send_timeout         90;
  proxy_read_timeout         90;

  proxy_buffer_size          4k;
  proxy_buffers              4 32k;
  proxy_busy_buffers_size    64k;
  proxy_temp_file_write_size 64k;
 }

}

My Apache is running on port 5000 with PHP enabled (only relevant php stuff):
LoadModule php5_module        modules/libphp5.so

<IfModule dir_module>
    DirectoryIndex index.php index.html
</IfModule>

AddType text/html .php
AddHandler php5-script  .php

The effect right now is that:
Chrome: the Wordpress website is shown, but looks like no PHP code is executed.. i can only see the HTML part.
Firefox: browsing the Wordpress site causes redirect on 127.0.0.1 ...
Safari: It Works ! is displayed...
Strangely, on all browsers if i browse http://media.example.net/wp-admin and perform login.. i can enter the Dashboard and everything is displayed perfectly !
All images are there, PHP code gets executed... but only after logging in the Dashboard !
What am i missing here ?
I did not create any VirtualHost in Apache, it is a simple Apache 2.4 server with the Wordpress site inside the default DocumentRoot.
I cannot migrate on newer nginx version cause its running a Production website.
Migration is already planned when Plumi will officially release the 4.5.2 on Debian 8.
Is there any preferred/working configuration to properly proxypass all the Wordpress content to my Apache without having it to redirect to 127.0.0.1 for example, and properly executing PHP Code on Apache ?
Thanks !
Comment: If all the data is being sent to Apache's backend, why do you have to separate location blocks?  That only serves to do configuration code duplication...
Answer: You may wish to set (and use) additional headers for proxying to the Apache instance, such as these:
proxy_set_header    X-Real-IP         $remote_addr;
proxy_set_header    X-Forwarded-For   $proxy_add_x_forwarded_for;

Most backends (including Apache and PHP) will work with one or more of these, as well as $Host (so it knows what site's being requested).
This should then allow for Apache's PHP to recognize the additional data and essentially say "Oh, this did NOT originate from localhost, it's actual origin is from $remote_addr".  ($remote_addr is a variable that indicates the real IP address of the real source, and the X-Forwarded-For works similarly.)
Comment: thanks for replying. Question edited as you are suggesting. You may also browse http://media.rawnews.net and check the actual mess i'm into.. uncommenting the "root" only causes nginx to process and log some css/js. I'd like to have everything processed by Apache, but its not happening.
Comment: @KRiSh05: edit your own question and add this data.  Also indicate in your question what you ***have*** tried - you didn't state that you tried these, therefore I could not have known.  Also, copy-pasting configs in won't help you in comments - **edit your question to add such data** instead.


Use Resolution to proove a sentence in First Order Logic

Question: I was just wondering if anyone could tell me if I've solved this problem right. If wrong, I would like to know what I did wrong.
"Use resolution to prove Green(Linn) given the information below. You must first convert each sentence into CNF. Feel free to show only the applications of the resolution rule that lead to the desired conclusion. For each application of the resolution rule, show the unification bindings, θ."
I have this axioms to start with:

Hybrid(Prius)
Drives(Linn, Prius)
∀x Green(x) <--> Bikes(x) ∨ (∃y Drives(x, y) ∧ Hybrid(y))

So this is my attempt to solve it. I won't write everything because it's a lot, but my results for each step.
I need to turn every axiom into CNF. The first and the second is already in CNF, so I need to turn the third axiom to CNF.

I start with removing the biconditional.
(∀x Green(x) --> Bikes(x) ∨ (∃y Drives(x, y) ∧ Hybrid(y))) ∧  ((Bikes(x) ∨ (∃y Drives(x, y) ∧ Hybrid(y))) --> Green(x))
Next step is to remove the implications.
(∀x ¬Green(x) ∨ Bikes(x) ∨ (∃y Drives(x, y) ∧ Hybrid(y))) ∧
(¬(Bikes(x) ∨ (∃y Drives(x, y) ∧ Hybrid(y)) ∨ Green(x))
Move the ¬ inwards.
(∀x ¬Green(x) ∨ Bikes(x) ∨ (∃y Drives(x, y) ∧ Hybrid(y))) ∧
((¬Bikes(x) ∧ (∀y ¬Drives(x, y) ∨ ¬Hybrid(y)) ∨ Green(x))
Skolemize the exitensial variable with a Skolem constant/function.
(∀x ¬Green(x) ∨ Bikes(x) ∨ Drives(x, A) ∧ Hybrid(A))) ∧
((¬Bikes(x) ∧ (∀y ¬Drives(x, y) ∨ ¬Hybrid(y)) ∨ Green(x))
Remove the universal quantifier.
(¬Green(x) ∨ Bikes(x) ∨ (Drives(x, A) ∧ Hybrid(A)))) ∧
((¬Bikes(x) ∧ (¬Drives(x, y) ∨ ¬Hybrid(y)) ∨ Green(x))
Distribute ∧ over ∨
(¬Green(x) ∨ Bikes(x) ∨ Drives(x, A)) ∧ (¬Green(x) ∨ Bikes(x) ∨ Hybrid(A)) ∧
(¬Bikes(x) ∨ Green(x)) ∧ (¬Drives(x, y) ∨ ¬Hybrid(y) ∨ Green(x))

Result: I end up with these 6 sentences I can use for the resoultion proof.
1. ¬Green(x) ∨ Bikes(x) ∨ Drives(x, A)
2. ¬Green(x) ∨ Bikes(x) ∨ Hybrid(A)
3. ¬Bikes(x) ∨ Green(x)
4. ¬Drives(x, y) ∨ ¬Hybrid(y) ∨ Green(x)
5. Hybrid(Prius)
6. Drives(Linn, Prius)
So my proof.
7. ¬Drives(x, Prius) ∨ Green(x) // I resolve 4 and 6. {y/Prius}
8. Green(Linn) // I resolve 6 and 7. {x/Linn}
This is it. I am not sure whether I've done it right or not. My proof is only two steps where I mostly resolve/merge some of the sentences. Can I do this?
Also, in my CNF steps, I'm not sure in step two, whether it should be ∀x ¬Green(x) or ∃x ¬Green(x) (Because ¬( ∀x Green(x) ), or can I move the negation directly in front of Green(x)?
I'd really appreciate any feedback. I'm pretty sure my attempt is not right.
Thanks in advance!
Answer: Your step 2 is correct if we read :

$∀xGreen(x) \leftrightarrow Bikes(x) \lor (∃y Drives(x, y) \land Hybrid(y))$

as :

$∀x[Green(x) \leftrightarrow (Bikes(x) \lor ∃y (Drives(x, y) \land Hybrid(y)))]$.

In this case, removing the conditional we get :

$∀x[(\lnot Green(x) \lor Bikes(x) \lor ∃y (Drives(x, y) \land Hybrid(y))) \land (\lnot (Bikes(x) \lor ∃y (Drives(x, y) \land Hybrid(y))) \lor Green(x))].$

Regarding the resolution proof, it must work, because, from :
1) $Hybrid(Prius)$
2) $Drives(Linn, Prius)$
3) $∀x[(Bikes(x) \lor ∃y (Drives(x, y) \land Hybrid(y))) \rightarrow Green(x)]$
i.e. using only "half" of the bi-conditional, we have :
4) $(Bikes(Linn) \lor ∃y (Drives(Linn, y) \land Hybrid(y))) \rightarrow Green(Linn)$ --- from 3) $\forall$-elimination, i.e. instantiating the universal quantifier with $x = Linn$
5) $Drives(Linn, Prius) \land Hybrid(Prius)$ --- from 1) and 2) by $\land$-introduction
6) $\exists y (Drives(Linn, y) \land Hybrid(y))$ --- from 5) by $\exists$-introduction
7) $Bikes(Linn) \lor (\exists y (Drives(Linn, y) \land Hybrid(y)))$ --- from 6) by $\lor$-introduction

8) $Green(Linn)$ --- from 7) and 4) by $\rightarrow$-elimination (modus ponens)

Regarding resolution, in order to prove that from the three axioms it follows $Green(Linn)$, we have to add to the six clauses also : 7. $\lnot Green(Linn)$ [because : $\Gamma \vDash \varphi$ iff $\Gamma \cup \{ \lnot \varphi \}$ is unsatisfiable].
With it, it is easy to derive the empty clause $\square$ from 4-7.


Expected outcome of a process following a uniform distribution

Question: A gambler is playing a game of roulette. There are $37$ possible outcomes, each numbered from $1$ to $37$. The probability of rolling any outcome is the same for each outcome. One game of this roulette is $N$ spins. Once the person picks a number, he has to stick with it to the end (if the gambler runs out of money, it is allowed for him to finish the game with a negative amount - it is not necessary to stay strictly positive throughout all the spins played).
A win gives the gambler $36$ dollars, a loss takes $1$ dollar away.

Given, that the gambler starts with $50$ dollars, what is the expected probability that the gambler will be left with a sum of money $> 0$ after a game with $N=\{100, 1000, 100000\}$ spins?
What is the expected value after $N$ spins?

I have written a simple function in R that generates the process of the gambler's money flow.

library(tidyverse)

roulette <- function(p, bank, n) {
  roulette <- round(runif(n,0,36),0)
  vault <- vector(length = n+1)
  vault[1] <- bank
  for (i in 1:n) {
    if (roulette[i] == p) {
      bank <- bank + 36
    } else {
      bank <- bank - 1
    }
    vault[i+1] <- bank
  }
  return(list(value=roulette,money=vault,result=vault[n]))
}

Using this function I generate $100000$ games with $N = 100$ and draw a histogram with all the final outcomes.
r <- replicate(100000, roulette(7, 50, 100)$result)

r %>% as.data.frame() %>%
  ggplot(aes(x=.))+
  geom_bar()+
  theme_bw()

Which results in:

And calculating the proportion of outcomes with a result $> 0$ gives me:
> length(r[which(r>0)])/length(r)
[1] 0.52124

$N = 100$:

> length(r[which(r>0)])/length(r)
[1] 0.51903

However, when $N = 100000$, the mean of the outcomes (and the proportion of outcomes with a result $> 0$) shifts dramatically:

> length(r[which(r>0)])/length(r)
[1] 0.92709

My intuition tells me, that the expected outcome after a game with $N$ spins should be close to the gamblers starting money, which in this case is $50$ dollars.
Comment: @gunes Yes, I understand my error, now I get the expected results. Thank you very much, I will pay more attention to my RNG from now on. I had to change the correct answer because otherwise it would have been off-topic.
Comment: One crucial aspect that you don't describe in your post, is the payoffs here. How much money does the gambler plays in each spin? How much money does he wins when his chosen number comes up?
Comment: @AlecosPapadopoulos Yes, my bad, I have edited the post accordingly. Thank you.
Comment: Clarify the first question please: does it mean "to stay strictly positive throughout all the spins played"?
Comment: With "allowed for him to finish the game with a negative amount" I implied that it is not necessary to stay strictly positive throughout all the spins played.
Comment: Did you make the corrections I advised on your random number generation procedure? I've explained why you get different and biased results because of it.
Comment: Glad to hear you've realized it. When you changed the accepted answer I thought you just didn't understand what I've been talking about :)
Answer: For your first question, let $I_k$ be a Bernoulli random variable taking the value $1$ if the gambler wins in spin $k$, and zero otherwise. Then
$$W_k = I_k\cdot (W_{k-1}+36) + (1-I_k)\cdot (W_{k-1}-1) = W_{k-1} +37I_k-1$$
By repeated substitution, we get
$$W_k = W_0-k + 37 \sum_{i=1}^kI_i$$
So we have expressed the random variable $W_k$ as a function of deterministic terms and the sum of independent RVs. Good. Then we ask for the probability, for some $k$,
$$P\big[W_k>0\big] = P\left[W_0-k + 37 \sum_{i=1}^kI_i>0\right] = P\left[ \sum_{i=1}^kI_i>\frac {k-W_0}{37}\right]$$
$$=1-P\left[ \sum_{i=1}^kI_i \leq \frac {k-W_0}{37}\right] $$
This is the probability that we are asked to calculate, for various values of $k$. The sum of independent Bernoullis does not have a closed form distribution, but it obeys the Central Limit Theorem after suitable centering and scaling, and so maybe one would want to use the Normal approximation (or go by simulation of course).
For your second question, this is why these are not the odds actually holding in a casino:
Let the spin index $k=1,...,N$. Let $W_0$ be the original amount of money, and let $W_k$ be the amount of money the gambler will have after spin $k$. Assume that we have arrived at that moment. Then the conditional expected value is
$$E[W_k|k-1,k-2,..,1] = \frac {36}{37}\cdot (W_{k-1}-1) + \frac {1}{37}\cdot (W_{k-1}+36) = W_{k-1}$$
$$\implies E(W_k) = E\big[E[W_k|k-1,k-2,..,1]\big] = E(W_{k-1})$$
Since $k$ was arbitrary, it follows that the the expected value is constant throughout and equal to the original amount of money (set $k=1$). By the way  the first line above is the defining property of a martingale.
Comment: This is very helpful, expressing the random variable as a function cleared up a lot for me. Thank you!
Answer: Your random number generation is not correct, because of the edge cases. Probability of getting $0$ or $36$ is half of probability of getting other numbers. For example, to get $0$, it needs to create a random number in $[0,0.5]$, but to get $1$, it needs to pick a number in the range $[0.5,1.5]$, which is twice the former.
The following needs to be changed as follows:
round(runif(n,0,36),0) $\rightarrow$ floor(runif(n,0,37))
Because of the above situation, one spin has the expectation $$E[X]=36\times\frac{1}{36}+(-1)\times\frac{35}{36}=\frac{1}{36}$$
$N$ spins (since they're independent) will have an expected revenue of $N/36$, which explains the shift in your last graph: $100000/36\approx2778$.
Normally, the expectation of one spin is $E[X]=0$ (if you calculate as above), with correct probabilities, i.e. $1/37$. And, the expected value will be $0$, and you'll be where you start actually.
Also, you don't use $50$ dollars anywhere in your code. For your first question, starting with no money, and asking for final money to be $>0$ is easy (and will be $0.5$ if you use the correct random number generator); however, asking for $>0$ when your start money is $50$ is a bit harder one to answer.
Edit: Since you edited your question back to original $50$ dollars initial condition, we can think as follows:
For $N=100$ spins, the probability of $X>-49$, where $X$ is our total earnings, is actually not losing more than $49$ dollars. If you win more than once, you'll be guaranteed to have more than $0$ dollars net. So, remove the probability of losing all the time and just once from $1$:
$$P(\text{Money}>0)=1-\left(\frac{36}{37}\right)^{100}-{100 \choose 1}\frac{1}{37}\left(\frac{36}{37}\right)^{99}\approx 0.75$$
For $N=1000$, the situation is harder. We need to win $26$ times or more to be on positive side. So, it's going to be a formula involving sums: i.e. $\sum$'s. Maybe, it's better to expect an approximate solution here, using Central Limit Theorem:
One spin has $\mu=0, \sigma=6$. $N$ of them will have $\mu=0,\sigma=6\sqrt{N}$:
$$P(X>-50)=P\left(Z>-\frac{50}{6\sqrt{N}}\right)=1-\Phi\left(\frac{50}{6\sqrt{N}}\right)$$
For $N=1000$, you'll have $P(X>-50)\approx 0.6$ for example.
Comment: This makes sense, thank you!

I jumped back and forth between leaving it with the original starting 50 dollars and 0 just to make the question simpler. Changed the code, but decided to leave the initial condition. Will edit the code. (The generated histograms follow the condition of starting with 50 dollars).


Finite field and multiplicative group

Question: $F$ is a field such that $F^*= F\setminus \{0\}$ is the cyclic multiplicative group. Prove that $F$ is a finite field.
I am struggling with this problem. We did not consider the material in class and I got stuck with this problem…
Comment: If the multiplicative group $F^*$ is cyclic, it has a generator $a\in F$. Play around with $a$ and see what you can find. Think of the prime subfield of $F$ (you know what that is?), and how it fits in with $a$.
Answer: As another answer has mentioned, since the only cyclic groups are $\mathbb{Z}$ and $\mathbb{Z}_n$, the problem reduces to showing that there is no field $K$ with multiplicative group $\mathbb{Z}$. Every field has one of $\mathbb{Q},\mathbb{Z}_p$, $p$ prime, as a subfield. This means that one of $\mathbb{Q}^*,\mathbb{Z}_p^*$ must be a subgroup of $K^*\simeq\mathbb{Z}$.
The first case $\mathbb{Q}\subseteq K$ is impossible because every subgroup of $\mathbb{Z}$ is of the form $n\mathbb{Z}$, and in particular is cyclic, being generated by $n$. But $\mathbb{Q}^*$ is not cyclic, or even finitely generated! It's also impossible to get $\mathbb{Z}_p^*$ as a subgroup of $\mathbb{Z}$, simply because every element of $\mathbb{Z}_p^*$ has finite order, whereas no element of $\mathbb{Z}$ does other than $0$.
Comment: This doesn't rule out $p=2$.
Comment: Actually, I believe it does. I guess you're thinking of the multiplicative structure on the integers where $-1$ has order 2, but the infinite cyclic group is the integers under *addition*, so the proposed isomorphism $K^*\simeq\mathbb{Z}$ turns multiplication into addition.
Answer: Well, if $F^*$ is cyclic, i.e. a unigenerated abelian group, we're in fantastic shape provided the group isn't $\mathbb{Z}$ (it's either that or $\mathbb{Z}/n\mathbb{Z}$, which is wonderfully finite).
So, what would happen if $\mathbb{F}^*$ were isomorphic to $\mathbb{Z}$ - this would mean that there's some element $x$ such that $x^i = x^j \Leftrightarrow i = j \in \mathbb{Z}$, and $F = 0 \cup x^i: i \in \mathbb{Z}$.
Could $F$ be characteristic 0? Well, we would have a map $\mathbb{Q} \rightarrow F$, and so we would have $2 = x^i, 3 = x^j$, extending to a map $\overline{\mathbb{Q} } \rightarrow \overline{F}$, where the bar denotes algebraic closure, we would have $x$ is some $\zeta_i 2^{1/i}$ and $\zeta_j 3^{1/j}$, where $\zeta_i$ is an $i^{th}$ root of unity; raising both sides to the $(ij)^{th}$ power, we have $2^j = 3^i$, a contradiction.
Could $F$ be characteristic $p$? Well, in all characteristics, we would know that $x + x^2 = x^i$, whence $F$ would be a unigenerated algebraic field extension of $\mathbb{F}_p$, whence finite.
Answer: Let $a$ generate $F^*$. Assume $F$ is not finite. Then, $\langle a \rangle \cong \mathbb{Z}$. Since $\mathbb{Z}$ has no torsion, we have $1 = -1$. Thus, $\operatorname{char} F = 2$.
Since $a \neq 1$, $a + 1 = a - 1 \neq 0$ so $a + 1 = a^i$ for some $i \neq 1$. If necessary we can replace $a$ by $a^{-1}$, so we may assume that $i > 1$.
Then,
$a = a^i + 1 = (a + 1)(1 + a + \ldots + a^{i - 1}) = a^i(1 + a + \ldots + a^{i - 1})$, so $1 + a + \ldots + a^{i - 2} = 0$. This gives $a^{i - 1} = 1$, a contradiction.
Comment: I get $a^{1-i}=1+a+\cdots+a^{i-2}+a^{i-1}$. Then how do you get $1+a+\cdots+a^{i-2}=0$?

Finite field and multiplicative group


Erro com setOnTouchListener

Question: Eae, venho recebendo o segundo erro ao rodar um app no AndroidStudio
/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.vinicius.login, PID: 3519
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vinicius.login/com.example.vinicius.login.inicio}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnTouchListener(android.view.View$OnTouchListener)' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnTouchListener(android.view.View$OnTouchListener)' on a null object reference
                  at com.example.vinicius.login.inicio.onCreate(inicio.java:40)
                  at android.app.Activity.performCreate(Activity.java:6664)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Pelo que pude ver ele aponta o erro como a linha 40 onde existe um botão, não sei se o erro é só esse mas aguardo respostas e ajudas, segue o código abaixo
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class inicio extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /********************************/
         /*    Define os botões  */
        /********************************/
        Button led1 = (Button) findViewById(R.id.LED1);
        Button led2 = (Button) findViewById(R.id.LED2);
        Button led3 = (Button) findViewById(R.id.LED3);
        Button led4 = (Button) findViewById(R.id.LED4);
        Button led5 = (Button) findViewById(R.id.LED5);
        Button led6 = (Button) findViewById(R.id.LED6);

        /*******************************************************/
         /*  Seta um Onclick e Onchange  */
        /*******************************************************/

        led6.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    /* button is led 3 */
                    new Background_get().execute("led6=1");
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    new Background_get().execute("led6=0");
                }
                return true;
            }
        });

        led5.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    /* button UP */
                    new Background_get().execute("led5=1");
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    new Background_get().execute("led5=0");
                }
                return true;
            }
        });

        led4.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    /* button BACK */
                    new Background_get().execute("led4=1");
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    new Background_get().execute("led4=0");
                }
                return true;
            }
        });

        led3.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    /* button RIGHT */
                    new Background_get().execute("led3=1");
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    new Background_get().execute("led3=0");
                }
                return true;
            }
        });

        led2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    /* button LEFT */
                    new Background_get().execute("led2=1");
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    new Background_get().execute("led2=0");
                }
                return true;
            }
        });

        led1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    /* button FRONT */
                    new Background_get().execute("led1=1");
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    new Background_get().execute("led1=0");
                }
                return true;
            }
        });

    }
}

class Background_get extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        try {
                /* Conexão com o Raspberry PI 3, solicitação HTML de comando PHP servidor APACHE  */
            URL url = new URL("http://192.168.0.101/?" + params[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder result = new StringBuilder();
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                result.append(inputLine).append("\n");

            in.close();
            connection.disconnect();
            return result.toString();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

meu XML é o seguinte
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#4F4F4F"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.vinicius.login.inicio">

    <TextView
        android:text="LOGIN™"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:textColor="#B5B5B5"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:text="FRONT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/LED1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="43dp" />

    <Button
        android:text="BACK"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/LED4"
        android:layout_below="@+id/LED2"
        android:layout_toRightOf="@+id/LED2"
        android:layout_toEndOf="@+id/LED2" />

    <Button
        android:text="RIGHT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/LED3"
        android:layout_above="@+id/LED4"
        android:layout_toRightOf="@+id/LED1"
        android:layout_toEndOf="@+id/LED1" />

    <Button
        android:text="LEFT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/LED2"
        android:layout_marginTop="48dp"
        android:layout_alignTop="@+id/LED1"
        android:layout_toLeftOf="@+id/LED1"
        android:layout_toStartOf="@+id/LED1" />

    <Button
        android:text="DOWN"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/LED6"
        android:layout_above="@+id/textView"
        android:layout_alignLeft="@+id/LED5"
        android:layout_alignStart="@+id/LED5"
        android:layout_marginBottom="39dp" />

    <TextView
        android:text="XY"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#B5B5B5"
        android:layout_alignTop="@+id/LED2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="13dp"
        android:id="@+id/textView2" />

    <Button
        android:text="UP"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/LED5"
        android:layout_above="@+id/LED6"
        android:layout_alignLeft="@+id/LED4"
        android:layout_alignStart="@+id/LED4"
        android:layout_marginBottom="18dp" />

    <TextView
        android:text="Z"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#B5B5B5"
        android:id="@+id/textView3"
        android:layout_above="@+id/LED6"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="80dp"
        android:layout_height="50dp"
        app:srcCompat="@android:drawable/ic_menu_preferences"
        android:id="@+id/imageView2"
        android:layout_above="@+id/LED5"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="34dp" />

    <ImageView
        android:layout_width="20dp"
        android:layout_height="20dp"
        app:srcCompat="@android:drawable/ic_partial_secure"
        android:id="@+id/imageView4"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/LED3" />

</RelativeLayout>

Comment: Falta `setContentView(R.layout.layoutDaActivity)`
Comment: Sou iniciante com o android ainda, pode ser mais especifico com relação ao local que falta isso? Onde está faltando  "setContentView(R.id.activity_login) " ?
Comment: Após `super.onCreate(savedInstanceState);`
Comment: Thanks amigo! O problema foi solucionado! Agora me resta estudar mais para aprender a função  de setContentView, abraço! (y)
Comment: Se de facto quer aprender esse é o caminho. Não basta ter o problema solucionado, só deve ficar satisfeito quando perceber a solução.
Comment: Sem dúvidas (y)
Answer: Como o amigo acima citou, falou o setContentView, que "infla" o arquivo XML de layout no JAVA para que os objetos da UI possam ser instanciados. Por isso você tomou o erro de "null object", visto que o JAVA não encontrou nenhuma referência ao botão que você tentou usar.

Erro com setOnTouchListener


error call to member function

Question: When I login in I am trying to set up some user activity for codeigniter project so can see which users logs on and off.
On my library function login I have this data here below But now throws error Not sure on how to fix it.
$activity_data = array(
'user_id' => $this->CI->session->userdata('user_id'),
'name' => $this->CI->session->userdata('firstname') . ' ' . $this->CI->session->userdata('lastname')
);

$this->CI->load->model('admin/common/user_login_model');
// Error Here Line 27
$this->user_login_model->addActivity('login', $activity_data);

Error
A PHP Error was encountered
Severity: Notice
Message: Undefined property: User::$user_login_model
Filename: libraries/User.php
Line Number: 27
Fatal error: Call to a member function addActivity() on a non-object in C:\Xampp\htdocs\codeigniter-cms\application\libraries\User.php on line 27

On Model
public function addActivity($key, $data) {
  $data['user_id'] = $this->user->getID();

  if (isset($data['user_id'])) {
     $user_id = $data['user_id'];
  } else {
     $user_id = 0;
  }

  $this->db->query("INSERT INTO `" . $this->db->dbprefix . "user_activity` SET
     `user_id` = '" . (int)$user_id . "',
     `key` = " . $this->db->escape($key) . ",
     `data` = " . $this->db->escape(serialize($data)) . ",
     `ip` = " . $this->db->escape($this->input->server('REMOTE_ADDR')) . ",
     `date_added` = NOW()
  ");

}
Answer: It seems that you made an instance of CI and loaded the model into it. Yet, you try to access the model directly from the library class with $this->user_login_model, which is wrong. Try instead :
$this->CI->user_login_model->addActivity('login', $activity_data);

error call to member function


How do we know what constants can replace variables in an open sentence?

Question: Consider for example the open sentence,

x lives in India

where 'x' is a variable, which can be substituted by various constants to make declarative sentences.
For instance,

Harshit lives in India
Carol lives in India
Zaid lives in India

where 'x' has been replaced by constants 'Harshit', 'Carol' and 'Zaid', respectively.
I don't understand how do we exactly come to know which constants can substitute the variables in an open sentence.
I mean, if someone says, significant substitutes are names of people, in this example, I would say why not of pets? Why not just of people of a particular City or ethnicity?

Since, this question is from logic, which is a prerequisite (AFAIK) of set theory, I would humbly expect no notions from set theory to be used.
Comment: A *term*, i.e. either a constant or a variable or a complex term made with a function symbol (if any).
Comment: Constants are part pf the language, thus they are specified by the rules of the language.
Comment: $x+0=1$ is a formula with variable x. You can replace it with 0 or with s(0), i.e.1.
Comment: @MauroALLEGRANZA Using the notion of sets only to get across the idea, what I mean to say is how do we decide the domain of the variable? For example, in the example that I gave in the question, how would one decide whether the domain is set of all people, set of people of a particular city, or set of animals who are pets?
Comment: "why not of pets?" Maybe the person making the statement doesn't want to study pets. "why not just people of a particular ethnicity?" Maybe the person making the statement doesn't want to restrict their study to people of a particular ethnicity. It all depends on the person making the statement. It depends on what the person making the statement wants to study. How much to restrict or generalize one's domain depends pretty much on one's problem. If one wants to study political beliefs of a particular state, restrict to that state and maybe only to people who vote etc.
Answer: When evaluating or constructing an argument, one typically defines a domain, that is, the set of all elements being considered in that specific problem or context. This is also referred to as the domain of discourse of universe of discourse. The domain can be restricted to a certain kind of thing, such as all animals or all people, or the domain can be unrestricted so as to include literally everything.
Members of the domain are specifically named things, and they are represented by individual constants such as $a,b,c$ or any of the first $23$ letters of the alphabet. A variable, such as $x$, represents an arbitrary, unnamed element from the domain.
An open sentence, or propositional function, becomes a statement with a definite truth value once every variable therein is either $(1)$ substituted with a constant from the domain or $(2)$ bound to a quantifier. You can substitute any constant you wish to produce such a statement, but the choice of constant is usually dictated by the specific problem or argument you're working with. In other words, you may require a specific constant from the domain because that constant appears in other statements, and you may need a subset of statements discussing the same constant in order to apply a desired inference rule. For example, take the argument
$\forall x [Fx \to Gx], Fa \vdash Ma$
where
$F:$ ___ is a folk singer.
$M:$ ___ is a musician.
$a:$ Alice
In general, the choice of domain should consist of all and only those things capable of possessing the relevant properties. So here the domain is appropriately defined as the set of all people because all folk singers and all musicians are people, and only people can be folk singers and musicians.
Note that one can apply universal elimination to $\forall x [Fx \to Mx]$ to obtain $Fb \to Mb$ where $b$ is Bob, and this would result in a perfectly acceptable statement, that is, "If Bob is a folk singer, then Bob is a musician." However, if I'm trying to prove the argument, then obtaining a statement about Bob is not helpful because the argument is about Alice. Among all constants I could choose from, I prefer to instantiate with $a$ corresponding to Alice so that I can obtain $Fa \to Ma$ and derive the conclusion $Ma$ via the inference rule known as Modus Ponens.


Do we perform division by zero while finding the derivative of a function?

Question: Please have a look at this example,
Finding the derivative of the function $f(x) = x^2 :$
$\lim_{\Delta x \to 0} \frac{f(x+\Delta x) - f(x)}{(x + \Delta x) - (x)}$
$=$ $\lim_{\Delta x \to 0} \frac{(x+\Delta x)^2 - (x)^2}{(x + \Delta x) - (x)}$
$=$ $\lim_{\Delta x \to 0} \frac{(x^2+2x\Delta x + \Delta x^2) - x^2}{x + \Delta x - x}$
$=$ $\lim_{\Delta x \to 0} \frac{x^2+2x\Delta x + \Delta x^2 - x^2}{\Delta x}$
$=$ $\lim_{\Delta x \to 0} \frac{2x\Delta x + \Delta x^2}{\Delta x}$
$=$ $\lim_{\Delta x \to 0} \frac{\Delta x(2x + \Delta x)}{\Delta x}$
$=$ $\lim_{\Delta x \to 0} 2x + \Delta x$
$=$ $2x$
From the last two lines(above),
$\Rightarrow$ $2x + \Delta x = 2x$
$\Rightarrow$ $\Delta x = 0$
If what I've done is correct, then aren't we performing division by zero while evaluating the limit ? But how can this be possible ?
I've started to learn Calculus just recently. So maybe this confusion is due to my lack of understanding of the concept.
Actually I'm still not clear about what is limit.
So, please give a detailed and intuitive explanation of the limiting process.
Comment: The last two lines say $\lim_{\Delta x\to 0}2x+\Delta x=2x$ and **not** $2x+\Delta x=2x$.
Comment: (Almost) every single $\Rightarrow$ here should have been $=$
Comment: Similar questions have been asked *many* times already: https://www.google.com/search?q=site:math.stackexchange.com+derivative+division+by+zero
Comment: By assumption $\Delta x$ is non-zero, so that must mean you cheated somewhere..
Answer: Remember that $\Delta x$ approaches $0$; it is never equal to $0$. This means that we do not need to worry about division by $0$ in order to find the derivative.
Comment: What's the difference between approaching to zero and being exactly zero ? If the limit is what the function approaches zero then, how can we get a definite answer. Because we can always approach more and more closer to zero and each time we approach closer than before we should get a different result.


Função http_build_query

Question: Gostaria de saber para que serve a função http_build_queryem php.
Li o manual, mas ficou vago para mim.
http_build_query
É correto utilizá-lo dentro deste contexto?
    $cURL = curl_init('http://teste');
    curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
    $dados = array(
            'NMCLIENTE' => $nome_lead,
            'DSEMAIL' =>  $email_lead,
            'NRTELEFONE' => $telefone_lead,
            'DSINTERESSE' => $meio_captacao,
            'DSMENSAGEM' => $mensagem
            );
    curl_setopt($cURL, CURLOPT_POST, true);

    curl_setopt($cURL, CURLOPT_POSTFIELDS,  http_build_query($dados));

    $resultado = curl_exec($cURL);
    curl_close($cURL);

Comment: Tens ai os exemplos no manual.
Answer: Nada mais é do que transformar seu array em um formato de querystring, pronta para ser passada para uma URL. Ele vai transformar a sequencia de chave-valor e separar por um &.
Ele simplifica o processo de:

Concatenar cada chave-valor com um & (como seria feito com implode());
Codificar a URL (como seria feito com urlencode()) em que todos os caracteres não-alfanuméricos são substituídos por um sinal de % seguidos por dois caracteres hexadecimais e espaços codificados com um sinal de +;

Sobre utilizar nesse contexto que você demonstrou, é correto mas não necessário, já que você informa que irá enviar a requisição através do método POST uma vez que CURLOPT_POST é verdadeiro. Desta forma, você pode passar em CURLOPT_POSTFIELDS tanto um array diretamente quanto uma string URL-like.
Quando você passa diretamente o array, o Content-type da requisição automaticamente será do tipo multipart/form-data, enquanto que se passar uma string, será do tipo application/x-www-form-urlencoded.
Comment: Muito obrigado Paulo!
Answer: Sim eu faço dessa forma:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($dados, '', '&'));

Função http_build_query


How to print block generated by views in the tpl file?

Question: I have a block with name: "Share Product"(block number 5) generated by my view with name: "main_product_deal". In this view i have 9 blocks.
Now in my .tpl file i need to print this block.
I have seen the function 'module_invoke' but not working.
My code is:
<code>//On my tpl file
<?php
$block = module_invoke('views','block','view',"main_product_deal-block_5");
print $block['content'];
?>
</code>
I working in drupal 6.x. Is it correct my code? Or exist another solution?
Note: I can not set the block in the administration, because I'm programming certain things in the tpl
Thanks :D
Answer: Have you tried views_embed_view()?
http://drupalcontrib.org/api/drupal/contributions!views!views.module/function/views_embed_view/6
Answer: Do you actually need the block, or can you just output the results of the view?  If you just need the results of the view:
<code>$view = views_get_view('main_product_deal');
print $view->execute_display('default');
</code>
Comment: The param of execute_display is the name of the view or the delta?.. I'll try your solution.
Comment: Don't work :(. A put this in my tpl file.. but doesn't show the result of the view-block.
Comment: What does it do? Are there any error messages?  More info would be great
Comment: Any errors, only don't show the block.
I need to show a block-views in my page-deals.tpl... I need extract only this block. (no the default)


How to know the module package?

Question: I need to know the package of a given module to performs some actions inside the implementation of a custom a drush command. So usually you will find that we will found this information in the module_handler service. But there is not method to get the module package.
So, how can I know the module package?
Answer: Maybe another simpler way exists, but after a little digging in the core I found that the modules list (admin/modules) with all the information is retrieve from the _system_rebuild_module_data() function that use the
info_parser service to retrieve all the module information.
If you want to know the module package you can use this code:
<code>$module_machine_name = 'views';
$module = \Drupal::service('module_handler')->getModule($module_machine_name);
$module_info = \Drupal::service('info_parser')->parse($module->getPathname());
// To use dpm() you need the devel module.
dpm($module_info['package']);
</code>
Output:

Core

How to know the module package?


PHP Country Time for SQL

Question: I am from India and My website server is located in UK. When ever I use the now() function in PHP, it takes the server time which is UK time. Also when I use the Query
"select * from tblAttendance where DATE(AttDate) =DATE(now())  Order by EmpID "

This takes the time from the Server, So for me to get the current date attendance I need to wait till 10:30 AM my time as only then its a new day as per the server time.
Any help would be great.
Thanks
Comment: What is the question? How to set the timezone correctly? https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
Comment: use "bool date_default_timezone_set ( string $timezone_identifier )" in php ti change the time zone
http://php.net/manual/en/function.date-default-timezone-set.php
and for mysql time check out bellow post
 http://stackoverflow.com/questions/930900/how-to-set-time-zone-of-mysql
Comment: @parag that will only affect the PHP time, mysql's time could still be off.
Comment: @chris85, yes comment is update for mysql time
Comment: This might help you: http://stackoverflow.com/a/32872549/3283363
Answer: You need date_default_timezone_set() to set timezone to set and get timezone
date_default_timezone_set()
Timezones
and store this time to database.
Get date from php and apply to mysql query as follows.
date_default_timezone_set('Asia/Kolkata');
$date=date('Y-m-d'); // current date
$q= mysql_query("select * from tblAttendance where DATE(AttDate) ='".$date."' Order by EmpID ");

Comment: Hi Thanks for the help But I am not sure whether I am doing the right thing,          date_default_timezone_set('Asia/Kolkata');
$q= mysql_query("select * from tblAttendance where DATE(AttDate) =DATE(now())  Order by EmpID "); This Again has the same issue, Is there anything else I need to do
Answer: Set timezone like this:
date_default_timezone_set('Asia/Kolkata');

Comment: Hi Thanks for the help But I am not sure whether I am doing the right thing,          date_default_timezone_set('Asia/Kolkata');
$q= mysql_query("select * from tblAttendance where DATE(AttDate) =DATE(now())  Order by EmpID "); This Again has the same issue, Is there anything else I need to do
Comment: now() is the mysql function. So you have to set the mysql server timezone as well by running this query. SET time_zone = "+05:30";

PHP Country Time for SQL


Superset individual dashboard permission

Question: Is it possible to set permission on a specific dashboard? Like only 'user1' and 'user2' will view/see 'dashboard1' and others will not see 'dashboard1'.
Answer: As of Spring/Summer of 2021, there is a feature flag, DASHBOARD_RBAC, to manage which roles can access the dashboard. See this GitHub issue for more details.

Non-owner user access can be managed two different ways:

Dataset permissions - if you add to the relevant role permissions to datasets it automatically grants implicit access to all dashboards
that uses those permitted datasets
Dashboard roles - if you enable DASHBOARD_RBAC feature flag in superset_config.py then you be able to manage which roles can access the dashboard

Having dashboard access implicitly grants read access to the associated
datasets, therefore all charts will load their data even if feature
flag is turned on and no roles assigned to roles the access will
fallback to Dataset permissions.
Comment: How can I enable `DASHBOARD_RBAC`?
Comment: You can enable or disable feature flags from `superset_config.py`: https://superset.apache.org/docs/installation/configuring-superset/#feature-flags
Answer: Yes,

Setup role (rules) : my trick is copy gamma rules, rename,

edit permission, just type your dashboard name, youll find : datasource:your dashboard name, add that, that's it.

Setup user, give rules (number 1)

Your new user will able to see the specific dashboard you point (number 2)
Comment: As of v0.37, it seems you can only see datasources and not dashboards when editing permissions.
Comment: Yes, correct, sorry, for dashboard, go to dashboard list, edit owner, put your secondary user in that owner name box, as for datasets, its required permissions at user roles, if you just put the name without the permissions, some data may chart or data may not be able to load
Answer: View Access
To control who sees a dashboard, define an access role for the datasource associated with the dashboard content.
For example:

create role_1 with permissions datasource access on [my_db].[dash1_data].
Assign user1 to role_1 and gamma (standard user profile).

dashboard1 is now presented to user1 assuming it's based on dash1_data.
Write Access
To control which non-admin users can edit dashboards set the Dashboard Owner.
Dashboard List > Edit [dashboard1] > Access Owners
Add individual users to the owner list to provide write access to individual dashboards.
Ref: https://superset.apache.org/docs/security/
Answer: Edit the dashboard and you will find the Owners sections, add the user names for whom you want to give the access. Now login with the user and you will able to see the dashboard.
Answer: Steps to Give dashboard permission to the particular user.
Step - 1:

Step - 2:
Click the + button on your right
Step - 3: Give the Unique name in name field for identification for example demo_dashboard_reader and choose the data source in permissions field. then click save.

Step - 4: Go to security and click list users (see the image in step-1). Filter the user you want to give permission of this dashboard and click edit. choose the role that you created in step-3 (demo_dahboard_reader) in my case and click save. Now only the chosen user can able to view the particular dashboard.
Step - 5: Repeat the step-4 to give permission to other users.


What is the maximum throughput or upload limit on the amount of simultaneous data being transferred using an Azure IRT?

Question: Is there a maximum throughput or upload limit on the amount of simultaneous data being transferred using an Azure IRT as part of an Azure data factory before a pipeline and/or activity may timeout or fail?
Answer: Good question. The answer is we cannot tell.
There is an interesting article about Hyperscale throughput and most of the research I did around throughput they don't give me a concrete answer.
On the same article you can find a comment that states:

Dont't bother with Azure Data Factory. For some reason with type
casting from blob to Azure SQL, but also Azure SQL Database as a
source, the throughput is dramatic. From 6 MB/s to 13 MB/s on high
service tiers for transferring 1 table, 5GB in total. That is beyond
bad.

So there are too many factor to count in: where the data come from, where the data go, the products you are using, etc...
You might need to open a (paid) ticket with Azure support and ask if they hardcoded that trigs a timeout. But in my experience I've seen simple database migration from SQL Server to Azure SQL DB failing for no reason and then complete at a second try.