Access Node image within Page template

Question: I need to access a Node's image field within the page.twig.html template in order to display it in relation to certain page-level elements such as primary/secondary menus and the page title.
In node.html.twig, I'm able to access it like so:
{{ content.field_responsive_hero_image.0 }}

but in page.html.twig if I try
{{ node.field_responsive_hero_image.0 }}

I get the following error:
Exception: Object of type Drupal\image\Plugin\Field\FieldType\ImageItem cannot be printed

I'm familiar with the workaround of loading the image with

However, I then lose the title and alt attributes (bad for 508 compliance) as well as the automatic resizing of the image served based on screen size (bad for SEO rankings).
How do I access the Node's image at a page-level?
Comment: You'd hide the image from node display and print it via a block instead. Place the block between the menu and page title, export config, done. UI kept intact, templates kept clean, everybody happy.
Comment: If you `{{ dump(node.field_responsive_hero_image.entity | keys) }}`, do you see the title and alt keys? If you can access the `fileuri` you should be able to access the `alt` and `title` values... e.g. ``.
Comment: **Printing node values in page templates is bad bractice!** Simply use a block instead.
Comment: @Prestosaurus that solves most of my problems. The only thing left is serving different images based on the device, but I may be able to work it out with "srcset".
Comment: @leymannx I get that it's bad practice.....just trying to build a page to a design. I'm not sure how using a block would work though....it's still going to be within the same place on the page.
Comment: You could use Views for that, or build a custom block in a custom module yourself. I'd recommend the latter, as it's a nice exercise to learn something really useful.
Comment: There have been times I've needed to update a theme this way. Most content is in `node`, but the chrome of the site is in `page`. Now, the client wants an image in the header and it isn't worth it to move all the chrome into the node template. I agree that a block is the best approach. When I want an image in the header that's all I want. For every entity in Drupal you add div's. So you would create a custom block type and template, a block instance, export config, etc... Is this more re-usable than just printing the node values in page? Debatable when you consider a real dollar budget.
Answer: In a preprocess hook (preferred):
/**
 * Implements hook_preprocess_HOOK() for page.html.twig.
 */
function MYTHEME_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    $variables['image'] = $variables['node']->get('field_image')->first()->view('full');
  }
}

Or in Twig:
{{ node.field_image.0|view('full') }}

To use |view install the module https://www.drupal.org/project/twig_tweak

Access Node image within Page template


Detecting users emotions by analyzing the text

Question: im doing a project which will detect users emotions through text? Im new to this area im still finding the best algorithm to detect the emotions from text.suggest me a good method to do this?
Comment: @ThomasMcLeod I don't think this question will be welcome on [Programmers.SE] in it's current form. It shows no prior reseach, and is asking for "the best", which can be subjective.
Comment: You might also submit this question here: http://programmers.stackexchange.com
Answer: You can use in a simple way:

Build a list of lets say 300 quotes with respective emotion.

I'm done of this kind of game   => Bored
  Size doesn't mean everything    => Defense
  I will bring you all pain       => Angry
  Fortune doesn't favor fools     => advise

Now make a filter to select only important words from each phrase, removing words that will not impact in the meaning
Create a range from 0 to 100 and lets create for example 5 emotions that will fit 0-20 21-40 41-60 61-80 81-100. Each emotion will be filled in a range. For example a good range would be:
coolness -> happiness -> normal -> bored -> sad
Now for each important word from step 2 you will have to assign a number in the range of 0-100 that most describe the emotion (For example: very happy is 1 little happy is 20 little sad is 81 very sad is 100)
now you will have quotes like numbers and you can put emotions in array of numbers
Now you can use a Neural Network (you will train the NN with your arrays and for a new entry it will try to 'say' what is the emotion that is seems to be.

Lets suppose you find a tool for training and testing NN as below.

Each of the inputs will be the numbers of your "emotion array" and the output will be a binary number. if you want represent a 0-4 (cool to sad) range, so you will need 3 outputs (3 bits = 8 possible numbers represented since 2 bit we can only 4 numbers)
the training file for your neural network will look like below:

i1 i2 i3 i4 output
  21 27 01 07 1
  01 07 02 91 5
  15 27 31 40 3
  16 01 07 55 4

By words it means: for this set of inputs representing these emotions i will have to show 1 (happy) and the same thinking to the other lines
THis file will be lots of lines of traning (300 i said above) and the result of the training will be the WEIGHTS of the neural networks be calibrated to your "artificial inteligence"
Of course the output depends of the quality of your data and your filter.
Also you will have to study how many inputs your Neural network will have, how many layers and so on.
Comment: thankz will try your method..
Comment: thankz for ur answer...can u type ur email address here..or can u send a mail to email@example.com
Answer: If have to do this I will divide it into 2 step process:

Make/Create a list/DB of emotion expressions/words ( like Happy, angry, bad or sad) from dictionaries. I am not sure but there might be already some API's from dictionaries Other wise you can maintain by your self.
For example :
http://www.thesaurus.com/browse/sad
http://www.psychpage.com/learning/library/assess/feelings.html
Check if the Users's text contains these Sad/Bad words.

You can create a user's text profile by capturing of any such word's count in the text. At the end based on these counts you can predict.
Comment: i thought of doing it like that but the problem is there are lots of words for any given emotion.Im searching for a method like which could split the sentence in to separate parts and check their special words.Something like that
Comment: I though the problem is to define a word if it is special (indicates some emotion). There might be cost in this but it should be thread safe to run in parallel. So my one process will break the statement word by word and n threads will check if these words have some emotional indication.  Diving a statement into sub parts should be easy. Do you see some problem?


Any solution abour Flutter Error: Error Opening Emulator?

Question: Flutter was working perfectly, but suddenly had this error. I tried many solutions, but none of them worked, thanks for any help!
<code>INFO | Android emulator version 22.214.171.124 (build_id 10696886) (CL:N/A) INFO | Found systemPath /Users/basem/Library/Android/sdk/system-images/android-30/google_apis_playstore/x86/
INFO | Found systemPath /Users/basem/Library/Android/sdk/system-images/android-30/google_apis_playstore/x86/
WARNING | Please update the emulator to one that supports the feature(s): Vulkan
ERROR | Running multiple emulators with the same AVD ERROR | is an experimental feature.
ERROR | Please use -read-only flag to enable this feature.
INFO | Storing crashdata in: /tmp/android-basem/emu-crash.db, detection is enabled
INFO | Duplicate loglines will be removed, if you wish to see each indiviudal line launch with the -log-nofilter flag.
</code>
Comment: Did you tried flutter doctor?
Answer: The error you're seeing says the problem you're having is with Vulkan. Vulkan is a Graphics Api. Google announced a few months ago that emulators can support Vulkan. so you can try to fix this problem by turning your computer off and on again. additionally, be aware that the SDKs and gradles are downloaded. you can reach especially gradles with this step:


What is the most appropriate place to place tomcat in a RHEL/Centos Environment

Question: Developing a virtual machine that will be managed by IT Admins - where is the most appropriate or commonly accepted place to install the tomcat directory on a CentOS system?
Answer: Default directory maybe :
<code>/usr/local
</code>
Answer: I saw many on /opt, same for jdk, /opt/java...
Answer: The location that the package maintainer specifies. Tomcat5 & tomcat6 packages are available from the JPackage yum repository. Using the package maintenance mechanisms of your operating system(yum in the case of CentOS) relieves a lot of cruftiness and administrative overhead in my experience.
Answer: Where the package puts it.
There is a tomcat5 rpm available from the "updates" repo in CentOS5.
Its actually just a redistributed copy of the jpackage one.
<code>[jim@ssh ~]$ yum info tomcat5
Loaded plugins: fastestmirror
addons                                                                                |  951 B     00:00
base                                                                                | 2.1 kB     00:00
epel                                                                                | 3.4 kB     00:00
epel/primary_db                                                                                | 3.3 MB     00:00
extras                                                                                | 2.1 kB     00:00
updates                                                                                | 1.9 kB     00:00
updates/primary_db                                                                                | 560 kB     00:00
Available Packages
Name       : tomcat5
Arch       : x86_64
Version    : 5.5.23
Release    : 0jpp.9.el5_5
Size       : 361 k
Repo       : updates
Summary    : Apache Servlet/JSP Engine, RI for Servlet 2.4/JSP 2.0 API
URL        : http://tomcat.apache.org/
License    : Apache Software License
Description: Tomcat is the servlet container that is used in the official Reference
           : Implementation for the Java Servlet and JavaServer Pages technologies.
           : The Java Servlet and JavaServer Pages specifications are developed by
           : Sun under the Java Community Process.
           :
           : Tomcat is developed in an open and participatory environment and
           : released under the Apache Software License. Tomcat is intended to be
           : a collaboration of the best-of-breed developers from around the world.
           : We invite you to participate in this open development project. To
           : learn more about getting involved, click here.
</code>


Exercise on characterization of free abelian groups

Question: I was wondering if someone can please check my work on a homework problem. This is from the graduate Hungerford text. Chapter 2.1, number 3.
Let $X=\{a_i\ |\ i\in I\}$ be a set. Then the free abelian group on $X$ is isomorphic to the group defined by the generators $X$ and the relations
$$\{a_ia_ja_i^{-1}a_j^{-1}=e\ |\ i,j\in I\}.$$
Proof: Let $F$ be the free abelian group on $X$ and let $G$ be the group defined by the generators $X$ and the relations $\{a_ia_ja_i^{-1}a_j^{-1}=e\ |\ i,j\in I\}$.
Since any two generators in $X$ commute, it follows that $G$ is abelian. Now since $F$ is free abelian on $X$, and since $G$ is an abelian group, the inclusion $\iota:X\rightarrow G$ induces a homomorphism of abelian groups $f:F\rightarrow G$ such that $fh=\iota$ where $h:X\rightarrow F$. We have $f(h(X))=\iota(X)=X$. So $X$ is in the image of $f$. But since $X$ generates $G$, the image of $f$ is all of $G$ so that $f$ is epic. I am having a lot of trouble proving that $f$ is also monic. Can someone read this over and tell me if I am on the right track. Thank you very much.
Comment: You might want to go in the other direction, showing that $G$ possesses the universal property of free abelian groups by using the universal property of free groups.
Comment: What is $ϕ$, though? Did you maybe mix up your names in the middle ant $ϕ$ is really $f$ and $f$ is really $h$?
Comment: Just fixed the typo, sorry everyone.
Answer: What you've written so far seems good to me, (modulo the now-fixed mix-up).
To go on: Try to find a group arrow $G → F$. Use the universal property of the free group on $X$ (of which $G$ is a factor group). Then use the first isomorphism theorem (or the universal property of factor groups, whatever you call it).
Then don't show that $f$ is monic, but that it has a left inverse (this makes the argument more solid since you then don't need to show "monic + epic = iso in $\mathrm{Grp}$", but only "left invertible + epic = iso" which is category-theoretic and straightforward).
Comment: Thank you so much for the quick response. This helps a lot because I want to argue this in category theory language.
Comment: @user113913 In that case you may also be interested in replacing the image-argument you have given to prove $f$ is epic by directly proving that both constructed arrows $f$, and the other $G → F$ are in fact inverse to each other. That would be bit more category-theoretic in flavour. (Your argument is of course perfectly fine, though.)


VBA Passing Object into another Objects Collection

Question: I have a set of owners, who each have their own set of opportunities.
I have two class modules, ClmOpportunity which has a bunch of properties, and ClmOwner which has a single name property and a Collection storing ClmOpportunity Objects:
Public name As Variant
Private opps As New collection

Public Function addOpportunity(opp As ClmOpportunity)

    opp.ID = opps.Count + 1
    opps.Add opp, opps.Count + 1

End Function

These owner objects are also being stored in a collection in my main module. When I try to use the function addOpportunity as shown below:
Dim item As New ClmOpportunity

item.name = "test"

owners.item(overallOwner).addOpportunity (item)

I get the error:

"object doesn't support this property or method"

I am quite new to VBA and I don't understand why this is, I am passing in a ClmOpportunity, so it should be fine right?
Any help would be greatly appreciated!
Answer: You don't use parentheses if there's no return value...
owners.item(overallOwner).addOpportunity item

...then you'll get a "type mismatch" error because a collection expects a string value as a key, so you'll need to adjust your addOpportunity function (which should probably be a Sub if you don't intend adding a returned value)


Include deployment timestamp into JSP page

Question: I'm writing web applications with Java EE 7 using JSP and servlets, deploying to a local Wildfly 10 server.
To help me developing and testing my code, it would be useful to include a little timestamp into the displayed webpage, so that I can directly see when the version I'm looking at in my browser was deployed.
That would prevent me from both forgetting to deploy changes as well as from looking at old cached versions instead of the latest one.
How can I display the date and time when a Java EE web app got deployed to my Wildfly server directly on the webpage?
My IDE is Eclipse Neon for Java EE, if that matters.
Answer: There is likely an API to do this too but you can get the server start time from the command line.  Assuming that you have your admin user name and password set up (i.e. you've run something like add-user.sh) you could run:
curl --digest "http://user:password@localhost:9990/management/core-service/platform-mbean/type/runtime?operation=attribute&name=start-time"

Of course, this is not Java - you'd either have to do a System.exec on this or use something like HttpClient.  Additionally, the big issue here is that you've got to have your admin username and password available to the code.
The Wildfly HTTP Management Docs go into some more detail with a small sample Java snippet.
EDIT:
Sorry - should not have assumed that the server restarts on deployment.  You can get deployment time for a web app with:
curl --digest "http://user:password@localhost:9990/management/deployment/test-1.0-SNAPSHOT.war/?operation=attribute&name=enabled-time"

However, that seems more difficult than the other answer of running something at startup.  I don't see a deployment time for a webapp as that time would have to be stored somewhere in case of server restarts.
Comment: Please note that don't restart the whole server to deploy a new version of my application, I just let it automatically publish the new build and then restart the module. Your approach only shows the server start time, not the module start time, right?
Answer: This is not deploytime, but starttime of the application. Maybe it is useful for your purpose. You can inject the class and use it to display data on your page.
@Startup
@Singleton
public class Deploytime
{
  private LocalDateTime starttime;

  @PostConstruct
  public void init() {
    starttime = LocalDateTime.now();
  }
}

Apart from that I can only think of Maven Git Plugin which can generate things like buildtime, commit id, ... into a propery file, which you can also use to display it on the page (if you use git/maven).
Comment: Thanks, that might be indeed equally helpful. Going to test it tomorrow morning


Basic Topology: Interior of a Given Topology

Question: The open half-line topology = {($a$,+$\infty$):$a \in R$} $\cup$ {$R,\varnothing$}.
What would the interior of a set in this topology look like?
My text states that, Let A = [1,5). Thus in the open half-line topology, $Int(A) = \varnothing$.  I do not understand why.
I am trying to understand so that I can apply this to other sets A, such as Z, R - Z, Q, and R - Q.
Comment: Indeed, $A$ does not contain any open set for this topology. The interior of $A$ being the union of all open sets contained in $A$, this implies that the interior is empty.
Comment: Does $A$ contain any open set?
Comment: A contains (1,5) but that is not open in this topology since it is not of the correct form (a,$\infty$).  Is that why Int(A) is $\varnothing$?
Answer: I'm assuming this is the basis for the topology. Consider the set $A \ = \ [1, \ 5)$, as the text says. We can see that there exists no union of intersection of "half intervals" $(a, \ \infty)$ contained within this set, as the an open set of this form necessarily extends off to positive infinity. Thus, the only open set contained in $A$ is $\emptyset$.
This same logic applies to any real interval in our topological space that does not extend to infinity.


"dynamic" for anonymous delegates?

Question: I wonder if there is a possibility to make the "dynamic" type for variables work for anonymous delegates.
I've tried the following:
dynamic v = delegate() {
};

But then I got the following error message:
Cannot convert anonymous method to type 'dynamic' because it is not a delegate type
Unfortunately, also the following code doesn't work:
Delegate v = delegate() {
};
object v2 = delegate() {
};

What can I do if I want to make a Method that accepts any type of Delegate, even inline declared ones?
For example:
class X{
    public void Y(dynamic d){
    }
    static void Main(){
        Y(delegate(){});
        Y(delegate(string x){});
    }
}

Comment: Any reason not to use `Func<>` or `Action<>`?
Comment: @AdamHouldsworth - Yep, having re-read the question I get the point now, but it doesnt make much sense. You must have to *do* something with the delegate which means your program must understand the I/O of the delegate.
Comment: @Jamiec I suppose because that won't satisfy the criteria of not caring what the signature of the delegate is. That said, it would boil down to calling Invoke with an `object[]` of parameters, which could then be expressed in `Func<>`.
Comment: You're not declaring any delegate type there.
Comment: @Jamiec because Func<> and Action<> has a FIX count/type of parameters. It has to be specified every time. I don't want to do this.
Comment: As an incomplete solution, you could make overloads of Y that accept variations of `Func`, `Func`, `Func`...I know that's not what you're looking for, but it's a start if you can't solve it with an arbitrary delegate signature.
Comment: @Jamiec It doesn't need to understand the I/O. A delegate boils down to "I can call it and give it something to work with", generically that means a call method (Invoke usually) and general arguments: `object[]`.  My answer shows this.
Answer: This works, but it looks a little odd. You can give it any delegate, it will run it and also return a value.
You also need to specify the anonymous method signature at some point in order for the compiler to make any sense of it, hence the need to specify Action<T> or Func<T> or whatever.
Why can't an anonymous method be assigned to var?
    static void Main(string[] args)
    {
        Action d = () => Console.WriteLine("Hi");
        Execute(d); // Prints "Hi"

        Action<string> d2 = (s) => Console.WriteLine(s);
        Execute(d2, "Lo"); // Prints "Lo"

        Func<string, string> d3 = (s) =>
        {
            Console.WriteLine(s);
            return "Done";
        };
        var result = (string)Execute(d3, "Spaghettio"); // Prints "Spaghettio"

        Console.WriteLine(result); // Prints "Done"

        Console.Read();
    }

    static object Execute(Delegate d, params object[] args)
    {
        return d.DynamicInvoke(args);
    }

Comment: couldnt you make the second param of `Execute` into `params` making it look less weird? See: http://rextester.com/KMX49960
Comment: @VanCoding It might be the same reason you cannot assign a lambda into a `var`.
Comment: This is what I already got. The problem here is, that I have to specify the signature of the Action for every delegate I pass to execute. With this question I wanted to find a way to avoid this.
Comment: @VanCoding I can't think of a way to avoid that, but that said, it won't matter or create any problems. You *know* what the signature is because you are creating the signature in-line, you simply need to cast it to that signature before giving it to the method.
Comment: @AdamHouldsworth that's sad, because specifying it seems absolutely unnecessary to me... It makes the whole code very awkward... No developer wants to define the type twice... It's not a matter of knowing the type, its a matter of code design.
Comment: @Jamiec Yes true, I have amended my code to look "less weird"... lol
Comment: @AdamHouldsworth Isn't there a way to do it like this: `Action x = delegate(string y) {};`? It doesn't work but maybe its another idea...
Answer: If you declare a type for each of your delegates, it works.
// Declare it somewhere
delegate void DelegateType(string s);

// The cast is required to make the code compile
Test((DelegateType)((string s) => { MessageBox.Show(s); }));

public static void Test(dynamic dynDelegate)
{
    dynDelegate("hello");
}

Comment: so I have to cast every anonymous delegate first before passing it to Test?
Comment: Yes, else it is not going to compile.
Answer: Action _;
dynamic test = (_ = () => Console.WriteLine("Test"));
test() // Test

Comment: Please add an explanation with your code to make it easier to understand.

"dynamic" for anonymous delegates?


Can some one point out my problem? I can't seem to print out the first element of my enum class

Question: so I have this simple code which just to print out the element of the enum class:
<code>using System;

namespace Program
{
  class Program
{
    public enum Mod
    {
        f1 = 3,
        f2 = 3,
        f3 = 3,
        f4 = 4,
        f5 = 4,
        f6 = 4,
        f7 = 5,
        f8 = 5
    }
    static void Main(string[] args)
    {
       Console.WriteLine(Mod.f1);
    }
   }
 }
</code>
So everytime I run this, the output is f2 not f1, but however When I try other(f2, f3, f4) the output is correct.(I'm sorry if my question is too bad but I can't seem to find the problem).
Comment: Because they have duplicated values. `Console.WriteLine(Mod.f1 == Mod.f2);` will output `True`
Comment: ok, I see it now, thank you.
Comment: The question is why did you give them the same values ?
Comment: I'm playing around with new things, I just start learning prog
Answer: The value of the element is duplicate, thank you cid for pointing this out for me, the question is solved


Can't change the tooltip y formatter in Apexcharts

Question: I'm trying to do something that should be pretty trivial. I have a simple formatter method to change a number into a currency value. It works because you can see that the y axis values have been formatted to values like "$8,000". However, the tooltip y values are not formatted (as you can see in the picture). The documentation says that they should be formatted using the y axis formatter, which clearly isn't happening.

Even if I try a custom formatter, it seems to do nothing:
tooltip: {
  shared: false,
  intersect: true,
  x: {
    show: true,
  },
  y: {
    formatter: (y: any) => {
      return '$' + y;
    },
  },
},

The strange thing is that when I console.log(...) inside of that custom formatter, it prints once or twice, and only the Maximum value (e.g. 7380.69999999999) but not all five of the values like I would expect.
Relatedly, I can't get the tooltip x header to show. I'm setting it to true but it doesn't appear.
I'm using vue but I don't think that matters. Almost every other Apexchart option seems to work except for this one.
Answer: Going through a bit in the code of apexcharts.js, I found this solution:
tooltip: {
    shared: false,
    intersect: true,
    custom: function({ seriesIndex, dataPointIndex, w }) {
      const minimum = w.globals.seriesCandleO[seriesIndex][dataPointIndex]
      const q1 = w.globals.seriesCandleH[seriesIndex][dataPointIndex]
      const median = w.globals.seriesCandleM[seriesIndex][dataPointIndex]
      const q3 = w.globals.seriesCandleL[seriesIndex][dataPointIndex]
      const maximum = w.globals.seriesCandleC[seriesIndex][dataPointIndex]

      return `

Minimum: \$${minimum}

Q1: \$${q1}

Median: \$${median}

Q3: \$${q3}

Maximum: \$${maximum}

`
    }
  }

Resulting in the following:

Demo in codi.link
Comment: Thank you. It's a shame that we have to resort to custom code in order to make this work. I can't tell if it's a bug in apexcharts or if I'm just doing something blatantly wrong.
Comment: @kevlar Instead of an error, I see it more like: "I give you the tools, find out how to implement them for your use case"
Comment: lol I agree in general, except in theory this functionality is supported.
Comment: @kevlar It also gives the feeling that the documentation is complete, but at the same time it is not


Is this series bounded?

Question: $$
\frac{2^n3^n}{n!}
$$
I know the series is not monotonoic. I believe the series is bounded below at when n goes to infinity the series will go to 0, but never hit it. I just don't know if the series is bounded above.
Comment: This is a **sequence**. A series is a **sum** of (countably) infinitely many numbers. I have had a couple hundred students who ran afoul in an exam problem because they forgot the distinction. Hence the nitpick. Also a friendly piece of advice: making the distinction clear in your mind avoids misapplication of theorems, and unnecessary deductions from your exam scores!
Comment: The sequence *is* monotonic for n >6.
Answer: $a_n = \dfrac{2^n3^n}{n!} = \dfrac{6^n}{n!}$
Then, $\displaystyle \lim_{n\to\infty}\dfrac{a_{n+1}}{a_n} = \lim_{n\to\infty}\dfrac{6}{n+1}=0$.
Therefore, the series converges, and is therefore bounded.
Comment: Much better if you say that since the series $\sum a_n$ is convergent (because of the Ratio Test), then $\lim_{n\to\infty} a_n=0$ and hence the sequence $(a_n)$ is bounded.
Answer: Yes it's bounded. To see this, notice that it's monotonic decreasing for $n>6$.

Is this series bounded?


ColdFusion: server-side user validations

Question: Is there some way to improve these server-side user fields validations?
<cfif Form.LoginName EQ "">
Login Name is required.
</cfif>
<cfif Form.Password EQ "">
Password is required.
</cfif>
<cfif Form.Password NEQ Form.PasswordConfirmation>
Password confirmation does not match Password.
</cfif>
<cfif Form.FirstName EQ "">
First Name is required.
</cfif>
<cfif Form.LastName EQ "">
Last Name is required.
</cfif>

<cfif Form.LoginName EQ "" OR Form.Password EQ "" OR Form.Password NEQ Form.PasswordConfirmation OR Form.FirstName EQ "" OR Form.LastName EQ "">

User has not been created

You can use your browser's back button to keep form fields filled and try again.

Return to users list.

    <cfabort>
</cfif>

Comment: Take a look at ValidateThis - http://www.validatethis.org/ - it is an open source library to handle validation, both client side and server side. Very cool, very powerful.
Answer: The way you're coupling your business logic to your display leaves a bit to be desired. You could probably benefit from reading up on MVC and separation of concerns.
From the perspective of your logic, your validation rules seem fine, but you're doing the validation twice, which seems excessive: each element, then all elements. This is in part due to the problem I highlight above.
I'd give some thought to stop thinking procedurally, and think in a more OO fashion, and define the notion of a User.cfc, and have some sort of validation service (see ValidateThis). Or something like that.
Lastly, this is not really the sort of question best asked on Stack Overflow, but would be good for Code Review. There's no one answer for this question, so people will be inclined to suggest closing it for being "primarily opinion-based".
I'm also gonna retag this as just "ColdFusion" rather than "ColdFusion 10", as it really has nothing specifically to do with CF10, it's just a CFML question. You'll get a bigger audience with it marked as just "ColdFusion".
Answer: Instead of sharing code with you, I would like to introduce the concepts to you. The first thing you should do is read the OWASP recommendations for Data Validation. In it they suggest that there are four strategies for validating data, and they should be used in the following order. I will post some excerpts here but I strongly recommend you read the entire article.

Accept known good
This strategy is also known as "whitelist" or "positive" validation. The idea is that you should check that the data is one of a set of tightly constrained known good values. Any data that doesn't match should be rejected.
Reject known bad
This strategy, also known as "negative" or "blacklist" validation is a weak alternative to positive validation. Essentially, if you don't expect to see characters such as %3f or JavaScript or similar, reject strings containing them. This is a dangerous strategy, because the set of possible bad data is potentially infinite. Adopting this strategy means that you will have to maintain the list of "known bad" characters and patterns forever, and you will by definition have incomplete protection.
Sanitize
Rather than accept or reject input, another option is to change the user input into an acceptable format
No validation
This is inherently unsafe and strongly discouraged. The business must sign off each and every example of no validation as the lack of validation usually leads to direct obviation of application, host and network security controls.

The article goes on to discuss each of these in greater detail and much more.
Answer: This is another way.  You can decide for yourself whether or not it is better.
Step 1 - create an error message variable.
<cfset ErrorMessage = "">

Step 2 - Do your checks.  If you see something you don't like, append text to your variable.
<cfif len(trim(form.LoginName)) gt 0>
<cfset ErrorMessage &= "
Login Name is required
">
</cfif>
more checks

Step 3 - Check the length of your error message variable
<cfif len(ErrorMessage) gt 0>
display it
<cfelse>
code for no errors
</cfif>

In addition to all this, you probably want to check to see if the page request actually came from your form page.  You can use cgi.http_referrer for that.
One more thing.  Instead of an anchor tag back to the form page like this,

Return to users list.

You can use javascript so that page does not have to reload in the browser.

Return to users list.


Matrix Representation of Octonions

Question: Since quaternions $\mathbb{H}$ have a matrix representation as elements of $\text{SU}(2,\mathbb{C})$ as the following
$$   1 \mapsto \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix},\quad \mathrm i \mapsto \begin{pmatrix} \mathrm i_{\mathbb C} & 0 \\ 0 & -\mathrm i_{\mathbb C} \end{pmatrix},\quad \mathrm j \mapsto \begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix},\quad \mathrm k \mapsto \begin{pmatrix} 0 & \mathrm i_{\mathbb C} \\ \mathrm i_{\mathbb C} & 0 \end{pmatrix},
$$
I always wondered if there is also matrix representation of the octonions?
How is the non-associativity realised with matrices?
Comment: You shpuld probably be explicit about the sense in which quaternions have a matrix representation as SU(2,C)... H is an algebra and SU(2,C) is a group!
Comment: Matrix multiplication is associative, so what do you hope for?
Comment: @GrigoryM: I don't hope, I wonder. So the answer is NO?
Comment: What you mean, probably, is that there is a representation of $\mathbb H$ as a real subalgebra of the algebra $M_2(\mathbb C)$ of $2\times 2$ matrices. $\mathrm{SU}(2,\mathbb C)$ has little to do with it.
Comment: @MarianoSuárez-Alvarez: Would $\text{su}(2,\mathbb{C})$ suit better?
Comment: No, because the matrix you are sending $1$ to is not there. It is just $M_2(\mathbb C)$.
Comment: @MarianoSuárez-Alvarez: ah right, I remember: just $i,j$ and $k$ can be represented as elements of $\text{su}(2)$.
Answer: A $\mathbb R$-linear function $\phi:\mathbb O\to A$ to any real associative algebra which is multiplicative and unitary (so that $\phi(xy)=\phi(x)\phi(y)$ for all $x$, $y\in \mathbb O$, and $\phi(1)=1$) has to vanish on the bilateral ideal $I$ generated by the elements of the form $$(x\cdot y)\cdot z-x\cdot(y\cdot z)$$ with $x$, $y$, $z\in\mathbb O$. Now, this ideal is not zero because $\mathbb O$ is not associative, and therefore $I=\mathbb O$, because $\mathbb O$ has no non-trivial bilateral ideals (it is a division thing).
It follows that the map $\phi$ is in fact zero.
Answer: M. Zorn (Abh.Mat.Sem.Hamburg,9,395, 1933) modified matrix multiplication for 2x2 "vector-matrices" with two real-numbers as diagonal entries and two 3d-vectors off the diagonal.
See also Matrix Representation of Octonions and Generalizations by Jamil Daboul and Robert Delbourgo,  (9 June 1999)
Answer: We have two Octonions algebra, one is a division algebra (with no zero divisors) and a split algebra (with zero divisors).
Both are constructed by Cayley-dicson process over a field $F$. If you pick the split algebra of octonions you can show that it is isomorphic to a non-assossiative matrix algebra called Zorn matrix-vector algebra, $M(F)$ where the elements are:
$\left[ \begin{array}{cc}
a &\textbf{x}\\
\textbf{y} & b
\end{array}\right]$, where $\textbf{x,y}\in F^3$.
The addition is defined term by term and the multiplication defined as $\left[ \begin{array}{cc}
a_1 &\textbf{x}_1\\
\textbf{y}_1 & b_1
\end{array}\right]
\left[ \begin{array}{cc}
a_2 &\textbf{x}_2\\
\textbf{y}_2 & b_2
\end{array}\right] =
\left[ \begin{array}{cc}
a_1a_2+\textbf{x}_1.\textbf{y}_2 & a_1\textbf{x}_2+b_2\textbf{x}_1-\textbf{y}_1\wedge\textbf{y}_2\\
a_2\textbf{y}_1+b_1\textbf{y}_2+\textbf{x}_1\wedge\textbf{x}_2 & b_1b_2+\textbf{y}_1.\textbf{x}_2
\end{array}\right]$. Where $\wedge$ denote the exterior product over $F^3$.
It is easy to show that it is non-assossiative. And, as we have the general linear group, the special linear group and the projective linear group over the assossiative matrix algebra, here we have the concept of general linear loop, special linear loop and projective linear loop over M(K).
Answer: The non-associativity is realized by representing 4 of the matrices as ket matrices. To multiply on one side versus the other the ket matrix needs to be converted to its bra representation. This is where the non-associativity comes in.
Comment: With ket matrix you mean the matrix in a vectorized form, like putting coloumns on top of each other?
Comment: Check out octonions on Wikipedia.  You can see under the matrix section. There are 4 ket matrices. All other elements are regular matrices.
Comment: thanks, I missed that on the wiki page...
Answer: I tried to convert different dimensional base units to matrices. The reals are trivial, the complexes are easy, the quaternions are interesting, but solvable and the octonions are so tricky, that it does not work. My matrix looks like this:
$ M_{n m} = i_x^{o-1} o (i_n i_m)$
So e. g.
M = $ \begin{pmatrix} 0 & -1 & -2 & -3 \\ 1 & 0 & -3 & 2 \\ 2 & 3 & 0 & -1 \\ 3 & -2 & 1 & 0\end{pmatrix}$
for the quaternions, it can be for the octonions, too.
But to make sense of all these matrices, we should convert it to another (in this case 4) matrices with full of 0, 1 and -1 numbers. And if we multiplicate them, we get each other, right? I tested it, and it works at quaternions, but so does not at octonions. I am really sorry.
Maybe the multiplication table of octonions is wrong or the previous person was right talking about its problematics of the associativity.

Matrix Representation of Octonions


Why does w3wp.exe comsumes a disproportionate amount of memory?

Question: I'm having a peculiar issue where IIS7 has decided to load a massive amount of memory for an otherwise small web page.  on each request it adds between 2 and 20MB of memory to the process and I can't for the like of me figure out why.  I've looked extensively for memory leaks but I just can't seem to find where this is happening.  Does anyone have some suggestions as to what i can do to isolate the problem?
Comment: You may have better luck on http://stackoverflow.com as this evolves into a programming question.
Comment: To answer your question, asking for suggestions to isolate the problem, i would start with a new empty web-site, feeding a static web-page. Then begin adding content, code, session variables, etc one by one.
Comment: Similar to: http://serverfault.com/questions/78629/which-requests-cause-a-w3wp-process-to-grow-considerably
Comment: Are you putting any objects into the session variables?
Comment: I'm using an out of process session state module.  Therefore it will not affect iis, also the session state is a negligable size <20K so there is no reason that it should affct the memory usge of IIS.
Answer: Finding the source of the memory isn't easy if you don't know how to do it. (Me neither...)
You might want to try to see if you can find out what code causes this:

Does it happen when you create a new application with just a Hello World script?
Does it happen on a specific page or every page in your website?

You probably want to read into: Configuring Recycling Settings for an Application Pool (IIS 7).
And in your case: Recycling when reaching a request limit.
Comment: these are dynamic pages and I've verrified that all connections to the database are closed and disposed of.
Comment: also i shouldn't have to recycle the app after 10 requests.  that's rediculous.
Comment: If recycling doesn't help then try garbage collecting at the end as a temporary solution. I would suggest to use debugging with WinDBG and SOS as this should be easier than native due to the .NET Framework, check http://www.google.be/search?q=ASP.NET+WinDBG+Memory (The First link) and http://geekswithblogs.net/.netonmymind/archive/2006/03/14/72262.aspx (A handy Cheat Sheet). I can remember that Visual Studio or an external application had this kind of features too, but it might be for client applications only.
Answer: What you need is a memory profiler. A good memory profiler, that audits your .NET code, will point you to the objects, and the places in the code where they're allocated, that take the most memory. Without such tool it is very hard, or even impossible, to pinpoint the actual problem (think hours or days, instead of weeks).
You can say that all database connections are closed and disposed off, but is that really true? Do you use a using-statement around all disposable objects (any object that implements IDisposable can leak resources, including memory)? There are code review tools around that can help you analyze your code for you (think ReSharper).
Some profilers:

SciTech Software .NET Memory Profiler (has free eval version)
YourKit profiler, includes excellent memory profiler (has free eval version)
JetBrains dotTrace from the makers of ReSharper (free eval)

If I remember well, I got the best results using YourKit (it gives the smallest overhead, but that's still significant on live servers). Many other memory and performance profilers exist for .NET.
Answer: Have you tried using any .NET memory profilers? That might be less painful than using WinDBG to track what the memory is being allocated to.


Json data is not showing in datatable using ASP.NET

Question: I am using ASP.NET; I am getting the data from the backend as expected, but it is not showing in the web page using a datatable.
Web page:
@{
    ViewBag.Title = "Employee";
}

Employee List

            EmployeeId
            Name
            Age
            Position

JavaScript portion of code (jQuery)
 $(document).ready(function () {
            $('#myTable').DataTable({
                processing:true,
                "ajax": {
                    "url": "/Employee/GetList",
                    "type": "GET",
                    "dataType": "json",
                    "success": function (msg) {
                        console.log(msg.data);
                    },
                    "failure": function (response) {
                        alert(response);
                    },
                    "error": function (response) {
                        alert(response);
                    }
                },
                "columns": [
                    { data: "EmployeeId" },
                    { data: "Name" },
                    { data: "Age" },
                    { data: "Position"},
                ]
            });
        });

Here is the response I am getting from the backend. This is the data I copied from Netword -> Response tab against the endpoint I call to fetch the data
{
    "data": [
                {
                  "EmployeeId": 1,
                  "Name": "Dhruv",
                  "Age": 23,
                  "Position": "Full Stack Developer"
                },
                {
                  "EmployeeId": 2,
                  "Name": "Soni",
                  "Age": 21,
                  "Position": "DBA"
                },
                {
                  "EmployeeId": 3,
                  "Name": "Mike",
                  "Age": 24,
                  "Position": "Frontend Developer"
                },
                {
                  "EmployeeId": 4,
                  "Name": "Bob",
                  "Age": 20,
                  "Position":"SRE"
                }
            ]
}

I am trying to get the data from database and show it to the user using a datatable. I am successfully getting the response back from the database, but the data is not showing inside the table. And I can't figure it out why....
Comment: Could you please share your backend code? How you are sending from your controller? As Json?
Comment: You must avoid using the `success` option the DataTables `ajax` option. See the official documentation for [`dataSrc`](https://datatables.net/reference/option/ajax.dataSrc) which explains why - and what to do instead. This may not be sufficient to get your code working (there may be other additional problems), but it is necessary.
Comment: Hello, have you tried the updated solution? Do you need any further assistance on this?
Answer: Update:3
Controller:
public ActionResult GetList()
        {
            var empList = new List<Employee>()
            {
                new Employee(){ EmployeeId = 1, Name = "A", Age = 19, Position = "Engineer-I"},
                new Employee(){ EmployeeId = 2, Name = "B", Age = 20, Position = "Engineer-II"},
                new Employee(){ EmployeeId = 3, Name = "C", Age = 21, Position = "Engineer-I"},
                new Employee(){ EmployeeId = 4, Name = "D", Age = 22, Position = "Engineer-III"},

            };

          return Json(new { data = empList }, JsonRequestBehavior.AllowGet);
        }

Note: You even can directly return Json(new { empList }) in that case, in your HTML-Ajax you only have to write return msg; not msg.data
View:

Employee List

            EmployeeId
            Name
            Age
            Position

@section scripts {

}

Note: I am returning as return Json(new { data = empList }); so I would receive response as msg.data. Check the response in your browser console as below:

Importantly, be sure about the column case as you can see I am getting it as lower-case so I bind them as like this"data": "employeeId". As you are saying you are getting in Upper-Case as EmployeeId you should then bind as "data": "EmployeeId"
Final Output:

Special Note:
Remember these words forver, If you want to be a great programmer, you must concentrate on :

Debugging
Code readability
Self reading/teaching attitude

Update:2
If you still want to persist with your code: You could do as following:
$('#myTable').DataTable({
                processing: true,
                "ajax": {
                    "type": "GET",
                    "url": "/Employee/GetList",
                    "dataSrc": function (msg) {
                        return msg;
                    }
                },
                "columns": [
                    { "data": "EmployeeId" },
                    { "data": "Name" },
                    { "data": "Age" },
                    { "data": "Position" },

                ]
            });

Issue on your code:
You were defining the column in worng way: you should do it in following way:
"columns": [
                        { "data": "EmployeeId" },
                        { "data": "Name" },
                        { "data": "Age" },
                        { "data": "Position" },

                    ]

Update:2 Output:

Update:
Based on your updated question, its clearly seen that you are ajax calling pattern is incorrect. How your msg.data would be bounded into your "columns": no way. Please try my updated code. Just copy and paste.

I am successfully getting the response back from the database but the
data are not showing inside the table. And i can't figure it out why?

It's because of your row definition in your columns within the datatable.
You would define all of your data members in lower case - like
"columns": [
               { data: "employeeId" },
               { data: "name" },
               { data: "age" },
               { data: "position"},
           ]

Note: UpperCase  EmployeeId, Name etc  in jQuery datatable are causing parsing issues. In addition, please follow the $.ajax({}); calling format as per my demo for better code readability.
Complete example:

            ID
            Name
            Age
            Position

@section scripts {

}

Output:
Comment: public ActionResult GetList()
        {
            using(DBModels db = new DBModels())
            {
                var empList = db.Employees.ToList();
                return Json(new {data = empList}, JsonRequestBehavior.AllowGet);
            }

        }
Comment: Hi @Md Farid Uddin Kiron I tried your code but I am still not getting the data inside the data table
Comment: You can now check the updated answer, try to place them accordingly, check your browser log details. If you still encounter issue, feel free to let me know.


PowerShell error record has empty/incorrect 'InvocationInfo'

Question: I am running a PowerShell script in Azure DevOps, and in the event of a command failing I need to log a warning so that observers can see that the script did not run as expected.
As part of the warning, I wish to output the path to the script and the line number / offset where an exception occurred.
To do this, am using the $_ variable within the catch or a try/catch block.
$command = "New-AzCosmosDBAccountKey -Name {0} -ResourceGroupName {1} -KeyKind {2}" -f $Name, $ResourceGroupName, $keyKind
Write-Verbose ("##[command] {0}" -f $command)
try {
    Invoke-Expression $command
}
catch
{
    Write-Host ("##[warning] {0}" -f $_.Exception.Message -replace "`r`n", ". ")
    Write-Host ("##vso[task.logissue type=warning;sourcepath={0};linenumber={1};columnnumber={2};]{3}" -f $_.InvocationInfo.ScriptName, $_.InvocationInfo.ScriptLineNumber, $_.InvocationInfo.OffsetInLine, $_.Exception.Message -replace "`r`n", ". ")
}

However, for some reason within $_.InvocationInfo, the ScriptName is blank and both ScriptLineNumber and OffsetInLine are set to 1.
If I output $_.ScriptStackTrace I see that there are three messages, and presumably $_ relies on the last message in the stack trace.
at


Exact value of $\tan^{-1}(\sqrt3/3)$

Question: I'm trying to figure out how to find the exact value of $\tan^{-1}(\sqrt3/3)$. I tried doing the following because I couldn't see any points where $\sqrt3/3$ lies on the Unit Circle $$\tan^{-1}(\sqrt3/3)=x$$ $$\tan(x)=\sqrt3/3$$ but from here I'm lost, I thought about maybe multiplying top and bottom by $1/\sqrt3$ but I just ended up with the same thing. Any suggestions.
Comment: To type $\tan^{-1}(\frac{\sqrt{3}}{3})$, type \tan^{-1}(\frac{\sqrt{3}}{3}) in math mode.  To type $$\tan^{-1}\left(\frac{\sqrt{3}}{3}\right)$$ type \tan^{-1}\left(\frac{\sqrt{3}}{3}\right) in display math mode.
Answer: Obviously, the best solution is to rationalize the numerator
$$\frac{\sqrt{3}}{3}=\frac{\sqrt{3}}{3}\cdot\frac{\sqrt{3}}{\sqrt{3}}=\frac{3}{3\sqrt{3}}=\frac{1}{\sqrt{3}}$$
But lets say that completely went by us. One solution may be to try to build  right triangle with an angle $\theta$ such that $$\tan\theta = \frac{\sqrt{3}}{3}$$
Setting $opposite = \sqrt{3}$, and $adjacent=3$, by Pythagoras we have
$$hypotenuse = \sqrt{opposite ^2 + adjacent^2}=\sqrt{12}=2\sqrt{3}$$
Notice that the hypotenuse is exactly twice that of the of the opposite side.

By reflecting this triangle onto itself, we can build an equilateral triangle, giving us an angle of $\theta = \frac{\pi}{6}$
Comment: Interesting (+1)
Answer: $$\tan^{-1}\frac{\sqrt{3}}{3}=\tan^{-1}\frac{1}{\sqrt{3}}=\frac{\pi}6$$
Comment: but how did you go from $$\tan^{-1}\frac{\sqrt{3}}{3}=\tan^{-1}\frac{1}{\sqrt{3}}$$? @GoodDeeds
Comment: Since $\frac{\sqrt{3}}{3}=\frac{1}{\sqrt{3}}$
Comment: @Billy  Observe that $3 = \sqrt{3} \cdot \sqrt{3}$.  Hence, $$\frac{\sqrt{3}}{3} = \frac{\sqrt{3}}{\sqrt{3} \cdot \sqrt{3}} = \frac{1}{\sqrt{3}}$$
Comment: I feel like an idiot, but I definitely see that 100%. How about the $\frac{\pi}{6}$ part @N.F.Taussig
Comment: @Billy What are your starting assumptions? Based on what should the answer be?
Answer: By Pythagoras, the height of an equilateral triangle of unit side length is $\frac{\sqrt 3}{2}$. Conclude from this that $\tan 30^\circ = \frac{1/2}{\sqrt 3 2}=\frac{\sqrt 3}3$.
Answer: The range of the arctangent (inverse tangent) function is $\left(-\frac{\pi}{2}, \frac{\pi}{2}\right)$.  Since
$$\frac{\sqrt{3}}{3} > 0$$
we may conclude that
$$\arctan\left(\frac{\sqrt{3}}{3}\right) \in \left(0, \frac{\pi}{2}\right)$$
so we are looking for an answer in the first quadrant.
Since
$$\frac{\sqrt{3}}{3} = \frac{\sqrt{3}}{\sqrt{3} \cdot \sqrt{3}} = \frac{1}{\sqrt{3}} = \frac{\frac{1}{2}}{\frac{\sqrt{3}}{2}}$$
we are looking for a first quadrant angle $\theta$ with
\begin{align*}
\sin\theta & = \frac{1}{2}\\
\cos\theta & = \frac{\sqrt{3}}{2}
\end{align*}
The only such angle is
$$\theta = \frac{\pi}{6}$$
Hence,
$$\arctan\left(\frac{\sqrt{3}}{3}\right) = \frac{\pi}{6}$$
Answer:
Notice, when $z\in\mathbb{C}$ and $\Re[z]>0$:

$$\arg[z]=\arctan\left(\frac{\Im[z]}{\Re[z]}\right)$$

In your example we can say:

$$\Re[z]=3$$
$$\Im[z]=\sqrt{3}$$

So:
$$z=\Re[z]+\Im[z]i=3+\sqrt{3}i$$
And we now that:
$$\arg[3+\sqrt{3}i]=\frac{\pi}{6}$$
So:
$$\arg[3+\sqrt{3}i]=\arctan\left(\frac{\sqrt{3}}{3}\right)=\frac{\pi}{6}$$

Exact value of $\tan^{-1}(\sqrt3/3)$


Obtaining opposite diagonal of a matrix in Matlab

Question: Let A be an matrix of size [n,n]. If I want to extract its diagonal, I do diag(A).
Actually, I want the opposite diagonal, which would be [A(n,1),A(n-1,2),A(n-2,3),...].
One way to do this is via diag(flipud(A)). However, flipud(A) is quite wasteful and multiplies the time it takes by a factor of 10 compared to finding the usual diagonal.
I'm looking for a fast way of obtaining the opposite diagonal. Naturally, for loops seem abysmally slow. Suggestions would be greatly appreciated.
Comment: possible duplicate of [Is there a function to get the skew diagonal of a matrix in matlab?](http://stackoverflow.com/questions/5201426/is-there-a-function-to-get-the-skew-diagonal-of-a-matrix-in-matlab)
Comment: FYI, the proper term for this is "[anti-diagonal](http://en.wikipedia.org/wiki/Anti-diagonal_matrix)".
Answer: Here is my matrix, produced by A = magic(5)
A =

17    24     1     8    15
23     5     7    14    16
 4     6    13    20    22
10    12    19    21     3
11    18    25     2     9

s = size(A,1)
A(s:s-1:end-1)

ans =
11    12    13    14    15

Comment: slighly faster version: `A(sqrt(end):sqrt(end)-1:end-1)`
Answer: Below is a comparison of all the methods mentioned so far, plus a few other variations I could think of. This was tested on 64-bit R2013a using TIMEIT function.
function [t,v] = testAntiDiag()
    % data and functions
    A = magic(5000);
    f = {
        @() func0(A) ;
        @() func1(A) ;
        @() func2(A) ;
        @() func3(A) ;
        @() func4(A) ;
        @() func5(A) ;
        @() func6(A) ;
        @() func7(A) ;
    };

    % timeit and check results
    t = cellfun(@timeit, f, 'UniformOutput',true);
    v = cellfun(@feval, f, 'UniformOutput',false);
    assert( isequal(v{:}) )
end

function d = func0(A)
    d = diag(A(end:-1:1,:));
end

function d = func1(A)
    d = diag(flipud(A));
end

function d = func2(A)
    d = flipud(diag(fliplr(A)));
end

function d = func3(A)
    d = diag(rot90(A,3));
end

function d = func4(A)
    n = size(A,1);
    d = A(n:n-1:end-1).';
end

function d = func5(A)
    n = size(A,1);
    d = A(cumsum(n + [0,repmat(-1,1,n-1)])).';
end

function d = func6(A)
    n = size(A,1);
    d = A(sub2ind([n n], n:-1:1, 1:n)).';
end

function d = func7(A)
    n = size(A,1);
    d = zeros(n,1);
    for i=1:n
        d(i) = A(n-i+1,i);
    end
end

The timings (in the same order they are defined above):
>> testAntiDiag
ans =
   0.078635867152801
   0.077895631970976    % @AlexR.
   0.080368641824528
   0.195832501156751
   0.000074983294297    % @thefourtheye
   0.000143019460665    % @woodchips
   0.000174679680437
   0.000152488508547    % for-loop

The most suprising result to me is the last one. Apparently JIT compilation is very effective on such simple for-loops.
Comment: I updated the results (I didnt have the laptop plugged in, so CPU throttling made it slower!). My conclusion is that they are very similar, perhaps you are [optimizing](http://c2.com/cgi/wiki?PrematureOptimization) the wrong thing :)
Comment: Thanks for the comparisons and for Knuth's advice!
Answer: The elements you want are easily obtained by indexing. For example, this should do the trick.
n = 4;
A = magic(n)
A =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

A(cumsum(n + [0,repmat(-1,1,n-1)]))
ans =
     4     7    10    13

I could also have used sub2ind to get those element indexes, but this does it a bit more cleanly, though less obvious in how it works.
Answer:

A = magic(6)

A =
35     1     6    26    19    24
 3    32     7    21    23    25
31     9     2    22    27    20
 8    28    33    17    10    15
30     5    34    12    14    16
 4    36    29    13    18    11

b = diag(A(1:length(A),length(A):-1:1))

b =
24
23
22
33
 5
 4


Ambiguous chords in Bach's "Ich dank dir lieber Herre" setting (BWV 347)

Question:
The image above shows, from Bach 371 Chorales, No. 2 "Ich dank dir lieber Herre" in A major, measures 11 and 12.
I'm very confused by this part.
1. first red square, Is that chord I or vi56?
If that is I, non chord tone 'F' is becomes a 7th note(G) in the next chord, and the 7th note goes up in the another next chord.
There is a theory that it is possible to ascend by steps when a resolution sound comes out of the bass of a chord with 7 notes, but I don't know if this applies to the Bach choral as well.
if that is vi56
7th note 'E' goes to 'D' but maybe D is a non chord tone in that chord, but I don't know if the 7th will go to a non-chord tone and can be resolved.
2. second red square, that is I46 or maybe vi7 with out the root?
this just can't figure it out anything..
first time i saw this i think maybe this chord is 'iii'
but if that iii, can't explain how non chord tone 'A' is resolved. because that's not a suspension or anticipation.
if that is I46, I don't know can come out like that.
and maybe vi7 with out root? i think that's not. but that's all i try..
so i appreciate to if you can help this.
Answer: First red box
The first chord is vi[6-5]. The chord on the half beat is viio[6-4], even those the B is missing, with the A service as a non-harmonic pedal tone. Thus, the progression is vi-vii-I.
Second red box
The chord here is a cadential 6-4 chord (I[6-4] or V[6-4] depending on who you're talking to), leading to the V chord on the following beat (not shown in the image).
A note on analyzing Bach in particular and music in general
It is tempting to try to label every single chord, but this is misleading. Bach was not composing this way — he was writing independent melodies, and later on, theorists came along and looked to give analytical explanations to his compositions.
Thus, many of Bach's "chords" are better seen as passing chords, expanding — but somewhat incidental to — a larger harmonic texture. In this light, it can be more productive to look at the first box as an expansion of the preceding V chord, with the A serving as an anticipation of the I chord.
Comment: @guss2222 Although the notes look like IV7, the C# is a melodic, not a harmonic, element. Thus, it's a IV chord with a suspension. This is the difference between just naming chords versus analysis. The other answer, for example, focuses on naming chords, but does not provide a functional analysis of how the music operates. Bach did not write in terms of vertical structures; his priority was independent lines of music. Quartal harmony is an idea that came along much later, and has more to do with chord voicings in, say, jazz, than as a functional form of analysis.
Comment: thank you so much! pedal tone is make sense! (i thought pedal too but i was not sure about viio)
Comment: and you right. V came out next IV7 BUT but can use cadential 6-4 like that?
Comment: i mean can 'IV' came out next cadential I46? not the V?
Comment: You seem to have stumbled on the wrong BWV number.  BWV 254 is _Ach Gott, erhör mein Seufzen._
Comment: Aaron you there?
Comment: @guss2222 It's a bit unusual, but yes, IV can come after cadential I64. I would not consider it a IV7, however. The apparent 7 (C#), I would consider a suspension.
Comment: @Aaron that's not lV7? why not..? so what chord is that? And what do you think another answer from Derion Mukhalfa here? kind a different to your answer.
Comment: @Aaron oh man ok. I think it just would be good to know like that.. thank you.
Answer: First of all the notation I use: y=first invertion; x=second invertion; Q=quartal.
( Vy - V5 ) ( viy - IQ ) ( I - IM7sus2 ) ( vi7no5 - ii7x ) ( iii6y - IVM7 )
Quartal harmony is his own topic, vi to I and I to I are fairly simple, so nothing fancy in here. The last chord is C#m6 intead of A because C# is doubled, which makes us think about it as the tonic, but it still works as V/IV.
Comment: Look, the Alto part in the second measure remains on A, that's why is a pedal point. We don't know if Bach purpously did add a quartal chord, that's only my interpretation as AM7sus4 because if taken D as the root it makes no sense neither G#. Again, at the end of the day even if Quartal or not for me it's like a suspended I chord. It is ii7x because it spells F# D A B which is Bm7 starting on the fifth. C#m6 is the same as A, and A works as the dominant to IV. Keep your Focus on voice leading.
Comment: you sure? i'm not doubt you, just First time hearing this Quartal harmony. and if that is 'ii7x -> iii6y'.  how can explain 'A' is resolved? 7th in ii7x is moving to non chord tone and that non chord tone in iii6y is not a suspension or anticipation. it's messed up
Comment: man. i research that Quartal harmony (Quartal chord).  i think that was not use to bach age.
Comment: Quartal chords is when you build chords by stacking fourths instead of traditional triads. But that A it´s a pedal tone in that whole measure it doesn´t needs to be resolved, there´s not such such thing as a "messed up" when moving to a neighbour chord.
Comment: Quartal harmony is a really overlooked topic and there´s no real works about it. It is something we use to call things like C7sus4. Also in Mozart´s age augmented chords weren´t a thing and in one of his works he uses the four existent augmented triads.
Comment: Bach had a greater understanding of harmony than you and me together. Where we see chords he saw voices, independent melodies dancing together and that´s why he did what others couldn´t.
Comment: so you sure he use Quartal chords and 'A' in [ ii7x->iii6y->IV7 ] is pedal tone? but there is no tie and the note 'A' is not connected and are separated. I don't know pedal tone can come out that way.
Comment: Are you saying that the pedal tone 'A' starts at the first red box and continues with the voice part shifted up to IV7? and again, I don't know pedal tone can come out that way.
Comment: your analysis make sense too. i just wanted to know a pedal tone is can use like that way. and i think possible to different analysis. I will remember how to analyze like you. you teach me a lot, thank you so much.
Comment: Actually it is more common to see pedal tones in the tenor and bass voices, but in alto it's a bit strange. However if Bach does so do I.


how to display block div on hover a tag

Question: how to open div tag on hover a tag
Service is id of a tag
Services is id of div tag
My Html Code is

Services

Hello

and my css code is this
#Services
    {
        display: none;
    }

    #Service:hover + #Services
    {
        display: block;
    }

Comment: The + combinator is for sibling selectors, and `#Service` and `#Services` are not siblings... `#Service` is nested in a list, you would need to adjust your markup for this to work.
Answer: #Services isn't a sibling of #Service, so the + selector won't match it.
Check this fiddle for modified markup which makes the two siblings. You will need to style it accordingly.

Services

Hello

Answer: Add the #services as the siblings element of the #service. Then the code would work.
Such as this:

  Hyperlink

Some text

how to display block div on hover a tag


form textfield name -value changed and does not validate any more

Question: i have a checkout-page (drupal commerce) form with an address section generated by the module addressfield.
currently all text-inputfields have this markup-structure:
<input class="last-name" id="edit-last-name" name="customer_profile_billing[commerce_customer_address][und][0][last_name]">
class + id + name
in this config they validate.
if i change the value of the name attribute the form doesnt validate anymore, the form says:

field XY is required

the form-validator obviously doesnt recognise my inputs.
question: how can i get the validation process to work with a modified name attribute?
Comment: The real question is "why do you need to modify the name attribute?" :) It's probably going to be easier to find a way around _that_ issue than it is to override the core form validation. Are you changing the name to make the element easier to find in jQuery code for example?
Comment: if would i could leave it like this, i dont need this name attribute anywere. but, i like things clean. i cant get it why `form()` gets upset if i change that attribute.
Answer: It all happens in drupal_validate_form().

Validates user-submitted form data in the $form_state array.

If I could offer some advice - have a re-think. Changing the name attribute of form elements, especially on those that are part of field widget forms, is a good way to get unexpected results. The name on an input is completely irrelevant to the page, so changing it doesn't actually get you anything. If you're trying to change it so you can target the elements using JS, for example, I'd advise changing your JS code rather than the form markup. Trust me when I say it will be easier.
The only valid situation I know of to override the name of an element is when you need to provide multiple submit buttons on a single form that carry out the same action, but in a different context.
Comment: thank you clive for your professional comment on this. i know, the `name` attribute is not relevant for the page, i just want to know were these amounts of ids, classes and divs come from and which of them are essential to the site and which are "just in case someone could need them". also i want to learn how much control can i have over the form markup.
Comment: @user19578 Short answer to that is: you can have 100% control over your form markup, but the more you change from the default, the more code you'll have to write. There isn't a single place where classes, ids, attributes, etc get set; that can happen in any number of theme functions, element theme functions, element process functions, theme preprocess functions, form theme/preprocess functions, and a ton of other places. You really have to follow the trail down for the specific form you're dealing with. After a while you just develop an instinct of where to look
Comment: yes i unterstand what you mean. 100% control will not be my goal but i am not happy with the standard markup of `form.inc` so i digg in and learn a bit how this thing works but this `name` thing is not so easy. seems before validating the `$form_state` get cached or something. maybe you can leave some words on the validating process pls?
Comment: That's quite tricky, it's a long process :) Could you outline exactly what you'd like to accomplish, and maybe why as well? It would just help to understand what needs to happen, and make it easier to know which functions to push you towards. If you'd be so good as to edit the question and add that information I'd be glad to revise my answer with the extra info. To start, [`_form_builder_handle_input_element()`](https://api.drupal.org/api/drupal/includes%21form.inc/function/_form_builder_handle_input_element/7) will probably be of interest, that's where the `#name` property is set for elements
Comment: extend my question description for maybe a better understanding.


How to identify the formula for calculating Cohen's d?

Question: If I am just asked to calculate Cohen's d what do I do?
Do I take the sample mean from the population mean and then divide that by the sample std deviation?
Comment: http://en.wikipedia.org/wiki/Effect_size#Cohen.27s_d.
Answer: The denominator for Cohen's d isn't just one sample's standard deviation, unless that's all you have. What data do you have? It sounds like a one-sample problem where you're given both a sample mean $\bar x$ and the population mean $\mu$, and asked to calculate the effect size of the difference.
According to Wikipedia:

What precisely the standard deviation s is was not originally made explicit by Jacob Cohen because he defined it (using the symbol "σ") as "the standard deviation of either population (since they are assumed equal)".[7]
  Other authors make the computation of the standard deviation more explicit with the following definition for a pooled standard deviation[16] with two independent samples.
  $$s = \sqrt{\frac{(n_1-1)s^2_1 + (n_2-1)s^2_2}{n_1+n_2-2}}\\s_1^2 = \frac{1}{n_1-1} \sum_{i=1}^{n_1} (x_{1,i} - \bar{x}_1)^2$$

So again, think about what descriptive statistics you already have. If you have sample means and SDs for two samples, this ought to be pretty straightforward for you (and you should explain what you've tried so far). If not, do you have a population standard deviation (denoted as $\sigma$)? It sounds like you have a sample standard deviation at least...If that's all you have to work with, I guess that wouldn't leave you with much choice.
On the other hand, if you have a choice between a population SD parameter and a sample SD statistic, do you think it would do any good to pool these? Can you see why it might make sense to just assume one standard deviation is equal to the other? Which one makes more sense to use this way?

References
  7. Cohen, J. (1988). Statistical power analysis for the behavioral sciences (2nd ed.). Lawrence Erlbaum Associates.
  16. Hartung, J., Knapp, G., & Sinha, B. K. (2008). Statistical meta-analysis with application. Hoboken, NJ: Wiley.


Is there a successor project to Omega 4?

Question: I'm a big fan of the Omega base theme, trying to make sense of what's going on with that project.
What I'm trying to do, is work with something similar to Omega 4 that is actively maintained on both 7 and 8 and will be capable of being upgraded to Drupal 8 in future.
I've read that there was a public falling out among the maintainers and that Omega 5 is progressing in a very different direction with different aims to Omega 4. I've also read that the Omega 4 maintainers are giving it minimal maintainence with many hints that their efforts will be focussed on other projects under other namespaces, and there have been no new dev releases since July 2015:

Omega 4.x is still minimally maintained (I am committing bug-fixes and other critical / major patches). However, I am not interested in further moving on with anything under this namespace as stated previously in other issues. The reasons for that are well known and have been publicly discussed... There won't be any extended effort from me (and probably not from Matt either) to expand on the existing functionality of 4.x or even work on a new version... I will keep maintaining the 4.x version of course though so you can totally feel safe when using that at least.

Is there a new project that continues what Omega 4 was trying to achieve under a new namespace, that will be actively maintained on Drupal 7 and 8?

I've seen Khan described as "the omega 4.x successor for drupal 8", but it's had no work since 2014 and its project page is... baffling. It looks more like a Drupal community in-joke than a serious project. There's a thread with many people asking about this, but no clear answers.
Answer: I found what looks like an explanation from 2016. It looks like Omega 4 is not going anywhere.

...both new Omega versions (7.x-5.x, 8.x-5.x) probably have nothing in common with (7.x-4.x) and are not the successor of Omega 4.
The successor to (7.x-4.x) is new project Khan so all the questions about that should be posted there. Truth to be told, there is not much activity there, since.
So if you wish to make some sort of continuation of current 4.4 code base to D8, probably you will have to do it yourself. Personally, I do not think it will make much sense as the differences between D7 and D8 would not leave much in common.

The same user asked what the status of Khan is two months ago and hasn't received any reply. In another thread, the maintainer posted that Khan is postponed indefinitely:

...This is a serious project but since I am currently focusing on GraphQL for Drupal you can consider it postponed until I am done with the first release of that module.

So it seem fair to conclude that there is no Drupal 8 successor to Omega 4 at time of writing.

Life is too short for drama, so I personally am going to (reluctantly) drop Omega and switch over to Bootstrap.
Comment: In that issue fubhy also linked to a github repo for kahn angular that no longer exists and his kahn boilerplate repo hasn't been used for a couple of years.


Display Only the Product Add to Cart Button

Question: Drupal 8.4.2
On both the commerce-product and the node--product level, I can get the add to cart button to show, but it also renders the product variation fields as well.
If I have content that does not have variations and only a single price, how can I render just the "add to cart button" in the commerce form?
I've been all through config via the admin panel and feel I am just missing something obvious???
My question would be: How do you render just the add to cart button on the product level, or node level (via reference) via the admin panel?
Comment: Instead of writing "latest release of Drupal 8 as of date", please give the version number (8.4.2).  Writing it with the date will make your question harder to understand for readers as time passes.
Comment: Some notes that might be helpful: [Add to cart config is here](https://drupal.stackexchange.com/questions/250504/where-is-the-add-to-cart-configuration), but it doesn't let you choose to show or hide the variations.  So I assume you have to theme the form, but [I haven't been able to figure out how to theme the add to cart form](https://drupal.stackexchange.com/questions/250509/how-to-print-the-product-variation-separately-from-the-submit-pay-button-in-a-co).
Comment: Updated question with Drupal version. And I was wondering the same and I guess I will look more at theming the form... I'll post anything I may find, thanks!
Answer: Yes the link above resolved my question: Where is the "add to cart" configuration?.
There is a sub-menu link that I was missing.

This allowed me control of the display of the form items on both the product and node level. With this I am able to choose to show the variations and quantity fields. Thanks Patrick Kenny!


Pesquisar conteúdo dentro das parâmetros da tag

Question: Estou criando uma barra de busca aonde o usuário vai digitando e vai filtrando em tempo real o conteúdo das
. Tenho um código parecido:
HTML

Conteudo 1

Conteudo 2

Conteudo 3

jQuery

Esse está funcionando como eu preciso, mas quero colocar um conteúdo dentro das tags  e ele também conseguir filtrar por eles. Então meu HTML ficaria mais ou menos assim:
HTML

Conteudo 1

Conteudo 2

Conteudo 3

Ou seja, se o usuário também digitar Rio de Janeiro achará o Conteúdo 2
Answer: Nesse caso precisas de mudar a lógica para:
if ($(this).find('a').data('cidade').toLowerCase().search(value) > -1) {

$(this).find('a') vai buscar o elemento
.data('cidade') vai buscar o valor desse campo data-

function filterMap(element) {
  var value = $(element).val().toLowerCase();

  $("#list-search-filter-map > li").each(function() {
    if ($(this).find('a').data('cidade').toLowerCase().search(value) > -1) {
      $(this).show();
    } else {
      $(this).hide();
    }
  });
}

<input onKeyUp="filterMap(this)" />

Conteudo 1

Conteudo 2

Conteudo 3

Comment: Acho que AP quer que filtre pelo data e pelo texto dentro do link @Sergio
Comment: @LucasCosta o AP escreveu _"Ou seja, se o usuário também digitar Rio de Janeiro achará o Conteúdo 2"_, daí esta sugestão.
Comment: "e ele também conseguir filtrar por eles".  Dessa forma se ele digitar Rio de Janeiro achará o Conteúdo 2, mas se Digitar Conteúdo 2 não achará nada
Comment: @LucasCosta ah, ok. Então nesse caso seria assim: https://jsfiddle.net/01ycfygj/ vou editar depois de saber melhor o que o AP quer.
Answer: Só trocar o $(this).text() por:
$(this).html()

Fica assim:

$('#search').keyup(function() {
    filterMap(this);
});

function filterMap(element) {
  var value = $(element).val().toLowerCase();

  $("#list-search-filter-map > li").each(function() {
    if ($(this).html().toLowerCase().search(value) > -1) {
      $(this).show();
    }
    else {
      $(this).hide();
    }
  });
}

Conteudo 1

Conteudo 2

Conteudo 3

<input type="text" id="search">
Comment: Obrigado @JuniorNunes


Does the composition of orthogonal projections have norm $1$?

Question: Let $X$ a Hilbert space, and $P_1, P_2: X \to X$ be orthogonal projections.
Consider $P = P_2P_1P_2$. Is it always the case that $\|P\|=1$?
Certainly $\|P\| \leq \|P_2\|\|P_1\|\|P_2\| = 1$, but does the reverse inequality always hold?
Answer: It is not necessarily the case the $P$ has norm one, and in fact $P$ could even be the zero map. This happens for instance if $P_2=I-P_1$.
Answer: No; consider the simple case when $X = \mathbb{R}^2$ and $P_1$ is the projection onto the $x$-axis, and $P_2$ is the projection onto the $y$-axis. What is the composition of $P_1$ and $P_2$?


Where is $(x-1)(x+1/2)\geq0$

Question: The solution is $x\geq 1$ or $x\leq-(1/2)$
However, I do not understand why you flip the sign of $-1/2$ but not $1$.
Comment: It is not just a question of "flipping" signs... For the product of two numbers to be positive you require both to have the same sign. Can you carry on?
Comment: ...You flip the sign of both... -1 turns into 1 and 1/2 turns into -1/2
Comment: That have to do with the fact that the roots of $(x-m)(x-n)$ are $m$ and $n$. Here you can write $(x-1)(x+1/2)$ as $(x-1)\big(x-(-1/2)\big)$, so the roots are $1$ and $-1/2.$
Answer: The solutions to $(x-a)(x-b)=0$ are $x=a$ and $x=b$. So in this case, the solutions to $(x-1)(x+1/2)=0$ are $x=1$ and $x=-1/2$. All fine, but we want to solve the inequality, which means we're looking for a region (or set of regions).
What does $(x-1)(x+1/2) \ge 0$ mean? It means, when you multiply two numbers ($x-1$ and $x-1/2$) together, you get something positive. What multiplies to give a positive number? Either two positive numbers, or two negative numbers. So we're looking for the regions where either $x-1$ and $x+1/2$ are both positive, or they're both negative.
If $x$ is really large and positive, then adding or subtracting something as small as $1$ or $1/2$ isn't going to change much, so both the quantities will be positive. So our inequality is true over on the right-hand side of the number line. Then where does it change? Presumably where one of the two quantities flips sign - so it'll be at either $x=1$ or $x=-1/2$, and coming in from the right the first one we'll hit is $x=1$. So for $x \ge 1$, our inequality is true.
Then between $x=-1/2$ and $x=1$, we know that $x-1 < 0$ but $x + 1/2 > 0$, so we're multiplying a positive and a negative to get a negative, so our inequality isn't true any more. But then, going further, once we pass $x = -1/2$, we hit another change of sign, as $x + 1/2$ becomes negative as well. Now we're multiplying two negatives together, giving a positive, so our inequality is once again true for $x \le -1/2$.
In general, to solve these kinds of inequalities, you can find the boundaries where the sign is likely to flip - generally where the function is either zero or has an asymptote - and test values on either side of those boundaries to see if the inequality holds. For example, in this case, the boundary points are $x=1$ and $x=-1/2$, so we could test $x=-1$, $x=0$ and $x=2$ to prove that only the middle one (and hence the region between the two points) fails the test.
Answer: You have that the original equation is $(x-1)(x+\frac{1}{2})\geq 0$. Since it is already factored we  can easily see where the zeroes of this function which are at $x=1$ and $x=-\frac{1}{2}$. So now just plot these points on a number line.

Now you pick a point in each interval to test whether the inequality remains positive or negative. Test $x=-1,x=0,x=1.5$ where your intervals are $[-\infty,\frac{-1}{2}]$, $[\frac{-1}{2},1]$,$[1,\infty]$. I'm sure you see how I got these intervals. And from here you can see the inequality remains true on $[-\infty,\frac{-1}{2}]\cup [1,\infty]$. This can be written as $x\leq \frac{-1}{2}$ or $x\geq 1$.(We include x=1 and x=1/2 since the inequality remains true at the zeroes).
Answer: Notice that if $x = 1$ or $x=-1/2$, then
$$(x-1)(x+1/2)=0.$$
This is a degree two polynomial so it can have at most two roots. Thus, if a single point in each of $(\infty, -1/2)$, $(-1/2,1)$, and $(1,\infty)$ is positive, then then $(x-1)(x+1/2)$ is positive on that whole interval. Similarly, if a point is negative in one of those three intervals, then $(x-1)(x+1/2)$ is negative on that entire interval.
So we must check a point in each interval:
$x < -1/2$: Let's check -1 because that easy. We have $(-1-1)(-1+1/2) = 1 > 0$.
$-1/2<x<1$: Let's check 0 because that easy. We have $(0-1)(0+1/2) = -1/2 < 0$.
$1<x$: Let's check 2 because that easy. We have $(2-1)(2+1/2) = 5/2 > 0$.
Thus whenever $x\geq -1/2$ or $x\geq 1$, we have that $(x-1)(x+1/2)$ is nonnegative.
Answer: Given: $(x-1)(x+\frac 12)\geq 0$, find the domain of $x$.
For the product to be non-negative, we require both factors to the same sign, or at least one to be zero
So we need either: $[(x-1) \geq 0 \bigwedge (x+\frac 12) > 0]$, or: $[(x-1)< 0 \bigwedge (x+\frac 12) \leq 0]$.
Which is to say: $[(x \geq 1) \bigwedge (x \geq -\frac 12)]$, or: $[(x\leq 1) \bigwedge (x \leq -\frac 12)]$.
Now: $(x \geq 1) \bigwedge (x \geq -\frac 12) \implies (x\geq 1)$
Likewise: $(x\leq 1) \bigwedge (x \leq -\frac 12) \implies (x\leq -\frac 12)$
So the solution is: $(x\geq 1)$ OR $(x\leq -\frac 12)$
Answer: The solution is actually $x \geq 1$ OR $x \leq -\frac{1}{2}$. Simple logic would dictate that both can't be true simultaneously so you shouldn't put "and" there.
There are a few ways to look at this.
One is graphically. Consider the function $y = (x-1)(x+\frac{1}{2})$. Sketch the curve like this: http://fooplot.com/#W3sidHlwZSI6MCwiZXEiOiIoeC0xKSh4KzAuNSkiLCJjb2xvciI6IiMwMDAwMDAifSx7InR5cGUiOjEwMDB9XQ--
Note that when the function is non-negative (i.e. on or above the y-axis), the x-values have to lie either to the left of the left-most x-intercept or to the right of the right-most x-intercept. This explanation is a little unwieldy but looking at the graph should make it clear.
The other way is simply to consider the properties of real numbers when you multiply them. To get a positive product, either both numbers have to be positive, or both numbers have to be negative. That gives:
Case 1:
$(x \geq 1) \wedge (x\geq -\frac{1}{2})$
(the symbol $\wedge$ is equivalent to "AND" in logic).
Those two conditions reduce to simply $x \geq 1$ because this satisfies both possibilities.
Case 2:
$(x \leq 1) \wedge (x\leq -\frac{1}{2})$
and again, these two conditions reduce to simply $x \leq -\frac{1}{2}$
(You can see the reason why two conditions reduce to one in these cases by drawing a simple number line).
Since either of the two possibilities can be true for the inequality to hold, there is an OR in the answer. So the solution is $(x \geq 1) \vee (x \leq -\frac{1}{2})$.
(The $\vee$ symbol refers to the logical OR).

Where is $(x-1)(x+1/2)\geq0$


Derivative of exponential functions

Question: I'm having trouble for the derivative of this exponential function which looks difficult. I have used the quotient rule and chain rule to solve for $0.6^x$ but its still wrong.
$$P(x)= \frac{1864}{1+49\times (0.6)^x}$$
Thanks for taking a look
Comment: use the representation $0.6^x=e^{ln(0.6)x}$
Comment: $$P'(x)=-\frac{1864\times\frac{d}{dx}\left(1+49\times(0.6)^x\right)}{(1+49\times(0.6)^x)^2}=\\=-\frac{1864\times49\times\ln(0.6)\times(0.6)^x}{(1+49\times(0.6)^x)^2}$$
Comment: Thank you Sassatelli, I understand it now
Answer: we have after simplifications $$P'(x)=-91336\,{\frac { \left( 3/5 \right) ^{x}\ln  \left( 3/5 \right) }{
 \left( 1+49\, \left( 3/5 \right) ^{x} \right) ^{2}}}
$$

Derivative of exponential functions


huge pages header file on centos is zero bytes

Question: I am trying to use the huge page API in Linux CentOS, the header file hugetlbfs.h is empty (i.e.: it exists, but it is zero bytes).
/usr/src/kernels/2.6.32-358.14.1.el6.x86_64/include/config/hugetlbfs.h

Does anyone have a solution?
Alternatively, how do you use transparent huge pages to enable huge pages for an application without code changes?
Answer: That particular file is part of the package kernel-devel-2.6.32-358.14.1.el6.x86_64. On a later system I have to hand it is 0 bytes too.
There is a package called libhugetlbfs-devel which contains /usr/include/hugetlbfs.h that's probably the package that you want to install.
For future reference the yum command can be used to search for files e.g.
yum provides */hugetlbfs.h

will search for and report the names of packages that contain the file anmes hugetlbfs.h


How to manage implicit groups in record rules?

Question: I am currently learning how to use Odoo. I am doing the following tutorial and i am at the advanced topic ACL And Records rules at the Record Rules part.
I produced the following .xml file by doing the tutorial from the beginning
<?xml version="1.0" encoding="utf-8"?>
<odoo>

    <record id="estate_group_user" model="res.groups">
        <field name="name">Agent</field>
        <field name="category_id" ref="base.module_category_real_estate_brokerage"/>
    </record>

    <record id="estate_group_manager" model="res.groups">
        <field name="name">Manager</field>
        <field name="category_id" ref="base.module_category_real_estate_brokerage"/>
        <field name="implied_ids" eval="[(4, ref('estate_group_user'))]"/>
    </record>

    <record id="estate_user_rule" model="ir.rule">
        <field name="name">Agent rule</field>
        <field name="model_id" ref="model_estate_property"/>
        <field name="perm_create" eval="False"/>
        <field name="perm_unlink" eval="False"/>
        <field name="groups" eval="[Command.link(ref('estate.estate_group_user'))]"/>
        <field name="domain_force">[
            '|',
            ('salesman_id','=', user.id),
            ('salesman_id', '=', None)]</field>
    </record>

</odoo>

The idea is to create user groups in an application that manages real estate properties, an "Agent" group and a "Manager" group.
The instruction is to create a rule that allows agents to see or modify only properties for which they are the sellers or that do not have sellers.
What I don't understand is that previously in the tutorial it says :  The estate_group_manager group needs to imply estate_group_user
which led me to add the following line in the group manager:  <field name="implied_ids" eval="[(4, ref('estate_group_user'))]"/>
The consequence of this is that a user who is in the Manager group is also in the Agent group. The rule will therefore also apply to managers.I guess this problem is expected, as it is written in the tutorial:

Verify that your real estate manager(s) can still see all properties. If not, why not? Remember:
The estate_group_manager group needs to imply estate_group_user.

This is exactly my problem.
I don't understand what is the solution expected by the tutorial. It works by deleting <field name="implieds_ids"... but I have the impression that this is not the right thing to do.
Thank you in advance for your answers.
Answer: As odoo's tutorial says, a good practice while creating group roles hierarchy is to let powerful roles inherit minor roles.
This means your manager group will also inherit agent visibility rules.
To avoid this, you need to override that visibility role only for manager group.
<record id="estate_user_rule" model="ir.rule">
        <field name="name">Agent rule</field>
        <field name="model_id" ref="model_estate_property"/>
        <field name="perm_create" eval="False"/>
        <field name="perm_unlink" eval="False"/>
        <field name="groups" eval="[Command.link(ref('estate.estate_group_user'))]"/>
        <field name="domain_force">[
            '|',
            ('salesman_id','=', user.id),
            ('salesman_id', '=', None)]</field>
</record>

<record id="estate_manager_rule" model="ir.rule">
        <field name="name">Manager rule</field>
        <field name="model_id" ref="model_estate_property"/>
        <field name="perm_create" eval="True"/>
        <field name="perm_unlink" eval="True"/>
        <field name="groups" eval="[Command.link(ref('estate.estate_group_manager'))]"/>
        <field name="domain_force">[]</field>
</record>

Comment: That's because usually in Odoo such "all records" domains are `[(1, '=', 1)]`.
Comment: It works, thank you.  The lines `perm_create` , `perm_unlink` are not necessary because it is implicitly `True` if I understood correctly, but it will help to understand when I will come back in this part. What confuses me is that throughout the tutorial I had taken the habit on my IDE to search in the Odoo source code, examples as they advise, but I did not see any use case  `[]` . Thanks for your help.
Comment: There should be a lot of examples like in sales, project or hr apps.
Comment: I must be searching wrong then, CTRL + SHIFT + F in IntelliJ Ultimate, I search "In Project" , `"domain_force">[]` , the only example it finds is the one I just filled.
Comment: Another interesting and probably important hint: these "group rules" (ir.rule with group and therefor not global) are logically combined OR, that's why the manager rule works that easy.
Comment: And there, magic! There are a ton of examples. Thank you.


Unable to read superblock on virtual server

Question: After booting ubuntu 14.10 I got log output like this
[1377286.486802] EXT4-fs (sda2): unable to read superblock
I can login and use the machine but I guess something is wrong.
Some diagnostics using fdisk, dumpe2fs and e2fsck were made.
How bad is this and what should/can be done?
sudo fdisk -l
Disk /dev/sda: 16 GiB, 17179869184 bytes, 33554432 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x71f43c62

Device     Boot  Start      End  Sectors  Size Id Type
/dev/sda1  *      2048   499711   497664  243M 83 Linux
/dev/sda2       501758 33552383 33050626 15.8G  5 Extended
/dev/sda5       501760 33552383 33050624 15.8G 8e Linux LVM

Disk /dev/mapper/Ubuntu--vg-root: 11.8 GiB, 12624855040 bytes, 24657920 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/mapper/Ubuntu--vg-swap_1: 4 GiB, 4294967296 bytes, 8388608 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

sudo dumpe2fs /dev/sda2
dumpe2fs 1.42.10 (18-May-2014)
dumpe2fs: Attempt to read block from filesystem resulted in short read while trying to open /dev/sda2
Couldn't find valid filesystem superblock.

sudo e2fsck -f /dev/sda2
e2fsck 1.42.10 (18-May-2014)
e2fsck: Attempt to read block from filesystem resulted in short read while trying to open /dev/sda2

Could this be a zero-length partition?

Comment: I just installed Ubuntu 15.10 server on an ESXI host. The default configuration left me with the exact same situation.
Answer: Well, yeah, you're trying to mount an extended partition, which is never going to end well -- there is no filesystem on that partition.  What partition did you want to mount, instead?
Comment: Also he needs to activate logical volumes.
Comment: There's no indication that the LVs aren't active.
Comment: Do you mean that I got the log message because the system have tried to mount /dev/sda? My guess in that case is that /dev/sda5 only should be used. From where would such a wrong mount operation come from? Are there a script where I possibly could disable it?
Comment: No, `/dev/sda5` shouldn't be used, because it's an LVM PV, not a filesystem.  A wrong mount operation happens when the system is misconfigured.  Whatever you misconfigured, undo that.
Comment: I just installed Ubuntu 15.10 server on an ESXI host. The default configuration left me with the exact same situation.