Is this modest change enough to make an idempotent element an identity element?

Question: In The Number System by Thurston the author introduces an algebraic structure he calls a hemigroup.  The laws of a hemigroup are:

(i)   $\left(x\odot y\right)\odot z=x\odot \left(y\odot z\right),$
(ii)  $\left(x\odot y\right)=\left(y\odot x\right),$
(iii) $\left(x\odot y\right)=\left(x\odot z\right)\implies{y=z},$
(iv)  $\exists_e e\odot e=e.$

I have been told (see comments) that $e$ of (iv) is not necessarily an identity element, but merely an idempotent element.  I'm trying to understand what this actually means.  I assume the distinction would be that $x\odot e=e\odot x=e\odot x\odot e,$ etc., but we have no rule $x\odot e=x.$  Please correct me if this is incorrect.
My main question is this: if $\mathcal{H}$ is the set of the hemigroup and we define our set of interest to be $\mathcal{S}\equiv \{\xi\backepsilon \xi=x\odot e\land e,x\in \mathcal{H}\},$ preserving the meaning of $\odot$ in $\mathcal{S},$ does $e$ now constitute an identity element of $\mathcal{S}?$ I am accepting the identity $e=e\odot e\in\mathcal{S}$.
Comment: The definition of algebraic structure given in BBFSK regarding sets of abstract mathematical entities is: "These sets have an *algebraic structure* consisting in certain relations or laws of combination among the elements within the set, in the existence of certain distinguished subsets, and so forth."   In their formal exposition of structure the existence of an identity element is part of the specification of algebraic structure.  So, by my book, there is no distinction.
Comment: Can you explain the quantifier on x in axiom iii?
Comment: The axioms are for all $x,y,z\in \mathcal{H}$.
Answer: Yes, $e$ ($=e\odot e$) is a right identity in $\mathcal S$ because
$$(x\odot e) \odot e = x\odot (e\odot e)= x\odot e$$
(and is a two sided identity because $\mathcal H$ was abelian to begin with).
Comment: I changed my preferred answer to Eric Wofsey's because he showed that $e$ is an identity element of $\mathcal{H}$, which obviates the rest of my question.
Answer: Actually, $e$ is an identity element of $\mathcal{H}$ itself, because of axiom (iii).  For any $x\in\mathcal{H}$, $$e\odot x=(e\odot e)\odot x=e\odot(e\odot x)$$ which by axiom (iii) implies $x=e\odot x$.
Comment: I should have seen that.


Dirichlet problem: Is the Poisson Integral always a solution?

Question: Let $f$ be continuous on the sufficiently smooth boundary $\partial D$ of a domain $D \subset \Bbb R^n$.
Is the Poisson integral of $f$,
$$
Pf(x)=\int_{\partial D} f(t) \frac{c_x}{\left|x-t\right|^n}dt,
$$
with $c_x$ an appropriate constant, always a solution to the Dirichlet problem?
I know the general solution of the Dirichlet problem is given in term of the Green function.
But I can't decide if, for arbitrary domain, the Green function is always the Poisson kernel or not.
As the Poisson kernel is an approximation to the identity, I guess the answer is yes.
Answer: No, the Poisson integral is only for balls.


Why the operation hierarchy works?

Question: I don't know if this is a silly question, but they never teached me this at school, i will have to trust my teacher and not doubt about this affirmation, but why we are completly sure that performing simple arithmetic operations in an specific order gives a correct answer?
For example:
2 + 4 × 2

Why we completly affirm that this is 10 and not 12?

Why this hierarchy is difined like this?

Why this works?
Comment: If they did not teach this in school, then your teacher is as dumb as the football coach who taught science class when I was in school back in the '60s. You always resolve 1) parentheses 2) powers and factorials 3) multiplication and division 4) addition and subtraction in that order so $2+4\times 2=10$
Comment: I mean, that they've never teached me why this hierarchy works
Answer: This is a mere convention ... so it could've historically ended up differently, but it hasn't, we are where we are, it's been accepted by everyone, and so everyone needs to learn it.
If you write something like:
$$2+4\times 2$$
(or, let's make it worse:
$$2+2\times 2-2-(2^{2+2^2}+2):2+2+2\times 2:2$$
) ... what does this writing even mean? The convention is about deciding what it means, i.e. which operations will be done first, and which will follow. Over centuries, people settled with the following:

Brackets (Parentheses): Do those first. Whatever is in brackets needs to be calculated already (as a separate, standalone, expression), before you go forward.
Indices (Exponents): Calculate those next, right-to-left. If you have something like $2^2$ do it here. If you have something like $2^{3^4}$ you do $3^4(=81)$ first, then you do $2^{81}$
Division/Multiplication: Do both, from left to right, in the order they appear.
Addition/Subtraction: Do both of them, again, from left to right, in the order they appear.

Those rules are usually remembered using a mnemonic BIDMAS or PEDMAS (or PEMDAS).
The flipside is, if you want the operations in your expression to be done in a different order than prescribed, you then put brackets/parentheses to modify the order.
In your question: $2+4\times 2$, there are no parentheses and no indices, but we do the multiplication first ($4\times 2 = 8$), and then we do addition ($2+8=10$). If you want it to be calculated differently, i.e. to first add $2+4$, and then multiply by $2$, you put $2+4$ in brackets, i.e. the expression becomes: $(2+4)\times 2$.
Hope this helps.
Comment: *Any* convention would work. We just needs a way to write succinctly something that would be in words "multiply $4$ by $2$ and add that to $2$" - many centuries ago people actually did this all in words! This has nothing to do with "real world". As far as the real world is concerned, some real things follow mathematical patterns (so science and engineering works, right?), and it is an interesting question in itself. However, we are here concerned only about *writing down* the mathematical patterns, once we have identified them already. This is not the same question.
Comment: @ÁlvaroRodrigo (Cont'd) You can just as easily ask why it works to write $\times$ (two crossed lines) for multiplication ... It does not matter, this is just another convention, and some people write $\cdot$ or $\circ$... Or it works when we write numbers as $1,2,3,4,\ldots$ (again, we could write them as $I, II, III, IV, V\ldots$ - that would be another convention). In other words, there is nothing mathematical in the convention, it is part of language, but it is the language that you can *use* to express mathematical ideas.
Comment: Some simple calculators, though, have no knowledge of this, and if you type $2+4\times 2$ into them, they will show $12$. They follow a different convention, which may be confusing. Most modern calculators, however, "know" about BIDMAS/PEDMAS and do what is expected. There are also other conventions used for various special purposes, such as RPN (https://en.wikipedia.org/wiki/Reverse_Polish_notation), in which $2+4\times 2$ would be written as $2\space 4\space 2\space \times\space +$. Mentioning just FYI, no need to remember it.
Comment: The thing is, why this convention works, why the things you write down on a paper, in theory, then works on real life.

Why the operation hierarchy works?


$f| _{dense\;set}=0$ and continuous on lines $\implies f \equiv 0$

Question: Denoting $I=[0,1]$, let $f:I^2 \to \mathbb{R}$, such that $f=0$ on a dense set $A \subseteq I^2$, i.e. $cl(A)=I^2$.
Assume also that $f$ is continuous on horizontal and vertical lines, i.e. $\forall x_0,y_0 \in I: f(x,y_0) \in C(I),f(x_0,y) \in C(I)$.
Prove that $f$ is identically $0$.
Comment: Where did you get this question from ? Did you make it up or did you find it in a textbook ?
Comment: 2 upvotes without showing any work? This site is awfully generous today.
Comment: @AlecTeal I think this is a very difficult and interesting problem, so I'm actually wondering why there are _only_ two upvotes. Indeed, three out of the four answers below have been deleted because they were based on an oversimplifying interpretation of the problem, and even the fourth answer by Nicolas has been edited abundantly and needed to make an extra assumption!
Comment: Please answer my question, if it comes from a textbook maybe there are hints there, if you made it up then it is useful to know that maybe a counterexample exists.
Comment: No counterexample should exist, yet the source of this question provides no hints.
Comment: What is the source ? You seem very mysterious about it^^
Comment: A talented friend who refuses  to give hints. Though he did say that the proof is not as 'global' as one might suppose.
Comment: Ok, I think I found a proof that is posted below. Tell your friend his problem is awesome !
Answer: NOTIFICATION : this answer is valid for an uniform continuity on the lines, i.e. the below $\delta_x,\delta_y$ are independant of the choice of the horizontal/vertical line.
Let $(x,y)\in I^2\setminus A$ and $\varepsilon>0$. By hypothesis, there exist $\delta_x,\delta_y>0$ such that
$$|x-x_0|<\delta_x\Longrightarrow|f(x,y)-f(x_0,y)|<\varepsilon/2\quad\quad\forall y\in I$$
and
$$|y-y_0|<\delta_y\Longrightarrow|f(x_0,y)-f(x_0,y_0)|<\varepsilon/2\quad\quad\forall x_0\in I.$$
Now, as $A$ is a dense set, we can find $(x_0,y_0)\in A$ such that
$$|x-x_0|<\delta_x,\quad |y-y_0|<\delta_y.$$
Then we have
$$|f(x,y)|=|f(x,y)-\underbrace{f(x_0,y_0)}_{=0}|\leq|f(x,y)-f(x_0,y)|+|f(x_0,y)-f(x_0,y_0)|<\varepsilon$$
As $\varepsilon$ was arbitrary, we've shown that $f(x,y)=0$. As $(x,y)\in I^2\setminus A$ was arbitrary, we've shwon that $f$ is identically zero on $I^2\setminus A$.
Comment: The uniform continuity assumption you added after this discussion actually makes $f$ continuous...
Comment: Indeed, and what you wrote in your answer is more or less a proof of that well known result :) But the original question is only interesting for functions that aren't continous...
Comment: This proof needs a little improvement. Note that the choice of the $\delta$ that satisfies $|y - y_0| < \frac{\delta}{2} \rightarrow |f(x_0, y) - f(x_0, y_0)| < \frac{\epsilon}{2}$ in general depends on your choice of $x_0$.
Comment: It is worth pointing out this fact ; however, I think what I've written is fine : I did not precised for what choice of $\delta(\varepsilon)=\delta(\varepsilon,y,x_0)$ we have the inequalities with $\varepsilon/2$. We know that we can find such $\delta$ due to the hypothesis of continuity on $f$ on the lines. Now, to write it more in details, what you've said is a good point to consider.
Comment: @Nicolas I'm afraid this construction gives rise to circularity: the choice of $(x_0,y_0)$ depends on $\delta$, and the choice of $\delta$ depends on $(x_0,y_0)$.
Comment: @triple_sec I do not see where... Here what I was thinking about : we have $|f(x,y)-f(x_0,y)|<\varepsilon/2$ if $|x-x_0|<\delta(\varepsilon,x,y)$ by continuity on the horizontal lines, and also $|f(x_0,y)-f(x_0,y_0)|<\varepsilon/2$ if $|y-y_0|<\delta(\varepsilon,x_0,y)$ by continuity on the vertical lines. What do you think about this argument ?
Comment: EDIT: it is true that we must fix $x_0$ first before choosing $\delta(\varepsilon,x_0,y)$, but I do not see any problem with that...
Comment: @Nicolas If you fix $x_0$ before choosing $\delta(\varepsilon,x_0,y)$, how do you know it will be sufficiently close to $x$?
Comment: @triple_sec $x_0$ is chosen in the interval $]x-\delta(\varepsilon,x,y),x+\delta(\varepsilon,x,y))[$. The continuity of $f$ on the horizontal line $[0,1]\times\{y\}$ tells us that we can do that. Now $x_0$ is fixed. On the vertical line ${x_0}\times[0,1]$, $f$ is continuous, so  we can choose $y_0$ on the interval $]y-\delta(\varepsilon,x_0,y),y+\delta(\varepsilon,x_0,y))[$. Here, the dependance on $x_0$ is not very important : it tells us that we are on the vertical line ${x_0}\times[0,1]$ ; the continuity on this line tells us that, when $x_0$ is fixed, if $y_0$ is close enough of $y$, [...]
Comment: [...] then we have $|f(x_0,y)-f(x_0,y_0)|$ small. The OP tells us that $f$ is continuous on every vertical lines, so who is $x_0$ here is not very important for the choice of $y_0$. What is important however is that the density of $A$ allows us to choose $y_0$ in $A$.
Comment: @Nicolas If $x_0$ is chosen arbitrarily in the interval $(x-\delta(\varepsilon,x,y),x+\delta(\varepsilon,x,y))$, it is not guaranteed that $\{x_0\}\times[0,1]$ will contain a point in $A$, despite the fact that $A$ is dense—it is _a fortiori_ not guaranteed that one can choose $y_0$ in such a way that both (i) $(x_0,y_0)\in A$; and (ii) $y_0\in(y-\delta(\varepsilon,x_0,y),y+\delta(\varepsilon,x_0,y))$.
Comment: @triple_sec Oh yes, you're right for this point : indeed, $A$ does not intersect necessarily with the line ${x_0}\times[0,1]$ ! So there is something in more to say. Anyway, the long discussions since I've posted this answer let me think that I had to modify it. So I will as soon as possible, thanks!
Comment: Edited. I have a doubt now about the OP : does $f$ is uniformly continuous for all lines ? I mean, is the $\delta_y$ the same for every vertical line $\{x'\}\times[0,1]$, $x'\in[0,1]$ ? I treat it like this as it was my original understanding of the question.
Comment: I saw your edit. I'm worried that one cannot guarantee that the constant of continuity $\delta_x$ will be the same for _every_ $y\in I$. Indeed, for any fixed $x\in I$ and $y\in I$, there exists some $\delta_x^y>0$ such that $$|x-x_0|<\delta_x^y\Rightarrow|f(x,y)-f(x_0,y)|<\varepsilon/2,$$ but this constant $\delta_x^y$ may vary with $y$ in an unpredictable way! I've been thinking a lot about this myself, and I'm now at a point of doubting whether the claim is true...
Comment: So we posted at the same time: yes, I'm afraid that the uniformity of the $\delta$'s is _not_ guaranteed.
Comment: Ok, I will notice this important point in my answer. Thank you anyway for your comments!
Comment: @Sergio And the conclusion is the well known result that a continuous function that is identically zero on a dense set is identically zero everywhere!
Answer: Drawing a picture next to this proof makes it much more clear (as with many proofs...)
Choose any $(a,b)\in [0,1]^{2}$ and $\varepsilon>0$.
By density of $\{f=0\}$ there is $(x_{1},y_{1})\in (a-\varepsilon,a+\varepsilon)\times(b-\varepsilon,b+\varepsilon)$ such that $f(x_{1},y_{1})=0$. By continuity on vertical lines there is $\delta_{1}$ such that $f(x_{1},y)<1/2$ for $|y-y_{1}|<\delta_{1}$, and we can take $\delta_{1}$ such that $\delta_{1}<1/2$ and $[y_{1}-\delta_{1},y_{1}+\delta_{1}]\subset (b-\varepsilon,b+\varepsilon)$.
Now repeat the construction recursively for each $n$ to find $(x_{n+1},y_{n+1})$ and $\delta_{n+1}$ such that

$(x_{n+1},y_{n+1}) \in (a-\delta_{n},a+\delta_{n})\times(y_{n}-\delta_{n},y_{n}+\delta_{n})$
$\delta_{n+1}<1/2^{n+1}$
$[y_{n+1}-\delta_{n+1},y_{n+1}+\delta_{n+1}]\subset (y_{n}-\delta_{n},y_{n}+\delta_{n})$
$f(x_{n+1},y)<1/2^{n+1}$ for $|y-y_{n+1}|<\delta_{n+1}$

The constructed sequences have the following properties:

$\delta_{n}\rightarrow 0$
$x_{n}\rightarrow a$ (because $\delta_{n}\rightarrow 0$)
$y_{n}$ has a limit $\bar{y}\in [a-\varepsilon,a+\varepsilon]$, which is the unique element of $\bigcap_{n} [y_{n}-\delta_{n},y_{n}+\delta_{n}]$.
$f(x_{n},\bar{y})\leqslant 1/2^{n}$ so that $f(a,\bar{y})=0$ by continuity on horizontal lines.

We have shown that for all $\varepsilon > 0$, there is $\bar{y}$ such that $f(a,\bar{y})=0$ and $|\bar{y}-b|<\varepsilon$. By continuity on vertical lines $f(a,b)=0$. Since $a,b$ were arbitrary, $f=0$.
Comment: Wow! Finally, a complete answer! Brilliant! +1
Comment: That's beautiful :)
By the way, $\bar{y}\in [b-\varepsilon,b+\varepsilon]$. (edit<6 characters)


Add image field programatically in D7

Question: I'm moving a bunch of info from an xml feed into drupal nodes. I'm a little hung up on adding the image. I'm using php copy() to copy the image from a url to my drupal directory. From here, I'm not sure how to insert the field info into the node in such a way that an fid and all of the required data is generated. What is the preferred way to do this?
Answer: OK, what I came up with here:
function save_my_image($uri) {
  //copy file into drupal files directory
  $contents = file_get_contents($uri);
  //then save into drupal's file system
  $file = file_save_data($contents);
  return $file;
}

file_save_data() (http://api.drupal.org/api/drupal/includes--file.inc/function/file_save_data/8) will handle creating an fid for the file and keeping track of it generally.. then simply add the fid to the node in question and you should be golden.

Add image field programatically in D7


Dictionary TryGetValue NullReferenceException

Question: I am getting  NullReferenceException at the _dicCache.TryGetValue(objID, out newObject);
line. And I have no Idea why this is happening at all. Can comeone point me to the right direction please?
Here is my class:
public class Cache<T>
{
    public string Name { get; set; }

    private  Dictionary<int, T> _dicCache = new Dictionary<int, T>();

    public  void Insert(int objID, T obj)
    {
        try
        {
            _dicCache.Add(objID, obj);

            HttpContext.Current.Cache.Insert(Name, _dicCache, null, DateTime.Now.AddMinutes(10), TimeSpan.FromMinutes(0));
        }
        catch (Exception)
        {
            throw;
        }
    }

    public bool Get(int objID, out T obj)
    {
        _dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);

        try
        {
            return _dicCache.TryGetValue(objID, out obj);
        }
        catch (Exception)
        {
            throw;
        }
    }
 }

And here is how I call it:
   Services.Cache<Entities.User> cache = new Services.Cache<Entities.User>();
   cache.Name = Enum.Cache.Names.usercache.ToString();

   Entities.User user = new Entities.User();

   cache.Get(pUserId, out user);

I Also have tried to change to Get class to:
    public T Get(int objID, out T obj)
    {
        _dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);

        T newObject = (T)Activator.CreateInstance<T>();

        try
        {
            _dicCache.TryGetValue(objID, out newObject);

            obj = newObject;

            return obj;
        }
        catch (Exception)
        {
            throw;
        }
    }

But I still get the same NullReferenceException at the _dicCache.TryGetValue(objID, out newObject); line.
Comment: `_dicCache` is probably null. Are you sure `(Dictionary)HttpContext.Current.Cache.Get(Name);` this cast is valid? Debug these lines
Comment: You needn't to initialize `newObject`, as it is initialized by `TryGetValue`. The problem is definitely not with it.
Comment: @Konstantin Vasilcov `_dicCache` is `null`! I didn't pay Attention to that. Thank you very much.
Comment: Since I declare the `_dicCache` variable like this: `private  Dictionary _dicCache = new Dictionary();` I thought it wouldn't be null. Can you explain why it is null?
Comment: Is there anything at all found by that `Name`in the cache?
Answer: I think the only way you could have that exception is if your dictionary is null.
_dicCache.TryGetValue(objID, out newObject);

null is not a valid argument for the key (if TKey is a reference type), though in your case it's int so cannot be null. You'd see an ArgumentNullException if passing a null value for key anyway.
Are you sure _dicCache is not null? I would check the value of the assignment:
_dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);

Comment: @rpmlins, I'm guessing the assignment from `HttpContext.Current.Cache` is setting it to `null`.
Comment: yes my _dicCache is null :(. trying to solve this... Since I declared the _dicCache variable like this: private Dictionary _dicCache = new Dictionary(); I thought it wouldn't be null
Comment: Well, someone does not seem to like me. If you look at my answer below, it explains exactly this. In your Insert method, you put _dicCache in the http context. In your Get method, you overwrite the member _dicCache variable from what is inside the http context cache, and that is always null because you never call the Insert method.
Comment: `_dicCache = (Dictionary)HttpContext.Current.Cache.Get(Name);` will always return null unless the `Insert` method is called which puts the non-null _dicCache into the http context's cache.
Comment: @AmeenTayyebiJazayeri, have an upvote from me.
Comment: @Drew Noakes thx. now I validate the _dicCache checking if its null before.
Comment: Glad you got it working.
Comment: > null is a valid argument for the key (if TKey is a reference type), though in your case it's int.
I had thought the same, but it seems this is not true. See https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.trygetvalue?view=net-8.0
Comment: @myavuzselim quite right! Updated. Thanks.
Answer: The method that actually puts _dicCache into the http context's cache is the insert method which is never called in your code, hence when you try to obtain it back from the http context, you get null (you only ever call Get).
I would change the Name setter to actually put the dictionary into the http context at that time, or better yet, if you can somehow insert the dictionary into the cache in the constructor by getting the Name property as a constructor parameter. In general, I try to design classes in such a way that they are in an "uninitialized" state for the least amount of time possible.
Comment: hey @Ameen I apretiate your answer but I am not calling the insert method as I've stated on my question. I am just Calling the Get method. That was on purpose. I only insert if the object is not in the  _dicCache . So I always call the Get first.


Expected number of balls that appear at least m times among n drawings of the same lottery?

Question: Imagine I have a bucket with $b$ individually numbered balls. Then I draw $d$ balls from this bucket. I repeat this drawing $n$ times, replacing the balls between each drawing (that is, between each drawing of $d$ balls, not each drawing of a single ball).
What is the expected number of balls that were drawn at least $m$ times, where $m \le n$?
This question is similar, but it is constrained to where $n = 2$ and $m = 2$, and asks for the probability that the answer to my question is at least $1$.
Answer: You can think about this in terms of the individual balls $B_i$ as random variable which take value $1$ if selected and value $0$ otherwise. For a particular ball $B_i$ the probability of selecting it on any draw is $\frac{{ b-1 \choose d-1 }}{{b \choose d }} = d/b$. Then the probability of selecting $B_i$ exactly $k$ times ( so $\sum B_i = k$) in your n draws is ${n \choose k}(d/b)^k(1-d/b)^{n-k}$, as the draws are independent. So the probability of drawing $B_i$ at least $m$ times is $P(\sum B_i \geq m)= \sum_{k=m}^{n}{n \choose k}(d/b)^k(1-d/b)^{n-k}$. Then probability of $r$ of the $B_i$ drawn at least $m$ times is then ${b \choose r}P(\sum B_i \geq
m)^r(1-P(\sum B_i \geq m))^{b-r}$. Therefore, the expected number of balls drawn at least $m$ times is $\sum_{r=1}^b r{b \choose r}P(\sum B_i \geq m)^r(1-P(\sum B_i \geq m))^{b-r} = bP(\sum B_i \geq m)$, where this last equality follows as it is the expectation of binomial random variable.


How to get content from an url by client ip address NOT server address

Question: What I'm actually trying to do is getting content of an URL from another site there I want get the content by client ip address NOT server. Is there any way to do this?
Here I tried some how but, not succeed :/
<?php
$homepage = $_SERVER['REMOTE_ADDR']file_get_contents('http://www.example.com/');
echo $homepage;
?>

I'll accept if there is a way in javascript also.
Comment: What do you mean by _"get the content by client ip address NOT server"_? If you have a question, please spend time in articulating your question with a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
Comment: MR @Thangadurai  when i'm getting content of for example google it's getting by server ip address which is something that don't want.
Comment: Am I the only one around here that doesn't quite understand what OP is trying to achieve? What content do you want to get from a regular user's computer?
Comment: @kerbholz .  I'm trying to get the **http://example.com/testm3u8?wmsAuthSign=code** using PHP get content

as u can see that code at the end of url is changing by ip address and it's not working by server ip address. only claint ip :D
Comment: Assuming the client is a browser, since you can't run PHP in the browser, you can't do this with PHP.
Answer: Use the following:
<?php
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $ip_address = $_SERVER["REMOTE_ADDR"];
    $page_name = $_SERVER["SCRIPT_NAME"];
    $query_string = $_SERVER["QUERY_STRING"];
    $current_page = $page_name."?".$query_string;
    echo $ip_address
?>

Comment: I want the to get the content of example.com by client ip address. :)


. separated json value parsing with jq

Question: I have this json and I'd like to go under the "rgw.main" but for some reason I'm not sure how to define.
{
    "bucket": "mybucket",
    "num_shards": 11,
    "tenant": "",
    "zonegroup": "xxx-11111",
    "placement_rule": "default-placement",
    "explicit_placement": {
        "data_pool": "",
        "data_extra_pool": "",
        "index_pool": ""
    },
    "id": "234324324",
    "marker": "234324324.2",
    "index_type": "Normal",
    "owner": "store",
    "ver": "0#1196975824,1#1195439377,2#1195232380,3#1194062417,4#1195521322,5#1195488056,6#1193225866,7#1195484409,8#1195542434,9#1195529602,10#1195327401",
    "master_ver": "0#0,1#0,2#0,3#0,4#0,5#0,6#0,7#0,8#0,9#0,10#0",
    "mtime": "2022-02-18T11:16:22.620065Z",
    "creation_time": "2021-03-12T10:02:54.033355Z",
    "max_marker": "0#01196975823.2645569872.5,1#01195439376.3395178223.5,2#01195232379.3168551901.5,3#01194062416.2633030768.5,4#01195521321.2647348717.5,5#01195488055.3126383883.5,6#01193225865.2630243615.5,7#01195484408.2645677558.5,8#01195542433.2655116258.5,9#01195529601.2621773307.5,10#01195327400.2629607598.5",
    "usage": {
        "rgw.none": {
            "size": 0,
            "size_actual": 0,
            "size_utilized": 0,
            "size_kb": 0,
            "size_kb_actual": 0,
            "size_kb_utilized": 0,
            "num_objects": 230
        },
        "rgw.main": {
            "size": 120124562767,
            "size_actual": 120220463104,
            "size_utilized": 120124562767,
            "size_kb": 117309144,
            "size_kb_actual": 117402796,
            "size_kb_utilized": 117309144,
            "num_objects": 29670
        },
        "rgw.multimeta": {
            "size": 0,
            "size_actual": 0,
            "size_utilized": 7776,
            "size_kb": 0,
            "size_kb_actual": 0,
            "size_kb_utilized": 8,
            "num_objects": 288
        }
    },
    "bucket_quota": {
        "enabled": false,
        "check_on_raw": false,
        "max_size": -1,
        "max_size_kb": 0,
        "max_objects": -1
    }
}

I'm trying to take out the rgw.main num_objects, however I can't get into only the rgw.main.
Tried like this but this gives back 3 number values:
.usage[].num_objects

Tried like this but this gives null:
.usage[].rgw.main.num_objects

Tried like this but this still null:
.usage[].rgw

What I'm missing?
Comment: Don't use the shortcut (i.e. omitting the quotes) if special characters are part of the identifier: `.usage."rgw.main".num_objects`
Comment: @pmf you're right and I've just tested on jqkungfu and it works properly, however on my linux machine still null. JQ version maybe or in linux need something more?
Comment: Ohh just found it, I missed the single quote: jq '.usage."rgw.main".num_objects'. Thank you for your help @pmf
Answer: Multiple issues:

usage is not an array but an object, so you need to navigate with .usage, not with .usage[]. .usage[] would iterate all values of the object, losing the keys.
Your key is "rgw.main", not "rgw"."main". In other words, your object structure is { "rgw.main": 42 } and not { "rgw": { "main": 42 } }. You must use ."rgw.main" or .["rgw.main"] if your key contains characters which are special to jq

.usage."rgw.main".num_objects

or
.usage["rgw.main"].num_objects

Output:
29670

. separated json value parsing with jq


Erro do tipo parsererror ao efetuar uma requisição AJAX crossDomain

Question: Criei essa página para testar uma requisição cross domain com AJAX:

No script eu uso dataType: "jsonp" porque li por ai que ele é necessário para isso e não consegui com apenas dataType: "json".
Com ambos, "jsonp" ou "json", consigo parar o processo com um break-point ao debugar o serviço. Mas com "json" recebo a mesangem de erro "error" e "jsonp" é "parsererror".
Como posso resolver isso?
Meu WebMethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void TestConnection(string key)
{
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(new {
        OnLine = true,
        Message = "Requisição efetuada com sucesso!"
    });
    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Flush();
    Context.Response.Write(json);
}

EDIÇÃO
Pelo Postman, plugin do Google Chrome para efetuar requisições, usando a opção "form-data" para efetuar o pedido com o método post, eu recebo o seguinte erro:

System.InvalidOperationException: Formato de solicitação inválido: multipart/form-data; boundary=----WebKitFormBoundarygLlKC2yNIYzbStBM.
     em System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
     em System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

Mas, mudando para "x-www-form-urlencoded" eu já consigo realizar a requisição e receber o meu objeto json pelo Postman.
Então, o que preciso mudar em meu script?
Answer: O Postman deve tratar essa questão sozinho, mas eu precisei mudar um pouco o meu WebMethod para então conseguir tratar o retorno.
Conforme resppsta aceita nessa questão no SOen, o retorno do tipo jsonp é esperado de forma que o resultado json esteja encapsulado em um método que trata o retorno.
O retorno deve ser algo do tipo callback({....});.
Logo, alterei meu WebMethod para isso:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void TestConnection(string key)
{
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(new {
        OnLine = true,
        Message = "Requisição efetuada com sucesso!"
    });
    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Flush();

    var callback = Context.Request.QueryString["callback"];
    if (!string.IsNullOrEmpty(callback))
        Context.Response.Write(string.Format("{0}({1});", callback, json));
    else
        Context.Response.Write(json);
}

Pronto, com isso minha requisição conseguiu tratar o retorno e o processo foi efetuado com sucesso.


How add a views page url to the admin_menu?

Question: I tried creating a view with a page display, giving it a normal menu item in navigation, the url admin/people/allusers (or any url like admin/content/listing), clearing the caches, but the admin menu does not pick up the page and put it in the drop downs.
How do I do this without having to use hook_menu for each views page url I want in the admin menu bar?
Answer: The link needs to get added to the Management menu to show up in admin_menu.
You can add a admin menu link on:
http://example.com/admin/structure/menu/manage/management
Or through the interface at : Structure->Menus->Management->Add Links
Comment: OH! thanks. putting it in management totally worked (I had looked for Administration, a d6 thing, but didn't know what management was for). I thought I was going crazy. :)
Comment: Glad it works - not crazy! Thanks for all your help recently!
Answer: As mentioned by @ursula, you can add view with a page display link from Structure->Menus->Management->Add link (admin/structure/menu/manage/management) in admin menu.
Please see the image where I have added Archive View link under Reports menu. I have specified following 3 fields in the 'Add link' form,
Menu link title - Archive View
Path - Archive
Parent link - ----Report


How To Update Multiple Conditions Using MERGE Statements

Question: I have to compare source and Target data and MERGE them accordingly. But I have multiple conditions.
Below is my first set of source data
Source-Table1
ID       StartDate      EndDate     Designation
1        2018-01-01     2199-12-31  Associate Engineer
2        2018-02-01     2199-12-31  Software Engineer

Target-Table2
ID       StartDate      EndDate     Designation
1        2018-01-01     2199-12-31  Associate Engineer
2        2018-02-01     2199-12-31  Software Engineer

Create table Table1(
  Id int,
  StartDate datetime,
  EndDate   Datetime,
  Designation nvarchar(100)
  )

  Create table Table2(
  Id int,
  StartDate datetime,
  EndDate   Datetime,
  Designation nvarchar(100)
  )
--insert values
  insert into Table1 values(1,'2018-01-01','2199-12-31','Associate Engineer')
  insert into Table1 values(2,'2018-02-01','2199-12-31','Software Engineer')

  --Use Merge to Update/Insert values
MERGE Table2 t
  USING Table1 s
  on t.id=s.id
  WHEN MATCHED THEN
  update SET
  t.id=s.id,
  t.StartDate=s.StartDate,
  t.EndDate=s.EndDate,
  t.Designation=s.Designation

  WHEN NOT MATCHED BY TARGET THEN
  INSERT(
  ID,
  StartDate,
  ENDDate,
  Designation
  )
  VALUES
  (s.ID,
  s.StartDate,
  s.EndDate,
  s.Designation)
  ;

Now, this code doesn't work if I have to update multiple conditions.
For Example,if My source data has below values,then each ID cannot have overlap values.
When there is new record for each ID, I have to check on StartDate, If start Date is < enddate then, update my old endDate to last day of the previous month and
insert the new record else if ID and StartDate match, then update all records. If ID and StartDate does not mach then Insert.
Source-Table1
ID       StartDate      EndDate     Designation
1        2018-01-01     2199-12-31  Associate Engineer
1        2018-02-01     2199-12-31  Software Engineer
2        2018-02-01     2199-12-31  Software Engineer
2        2018-03-01     2199-12-31  Senior Software Engineer

Now I want my Target Table to have
ID       StartDate      EndDate     Designation
1        2018-01-01     2018-01-31  Associate Engineer
1        2018-02-01     2199-12-31  Software Engineer
2        2018-02-01     2018-02-28  Software Engineer
2        2018-03-01     2199-12-31  Senior Software Engineer

I am not able to do this Using MERGE statements.Can anyone of you help me to get this result?
Answer: If I understand your question correctly then you want to merge your source table with your target table. However, if a user's role has changed, example Associate Engineer to Software Engineer then you want to update the original record's EndDate to the last day of the month just before the new records start date.
If my understanding is correct then you should be able to achieve this as follow:
;MERGE  [Table2] [T]
USING   (
            SELECT       [T1].[Id]
                        ,[T1].[StartDate]
                        ,CAST(LEAD(EOMONTH(DATEADD(DAY, -1, [T1].[StartDate])), 1, [T1].[EndDate]) OVER (PARTITION BY [T1].[Id] ORDER BY [T1].[StartDate]) AS DATETIME) AS [EndDate]
                        ,[T1].[Designation]
            FROM        [dbo].[Table1] [T1]
        ) [S]
ON ([T].[Id] = [S].[Id] AND [T].[StartDate] = [S].[StartDate])
WHEN MATCHED THEN
    UPDATE
            SET [T].[EndDate] = [S].[EndDate],
                [T].[Designation] = [S].[Designation]
WHEN NOT MATCHED BY TARGET THEN
    INSERT
    (
      [Id],
      [StartDate],
      [EndDate],
      [Designation]
    )
    VALUES
    (
        [S].ID,
        [S].StartDate,
        [S].EndDate,
        [S].Designation
    );


GPU-Computation (CUDA) tex2d/tex3d - How to deal with anisotropic pixel/voxel

Question: I am quite new to cuda programming and i have a question about the texXD function. My goal is to implement a simple GPU-based ray tracer using the optimized CUDA functionality.
See CUDA texture API that is used by NVIDIA.
At my research I have to deal with images that have a different resolution for every dimension (like CT images, (x,y) have a different resolution as (z)). Resampling to an isotropic pixel/voxel size might bring up some problems (especially for medical diagnosis).
For example i have an image with size (100px x 50px) and a resolution of (2px/mm x 1px/mm). The ray enters the image at an arbitrary point and leaves is somewhere else. The ray is sampled in the direction form entrance to leaving point. At each sample point (pos.x,pos.y) the tex2D function carries out an (bicubicbilinear) interpolation taking the neighbour pixel values into account weighted by their distance from the sample point.
example image:
In both shapes the corner points are named the same way(x1,y1),.... The only difference is the physical space between the corner points. The interpolation point is (x,y). I computed an example using the formula for rectangular grids and yield a different results for both grids. But if I use the ratio of areas of the numbered rectangles I got a different result.
My Question: Will CUDA take care of the different resolutions of the  dimensions or does CUDA see all pixel in the same distance (and therefore as a squared grid)?
The formula used by CUDA seems to be the one for a squared grid (google:CUDA Texture fetching).
Or can I resample the image to squared grid before using tex2D without a substantial information loss?
Any suggestions are recommended. If you need some more clarification, feel free to ask. I will specifiy my question.
Comment: The link you've given is **not** for CUDA but for Cg.  They are not the same.
Comment: Textures don't support bi-cubic interpolation
Comment: Can you give an example where it matters?  (e.g. the values for four corner pixels, coordinates of the point in the middle you want to interpolate, and the results you get using isotropic and anisotropic interpolation)  Do the two methods actually give different results?
Comment: I updated the question with an example. As you may see this is my first time asking a question an therefore I need some iteration to get the questions asked correctly. :-)
Answer: I don't believe what (I think it is) you are trying to do can be achieved using textures. The sole filtering mode supported using textures is described here.
Some salient points:

Textures don't have resolution. The just have dimensions.
Textures data is implicitly uniformly spaced in all dimensions.
Texture interpolation is done in a reduced accuracy fixed point arithmetic format which gives 8 bits of representational accuracy

None of this seems like anything that would be useful for the interpolation on a non-uniform grid which you are describing. At a minimum you would need to perform a coordinate transformation before you could use the uniform filtering mode. The amount of effort and expense would be about the same as just writing an interpolation routine yourself in user code.
Comment: Thank you for clarification. I suspected that I have to write the routine myself.
Comment: Why would non uniform grid be a problem? In an interpolation, what matters is the position relative to the neighboring pixels. A voxel in the middle of two voxel in the same dimension will be in the middle whatever the distance of the two neighboring voxels. As long as your coordinate system is setup correctly and you convert the LPS ("world") system to the volume coordinate system properly, this should not be a problem.


Hide Superfish menu on selected pages

Question: I have installed Danland Theme and it is cool. I want the superfish menu to be appeared on few pages, not all the pages. For example if I type a wrong URL address in the address bar, it says Page not found and it still gives that Superfish menu there on the page.

I have some pages, where I don't want that superfish menu to be appeared.
Can anyone help?
Answer: Goto /admin/structure/block/ configure your superfish menu block
Scroll down to the bottom and locate "Show block on specific pages"
select this option " Only the listed pages "
and define the paths of the pages on which you want superfish menu to appear.

Hide Superfish menu on selected pages


Predicting CPU and GPU memory requirements of DNN training

Question: Say I have some deep learning model architecture, as well as a chosen mini-batch size. How do I derive from these the expected memory requirements for training that model?
As an example, consider a (non-recurrent) model with input of dimension 1000, 4 fully-connected hidden layers of dimension 100, and an additional output layer of dimension 10. The mini-batch size is 256 examples. How does one determine the approximate memory (RAM) footprint of the training process on the CPU and on the GPU?
If it makes any difference, lets assume the model is trained on a GPU with TensorFlow (thus using cuDNN).
Answer: The answer of @ik_vision describes how to estimate the memory space needed for storing the weights, but you also need to store the intermediate activations, and especially for convolutional networks working with 3D data, this is the main part of the memory needed.
To analyze your example:

Input needs 1000 elements
After layers 1-4 layer you have 100 elements, 400 in total

After final layer you have 10 elements

In total for 1 sample you need 1410 elements for the forward pass. Except for the input, you also need a gradient information about each of them for backward pass, that is 410 more, totaling 1820 elements per sample. Multiply by the batch size to get 465 920.
I said "elements", because the size required per element depends on the data type used. For single precision float32 it is 4B and the total memory needed to store the data blobs will be around 1.8MB.
Answer: I see two option:

The Network is loaded from disk
The Network is created on the fly

In both cases the size of the memory in GPU need to be multiplied by the Batch size as most of the network is copied for each sample.
Rule of Thumb if loaded from Disk:
If the DNN takes X MB on Disk , the network will be 2X in the GPU memory for batch size 1.
The Network is created on the fly  for batch size 1:
count the parameter and multiply by 4 bytes (float32 bit):
Counting the number of Parameter Manually:
 fc1    : 1000x100    (weights) + 100 (biases)
 fc2    : 100x100     (weights) + 100 (biases)
 fc3    : 100x100     (weights) + 100 (biases)
 fc4    : 100x100     (weights) + 100 (biases)
output  : 100x10      (weights) + 10 (biases)
Counting the number of Parameter using Keras:
model.count_params()
Comment: As far as I can tell, this gives the memory requirements for storing **the weights themselves**, but ignores any memory dedicated to storing anything **required strictly for the training**, such as the gradients. Storing the gradients is required, say for implementing momentum.  am I missing?
Comment: @Whaa this is correct, for normal training you need memory to store the weights, the activations in the forward pass and the gradients in the back-propagation pass (3x the memory even without momentum).
Comment: @mjul my experiments show 4.5x ik_vision's estimate.  I understand the rationale behind the 3x but I'm not sure why in practice it's using 4.5x.  There must be other Keras/TF overhead??


Set with a property

Question: This was a mock math olympiad problem sent to me by a friend.

Let $P$ be a set of prime numbers. Then, create a set $S$ of positive integers that satisfies the following property:

For every element $p \in P$, $p$ is a factor of at least three elements in $S$.

Prove that for all sets $P$ and $S$, it is possible to divide $S$ into 4 nonempty subsets such that each $p$ is a factor of at least three integers.

I tried to consider the element $a \in P$ that was a factor of the least number of elements in $S$ and see what I could discover, but got nowhere. I also thought that perhaps some sort of algorithm would work too, but I didn't make any progress. Overall, I'm just not quite sure how to even start.
Comment: I'm not sure I understand this problem properly.  Is it the case that if $P$ contains at least three primes, then condition 2 implies condition 1?
Comment: That's not necessarily true. If the three primes were $p_1, p_2$, and $p_3$, $S$ can contain the integer $p_1p_2p_3$. If $S$ consisted of only $p_1p_2p_3$, condition 2 would be satisfied but not condition 1.
Comment: Ahh, OK, got it, of course.
Comment: I just noticed that this question was changed almost completely a day after posting — while the structure is loosely the same, one condition was removed entirely, one changed and the conclusion is completely different. Why such a drastic change?
Answer: Consider a partition $\{S_1,S_2,\ldots,S_k\}$ such that
($\ast$) each $p \in P$ has multiples in at least two different sets $S_i$
for which $k$ is as small as possible. (Note that there exist partitions for which ($\ast$) is true, such as the partition with only singletons, because of (1).) We intend to show that $k \le 3$.
Indeed, suppose that $k \ge 4$. By minimality of $k$, there exists a $p \in P$ that only divides numbers in $S_1$ and $S_2$; otherwise, we could merge $S_1$ and $S_2$ and ($\ast$) would still hold. Similarly, there is a $q \in P$ that only divides numbers in $S_3$ and $S_4$. But now $S$ does not contain a multiple of $pq$, contradicting (2).
Answer: Not entirely an answer, but too long to be a comment: note that primes and factoring here are a little bit of a red herring. It's possible to rewrite this question in such a way that they don't come into it at all. To see this, let the set of primes be labeled $\{p_1, p_2, \ldots, p_N\}$ (where possibly there is no last $N$, in which case we'll say that $N=\omega$ just for convenience). Then label each number $i\in S$ by the set $s_i$ of numbers $j$ such that $p_j$ is a factor of $S$. For instance, if $P$ is the set $\{2, 3, 11\}$ and $S$ is the set $\{12, 22, 99\}$, then we would have $p_1=2, p_2=3, p_3=11$ and $s_{12}=\{1,2\}$ since $p_1$ and $p_2$ are the factors of $12$; similarly $s_{22}=\{1,3\}$ and $s_{99}=\{2,3\}$. But now we can write the condition '$p_j$ divides $i$' as '$j$ is a member of $s_i$' and just write $S$ in terms of the $s_i$ (e.g., here $S$ would be $\left\{\{1,2\}, \{1,3\}, \{2,3\}\right\}$) and your initial properties become:

for every $n \leq N$, there are at least two sets $s\in S$ such that $n\in s$
for every $i, j\leq N$ there is at least one set $s\in S$ such that $i\in s$ and $j\in s$ (or equivalently, $\{i,j\}\subseteq s$)

And your result becomes that it's possible to divide $S$ into three sets $S_1, S_2, S_3$ such that for every $n\leq N$ at least two $S_i$ contain a set which has $n$ as an element.
Comment: The bipartite graph representation might be an easier way to represent what you wrote. However, that doesn't yield any results for me.
Comment: @CalvinLin I was looking at possible graph realizations too, but likewise didn't really get anywhere with them.

Set with a property


flex3 datagrid horizontal alignment

Question: i cant find a way to horizontal alignment of the data grid rows, although it has a vertical alignment parameter.
Answer: Do you mean something like DataGridColumn's textAlign Style?
<code><mx:DataGrid>
  <mx:columns>
    <mx:DataGridColumn headerText="Column 1" textAlign="left"/>
    <mx:DataGridColumn headerText="Column 2" textAlign="center"/>
    <mx:DataGridColumn headerText="Column 3" textAlign="right"/>
  </mx:columns>
</mx:DataGrid>
</code>
Comment: i have an item renderer in each dataGridColumn and rows have CheckBoxes... the check boxes are always at left... do i have to contain them with an hbox and then use horizontal alighn???
Comment: Yes. That's what I would do too.

flex3 datagrid horizontal alignment


What is the dimension of $f(A)$ if $f:A\subseteq\mathbb{R}^k\to\mathbb{R}^n$ is linear and $A$ is a subspace of $\mathbb{R}^k$?

Question: Let $k\le n$ and $f:A\subseteq\mathbb{R}^k\to\mathbb{R}^n$. Obviously, $f(A)$ is a subspace of $\mathbb{R}^n$ iff

$\forall x,y\in A:\exists z\in A:f(z)=f(x)+f(y)$
$\forall x\in A,\alpha\in\mathbb{R}:\exists z\in A:f(z)=\alpha f(x)$

If $f$ is linear and $A$ is a subspace of $\mathbb{R}^k$, $(1.)$ and $(2.)$ are fulfilled. $\color{blue}{\text{Can we weaken these requirements on }f\text{ and }A\text{?}}$
Suppose $A$ has dimension $k'\le k$. What can we say about $\dim f(A)$?
Comment: @Arthur Hence, I've written "$f(A)$ is a subspace of $\mathbb{R}^n$ if and only if ..."
Answer: In the assumption that $f$ is linear you have that dim$f(A)\leq\mathrm{dim}A$. This is because if $u,v\in A$ are linearly dependent then $f(u),f(v)$ will be linearly dependent in $f(A)$: assume $\lambda u+\mu v=0$ then, since $f$ is linear, $\lambda f(u)+\mu f(v)=f(\lambda u+\mu v)=f(0)=0$. However, if $u,v\in A$ are linearly independent then you cannot deduce that $f(u),f(v)$ are linearly independent, for example if one is sent to the zero vector.
If $f$ is a monomorphism, i.e. $f$ is injective, then dim$f(A)=\mathrm{dim}A$. This is because monomorphism sent a linear independent set of vectors in a linear independent set of vectors. In particular a basis of $A$ will be sent to a basis of $f(A)$.
Notice that dim$f(A)=\mathrm{dim}A$ does not imply that $f$ is a monomorphism. For example assume that $\{u_1,...,u_{l},u_{l+1},u_k\}$ is a basis of $\mathbb{R}^k$ and  $\{u_1,...,u_{l}\}$ is a basis of $A$. Then you can construct a linear map with the following properties: $\{f(u_1),...,f(u_{l})\}$ is linear independent and $f(u_{l+1})=...=f(u_k)=0$. In this case $f$ is not a monomorphism (provided that $l<k$).
To conclude, I don't think that there is a nice property (other than "$f$ restricted to $A$ is a bijection") that will imply dim$f(A)\leq\mathrm{dim}A$.
Comment: Under which further requirement on $f$ would hold equality?
Comment: I edited to give more details!


Validation of Conditional String Android

Question: I have been trying to validate a sample string which I read from a file. I want to check if the condition in the given string evaluates to true or false.
<code>String Test = "( ((10>20) & (10>5)) & (7>9) ) | (123>45)";
</code>
How can I do that using Java. I have been trying to split the brackets and operators. Is there any easy way to solve this kind of textual expressions?
I have tried JSR.JAR but I'm getting

java.lang.NoClassDefFoundError: Failed resolution of: Lsun/misc/Service;                                                                            at javax.script.ScriptEngineManager.initEngines(ScriptEngineManager.java:108)at javax.script.ScriptEngineManager.access$000(ScriptEngineManager.java:55)at javax.script.ScriptEngineManager$1.run(ScriptEngineManager.java:98)at java.security.AccessController.doPrivileged(AccessController.java:45)at javax.script.ScriptEngineManager.init(ScriptEngineManager.java:96)at javax.script.ScriptEngineManager.(ScriptEngineManager.java:69)
Comment: Possible duplicate: http://stackoverflow.com/questions/19383953/is-it-possible-to-evaluate-a-boolean-expression-for-string-comparions
Comment: I have tried using ScriptEngine But Im getting the above exception.
Comment: Ah, I see, sorry. Maybe you can use a third party library on android like this: https://github.com/ericwlange/AndroidJSCore or this built on top of googles V8 engine: http://eclipsesource.com/blogs/getting-started-with-j2v8/
Answer: It seems that android does not provide the java scripting engine.
Possibly you could use a third party library instead:

AndroidJSCore
J2V8 (java wrapper built on top of googles V8 engine)


solution of $y(xy+1)dx+x(1+xy+x^2y^2)dy = 0$

Question: solve $y(xy+1)dx+x(1+xy+x^2y^2)dy = 0$
writting differential equation $xy^2dx+ydx+xdy+x^2ydy+x^3y^2dy =0$
$xy(ydx+xdy)+(ydx+xdy)+x^3y^2dy=0$
$(1+xy)d(xy)+x^3y^2dy=0$
could some help me with this, thanks
Comment: @DURGESHTIWARI: **Hint:** Let $y = \dfrac{v}{x} \implies y' = \dfrac{v'}{x} - \dfrac{v}{x^2}$.
Comment: @Moo if you wouldn't mind, could you please explain why this is the case? I'm curious.
Comment: Using this substitution makes the DEQ a Separable Equation and solvable. There could be other approaches.
Comment: @Moo wont the resultant integration be lengthy
Comment: The resulting integration is not bad, but you will not be able to solve it explicitly, but will get a closed-form implicit solution.
Answer: The solution (below) is obtained on the form of an implicit equation.

Then, it is not very difficult to explicit $x(y)$. But it seems not possible to get a closed form for the inverse function $y(x)$ with the available standard functions.


Qt Creator 2.7 add new disabled

Question: I'm sitting in Ubuntu 12.04 with Qt Creator v2.7 (tried new one aswell, 2.8 beta) and when I create a Non-Qt Project / Plain C++ Project (CMake Build) all seems well. But when I right-click on the project to Add New, that option is disabled. So is Add Existing Files..., New Subproject and Add Library.
Am I missing something obvious? I think I've been through pretty much all of the menus but I can't find anything seemingly related to this issue.
Thank you!
Comment: I don't use `cmake`, but if I remember this correctly you have to add the file/s in `CMakeLists.txt` and this makes sense because you explicitly choosing `cmake` over the internal building system.
Comment: You are correct! It seems I have not really understood what it means to use cmake in Qt Creator. Now only to figure out how to set your response to an answer.
Comment: I have added a complete answer, glad you solved this.
Answer: That's because you have to add the file/s in CMakeLists.txt and this makes sense because you explicitly choosing cmake over the internal building system.
Answer:
Add the file to the CMakeLists.txt file.
Note: If you added another file while working on the same project, that new .cpp file would already be added in the same folder structure as your current project. In that case, no changes to CMakeLists.txt are required.
Now simply, right click on the project entry and click on "Run CMake". This will automatically add the newly created .cpp file to the project structure and it will be shown in the project outline view.

Qt Creator 2.7 add new disabled


O que é o Spectre?

Question: O Spectre é uma falha de segurança que compromete uma grande quantidade de sistemas.

O que é?
Como ele funciona?
Que tipo de sistemas e dispositivos estão vulneráveis?
O que pode ser feito para se defender dele?
Por que ele recebeu esse nome?
Comment: Os votos de fechamento estão considerando que a pergunta é sobre hardware? Eu acho válida, especialmente considerando a relevância dessa vulnerabilidade.
Comment: @bfavaretto Acho que quem votou para fechar não deve ter entendido a pergunta.
Comment: Eu uso o Iobit ASC e ele faz o patch no Windows 10 para correção.
Answer: O que é?
O Spectre é uma vulnerabilidade decorrente de uma falha de projetos de microprocessadores que permitem que processos maliciosos possam ler a memória pertencentes a outros processos.
Foi descoberto junto com o Meltdown em meados de 2017, mas tornou-se público apenas na primeira semana de 2018.
Como ele funciona?
Para entender como o Spectre funciona, é necessário entrar-se em alguns detalhes de arquitetura de computadores, em especial o pipeline, a execução especulativa, o branch prediction e a memória cache.
O que é pipeline?
Para um processador executar uma instrução, é necessário realizar-se várias ações:

Buscar a instrução a ser executada na memória.
Decodificar a instrução e identificá-la.
Mapear os registradores que a instrução referência.
Executar a instrução propriamente.
Armazenar o resultado da instrução em algum registrador.

Os passos exatos obviamente variam bastante de um tipo de processador para outro. Processadores antigos executam uma instrução por vez, o que significa que apenas uma das etapas acima estaria ativa em um determinado momento. Processadores mais novos têm ganho de desempenho ao implementar o conceito de pipeline, onde uma instrução inicia a sua execução antes da anterior terminar: Enquanto o resultado da instrução X está sendo armazenada em algum registrador, a instrução X+1 já está sendo executada, a instrução X+2 está tendo os registradores mapeados, a instrução X+3 está sendo decodificada e a X+4 está sendo buscada na memória.
No entanto, o pipeline tem dois problemas:

Quando ocorrem instruções de desvio condicionais do tipo se A então B, senão C, pois antes da instrução que avalia A ter o seu resultado conhecido as instruções consecutivas já estão entrando pipeline. O processador não tem como saber se ele vai colocar o caminho do então ou o caminho do senão no pipeline.
Quando o resultado de uma instrução depende de carregar da memória principal algum valor qualquer, especialmente se este valor não estiver presente na memória cache. Carregar um valor da memória principal para um registrador pode demorar algumas centenas de ciclos do processador.

E é aí que entra a execução especulativa.
O que é execução especulativa?
Com a execução especulativa, o processador irá chutar o resultado de desvio condicional e então escolher um dos dois caminhos para colocar no pipeline mesmo sem saber se era o caminho certo. Se ele tiver acertado, então ótimo, o ganho de desempenho será satisfatório. Se tiver escolhido o caminho errado, ele descarta qualquer alteração que teria resultado disso, volta e toma o outro caminho, o que é mais lento.
Algo similar acontece quando um valor é lido da memória e está indisponível. Para não parar o pipeline, o processador chuta um valor lido (normalmente zero) e continua a execução especulativamente com esse valor. Se quando o valor tornar-se disponível, esse revelar-se ser diferente do valor chutado, o processador desfaz as alterações realizadas com o valor especulado e refaz com o valor correto.
O que é branch prediction?
Para saber é o melhor lado para ser chutado em desvios condicionais, o processador utiliza um algoritmo de branch prediction.
O branch prediction faz uma análise simples no histórico de cada desvio condicional para tentar determinar qual é o melhor lado para chutar. Se um determinado if tem caído muito mais vezes recentemente no então, o branch prediction vai dizer para chutar o então porque é provável que esse seja o caso da próxima vez que o if for executado. O mesmo ocorre se ele estiver caindo muito mais no senão. Os detalhes do algoritmo de branch prediction, tais como o número necessário de chutes errados para ele mudar de ideia, quais são os desvios que devem ser rastreados e quando variam de processador para processador.
Na prática, ifs cujo resultado sejam complemente aleatórios e caóticos são raros, então, exceto se o if estiver sendo executado pela primeira vez, o branch prediction provavelmente vai chutar o lado certo para o processador colocar dentro do pipeline.
O que é memória cache?
Além da memória principal, existe uma outra memória menor dentro do processador denominada cache. O acesso a ela é bem mais rápido do que o acesso a memória principal, porém a capacidade dela é bem menor. São mantidos na cache os dados mais frequentemente e recentemente acessados da memória principal. Os dados na cache constituem-se em blocos mapeados para a memória principal. O tamanho de cada bloco varia de processador para processador, mas tamanhos como 128, 256 ou 512 bytes são comuns. O tamanho da cache de cada processador é fixo e não pode ser alterado.
Ao manter os dados mais frequentemente e recentemente acessados na cache, evita-se o custo de tempo de ter que localizá-los na memória principal. Como a cache é menor que a memória principal, quando um bloco de dados tem que ser trazido da memória principal para a cache, um outro bloco de dados já existente na cache tem que ser retirado.
Na verdade, processadores modernos mantêm vários níveis de cache, onde além da cache da memória principal, temos a cache da cache e até mesmo a cache da cache da cache. Essas diversas caches são denominadas L1, L2 e L3, onde a L1 é a mais interna. Em processadores Intel, cada núcleo (core) do processador tem a sua própria L1 e L2, enquanto que a L3 é compartilhada entre todos os núcleos.
Qual é o problema da execução especulativa?
O caminho ou o valor que o processador de fato escolheu (branch prediction) para colocar no pipeline deveria ser algo completamente invisível para o processo que está sendo executado. Entretanto, dado o fato de que se o processador escolher o lado certo ou o valor certo na execução especulativa, ele executará a tarefa mais rápido do que se escolher o lado ou o valor errado, então o tempo demorado pode ser medido para determinar-se qual caminho o processador executou especulativamente.
A execução especulativa pode trazer blocos da memória principal para a cache do processador. Embora os efeitos da execução especulativa quando incorretos sejam revertidos, não há reversão nas caches. Um bloco de memória trazido à cache devido a uma execução especulativa fica lá mesmo se essa execução especulativa for revertida.
Isso significa que um hacker atacante pode, ao medir o tempo que uma função demora para executar, determinar se ela acessou a cache ou não, mesmo que de forma especulativa. Com certa engenhosidade, é possível fazer com que a diferença entre ter executado de forma rápida e ter executado de forma lenta sirva para revelar o conteúdo de alguma informação existente na memória.
Como o Spectre pode ser usado para elaborar um ataque?
O Spectre é uma vulnerabilidade que permite a um processo malicioso ler (de uma forma bastante indireta) o conteúdo da memória de um outro processo que deveria ser inacessível, ao aproveitar-se da execução especulativa.
Por exemplo, vamos supor que o processo a ser atacado tenha uma verificação como essa em C (código fornecido pelos descobridores do Spectre):
if (x < array1_size)
    y = array2[array1[x] * 256];

Nesse caso, isso trata-se de um if que verifica se o array1 pode ser acessado. Em caso positivo, o mesmo é acessado e o valor dele lido é usado para indexar-se o array2. O atacante precisa ter o controle do valor de x. O 256 é um valor que seja grande o suficiente para que diferentes valores de array1[x] resultem em diferentes porções de array2 sendo colocados na cache.
Com isso, o atacante primeiro treina o processador para que a execução especulativa sempre chute que o if vai entrar (ou seja, que não cairia em um else). Uma forma de fazer isso é atribuir zero para x e então invocar o código que contém o if acima algumas vezes.
Tendo o processador sido treinado, o atacante realiza algumas operações para garantir que array1_size e array2 fiquem fora da cache. Uma forma de fazer isso é usar a instrução clflush que serve especificamente para limpar a cache. Caso isso não seja possível, pode-se acessar diversas partes da memória distantes umas das outras para que elas ocupem a cache e acabem deixando array1_size e array2 fora dela.
O atacante então executa esse código utilizando um valor x maior do que array_size. Uma vez que array_size não está disponível na cache, o processador vai chutar o seu valor e começar uma execução especulativa que vai incorretamente entrar no if e fazer uma leitura de dados fora do limite com o array1[x]. Como essa leitura é fora do limite, ela resultará em alguma outra informação qualquer que esteja na memória do processo atacado.
Executando-se isso repetidamente com diversos valores para x, é possível acessar-se grande parte da memória do programa atacado. Assim sendo se o atacante quiser forçar um acesso especulativo ao endereço de memória y do programa atacado, sabendo-se que a é o endereço de memória de array1, computa-se o x com x = y - a.
Entretanto, embora qualquer byte da memória do programa atacado possa ser lido pelo mesmo ao acessar-se array1 fora dos seus limites (mesmo que de forma especulativa), isso ainda não permite ao atacante conhecer o seu conteúdo, até porque, de forma direta, ele só obterá o resultado da execução real, que não será relevante. E é aí que o array2 entra.
O conteúdo lido de array1[x] é usado para acessar-se array2, de forma que diferentes partes de array2 entram na cache para diferentes valores obtidos de array1[x]. Supondo que a leitura especulativa de array1[x] tenha produzido como resultado um número k, um acesso a array2[k * 256] será rápido, enquanto que um acesso a qualquer outra parte de array2 será lento.
Se o atacante tiver acesso a array2, ele poderá chutar um valor j (vamos supor que 42) e acessá-lo na posição j * 256 e se esse acesso for rápido, então 42 será o valor da posição correspondente a x. Caso contrário (se o acesso for lento) o atacante saberá que o valor na posição y não é 42, e poderá repetir esse o processo com outros valores de j até descobrir qual é o conteúdo do byte y.
Caso o atacante não tenha acesso ao array2, ainda assim ele pode invocar o código a ser atacado passando um valor válido de x e medir o tempo resultante, de forma que se for rápido, deduz-se que o bloco de array2 estava na cache e isso ajuda a descobrir qual parte de array2 foi acessada e consequentemente (com uma boa dose de tentativa e erro) qual o valor de y.
Tudo isso é possível se o atacante tiver acesso a um código tal como o demonstrado acima. No entanto, vários outros padrões de código que contenham mais de dois caminhos possíveis (ifs, switches, whiles) e façam acessos a blocos de memória (arrays, matrizes e assemelhados) podem ser de alguma forma abusados ao mensurar-se o tempo demorado em execuções especulativas. Ou seja, esses padrões de código que podem ser abusados pelo Spectre são comuns e abundantes em quase todos os tipos de programas, muitas vezes encontrados até mesmo dentro de bibliotecas padrão que nele são inclusas.
O ataque não se restringe apenas a código de baixo nível que interaja diretamente com a memória. Por exemplo, o seguinte ataque em Javascript foi publicado pelos descobridores do Spectre:
if (index < simpleByteArray.length) {
    index = simpleByteArray[index | 0];
    index = (((index * TABLE1_STRIDE)|0) & (TABLE1_BYTES-1))|0;
    localJunk ^= probeTable[index|0]|0;
}

Uma variante do Spectre é quando o atacante tem o controle não apenas de determinar se um desvio condicional será ou não executado especulativamente, mas também quando ele tem o controle de para onde o desvio ocorre. Em muitas linguagens, isso é mais ou menos o caso que ocorre quando o atacante está se aproveitando de uma função, procedimento ou método que recebe como parâmetro um lambda, um callback, uma outra função ou coisa semelhante e essa seja algo que o atacante controle. Dessa forma, a função atacada acaba por executar código escolhido pelo atacante de forma especulativa, aumentando as possibilidades de realizar-se o ataque.
Ataques que determinem um bit de cada vez são possíveis. Isso reduz a necessidade de realizar-se 256 testes por byte da memória atacada para apenas 8 testes por byte (ou seja, 1 por bit).
Que tipo de sistemas e dispositivos estão vulneráveis?
Quase todos os dispositivos modernos estão vulneráveis. PCs, Notebooks, smartphones, tablets, servidores virtualizados e cloud. Isso ocorre porque quase todos os processadores modernos usam execução especulativa.
Os únicos dispositivos que ficam de fora são microcontroladores, arduino, dispositivos embarcados, calculadoras e outros dispositivos que têm projetos extremamente simples e capacidades extremamente limitadas ou que são bastante antigos. Esses dispositivos não usam execução especulativa ou mesmo pipelines em seus processadores.
Especificamente, o programa atacante precisa ter a possibilidade de interagir de alguma forma com o programa a ser atacado, o que diminui bastante a possibilidade de um hacker aproveitar-se disso. No entanto, no caso de navegadores, isso é bem mais factível de ocorrer vez que o Javascript permite ao atacante forjar o código que acesse qualquer outra parte da memória do navegador de forma especulativa (inclusive a pertencente a outras abas), o que em teoria significa que qualquer aba poderia usar o Spectre para ler o conteúdo de qualquer outra aba ou mesmo o de detalhes internos do navegador, e com isso roubar senhas ou outros tipos de informações sensíveis.
O que pode ser feito para se defender dele?
O Spectre é algo muito difícil de se defender. As duas formas de combatê-lo são:

Eliminar ou modificar bastante o funcionamento da execução especulativa.
Eliminar-se a possibilidade de medir-se o tempo de forma precisa o suficiente para viabilizar o ataque.

Nenhuma das duas alternativas é muito atraente. A execução especulativa é que traz altos ganhos de desempenho, não podendo ser abandonada. E mesmo que fosse, ainda iria demandar a troca de todos os processadores de quase todos os PCs, notebooks, tablets, smartphones e servidores produzidos nos últimos 20 anos ou mais, o que claramente é inviável.
Os desenvolvedores de navegadores (Chrome, Firefox, Safari, Edge, etc) por enquanto estão fornecendo uma solução paliativa que consiste em atualizações que reduzem a precisão das funções no Javascript que medem o tempo. Com isso, a ideia é impedir que um atacante possa medir o tempo que determinadas instruções demoraram para executar, o que impede o ataque de surtir efeito.
É de se admitir que essa solução é bastante paliativa e simplória, mas uma vez que essa falha veio ao público apenas muito recentemente, ainda desconhecem-se outros métodos que permitam a sua mitigação.
Os desenvolvedores da LLVM estão modificando a forma como ocorre a compilação de código para reduzir (mas isso não elimina ainda) a possibilidade de acessar-se partes indevidas da memória por meio de execução especulativa.
Por que ele recebeu esse nome?
A chave de tudo está na execução especulativa. A palavra especulativo lembra espectro. Além disso, nas palavras dos descobridores, esse problema é algo que irá assombrar a todos por muitos anos, pois é algo bastante difícil de ser corrigido. E é por isso que ele recebeu esse logotipo:

Eu ainda acrescentaria que execuções especulativas de código que são revertidas é algo que me soa como um código "fantasma" ter sido executado no processador. Ele é algo que deveria ser totalmente invisível e indetectável e que não deixaria nenhum traço perceptível de sua existência no mundo real tal como se nunca tivesse existido, até porque dependia de condições que não eram verdadeiras para vir a existir de fato. Mas, algum efeito paranormal da sua (não-)existência ainda assim é capaz de fazer com que de alguma forma ele se manifeste no mundo dos vivos trazendo assombração e tormento.
Referências

https://googleprojectzero.blogspot.com.br/2018/01/reading-privileged-memory-with-side.html
https://spectreattack.com/spectre.pdf
https://spectreattack.com/
http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20180101/513630.html
https://winaero.com/blog/windows-7-8-1-fixes-meltdown-spectre-cpu-flaws/
https://winaero.com/blog/secure-chrome-meltdown-spectre-vulnerabilities/

O que é o Spectre?


How to use expert class settings for display suite for images?

Question: I've tried different combinations, but it's now working or showing up in chrome inspector...
I'm also using Bootstrap template, could that by a problem?
Or maybe I'm not filling out the information correctly in the field boxes?
Comment: It is behaving exactly as expected. The field formatter needs to run, and it is wrapped in the 'Field item' that you specify. In your case you specify an img wrapper which is self closing and therefore will not wrap the field at all as it will just insert a self closed img tag with no src attribute above your img field. In other words what you are trying to do (add a class to the img field) is not possible with Display Suite
Comment: So what should I put in there so it works?
Comment: You either override the preprocess or theme functions for image / image style (google: drupal add class to image) or you add a div around the image via Display Suite and target the enclosed image via CSS via that parent. Then just add the CSS for responsive image (I assume that is what you want) to that. Just duplicate it from the Bootstrap CSS class img-responsive. Bootstrap is nice but it does force you to add specific classes to your html at times which may not always be easy-as-you-go. Just work around it.
Answer: Have you tried  Image Class.

Extends the Image formatter by adding an option to add an element
  class.

It does not work in combination with Display Suite unfortunately as per this post: Merge Image Class into Display Suite
Answer: Ok, got it figured out.
It didn't work because I had nothing selected for:
<code> "Use custom display settings for the following view modes"
</code>
So I had to select "full content" then use that one for custom fields.
The default tab page doesn't work....
So using only default will NOT work, you MUST have a custom diplay.


Printing serial number in jasper report detail

Question: I have created a jasper report. In that report in detail areaI have "serialNumber" column. That column wants to be auto incrementive and stats with "1". I am using hibernate for query.
Sample code is :
<detail>
    <band height="17" splitType="Stretch">
        <textField isBlankWhenNull="true">
            <reportElement x="12" y="0" width="27" height="15"/>
            <textElement/>
            <textFieldExpression class="java.lang.Integer"><![CDATA[serialNumber]]>
            </textFieldExpression>
        </textField>
        <textField>
            <reportElement x="51" y="0" width="37" height="15"/>
            <textElement textAlignment="Center" verticalAlignment="Middle"/>
            <textFieldExpression class="java.lang.String"><![CDATA[$F{date}]]>
            </textFieldExpression>
        </textField>
        <textField>
            <reportElement x="138" y="0" width="75" height="15"/>
            <textElement textAlignment="Center" verticalAlignment="Middle"/>
            <textFieldExpression class="java.lang.String"><![CDATA[$F{time}]]>
            </textFieldExpression>
        </textField>
    </band>
</detail>

Can anyone help to print serial number in jasper report.
Answer: Using variable we can achieve that.
Sample code :
 <variable name="seraialNumber" class="java.lang.Integer" resetType="None"
calculation="Count"/>

Depends on the requirement we have to change expression
Answer: You have to bind the column to a bean which returns incrementing numbers.
Answer: You Can use alternate solution for this problem that build in Variable $V{REPORT_COUNT}.
This variable will return the row count in Integer format.
Sample Expression :
<textFieldExpression class="java.lang.Integer"><![CDATA[$V{REPORT_COUNT}]]></textFieldExpression>.

Answer: <variable name="serial number" class="java.lang.Integer" resetType="Column" calculation="Count">
        <variableExpression><![CDATA[0]]></variableExpression>
    </variable>

I will show an image for better understanding


how to store images into file_managed table from android to drupal

Question: I have tried calling Drupal file service from android and it is storing images in application/octet format and not in image/jpeg format in file_managed table.
$data['file'] ='encodedimage';
$fid = file_save_data($data);

So I thought I will call file_save_data($data) to store images where I pass the image as encoded string. But it is still storing in application/octet format and not in image/jpeg.
Can somebody help me to store as image/jpeg format into file_managed table?
Answer: The Services module provide an easy to use web services enpoint to create file which do all the heavy PHP work for you.
In file_save_data(), the mime type of the file is derived automatically, likely from its filename. You can set the filename of the saved file by using the $destination argument.
Comment: problem in using services module is in filemime type it is storing as application/octet so i wanted it to be image/jpeg


Ubercart: maintaining cart content after user login

Question: I have a Ubercart site where the user can add items to cart even if it is not logged in: the problem is that when he logs in the cart is emptied and he has to refill it.
Is there a way to save the cart for the anonymous user and, when he logs in, to retrieve the cart content?
Comment: i'm having the same problem. what was your solution?
Comment: Have you find the issue with your code ?
Comment: I would also like to know?
Answer: The feature looking for is default ubercart behavior. You may have missed with some of your custom code may be with hook_user Check that to see what happens and try disable any custom modules.


Object detection with just one image?

Question: Deep neural networks require lots of examples to learn tasks like image classification, and object recognition. On the other hand, we humans can learn and identify object just by looking at it once. Is there any method that allows us to do object detection just with one example? I tried to search for it, but couldn't get any satisfactory solution.
Answer: Can you train an algorithm to recognize a class with a single example? Yes, this is called one-shot learning. However, you will of course have little guarantee that it works well.
But don't we humans learn from single examples too? Not really. You may recognize someone after seeing them only once, or even after only seeing a single picture of them. But that is after you have already learned to recognize many different people's faces, and after you have already learned to discern a myriad of other things from a human face.
An algorithm can do this too, through transfer learning, where an 'unrelated' task is used to learn the general task of image recognition. If you already know that all images in your task are faces, you can use that information to your advantage and use transfer learning based on other facial recognition data, or you could use an existing pre-trained network as a starting point.
Depending on the application you have in mind, it can in fact work reasonably well. See for example this example,$^\dagger$ of a network that can do 3D reconstruction of a face from a single example.

$\dagger$: Jackson et al. (2017): Large Pose 3D Face Reconstruction from a Single Image via Direct Volumetric Regression. International Conference on Computer Vision
Comment: Thanks for pointing out "One Shot Learning".  Others may find this useful - https://paperswithcode.com/task/one-shot-learning

Object detection with just one image?


Why is my muted guitar noisy in my new house and the noise goes away when playing any note?

Question: 1) I have noticed that when I leave the metal parts of the guitar and the strings untouched, there is a significant noise when my distortion pedal is on.
On touching the strings/tailpiece(I have a LP), the noise used to go away almost completely. I suspect this is a grounding problem on my guitar but any leads on this would help.
2) This is my main problem where I really need an answer. Recently, I have moved into another place.
Since then,I have noticed that on touching the strings/tailpiece, the noise reduces to what is probably half. This means in my new house, for some reason there is also noise due to other than the grounding problem I have suspected. What I have found is when I play any note(even very low ones), the noise is completely removed and I can hear the note very well. But like I mentioned, I can hear some noise when all strings are muted/touched.
The only thing I have changed in my new house is that I am not using one of those circular extension boxes.
Please help!
This is my signal chain: Gibson LP Signature T > JHS Angry Charlie > Egnater Tweaker 15 head and cab.
Comment: You might try a 3-prong outlet tester ( https://www.google.com/search?q=3+prong+outlet+tester&source=lnms&tbm=isch ) to ensure you have proper grounding. If you are fixing the ground by touching it, you are the path to ground and that is potentially dangerous. Also, ensure all your equipment is powered off a single outlet.
Answer: Distortion effects are typically produced by having having very high gain at the low-amplitudes portions of each wave, and lower gain at the higher-amplitude portions.  If the guitar is not being played, any stray noises will have low amplitude and thus be maximally amplified.  A common solution is to use a noise gating function, either as a stand-alone pedal or integrated with some other function.  A noise gate will mute all sounds from an instrument when it has below a certain volume for some length of time (e.g. 1/20 second) and start passing through audio as soon as it exceeds that volume.
If you can solve grounding issues or use a humbucker or pickup arrangement with two out-of-phase coils those approaches may be preferable to using a noise gate, but a noise gate may help deal with other stray noises that grounding fixes wouldn't solve (e.g. sounds from handling the instrument, etc.)
Answer: It sounds like you have a grounding problem. The noise will change when you touch any of the metal parts that are connected to pickups.
If the noise is only present when you use distortion pedal, then it might be it that is the problem. Maybe the connector is broken or there is something else lose inside?
The noise in the new house might come from other electrical appliances.  Dimmer switches generate a lot of electrical noise, faulty fluorescent tube, and so on. If you have a grounding problem, then this will add noise to you signal.
Comment: Re: the second paragraph: the pedal *may* just be amplifying a ground noise that is always there. Without some sort of noise gate, distortion pedals are super noisy, even when the volume knob is on 1. Also, the particular pedal may have a compressor circuit that could be lifting the volume floor.
Comment: @Yorik this is more likely, any grounding issue with the guitar will always be much more noticeable when playing through something which compresses the sound.
Answer: Also, the LP Signature T has coil-splitting capabilities. If you are in single-coil mode, then you are liable to get 60 cycle hum from the electrical devices in your space. Try moving the guitar physically around while not touching the metal. If the "noise" gets better or worse depending on which way you face, then it's probably hum. See what happens if you turn the coil-split on and off...


Fetch all the values of an attribute through NSPredicate in CoreData

Question: This question will sound like a newbie but i have gone through all threads for my solution which is still an issue for me. So i have an entity "LookUp" which has an attribute 'descrip'.
Now my question is i want to fetch all values of attribute 'descrip'.
Till now i have used all this queries:
<code>[NSPredicate predicateWithFormat:@"descrip == %@",[NSNumber numberWithInt:1]];
[NSPredicate predicateWithFormat:@"descrip == %@",@"descrip"];
[NSPredicate predicateWithFormat:@"descrip == %@",[NSNumber numberWithBool:YES]];
</code>
if i fire a query
<code>[NSPredicate predicateWithFormat:@"descrip == %@",@"Art Gallery"];
</code>
it returns me an array with the values associated with "Art Gallery". The 'descrip' attribute contains 250 values like "Art Gallery".
Please help it out. Thanks in advance.
Comment: Have you tried [NSPredicate predicateWithFormat:@"descrip == %@",@"%"];? Do you want only the unique values of descrip?
Answer: NSPredicate is used to limit your results to entities that adhere to a certain restriction - like you said, descrip == @"Art Gallery" will return all entities that have a decrip attribute set to Art Gallery.
In your case, you do not want to restrict the entities in your query. Just perform your query without any predicate, and all entities will be returned. Now just loop over the entities, and get all values of descrip into a NSMutableSet or NSMutableDictionary, and you have your list of descrip values.
Answer: You probably want to modify the fetch request, rather than a predicate. See "Fetching Distinct Values" in Apple's Core Data Snippets.
<code>NSManagedObjectContext *context = // Get the context.

NSEntityDescription *entity = [NSEntityDescription entityForName:@"LookUp" inManagedObjectContext:context];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch:@[@"descrip"]];

// Execute the fetch.
NSError *error;
id requestedValue = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
    // Handle the error.
}
</code>
Answer: You can also set the request
<code>[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:
  [NSArray arrayWithObject: @"descrip"];
</code>
But you'd still have to loop over the results array in order to grab the descrip values only.


Are these two inclusions of finite groups, equivalent?

Question: Definition :  Let $\sim$ be the equivalence relation on inclusions of finite groups, generated by :
$(H \subset G) \sim (\phi(H) \subset \phi(G))$, with $ \phi: G \to L$  a group morphism, and $ker(\phi) \subset H$.

Question :  $(\langle (1234)   \rangle \subset S_4 ) \sim (\langle
 (12),(34)   \rangle \subset S_4 )$ ?

Warning: Of course, there is no $\phi \in Aut(S_4)$ with $\phi(\langle (1234)   \rangle) = \langle (12),(34)   \rangle$,   because $\langle (1234)   \rangle \simeq \mathbb{Z}_4 \not\simeq \mathbb{Z}^2_2 \simeq \langle (12),(34)   \rangle$, that why $\sim$ is the equivalence relation generated by the relation above, not just the relation alone.
Remark : the non-trivial normal subgroups of $S_4$ are $A_4$ and $\langle
 (12)(34), (13)(24)   \rangle$ (see here).
Motivation : These inclusions are famous in the group-subgroup subfactor theory (see here p47).
Comment: No. If $H \subset G$ is equivalent to $X \subset Y$ then the permutation action of $G$ on the cosets of $H$ is equivalent to the permutation action of $Y$ on the cosets of $X$. However, those two groups of degree 6 are not permutation isomorphic.
Comment: @JackSchmidt : I have developed your comment as an answer, I hope it's what you had in mind.
Answer: I'm not an expert in finite groups theory, so I will try to develop the comment of Jack Schmidt :
Let $(H \subset G)$ and $\phi:G \to L$ with $ker(\phi) \subset H$.
Let $\Omega=G/H$ and $\Omega' = \phi(G) / \phi(H)$.
Let the map $\delta : \Omega \to \Omega'$ : $\delta(gH) = \phi(g)\phi(H)$
$\delta$ is well-defined because if $g_1^{-1}g_2 \in H$ then $\phi(g_1)^{-1}\phi(g_2) = \phi(g_1^{-1}g_2) \in \phi(H)$
$\delta$ is then obviously surjective, and it's injective because if $\phi(g_1)^{-1}\phi(g_2) \in \phi(H)$ then $g_1^{-1}g_2 \in H$, because for $h \in H$, $\phi^{-1} (\{\phi (h) \}) = h.ker(\phi) \subset H$.
Let $\pi: G \to S_{\Omega} : \pi(g_1)(g_2H) = g_1g_2H$, then $\pi(G) \simeq G/ker(\pi) $
$ker(\pi) = \{ g_1 \in G: g_1g_2H = g_2H,  \forall g_2 \in G \} = \bigcap_{g_2 \in G} g_2^{-1}Hg_2 = core_{G}(H) \subset H$ is the normal core of $H$ in $G$ i.e the largest normal subgroup of $G$ contained in $H$.
Idem, let $\pi': \phi(G) \to S_{\Omega'} $, then  $\pi'(\phi(G)) \simeq \phi(G)/ker(\pi') $
Now $\pi(G)$ and $\pi'(\phi(G))$ are permutation isomorphic because $\delta$ is a bijection and obviously $\delta(\pi(g_1)(g_2H)) = \pi'(\phi(g_1))(\phi(g_2)\phi(H))$;  in particular $\pi(G) \simeq \pi'(\phi(G))$.
Conclusion, the equivalence relation generated by:
$$(H \subset G) \sim (\phi(H) \subset \phi(G)) \text{ with }   \phi: G \to L \text{ morphism  and } ker(\phi) \subset H$$  implies this equivalence relation  $\sim'$ as above (equivalence of permutation actions on the cosets).
Optional question : What's about the converse ?

Anyway, about my example :
If $(\langle (1234)   \rangle \subset S_4 ) \sim (\langle
 (12),(34)   \rangle \subset S_4 )$, then $(\langle (1234)   \rangle \subset S_4 ) \sim' (\langle
 (12),(34)   \rangle \subset S_4 )$ and so $\langle (1234)   \rangle \simeq \langle
 (12),(34)   \rangle$, because the normal cores are trival,  contradiction.
The normal cores are trival because there is not non-trivial normal subgroup of $S_4$ contained in $\langle (1234)   \rangle $ or $ \langle
 (12),(34)   \rangle$, thanks to the classification of the normal subgroups of $S_4$ given above.
Comment: This seems fine. I think the equivalence relation looks like $(H \subset G) \to (H/H_G \subset G/H_G) \cong (X/X_Y \subset Y/X_Y) \leftarrow (X \subset Y)$ where $K_L$ is the largest normal subgroup of $L$ contained in $K$. In other words, every inclusion is equivalent to a core-free inclusion, and two inclusions are equivalent iff there core-free inclusions are permutation isomorphic.


How to show this map is open?

Question: Let $f$ be the canonical quotient map of $\mathbb R^{n+1} - \{0\}$ onto $\mathbb R P^n$. Restrict $f$ to the hyperplane $H$ away from zero, so let $g = f|H$. Then I want to show that $g$ is a homeomorphism. It is easy to check that $g$ is bijective and continuous. Also easy to show that $f$ is an open mapping.
But how to show that $g$ is an open mapping?
Comment: Maybe use some concrete parametrization for H? For example let $H=\{(\mathbf{x}, 1)| \mathbf{x} \in \Bbb{R}^n\}$ that is the hyperplane with the $(n+1)$-th coordinate equaling 1. And let $p: \Bbb{R}^{n+1}\sim \{0\} \rightarrow H$ be the projection from $\Bbb{R}^{n+1}\sim \{0\}$ to it: $p((\mathbf{x}, y)) = (\mathbf{x}/y, 1)$. Then for any open set $G$ in $H$, $p^{-1}(G)$ is open in $\Bbb{R}^{n+1}\sim \{0\}$. And $p^{-1}(G) = f^{-1}(g(G))$. By definition of $\Bbb{R}P^n$, $g(G)$ is open.
Answer: There are infinitely many such hyperplanes. Okay, let us pick one. If $g$ were a homeomorphism, we would get a homeomorphism $\mathbb R^n \to \mathbb RP^n$. But this cannot exist.

How to show this map is open?


Create temp table with variable @user

Question: I have a Store procedure that receives a variable @user and creates a temporary table called with @user value for example #mrossi.
declare @user nvarchar(100)
    ,@sql nvarchar(100)
set @sql = 'CREATE TABLE #'+@user+'(Tipo nvarchar(10),Val float)'
exec(@sql)

The execution ends without issue, but the table is not created.
What do i wrong?
Comment: It is a scope issue.  The temp table evaporates when the session completes.   That said, being a temp table, there is really no reason to customize by user name.  Just use temp1, temp2, etc/
Comment: It does create the table, but it is dropped when the `EXEC` completes. This is generally a good thing, because it allows you to create temporary tables in dynamic batches without fear of clashing with something else. You can verify this with `EXEC('CREATE TABLE #Foo(ID INT IDENTITY); SELECT [name] FROM tempdb.sys.tables'); SELECT [name] FROM tempdb.sys.tables;`. Inside the batch, you should see `#Foo_______...`. Note that this is true even inside a stored procedure (this doesn't appear to be explicitly documented in either `CREATE TABLE` or `EXEC`, but it is how it works).
Comment: Ok, but in this SP I Insert values in this temp table and I use them to check some values, so why the system not created it but if I exec CREATE TABLE #mrossi(Tipo nvarchar(10),Val float) the system create it without issue?
Comment: As soon as you call this procedure, as written, it is created and then goes away. Anything you want to do with this temp table needs to happen inside of the procedure as @JohnCappelletti stated.
Answer: once your stored procedure has been called, the temp table then 'drops out of scope' and is deleted when you drop back into any calling procedure.
You may have noticed that in SSMS the #temp table does hang around after you have called code in a window that makes a temp table.
You can experiment with ##temp tables which persist until the connection that created them gets closed.  But watch out, they are visible globally to all connections.
declare @user nvarchar(100), @sql nvarchar(100);

SET @user = 'don';

SET @user = @user + REPLACE(cast(newid() as nvarchar(100)),'-','');
print @user;
set @sql = 'CREATE TABLE ##'+@user+' (Tipo nvarchar(10),Val float)'
exec(@sql);
print @@error;
set @sql = 'INSERT ##' + @user + ' VALUES(''foo'',3.14)'
exec(@sql);

set @sql = 'SELECT * FROM ##' + @user;
exec(@sql);

Comment: Ok, but in this SP I Insert values in this temp table and I use them to check some values, so why the system not created it but if I exec CREATE TABLE #mrossi(Tipo nvarchar(10),Val float) the system create it without issue?
Answer: The table is created but you can not access the table or variable out side the script execution scope where the table is created. You can access the table as below-
declare @user nvarchar(100)
,@sql nvarchar(100)

SET @user = 'Test'
SET @sql = 'CREATE TABLE #'+@user+'(Tipo nvarchar(10),Val float)

SELECT * FROM #test'

EXEC(@sql)

Create temp table with variable @user


Prove $\mathscr{F}[(1+|x|^2)^{-s}]\in L^1(\mathbb{R}^d)$

Question: Let $s>0$, show that $\mathscr{F}[(1+|x|^2)^{-s}]\in L^1(\mathbb{R}^d)$.
The original goal is to prove that $W^{s,p}(\mathbb{R}^d)\hookrightarrow L^p(\mathbb{R}^d)$ for all $s>0,1\le p\le \infty$, where the norm of $W^{s,p}$ is $||f||_{s,p}=||\mathscr{F}[(1+|\omega|^2)^s\hat f(\omega)]||_p$
Answer: For $x\in\mathbb{R}^d$, define $\displaystyle G(x)=\int_0^\infty t^{s-1-d/2}e^{-t}e^{-\frac{|x|^2}{4t}}dt$. Since $t^{s-1-d/2}e^{-t}e^{-\frac{|x|^2}{4t}}>0$, $0<G(x)\le\infty$ is well-defined.
By Tonelli's theorem $\displaystyle||G||_1=\int_{\mathbb{R}^d}dx\int_0^\infty t^{s-1-d/2}e^{-t}e^{-\frac{|x|^2}{4t}}dt=\int_0^\infty t^{s-1-d/2}e^{-t}dt\int_{\mathbb{R}^d}e^{-\frac{|x|^2}{4t}}dx\\\displaystyle=(4\pi)^{d/2}\int_0^\infty t^{s-1}e^{-t}dt=(4\pi)^{d/2}\Gamma(s)<\infty$
So $G\in L^1(\mathbb{R}^d)$.
By Fubini's theorem $\displaystyle\hat G(\xi)=\int_{\mathbb{R}^d}G(x)e^{-2\pi i x\xi}dx=\int_0^\infty t^{s-1-d/2}e^{-t}dt\int_{\mathbb{R}^d}e^{-\frac{|x|^2}{4t}}e^{-2\pi i x\xi}dx\\\displaystyle=(4\pi)^{d/2}\int_0^\infty t^{s-1}e^{-t}e^{-4\pi^2 t|\xi|^2}dt=(4\pi)^{d/2}\int_0^\infty (1+4\pi^2 t|\xi|^2)^{-s}w^{s-1}e^{-w}dw=(4\pi)^{d/2}\Gamma(s)(1+4\pi^2 t|\xi|^2)^{-s}$.
By uniqueness of Fourier transform, $\displaystyle\mathscr{F}^{-1}[(1+4\pi^2 t|\xi|^2)^{-s}](x)=\frac{G(x)}{(4\pi)^{d/2}\Gamma(s)}\in L^1(\mathbb{R}^d)$


Destruir Tedits em tempo de execução

Question: Possuo uma aplicação que cria TEdits de 1 a 15
Gostaria que eles desaparecem, mas quando a pessoa clicar no botao de criar eles voltasem..
eles foram criados da seguinte maneira:
ArrayEdit[x] := TEdit.Create(Self);
ArrayEdit[x].Parent:= Self;
ArrayEdit[x].Left := 100 + x * 50;
ArrayEdit[x].Top := 124;
ArrayEdit[x].Width := 41;
ArrayEdit[x].Height :=24;
ArrayEdit[x].Name := 'edit'+ inttostr(x+20);

E estou destruindo eles da seguinte maneira:
 for i := ComponentCount - 1 downto 0 do
    begin
      If (Components[i] is tedit) then
        Tedit(Components[i]).Destroy;
    end;

O problema é o seguinte, ele da um erro de Acess Violation e também seeu destruir os edits terei que fechar a aplicação para usá-los novamente, alguma ideia?
Comment: Fiz aqui usando o seu código e está tudo ok.
Answer: Algumas observações:

Não execute Destroy diretamente, prefira usar o Free, que executa o
Destroy apenas depois de checar se o componente realmente está alocado.
O que você chama de "desaparecer" é realmente destruir o componente?
Não bastaria torná-los invisíveis?

Para torná-los invisíveis bastaria fazer:
for i := ComponentCount - 1 downto 0 do
begin
  If (Components[i] is tedit) then
    Tedit(Components[i]).Visible:= false;
end;

E para torná-los visíveis novamente, seria só fazer
for i := ComponentCount - 1 downto 0 do
begin
  If (Components[i] is tedit) then
    Tedit(Components[i]).Visible:= true;
end;

Comment: Ou remover/adicionar o parent
Answer: Com esse código aqui (que usa o código que você passou), está tudo ok.
unit Unit2;

interface

uses
  Winapi.Windows,
  Winapi.Messages,
  System.SysUtils,
  System.Variants,
  System.Classes,
  Vcl.Graphics,
  Vcl.Controls,
  Vcl.Forms,
  Vcl.Dialogs,
  Vcl.StdCtrls;

type
  TForm2 = class(TForm)
    btn1: TButton;
    btn2: TButton;
    procedure FormCreate(Sender: TObject);
    procedure btn2Click(Sender: TObject);
    procedure btn1Click(Sender: TObject);
  private
    procedure criarEdits;
  public

  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.btn1Click(Sender: TObject);
var
  i : Integer;
begin
    for i := ComponentCount - 1 downto 0 do
    begin
        If (Components[i] is tedit) then
            Tedit(Components[i]).Destroy;
    end;
end;

procedure TForm2.btn2Click(Sender: TObject);
begin
    criarEdits;
end;

procedure TForm2.criarEdits;
var
  i : Integer;
  arrayEdit : array[1..15] of TEdit;
begin
  for i := 1 to 15 do
  begin
    ArrayEdit[i] := TEdit.Create(Self);
    ArrayEdit[i].Parent:= Self;
    ArrayEdit[i].Left := 100 + i * 50;
    ArrayEdit[i].Top := 124;
    ArrayEdit[i].Width := 41;
    ArrayEdit[i].Height :=24;
    ArrayEdit[i].Name := 'edit'+ inttostr(i+20);
  end;
end;

end.

Destruir Tedits em tempo de execução