text:
Q: Регистрация на сайте с помощью ASP.NET MVC C# Делаю регистрацию на сайте в учебных целях. Хочу запретить создавать пользователей с одинаковым логином. Проверку на одинаковый логин делаю в реализации интерфейса. Вот код:
public void Add_New_User(User user)
{
    User olduser = context.Users.FirstOrDefault(c=>c.LoginUser == user.LoginUser);
    if (olduser == null)
    {
        context.Users.Add(user);
    }
    else
    {
         throw new Exception();
    }
    context.SaveChanges();
}

То есть если пользователя с таким логином нет, то я регистрирую его. Если же пользователь с таким логином есть, то выпихиваю ошибку(И вот эту ошибку я хочу изменить на что то более красивое. Например: на сообщение "Пользователь с таким логином уже есть").

A: Посидел. Подумал. И решил, что лучше перенести логику проверки в контроллер:
[HttpPost]
        public ActionResult Registr(User user, HttpPostedFileBase image)
        {
            if (image != null)
            {
                user.IconUserType = image.ContentType;
                user.IconUserData = new byte[image.ContentLength];
                image.InputStream.Read(user.IconUserData, 0, image.ContentLength);
            }

            User olduser = repository.Users.FirstOrDefault(u => u.LoginUser == user.LoginUser);

            if (olduser != null)
            {
                ModelState.AddModelError("", "Такой пользователь уже есть");
            }

            if (user.Password == Request.Form["Повторите пароль"] && ModelState.IsValid)
            {
                TempData["Message"] = "Регистрация прошла успешно! Можете логиниться";
                repository.Add_New_User(user);
                return Redirect("/Account/Login"); //С помошью такого перевода мы избегам ошибки, когда при перегрузке браузера мы два раза отправляем одни и теже данные
            }
            else if(user.Password != Request.Form["Повторите пароль"])
            {
                ModelState.AddModelError("", "Пароли не совпадают");
            }

           return View("Registr");
        }

Можно ли как то это все упростить, а то мне кажется, что данный контроллер получился уж слишком большим...

A: Почему делаете в методе, а не в ActionResult ?
Можно использовать remote Validation - http://www.c-sharpcorner.com/UploadFile/d87001/remote-validation-in-mvc/

A: Public Class RegisterViewModel

    <Required(ErrorMessage:="Не указан логин")>
    <Display(Name:="Логин")>
    <RegularExpression("[A-z0-9_]{5,15}", ErrorMessage:="Допустимые символы - латиница, нижнее подчеркивание, цифры (5-15 символов)")>
    Public Property Login As String ' имя пользователя (логин) проверка на уникальность
End Class

проверка
If olduser IsNot Nothing Then
ModelState.AddModelError("", "Пользователь с таким логином уже существует")
End If


text:
Q: Controlling a Parse with Arbitrary Predicates Not Working in Bison In section 1.5.4 Controlling a Parse with Arbitrary Predicates:
The bison manual specifies that you can make a parse fail up front for an option in a rule by checking the return of the predicate between the brackets in this format:
parent_rule: %?{ test_predicate_flag } child_rule_1 |
             %?{ !test_predicate_flag } child_rule_2;

The problem is that I get this syntax error with the above format in my grammar file:
error: invalid directive: '%?{'

I added the %glr-parser flag before the first %% as stated in the manual.  Is there something I'm missing?
update: attempted this with bison version 3.0 prior to posting and didn't work.  Not much information online about people's experience with this "experimental feature" as the doc says.  Can anyone confirm or deny that it works for them?
update #2: After following the solution that rici posted, the resulting .c file has issues.
It seems that in attempt to aid compile debug, bison outputs #line directives of the following format:
#line <line_no> <grammar_file_prefix>.tab.c

In the case of the arbitrary predicate generation, the above predicate option for the rule ends up in the parser file's main switch block as this:
if (! (#line <line_no> <grammar_file_prefix>.tab.c

This will of course not compile, and I'm guessing is intended to be output on the line before the start of the case statement like I see in the rest of the rule match options.  Perhaps another bit of information to add to the bug report once it's filed?  For now, I can search and replace these out to move forward.

A: The semantic predicates feature was added in bison 3.0, released at the end of July, 2013; at this writing, it's not yet bundled into most OS distributions so you need to install from source to even try it. However, I took a quick glance at the bison source code (as of October 10, 2013, and found what looks like a bug in the scanner specification, at line 269 of scan.gram.l
The pattern in that line will match %{nonletter}[[::graph:]]+ (where nonletter is anything other than an alnum, % or {), which will certainly match %?{
However, it will not match %? {. I tried the example from the manual, and indeed:
widget:
       %?{  new_syntax } "widget" id new_args  { $$ = f($3, $4); }
     | %?{ !new_syntax } "widget" id old_args  { $$ = f($3, $4); }
     ;

produces the error you see, while
widget:
       %?  {  new_syntax } "widget" id new_args  { $$ = f($3, $4); }
     | %?  { !new_syntax } "widget" id old_args  { $$ = f($3, $4); }
     ;

does not.
I believe the fix would be to add ? to the characters not matched by {notletter}. At least, I tried that, and afterwards both of the above snippets "worked" (at least to the extent that bison generated a .c file.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: const float & x = something; // considered harmful? There was some code like this:
// Convenience to make things more legible in the following code
const float & x = some.buried.variable.elsewhere;

// Go on to use x in calculations...

I have been told that the "const float &" is "bad" and should just be a plain float or const float.
I, however, could not think of a compelling reason other than "you don't have to type '&'".
In fact, it seems to me that in some cases the original could be better, since compiler might not allocate extra stack space to the variable.
In other words, originally I could validly say:
assert(&x == &some.buried.variable.elsewhere)

Whereas in the second case I cannot.
Also, the original seems to communicate intent better, in my view, since the whole point of a reference is to make an alias to another value.
Can anyone give me examples of where the "const float &" version is worse than a plain "float" or "const float" in some tangible way?

A: I can't think of a reason why const float & would be better than const float.
References make sense if you're either worried about copies being made (which is irrelevant with a primitive type like float) or you want to be able to update a value across all instances that share the reference (which is irrelevant with const members).
On top of that, references in members are a huge pain in the neck* when it comes to initialization, and so they'd have to offer a significant advantage of the alternatives in order to be useful, and it's clearly not the case with const float.

* The FQA on references is always amusing and thought provoking

A: You should only use references in the following cases: (If I didn't forgot one)

*

*The type being referred is not small and causes performance problems.

*You want your local alias to update when the value being referred to is updated.
Or: You don't want to make a copy.

*You want the ability to update the other value. (In case it is not constant)

So in this case the float is small enough, you probably don't want it to update when the value being referenced to updates (causing problems in your calculations) and since you are using constants you don't want it to update.
So, you would want:
const float x = some.buried.variable.elsewhere;

A: The address of a float may be bigger than the float itself (e.g., on 64 bits PCs).
Also it's faster to computing something with a float directly than with the address of a float (you don't have to dereference it), but maybe compilers can optimize that.

A: There is no reason why that reference would be wrong or bad. If what you want is a local short-cut name ("alias"), references are the way to go. If you copy the float into a new variable, then you will get a new object and as you pointed out, of course you will also get a new address: Not at all what you would have wanted. So take a reference for that:
float &x = some.buried.variable.elsewhere;

Which will behave as the original variable in expressions.
However, as with everything, hard-coded rules won't do it. It depends on the specific situation. If you don't care about the object, but rather about the object's value, then create a copy. It's better to use the float directly than have that possible indirection through a reference when all you are interested in is to get easy access to the value of something.
What is bad is to use a reference when storing the result of a computation - because what is clearly of interest is the value only. You couldn't have any interest in a temporary float identity anyway, because it doesn't exist in the first place: A temporary float is not an object. It isn't even required to have any address (which can happen if the compiler keeps the float in a register):
float const &x = 3.0; // non-sense. don't use reference here

Same with the result of a function call of course
float const &x = get_some_float(); // non-sense too.

A: You do not need to worry so much about stack use, especially for a single float.
If you declare a variable on the stack, nothing says that the compiler has to actually create space for it unless you take its address.  Even then, if the compiler can show that the variable's address isn't used, or if the compiler can see all the uses of that address (if the function calls that get passed the address are all visible) then it still doesn't have to actually create space for the variable.
One case I can see for using the reference instead of a copy is if the value is changed through the other name, perhaps in a function call, then the reference value will change also.  With a copy it wouldn't.

A: You mentioned that you thought the compiler might avoid allocating stack space for the reference.  This may be true if you have optimization enabled, but the compiler could also optimize "const float x" by keeping the value in a FP register instead of on the stack.  This is what GCC does on x86, for example.

A: Short answer: this code is correct, keep it this way!
Long answer:
The problem with storing the return value of a function in a reference is that you are not allocating the space to actually store the return value, so you often end up with a reference pointing to a temporary value, either the temporary return value of the function (automatically created by the compiler) or a local variable allocated during the function (and freed at its end).
This is true that you must not return a reference on a local variable because this variable will be freed when the function ends.
But the C++ standard states that the compiler must not free the temporary return value of a function if it is "const referenced". So if your function is returning a float by value, you can store this value in float reference, the compiler ensures that the actual temporary value returned by the function will not be freed until you are done with your reference.
Note that this behaviour is only valid for "const" references only.
Take a look at this Herb Sutter's article for more explanation.

A: Rewritten for clarity:
References are pointers in disguise with some added syntactic sugar.  Pointers have any number of performance and efficiency problems.  Aliasing is one notable example.  The compiler can't guarantee that the memory underneath the pointer or reference is the same as the last time it read it, because any old pointer can go through and modify it.  The compiler is forced to re-read the value from memory on every use rather than caching it in memory.
On most processors registers are fast, memory accesses are not.  So we never want to access memory if we can avoid it.  Primitive types (int, float, etc) often go into registers.  The compiler has complete control over what data resides in each register and can guarantee that nothing will overwrite the value, so variables of primitive types can potentially stay in registers for a long time until the compiler needs to write any changes back out to memory.
So when dealing with primitive types, it's often less efficient to use a reference.  It disallows the compiler from caching the value in a register, inserts hidden dereferences, and can open you up to performance issues arising from aliasing.
Perhaps the efficiency isn't important to you in this case, but you said you couldn't think of a good reason not to use the reference other than saving typing.  I submit there is a very good reason.
Best practice with this in mind, in my opinion, would be to use references primarily for aggregate types.  The compiler can't pass these around in a single register so the relative cost of using the reference is going to be heavily mitigated.  If the type in question is a primitive type, I would always prefer to work with a copy of the value rather than a reference.

A: Whenever you are dealing with a reference you are taking a risk, which is probably why you were told to avoid this.
It is not clear what you mean by "buried variable". If you mean a member of an object (or even accessible through a sequence), there is a greater risk in that since the object could be deleted, leaving you with an invalid reference. Since you cannot aim a reference later at something else, there's no way for you to indicate that it is invalid, so a pointer might be better.
There is no problem with the const.
Can you explain what it is that you are trying to do or give more context?

A: Something to keep in mind: a reference-to-const doesn't necessarily mean the thing you're referencing won't change at some point.  It just means you will not change the referred-to data through that reference.
So someone could theoretically change the value of some.buried.variable.elsewhere and then reading x would reflect that updated value.  (Subject to the usual aliasing rules, etc, etc.  Essentially, it would be updated the next time the value of x was read.)
(Feel free to comment if I'm getting anything wrong, here, I'll update or delete the answer.)


text:
Q: Tensor notation of a triple scalar product
I want to write the tensor notation for $$[a\dot\ (b\times c)]a=(a\times b)\times (a\times c).$$

What I got so far is:
$$a \dot\ (b\times c)=a_i(\epsilon_{ijk}b_jc_k)=\epsilon_{ijk}a_ib_jc_k.$$ Now If I let, $F=a\times b=F_i\hat{e}_i$ and $E=a\times c=E_i\hat{e}_i.$ Then, $$F_i=\epsilon_{ijk}a_jb_k$$ $$E_i=\epsilon_{ilm}a_lc_m$$ $$\left[\epsilon_{ijk}a_ib_jc_k\right]a=\left(\epsilon_{ijk}a_jb_k\right)\times \left(\epsilon_{ilm}a_lc_m\right).$$
But I am stuck now because I do not know how to write the tensor notation of a cross product of a cross product. I know I must use the identity $$\epsilon_{ijk}\epsilon_{k\ell m} = \delta_{i\ell}\delta_{jm}-\delta_{im}\delta_{j\ell}$$ but I do not know how to apply it.

A: You can use the following definition of the cross product
$$
a \times b = \epsilon_{ijk} a_j b_k \hat{e}_i
$$
So your second cross product $(a \times b) \times (a \times c) = $ is
$$
\epsilon_{ijk} a_j b_k \hat{e}_i \times \epsilon_{lmn} a_m c_n \hat{e}_l \\
= \epsilon_{rst} (\epsilon_{ijk} a_j b_k \hat{e}_i \cdot \hat{e}_s)(\epsilon_{lmn} a_m c_n \hat{e}_l \cdot \hat{e}_t) \hat{e}_r
$$
The second step merely expresses the fact that the cross-product formula requires the s-th component of the first vector and the t-th component of the second.
Now use $\hat{e}_i \cdot \hat{e}_s = \delta_{is}$ etc
$$
(a \times b) \times (a \times c) = \\
\epsilon_{rst} (\epsilon_{ijk} a_j b_k \delta_{is})(\epsilon_{lmn} a_m c_n \delta_{lt}) \hat{e}_r \\
= \epsilon_{rst} \epsilon_{sjk} \epsilon_{tmn} a_j b_k a_m c_n \hat{e}_r
$$
Now use the $\epsilon-\delta$ identity $\epsilon_{trs}\epsilon_{tmn} = \delta_{rm}\delta_{sn} - \delta_{rn}\delta_{sm}$ and simplify this further. You have
$$
(a \times b) \times (a \times c) = \\
\epsilon_{sjk}\delta_{rm}\delta_{sn}a_j b_k a_m c_n \hat{e}_r - \epsilon_{sjk}\delta_{rn}\delta_{sm}a_j b_k a_m c_n \hat{e}_r \\
=\epsilon_{sjk}a_j b_k a_r c_s \hat{e}_r - \epsilon_{sjk}a_j b_k a_s c_r \hat{e}_r \\
$$
Since $\epsilon_{sjk} c_s a_j b_k = c \cdot (a \times b)$, and $\epsilon_{sjk} a_j b_k a_s = 0$, your final expression for $(a \times b) \times (a \times c) = $ is
$(c \cdot (a \times b)) a_r \hat{e}_r$ = $(c \cdot (a \times b)) a$.


text:
Q: Only animate only one transform property I have a css after selector that I'm trying to just animate the X position but not sure how to stop all the other transform functions from happening also. Whats the transition-property I need for translateX ?
.myLink {
    &:hover .myText:after {
      transition: transform 0.6s;
      transform: translateX(3px);
    }
  .myText {
    display: flex;
    flex-wrap: wrap;
    &:after {
      content: "";
      display: block;
      width: 1px;
      height: 1px;
      border-top: 2px solid $blue;
      border-right: 2px solid $blue;
      -moz-transform: rotate(45deg);
      -webkit-transform: rotate(45deg);
      transform: rotate(45deg);
    }
  }
}


text:
Q: combine several align-environments I want to combine several align-environments but reset the alignment at some point.
Esp., I want to combine these:
\begin{align*}
& \lim(\emptyset) = \ext(\emptyset), \lim(\Sigma^* a_1 \Sigma^* a_2 \dotsb a_n \Sigma^*) = \ext(\Sigma^* a_1 \Sigma^* a_2 \dotsb a_n \Sigma^*) \text{(see above)}
\end{align*}
\begin{align*}
& \lim( \neg ( \Sigma^* a_1 \Sigma^* a_2 \dotsb a_n \Sigma^* ) ) & = & \{ \alpha \in \Sigma^\omega | \exists^\omega n : \alpha [0,n] \notin \Sigma^* a_1 \Sigma^* a_2 \dotsb a_n \Sigma^* \} \\
& & = & \{ \alpha \in \Sigma^\omega | \forall n: \alpha [0,n] \notin \Sigma^* a_1 \Sigma^* a_2 \dotsb a_n \Sigma^* \} \\
& & = & \neg \ext( \Sigma^* a_1 \Sigma^* a_2 \dotsb a_n \Sigma^* )
\end{align*}

But the should not share a common alignment. (Edit: Actually, they should share the same outermost left alignment but nothing more.)
I want to combine them because it otherwise adds an empty line/space between them but I don't want that. Or is there any other way I can avoid that?

A: You can use the aligned environment inside align*. Note that I added a \  before \lim and before \text so that you get a space there. (This gives an overfull \hbox, but that's another thing.)
\documentclass{article}
\usepackage{amsmath}
\DeclareMathOperator\ext{ext}
\begin{document}
\begin{align*}
& \lim(\emptyset) = \ext(\emptyset),       \lim(\Sigma^* a_1 \Sigma^* a_2 \dotsb a_n \Sigma^*)
  = \ext(\Sigma^* a_1 \Sigma^* a_2 \dotsb a_n \Sigma^*)\ \text{(see above)}, \\
& \begin{aligned}
  \lim( \neg ( \Sigma^* a_1 \Sigma^* a_2 \dotsb a_n \Sigma^* ) )
   &= \{ \alpha \in \Sigma^\omega | \exists^\omega n : \alpha [0,n] \notin \Sigma^* a_1 \Sigma^* a_2 \dotsb a_n \Sigma^* \} \\
   &= \{ \alpha \in \Sigma^\omega | \forall n: \alpha [0,n] \notin \Sigma^* a_1 \Sigma^* a_2 \dotsb a_n \Sigma^* \} \\
   &= \neg \ext( \Sigma^* a_1 \Sigma^* a_2 \dotsb a_n \Sigma^* )
  \end{aligned}
\end{align*}
\end{document}


text:
Q: How to pass options like `only_path: true` and `anchor:` to `url_for` when generating a route from an array or object (instead of from a hash) I'm trying to change a function — which currently only accepts a URL (path) string — to make it more flexible, so that it will also accept as input the same arguments that you can pass to url_for. The problem is, url_for returns a full URL including protocol/host, and I only want the path portion...
url_for has a lovely only_path: true option that makes it skip adding the protocol/host. This works great as long as you're passing it as part of a single hash to url_for:
main > app.url_for(controller: 'users', action: 'index', only_path: true)
=> "/users"

But how do you pass options when you are passing an array or a model object to url_for?
main > app.url_for(user, only_path: true)
ArgumentError: wrong number of arguments (given 2, expected 0..1)
from /gems/actionpack-5.1.6/lib/action_dispatch/routing/url_for.rb:166:in `url_for'

main > app.url_for([user, :notification_preferences], only_path: true)
ArgumentError: wrong number of arguments (given 2, expected 0..1)
/actionpack-5.1.6/lib/action_dispatch/routing/url_for.rb:166:in `url_for'

You can't! Clearly, it's not even syntactically possible to pass an options hash if you're passing anything other than a hash, since its arity is 0..1 and it only takes a single argument: url_for(options = nil).

So my question is, is there a Rails helper that takes the same options as url_for (including anchor:) but returns a path?
I suppose it wouldn't be too hard to add one, like this one, that uses URI.parse(path).path (probably what I'll do for now)... but that seems inefficient, inelegant, and inconsistent.
Inefficient and inelegant because it generates a string containing extra unwanted information and then has to parse it, convert it to a structured data structure, and then convert it back to a string without the unwanted information.
Inconsistent because:

*

*Rails includes a _path variant for every _url route helper. Why doesn't it have a built-in "path" variant of url_for (or does it and it's called something else?)?

*Other routing helpers that accept an object or array—such as polymorphic_path— let you pass in options too:
Example:
main > app.polymorphic_url [user, :notification_preferences], anchor: 'foo'
=> "http://example.com/users/4/notification_preferences#foo"

main > app.polymorphic_path [user, :notification_preferences], anchor: 'foo'
=> "/users/4/notification_preferences#foo"

main > app.polymorphic_path user, anchor: 'foo'
=> "/users/4#foo"

ActionDispatch::Routing::RouteSet actually has a path_for:
  # strategy for building urls to send to the client
  PATH    = ->(options) { ActionDispatch::Http::URL.path_for(options) }
  UNKNOWN = ->(options) { ActionDispatch::Http::URL.url_for(options) }

  def path_for(options, route_name = nil)
    url_for(options, route_name, PATH)
  end

  # The +options+ argument must be a hash whose keys are *symbols*.
  def url_for(options, route_name = nil, url_strategy = UNKNOWN)
    options = default_url_options.merge options
    ...

— just not ActionDispatch::Routing::UrlFor, apparently. Anyway, ActionDispatch::Routing::RouteSet#path_for is buried too deep in internals to be helpful to me; I need a helper that is callable from the controller/view.
So, what is a good solution for this that is elegant, consistent with other Rails routing helpers, and relatively efficient (no URI.parse)?

Better yet, is there any reason the method signature of the built-in url_for couldn't simply be modified (in a future version of Rails, by submitting a pull request) to allow both a subject (model object, array, or hash) and any number of optional options to be passed in?
Probably the original url_for was written before Ruby had keyword arguments. But nowadays, it's pretty trivial to do exactly that: accept an "object" plus any number of optional keyword options:
def url_for(object = nil, **options)
  puts "object: #{object.inspect}"
  puts "options: #{options.inspect}"
end

main > url_for ['user', :notification_preferences], anchor: 'anchor'
object: ["user", :notification_preferences]
options: {:anchor=>"anchor"}
=> nil

main > url_for ['user', :notification_preferences], only_path: true
object: ["user", :notification_preferences]
options: {:only_path=>true}

Is there any reason we couldn't/shouldn't change url_for's method signature to url_for(object = nil, **options)?
How would you modify url_for/full_url_for such that it remained as backwards compatible as possible but also let you call it with an array + keyword options?

A: Here's one potential solution that shows kind of what I'm looking for:
  def url_for(object = nil, **options)
    full_url_for(object, **options)
  end

  def full_url_for(object = nil, **options)
    path_or_url_for = ->(*args) {
      if options[:only_path]
        _routes.path_for(*args)
      else
        _routes.url_for( *args)
      end
    }
    polymorphic_path_or_url = ->(*args) {
      if options[:only_path]
        polymorphic_path(*args)
      else
        polymorphic_url( *args)
      end
    }

    case object
    when nil, Hash, ActionController::Parameters
      route_name = options.delete :use_route
      merged_url_options = options.to_h.symbolize_keys.reverse_merge!(url_options)
      path_or_url_for.(merged_url_options, route_name)
    when String
      object
    when Symbol
      HelperMethodBuilder.url.handle_string_call self, object
    when Array
      components = object.dup
      polymorphic_path_or_url.(components, components.extract_options!)
    when Class
      HelperMethodBuilder.url.handle_class_call self, object
    else
      HelperMethodBuilder.url.handle_model_call self, object
    end
  end

(Compare to source of original Rails version)
I haven't tried running the Rails test suite against this code yet, so it very well may have missed something, but it seems to work for my simple tests so far:
main > app.url_for(controller: 'users', action: 'index')
=> "http://example.com/users"

main > app.url_for(controller: 'users', action: 'index', only_path: true)
=> "/users"

main > app.url_for [user, :notification_preferences]
=> "http://example.com/users/4/notification_preferences"

main > app.url_for [user, :notification_preferences], only_path: true
=> "/users/4/notification_preferences"

Let me know if you find any bugs in this or have any improvements or can think of a cleaner way to accomplish this.
Please do post any improved version you may have as an answer!


text:
Q: Product price changed to 0.00 in product detail page I am facing a very strange issue after the installation of Magento 2.0.4. I have create a product with the price $12 and change the locale from Magento configuration in backend.
Below is the screenshot for the listing page.

Also find the below screenshot for the detail page.

You might have noticed the difference between two screenshot. Yes, Product detail page shows $0.00 price while listing page has retain with the price what i have added.
Product details page automatically updates correct price to $0,00 after one or two seconds (JavaScript Updates).
Find the below code for it
$('[data-price-type="' + priceCode + '"]', this.element).html(priceTemplate({data: price}));

I have debug further in the code and found another JavaScript code that passes parameter to Magento 2 pricebox widget.
<script>
    require([
        'jquery',
        'Magento_Catalog/js/price-box'
    ], function($){
        var priceBoxes = $('[data-role=priceBox]');

        priceBoxes = priceBoxes.filter(function(index, elem){
            return !$(elem).find('.price-from').length;
        });

        priceBoxes.priceBox({'priceConfig': <?php /* @escapeNotVerified */ echo $block->getJsonConfig() ?>});
    });
</script>

Now I have checked the getJsonConfig() method,
  $product = $this->getProduct();

        if (!$this->hasOptions()) {
            $config = [
                'productId' => $product->getId(),
                'priceFormat' => $this->_localeFormat->getPriceFormat()
                ];
            return $this->_jsonEncoder->encode($config);
        }

        $tierPrices = [];
        $tierPricesList = $product->getPriceInfo()->getPrice('tier_price')->getTierPriceList();
        foreach ($tierPricesList as $tierPrice) {
            $tierPrices[] = $this->priceCurrency->convert($tierPrice['price']->getValue());
        }
        $config = [
            'productId' => $product->getId(),
            'priceFormat' => $this->_localeFormat->getPriceFormat(),
            'prices' => [
                'oldPrice' => [
                    'amount' => $this->priceCurrency->convert(
                        $product->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue()
                    ),
                    'adjustments' => []
                ],
                'basePrice' => [
                    'amount' => $this->priceCurrency->convert(
                        $product->getPriceInfo()->getPrice('final_price')->getAmount()->getBaseAmount()
                    ),
                    'adjustments' => []
                ],
                'finalPrice' => [
                    'amount' => $this->priceCurrency->convert(
                        $product->getPriceInfo()->getPrice('final_price')->getAmount()->getValue()
                    ),
                    'adjustments' => []
                ]
            ],
            'idSuffix' => '_clone',
            'tierPrices' => $tierPrices
        ];

I did lot of debugging through the code and come to the conclusion that they are using ICUDATA for locale support.
I am stuck with this all thing, It seems it is PriceFormat issue.


text:
Q: Order nested facet labels in facet_grid So, I am trying to make a grid of plots that are faceted by three different variables. I can generate the grid of plots just fine, the only hitch I am having is that the order in which the labels is placed seems out of order. Here is a simple example of what I am doing:
library(ggplot2)
data(mtcars)
qplot(mpg, wt, data=mtcars) + facet_grid(cyl +am ~ vs, labeller = label_both)

which produces the following plot:

Now, for the most part, the plot looks great, but for the labels on the right hand side, we see that cyl  is labeled "first" (i.e. close to the plot) and am is nested outside, but the way the plot is laid out, it is clear that the facets are displayed with am nested within cyl.
So, I would like to change the order that the labels are listed so that am levels are listed within cyl levels to reflect the layout. I have tried to search for things like "facet_grid order labels" or "nested facet label order ggplot2", but almost all of the results I found had to do with changing the order of the actual levels of a given facet, rather than the problem I have described. Additionally, I looked into tinkering with the labeller, but that function seems to be called after the placement of the labels has been decided.
Thanks for your help!

A: It seems that the ordering of the labels that you see is just the standard way how ggplot orders the labels. If you exchange the order of the variables in the formula, the labels also change position, but this at the same time also reorders the rows, which is probably not what you want:
qplot(mpg, wt, data=mtcars) +
    facet_grid(am + cyl ~ vs, labeller = label_both)

You can indeed use the labeller to fix this, as was suggested by alistaire. The following function calls label_both() with the columns of the label data frame in reversed order:
label_rev <- function(labels, multi_line = TRUE, sep = ": ") {
  label_both(rev(labels), multi_line = multi_line, sep = sep)
}

And it leads to the desired result:
qplot(mpg, wt, data=mtcars) +
    facet_grid(cyl + am ~ vs, labeller = label_rev)


text:
Q: Chose how many times the bot rolls (Discord.js) Right now I'm working on a random number generator to be like a virtual dice roller. I have users input a number and the bot randomly chooses a number between 1 and whatever the user inputs. I've been trying to add in a way for users to first say how many times they want it to roll. I'm very confused about how to go about doing this with the code I have already.
A quick run down:
I want the bot to ask after the user sends the max number to roll I want the bot to ask how many times they want to roll it.
code:
const Discord = require('discord.js');

const client = new Discord.Client();

function getRandomInt(max){
    return Math.floor(Math.random() * Math.floor(max));
}

const prefix = 'roll';

client.once('ready', () => {
    console.log('your bot name is online!');
    client.user.setActivity("Type 'Role Help'", {type: 3});
});

client.on('message', message =>{
    if(!message.content.toLowerCase().startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/g);
    const command = args.shift().toLowerCase();

    if(command === ''){
       message.channel.send("What's the **Max** role number you want?");
       message.channel.awaitMessages(m => m.author.id == message.author.id,
        {max: 1, time: 10000}).then(collected => {
            console.log('collected :' + collected.first().content);
            if (isNaN(collected.first().content)){
                return message.channel.send("Please provide a valid number!")};

            var n = (getRandomInt(collected.first().content));
            message.channel.send("You Rolled a " + (n + 1));
            }).catch(() => {
                message.channel.send("*Roll has been cancelled.*");

            })} else if(command === 'Help' || 'help' || 'h' || 'H'){

                message.channel.send("**How to use Roll Bot**");
                message.channel.send("*1. Type Roll to begin*");
                message.channel.send("*2. Input a number or type stop to end the roll.*");
                message.channel.send("**Have Fun!**");
        }
});

client.login(process.env.token);


text:
Q: Dragging a file from a TreeNode to the desktop or Windows Explorer? I am attempting to drag a file represented by a TreeView node onto the desktop, Windows Explorer, or any other applications that allow files to be dropped onto them.  I've written the code below based on various Internet examples I've found and I'm running it as administrator.  It does allow me to drag as long as I remain in the TreeView control that contains the nodes, displaying the Copy icon with the cursor as it moves.  However, when I drag it off the control to the desktop or Windows Explorer for example, the icon turns into the red circle with a slash across it and nothing gets dropped.  I've ensured that the dragged file actually does exist.
private void treeView_Files_ItemDrag(object sender, ItemDragEventArgs e)
{
    DoDragDrop(e.Item, DragDropEffects.Copy);
}

private void treeView_Files_DragDrop(object sender, DragEventArgs e)
{
    TreeNode NewNode;

    if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
    {
        Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
        TreeNode DestinationNode = ((TreeView)sender).GetNodeAt(pt);
        NewNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
        string[] files = new string[] { "C:\\temp\\TestFile.pdf" };
        DataObject dataObject = new DataObject(DataFormats.FileDrop, files);
        DoDragDrop(dataObject, DragDropEffects.Copy);
    }
}

A: I was unable to figure out why my original code above would not display the Copy icon on the cursor unless it was within the TreeView control itself and, hence, would not let me drop the desired file.   However, I was able to come up with a solution that does display the icon and will drop on any application capable of accepting a dropped file.  I simply abandoned the use of the ItemDrag and DragDrop events entirely and used the MouseDown event instead as shown below.  As in my original code I'm using a test file instead of the file represented by the node, but extracting the real file path from the node is trivial.  Of course some additional simple code is necessary to determine if the coordinates are actually on a node:
private void treeView_Files_MouseDown(object sender, MouseEventArgs e)
{
    TreeNode node = treeView_Files.GetNodeAt(e.X, e.Y);
    string[] files = new string[] { "C:\\temp\\TestFile.pdf" };
    DataObject dataObject = new DataObject(DataFormats.FileDrop, files);
    DoDragDrop(dataObject, DragDropEffects.Copy);
}

A: Try constructing the DataObject and performing the DoDragDrop() operation inside the ItemDrag function, instead of the DragDrop function:
private void treeView_Files_ItemDrag(object sender, ItemDragEventArgs e)
{
    string[] files = new string[] { "C:\\temp\\TestFile.pdf"};
    DataObject dataObject = new DataObject(DataFormats.FileDrop, files);
    DoDragDrop(dataObject, DragDropEffects.Copy);
}

The e.Item parameter (which is the TreeView item) is not really the object that you want to pass to Explorer, so you shouldn't be putting it into the DoDragDrop call.
On a side note, I spent a long time researching how it's possible to get the "destination" folder onto which the item was dropped. My solution involves roughly the following:

*

*Create a FileSystemWatcher and make it send events when new files are created.

*Give it a Filter that matches the file name that you're dropping.

*When the file is dropped (i.e. when it's created in the destination folder), you'll receive an event via the watcher.

Something like this:
private void CreateWatcher()
{
    var watcher = new FileSystemWatcher();
    watcher.Filter = "TestFile.pdf";
    watcher.NotifyFilter = NotifyFilters.FileName;
    watcher.Created += new FileSystemEventHandler(OnWatcherFileCreated);
    watcher.IncludeSubdirectories = true;
    watcher.Path = "C:\\";
    watcher.EnableRaisingEvents = true;
}

private void OnWatcherFileCreated(object sender, FileSystemEventArgs e)
{
    // Note: this happens in a separate non-UI thread.
    Console.WriteLine("Dropped onto: " + e.FullPath);
}


text:
Q: Error: It isn't possible to write into a document from an asynchronously-loaded external script Im trying to load ads on a rails 4 site and keep getting the following error
onejs?MarketPlace=US&adInstanceId=xxxxxxxx&storeId=xxxxxxx:1 Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

If I refresh the page the ad loads just fine. Here is the ad code from amazon which is places in a show.html.erb file.

If I use the amazon ads with Iframe code there is no issue but this format ad doesn't have an iframe option (It's the Native Ads - scans page for relevant content to display ads)
Its a rails 4 site with turbolinks enabled on heroku. I'm at a total loss as to how to fix it. This is also happening with adwords and media.net ad.
Any idea how to solve?

A: This library might solve your problem https://github.com/krux/postscribe

Asynchronously write javascript, even with document.write.

Advertisement


text:
Q: How do i make a function that returns amount of indexes that are the same I'm trying to make a number based Mastermind game. Trying to figure out a function that takes two lists as paramenters and if indexes in the lists are the same it should return the amount of indexes that are the same.
PS. hope you understand what i mean ;P
generated_number_as_list = [1,1,1,1]
guess_as_list = [1,2,1,2]

correct = right_inrightplace(guess_as_list, generated_number_as_list)

print(correct)

output >> 2

A: You can use zip to compare values with corresponding indexes and then sum True which will be cast to 1
print(sum(x==y for x,y in zip(generated_number_as_list, guess_as_list))) #2

A: I wrote it outside of a function. Just copy the for loop in your function and return the ans value as the output.
generated_number_as_list = [1,1,1,1]
guess_as_list = [1,2,1,2]

ans = 0

for i in range(len(generated_number_as_list)):
    if guess_as_list[i] == generated_number_as_list[i]:
        ans = ans + 1

print(ans)

A: You can try this also:
a=[1,1,1,1]
b=[1,2,1,2]
print(min(len([x for x in a if x in b]),len([x for x in b if x in a])))

A: You can use the sum and map with operator.eq:
def right_inrightplace(a, b):
    return sum(map(eq, a, b))

Or without using additional libraries:
def right_inrightplace(a, b):
    return sum(x == y for x, y in zip(a, b))

A: Just for fun here's a solution using recursion:
def right_inrightplace(a, b):
    if len(a) == 0 or len(b) == 0:
        return 0

    current = 0
    if a[0] == b[0]:
        current = 1
    return current+right_inrightplace(a[1:],b[1:])


text:
Q: How do I change State to a Country in Tableau? Tableau seems to think that Scotland is a State rather than a country. I'm trying to highlight the country Scotland as well as other countries but I can't. It does recognize Scotland at a State/Province level. Is there any way I can change the settings so I can show it as a country?
Thank you,
Michael

A: It's only possible to set an entire field Geographic Role. Meaning, if in your data the "Scotland" entry is in a field (let's call it "Location") where you have typically states or provinces, you won't be able to tell Tableau that "Scotland" is a Country and other entries are States/Provinces.
Only thing you can do is tell Tableau that "Location" hold Country information. For that, right click on the field, go for Geographic Role, and select Country/Region.

A: I also faced this problem, because tableau not recognizing Uk countries
(England, Scotland, Wales, NORTHERN IRELAND).
But I have done this one by small tricky process here are the details what I have done.

*

*Create a filled map using the Country field and the desired measure.

*Right-click on the country field and duplicate the field. The new field is called "Country (Copy)" in the attached workbook.

*Right click on Country (Copy), go to Geographic Role and select "State/Province". We now have 2 copies of the country field, however, Tableau is reading one as country data and one as a province data.

*Step one will have brought Longitude to Columns and Latitude to Rows, for the next step drag a second copy of latitude to rows, right-click on it and select "Dual Axis". The map should not have changed since step 3.

*Now click on the 2nd instance of Latitude in the Marks card and remove Country.

*Drag Country (Copy) to detail on the Marks card.

*There will be an "Unknown" box in the bottom right corner of the map, click on this, change the Country/Region to United Kingdom and then click OK. All countries should be plotted correctly.

A: Another way is you can change the default type of dimension and set is as country as whole. and then if the problem still persist you can edit the location after the map is plotted. HTH


text:
Q: Bootstrap modal closes when focus on textarea I am using bootstrap modal. The problem is when I try to focus on the textarea the modal disappears.
Here is my code:

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

Secret #<?php echo $counter; ?>

                    <form method="post" action="">

                            <textarea id="comment" name="comment" class="form-control" rows="2"></textarea>

                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button name="comment" type="submit" class="btn btn-primary">Comment</button>

                    </form>

A: So , I have solved this by preventing triggering events for the comment box :
    $( ".modal form #comment" ).click(function( event ) {
      event.stopPropagation();

    });

A: I put my model on top of everything, solved for me.

   <form>


text:
Q: Portable Frontend Data input interface for SQL Server Database I have a SQL Server Database, I want a front-end graphical user interface for data input, which can be either web or desktop. But it has to be portable I mean it should be used without additional installation of any program. That front-end interface will be used by many users for input data into Database. Can you please help and suggest me?

A: Please see the link to the similar question. I find it quite helpful.
Which tool to build a simple web front-end to my database
and this
http://community.spiceworks.com/topic/195850-does-anyone-have-a-quick-and-dirty-way-to-access-ms-sql-data-from-a-web-app
and if you have some free time also this
http://www.academia.edu/4948292/Design_and_Implementation_of_Graphical_User_Interface_for_Relational_Database_Management_System
and potentially this
https://ask.sqlservercentral.com/questions/89751/is-there-a-front-end-application-development-tool.html
I hope it helps (at least a bit!)

A: Not sure if anyone is still looking for this, but https://beekeeperstudio.io is an open source database gui with a portable build.
Windows has a portable exe
Linux has appimage


text:
Q: Min and Max from same subquery If a query having a subselect for the highest money payed and the lowest money payed in example:
SELECT p.firstname,
       p.lastname,
       (SELECT MAX(pmt.amount)
          FROM Payment pmt
         WHERE pmt.person.id = p.id)  maxAmount,
       (SELECT MIN(pmt.amount)
          FROM Payment pmt
         WHERE pmt.person.id = p.id)  minAmount,
  FROM Person p

We need to write two subqueries. This have a bad performance on huge databases.
Any solutions in plain JPQL?

A: If you have a huge database this problem probably should be addressed by tweaking the schema design. Most RDBMS would have to do a full table scan on Payment table to find both minimum and maximum  amount value. You can check this by looking at EXPLAIN output for your current query.
Since you are concerned with the query speed you can denormalize the schema and store the maxAmount and minAmount columns in Person table or create a new PersonMinMaxPayment table. You can then update these when new row is inserted into Payment table e.g. by declaring @PrePersist or creating a trigger.
There are also few more possibilities if your system can be eventually consistent. You can recalculate these values with a delay e.g. as a once a day batch job.

A: I used this:
   SELECT p.firstname,
          p.lastname,
          MAX(pmt.amount),
          MIN(pmt.amount)
     FROM Person p
LEFT JOIN p.payments pmt
    GROUP BY p.firstname, p.lastname


text:
Q: Do I need to use a horizontal layout (android studio 1.5.1)? I am new in the Android world and I have a little problem with the screen in horizontal position. My android studio version is 1.5.1.
I have already completed the vertical layout, but I have issues when I turn the mobile in horizontal position; all the images, buttons get moving and the VideoView disappears.
This how my layout looks like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical"
tools:context="com.example.ubuntunyx.apptest3.MainActivity"
android:background="#a987b7"
android:weightSum="1">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#4c335a"
app:popupTheme="@style/AppTheme.PopupOverlay" />

<RelativeLayout
android:id="@+id/LytRelVideoResize"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_weight="0.94">

<Button
android:id="@+id/btnResize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btnResize"
android:layout_gravity="left"
android:onClick="btnResize_click"
android:background="@drawable/btn_redondo"
android:layout_marginBottom="39dp"
android:textColor="#ffffff"
android:layout_alignBottom="@+id/imgResize"
android:layout_toLeftOf="@+id/imgResize"
android:layout_toStartOf="@+id/imgResize"
android:layout_marginRight="41dp"
android:layout_marginEnd="41dp" />

<ImageView
android:id="@+id/imgResize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ocaso"
android:layout_below="@+id/barResize"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="49dp"
android:layout_marginEnd="49dp" />

<VideoView
android:id="@+id/videoPiramides"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_below="@+id/imgResize"
android:layout_marginTop="41dp"
android:layout_alignRight="@+id/barResize"
android:layout_alignEnd="@+id/barResize"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/btnResize"
android:layout_alignStart="@+id/btnResize" />
</RelativeLayout>

<ImageView
android:id="@+id/imgDragDrop"
android:layout_width="118dp"
android:layout_height="100dp"
android:src="@drawable/buho"
android:layout_marginLeft="43dp"
android:layout_marginStart="43dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:id="@+id/btnExit"
style="?android:attr/buttonStyleSmall"
android:layout_width="81dp"
android:layout_height="wrap_content"
android:text="@string/btnExit"
android:onClick="btnExit_click"
android:textColor="#ffffff"
android:background="#124a68"
android:layout_gravity="right"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</LinearLayout>

I was looking at: http://developer.android.com/intl/es/training/basics/supporting-devices/screens.html but it just get me more confused.

A: you just need  to build another layout landscape
just follow the picture below:

and then you design that new layout as you wish.
OR
if you dont need that landscape (forcing the APP to set in one orientation only)
AndroidManifest.xml

and add this one of these code to the application tag
android:screenOrientation="portrait"
android:screenOrientation="landscape"

A: The best solution for this problem is to create design for landscape mode. You should make new folder called 'layout-land' in your res folder. In new folder create new layout file with the same name but with design for landscape mode. Android os will know when to use landscape and when to use portrait mode.

A: You have a couple of options here:
1. Rearrange the layout child views so that they look fine both in landscape and portrait mode. This will need trial and error and is not always possible.
2. Make your activity stick to a particular layout, regardless of changes in the device orientation. This can be done in you apps manifest file as:
<activity android:name=".MyActivity"
            android:screenOrientation="portrait"
            android:configChanges="orientation|keyboardHidden"/>

3.The best way: Create separate layout files for landscape and portrait orientations. In android studio it is easy. Suppose you have an activity named MyActivity, then the layout files will be something like: my_activity.xml (for normal, portrait mode) and my_activity_land.xml for landscape mode.


text:
Q: Why dropdownlist values not binding into database I'm using angular JS MVC here data is binding into dropdownlist but when I try to load the value into database but that data not binfing:

                                State

                                  <select class="form-control" data-modal="modal" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-model="CountryID" ng-change="StateList()" ng-required="true">
                                <option value="" disabled selected>--Select Country--</option>

angular code
$scope.AddUpdateEmployee = function (Emp) {
        alert("Enter in update")
        var Employee = {
            Id: $scope.EmployeeId,
            Name: $scope.EmployeeName,
            Email: $scope.EmployeeEmail,
            Psw: $scope.Password,
            Country: $scope.CountryID,

        };

mvc code
   public JsonResult AddEmployee( Employee emps)
        {
            if (emps != null)
            {
                Employee ee = new Employee();
                ee.Name = emps.Name;
                ee.Email = emps.Email;
                ee.Psw = emps.Psw;
                ee.Country = emps.Country;
                ee.State = emps.State;
                ee.City = emps.City;
            }

A: Please check below, its binding from the database.
http://jsfiddle.net/81t6cbjw/261/
  <select class="form-control" data-modal="modal"
           ng-options="I.CountryID as I.CountryName for I in CountryList"
           ng-model="CountryID" ng-change="StateList()" ng-required="true">
       <option value="" disabled selected>--Select Country--</option>
  </select>

A: Add a ng-if in select element, the problem element render before the data is coming, ng-if sets a watch on it
<select ng-if="CountryList && CountryList.length" class="form-control" data-modal="modal" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-model="CountryID" ng-change="StateList()" ng-required="true">
       <option value="" disabled selected>--Select Country--</option>
</select>


text:
Q: I have a Topic with 0 leader and 0 isr: UNKNOWN_TOPIC_OR_PARTITION I tried to create some messages in my Topic test_partitions_41 but I got this error:
[2019-02-07 14:53:17,484] WARN [Producer clientId=perfs-0e930f51-38a1-5baa-8fcf-f2b1033a73f0] Error while fetching metadata with correlation id 738756 : {test_partitions_41=UNKNOWN_TOPIC_OR_PARTITION} (org.apache.kafka.clients.NetworkClient)

when I checked the topic, I found that partitions have neither Leader nor isr:
Topic:test_partitions_41        PartitionCount:4        ReplicationFactor:4     Configs:
        Topic: test_partitions_41       Partition: 0    Leader: none    Replicas: 4,1,2,3       Isr:
        Topic: test_partitions_41       Partition: 1    Leader: none    Replicas: 1,2,3,4       Isr:
        Topic: test_partitions_41       Partition: 2    Leader: none    Replicas: 2,3,4,1       Isr:
        Topic: test_partitions_41       Partition: 3    Leader: none    Replicas: 3,4,1,2       Isr:

I ve been looking for the problem where it comes from, and I found that 2 brokers were down when I ve been sending messages to this Topic.
I found also that poste which talk about PartitionStateChange, they said that Topic in newpartition's state doesn't have either Leader nor isr.
How should I resolve this problem without removing topic?

A: I got it!!
The problem comes from broker controller, to resolve this problem I ressigned a new controller by zookeeper, this is the command I've runned in zookeeper:
su - kafka -c 'zookeeper-shell localhost:2181 rmr /controller'


text:
Q: Find the solutions of the equation $\frac{a^2(x-b)(x-c)}{(a-b)(a-c)}+\frac{b^2(x-a)(x-c)}{(b-a)(b-c)}+\frac{c^2(x-a)(x-b)}{(c-a)(c-b)}=3x-2$
Find the solutions of the equation $$\frac{a^2(x-b)(x-c)}{(a-b)(a-c)}+\frac{b^2(x-a)(x-c)}{(b-a)(b-c)}+\frac{c^2(x-a)(x-b)}{(c-a)(c-b)}=3x-2$$

If we consider the expression as an identity and substitute $x=a$ we get the value of $a=1,2$ similarly $b=1,2$ and $c=1,2$
If we substitute these values into the expression at least one of the denominator will be equal to $0$ which is not possible therefore this expression is not an identity. How to proceed further?

A: Assume $a,b,c$ are fixed distinct (all different) real number values. (Otherwise the left-hand side is undefined.)
Then the left-hand side is a quadratic function in $x$. Call this function $f(x)$.
We have $f(a) = a^2$, $f(b)=b^2$ and $f(c)=c^2$. Since a quadratic is determined by its values at three points, we must have $f(x)=x^2$. (This expression for $f(x)$ should be independent of the values of $a, b$, and $c$, provided, as noted above, that these values are all different.)
So the equation becomes $x^2=3x-2$, which you can now easily solve for $x$.

A: Add $-x^2$ on both sides , Let expression on LHS be $f(x)$
Therefore LHS will be a quadratic in $x$ will be become zero three times clearly as
$f(a)=f(b)=f(c)=0$ Now if a quadratic equation has more than three roots, then all complex numbers will be it's roots and therefore it will identically be equal to zero.
$f(x)\equiv 0$ and therefore since $f(x)=3x-2-x^2$
$3x-2-x^2\equiv 0$
which is possible for $x=1,2$ only


text:
Q: Bind to WPSetAsThumbnail is there a way to bind some extra script to the WPSetAsThumbnail function?  the function automatically inserts the image into the post's metabox, but what if i wanted to do something else with it?  could i make it alert('bacon') after the thumbnail is set via ajax?
i'm trying to get a way to set the thumbnails from the quick edit screen and while i can launch the media editor, and the "set as thumbnail" does work, i can't fade in the new image b/c i can't figure out how to latch onto the action and grab the HTML that is passed back.
as an aside, .ajaxComplete seems to fire when i click on the Remove featured image link, but not when i click on the Set as Featured image link.  is it b/c the later occurs in a thickbox that isn't part of the original DOM?
///* edit *///
i've tried replicating the html more exactly.  this has the problem of having multiple items with the same div ID... and still doesn't fade in the new image either.  the image is saved via ajax though and the new thumb appears on refresh.
the html markup in my post column:

'.get_the_post_thumbnail($post_id, array(35,35))

i'd still like some way to latch onto the jquery event so that i can do my own script, but i'm starting to believe this is impossible.   i liked the idea of using ajaxComplete but i can't get that to run based on an action that occurs in the media thickbox.

A: Yes, on your 2nd question :)
From what I saw in set-post-thumbnail.dev.js, it appears that you only need to add a link/anchor with the wp-post-thumbnail class on it in your quick edit screen.
And you will get the image faded inside that link when the ajax request completes.
For alerting "bacon" after the ajax completes, this might work:
$('a.wp-post-thumbnail').ajaxComplete(function() {
  alert('bacon');
});

The ajaxComplete approach:

jQuery(document).ready(function($){

  $('a.wp-post-thumbnail').ajaxComplete(function(event, XMLHttpRequest, ajaxOptions) {

    // the image should be here
    // use something like $(XMLHttpRequest.responseText).find('img')
    console.log(XMLHttpRequest.responseText);

  });

});

You might need to check which ajax request this is, do console.logs for all arguments and search of the property that holds the ajax action name, which should be "set_post_thumbnail" or something...

A: In the end I found that I could not bind or trigger this action.  I had to duplicate it as follows with the javascript and then an ajax callback.
Javascript:
function PrismSetAsThumbnail(id, nonce){
    var $link = jQuery('a#wp-post-thumbnail-' + id);

    $link.text( setPostThumbnailL10n.saving );
    jQuery.post(ajaxurl, {
        action:"prism_set_thumbnail", post_id: post_id, thumbnail_id: id, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie)
    }, function(str){
        var win = window.dialogArguments || opener || parent || top;
        $link.text( setPostThumbnailL10n.setThumbnail );
        if ( str == '0' ) {
            alert( setPostThumbnailL10n.error );
        } else {
            jQuery('a.wp-post-thumbnail').show();
            $link.text( setPostThumbnailL10n.done );
            $link.fadeOut( 2000 );

            //display new thumbnail in the columns w/o refresh
            jQuery('#post-'+win.post_id + ' .postimagediv a', win.parent.document).html(str).fadeIn();

            //if successful close thickbox
            win.parent.tb_remove();
        }
    }
    );
}

Ajax Callback:
  //add callback for custom version of set thumbnail
  add_action('wp_ajax_prism_set_thumbnail', 'kia_set_thumbnail_callback');

  // the function name must match the above passed name
  function kia_set_thumbnail_callback(){

    $post_ID = intval( $_POST['post_id'] );
    if ( !current_user_can( 'edit_post', $post_ID ) )
        die( '-1' );
    $thumbnail_id = intval( $_POST['thumbnail_id'] );

    check_ajax_referer( "set_post_thumbnail-$post_ID" );

    if ( $thumbnail_id == '-1' ) {
        if ( delete_post_thumbnail( $post_ID ) )
            die( _wp_post_thumbnail_html() );
        else
            die( '0' );
    }

    if ( set_post_thumbnail( $post_ID, $thumbnail_id ) )
        $msg = get_the_post_thumbnail( $post_ID, array(35,35));
        die($msg);
    die( '0' );
}

A: Answering to this:

[...] what if i wanted to do something else with it? could i make it alert('bacon') after the thumbnail is set via ajax?

add_action( 'wp_ajax_set-post-thumbnail', 'wpse_35588_ajax_set_post_thumbnail' , 0 );

function wpse_35588_ajax_set_post_thumbnail() {
    $post_ID = intval( $_POST['post_id'] );
    if ( !current_user_can( 'edit_post', $post_ID ) )
        wp_die( -1 );
    $thumbnail_id = intval( $_POST['thumbnail_id'] );
    check_ajax_referer( "set_post_thumbnail-$post_ID" );

    if ( $thumbnail_id == '-1' ) {
        if ( delete_post_thumbnail( $post_ID ) )
            wp_die( _wp_post_thumbnail_html( null, $post_ID ) );
        else
            wp_die( 0 );
    }

    ?>

    <?php

    if ( set_post_thumbnail( $post_ID, $thumbnail_id ) )
        wp_die( _wp_post_thumbnail_html( $thumbnail_id, $post_ID ) );

    wp_die( 0 );
}

If we do this, instead of bacon, we close the ThickBox window :)
jQuery('#TB_closeWindowButton').click();

Check this Q&A for more details:
How to Reload the Dashboard After Clicking Update in Quick-Edit?


text:
Q: basic intuition for perceptron algorithm / linear regression I'm studying about neural networks and I came across the following xorcise (that was a joke!) question.
I asked my friend if I need to implement the perceptron algorithm to solve it and he said "no- just think about it". Well, I thought about it, but my small monkey brain was only able to come up with the following:
My friends words make me think it's a trick question, and the only trick we've discussed thus far is the inability of perceptron to do an XOR function.
Is that was this question is getting at?
How to solve this problem?...
A simple Perzeptron with two inputs x₁, x₂,
BIAS, and transfer function y = f(z) = sgn(z),
separates the two dimensional input space into
two parts with help of a line g.

Calculate for this Perzeptron the weights
w1, w2, wb, so that the line separates
the given 6 patterns (pX1, pX2; Py) into
two classes:

1X = (0,  0;  -1),
2X = (2, -2; +1),
3X = (7 + ε, 3 - ε; +1),
4X = (7  -  ε, 3 + ε; -1),
5X = (0, -2 - ε; +1),
6X = (0 - ε, -2; -1),

Remark: 0 < ε << 1.

A: If you graph the points, you'll see that all the -1s are on the top left side, and all the +1s are on the bottom right.  You can draw a line intersecting (0, -2) and (7,3) which gives you the expression:
y = 5x/7 - 2

which is enough to skip running through any algorithm.
The equation of the line to predict +1 occurences is given by:
y < 5x/7 - 2

The line above splits the 2 dimensional space in two.   The shaded area is BELOW the line, and the line goes up and to the right.  So for any arbitrary point, you just have to figure out if it's in the shaded area (positive prediction = +1).
Say, (pX1, pX2) = (35, 100),
1) one way is to plug pX1 back in the formula (for x' = pX1) to find the closest part on the line (where y=5x/7-2):
y' = 5(35)/7 - 2
y' = 23

Since the point on the line is (35, 23) and the point we are interested is (35, 100), it is above the line.  In other words, pX2 is NOT < 23, the prediction returns -1.
2) plot y'=100, so
100 = 5x/7-2
x = 142.8

Line point=(142.8, 100), your point (35, 100), our point is on the left of the line point, it still falls outside the shaded area.
3) You can even graph it and visually check if it's in the shaded area
The point is some calculation has to be done to check if it's IN or OUT.  That's the point of linear regression.  It should be really simple for the machine to figure out because you're just calculating one thing.  Predicting once you have your formulas should be quick.  The hardest part is determining the formula for the line, which we've already done by graphing the points and seeing an obvious solution.  If you use machine learning, it will take longer in this case.


text:
Q: Trivial transfiguration I have $\frac{2ab}{ab-ac-bc+c^2}$. Of course it's $\frac{2ab}{c^2-ac-bc+ab}$ which is $\frac{2ab}{c^2-c(a+b)+ab}$ but for the latter Wolfram tells me it's not the same as $\frac{2ab}{ab-ac-bc+c^2}$. Why? What's wrong with it?
And I know it probably sounds as newbish as it can but I don't have the slightest idea what's wrong here.

A: The problem is that $c(a+b)$ is being interpreted as a function application. If you put a space after $c$, it works. That underlines the point that you should have included your precise input in the original question.


text:
Q: NodeJS and PCAP, ignore packets send by PCAP I have the following code for sniffing and sending packets with PCAP, if the source address is matching a specific one:
var Cap = require('cap').Cap;
var decoders = require('cap').decoders;
var PROTOCOL = decoders.PROTOCOL;

var c = new Cap();
var device = Cap.findDevice('192.168.0.10');
var filter = 'net 192.168.0.0 mask 255.255.255.0';
var bufSize = 10 * 1024 * 1024;
var buffer = Buffer.alloc(65535);

var linkType = c.open(device, filter, bufSize, buffer);

c.setMinBytes && c.setMinBytes(0);

c.on('packet', function(nbytes, trunc) {

  // raw packet data === buffer.slice(0, nbytes)

  if (linkType === 'ETHERNET') {
    var ret = decoders.Ethernet(buffer);

    if (ret.info.type === PROTOCOL.ETHERNET.IPV4) {
      ret = decoders.IPV4(buffer, ret.offset);

      if (ret.info.srcaddr === '192.168.10.10') {
        try {
          bufferToSend = buffer.slice(0, nbytes);
          // TODO, this packet will be catched by pcap and resend again and again and again
          c.send(bufferToSend, bufferToSend.length);
        } catch (e) {
          console.log("Error sending packet:", e);
        }
      }

    } else
      console.log('Unsupported Ethertype: ' + PROTOCOL.ETHERNET[ret.info.type]);
  }
});

The code works, but there's a catch which is that the packet I'm sending out gets sniffed once again with PCAP, and creates a loop.
I'm running Node.JS and cap module.
Is there a good way to overcome this issue?


text:
Q: Google map clustering in android I want to change  clustering icon like below in android. In a circle there will be a one imageview and one textview.

My code for custom icon
  private class ItemRenderer extends DefaultClusterRenderer<ClusterPopupList> {
    private final IconGenerator mIconGenerator = new IconGenerator(getApplicationContext());
    private final IconGenerator mClusterIconGenerator = new IconGenerator(getApplicationContext());
    private final int mDimension;

    public ItemRenderer() {
        super(getApplicationContext(), map, mClusterManager);

        View multiProfile = getLayoutInflater().inflate(R.layout.multi_profile,null);
        mClusterIconGenerator.setContentView(multiProfile);
        mImageView = new ImageView(getApplicationContext());
        mDimension = (int) getResources().getDimension(R.dimen.custom_profile_image);
        mImageView.setLayoutParams(new ViewGroup.LayoutParams(mDimension, mDimension));
        mIconGenerator.setContentView(mImageView);
    }

    @Override
    protected void onBeforeClusterItemRendered(ClusterPopupList item, MarkerOptions markerOptions) {
        mImageView.setImageResource(item.profilePhoto);
        Bitmap icon = mIconGenerator.makeIcon();
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
        super.onBeforeClusterItemRendered(item, markerOptions);

    }

    @Override
    protected void onBeforeClusterRendered(Cluster<ClusterPopupList> cluster, MarkerOptions markerOptions) {
        List<Drawable> profilePhotos = new ArrayList<Drawable>(Math.min(4, cluster.getSize()));
        int width = mDimension;
        int height = mDimension;

        for (ClusterPopupList p : cluster.getItems()) {
            // Draw 4 at most.
            if (profilePhotos.size() == 4) break;
            Drawable drawable = getResources().getDrawable(p.profilePhoto);
            drawable.setBounds(0, 0, width, height);
            profilePhotos.add(drawable);
        }

        Bitmap icon = mClusterIconGenerator.makeIcon(String.valueOf(cluster.getSize()));
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
    }

    @Override
    protected void onClusterRendered(Cluster<ClusterPopupList> cluster, Marker marker) {
        super.onClusterRendered(cluster, marker);
    }

    @Override
    public ClusterPopupList getClusterItem(Marker marker) {

        return super.getClusterItem(marker);
    }

    @Override
    protected boolean shouldRenderAsCluster(Cluster<ClusterPopupList> cluster) {
        return cluster.getSize() > 1;
    }
}

multi_profile.xml
    <?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<de.hdodenhof.circleimageview.CircleImageView
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:background="@android:color/transparent"
    android:src="@drawable/icon_cluster_count"/>

<TextView
    android:id="@id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="@style/Bubble.TextAppearance.Light"
    android:paddingLeft="@dimen/custom_profile_padding"
    android:paddingRight="@dimen/custom_profile_padding"
    android:layout_below="@id/image"
    android:text="150"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="8dip"
    android:textColor="@color/theme_color"
    android:alpha=".8"/>
   </RelativeLayout>

Output :

I want to achieve cluster icon like first image in a circle. I have used circle background in relative layout, but that does not work.

A: Use this to remove background
mClusterIconGenerator.setBackground(null)

Set the background to a given Drawable, or remove the background.
@param background the Drawable to use as the background, or null to remove the background.

A:     mClusterIconGenerator.setBackground(AndroidUtil.getDrawable(R.drawable.cluster_backgroud));

A: From the Google Maps documentation site:
Customize the marker clusters
The ClusterManager constructor creates a DefaultClusterRenderer and a NonHierarchicalDistanceBasedAlgorithm. You can change the ClusterRenderer and the Algorithm using the setAlgorithm(Algorithm<T> algorithm) and setRenderer(ClusterRenderer<T> view) methods of ClusterManager.
You can implement ClusterRenderer to customize the rendering of the clusters. DefaultClusterRenderer provides a good base to start from. By subclassing DefaultClusterRenderer, you can override the defaults.


text:
Q: How to filter out specific words in an Array with Javascript Okay so, I'm new to Javascript and im just trying to get the hang of loops and how to use them. So I came up with an exercise:

*

*I will create an Array with random words, some will be fruits.

*I want the loop to go through the Array (I came this far).

*Next I want to filter out only the fruit words, (which are called mango, banana etc.) and I want to replace these with the word Fruit
this is my current code :
let words = ['mango','desk','phone','banana','airpods', 6 ,'mouse','strawberry',9,'raspberry', 10];

let wordsArrayLength = words.length;

for (let wordLoop = 0; wordLoop < wordsArrayLength; wordLoop++ ) {

}

So I thought I would do a .filter() and then call out those names, and replace them with the word Fruit but I'm just kinda stuck now and I don't know how to go on from here... I couldnt find anything online that helped me with this, so maybe I didn't really make a good exercise for myself?
Also if anyone has any tips on what to practise with, with Javascript then let me know. Im thinking of making a puzzle/quiz next. I just wanted to know if there was a solution for what im trying to make now or if I just move on.

A: You don't want to filter out words - you want to create an array that's one-to-one with the original array, only with the fruit words replaced. Use .map instead.
You can also put the predefined fruit words into Set to reduce runtime complexity:

const fruits = new Set(['mango', 'banana', 'strawberry', 'raspberry']);
const input = ['mango','desk','phone','banana','airpods', 6 ,'mouse','strawberry',9,'raspberry', 10];
const mapped = input.map(val => fruits.has(val) ? 'fruit' : val);
console.log(mapped);

Or, using only array methods, you would test to see if the fruits array includes the value:

const fruits = ['mango', 'banana', 'strawberry', 'raspberry'];
const input = ['mango','desk','phone','banana','airpods', 6 ,'mouse','strawberry',9,'raspberry', 10];
const mapped = input.map(val => fruits.includes(val) ? 'fruit' : val);
console.log(mapped);

A: You can create a new array called fruits that will have all the fruits item. With that you can loop over to the words array and check if the item is fruit or not using fruits.indexOf(). If it is simply replace that word with Fruit:

let fruits = ['mango','banana','strawberry','raspberry'];
  let words = ['mango','desk','phone','banana','airpods', 6 ,'mouse','strawberry',9,'raspberry', 10];

words.forEach((word, index) => {
  if(fruits.indexOf(word) !== -1){
     words[index] = 'Fruit';
  }
});
console.log(words);

A: You could do this with map (https://www.w3schools.com/jsref/jsref_map.asp)
So what the map function does is loop through every item in the array and pass it to a function so you can transform that value


text:
Q: Evaluation of $ \int_{0}^{\infty}\frac{x\ln x}{(1+x^2)^2}dx$ $\bf{My\; Try:}$ Let $$\displaystyle I = \int_{0}^{\infty}\frac{x\ln x}{(1+x^2)^2}\,dx = \underbrace{\int_{0}^{1}\frac{x\ln x}{(1+x^2)^2}\,dx}_{I_{1}}+\underbrace{\int_{1}^{\infty}\frac{x\ln x}{(1+x^2)^2}\,dx}_{I_{2}}.$$
Now Here $$\displaystyle I_{2} = \int_{1}^{\infty}\frac{x\ln x}{(1+x^2)^2}\,dx.$$ Put $\displaystyle x=\frac{1}{t}.$ Then $\displaystyle dx = -\frac{1}{t^2}dt$ and changing limit
We get $$\displaystyle I_{2} = \int_{1}^{0}\frac{-t^3\cdot \ln t}{(1+t^2)^2}\cdot -\frac{1}{t^2}\,dt = \int_{1}^{0}\frac{t\ln t}{(1+t^2)^2}\,dt = -\int_{0}^{1}\frac{t\ln t}{(1+t^2)^2}\,dt$$
So we get $$\displaystyle I_{2} = -\int_{0}^{1}\frac{x\ln x}{(1+x^2)^2}dt = -I_{1}\Rightarrow I_{1}+I_{2} = 0$$
So we get $$\displaystyle I = \int_{0}^{\infty}\frac{x\ln x}{(1+x^2)^2}dx = I_{1}+I_{2} =0$$
My question is, can we solve it using another method? If so then please explain.

A: Your solution is simple and straight to the point. Here is a longer way:
You could take the indefinite integral then apply limits to find the definite integral.
Let $v=\log x$, $u'=\frac{x}{(1+x^2)^2}$
So $v'=\frac{1}{x}$, $u=-\frac{1}{2(1+x^2)}$
$$\int\frac{{x\log x}}{(1+x^2)^2}dx=-\frac{\log x}{2(1+x^2)}+\int\frac{1}{2x(1+x^2)}dx$$
$$=-\frac{\log x}{2(1+x^2)}+\int\frac{1}{2x}-\frac{x}{2(1+x^2)}dx$$
$$=-\frac{\log x}{2(1+x^2)}+\frac{\log x}{2}-\frac{\log(1+x^2)}{4}$$
$$=-\frac{x^2\log x}{2(1+x^2)}-\frac{\log(1+x^2)}{4}$$

A: $$\int\frac{x\ln(x)}{(x^2+1)^2}\space\text{d}x=$$

Integrate by parts $\int f\text{d}g=fg-\int g\text{d}f$: $f=\ln(x),\text{d}g=\frac{x}{(x^2+1)^2}\space\text{d}x, \text{d}f=\frac{1}{x},g=\frac{1}{2(x^2+1)}$:

$$-\frac{\ln(x)}{2(x^2+1)}+\frac{1}{2}\int\frac{1}{x(x^2+1)}\space\text{d}x=$$

Substitute $u=x^2$ and $\text{d}u=2x\space\text{d}x$:

$$-\frac{\ln(x)}{2(x^2+1)}+\frac{1}{4}\int\frac{1}{u(u+1)}\space\text{d}u=$$
$$-\frac{\ln(x)}{2(x^2+1)}+\frac{1}{4}\int\left(\frac{1}{u}-\frac{1}{u+1}\right)\space\text{d}u=$$
$$-\frac{\ln(x)}{2(x^2+1)}-\frac{1}{4}\int\left(\frac{1}{u+1}-\frac{1}{u+1}\right)\space\text{d}u+\frac{1}{4}\int\frac{1}{u}\space\text{d}u=$$

Substitute $s=u+1$ and $\text{d}s=\text{d}u$:

$$-\frac{\ln(x)}{2(x^2+1)}-\frac{1}{4}\int\left(\frac{1}{u+1}-\frac{1}{s}\right)\space\text{d}s+\frac{1}{4}\int\frac{1}{u}\space\text{d}u=$$
$$-\frac{\ln(x)}{2(x^2+1)}-\frac{\ln(s)}{4}+\frac{\ln(u)}{4}+\text{C}=$$
$$-\frac{\ln(x)}{2(x^2+1)}-\frac{\ln(x^2+1)}{4}+\frac{\ln(x^2)}{4}+\text{C}=$$
$$\frac{1}{4}\left(\frac{2x^2\ln(x)}{x^2+1}-\ln(x^2+1)\right)+\text{C}$$

Setting the boundaries:

*

*Zero:
$$\lim_{x\to 0}\frac{1}{4}\left(\frac{2x^2\ln(x)}{x^2+1}-\ln(x^2+1)\right)=$$
$$\frac{1}{4}\lim_{x\to 0}\left(\frac{2x^2\ln(x)}{x^2+1}-\ln(x^2+1)\right)=$$
$$\frac{1}{4}\left(2\lim_{x\to 0}x^2\ln(x)-\lim_{x\to 0}\ln(x^2+1)\right)=$$
$$\frac{1}{4}\left(2\cdot 0-0\right)=0$$

*Infinity:
$$\lim_{x\to\infty}\frac{1}{4}\left(\frac{2x^2\ln(x)}{x^2+1}-\ln(x^2+1)\right)=0$$

So:
$$\int_{0}^{\infty}\frac{x\ln(x)}{(x^2+1)^2}\space\text{d}x=\left[\frac{1}{4}\left(\frac{2x^2\ln(x)}{x^2+1}-\ln(x^2+1)\right)\right]_{0}^{\infty}=0-0=0$$

A: The simplest solution for this problem is to use the substitution $x=\frac1t$. In fact
\begin{eqnarray}
I&=&\int_{0}^{\infty}\frac{x\ln x}{(1+x^2)^2}dx
I&=&\int_{\infty}^0\frac{\frac{1}{t}\ln \frac{1}{t}}{(1+(\frac{1}{t^2})^2}(-\frac{1}{t^2})dt\\
&=&-\int_{0}^{\infty}\frac{t\ln t}{(1+t^2)^2}dt\\
&=&-I
\end{eqnarray}
and hence $I=0$.


text: Q: create generic list object from datatable which has different schema at runtime Datatable should be converted to a generic list. The datatable may have different schema at runtime.so extracting the class type for the generic list becomes difficult. Because as the columns differ at run time, I could'nt create property for the class type accordingly. I want to know how to do that. i am using c#.


text:
Q: How do you Access Grails ServletContext in a gsp file? I have a list of categories that need to live inside of the servletContext scope of the app since the list will be accessed by every view and will not need to be modified.
I tried setting a new servletContext property in the init method of BootStrap.groovy but I don't seem to be able to access the servletContext in the gsp files.
Here is what I'm trying. How do I access servletContext (application) scope properties from a gsp file?

import org.codehaus.groovy.grails.commons.ApplicationHolder as AH

import java.util.List
import java.util.ArrayList

class BootStrap {

    def init = {

        servletContext ->

        def dataSource = AH.application.mainContext.dataSource

        List categories

        def sql = new Sql(dataSource);
        def rows = sql.rows("select distinct catgry from cmpitmms");

        categories = new ArrayList();

        for (arg in rows) {
            println arg.getAt(0)
            if (!arg.getAt(0).trim().equals("")) {
                categories.add(arg.getAt(0).trim());
            }
        }

        servletContext.categories = categories

    }
    def destroy = {
    }
}

Here is where I'm trying to access it in the gsp file.

    <g:each var="category" in="${servletContext.categories}">

${category}

    </g:each>

A: Found it!
Instead of
servletContext.categories = categories

Do
servletContext.setAttribute("categories", categories)

Then in the gsp use
<g:each var="category" in="${application.categories}">

${category}

</g:each>

A: You could still use
servletContext.categories = categories

and in the gsp use
<g:each var="category" in="${application.categories}">

${category}

</g:each>

Setting it as a attribute is not needed


text:
Q: Regex extra in Hive after particular string I am very bad with Regex extract. I am trying to get the string which is marked in bold. Basically everything after cardUUID':u' till next '

'{u'cardName': u'Hilton Garden Inn Macon/Mercer University',
  u'cardUUID': u'a99512ea-c875-4aaa-8b0d-bb8dd668aaa8',
  u'attributionId': u'29fb392a-b4b6-ffab-d7e8-45e9d470e585', u'title':
  {u'content': u'Hilton Garden Inn Macon/Mercer University', u'type':
  u'title'}, u'cardSubtype': u'GETAWAYS_MARKET_RATE', u'slot_1':
  {u'content': u'Macon, Georgia', u'type': u'location-and-distance'},
  u'value': {u'content': u'$135', u'type': u'price'}}'

I tried couple of things in regex it did not work. Any suggestions? I am using Hive

A: Using get_json_object:
Check original string:
 select  '{u\'cardName\': u\'Cortyard Greenbelt\', u\'cardUUID\': u\'cfcc39d4-24d1-40b2-84b5-9aaab263fa0e\', u\'attribtionId\': u\'29fb392a-95fd-268f-7f84-7a58a7494c35\', u\'title\': {\'content\': \'Cortyard Greenbelt\', \'type\': \'title\'}, \'cardSbtype\': \'GETAWAYS_MARKET_RATE\', \'slot_1\': {\'content\': \'Greenbelt, Maryland\', \'type\': \'location-and-distance\'}, \'vale\': {\'content\': \'$140\', \'type\': \'price\'}}' as json;
OK
{u'cardName': u'Cortyard Greenbelt', u'cardUUID': u'cfcc39d4-24d1-40b2-84b5-9aaab263fa0e', u'attribtionId': u'29fb392a-95fd-268f-7f84-7a58a7494c35', u'title': {'content': 'Cortyard Greenbelt', 'type': 'title'}, 'cardSbtype': 'GETAWAYS_MARKET_RATE', 'slot_1': {'content': 'Greenbelt, Maryland', 'type': 'location-and-distance'}, 'vale': {'content': '$140', 'type': 'price'}}
Time taken: 2.38 seconds, Fetched: 1 row(s)

Now remove u and replace ' with " and extract JSON element:
hive> select get_json_object(regexp_replace(json,'(u\')|\'','"'),'$.cardUUID') cardUUID
    > from
    > (
    > select  '{u\'cardName\': u\'Cortyard Greenbelt\', u\'cardUUID\': u\'cfcc39d4-24d1-40b2-84b5-9aaab263fa0e\', u\'attribtionId\': u\'29fb392a-95fd-268f-7f84-7a58a7494c35\', u\'title\': {\'content\': \'Cortyard Greenbelt\', \'type\': \'title\'}, \'cardSbtype\': \'GETAWAYS_MARKET_RATE\', \'slot_1\': {\'content\': \'Greenbelt, Maryland\', \'type\': \'location-and-distance\'}, \'vale\': {\'content\': \'$140\', \'type\': \'price\'}}' as json
    > )s;
OK
cfcc39d4-24d1-40b2-84b5-9aaab263fa0e
Time taken: 0.184 seconds, Fetched: 1 row(s)

If the string contains leading and trailing ' like in your post, they should be removed.

A: Positive lookbehind and lookahead with lazy matching:
(?<='cardUUID': u').*?(?=')

Check: https://regexr.com/42jru


text:
Q: What is a TLS Lenovo Home automation controller? I went to install a printer on my laptop and spotted the following:

I have an HP laptop and am in the office and don't have anything Lenovo related hooked up to my machine, so what could this be?

A: I've found it on a Lenovo E550 notebook, the only Lenovo product in my lan.
I don't know what it is, but I got rid of it by uninstalling Lenovo Peer Connect and Lenovo Communications Utility.


text:
Q: How to get operator definition in PostgreSQL? I want to create alias for an operator. In this case I need its definition. How can I get it?

A: This information is in pg_operator system catalog.
See https://www.postgresql.org/docs/9.5/static/catalog-pg-operator.html for details.


text:
Q: group by keys and its value, where a key has many keys with values In json format:
form_data = {"block_1":{"mobile_number":"8745965123"},"block_2":{"diabetic":"Yes","diabetic_insulin":"INSULIN","major_illnesses_in_the_past":"qwe","major_surgeries_in_the_past":"qwerf"},"block_4":{"orientation_time":"TIME"},"block_5":{"skin_condition_intact":"INTACT"},"block_6":{"transferring_self":"SELF"},"block_7":{"mobility_independent":"INDEPENDENT","assistive_device_walker":"WALKER","upper_limbs_normal":"NORMAL","lower_limbs_normal":"NORMAL"},"block_8":{"oral_status_dry_mouth":"DRY MOUTH","diet_regular":"REGULAR"},"block_9":{"bowels_self_care":"SELF CARE"},"block_10":{"what_decrease_helps_to_reduce_pain_medication":"MEDICATION","what_decrease_helps_to_reduce_pain_any_other_method":"ANY OTHER METHOD"},"block_11":{"have_you_had_a_fail_in_last_12months":"Yes"},"block_12":{"medication_regimen_medication_1":"qwerfg","medication_regimen_dosage_1":"11"},"block_13":{"physical_problems_difficulty_in_hearing":"DIFFICULTY IN HEARING"},"block_14":{"eating_drinking_self":"SELF"},"others":{"daily_routinr_optional":"on","assesors_name":"qwert"},"block_15":{"6am_mon":"qwer","7am_tue":"wer","8am_wed":"wert","9am_fri":"wert"},"block_16":{"week_1":"qwer","week_2":"wer"},"block_17":{"environmental_assessment_family_members":"qwer"},"block_18":{"facilities_for_caregivers_accomodation":"qwert"},"block_19":{"sevice_required_live_in_care":"LIVE-IN-CARE"},"block_21":{"ventilator_evo":"Ventilator-EVO"}}

then to object:
var data_key = JSON.parse(form_data);

I want output like:
block_1
    mobile_number - 8745965123
block_2
    diabetic - Yes
    diabetic_insulin - INSULIN
    major_illnesses_in_the_past - qwe
    major_surgeries_in_the_past - qwerf

...continue...

Thanks in advance!

A: var form_data = {"block_1":{"mobile_number":"8745965123"},"block_2":{"diabetic":"Yes","diabetic_insulin":"INSULIN","major_illnesses_in_the_past":"qwe","major_surgeries_in_the_past":"qwerf"},"block_4":{"orientation_time":"TIME"},"block_5":{"skin_condition_intact":"INTACT"},"block_6":{"transferring_self":"SELF"},"block_7":{"mobility_independent":"INDEPENDENT","assistive_device_walker":"WALKER","upper_limbs_normal":"NORMAL","lower_limbs_normal":"NORMAL"},"block_8":{"oral_status_dry_mouth":"DRY MOUTH","diet_regular":"REGULAR"},"block_9":{"bowels_self_care":"SELF CARE"},"block_10":{"what_decrease_helps_to_reduce_pain_medication":"MEDICATION","what_decrease_helps_to_reduce_pain_any_other_method":"ANY OTHER METHOD"},"block_11":{"have_you_had_a_fail_in_last_12months":"Yes"},"block_12":{"medication_regimen_medication_1":"qwerfg","medication_regimen_dosage_1":"11"},"block_13":{"physical_problems_difficulty_in_hearing":"DIFFICULTY IN HEARING"},"block_14":{"eating_drinking_self":"SELF"},"others":{"daily_routinr_optional":"on","assesors_name":"qwert"},"block_15":{"6am_mon":"qwer","7am_tue":"wer","8am_wed":"wert","9am_fri":"wert"},"block_16":{"week_1":"qwer","week_2":"wer"},"block_17":{"environmental_assessment_family_members":"qwer"},"block_18":{"facilities_for_caregivers_accomodation":"qwert"},"block_19":{"sevice_required_live_in_care":"LIVE-IN-CARE"},"block_21":{"ventilator_evo":"Ventilator-EVO"}};

Object.keys(form_data).forEach((x)=>{
    console.log(x);
  Object.keys(form_data[x]).forEach((y)=>{
      console.log("\t"+y+" - "+form_data[x][y]);
    })
})


text:
Q: insert stylesheet link into multiple index.html I have a folder in a ftp with a hundred of subfolders, each have it's own index.html
I want to add a <link rel="stylesheet" href="https://subdomain.domain.fr/vad/client/build/iconfont.css">
in each index.html
The subdomain is variable and can be captured from another stylesheet link ex :
<link rel="stylesheet" href="https://subdomain.domain.fr/vad/client/build/theme.css">
I tried this :
find . -type f -name index.html -exec sed -i 's/<link rel="stylesheet" href="https:\/\/\(*\).domain.fr\/vad\/client\/build\/theme.css">/<link rel="stylesheet" href="https:\/\/\1.domain.fr\/vad\/client\/build\/theme.css"><link rel="stylesheet" href="https:\/\/\1.domain.fr\/vad\/client\/build\/iconfont.css">/g' {} \;

With capturing and copy groups but it's not working

A: Using Perl and a Mojo::DOM HTML Parser to edit your HTML:
use strict; use warnings;
use Mojo::DOM;

# Slurp the whole HTML as string
my $html = join "", <>;

my $dom = Mojo::DOM->new($html);

# Fetch domain name
$_ = $dom
     ->find('link[href][rel="stylesheet"]')
     ->map(attr => 'href')
     ->last;
my ($domain) = m|^https?://([^/]+)/|
    or die "No match https?!\n";

# Find/append
$dom
    ->find('head > link[href][rel="stylesheet"]')
    ->last
    ->append(
        "\n" .
        '<link rel="stylesheet" href="https://' .
        $domain .
        '/build/iconfont.css" />'
    );

# Render
print "$dom";

Output
Example of one file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="fr" xml:lang="fr" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<link href="https://subdomain.domain.fr/build/theme.css" rel="stylesheet">
<link href="https://subdomain.domain.fr/build/iconfont.css" rel="stylesheet">
<title></title>
</head>
<body>
  POUET
</body>
</html>

Usage
First test the script against some files without sponge.
Then, if tests are satisfactory:
#!/bin/bash

shopt -s globstar # enable recursion **

for h in **/*.html; do
    perl Mojo::DOM.pl "$h" | sponge "$h"
done

A: For ease and readability, change the delimiter from / to let's say # You also have to escape real dots in search pattern…
sed -i 's#<link rel="stylesheet" href="https://\(*\)\.domain\.fr/vad/client/build/theme\.css">#<link rel="stylesheet" href="https://\1.domain.fr/vad/client/build/theme.css"><link rel="stylesheet" href="https://\1.domain.fr/vad/client/build/iconfont.css">#g'

From there, I can see there's a mistake in your regexp capturing group… You wrote \(*\), but I suspect you mean \(.*\) :) (otherwise, you where trying to capture nothing …or by chance opening parenthesis only…)

Now, it's look like you are replacing one word with another one, in order to change the CSS file? As it's appearing in a specific kind of line, you can perform a simple replacement in line matching that pattern ;)
sed -i '/\<link rel="stylesheet" href="https:\/\/.*\.domain\.fr\/vad\/client\/build/s#theme#iconfont#'


text:
Q: How to check if a module is enabled/disabled in Magento 2? I have 2 stores views and a custom module, lat say module X with an observer.
public function execute(\Magento\Framework\Event\Observer $observer)
    {

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSession = $objectManager->get('Magento\Customer\Model\Session');

         $urlInterface = $objectManager->get('Magento\Framework\UrlInterface');

        //check if the crrent url not belong to the clubshop
        if($urlInterface->getCurrentUrl() =='https://www.storeview1.com/'){
            return true;
        }
        if(!strpos($urlInterface->getCurrentUrl(), "club_login" )){

            if($customerSession->getMyValue()==1){
                return true;

            }else{

            //redirect if sotreview 2
             $url = $urlInterface->getUrl('club_login');
                 $observer->getControllerAction()
                            ->getResponse()
                            ->setRedirect($url);
                            return false;
            }

        }

    }

For storeview no 1. this module in disabled(Storev-Config-Developer-Advanced) and for storeview no 2 this module is enabled.
Even the module is disabled on sotreview no 1, the observer still work on both stores and it redirect me.
What i tried to do, is to check if the module x is or no enabled on the storeview no 1, to avoid the extecution of this function.
Does anyone know how to do that?

A: You can use the method isEnabled to check if your module is enabled, if your code is enabled when you use this command below, so you can use this method to do the same check:
php bin/magento module:status

First thing, add the class into your module.
protected $moduleManager;
public function __construct(
    ...
    \Magento\Framework\Module\Manager $moduleManager,
    ....
) {
    ...
    $this->moduleManager = $moduleManager;
    ...
}

Then implement this check:
if ($this->moduleManager->isEnabled('Vendor_Module')) {
    //the module is enabled
} else {
    //the module is disabled
}

A: From Storev-Config-Developer-Advanced you only disable the output of a module and not the module itself. So the plugins the preferences and the event observers are still taken into consideration.
If you want to detect if a module output is disabled you can do this:
change your class constructor to provide an instance of Magento\Framework\Module\Manager as a dependency:
protected $moduleManager;
public function __construct(
    ...
    \Magento\Framework\Module\Manager $moduleManager,
    ....
) {
    ...
    $this->moduleManager = $moduleManager;
    ...
}

then you can call in your execute method this:
if ($this->moduleManager->isOutputEnabled('Vendor_Module')) {
    //the module output is enabled
} else {
    //the module output is disabled
}

you might not need the else part

A: You can check module status by below command:
php bin/magento module:status

You can see the list of enables modules.


text:
Q: Cron not creating logs This is my first time trying to create a cron job.  My server keeps getting warnings of high cpu usage so I am trying to create a cron to save a file of all processes every 10 minutes. I have created the folder already and chmod -R 777 that folder. the path is correct.  i would appreciate any help. in terminal i typed
crontab -e
then i typed in
*/10 * * * * ps aux > /var/www/html/cron/psOutput-`date +%F_%T`.txt

then i saved it.   if i go back and look at my cron, that line is there, its the only line.  i am lost. please help

A: You can see log of your cron job using heroku ...
$ heroku logs --ps cron.1
you will be able to see cron log...try it out.
best luck


text:
Q: How to convert a POST to a url? Is possible to send data, that you normal have to use a submit button to send it, by using just the url?
Here is an example of code from a site with a button like that:
<form method="POST" action="Action.php?action=338&n=688&t=mine"><input type="hidden" id="Mine688" value="1" name="duree"><button value="submit" class="boutonsGeneral" type="submit" name="travail"> +2,18Munca 1 hour</button></form>

This is from Live HTTP Header when I click on that button:
ww.kraljevine.com/Action.php?action=338&n=688&t=mine

POST /Action.php?action=338&n=688&t=mine HTTP/1.1
Host: ww.kraljevine.com/
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: ro-ro,ro;q=0.8,en-us;q=0.6,en-gb;q=0.4,en;q=0.2
Accept-Encoding: gzip, deflate
Referer: ww.kraljevine.com/EcranPrincipal.php?l=8
Cookie: PHPSESSID=ec95ed7caf7c28f8a333; KC=account_name; KC2=1502cae30e04f5f55963e93; > > Glup=274; pageTamponVue=1
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 22
duree=1&travail=submit

What I want to do is to send the post by url. Something like:
http://www.kraljevine.com/Action.php?action=338&n=688&t=mine (untill here is the link from site, and I want to add this) duree=1&travail=submit
Is not working http://www.kraljevine.com/Action.php?action=338&n=688&t=mine&duree=1&travail=submit and because of this I am wondering if is possible to do this.

A: Firstly you need to know what POST and GET are used for.

*

*If you want to SEND data you should use POST

*If you want to GET data depending on some params then use GET.
There is no sense in sending data with GET there are also some limitations to this. You can read more about limits here.
You can always use CURL to send POST data to the other URL.
Here is good tutorial how to do it and here goes the example based on this tutorial:
<?php
$url = 'http://www.kraljevine.com/Action.php?action=338&n=688&t=mine';
$fields = array(
                    'duree' => urlencode('1'),
                    'travail' => urlencode('submit')
            );
//$fields can be extended with more params for POST submit always encode them with urlencode for these 2 examples of 1 submit it is not necessary but sometimes is really imporant to do it

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);
?>

The last thing is $_REQUEST which is An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE. You can use it in php script and there will be no difference how the variable is passed for php script.
Use it wisely.

A: make the form method GET and put the variables in hidden fields in your form.
for example:
<form method="GET" action="Action.php">
 <input type="hidden" name="action" value="338" />
 <input type="hidden" name="n" value="688" />
 <input type="hidden" name="t" value="mime" />
 ...more html/php...
</form>

A: The short answer is no.
By definition, GET variables are sent in the URL,
and POST variables are sent in the request's body.
So, you can't send your variables JUST by using the URL, as you requested.
You probably can physically catch a possible URL with parameters even in POST request, but I highly recommend you not the takes this approach.
You can read more about it in this post

A: In my case using spring boot.
I have converted from POST to GET like this :
BEFORE
in jsp( sender ):

in Java (reveiver):

I have converted to :
AFTER
in Jsp:

in Java:

and the result is match to what I want. I have changed only where the arrow is pointed in the picture, it saves my time a lot. All parameters will be composed into object "searchModel" easily.


text:
Q: Using sed to replace pattern How can i write bash script to do the below

*

*search all files recursively within directory ending with html and htm.

*using sed to search for <body> and delete all lines before this line including the <body> line

*As well as searching for </body> and deleting all the lines after that including <body> line.

*the change should not be on the same file but like index-temp.html.

I wrote the below but I cant get how can I change the whole block after and safe the change to another file and not on the same file. Do I have to use if?
#!/bin/bash
input=$1
find "$input" -type f -name "*.htm" -exec sed

A: as says @Tom Fenech :
xmllint --html --xpath '//body/node()' index.htm* > index-temp.html

*

*<body> and <BODY> are targeted

**.html?(l) for only htm/html but with extglob active (debian default)

with the details of @tripleee:
find "$input" -type f -iregex '.*\.html?' \
  -exec sh -c 'for f; do
      xmllint --html --xpath "//body/node() "$f" >"${f%.htm*}"-temp.html;
    done' _ {} +

A: For a single file, the sed command would be:
sed '1,/<body>/d;/<\/body>/,/$/d' index.html > index-temp.html

The syntax is
sed 'ROWa,ROWz d'

where ROWa is the linenumber to start, ROWz where to end, inclusive, counting from 1. The $ can be used for LASTLINE.
You can use patterns too:
sed '/PATa/,/PATz/ d'

From pattern PATa until pattern PATz. And pattern/lines can be mixed.
Now for the find-part:
find "$input" -type f -name "*.htm*" -exec sed -i.temp '0,/<body>/d;/<\/body>/,/$/d' {} ";"

would change the htm(l)-file, but create a backup (like index.html.temp) from the original.
Maybe that's even more convenient to you. Else you have to rename all those files, which would require another script, since sed and find themselve know no redirection, so it would require some shell invocation with basename, which would be an alternative way to go:
#/bin/bash
#
# justbody.sh
#
infile=$1
outfile="$(basename $infile .htm)-temp.htm"
sed '0,/<body>/d;/<\/body>/,/$/d' $infile > $outfile

and now invocation by:
find "$input" -type f -name "*.htm" -exec ./justbody.sh {} ";"