Dropzone.js remove link hidden behind pop-up message

Question: I am using Dropzone.js to add file drag and drop functions to an upload form, and it looks good and all works great.
However, when a file is rejected, if it is too large or not an allowed extension, the pop up error message hides the "remove" link, so you cant remove that bad file icon.

Is there any way around this?
I think you can set to remove bad items from the queue automatically, but then the user wouldnt get the explanation message.
Maybe hide the "remove" text for a bad file and add a link to the pop up message?
Or change the "remove" links to a small "X" icon at the bottom right corner of the icon that wouldnt be hidden?
Not sure how to do either of these, or if there is a better solution to this?
Answer: One solution is customize the dropzonejs CSS for the preview template to adjust the error message. For example, in your case you could update:

.dropzone .dz-preview .dz-error-message {
    top: 150px!important;
}

And this is the result:
Comment: Is the `!important` strictly necessary? I don't find that it is in my case.
Comment: @BenJohnson It depends, but probably not, so you can remove it.
Answer: When faced with the same problem I chose to solve it by both shifting the tooltip a little lower and changing the position and size of its arrow to not obscure the remove link. I also shortened the text of the link to just "remove" and styled it to look better.

Here are my CSS customizations:

.dropzone .dz-preview .dz-image img {
    margin: auto;   /* center the image inside the thumbnail */
}
.dropzone .dz-preview .dz-error-message {
    top: 140px;     /* move the tooltip below the "Remove" link */
}
.dropzone .dz-preview .dz-error-message:after {
    left: 30px;     /* move the tooltip's arrow to the left of the "Remove" link */
    top: -18px;
    border-bottom-width: 18px;
}
.dropzone .dz-preview .dz-remove {
    margin-top: 4px;
    font-size: 11px;
    text-transform: uppercase;
}
Answer: .dropzone .dz-preview.dz-error .dz-error-message {
  display: block;
  position: absolute; /* add this */
  top: 150px;         /* add this */
}

Comment: Your answer could be improved by adding more information on what the code does and how it helps the OP.
Answer: One of the suggestions in your question could also work as an alternative solution. Instead of moving the tooltip, you could also move the "remove" button and even change the text to something like this "✖" or custom html.
/* Change position of remove button */
.dz-remove {
    z-index: 999;
    position: absolute;
    display: block;
    top: 0%;
    left: 100%;
    margin-left: 5px;
    margin-top: -15px;
}

const myDropzone= new Dropzone('#myDropzone',{
    ...
    addRemoveLinks: true,
    dictRemoveFile: "

", // Or simply replacing it by "✖"
    ...
})


Strategy Exit for Inside days

Question: My Strategy gets posted, but my strategy exit is not being displayed on the chart. Also, my strategy tester is showing all 0 values on all but Buy and Hold.
I've already tried using parentheses. The strategy exit factors are fairly similar to the strategy entry. Both entry and exit have the same values (Open and close)
Inside_days = (high < high[1] and low > low[1])

long = low < low[1]

short = high > high[1]

strategy.entry("GO LONG", strategy.long, when = Inside_days)

strategy.entry("GO SHORT", strategy.short, when = Inside_days)

strategy.close("OFF LONG", when = long and Inside_days)

strategy.close("OFF SHORT", when = short and Inside_days)

I expect the chart to be posted with proper values on the strategy tester and the strategy and exit signals placed on the correct places.
What I'm getting as of right now is my strategy entry signals are showing up, but my strategy close signals are absent.
Answer: You must use the same order id that you want to close in strategy.close() calls.
Here is an example from the Pine Script Reference Manual:
strategy("closeEntry Demo", overlay=false)
strategy.entry("buy", true, when = open > close)
strategy.close("buy", when = open < close)
plot(strategy.position_size)

Strategy Exit for Inside days


Is there a better way of getting specific pieces of data from taxonomy_term_load()?

Question: I have a taxonomy that has several fields attached to it. If I do a taxonomy_term_load($tid) on a specific item, it returns a huge object with multiple levels of nested arrays. I know which "parent" item (i.e. field name) I want, so I can do something like this:
$track_tax = taxonomy_term_load($value);
var_dump($track_tax->field_track_icon);

But even this returns a lot of nested levels:
array(1) {
  ["und"]=>
  array(1) {
    [0]=>
    array(15) {
      ["fid"]=>
      string(3) "702"
      ["alt"]=>
      string(0) ""
      ["title"]=>
      string(0) ""
      ["width"]=>
      string(2) "36"
      ["height"]=>
      string(2) "36"
      ["uid"]=>
      string(1) "1"
      ["filename"]=>
      string(24) "strategies_at_retail.jpg"
      ["uri"]=>
      string(44) "public://track_icon/strategies_at_retail.jpg"
      ["filemime"]=>
      string(10) "image/jpeg"
      ["filesize"]=>
      string(4) "1129"
      ["status"]=>
      string(1) "1"
      ["timestamp"]=>
      string(10) "1338391429"
      ["type"]=>
      string(5) "image"
      ["rdf_mapping"]=>
      array(0) {
      }
      ["image_dimensions"]=>
      array(2) {
        ["width"]=>
        string(2) "36"
        ["height"]=>
        string(2) "36"
      }
    }
  }
}

I know I can get the uri by doing something like this:
$uri = $track_tax->field_track_icon["und"][0]["uri");

Is there a better way? Some other function that will return specific pieces? Or do I need to address it level by level?
Answer: The field_get_items() function is very useful for this sort of thing. It doesn't produce shorter code, but it's more structured and a lot easier to get your head round than the endless arrays of data:
// Get the items for a particular field
$field_items = field_get_items('taxonomy_term', $track_tax, 'field_track_icon');

// Get the first item (fields can have multiple items so field_get_items always returns an array)
$first_item = array_shift($field_items);

// Get the URI
$uri = $first_item['uri'];

Using that method has the added benefit of automatic language negotiation, so you can avoid having to get that from context or just relying on 'und'.
I should also say the use of this function isn't limited to taxonomy terms; you can use it to get field values for any type of entity.
Comment: Thanks. So, for the param you have as `$term`, is that the tid or the term value?
Comment: Sorry should have noticed that, it's the term object which is `$track_tax` in your code
Comment: OK, so I still need to do the taxonomy_term_load, but then I can use field_get_items on the particular field attached to the taxonomy? Sounds good.
Comment: Yep spot on. There's also the `entity_metadata_wrapper()` function if you're using the Entity API module which does something similar, have a look at [this question](http://drupal.stackexchange.com/questions/33444/what-is-the-purpose-of-the-entity-metadata-wrapper-function-and-why-should-i) for more info


How to build a bundle sbt from source for offline use?

Question: My goal is to have a sbt jar file with all dependencies in order to create a debian package, so it could be install on machine without check/install package at first run.
Is it the right choice use sbt-assembly to build a sbt jar with all dependencies?
The sbt binary version doesn't come with dependecies and sbt download them at first run.
Comment: Not the answer you might looking for, but for an quick and dirty solution: Just copy the ivy cache (`~/.ivy2/cache`). If you explain why you try to accomplish this there is certainly a better solution.
Comment: @semptic I rephrase my question in order to explain my final goal. Thanks for your comment but for my case copying ivy cache is not the rigth "solution"
Answer: I don't fully understand your use case, but would sbt-native-packager .deb format be a good fit?
Comment: Thanks for your answer. It is not exactly what I search but it will help me to packaging sbt dependencies. Thanks again


Examples of classes of structures which are "surprisingly" axiomatizable.

Question: This is a bit of a soft question, but I am interested in a list of classes of structures (in the sense of model theory) which are "surprisingly" first-order axiomatizable classes. Meaning, the class of structures is defined in such a way that it is not at all obvious that it is in fact first-order axiomatizable. So, for example, the class of fields with exactly 3 elements is axiomatizable, but not surprisingly so.
Comment: Besides that one negative example, a positive example or two would help establish what you are asking for.
Comment: @GregNisbet I would say that the class of models of $Th(\mathbb{N})$ is obviously first-order axiomatizable. More generally, this is true for any $Th(\mathfrak{A})$, by definition of "$Th$."
Comment: @GregNisbet The non-obviousness there is about the "coherence" of $Th(\mathbb{N})$, though; once we understand (or temporarily take for granted) that it makes sense, it's literally trivial that the class of its models is elementary.
Comment: To the OP, here are two nice near-misses: the class of finite symmetric groups is surprisingly "finitely axiomatizable on the class of finite structures," and the class of "$\omega$s of $\mathsf{ZFC}$-models" is surprisingly non-elementary even when we restrict attention to countable structures. See [1](https://math.stackexchange.com/questions/4098806/identifying-the-finite-symmetric-groups), [2](https://math.stackexchange.com/questions/4564392/which-models-of-pa-can-be-standard-in-some-model-of-zfc) respectively.
Comment: So basically, you're asking about non-first-order properties that have non-obvious first-order equivalents.
Comment: This may be a silly example, but does $\text{Th}(\mathbb{N})$, the true theory of arithmetic, count?
Comment: @NoahSchweber that's true, but it was not obvious to me when I first learned about it that you could even define things like $\text{Th}(\mathbb{N})$ without running into circularity or foundational troubles. Other than that, though, I really have no idea what things are surprisingly first-order axiomatizable ... and what level of misconception about first-order axiomatizability an example would be refuting.
Comment: @tomasz Yes, it may be a bit easier to think in terms of properties than classes of structures, but I think that varies from person to person.
Answer: The class of graphs that are 2-colorable.
A graph is 2-colorable if there is an equivalence relation on the set of verteces that has 2cclasses and is such that no adiacent vertexes are in in the same classs.
The description above is second-order, but it is equivalent to the class of graphs without odd cycles, hence first-order axiomatizable.
Comment: More generally, there are many examples in graph theory of a priori existential second-order properties that turn out to be equivalent to the nonexistence of a certain type of finite obstacle, and thus are first-order-expressible.
Comment: @Karl: For each $n$, you say that there is no cycle of length $2n+1$.
Comment: How does one say "there are no odd cycles" in a first-order way?
Answer: How about the class of fields $K$ with a finitely generated (over $K$) algebraic closure?
(It consists of the fields which are either real closed or algebraically closed.)
I think most equivalent definitions (given on Wikipedia) of real closed fields can be turned into examples of this.
Answer: Here's a class of examples which connects to a currently-0pen large-cardinals-flavored question:
Given a first-order theory $T$, let $NE(T)$ be the class of structures not embeddable in a model of $T$. On the face of things, the definition of this class of structures is even worse than second-order, since (even ignoring finite structures) we need the Lowenheim-Skolem theorem to reduce "not embeddable into a model of $T$" to a $\Pi^1_1$ condition. However, $NE(T)$ is always elementary. This is a quick application of compactness (which is also the key step in the proof of the Los-Tarski theorem): we have $\mathcal{M}\in NE(T)$ iff the theory $T\cup AtDiag(\mathcal{M})$ is inconsistent, which happens iff some "finite bad configuration" occurs in $\mathcal{M}$. So in fact we get that $NE(T)$ is not only always elementary, it's always axiomatizable by a set of existential sentences!
Things get more interesting when we iterate this idea. What about, for example, the class $NE_2(T)$ of structures $\mathcal{M}$ which can be embedded into an element of $NE(T)$? Or the "higher $NE_n(T)$s" ($n\in\omega$)? While true elementariness is definitely too much to hope for now, we might at least hope for single-sentence-axiomatizability in infinitary first-order logic $\mathcal{L}_{\infty,\infty}$. (This is closely-related to question 57/58 of Hamkins and Woloszyn). While this is still open to the best of my knowledge, we do have some partial progress: the answer is affirmative assuming an appropriate large cardinal hypothesis, and in particular we get a conditional affirmative answer to H/W's question. In fact, assuming a really strong large cardinal axiom (Vopenka's principle), we get a kind of preservation-of-definability argument: if $T$ is an $\mathcal{L}$-theory for any logic $\mathcal{L}$, then the $NE_n(T)$s are uniformly-infinitarily-$\mathcal{L}$-definable in an appropriate sense. See the end of this post for the argument.


Stripe subscription with fixed monthly renewal date

Question: I want fixed subscription invoice date on my stripe subscriptions. Currently it takes 30days in each month and If I create a subscription on 1st, next invoice comes on 30th but it should be 1st for every month. Here is my code-
$subscription = $stripe->subscriptions->create([
        'customer' => $customerID,
        'items' => $items,
        'add_invoice_items' => $invoiceitems,
        'payment_behavior' => 'default_incomplete',
        'expand' => ['latest_invoice.payment_intent'],
        'trial_end' => $startdate,
        //'cancel_at' => $enddate,
        'proration_behavior' => 'always_invoice',
        'billing_cycle_anchor' => $startdate
    ]);

Answer: I can see in your code snippet that you are using the billing_date_anchor.  The docs state

Determines the date of the first full invoice, and, for plans with month or year intervals, the day of the month for subsequent invoices.

Based on that here are two things you should try.

Verify the price.recurring attribute has your prices recurring with interval  set to "month" and interval_count set to 1.
Ensure the $startdate value passed in is anchored to your timezone.
Comment: $price = $stripe->prices->create([
              'unit_amount' => $productPrice,
              'currency' => 'aed',
              'recurring' => ['interval' => 'month'],
              'product' => $productID,
            ]);
Comment: interval is alreay set to month
Comment: and startdate is selected by user. I am just adding 30day in selected date -         $delivryDate = strtotime($_POST['ywcdd_delivery_date']);
$startdate = $delivryDate + 24*60*1800;


Keras and Tensorflow: UnboundLocalError: local variable 'self' referenced before assignment

Question: I am following a tutorial for TensorFlow and Keras.
When I run the following syntax:
<code>from keras.models import Sequential
from keras.layers import Dense

model = Sequential()

model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))
</code>
(This is not full stacktrace as StackOverflow wont let me saying it has code only)
I get following error:
<code>--------------------------------------------------------------------
UnboundLocalError                  Traceback (most recent call last)
<ipython-input-49-30ebc8793948> in <module>()
      5 from keras.layers import Dense
      6
----> 7 model.add(Dense(units=64, activation='relu', input_dim=100))

--> 164                     layer(x)
    165                     set_inputs = True
    166                 else:

/usr/local/lib/python3.7/site-packages/keras/initializers.py in __call__(self, shape, dtype)
   self._message_listener.Modified()

UnboundLocalError: local variable 'self' referenced before assignment
</code>
Could this be because of python 3.7?
Comment: That is probably true, because it works on Python 3.6.
Answer: Yes, I had to uninstall and reinstall Python 3.6. Python 3.7 looks like it introduces unexpected behavior. Thankfully, my issue is now resolved.
Comment: You can switch between multiple versions of Python using `virtualenv` or sort by the way. No need to uninstall Python 3.7 if you need it for other projects.
Comment: Indeed. I got annoyed and uninstalled. So the bug exist for TF / Keras on that front.
Comment: This helped me solve my issue too.  Instead of uninstalling 3.7 and installing 3.6 I downloaded anaconda, created a virtual environment for 3.6 along with all the other dependancies.  Thanks!
Answer: I had the same issue. The problem seemed to be with python 3.7. Instead of uninstalling 3.7 and installing 3.6 I downloaded anaconda, created a virtual environment for 3.6 along with all the other dependancies.


Modify metatag description programmatically Drupal 8

Question: I modified the meta-tag title for a view in hook_preprocess_html() using the following code.
if (isset($variables['head_title'])) {
    $variables['head_title'] = $variables['page']['#title'] . " | My web";
}

Is it possible to modify the description in the same hook?
Answer: That depends on your theme and its use of $variables in combination with the description meta tag.
A code snippet for Drupal 8 that does what you want for the Bartik Theme would be the following:
function bartik_page_attachments_alter(array &$page) {
  $description = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'description',
      'content' => 'your description content',
    ),
  );
  $page['#attached']['html_head'][] = [$description, 'description'];
}

This was inspired by this post => https://drupal.stackexchange.com/a/134145/57183
Maybe this does solve your problem!


If $x+y+z=2$ prove that $\sum_{cyc}\frac{1}{\sqrt{x^2+y^2}}\ge2+\frac{1}{\sqrt{2}}$

Question: Let $x,y,z$ be non-negative reals whose sum is $2$. Prove that
$\frac{1}{\sqrt{x^2+y^2}}+\frac{1}{\sqrt{y^2+z^2}}+\frac{1}{\sqrt{z^2+x^2}}\ge2+\frac{1}{\sqrt{2}}$
I have tried bounding them up (assuming that $a\le b\le c$), many inequalities (AM-GM, QM-AM, Cauchy) but nothing has worked. I know that equality is achieved when one of $x,y,z$ is $0$ and the other two are $1$ but that doesn't help.
Answer: Without loss of generality, assume that $x \geq y \geq z$. It is easy to verify that using $(x + \frac{z}{2}, y + \frac{z}{2}, 0)$ to replace $(x, y, z)$ would make the LHS smaller, i.e.,
$$
\frac{1}{\sqrt{x^2 + y^2}} +
\frac{1}{\sqrt{y^2 + z^2}} +
\frac{1}{\sqrt{x^2 + z^2}}
\geq
\frac{1}{\sqrt{\left(x + \frac{z}{2}\right)^2 + \left(y + \frac{z}{2}\right)^2}} +
\frac{1}{y + \frac{z}{2}} +
\frac{1}{x + \frac{z}{2}}.
$$
This is obvious as $\left( y + \frac{z}{2}\right)^2 \geq (y + z)^2, \left( x + \frac{z}{2}\right)^2 \geq (x + z)^2$.
As a consequence,  we only need to prove the case where $z = 0$, i.e., for nonnegative $x$ and $y$ with $x + y = 2$,
$$
\frac{1}{\sqrt{x^2 + y^2}} + \frac{1}{x} + \frac{1}{y} \geq 2 + \frac{1}{\sqrt{2}}.\tag{*}
$$
Note that the LHS in (*) could be written as
$$
\begin{align}
\frac{1}{\sqrt{(x+y)^2 - 2xy}} + \frac{x+y}{xy}
&= \frac{1}{\sqrt{4 - 2xy}} + \frac{2}{xy}\\
&= 2 + \frac{1}{\sqrt{2}} + (1 - xy) \left[\frac{2}{xy} - \frac{1}{\sqrt{2}(2 - xy + \sqrt{2 - xy})}\right]\\
&\geq 2 + \frac{1}{\sqrt{2}} + (1 - xy)\left(2 - \frac{1}{2\sqrt{2}}\right)\\
&\geq 2 + \frac{1}{\sqrt{2}},
\end{align}
$$
where we have used the fact that $xy \leq \left(\frac{x + y}{2}\right)^2 = 1$.
Answer: The hint.
By Holder
$$\left(\sum_{cyc}\frac{1}{\sqrt{x^2+y^2}}\right)^2\sum_{cyc}(x^2+y^2)(x^2+y^2+3z^2+2(\sqrt2-1)xy)^3\geq$$
$$\geq\left(\sum_{cyc}(5x^2+2(\sqrt2-1)xy)\right)^3.$$
Thus, it remains to prove that
$$(x+y+z)^2\left(\sum_{cyc}(5x^2+2(\sqrt2-1)xy)\right)^3\geq$$
$$\geq2(9+4\sqrt2)\sum_{cyc}(x^2+y^2)(x^2+y^2+3z^2+2(\sqrt2-1)xy)^3,$$
which is true by $uvw$ (https://math.stackexchange.com/tags/uvw/info).


Outer measure induced by set function

Question: I'm trying to understand the following theorem from Folland's Real Analysis (proposition 1.10 page 29):
Let $\mathcal{E} \subset \mathcal{P}(X)$ and $\rho: \mathcal{E} \mapsto [0,+\infty)$ be such that $\emptyset \in \mathcal{E}, X \in \mathcal{E}$ and $\rho(\emptyset)=0$.
Then for any $A \subset X$ $\mu^*(A)=inf \lbrace \sum_{i=1}^{\infty} \rho(E_i), \forall i \ E_i \in \mathcal{E}, A \subset \cup_{i=1}^{\infty}E_i \rbrace$ is an outermeasure.
I kind of understand the proof except for when he proves the subadditivity:
Suppose $\lbrace A_j \rbrace_{j=1}^{\infty} \subset \mathcal{P}(X)$ and $\epsilon >0$. For each j there exists $\lbrace E_j^k \rbrace_{k=1}^{\infty} \subset \mathcal{E}$ such that $A_j \subset \cup_{k=1}^{\infty} E_j^k$ and
$\sum_{k=1}^{\infty} \rho(E_j^k) \leq \mu^*(A_j) +\epsilon 2^{-j}$...
How does one know that such a sequence of sets exists?
Answer: This is known by the very definition of $\mu^*$. $\mu^*(A_j)$ is the $\inf$ over all sums of this kind, so in the set
$$\{\sum\rho(E_i), \forall i E_i \in {\cal{E}}, A_j \subset \cup_i E_i \} $$
you will find elements which are arbitrarily close to  $\mu^*(A_j)$
Comment: Thanks for your reply! What I'm thinking is that since the only restriction is that $\emptyset$ and X are in $\mathcal{E}$ I can take $\mathcal{E}=\lbrace \emptyset, X \rbrace$. How can I then find elements arbitrarily close to $\mu^*(A_j)$?
Comment: If $\mathcal{E}=\{\emptyset,X\}$, then for each non-empty subset $A$ of $X$, we have that the only such sum in the set is $\rho(X)$.
Comment: @user202542 see the comment of sqtrat. In that case you can always acchieve equlity, and again, you simply refer to the definition.
Answer: Let $B\subseteq X$ and define $E_1=X$ and $E_i=\varnothing$ for $i=2,3,\dots$
Then $B\subseteq\bigcup_{i=1}^{\infty}E_i$ so that by definition: $$\mu^*(B)\leq\sum_{i=1}^{\infty}\rho E_i=\rho(X)+0+0+\cdots=\rho(X)<\infty$$
In fact we can say that: $$0\leq\mu^*(B)=\inf S_B<\infty$$ where $S_B$ is a non-empty subset of $[0,\infty)$.
That means that for any $\delta>0$ we can find a value $s\in S_B$ with $\mu^*(B)<s\leq\mu^*(B)+\delta$.
This is applied on $B=A_j$ and $\delta=\epsilon2^{-j}>0$.

Outer measure induced by set function


Views query building internals

Question: I have looked at the source code, briefly, and the problem is that the module is a complex "beast" that relies heavily on the core's API which I am not currently familiar with.
I have a kind of pieced together on how Drupal assembles a completed node object by traversing the various tables (node, node_type, field_config, field_config_instance, etc).
What confuses me is the data abstraction layer. field_config has a storage_type which appears to indicate whether a field is stored in SQL or not.
From what I have read and interpreted, Drupal is flexible enough to have a system which is data store agnostic, so if I had a products content type and capacity out-grew what MySQL was capable of, I could (in theory) switch to MongoDB or similar DBMS which allows better scaling.

So, how would I attach a field to a content type, which let's say was stored in Mongo, but the remaining fields stayed in SQL?
More interesting, how does VIEWS deal with this disconnection in data storage? If I store some fields for a given type in MongoDB and some in SQL how does VIEWS handle the JOINS and filtering capability?
Comment: As far as I know field storage has to be set globally, not per field. If you use mongo you can say goodbye to relationships in views, as mongo doesn't support them in the same way. I'm pretty sure this should answer your question fully: http://drupal.stackexchange.com/questions/84883/does-using-mongodb-for-field-storage-limit-functionality
Comment: As I understand it you'd be able to get entity/field data into there using the [EFQ Views](https://drupal.org/project/efq_views) module, but it does limit things (you couldn't link the node author entity through to a node-based view, for example). I'm not sure why that flag is per-field to be honest, I'd probably go with your suspicion that it was for future work, but then everything changed in D8 so it hasn't been continued. Always happy to help, this is also a very interesting question :)
Comment: So the implicit JOINS D7 performs between node A and node B would not be possible if Mongo was used? I figured as much, and if they do, I am very curious to know how it's done...Still confusing me though, why would D7 store the field type on a per field basis if its supported only globally? I can only assume this is a future spec they are looking into?? Thanks again - your always a help :)
Answer: As it currently stands it is not possible for Drupal to run a pure MongoDB installation with Drupal. Drupal has made a lot of progress towards abstracting out database connectivity into a central model layer with Drupal 7 and Drupal 8 promises even more. However it is still a work in progress and while a majority of the functionality is available as MongoDB backend, as it stands today a few of the components remain dependant on SQL.
As most of the work to port Drupal to MongoDB has been towards scalability and performance, it is possible to have a site where public page views are 100% on MongoDB. Performance benchmarks on a MongoDB backed Drupal instance are quite impressive.

Views query building internals


Why is my record update giving a null pointer exception?

Question:
I am creating notepad application and want to update my notes but I am unable to record in sqlite database. Please check my update query
I am sharing error details.
public class MainUpdateActivity extends Activity  {

SQLiteDatabase mydb1;
EditText titleedit,notetextedit;
Button update;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        titleedit=(EditText)findViewById(R.id.title);
        notetextedit=(EditText)findViewById(R.id.notetext);
        update=(Button) findViewById(R.id.update);

        Intent myintent = getIntent();

        String product7 = myintent.getStringExtra("product1");
        String product8 = myintent.getStringExtra("product");

        titleedit.setText(product7);
          notetextedit.setText(product8);

update.setOnClickListener(new View.OnClickListener()
            {

            public void onClick(View v)
            {
mydb1.execSQL("UPDATE notes SET (title,notetext) values(?,?);",new String[]{titleedit.getText().toString(),notetextedit.getText().toString()});

Toast.makeText(getApplicationContext(), "note Updated", 3000).show();

            Intent myIntent1 = new Intent(MainUpdateActivity.this,menu.class);

            startActivity(myIntent1);

            finish();

            }

            });

Comment: what is your MainUpdateActivity line 63?
Comment: mydb1.execSQL("UPDATE notes SET (title,notetext) values(?,?);",new String[]{titleedit.getText().toString(),notetextedit.getText().toString()});
Answer: you have declared SQLiteDatabase mydb1 but not initialized it. Error is in this line.
mydb1.execSQL("UPDATE notes SET (title,notetext) values(?,?);",new String[]{titleedit.getText().toString(),notetextedit.getText().toString()});

You need to initialize mydb1.
Comment: thanks i correct it :)
Answer: Looks like in
mydb1.execSQL("UPDATE notes SET (title,notetext) values(?,?);",new String[]{titleedit.getText().toString(),notetextedit.getText().toString()});

mydb1 is null,you didn't new and init mydb1.
Comment: yes,`toString` can be removed.
Comment: Note: an **explicit** `.toString()` conversion is not really needed, here, since the inclusion in the string array will automatically perform the **implicit** conversions.
Comment: no its not null it has two record.
Comment: @ramanrayat,I mean you don't init value for `mydb1`.For exmaple,you should use `SqlLiteOpenHelper.getWriteableDatabase()` to init it.
Comment: still i didn't get you please correct my code if you can..
Comment: Please refer [sqlite doc](http://developer.android.com/intl/es/guide/topics/data/data-storage.html#db),you should create your own  `SqlLiteOpenHelper`,and create databse then init `mydb1`.
Comment: i can't do this at this stage because it already a very large code.do you have any other suggestions ?
Comment: Thanks i correct it by my way ;)

public class MainUpdateActivity extends Main1Activity (it include insert query where my database is initializing )


Why is my stored procedure query returning extra results?

Question: I have the following query inside of a stored procedure:
CREATE PROCEDURE [s_Staff_ByLikeLastNmByLikeFirstNm]

 @LastNm varchar(10),
 @FirstNm varchar(10)

 /*WITH ENCRYPTION*/

AS

SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ COMMITTED

SELECT
    Staff.FirstNm,
    Staff.LastNm
FROM
    Staff
WHERE
    Staff.LastNm LIKE @LastNm + '%'
    AND Staff.FirstNm LIKE @FirstNm + '%'

If I input 'Christiansen' in my query for @LastNm, when I execute the stored procedure, it is returning me both 'Christiansen' and 'Christianson', and performing more of a SOUNDEX search.
How can I fix this?
If I run do a select outside of the stored procedure, I am getting the correct results.
Comment: `LIKE` doesn't do soundex.
Answer: 'Christiansen' has 12 characters in it.
You have defined the parameters to the stored procedure to have a length of 10, so the value is truncated to 'Christians'.
Fix the length parameter in the declaration of the stored procedure.


A probability problem

Question:
Possible Duplicate:
Card probability problem

The following question was asked on a closed online forum. I think the correct answer is 1/2, however the original poster insists that it's 1/3. What is the correct answer?

I have 3 cards, one black on both sides, one red on both sides, and
  one that is red on one side and black on the other. I shuffle the
  cards, select one completely at random and hold it up to you. The side
  of the card you see is red. What is the probability that the other
  side of the card is black?

1/3
1/2
2/3
Comment: Does shuffling also include changing which side is up?
Comment: @Egbert, no. (filler)
Answer: The correct answer is 1/2.  There are 3 card but 1 has both sides black.  So given the face you see is red only 2 cards are possible.  They are equally likely.  So the chance it is black is 1/2.

A probability problem


Problemas ao compilar BitBucket +Eclipse

Question: Eu uso o Eclipse para compilar/modificar servidores de jogos emulados em Java e sempre usei a Assembla, ela usa o build.xml para compilar e nunca tive problemas.
Tenho um projeto que preciso compilar e está no Atlassian/BitBucket e por todas as maneiras que tentei, não consegui compilar o projeto!
O link é este: Projeto e se alguém me der uma luz, ficarei imensamente agradecido.
Answer: Como este projeto possui o arquivo pom.xml, ele está estruturado com Maven. O processo de build do Maven segue um ciclo de vida com fases de construção e distribuição da aplicação.
Para fazer o build pelo Eclipse clique com o botão direito no projeto e escolha a opção Run as e, em seguida, Maven Build.
Mais informações aqui.
Comment: Para mim não aparece essa opção, tu teria um tutorial para que eu possa seguir?
Muito obrigado!


PG::Error: ERROR: out of memory on Heroku

Question: I deployed an application on Heroku. I'm using the free service.
Quite frequently, I get the following error.
PG::Error: ERROR:  out of memory

If I refresh the browser, it's ok. But then, it happens again randomly.
Why does this happen?
Thanks.
Sam Kong
Answer: If you experience these when running queries, your queries are complicated or inefficient. The free tier has no cache, so you're already out there.
If you're getting these errors otherwise, open a support ticket at https://help.heroku.com
Answer: heroku restart simply helped me though
Comment: @Emmanuel If you have to regularly restart, or pg:killall, then you may have a connection leak, meaning your application is getting hung / dead connections and simply opening new ones. Each connection needs memory to maintain, and you run out.
Comment: `restart` would only have an affect here if your connection count was high and consuming too much memory, in which case a restart should clear our all those connections. Heroku Postgres databases are not run on dynos. `restart` does not restart your database instance.
Comment: yes @catsby, in my case I have to run heroku pg:killall and it goes back to normal. it happens regularly these days. any idea how to avoid it ?
Answer: If you are not in a free tier, its maybe because you are using too much memory connecting to PG.
Consider an app running on several dynos, with several processes, each with lots of threads, maybe you are filling up the pool.
Also, as it appears in Heroku's Help Center maybe you are caching too many statements that wont be used.


List of Exchange 2007 Mailbox attributes(properties) using by powershell command?

Question: I need to list exchange 2007 mailbox attributes (using powershell), which can be set using powershell command (Enable-Mailbox). Do you know how I can do this?
I know the list of parameters are here: http://technet.microsoft.com/en-us/library/aa998251%28EXCHG.80%29.aspx, could there be any custom parameters which is not listed here ?
Answer: try using:
get-mailbox

TechNet
Edit after comments:
set-mailbox mailboxname | Get-member | ? { $_.membertype -eq "Property"} # give all properties usable with se-mailbox commandlet

Get-Mailbox | Get-member | ? { $_.membertype -eq "Property"} #This give a list of all properties available from the Get-mailbox cmdlet

Comment: Tried. If I do not specify Identity in this command it returns me a list of all mailboxes(it is a lot of info). Specifying the Identity is not acceptable for me. I need only property names which I get while using this command for one mailbox
Comment: Get-Mailbox | Get-member | ? { $_.membertype -eq "Property"} #This give a list of properties available from the Get-mailbox cmdlet
Comment: Thanks a lot Christian, that is exactly what I need


Open and Closed Set Problems using a Ball

Question: I am having trouble with these two questions. In particular, using a ball and choosing an $r$ to show that a set is open.

(a)
  $$X = \left \{  \mathbf{x} \in \mathbb{R}^d | \:  ||\mathbf{x}|| \leq 1 \right \} .$$

So, $X$ is closed if its compliment $X^c$ is open. So if I can show that $X^c$ is open, then it follows that $X$ is closed. I'll start with the definition I am using for a ball.

The ball about $\mathbf{a}$ in $\mathbb{R}^n$ of radius $r$ is the set
  $$B_{r}(\mathbf{a})= \left \{ \mathbf{x} \in \mathbb{R}^n : || \mathbf{x} - \mathbf{a} || < r\right \}$$
  A subset $U$ of $\mathbb{R}^n$ is open if for every $\mathbf{a} \in U$, there is some $r=r(a) > 0$ such that the ball is contained in $U$.

So, I have a set $X^{c} = \left \{  \mathbf{v} \in \mathbb{R}^d | \:  ||\mathbf{v}|| > 1 \right \} $. It consists of points whose lengths are longer than 1. Let $\mathbf{a} \in X^{c}$, then $|| \mathbf{a} || > 1$. Now, using $B_{r}(\mathbf{a})$ as it is written above, how do I find an explicit formula for $r>0$? Intuitively it seems to make sense if $\mathbf{x}$ is in $X$, then $0<|| \mathbf{x} - \mathbf{a} ||$ as $||\mathbf{x}|| \neq  ||\mathbf{a}||$. I am not sure how to proceed.

(b)
  $$X = \mathbb{R}^2 \setminus \left \{  \mathbf{x} \in \mathbb{R}^2 | \mathbf{x}=(x,0) \: \right \}$$

I know that this set is open, but it again comes down to choosing some $r$ and using a ball. The set is $\mathbb{R}^2$ less a line across the x-axis - that is, any $x$ and any $y$ with $y \neq 0$. The line has no height, so it should be easy to show that for any $\mathbf{a} \in X$  there exists $r>0$ such that $B_r(a) \subseteq X$.
I've done lots of scratch work and diagrams etc. but I just can't seem to put this concept together. Any help and clarification would be appreciated.
Answer: HINT: Suppose that $\mathbf{x}\in\Bbb R^d$ with $\|\mathbf{x}\|=r>1$. Let $\epsilon=r-1$. Does $B_\epsilon(\mathbf{x})$ contain any points of the closed unit ball $X$? (If you're not sure about that $\epsilon$, cut it in half.)
Added: Sorry: I missed the second question originally. You can use the same idea. Suppose that $\mathbf{p}=\langle x,y\rangle\in X$, so that $y\ne 0$. Let $r=|y|$; does $B_r(\mathbf{p})$ contain any point of the $x$-axis?
Answer: Regarding you second question: Let $a\in X$, and you want to find $r>0$ such that $B_r(a)\subseteq X$. What could "go wrong"? Well, this ball might contain points of the form $(x,0)$, and these are not in $X$. So all we have to do is to eliminate this option. Try to figure out a general way of doing it, using an example. Suppose $a=(1,8)$. If you take $r=9$ it won't work, right? But it will work for all $r<8$.
Answer: For (a) draw a plane figure. Choose a point $a\notin X$. How large a circle can you draw around $a$ such that its interior does not intersect $X\>$? Use some form of the triangle inequality to show that what you see is indeed true.
With (b) it's the same thing. Choose a point $a:=(a_1,a_2)\notin X$. How large a circle can you draw around $a$ such that its interior does not intersect $X\>$?


how many users can open a connection to Microsoft Access?

Question: how many users can open a connection to Microsoft Access database simultaneously ?
I am using asp.net 4.0 to write my application.
<code><add name="E_ShopAccessConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\report.mdb;Persist Security Info=True" providerName="System.Data.OleDb"/>
</code>
Answer: The Access database has a limit of 256 connections, but there is a limit of 64 connections per process in the database drivers, and as IIS is a single process your limit is 64.
If you are careful to close your connections, commands and data readers properly, this is usually enough for plenty of users. Each visitor doesn't need a connection of their own.
You are likely to run into other limitations before you run out of connections. If you have many visitors, you will find that the Access database is simply not fast enough, and you need a more advanced database system.
If you are running out of connections, that is most likely because you are not closing database objects properly, so that they are still keeping the database connection alive until they are garbage collected.
Comment: The Jet/ACE limitation is actually 255 simultaneous users, which may or may not map directly onto what you think you have in terms of connections. But that's a theoretical limitation -- nobody ever gets much beyond 50% of the actual theoretical limit. In general, though, I would say that Jet/ACE is not an appropriate data store for a web server application in the first place.
Answer: According to Microsoft: A maximum of 64 connections per process with a limit of 256 concurrent open read/write connections per database.
But with my experience above 20 connections performance goes down significant.
Answer: If you're using MS Access from ASP.NET the site runs under the context of a single user so shouldnt have too many issues.
[Most people wont agree, but I have had experience using MS Access with both ASP and ASP.NET on a fairly high transactional site and it worked fine, make sure the DB is the latest version of MS access]
I would consider using SQL Server Express as an alternative though.
Answer: Not enough.
The depending on the version you can have 5 to 10 but safely its really < 3 for "high volume per user work".
Technically it can get much higher but have had some bad experiences trying to recover files. Generally we advise > 5 as an average should move to something like SQL Server as the backend with the MS Access mapping for the front end.
Comment: Less than three may be correct for ASP.Net implementations but is quite low for regular Access front end back end implementations. I've had at least 10 folks doing pretty constant data entry with another 15 doing miscellaneous stuff and reporting.


Any replacement for get_header in php?

Question: I am creating a function which crawls links from a page.
Now there can be different ways of specifying links in href tag..
1) http://example.com
2) http://www.example.com
3) example.com
4) files/downloads
5) www.example.com
Now here the 1), 2) and 5) are in proper format.
But before adding 3) and 4) i want to make them in proper url format...
which means 3) should become http://example.com and 4) should become
http:// THECURRENTPAGEURLDOMAIN /files/download
I am using get_headers to differentiate between a relative and independent URL. So if i test headers for example.com by appending http:// in front, it would return some headers and
if i test headers for files/download by same method , it would return failed to open stream instead of some false value which i can use to know that its a relative url.
So why get_headers isnt returning false value. It is giving warning about failed to open stream.
Answer: 1- you should have the base your, e.g: example.com
2- check if th url is not a url, then the append it to the base url

is_url($url)
{
    return (bool) filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);
}

$url = '/files/download';
$base_url = 'http://example.com';
if !is_url($url) {
   $url = rtrim($base_url, '/') . '/' . ltrim($url, '/');
}

// continue your code ....

Answer: use curl() or file_get_contents() for faster response use curl
For more info :- PHP get_headers() alternative

Any replacement for get_header in php?


How do you find the area under a curve only for the area above the x-axis?

Question: Let's say I have function $f(x) = -x^2 + 1$ and I want to find the area between that curve and the $x$-axis
I use definite integrals obviously.
Let's say I use the $-3$ and $3$ as my definite values for my integral, meaning I would be looking at both areas under and over the $x$-axis
Besides changing my definite values, is there any way to have my integral only measure the area above the $x$-axis?
Comment: Find the zeroes of $f$, maybe?
Comment: Just found the area where the function is above the $x$-axis and then evaluate the integral inside that interval.
Answer: You have to find the area of the following set:
$$S=\{(x,y) \in \mathbb R^2: x \in [-1,1], 0 \le y \le 1-x^2\}.$$
The area of $S$ is given by
$$ \int_{-1}^1(1-x^2) dx.$$


is $\sin^2 (x)$ the same as $\sin(\sin(x))$?

Question: From my understanding, if something like this is given -> $f^2(x)$ then it is equal to $ff(x)$.
Now if that is the case, then shouldn't $\sin^2 (x)$ be equal to $\sin(\sin x)$, however, I have seen people use it as $\sin(x)^2$. Could someone please clarify my confusion.
Comment: $\sin^2 x =(\sin x)^2=(\sin x)\cdot (\sin x)$. For $\sin (\sin x)$ one possible notation is $\sin^{\circ 2} x$.
Comment: There's not much logic to it. $f^2(x)$ sometimes means $f(f(x))$, sometimes $(f(x))^2$. $\sin^2x$ always means $(\sin x)^2$, but $\sin^{-1}x$ usually means the functional inverse, not the multiplicative inverse. It's all conventions, and context. And it has probably been asked & answered on this site before.
Answer: This is a very annoying notational convention, but:
If $n$ is a positive integer, then $\sin^n(x)$ means $\big(\sin(x)\big)^n$. For instance, $\sin^2(x)$ means $\big(\sin(x)\big)^2$.
If $n$ is $-1$, then $\sin^{-1}(x)$ means the inverse function $\arcsin(x)$, instead of the reciprocal.
I'm not fully certain what happens for other values. I don't know if there's a consensus on what $"\sin^{-2}(x)"$ means.
The same stuff is true for the other trigonometric functions.
For what it's worth, for an arbitrary function like $f$, I like to write $f^{\circ n}(x)$ for $f(\dotsb(f(x)\dotsb)$, as described here, to avoid ambiguity like this. (In general, in mathematical writing, one should always explain such notations to the reader.)
Comment: I think the consensus on $\sin^{-2}x$ is that one should write $\csc^2x$ instead.


Fixtures: How to load utf-8 characters and convert to non utf-8 and save into database?

Question: I am new to Rails.
I am working on a legacy code which relies on Fixtures to load non UTF8 characters from yml files into database.
With rails lastest version, the yml must be utf-8 encoding, meaning that what Fixtures read in will be utf-8 encoding.
How to convert the following codes so that it will convert from utf-8 to non-utf8 and load into database (non-utf8 encoding of course).
<code>class LoadUsersData < ActiveRecord::Migration
  def self.up
    down

    directory = File.join(File.dirname(__FILE__))
    Fixtures.create_fixtures(directory, "users")
  end
  def self.down
    User.delete_all
  end
end
</code>
where users.yml contains data in utf-8 format (have to).
Or is it possible to use .txt (can be in non-utf8 format) and load with Fixtures?
I am using oracle_enhanced, and I tried to change "encoding" to my database encoding in database.yml, but it seems that the conversion is not done automatically from utf-8 to my encoding (because the string length is different for these two encodings with utf-8 has more bytes, and the database returns that user_name is too long error).
Answer: I solved this by

add the following line in boot.rb

ENV['NLS_LANG'] ||= 'AMERICAN_AMERICA.JA16SJIS'

convert all yml files to utf-8 format (Note that uses sjis formatted yml and ruby gem syck will load the yml but fixtures wont work even yml is loaded).


Can I run one way ANOVA at each of my time points?

Question: Suppose that I have two or more groups of data (e.g. two or more cities with 10 sampled population each) and I want to test if they behave differently for a variable (e.g. specific crime) through the years.
Is it correct if I run one way ANOVA or Kruskal-Wallis at each of the time points? I guess the answer is no because the time points are relevant to each other and not independent.
Answer: You're right that a series of one-way ANOVAs is not the best way to model this. Instead, consider repeated measures ANOVA, or a mixed effects model. There are lots of resources for both on CV and elsewhere on the web.
Comment: I haven't read about mixed effects model yet, but considering the repeated measures ANOVA test, what is its non parametric equivalent? Friedman test does not take into account more than one group (city) concurrently.
Comment: That's a new question entirely ("what's a nonparametric alternative to a repeated measures ANOVA"), and probably worthy of its own post. The appropriate answer may depend in part on why you believe you need a nonparametric test.


Perl wsdl webservice call

Question: I am new to perl webservice call.
I am calling a wsdl webservice function and I am getting the response as 400 bad request error. I tried and googled many sites but could not get successful. Please help me in solving this issue. Below is my code.
use SOAP::Lite;
my $lite = SOAP::Lite -> service('http://localhost:8080/service.svc?wsdl');
my $arg1 ="SRC";
my $arg2 = "ARG";
my @arg3 = ('test1','test2','test3');
my @res = $lite->Func($arg1,$arg2,@arg3);
print "@res";

Answer: I just had similar problem and seemed that SOAP::Lite may have a bug concerning handling complex data structures.
Whatever, if your SOAP method (Func) needs 3 arguments, the last one should be reference to array.
Also, with use SOAP::Lite qw(trace) you could debug request envelope.
Comment: tried passing as reference but still says bad request error itself...:(
Comment: @Naga: So next move i sugegst is to debug your request envelope. I bet that third argument is missing from envelope. This may be one reason for bad request.
Answer: If you are not restrict at SOAP::Lite, I will request you to please have a look at XML::Compile::SOAP::Client
Answer: I'm not sure how much of a difference there is between a WSDL and an ASMX web service.  If not much, try this code sample which works for me.
  my $soap = SOAP::Lite
    -> uri('http://foo.com')
    -> on_action( sub { join '/', 'http://foo.com', $_[1] } )
    -> proxy('http://foo/services/GetEmailAddress/Service.asmx');

  my $method = SOAP::Data->name('GetEmailAddress')
    ->attr({xmlns => 'http://foo.com/'});

  my @params = ( SOAP::Data->name(username => $user) );
  my $email = $soap->call($method => @params)->result;

Input is a username, output is an email address.  The ASMX web service was created in .NET 3, I believe.
Everything I know about how this works I learned from http://msdn.microsoft.com/en-us/library/ms995764.aspx.
Comment: tried the above...getting the error like this "cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver.  Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None)"

Perl wsdl webservice call


DPM won't synch due to a non-existent file

Question: DPM 2007
Server with issue is Windows Server 2003 R2 Enterprise Edition
DPM is reporting that "DPM encountered an error while performing an operation for C:\program files\vexira antivirus\server\temp\aa29n3f0.vbt (ID 2033 Details: The parameter is incorrect (0x80070057))"
The problem is that the file isn't there and I am not finding any open file handles referring to that file as being held open (did a search using procexp.exe for handles or dll strings).
The temp subdirectory did have misordered permissions when I checked them, but I told Windows to reset the permissions and verified that applications should have access to the subdirectory and it no longer complained about access issues.
Anyone else run into this issue before with DPM?
Comment: Any VSS snapshots (`vssadmin list shadows` should list them)?
Comment: @ChrisS: No items found that satisfy the query
Answer: Not exactly a solution to the synch issue, but if you cancel the sync and do a consistency check it should resolve the issue and allow you do create a manual recovery point (or wait for the next scheduled one).
Comment: Worked. Don't know why, can't explain it. There was an order-of-ACL's issue before this on that subdirectory, perhaps that interfered with it at some point and created an inconsistency that made DPM's head rattle.
Comment: Thank you. Had this error for quite some time and tried *a lot*. Now I found the consistency check option only in the "Protection" menu, not in the "Monitoring" menu, DPM 2016.


Join two tables (users and userpoints_total)

Question: I'm working with Drupal Commerce, and I am currently developing a new module that displays the best customers that have a maximum points in a single block.
I want to do a join between the two tables (users and userpoints_total)
$query = db_select('users', 'u')
  ->fields('u',array('name','uid'));
$query->join('userpoints_total', 't', 't.uid = u.uid');
$results = $query->execute();

That works but in the block views I can't see anything. This is the code:
    function best_client_block_view($delta = '') {
      switch ($delta) {
        case 'best_client':
          $block['subject'] = t('Les meilleures Clients Chez nous');
          if (user_access('access content')) {
            // Use our custom function to retrieve data.
            $result = best_client_contents();
            // Array to contain items for the block to render.
            $items = array();
            // Iterate over the resultset and format as links.
        if (is_array($result) || is_object($result))
            {
            foreach ($result as $node) {

              $items[] = array(
                'data' => t($node->name),

              );
            }
        }
           // No content in the last week.
            if (empty($items)) {
              $block['content'] = t('No user available.');
            }
            else {
              // Pass data through theme function.
              $block['content'] = theme('item_list', array(
                'items' => $items));
            }
          }
        return $block;
      }

    }

How can I fix that?
Comment: Would you be interested in a Views based answer to create such block? I.e. based on user points (ranking), and similar to the block you can see [here](http://drupal.placeto.be/answers/rankings/reputation), in the left column with block title "Top Users".
Answer: You don't call a result set method on your query. Try $results = $query->execute()->fetchAll(); and have a look at the results via devel or something similar.
I believe that block['content'] defaults to markup but theme functions return HTML strings not renderable arrays so you could try to use the #markup key to make them render.
$block['content']['#markup'] = theme('item_list', array('items' => $items));

Or use the theme as a part of the render array.
$block['content'] = array(
  '#theme' => 'item_list',
  '#type' => 'ul',
  '#items' => $items
)

Comment: Hmm, updated answer to adres another possible issue. Could you post your entire query @SeifBh and and show us the content of the result?
Comment: but he tell always << no users avaible >> i can't understand , my query is correct, can you give me a solution?
Comment: @SurangaPanagamuwaGamage Thankyou for your answer, the same thing , i always see << no users avaible >> , and this is my query
Comment: function best_client_contents() {

$max_num = variable_get('best_client_max', 3);

$query=db_select('users','us');

$query->join('userpoints_total','up','us.uid = up.uid');

$query->condition('us.uid','1')
                       ->fields('us',array('name','uid'))
                       ->fields('up',array('uid','points'));

$results = $query->execute()->fetchAll();

     }
Comment: Ah I see, if you're not going to use the items as render arrays you don't need to use `data` (wich I believe expects a render array), try using `$items[] = t($node->name)` directly
Comment: without foreach ?
Comment: no in the foreach, replace
`$items[] = array('data' => t($node->name),); ` with `$items[] = t($node->name);`
Comment: dosen't work man !
Comment: the same message << no user avaible >> with error : Invalid argument supplied for foreach() dans best_client_block_view()
Comment: And you're sure your query returns a result? Use print_r or some devel function to print out the $result
Comment: yes i test that in the  function best_client_contents() like that foreach($result as $node){print $node->name}
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/24581/discussion-between-seifbh-and-suranga-panagamuwa-gamage).
Comment: show us a print_r of the result variable then. Because I can't see any reason why it wouldn't work apart from that the result set is somehow not a valid array of objects...
Comment: where i put the print_r ? in the hook_block_view() or where ?
Comment: this is the result of print: Array ( [0] => stdClass Object ( [name] => SeifEddineBh [uid] => 1 [up_uid] => 1 [points] => 3670 ) )
Comment: Warning : Invalid argument supplied for foreach() dans best_client_block_view()


Morphism of quasi affine varieties giving algebra homomorphism and back.

Question: $\newcommand{\set}[1]{\{#1\}}$ $\newcommand{\vp}{\varphi}$ $\newcommand{\mr}{\mathscr}$ $\newcommand{\mc}{\mathcal}$
$\newcommand{\A}{\mathbb A}$
I am new to algebraic geometry and in the following I ask two related questions that have come to my mind given the material I have read so far.
I believe the notation and terminology I have used is standard.
However, I have supplied most of the relevant definitions and notations in the appendix.
Please feel free to correct and inaccuracies.
In what follows $k$ is an algebraically closed field.
Question 1
Let $X$ and $Y$ be affine varieties.
It is a fact that a morphism $\vp:X\to Y$ is an isomorphism if the corresponding map $\vp^*:\mr O(Y)\to \mr O(X)$ is an isomorphism of $k$-algebras.

Question.
Can we extend this fact to the case when $X$ and $Y$ are quasi affine varieties, that is, is a morphism $\vp:X\to Y$ an isomorphism if and only if the corresponding map $\vp^*:\mr O(Y)\to \mr O(X)$ is an isomorphism of $k$-algebras?

The problem I am facing in proving this is the following.
When $X$ and $Y$ are affine varieties in $\A^m$ and $\A^n$ respectively, then we have $\mr O(X) = k[x_1, \ldots, x_m]/\mr I(X)$ and $\mr O(Y) = k[y_1, \ldots, y_n]/\mr I(Y)$.
Now once we have a $k$-algebra homomorphism $\mr O(Y)\to \mr O(X)$, we get a morphism of varieties $X\to Y$ by using the induced map $\text{MaxSpec}(\mr O(X))\to \text{MaxSpec}(\mr O(Y))$ and then use the nullstellensatz to get a map $X\to Y$.
However, when $X$ and $Y$ are quasi affine varieties in $\A^m$ and $\A^n$ respectively, then one cannot think of $\mr O(X)$ or as a quotient of $k[x_1, \ldots, x_m]$ (and similarly for $\mr O(Y)$).
For instance, let $X=\A^1\setminus \set{0}$. Then $\mr O(X) = k[x]_{x}$ which is not a quotient of $k[x]$ but of $k[x, y]$.
So I am unable to identify $\text{MaxSpec}(\mr O(X))$ and $\text{MaxSpec}(\mr O(Y))$ as subsets of $\A^m$ and $\A^n$.
Question 2
Let $\mc V$ be the category of affine varieties and $\mc A$ be the category of finitely generated $k$-algebras that are integral domains.
We get an equivalence between two categories by associating to an affine variety its coordinate ring and to a morphism its corresponding map between the algebras, namely the pullback map.

Question.
Is there such a statement for the category of quasi affine varieties, that is, is there a nice algebraic category to which the category of quasi affine varieties equivalent?

Question.
Suppose we consider the category of subsets of $\A^n$, $n\geq 0$.
We can still define $\mr O(X)$ for any such subset and form a category with morphisms as maps which pullback regular functions to regular functions.
Is this category useful in any way? Is there a reason why it is not studied?

Appendix
Let $k$ be an algebraically closed field.
We write $\A^n$ to denote $k^n$ with the Zariski topology.
An affine variety is an irreducible closed subset of some $\A^n$.
Given an affine variety $X$ in $\A^n$, the coordinate ring $\mr A(X)$ of $X$ is defined as $k[x_1, \ldots, x_n]/\mr I(X)$, where $\mr I(X)$ is the set of all the polynomials in $k[x_1, \ldots, x_n]$ which vanish on each point of $X$.
It turns out that $\mr I(X)$ is a prime ideal.
A quasi affine variety is any open subset of an affine variety.
A regular function on a quasi affine variety $Y\subseteq \A^n$ is a map $\vp:Y\to k$ which can be locally written as a quotient of polynomials in $k[x_1, \ldots, x_n]$.
The set of all the regular functions on $Y$ is denoted by $\mr O(Y)$.
It turns out that $\mr O(Y)$ has a natural $k$-algebra structure.
It is a fact that if $X$ is an affine variety, then $\mr A(X)$ can be naturally identified with $\mr O(X)$.
A morphism of quasi affine varieties $X$ and $Y$ is a map $\vp:X\to Y$ which is continuous (in the Zariski topology) such that $\vp$ pulls back regular functions on $Y$ to regular functions on $X$.
Given a morphism $\vp:X\to Y$, we get the pullback map $\vp^*:\mr O(Y)\to \mr O(X)$, and it is easy to check that $\vp^*$ is a $k$-algebra homomorphism.
Answer: The problem with quasi-affine varieties is that, well, they are not affine. You should think of an affine variety as one that is ``determined by its global regular functions'' and this is not the case for arbitrary quasi-affine varieties.
Here is a classic example: let $X = \mathbb{A}^2 \setminus \{ (0,0) \}$. Then I claim $\mathcal{O}(X) \cong k[x,y]$ where the map $\mathcal{O}(\mathbb{A}^2) \to \mathcal{O}(X)$ induced by the inclusion $X \subset \mathbb{A}^2$ is an isomorphism. I highly recommend you try to prove this if you are not familiar with the example. It is often thought of as an algebraic version of the Harthogs's phenomenon.
This example shows that the answer to Question 1 is no. In Question 2, I don't know of any purely algebraic description and the category you suggest is useful it just does not give information about the quasi-affine varieties $X$ rather it tells you about the affine varieties $\mathrm{Spec}{(\mathcal{O}(X))}$.
Note: when you say subsets, I assume you mean locally closed subsets for the Zariski topology since an arbitrary subset of $\mathbb{A}^n$ need not have the structure of an algebraic variety.
Comment: @RagingBull if $Y$ is affine then for any variety (even scheme or even any locally ringed space) $X$ it is true that $\mathrm{Hom}(X, Y) = \mathrm{Hom}_{\mathrm{Ring}}(\mathcal{O}(Y), A(X))$  as sets. However, that does not mean that isomorphisms on one side have to carry over to isomorphisms on the other side. In this example, the rings are isomorphic but the isomorphism of rings corresponds to the canonical inclusion map $X \to \mathbb{A}^2$ which is not an isomorphism.
Comment: Helpful answer. Thanks. By *subsets* I mean only subsets. I think there is no problem in defining $\mathscr O(X)$ for an arbitrary subset of $\mathbb A^n$. This may not be useful and that is my third question.
Comment: Can you explain how you define $\mathcal{O}(X)$ for an arbitrary subset of $\mathbb{A}^n$?
Comment: Let $X$ be a subset of $\mathbb A^n$. A map $f:X\to k$ is said to be regular is for each $p\in X$ there is an open set $U$ in $X$ and polynomials $g$ and $h$ in $k[x_1, \ldots, x_n]$ such that $h$ does not vanish on $U$ and $f = g/h$ at all points of $U$. (Here $X$ has the subsapce topology of the Zariski topology on $\mathbb A^n$, of course). The set of all the regular functions on $X$ is denoted by $\mathscr O(X)$.
Comment: @BenC with regards to question-1 please take a look at this video lecture:
https://www.youtube.com/watch?v=4ozDnMxA2z4&list=PLbMVogVj5nJSNj24jdPGivlJtxbxua2by&index=19
at the 11th minute. The professor actually proves that if X is quasi-affine or affine and Y is affine then we do have a bijection from the set of morphisms between X and Y and the set of isomorphisms between A(Y) and O(X). But then your example has got me confused. Please explain.
Comment: This is a general phenomenon of adjunctions. For example, you may know that $\mathrm{Hom}_A(M \otimes_A N, K) = \mathrm{Hom}_A(M, \mathrm{Hom}_A(N, K))$ as $A$-modules but if $K = M \otimes_A N$ then the isomorphism $\mathrm{id} : M \otimes_A N \to M \otimes_A N$, of course, cannot correspond to an isomorphism $M \to \mathrm{Hom}_A(N, M \otimes_A N)$ on the other side since the target is much bigger than the source (think about free modules for example).
Comment: @BenC I got it now.Thanks a lot for the help!
Answer: "Question. Can we extend this fact to the case when $X$ and $Y$ are quasi affine varieties, that is, is a morphism $φ:X→Y$ an isomorphism if and only if the corresponding map $φ∗:O(Y)→O(X)$ is an isomorphism of k-algebras?"
Example 1. If $\phi: \mathbb{P}^1_k \rightarrow \mathbb{P}^d_k$ is the $d$-uple embedding with $d\geq 2$, it follows $\phi$ is not an isomorphism. But
$$\Gamma(\mathbb{P}^1_k, \mathcal{O}_{\mathbb{P}^1_k}) \cong \Gamma(\mathbb{P}^d_k, \mathcal{O}_{\mathbb{P}^d_k}) \cong k$$
Hence the global sections are isomorphic, but the varieties are not (a projective variety is quasi projective). Hence it seems the correspondence you mention can not be extended to quasi projective varieties. You find this construction in Hartshornes book, chapter I and II. The projective varieties $\mathbb{P}^1_k$ and $\mathbb{P}^d_k$ have different dimensions, but their structure sheaves $\mathcal{O}_{\mathbb{P}^1_k}$ and $\mathcal{O}_{\mathbb{P}^d_k}$ have the same number of global sections. In chapter I you find the definition of the $d$-uple embedding and in chapter II you find the definition of the structure sheaf.
Example 2. If $k$ is algebraically closed, $X:=Spec(k[x,y])$ and $U:=X-\{(0,0)\}$ it follows there is an isomorphism
$$i^{\#}: \Gamma(X, \mathcal{O}_X) \cong \Gamma(U, \mathcal{O}_U)\cong k[x,y]$$
(Hartshorne Exercise I.3.6) but $X$ and $U$ are not isomorphic. Hence the correspondence seems not to hold for quasi affine varieties either.
The map $i^{\#}$ is induced by the inclusion
$$ i: U \rightarrow X.$$
The scheme $U$ is not affine.
You may change the  notion "regular map" - this is discussed briefly here:
Regular rational functions over real projective lines and projective spaces.
Example 3. If $k:=\mathbb{R}$ is the field of real numbers and $f:=x^2+y^2$
it follows $Z:=V(f):=Spec(A)$ where $A:=k[x,y]/(f)$. $Z$ has $(0,0)$ as the only rational point: $x^2+y^2=0$ iff $(x,y)=(0,0)$. Why? Let
$$\phi: A \rightarrow k$$
be a map of $k$-algebras.It follows $\phi(x)=a, \phi(y)=b$ for $a,b\in k$.
Since the map $\phi$ is well defined it follows $\phi(x^2+y^2)=a^2+b^2=0$, and from this it follows $a=b=0$. Hence the only $k$-rational points of $Z$ is the point $(0,0)$. Hence we may claim that $Z=\{(0,0)\}$ is the "one point space"
with only rational point $(0,0)$. It is defined as closed subscheme of $X:=Spec(k[x,y])$ corresponding to the ideal $I:=(f)$, hence $Z$ is indeed a hypersurface in $X$.
Let $U:=X-Z:=X-\{(0,0)\}$. Since $U$ is the complement of the "hypersurface" $Z$, it follows $U\cong D(f)\cong Spec(B)$ where
$$B:=k[x,y,t]/(tf-1)$$
hence $U$ is affine. Hence over a non-algebraically closed field $k$ it follows $U:=\mathbb{A}^2_k-\{(0,0)\}$ may be an affine scheme.
Note: If $\mathfrak{m}:=(x,y)$ and $P:=Spec(k[x,y]/\mathfrak{m})$ we may realize $V(\mathfrak{m})$ as a closed subscheme of $Z$: There is a canonical surjective map
$$ A \rightarrow k[x,y]/\mathfrak{m}\cong  k.$$
Hence the hypersurface $Z$ is the rational point $(0,0)$ with a non-trivial scheme structure.
Example 4. This generalize as follows. Let $k$ be the field of real numbers and let $J:=(f_1,..,f_k)\subseteq A:=k[x_1,..,x_n]$ be an ideal generated by the polynomials $f_i$. Let
$$F(x_1,..,x_n):=f_1^2+\cdots +f_k^2 \in A.$$
It follows $F$ defines a hypersurface. Let $B_1:=A/J, B_2:=A/(F)$ and let $X_i:=Spec(B_i)$ for $i=1,2$.
Lemma: The two affine schemes $X_1,X_2$ have the same $k$-rational points.
Proof: Assume $\phi: B_1\rightarrow k$ is a map of $k$-algebras. It follows
$$ \phi(x_i)=a_i$$
for $i=1,..,n$ and since $\phi$ is well defined it follows $f_j(a_1,..,a_n)=0$
for all $j=1,..,k$. Hence the point $a:=(a_1,..,a_n)$ is a zero of the polynomials $f_j$. It follows
$$F(a_1,..,a_n):= \sum_j f_j(a_1,..,a_n)^2=0.$$
Conversely if $\phi: B_2\rightarrow k$ is a map of $k$-algebras with $\phi(x_i):=a_i\in k$ it follows
$$F(a_1,..,a_n)=0.$$
It follows
$$F(a_1,..,a_n):= \sum_j f_j(a_1,..,a_n)^2=0$$
and since $f_j(a_1,..,a_n)^2\geq 0$ it follows $f_j(a_1,..,a_n)=0$ for all $j=1,..,k$. This sets up a 1-1 correspondence between $k$-rational points of $X_1$ and $k$-rational points of $X_2$. QED.
Note: $X_1$ and $X_2$ have the same rational points but are not isomorphic as affine schemes in general. Over the field of real numbers, any "real affine algebraic variety" may set-theoretically be realized as the zero set of a single polynomial.
Since there is an inclusion of ideals $(F) \subseteq J$, we get a canonical map of affine schemes
$$\phi: X_2\rightarrow X_1$$
where $\phi$ induce a bijection $X_2(k)\cong X_1(k)$ at the level of $k$-rational points, but $\phi$ is not an isomorphism of schemes. Moreover the hypersurface $(F)$ depends on the choice of generators of the ideal $J$. If $X_i$ are "smooth algebraic varieties" we get an induced isomorphism of real smooth manifolds $(X_1)_k \cong (X_2)_k$.
Comment: The conclusion of example 3 ("over a non-algebraically closed field ... $\Bbb A^2_k\setminus\{(0,0)\}$ may be affine") is completely false. $\Bbb A^2_k\setminus\{(0,0)\}$ is never affine over any field $k$.


Process finished with exit code -1073740791 (0xC0000409) error shown in IntelliJ

Question: While running a program in IntelliJ which was running earlier but now this error pops up:

and this error is shown
Process finished with exit code -1073740791 (0xC0000409)
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: This can be because of following reasons:

The incorrect or failed installation of application that may have left invalid entries in your Windows registry;
The virus or malware attack;
The improper system shutdown;
Corrupted or deleted system files.

You need to either restart the program or shutdown the system once and try to start the program again.
If that doesn't help re-install the application again.


SARIMA vs deseasonalizing with ARIMA

Question: I am trying to check what is the differnce between  modeling a time series with:

SARIMA
Deseasonalizing it first and then using ARIMA

Is there a preferable method over the other? If yes, why ?
Comment: Depends on the data generating process and on the method of seasonal adjustment (there are many). Some processes can be better approximated by SARIMA, other by other models of seasonality.
Comment: Related question: [ARIMA vs SARIMA](https://stats.stackexchange.com/questions/413176/arima-vs-sarima).
Comment: @RichardHardy: do you want to post your comment(s) as an answer? [Better to have a short answer than no answer at all.](https://stats.meta.stackexchange.com/a/5326/1352) Anyone who has a better answer can post it.
Comment: @StephanKolassa, you are right. Posted.
Comment: Dear Mr. @RichardHardy, thank you for your answer, however I think it is missing some references, o rat least some examples to show that in which cases deseasonalization is prefered over SARIMA.
Comment: Thanks, I will see what I can do.
Answer: The answer depends on the data generating process and on the method of seasonal adjustment ("deseasonalizing") of which there are many. Some processes can be better approximated by SARIMA, other by other models of seasonality. There is no method or model that is universally the best.

SARIMA vs deseasonalizing with ARIMA


Is that any way to alter the sqlite table

Question: I was create the SQLite database in Chrome extension,after that i want to modify the table column value in xcode,that is returns an error.

Error:the table has the no column value.

NOTE:I used the following code to alter the table,
<code>[instance.database executeQuery:@"ALTER TABLE studentInfo ADD COLUMN l3 TEXT"];
</code>
Comment: Well you need to obtain the exact error text and I don't see what that error message means.  I assume you've copied the database file from the app bundle into the documents folder before attempting to write to it?
Comment: You want to modify it in Xcode?  What does that mean?  Also what framework does `executeQuery:` belong to?
Comment: yes i want to modify,i think you are not getting my point.i used the FMDB framework
Comment: And did you write the error text "the table has the no column value"?  I ask as there is no reference to that text anywhere on the internet apart from this question.  If so you need to find the actual error text from the database (I don't know how that's done in FMDB as I don't use it).
Comment: Explain it clearly
Comment: Actually i want insert data in database,and i create the Database in Browser that file downloaded and i was added that file in my xcode,after that i used to fmdb code to insert the data,in my case if i want to add the any other new columns in xcode that was given an error.that was i mentioned.
Answer: You can directly alter table by SQlite manager applying into SQL query.
Find a path for your database and then open it and Edit with SQLite manager:
<code>let fileManager = FileManager.default

    do {
        let documentsURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        print(documentsURL)

    } catch let error as NSError {
        print("Could not save \(error), \(error.userInfo)")
    }
</code>


Hypothesis testing - speeds before and after

Question: I have the following data:
<code>   A   |   B
---------------
9,794  |  10,7098
9,8022 |  10,5176
9,7055 |  11,1039
9,7091 |  11,1474
10,1882|  10,4693
10,2204|  10,8072
9,8221 |  11,2713
9,9272 |  11,2888
10,0855|  10,9026
10,108 |  10,872
10,1433|  10,9649
10,1432|  10,9805
9,7451 |  10,5126
9,8088 |  10,4722
10,0242|  10,6095
10,0402|  10,7719
9,5203 |  11,0741
9,5211 |  11,0357
9,4078 |  11,1146
9,4367 |  11,1176
10,3585|  11,0609
10,3234|  11,0389
10,0555|  10,6333
9,9836 |  10,4394
9,8306 |  10,2537
9,8836 |  10,3016
9,9489 |  10,1945
9,9176 |  10,339
10,0038|  10,639
9,9711 |  10,6681
-----------------
9,91431|  10,77706 - Average
0,2404 |  0,31310438 - Standard deviation
</code>
It represents the seconds a computer program did when using configuration A and B. I run the program 30 times with configuration A, and another 30 times with configuration B.
I want to construct a hypothesis test that proves configuration B runs slower than A (or configuration B runs with a different time than A).
What test should I use and what values go where?
I did some tests using the formulas and got this value por z (or t, dont remember): -11,769. Isn't this number really low? The critical point for 5% is 1.96 (two-tailed) and -11.769 is really deep into the critical zone (rejecting H0) with high probability. I think i'm doing something wrong so please help me. Thanks!
Comment: What makes you think your test results might be misleading you?  Have you graphed the data?  (The graph will make the conclusions obvious.)
Comment: draw a box plot with both variables, they are clearly very different appart from few very small values. It looks normal to have a very significant p-value
Comment: Thanks guys! I've never done hypothesis testing and I thought the values I was getting were wrong but yes I can see the values are different.
Comment: Just as a quick clarification - it looks like you are using the comma as the indication that separates the integer part of the number from the fractional part of the number.  Am I reading that correctly?
Comment: @DonDresserLatentView, exactly. The number is expressed in seconds using comma as a decimal separator
Answer: Since I already collected the data and draw some things, I wil post them here too.
First is a density plot of all values

Second is a box plot.
Comment: The comma was used as a decimal point. Thus, you should have multiplied all those small outliers by $10$ to make them comparable to the others.
Answer: I get a similar value for the t-test of difference in means between the two samples, and a t test is an appropriate test for this question.
There are some fussy technical points about exactly how you figure the standard error for the difference of means, that I am not sure I can answer correctly (although I am pretty sure that for any of them, you would want to start by calculating the estimate of the standard deviation from a sample, which is slightly larger than the standard deviation you appear to have calculated in your data display - I think you used the formula for calculating the standard deviation of a population there) - but any of the variations still produce t statistics of well over 11 - which is way out in the tail of the t distribution, so you would certainly reject a null hypothesis that the means were the same.
Answer: It seems to me that usually with timings you'd be expecting (and interested in detecting) scale shifts. This would corresponding to looking at the percentage faster or slower.
As such, a location-shift in log-time would probably be of prime interest.
I don't think there's likely to be much of a problem with a t-test on the logs, but a Wlcoxon-Mann-Whitney should work very well (the statistic and the p-value will be unaffected by the log-transform, but it's better to work on the log scale because you can get a nice CI for the location-shift in the logs, which when exponentiated will be a CI for the scale shift).
(It's not completely clear whether you're after a one-sided test or a two-sided test; I've done this as if you're interested in the two-sided alternative.)
<code>wilcox.test(x=log(AB$B),y=log(AB$A),exact=TRUE,conf.int=TRUE)

    Wilcoxon rank sum test

data:  log(AB$B) and log(AB$A)
W = 892, p-value = 1.133e-15
alternative hypothesis: true location shift is not equal to 0
95 percent confidence interval:
 0.06819419 0.09942080
sample estimates:
difference in location
             0.0842329
</code>
and the CI for the scale shift:
<code>> exp(wilcox.test(x=log(AB$B),y=log(AB$A),exact=TRUE,conf.int=TRUE)$conf.int)
[1] 1.070573 1.104531
attr(,"conf.level")
[1] 0.95
</code>
So we might say that $B$ is clearly slower than $A$, and runs somewhere in the region of 7% to 10.5% slower.
An equal-variance t-test on the logs produces a similar (but slightly narrower) interval for the percentage by which $B$ is slower.
Either would seem to be eminently suitable as a way of looking at the data.


Is it possible to render specific content from Partial View into main view?

Question: I have a partial view let say _ABCPartialView and within my partial view I have two
 tags as below:

//some dynamic stuff

Is it possible to render only the second
 which contains an  tag into my main view?
This method @html.Partial("_ABCPartialView") renders all the elements of partial view. Your thoughts?
Answer: You can use the ViewData to provide arguments to your PartialView. For Sample:
@Html.Partial("_ABCPartialView", null, new ViewDataDictionary { { "ShowSecondDiv", true } })

And inside your PartialView, you just use:

@if ((bool)ViewData["ShowSecondDiv"])
{

}

Comment: It still renders two ``s. What could be the problem?
Comment: Try using another overload of the `Partial` method. See my edits
Comment: Same results, main view renders the whole partial view.
Comment: Are you passing `true` or `false` to the argument? If you want to hide, you must pass `false` :)
Comment: I want to hide the first div and show the second div, what should I then?
Comment: Abstract and adapt for what you need :). The ideia here is to expose you how to use arguments over the partial views.
Comment: ViewBag is a usable alternative like ViewData  If you want to set data, choose a key for example myKey. And inside the parent, set to it;  ViewBag.myKey = anObjectOrData;   After inside the partial, when you need, call it;  MyClass myKey = (MyClass) ViewBag.myKey;   **Dont forgot to cast type **
Comment: Yeah, the ViewBag encapsulates the ViewData.
Answer: You can pass a model into your partial which will have a property whether to do that or not. For example:
This is the model:
public class YourModel
{
    public bool ShowDiv { get; set; }
}

This is code in your parent view and it passes the info to your partial view:
@Html.Partial("_ABCPartialView", new YourModel { ShowDiv = false });

Inside your partial view check that property and do what you need to do.
@if ((bool)Model.ShowDiv)
{

         //some dynamic stuff

}

A partial view can have a model just like a regular view. Also, with a model you get compiler help and intellisence so you do not have to worry about misspellings.
Comment: I up voted your answer but because your answer came second I can't accept it as answer although it is a perfect answer.
Comment: No worries. My intention was to show that you can treat it like a regular view and pass a model to the partial with as many properties as you need. And please not that the partial view model can be a property of your parent view's model.
Comment: What is the `ShowDiv` in your partial method? Which `` it is?


Bit increase when averaging?

Question: I have a given number $N$ of binary numbers, that are stored using a given number $B$ of bits. $B$ is the same for all the numbers.
For example, thease values where $N = 4, B = 4$.
0000 (zero)
0001 (one)
1111 (fifteen)
1001 (nine)

Q: I take the average, how many bits $R$ do I need to store the result with an ordinary binary number?

My workings before the answer:
The average of the above example, adding extra bits to the result:
0000 (zero)
0001 (one)
1111 (fifteen)
1001 (nine)

=
0110.01 (6.25)

One might assume that combining all four, 4 bit numbers requires 16 bits, $R = N * B$, however many of thease values will represent impossible results. For example when $N = B = 4$, $R$ cannot equal $0000.000000000001$.
So I know that in just the case where $N = B = 4$, that $5 < R < 16$.
Comment: If N is a power of two, think about what happens in the averaging process (think of averaging as first adding them all up and then dividing by N).  As N is a power of two, this has the effect of shifting the decimal place.  Couple this with the fact that the average cannot exceed the maximum value and reach a conclusion
Comment: The question is a little vague. What would you do with the numbers $00, 00, 01$? Store an infinite string of bits?
Comment: If you have $N=3$ and $B=1$, and the numbers $0$, $0$, and $1$, what is their average denoted in binary?  Taking this into account, do you wish to invoke any special restrictions on the possible values of $N$?  E.g. $N$ must be a power of two...
Comment: @copper.hat and JMoravitz. Assume we are not using $N$ values where this is a problem, such as $N = 3$. If you want to include cases such as $N = 3$, then include enough bits to differentiate it from other possible values.
Comment: @JMoravitz If you have an answer for specifically where N is a power of two, I'd consider this a good enough answer to mark as correct, and it covers what I need the answer for.
Comment: @JMoravitz TY :) Where $N$ is a power of 2, $R = B + log2(N)$
Answer: $N ∈ ℕ, B ∈ ℕ$

Where $N$ is a power of two, $N = 2^{∈ℕ}$, then $R = B + log2(N)$.
In some cases, this way will require an infinite number of bits, then $R = ∞$, or at times more practically $R = B + log2(N) + ∈\{0, 1\}$.

256 bytes are able to be included in an average before the result requires 2 bytes to store.
Answer: Suppose $p\neq 2$ is a prime factor of $N$ and choose $N$ numbers such that their sum is ${N \over p}$, then the result is ${ 1\over p}$
which has a non terminating binary expansion. Hence the only non problematic $N$ are those that are powers of $2$.
So, suppose $N = 2^n$ for some $n$ (hence dividing by $N$ corresponds to
a right shift of $\log_2 N$ bits). Since the sum of the numbers must lie
between $0$ and $2^n (2^{B+1}-1)\le 2^{n+B+1} -1$, we see that at most
$n+B$ bits are required, and by considering $2^n-1 $ copies of the number
$2^B$ and one number of $2^B+1$, we see that the sum is $1+2^{n+B}$, hence
at least $n+B$ bits are required,
hence we see that $B+\log_2 N$ bits are required.

Bit increase when averaging?


Exponential stability under global diffeomorphism

Question: Consider a system of the form
\begin{equation}
\Sigma\colon\ \dot{x}=f(x),
\end{equation}
where $x\in \mathbb{R}^n$ and $f\colon \mathbb{R}^n\to \mathbb{R}^n$ is a sufficiently smooth function vanishing at the origin. Assume that $\Sigma$ has a globally exponentially stable equilibrium at $x=0$. Now apply a global coordinate transformation
\begin{equation}
z=T(x),
\end{equation}
where $T\colon \mathbb{R}^n\to \mathbb{R}^n$, $T(0)=0$ is a global $\mathcal{C}^1$ diffeomorphism. Accordingly, we obtain the transformed system
\begin{equation}
\Sigma^\prime \colon\ \dot{z}=g(z):=\frac{\partial T(x)}{\partial x}f(x)\bigg|_{x=T^{-1}(z)}.
\end{equation}
Question: Is $\Sigma^\prime$ globally exponentially stable at $z=0$?
Comment: Clearly not, in general. You should be able to give counterexamples easily, I suggest that you take $n=1$ and think of $T(x)$ similar to $\log x$ for very large $x$.
Comment: It depends on what is your diffeomorphism, but as I noted above in general such a diffeomorphism does not preserve exponential stability, although it preserves stability and asymptotic stability (quantitative versus qualitative).
Comment: What would be the interest in making coordinate changes to study stability?
Comment: Thanks @John B, could you please introduce some references that have discussed stability under coordinate transformation?
Comment: In a certain nonlinear control problem, I have two systems that are related to each other by a global $C^1$ diffeomorphism. For one of the systems (the $z$-dynamics), I have proved exponential stability. Now I was wondering that is it possible to infer the same result for the other system (the $x$-dynamics)?
Answer: Yes, it is. Moreover, let $x(t)$ and $y(t) = \Phi(x(t))$ be solutions of the systems
$$
\dot{x}=f(x,t), \quad x\in\Omega\subseteq\mathbb{R}^n,
$$
and
$$
\dot{y}=h(y,t), \quad y\in\Phi(\Omega)\subseteq\mathbb{R}^n,
$$
respectively (the second system is the transformed first system, $\quad y=\Phi(x)$ is a diffeomorphism); suppose that the solution $y(t)$ is
bounded and exponentially stable; finally, exists an $\epsilon>0$ such that a closed $\epsilon$-neighborhood of any point of $y(t)$ is a subset
of $\Phi(\Omega)$. Then the solution $x(t)$ is exponentially stable.
The proof of this fact can be found in https://link.springer.com/article/10.1134/S0012266107110043
Update:
The main idea of the (simplified, for an equilibrium point and for $\Omega=\Phi(\Omega)=\mathbb R^n$) proof is as follows. Let the zero solution of the system
$$\tag{1}
\dot y= g(y),\quad g(0)=0
$$
be exponentially stable.  It means, by definition, that there exists
$\delta>0$ such that $\forall y_0 \in D_{\delta}=\{y:\; \|y\|< \delta\}$
the solution of the initial value problem
$$
\dot y= g(y),\quad y(0)=y_0
$$
satisfies
$$\tag{2}
\|y(t)\|\le M e^{-\gamma (t-t_0)}\|y_0\|,
$$
where $M$ and $\gamma$ are some positive constants.
Let $\Phi(x)$ be a diffeomorphism, $\Phi(0)=0$.
Since $\Phi$ is a diffeomorphism and, consequently, $\Phi^{-1}$ is also a diffeomorphism, they fulfill the Lipschitz property
$$\tag{3}
\|\Phi(x_1)-\Phi(x_2)\|\le L \|x_1-x_2\|
$$
for any $x_1,x_2\in \Phi^{-1}\left(D_{\delta}\right)$ and, respectively,
$$\tag{4}
\|\Phi^{-1}(y_1)-\Phi^{-1}(y_2)\|\le L' \|y_1-y_2\|
$$
for any $y_1,y_2\in D_{\delta}$, where $L$,$L'$ are some constants.
Now one can combine (2), (3) and (4) and obtain $\forall x_0 \in
\Phi^{-1}\left(D_{\delta}\right)$, $y(t)=\Phi(x(t))$, $y_0=\Phi(x_0)$
$$\tag{5}
\|x(t)\|=\|x(t)-0\|=\| \Phi^{-1}\left(y(t)\right)-\Phi^{-1}(0) \|\le
L' \|y(t)-0\|
$$
$$
\le L' M e^{-\gamma (t-t_0)}\|y_0\|= L' M e^{-\gamma (t-t_0)}\|\Phi(x_0)-\Phi(0)\|\le L' M L e^{-\gamma (t-t_0)}\|x_0\|
$$
Thus, the zero solution of the system in variables $x$ is exponentially stable.
As for the global exponential stability, well, (3) and (4) are not, in general, satisfied in $\mathbb R^n$ for an arbitrary diffeomorphism; but if the solutions $x(t)$ and $y(t)$ are contained in some compact sets (which is a common case for control theory problems), then one can determine the constants $L$ and $L'$ and establish (5).


Android Application which requires user to login first

Question: I am developing an application which requires user to login before accessing any functionalities. Currently the login page is a standalone activity. I would like to ask which activity should I place as the MAIN of my application, the login activity or application activity (the first activity after login). In either way, there is a situation that I need to finish the current activity and start the other one (e.g. When application activity is the MAIN, when user didn't login before, I need to manually finish the application activity and start the login activity. I am not sure if it is a good approach because the first activity was started with nothing done). What is the best practice for login application like this?
P.S. I saw Skype will first show a Splash Screen before the login activity. The login state can be determined in the Splash Screen activity and start the subsequent one (login or application) accordingly. But I am not likely to take this if there is other good approach because an extra splash screen is needed.
Comment: Possible duplicate of [How would one design a flow where one of the screens is a login screen?](http://stackoverflow.com/questions/5126406/how-would-one-design-a-flow-where-one-of-the-screens-is-a-login-screen)
Answer: It doesn't really matter and depends on your application model. Using finish() on an Activity is quite acceptable.
I would say if you have a short time-out on the 'logged in' session, then you will likely need to use the login activity quite regularly and set it as the MAIN activity.
If the login credentials are to be cached for a long period of time (or indefinitely) then set the other activity as the MAIN one.
Comment: Thanks for your answer. In my application, the login session will be expired after some time. I would like to ask how should the activities stack be handled when I start the login activity. If it isn't cleared, the activities will be shown again when the user presses "Back". However, the last activity cannot be resumed after user logged in if the stack is cleared. How to handle this case properly?
Comment: @pinglamb: That was my point about using finish(). Whichever activity you start first can easily start the other and finish() itself.
Comment: My follow up questions might be a little bit out of the scope. In my application, there are multiple entry points (e.g. activity for LAUNCHER, activity for Intent actions) and all required user to login first. Therefore finish the original activity and start the login one might not be good enough because I need to determine which activity to "restart" again after user logged in. One possible solution I can think of is keep the original activity and start the login screen on top, then implement the onResume() method to ensure user is logged in. Anyway, thank you very much.
Comment: @pinglamb: As you say, keeping track of which activity to restart will be a problem. I agree, simply starting the login activity to appear in front of current activity then have the login activity finish() itself to return to that activity seems like the best approach. Good luck.
Answer: Splash Screens are good. They make your app look and feel good :-)
Aesthetics aside splash screens are a single instance activity that does not require a lot of complexity and allows you do do the exact thing you want : switch activities based on some condition , in your case if the user is logged in or not.
This also simplifies your login and main activities as you no longer need to check login in state in these activities as you would have to if there was no splash screen.


Quais tipos de coleções e suas diferenças em java?

Question: Há muitas tipos de coleções em java e tenho a dificuldade de saber as seguintes questões apresentadas abaixo:

Quais as diferenças entre elas?
Quais situações e/ou casos devo utilizar cada uma das diferentes coleções?
Comment: Sua pergunta pode ser respondida na documentação oficial, sendo a diferenças: http://docs.oracle.com/javase/tutorial/collections/implementations/index.html ; e uso: http://docs.oracle.com/javase/tutorial/collections/algorithms/index.html
Comment: Complementando: [How to choose which Java collection class to use?](http://www.javamex.com/tutorials/collections/how_to_choose.shtml)
Answer:
Quais as diferenças entre elas?

Primeiramente é importante entender que Collection é um termo que pode ser ambíguo, pois existem:

collection (ou coleções em tradução livre): Que seriam qualquer estrutura de dados em que objetos são armazenados e podem ser iterados;
Collection (java.util.Collection): Que é uma interface que possui as subinterfaces Set, List e Queue; e
Collections (java.util.Collections): Que é uma classe com alguns métodos estáticos para serem usados com subclasses de Collection.

Enquanto Set, List e Queue além de serem coleções (ou collection, com "c" minúsculo) também são Collection's, pois implementam a interface java.util.Collection. O mesmo não acontece com o Map, que apesar de poder ser considerado uma coleção, ele não implementa a interface java.util.Collection.
Veja abaixo:

As principais diferenças dentre as interfaces citadas acima são:

List: Lista de coisas;
Set: Lista de coisas sem repetição;
Map: Lista com chave-valor, sendo que a chave deve ser única; e
Queue: Fila.

Cada interface possui classes que as implementam. Como são muitas vou apenas colocar o quadro comparativo de cada uma delas, que acho que resume muito bem a funcionalidade de cada uma:

Significado de:

Ordered (ordenada): Quando uma coleção é ordenada, quer dizer que é possível iterar os elementos da coleção em uma ordem específica e não aleatória.
Sorted (classificada): Quando uma coleção é classificada, quer dizer que a ordem dos elementos da coleção é determinada de acordo com alguma regra, conhecida como ordem de classificação.

Fonte: SCJP Sun Certified Programmer for Java 6

Quais situações ou casos devo utilizar cada uma das diferentes coleções?

A situação depende da sua necessidade, olhando as diferenças listadas acima fica muito claro quando deve-se escolher uma ou outra coleção.


Gitlab CI and matlab

Question: I am trying to set up some tests for a fairly large Matlab code I have on gitlab.
I created the .gitlab-ci.yml  file which launches a bash script that then calls matlab.
#.gitlab-ci.yml

before_script:

Test:
  script:
    - chmod +x RunTests.sh
    - ./RunTests.sh

The bash script is the following:
# RunTests.sh
cd IntegratedTests

LOGFILE=log.txt

matlab -nodesktop -nosplash -minimize -wait -logfile "$LOGFILE" -r 'RunTests';
CODE=$?

cat "$LOGFILE"

exit $CODE

However, gitlab tries to use the shared gitlab-runner which uses a docker image from ruby. The tests end ups failing because it cannot find matlab on the docker-image.
Running with gitlab-runner 12.0.0-rc1 (58d8360f)
  on docker-auto-scale ed2dce3a
Using Docker executor with image ruby:2.5 ...
Pulling docker image ruby:2.5 ...
Using docker image sha256:80f53b90f8657c63c8d35d5eff399e6410baf19013c3b4c1c4158b2029060147 for ruby:2.5 ...
Running on runner-ed2dce3a-project-11747478-concurrent-0 via runner-ed2dce3a-srm-1561674473-a1c90512...
Fetching changes...
Initialized empty Git repository in /builds/darsim2simulator/darsim2/.git/
Created fresh repository.
From https://gitlab.com/darsim2simulator/darsim2
 * [new branch]      3-fixed-time-step-size -> origin/3-fixed-time-step-size
 * [new branch]      4-single-temperature-formulation-for-geothermal -> origin/4-single-temperature-formulation-for-geothermal
 * [new branch]      FIMLTS                 -> origin/FIMLTS
 * [new branch]      master                 -> origin/master
 * [new branch]      patch-1                -> origin/patch-1
 * [new branch]      patch-2                -> origin/patch-2
 * [new branch]      patch-3                -> origin/patch-3
Checking out ff3f0a4f as master...

Skipping Git submodules setup
$ chmod +x RunTests.sh
$ ./RunTests.sh
./RunTests.sh: line 6: matlab: command not found
cat: log.txt: No such file or directory
ERROR: Job failed: exit code 1

I am guessing that the problem is that matlab is not installed on the docker-image
It's the first time I use the gilab CI so I may have not understood correctly how to use it but what are my alternatives? How can I set up a runner that has matlab?
Answer: For specific runners in our project, I specify tags for a job in the .gitlab-ci.yml
Something like:
Test:
  script:
    - chmod +x RunTests.sh
    - ./RunTests.sh
  tags:
    - runners-tag

More info at
https://docs.gitlab.com/ee/ci/yaml/#tags

Gitlab CI and matlab


How to Ignore Spring boot configuration in the dependency

Question: I am working on test framework application, which is built in groovy, java 8 and springboot framework.  Recently, one of the dependencies was upgraded to its latest version.
When I run the tests, the test fails with below message:
Caused by: org.springframework.core.NestedIOException: ASM ClassReader failed to parse class file - probably due to a new Java class file version that isn't supported yet: class path resource

    at org.springframework.boot.autoconfigure.AutoConfigurationSorter$AutoConfigurationClass.getAnnotationMetadata(AutoConfigurationSorter.java:229)
    ... 86 more
Caused by: java.lang.IllegalArgumentException: Unsupported class file major version 61
    at org.springframework.asm.ClassReader.<init>(ClassReader.java:196)
    at org.springframework.asm.ClassReader.<init>(ClassReader.java:177)
    at org.springframework.asm.ClassReader.<init>(ClassReader.java:163)
    at org.springframework.asm.ClassReader.<init>(ClassReader.java:284)
    at org.springframework.core.type.classreading.SimpleMetadataReader.getClassReader(SimpleMetadataReader.java:57)
    ... 92 more

I see this error coming from the autoconfiguration in spring.factories of one of dependency:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.app.api.config.testAutoConfig
I am guessing this issue is occurring because the dependency is built in Java17 and I am compiling my test framework in Java 8.
How can I ignore the autoconfiguration in the dependency.  Is there a hack or what is the correct way of implementing the solution.
Answer: No need to hack, there is an API! :)
SpringBootApplication|EnableAutoConfiguration#exclude().
Just like:
@SpringbootApplication(exclude = com.app.api.config.testAutoConfig.class) // type safe alternative : Class[]
class MyApp // ...

For exclusion, the "non-type-safe"/string alternative makes sense:
@SpringbootApplication(excludeName = "com.app.api.config.testAutoConfig") // ... String[]

#excludeName
...  which brings the advantage, to (possibly!?) exclude it from your class path (completely;)
Comment: but this is more regarding "How to Ignore Spring boot configuration in the dependency", regarding your specific probem: not sure! 1.: whether this can prevent it from class loading 2. If you can't use the configuration, why do you think/how you can use any of its classes?
Comment: This AutoConfig is from another transitive dependency. My application is not using it. So, it is something like this. MyApplication--DependentJar--Its DependentJar which is having this autoconfiguration.
Comment: ok, @SajitGangadharan, `exclude` helps?
Comment: no, Now the exclude throws same exception when starting the application stating it cannot identify the class because of unsupported major version
Comment: 1. Tried also `excludeName` ? 2. what happens, if you remove the dependency?