TYPO3 Render FLUID Template in Backend

Question: I have an extbase extension with this TCA:
$GLOBALS['TCA']['tt_content']['types']['list']['previewRenderer']['items_item']
= \Vendor\Name\Backend\Preview\PreviewRenderer::class;

and this tsconfig:
mod.web_layout.tt_content.preview.list.items_item = EXT:EXT/Resources/Private/Templates/Preview/Items.html

Everything works well if i write the complete Code in this template file. But if i change it and use Partials like  this:
<f:render arguments="{_all}" partial="Preview/List"/>

I only get the following error:
Error while rendering FluidTemplate preview using /typo3conf/ext/EXT/Resources/Private/Templates/Preview/Items.html The Fluid template files "" could not be loaded.

How can i set the Partial and Layout path?
Ive tried ist with module via typoscript but it doesnt work.
Answer: It depends on what your PreviewRender is doing.
The StandardContentPreviewRenderer  supports only a template-file, no layouts, no partials. It's using a FluidStandaloneView and only setting setTemplatePathAndFilename() without setting paths for other parts of the template (renderContentElementPreviewFromFluidTemplate()):
 protected function renderContentElementPreviewFromFluidTemplate(array $row): ?string
 {
     $tsConfig = BackendUtility::getPagesTSconfig($row['pid'])['mod.']['web_layout.']['tt_content.']['preview.'] ?? [];
     $fluidTemplateFile = '';

     if ($row['CType'] === 'list' && !empty($row['list_type'])
         && !empty($tsConfig['list.'][$row['list_type']])
     ) {
         $fluidTemplateFile = $tsConfig['list.'][$row['list_type']];
     } elseif (!empty($tsConfig[$row['CType']])) {
         $fluidTemplateFile = $tsConfig[$row['CType']];
     }

     if ($fluidTemplateFile) {
         $fluidTemplateFile = GeneralUtility::getFileAbsFileName($fluidTemplateFile);
         if ($fluidTemplateFile) {
             try {
                 $view = GeneralUtility::makeInstance(StandaloneView::class);
                 $view->setTemplatePathAndFilename($fluidTemplateFile);
                 $view->assignMultiple($row);
                 if (!empty($row['pi_flexform'])) {
                     $flexFormService = GeneralUtility::makeInstance(FlexFormService::class);
                     $view->assign('pi_flexform_transformed', $flexFormService->convertFlexFormContentToArray($row['pi_flexform']));
                 }
                 return $view->render();
             } catch (\Exception $e) {
                 $this->logger->warning('The backend preview for content element {uid} can not be rendered using the Fluid template file "{file}"', [
                     'uid' => $row['uid'],
                     'file' => $fluidTemplateFile,
                     'exception' => $e,
                 ]);

                 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['debug'] && $this->getBackendUser()->isAdmin()) {
                     $view = GeneralUtility::makeInstance(StandaloneView::class);
                     $view->assign('error', [
                         'message' => str_replace(Environment::getProjectPath(), '', $e->getMessage()),
                         'title' => 'Error while rendering FluidTemplate preview using ' . str_replace(Environment::getProjectPath(), '', $fluidTemplateFile),
                     ]);
                     $view->setTemplateSource('<f:be.infobox title="{error.title}" state="2">{error.message}</f:be.infobox>');
                     return $view->render();
                 }
             }
         }
     }
     return null;
 }

If you want more advanced features in your preview, you have to extend/override this method.

Update:
StandaloneView extends TYPO3\CMS\Fluid\View\AbstractTemplateView, so you have also those setters:

setTemplate($templateName)
setTemplatePathAndFilename($templatePathAndFilename)
setTemplateRootPaths(array $templateRootPaths)
setPartialRootPaths(array $partialRootPaths)
setLayoutRootPaths(array $layoutRootPaths)

So setting paths for partials in your renderContentElementPreviewFromFluidTemplate() should solve it:
 $view->setPartialRootPaths([
   \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName('EXT:extensionfolder/Resources/Private/Partials'),
 ]);

Comment: Yes im using the StandardContentPreviewRenderer. How can i extend this to set the paths for my files?
Comment: Just add `$view->setPartialRootPaths(['EXT:.../Resources/Private/Partials/']);`. Julian also pointed it out in his updated answer.

TYPO3 Render FLUID Template in Backend


Update Grub In Another filesystem

Question: My cloud server hosted in Rackspace stopped working after I installed some GUI application in Ubuntu 12.04 which automatically installed it's dependency package ubuntu-desktop (or some other similar (GUI) package).
Actually, that happened 2 weeks ago.
But today is the first time I'm rebooting my server after ubuntu-desktop (or a similar package) was installed, and I realized the webserver cannot boot as it does not have enough RAM to load the GUI (and it doesn't have a graphical device neither) - It frezes after printing "Loading Boot screen" (or something like that) into the terminal.
To fix it, I have access to Rescue Mode in Rackspace, where I can access the filesystem of my server without actually booting it, so I can tweak configs here and there before turning it on.
I did some research and saw that I can force console mode changing Grub configuration from GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" to GRUB_CMDLINE_LINUX_DEFAULT="text". But this change requires running update-grub which I can't, because I can only access the server filesystem, but not log into it to run commands.
Do you guys understand my problem? Am I clear enough? Sorry about my bad English, i'm still learning it.
So, here's my question:
How can I update grub without being logged in a server? Is that even possible? If not, is there any other way to force boot into text mode by only tweaking configuration files and thus not having to log into the server?
Thanks.
Answer: Yay!
I got it to work by manually editing /boot/grub/grub.cfg on the mounted filesystem and replacing the single occurrence of "quiet splash" to "text". That way, update-grub was not needed.
It's not an elegant solution, but it worked.
Now I'm able to connect normally through SSH to my server again. I'll later run update-grub so I can make sure this manual file edit won't have any side effects.
So, here's what I learned today: don't install a GUI on those cheap low performance cloud servers because they won't have enough resources to boot, making things difficult to fix.
Comment: you shouldn't have to run update-grub.  The manual edit should be just fine.
Comment: Thanks @mdpc. Is grub.conf just an intermediate configuration file for the sake of organization and clearness? Is it always safe to make changes directly into grub.cfg?
Comment: grub.cfg is the control file that grub consults as it runs through its paces at reboot.
Comment: `grub.cfg` is completely generated by `update-grub`, so any changes you make there will get overwritten. Your solution of editing `grub.cfg` to get the system to boot and then running `update-grub` is correct though.
Answer: Hmmm.....Is rescue mode basically a Linux single user root shell?  If so, try running the program from the mounted filesystem.  I assume that your mounted disk contains the /boot area.
There also might be a grub on the rescue image for you to run to fix the external disk.
At worse, contact Rackspace for guidance.
Comment: First: the Rescue Mode is a different server that I loggin as root, that I can access my regular filesystem by mounting it. But running update-grub will only update the grub for this specific "Rescue Mode special server", not my real server.
The bad thing is that I don't have the Rackspace managed plan, as they won't fix stuff inside my server, you know? I have to pay more for them to do that.
Comment: I don't know if I was clear, but after logging into the special Rescue Mode server, I can mount my regular filesystem in, as an example, /mnt/regular_fs. So my grub config is at /mnt/regular_fs/etc/default/grub and my boot folder is at /mnt/regular_fs/boot so if I run udpate_grub it will not know that I want to update the regular_fs config.
Answer: Can you log into the host via single-user mode? That should interrupt the attempt at a GUI and give you an opportunity to edit grub.conf and run update-grub.
Also, check your /etc/inittab, if your OS uses that functionality. You may be able to set your default runlevel to a non-GUI value. See Section 10.4.2 of the RHEL6 Installation Guide for one example.
Good luck!
Comment: Thanks. Right now, the server is checking filsystem for errors (due to the many reboots I went through in the past few hours), so I can't test your suggestions. When the filesystem check is completed, I'll try them.
Comment: I couldn't get to test your solutions, because my system booted just fine after the filesystem check, because of the changes I made in /boot/grub/grub.cfg. Right now, I rather not mess with that again, because my webservices stood offline for a long time today (~ 3 hours). Thanks for your help, tho.

Update Grub In Another filesystem


DOMDocument->saveHTML isn't working as expected with href attributes

Question: I'm trying to parse some html with PHP in order to add some nodes, but output of DOMDocument->saveHTML isn't working as expected cause href attributes are encoded.
This is a simple code in order to check the wrong output:
$html = "click here";
$doc = new DOMDocument();
$doc->loadHTML( $html );
echo $html . "\n";
echo "-----------------\n";
echo $doc->saveHTML( $doc->getElementsByTagName('a')[0] ) . "\n";

And here is the output:
click here
-----------------
click here

As you can see something goes wrong with the href attributes.
Any idea about how can I solve this?
Test/play url: http://ideone.com/TsDhI3
Answer: Try writing the HTML in the correct format, with values for attributes delimited by double quotes, not single ones, so they don't get encoded. Javascript recognises strings delimited by single quotes.
Here's an example:
 $html = 'click here';
 $doc = new DOMDocument();
 $doc->loadHTML( $html );
 echo $html . "\n";
 echo "-----------------\n";
 echo $doc->saveHTML( $doc->getElementsByTagName('a')[0] ) . "\n";

Here's the working version - http://ideone.com/DjEyUX
Comment: The DOMDocument() functionality is built for correct HTML. If your app gets its input from uncontrolled sources which give out garbled HTML, you should use an utility to clean it up before feeding it in. Libraries for this are http://htmlpurifier.org/docs or http://php.net/manual/en/book.tidy.php
Comment: This is just an example, the problem is that html comes from a lot of sources and I can't warranty how the html is created  ...


Java Bean Validation - Applying Constraints Dynamically

Question: In Java Bean Validation (JSR 303), is there a way to programmatically (dynamically) add constraints in the code before the validate method is called (in addition to the constraints declared as annotations in the bean)?
Comment: Thanks. In my case, the beans are auto generated and I don't have control over their generation and I can't modify them. My workaround was creating a custom validator instead of relying on the API.
Comment: The answer to your question is no, but maybe there are other ways to solve your problem if you share your actual usecase.
Answer: The specification says

This JSR defines a metadata model and API for JavaBean validation. The default metadata source is annotations,
  with the ability to override and extend the meta-data through the use of XML validation descriptors.

so I guess if any programmatic configuration exists, it is implementation specific and thus nonportable.
Comment: Right. A programmatic configuration is not portable. Hibernate Validator offers a programmatic configuration, but in order to apply constraints dynamically you would have to rebuild the ValidatorFactory all the time, since this is where you specify the configuration.


how can I prove field-grouping functionality(tuple with same field goes to same task)?

Question: I'm a fresher of Storm, I'm getting started with Storm using the project storm-starter. In this project there is a Topology called WordCountTopology, the key code for building topology is:
builder.setBolt("split", new SplitSentence(), 8).shuffleGrouping("spout");
builder.setBolt("count", new WordCount(), 12).fieldsGrouping("split", new Fields("word"));

and in the implementation of WordCount bolt, the key method execute is:
@Override
public void execute(Tuple tuple, BasicOutputCollector collector) {
  String word = tuple.getString(0);
  Integer count = counts.get(word);
  if (count == null)
    count = 0;
  count++;
  counts.put(word, count);
  collector.emit(new Values(word, count));
}

My Question is:
As the functionality of filed-grouping is that: tuples with the same filed word will go to the same task for post processing. Here "task" means thread, how can I prove this functionality? In addition, in my opinion, the logic in method execute is a little awkward. In a single task, the parameter tuple is always the same, but in the execute method it does not reflect this, in other words, the logic dose not use this convenience.
Am I clear? My point is that, the code here in execute is not taking the feature of filed-grouping into account, the code here can also be applied to the situation of shuffle-grouping.
Answer: I would like to site few points, it might help clear your doubts

Here "task" means thread

In storm's terminology tasks are NOT threads but they are responsible for processing the actual logic.  Each spout or bolt that you implement in your code executes as many tasks across the cluster.  So you can define them as an running instance of the components i.e Spouts or Bolts.
There is another entity called Executors which are the thread responsible for running  these tasks.It can run one or multiple tasks of the same component. An executor having multiple tasks actually is saying the same component is executed for multiple times by the executor.
Now coming back to your question

the code here in execute is not taking the feature of filed-grouping into account, the code here can also be applied to the situation of shuffle-grouping

In very brief A fields grouping lets you group a stream by a subset of its fields, meaning  in order to do a word count, if we filtered the stream by using fieldsGrouping on a field name 'first_name` then it is expected that all the first_name field with a value say (Foo) should go to the same task, and the same field with a different value (Bar) goes to another task.
So here the execute method is supposed to receive the same field value and thus can easily update its counter and to do that it does not require to consider anything special. The whole logic is written keeping in mind that the bolt will be chained with the proper data and that's why using the proper grouping become such an important thing. So if you use shuffleGrouping then same code will run but produces incorrect data.
Comment: You are assuming that the statement "All tuples with the value Foo will go to the same bolt" also extrapolates to "All tuples going to this bolt will have the value Foo". That isn't correct. A given bolt will receive many tuples with many different values for the grouped fields, the guarantee is that all the tuples with the same values for the grouped fields will go to the same bolt.
Comment: if all the first_name field with value 'Foo' go to the same task, can I change the logic of `execute` method to this: set a member variable of WordCount bolt named `time` with initial value 0, in execute method, increase `time` by 1. Now if `time == 1`, that means this is the first time we receive a word from spout, extract the value(Foo), store the value to a member variable(like `word`), assign count = 1, else if `time > 1`, we do not need to extract the value again, cause the value is Foo, we directly make `count++`. I think this is taking the feature into account more directly.
Answer: Well Pinky (or anyone else who finds this useful), to prove it, you just have to keep track of the bolt or spout task ID:
@Override
public void prepare(Map map, TopologyContext tc, OutputCollector oc) {
  this.boltId = tc.getThisTaskId();
}

Now in the execute() of the same fieldsGrouped bolt that receives the tuples, you just print the id and the tuple:
@Override
public void execute(Tuple tuple) {
  String myWord = (String) tuple.getValue(0);
  System.out.println("word: "+myWord+" boltID:"+boltId);
}


What is the science behind pleasant chord progressions?

Question: Especially in pop music (or baroque music), chord progressions play a key role in music. Popular chord progressions include (I,III,VI,V), as well as popular cadence progressions like (I,IV,I64,V,I) are attractive and sound pleasant to the ear. On the other hand, chord progressions like (I,III,II,IV,I) or a cadence progression like (I,VI,II,I) do not sound as pleasant to the ear or sound complete.
While intervals like the perfect fifth sound pleasant due to sound waves matching up, what is the science behind chord progressions that sound pleasant vs. unpleasant, or is this just due to random personal preference?
Comment: IMO, comments like "attractive and sound pleasant" are mostly value judgements based on someone's personal musical experience. Personally I would call your two chord sequence examples "boring clichés" not "attractive and pleasant sounding!". **This** is "attractive" and certainly "complete" (but note, it's only the last few minutes of a piece that last for more than 8 hours in total!) https://www.youtube.com/watch?v=eD4MY3rmrXI
Comment: Why is there any *requirement* that music should sound "attractive" or "pleasant?" - unless its only function is to be "background noise", like elevator music for example.
Comment: The science is music theory, good old harmony and counterpoint. It is also covered by psycho-acoustics. It is largely a matter of mathematics.
Answer: I would argue that there is little acoustical science behind whether a chord progression is pleasant or not. Two other considerations may easily overpower what acoustical effects exist. One is just cultural preference; some cultures (or sub-cultures within another tradition) prefer certain types of patterns. In other cases, especially where music is used to support drama (opera, movies, video games), one may prefer a "bad-sounding" (not just dissonant) passage to illustrate the action (or to describe what isn't easily shown visually.)
There is personal preference, but it's more cultural (or learned) than random. Of course, this is only my opinion.
Comment: Some acoustic-psychological studies seem to show that some sounds are considered better or worse sounding. Think fingernails on a black board. Very loud sounds can be painful. Think 200+Db fingernails on a blackboard (which is used as an anti-terrorism weapon.) Helmholtz's book discusses some ideas from a very old perspective.
Comment: Music is art not science. Music theory and acoustics provide us descriptive terminology. But, I too feel these shouldn't be relied on too heavily to explain aesthetics.
Comment: But then this leads o to an even more fundamental question. As a composer, how does my brain work when I compose? - how does the brain produce "art"?
Answer: I would get past trying to nail this down to science. Pleasant sounds you hear from a I-IV-V may not be as pleasant to somebody else. In music there are rules with a science underlying (the sound waves and how they travel and levels among the frequencies that are sounded...), but it is the rules that dictate how music is composed. Not the underlying science. We mostly follow the rules and sometimes we break away. In fact, many times we break away but still follow some rules. An example I can think of is the harmony technique of creating a verse or bridge progression that stems from the V, iii, or IV in the original key. Breaking away but with some guidelines to doing so. That is the craft and artistic side of music.
Answer: There's definitely some interesting attempts to tackle a harmony more from a physics point of view. For example:
https://arxiv.org/html/1202.4212v1
There's no need to deny either physical (absolute) or cultural (relative) influences on our perception of nice versus harsh. They can coexist.


My program is not correctly outputting the amount of students in my struct

Question: i am making a program which is supposed to collect input from the user by asking for id, name, units attempted, units earned and the gpa of a student and store that into a struct. Currently, when i input more than one student into the struct, it only outputs the last student in the array. What can i do to fix this?
Here is my code
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

struct Student {
string ID;      //an 8-digit student ID
string name;        //name of the student
unsigned unitsAttempted;//number of units attempted by the student
unsigned unitsEarned;   //number of units earned by the student
double gpa;     //the grade point average for the student
};

int main()
{
  Student students[10];//array for 10 Student Structs

  char answer = 'y';
  int number = 0;

  while ((answer == 'y') || (answer == 'Y')) {
   //prompt the user to enter the data
  {
    answer = ' ';
    int i = 0;

    cout << "Enter the students ID: \n" ;
    getline(cin, students[i].ID);

    cout << "\nEnter the name:\n";
    getline(cin, students[i].name);

    cout << "\nEnter the units attempted:\n";
    cin >> students[i].unitsAttempted;
    cin.ignore();

    cout << "\nEnter the units earned:\n";
    cin >> students[i].unitsEarned;
    cin.ignore();

    cout << "\nEnter the GPA: \n";
    cin >> students[i].gpa;
    cin.ignore();

    cout << "\nWould you like to add another student? y or n\n";
    cin >> answer;
    cin.ignore();

    i++;
    number++;
  }
  }

  cout << left << setw(10) << "ID " << setw(20) <<"Name" << setw(20) <<"Units Attempted" << setw(20) <<"Units Earned" << setw(10) <<"GPA";
  cout << "\n===============================================================\n";

    for (int i = 0; i < number; i++)//display the students
    {
      cout << left << setw(10) << students[i].ID << setw(20) << students[i].name << setw(20) <<students[i].unitsAttempted << setw(20) <<students[i].unitsEarned << setw(10) <<students[i].gpa << endl << endl;

    }

  return 0;
}

Im still learning so please go easy on me, thanks.
Comment: visual studio on windows. It is very easy to debug with it.
Comment: Glad to hear that you're still learning, so the next thing for you to learn is how to use your debugger to run your program one line at a time, inspect the values of all variables, and see exactly what your program is doing. Knowing how to effectively use a debugger is a required skill for every C++ developer, no exceptions. With your debugger's help you can quickly figure out the bugs in your code without asking anyone else for help, good luck!
Comment: do you know how to access the debugger in repl.it
Comment: Never heard of it. Seem to be some web-based development tool. You can't effectively learn C++ like this. You need both [a good C++ textbook](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), as well as a modern C++ compiler with a debugger.
Comment: what modern c++ compiler would you recommend
Comment: gcc on Linux, of course. gdb as a debugger. Pretty hard debugger to learn, but once you do, it's invaluable.
Answer:
Currently, when i input more than one student into the struct, it only outputs the last student in the array.

It looks most likely that the scope of your i is incorrect:
    int i = 0;   //<-- this should be declared outside the `while` loop

As it stands, your i is scoped inside while loop, so it will be reset every time the while loop is entered. In other word, that i never increased.


Swapping rootViewController on UIWindow does not deallocate view controller

Question: If you swap out a rootViewController in UIWindow, for example, to present a log in window, if the rootViewController has presented (modal) view controllers, those presented view controllers and possibly the old rootViewController will not be deallocated.
self.window.rootViewController = newViewController

Answer: UIKit objects are often released internally using autorelease. That means that they're not guaranteed to get released right away. You can, however, force things to deallocate by wrapping the function that should release the object with an autoreleasepool.
autoreleasepool {
    self.window.rootViewController = newViewController
}

For a good explanation of autorelease and autorelease pools, go check out this answer.
Answer: You must always do a dismissal of all modals when swapping out the rootViewController, otherwise there will be a retain cycle.
if window?.rootViewController.presentedViewController != nil {
    window?.rootViewController.dismiss?(animated: false) {
        window?.rootViewController = newViewController
    }
}
else {
    window?.rootViewController.dismiss?(animated: false)
    window?.rootViewController = newViewController
}

If you want to do a nice transition, you could always wrap it in an animation:
func transition() {
    if window?.rootViewController.presentedViewController != nil {
        window?.rootViewController.dismiss?(animated: false) {
            window?.rootViewController = newViewController
        }
    }
    else {
        window?.rootViewController.dismiss?(animated: false)
        window?.rootViewController = newViewController
    }
}

UIView.transition(with: window!,
                  duration: 0.3,
                  options: .transitionCrossDissolve,
                  animations: transition)

Comment: This is mostly right. For securely removal, here is one point : `self.myWindow?.rootViewController?.dismiss(animated: false, completion: {
                self.myWindow?.rootViewController = newViewController
            })`
Comment: Even better, don't do that. You shouldn't change the root view controller.
Comment: @matt I see nothing in the documentation stating that changing the root view controller of a window is discouraged, it is a readwrite property. Much safer than dealing with existing view hierarchy in the existing root view controller or using view controller containment in a "base" root view controller.
Comment: @E.Coms Thank you, that is right! I assume completion is called even if there aren't any modals presented. Otherwise you would need a check on `presentedViewController`, I will do some testing later
Comment: I disagree obviously.
Comment: @matt please provide justification so we can update the answer. Otherwise it is just a matter of opinion. Technically this is correct and safe as UIWindow objects support this despite them being somewhat ignored in iOS. You could also swap out windows themselves instead of adding complexity to your root view controller.
Comment: You don't have to do it my way, but as you've discovered there are issues when you mess with the view controller hierarchy from the bottom end like this. I'm saying you would have had those issues if you treated the view controller hierarchy the way it expects to be treated. You are giving a workaround for a self-inflicted wound.
Comment: It isn't a workaround. It is the proper way to dealloc a view controller manually. Many users swap out the root like this and I thought I would help them do it correctly. You should google "Compassionate Coding" it may be helpful in improving communication style.
Comment: @E.Coms I've tested it and the completion block does not get called if there isn't a presentedViewController, so I've updated my answer to safely work in all cases.


Facebook Android SDK 4.0 not returning emailID

Question: I am trying to implement facebook login using latest facebook SDK 4.0.It is only returning User-ID and User-name. Below is the code which I have implemented using GRAPH APIs.
@Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
        textView = (TextView) view.findViewById(R.id.textView);

        List<String> permissions = new ArrayList<>();
        //permissions.add("user_friends");
        permissions.add("email");
        //permissions.add("user_birthday");
        loginButton.setReadPermissions(permissions);
        loginButton.setFragment(this);
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),new GraphRequest.GraphJSONObjectCallback() {

                            @Override
                            public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
                                if (graphResponse.getError() != null) {
                                    // handle error
                                } else {
                                    String email = jsonObject.optString("email");
                                    String id = jsonObject.optString("id");
                                    new GraphRequest(
                                            AccessToken.getCurrentAccessToken(),
                                            "/" + id,
                                            null,
                                            HttpMethod.GET,
                                            new GraphRequest.Callback() {
                                                @Override
                                                public void onCompleted( GraphResponse graphResponse) {
                                                        Log.d("FACEBOOK LOGIN","graph response" +graphResponse.toString());
                                                }
                                            }
                                    ).executeAsync();
                                    Log.d("FACEBOOK LOGIN ","email id and the user_id of the looged in user is = ::" + email+" ::"+id+"" +
                                            "JsonObject from facebook i am getting is :" +jsonObject.toString());
                                    // send email and id to your web server
                                }

                            }

                        }).executeAsync();
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(FacebookException e) {

            }
        });

    }

Also I tried using GRAPH API EXPLORER, where it is showing me my email address as well as birthday and gender too. Below is the snapshot of it
Comment: it will not display the email id until the user is either administrator or test user of the app
Answer: Try this .
    String username,email ;

    loginButton.registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        new fblogin().execute(loginResult.getAccessToken());

                    }

                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onError(FacebookException e) {

                    }
                });

class fblogin extends AsyncTask<AccessToken, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Loading Data..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(AccessToken... params) {
            GraphRequest request = GraphRequest.newMeRequest(params[0],
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object,
                                GraphResponse response) {

                            try {

                                username = object.getString("first_name");

                                emailid = object.getString("email");

                            } catch (JSONException e) {
                                // TODO Auto-generated catch
                                // block
                                e.printStackTrace();
                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields",
                    "id,first_name,email,gender,birthday");
            request.setParameters(parameters);
            request.executeAndWait();

            return null;
        }

        protected void onPostExecute(String file_url) {

            pDialog.dismiss();

        }

    }

Its done.!!
Answer: try this one
loginButton.setReadPermissions(Arrays.asList("public_profile", "user_friends", "email"));
Comment: doesn't make any difference. Tried it.


Consider a possible system of m linear equations with n variables in the form $AX = B$. Is the set C of the solutions a subspace of $\mathbb{K}^n$?

Question:
Consider a possible system of m linear equations with n variables, on
  $\mathbb{K}$, in the form $AX = B$ ($A$,$B$ and $X$ are matrices).
  Show that the set C of the solutions is only a subspace of
  $\mathbb{K}^n$ if $B=0$, (in other words, if AX=B is an homogenous
  system).

In the book $\mathbb{K}$ is used for $\mathbb{R}$ and $\mathbb{C}$ interchangeably.
I think this is proven because of that condition that for a subspace to be a subspace of vectorial space it needs to contain its null vector. The trick here is probably to prove that in a homogenous system, (0,0,0,...) (whatever the degree of the subspace is) is necessarily a solution but I don't know how to do that. Help?
Answer: 1.) The solutions of $AX =0$ are a subspace:
$0$ is a solution, since $A0=0$. If $X_1$ and $X_2$ are solutions, then $A(\lambda X_1 + X_2) = \lambda AX_1 + AX_2 = \lambda 0 + 0 = 0$. Thus, $\lambda X_1 + X_2$ is also a solution.
2.) The solutions of $AX = B$ are not a subspace for $B\neq 0$:
You already said it. The reason is, that $0$ is not a solution of $AX = B$, but must be contained in a subspace.
In general: If $AX = B$, then $\{Y | AY = B\} = X + \{Y|AY = 0\}$.


Time series notation

Question: Consider a time series of time t=1...T as $$\left(y_{1},y_{2},...,y_{T}\right)$$ Here, do each of the $y_{t}$'s correspond to different realizations of a the same random variable Y? Or are each of the $y_{t}$'s thought of as random variables themselves ?
Comment: This isn't a question about notation: it seems to be asking about what "time series" means.  Doesn't https://stats.stackexchange.com/questions/126791 answer that?
Answer: One way to look at the series is to consider each $y_t$ an observation of a random variable $Y_t$, then when you write $y_1,\dots,y_T$ you mean that you sampled from the joint T-dimensional distribution, i.e. each element is a distinct random variable. The problem is that you can only sample once. There's only one January 1 2023, so whatever you observed that day will be a single sample from the variable $y_{2023/1/1}$.
There's not much you could do to forecast such series or generally study its properties. Even the simplest metrics such as correlation between $y_t,y_s$ become pretty much impossible to estimate in this framework.
So, we start mental acrobatics, such as a notion of stationarity. For instance, we assume that correlation between $\rho_{t,s}=y_t,y_s$ depends only on the distance in time, i.e. $\rho_{t,s}=\rho_{|s-t|}$. All of a sudden, we got more than one sample to calculate the correlations!
For instance we have T-2 observations to calculate $\rho_2$: $$y_1,y_3\\y_2,y_4\\y_3,y_5\\\dots\\y_{T-2,T}$$
There's also a concept of ergodicity in physics: if you observe the system long enough then you'll encounter it to go through every possible state at the rate that corresponds to the probabilities of states. This essentially means that if you're dealing with a system in some kind of equilibrium then $y_1,\dots,y_T$ is the same as T observations of the system $y$, i.e. T realizations of one variable.

Time series notation


How should we handle Magento questions on Stackoverflow?

Question: Since magento.se is now in public beta, how should we handle question about Magento in other se websites?
I mean, if a good question about Magento is asked on Stackoverflow, do we have to flag it as off topic and/or ask a mod to be migrate the question to magento.se ?
Comment: It looks like there has been a number of migrated questions from SO now.
Comment: @sonassi Which ones ?
Comment: From looking at my fancy moderator panel :) http://magento.stackexchange.com/questions/1182/how-to-recalculate-shipping-costs-in-magento-one-page-checkout http://magento.stackexchange.com/questions/1144/magento-what-is-the-customer-payment-entity-type-used-for http://magento.stackexchange.com/questions/1082/magento-can-the-associated-products-of-a-configurable-product-inherit-details http://magento.stackexchange.com/questions/1039/set-individual-options-out-of-stock-in-magento
Comment: @sonassi that have been done by moderator which is not really my question :)
Answer: No. Migration should be rare for a beta site, particularly during the early days.
That said, if you see a good question going unanswered on SO - especially if it's not strictly programming-related - go ahead and leave a comment there noting that such a question would be welcomed here as well. For instance,

While questions on Stack Overflow are expected to be about programming in some fashion, [magento.se] welcomes any question on the use of Magento.

(the bit in brackets will automatically expand to a link here)
Be careful not to flag or spam questions that are already well-answered and clearly on-topic; this will tend to irritate both the askers and the moderators.
Comment: All right, thanks !
Comment: You know that "magento.se" links to some Finnish magento developer's website, right?
Comment: Try it in brackets in a comment, @buttle [magento.se]


Fatorial de 0 a 20 usando For

Question: Preciso fazer o seguinte exercício:
"Utilizando o loop for, calcule e imprima em tela o fatorial
de todos os números entre 0 e 20. Utilize o tipo Double. Ex: 0! =1
1! =1
2! = 2
... 20! = 2432902008176640000"
Mas não consigo identificar o erro que estou cometendo.
Alguém tem uma ideia?
#include <stdio.h>

int main(){
    int cc, cf, acc;
    double fat;

    for(cc=0; cc<=20; cc++){
        if(cc==0) fat=1;
        else{
            for(cf=0;cf<cc;cf++){

                fat = fat * cf;
                acc = acc + fat;
            }
        }
        printf("%d! = %.1lf\n",cc+1 , fat);
    }
}

Answer: (1) Você está somando "int" com "double":
acc = acc + fat;

O problema é que valores altos de fatorial cabem em double, mas não cabem em int.
Aliás, você nem está usando a variável "acc" para nada...
(2) Você não está inicializando a variável "acc":
  int cc, cf, acc;

Isto é, mesmo ignorando que acc deveria ser double, e que você não está usando acc para nada, suas contas com acc resultam em valor indefinido, porque acc não foi inicializado.
(3) Sua lógica está ineficiente e confusa:
for (cc = 0; cc <= 20; cc++)
{
  if (cc == 0) // <------- INEFICIENTE, está repetindo a mesma comparação
    fat = 1;   // <------- 21 vezes, sendo que só 1 vez ela vai ser verdadeira
  else
  {
    for (cf = 0; cf < cc; cf++) // <---- CONFUSO: por que este segundo loop ???
    {
      fat = fat * cf;
      acc = acc + fat;
    }
  }

(4) Seu programa não está documentado. Você não colocou nem UM comentário explicando sua lógica.
Abaixo, uma versão simplificada do programa.
#include <stdio.h>

int main()
{
  int cc;
  double fat = 1;

  // caso especial: 0! = 1
  printf("* 0! = 1\n");

  // caso geral: n! = 1 * 2 * .. * n
  for (cc = 1; cc <= 20; cc++)
  {
    fat *= cc;
    printf("* %d! = %.0lf\n", cc , fat);
  } // for

  return 0;
}

Teste:
$ 380272.exe
* 0! = 1
* 1! = 1
* 2! = 2
* 3! = 6
* 4! = 24
* 5! = 120
* 6! = 720
* 7! = 5040
* 8! = 40320
* 9! = 362880
* 10! = 3628800
* 11! = 39916800
* 12! = 479001600
* 13! = 6227020800
* 14! = 87178291200
* 15! = 1307674368000
* 16! = 20922789888000
* 17! = 355687428096000
* 18! = 6402373705728000
* 19! = 121645100408832000
* 20! = 2432902008176640000
$

Answer: Olá, tudo bem?
Você pode fazer em C da seguinte maneira:
#include <stdio.h>

int main()
{
   double fat;
   int n;
   printf("Insira um valor para o qual deseja calcular seu fatorial: ");
   scanf("%d", &n);

   for(fat = 1; n > 1; n = n - 1)
     fat = fat * n;

   printf("\nFatorial calculado: %lf", fat);
   return 0;
}

Answer: Eu faria algumas alterações estruturais e de lógica no seu código:
#include <stdio.h>

int main() {
  int cc, cf, acc;
  long fat; // <1>

  for (cc = 0; cc <= 20; cc++) {
    fat = 1; // <2>
    if (cc == 0) fat = 1;
    else {
      for (cf = 1; cf <= cc; cf++) { // <3>
        fat *= cf; // <4>
      }
    }
    printf("%d! = %ld\n", cc, fat); // <5>
  }
}

<1> Primeiro que eu mudaria o type da variável para long, que é muito superior ao de um simples int, e levando em consideração que não existe multiplicação de números inteiros com resultado com casas decimais, não vejo problema em exibir como inteiro.
╔════════╦══════════════╦══════════════════════╦════════════╗
║ Type   ║ Storage size ║ Value range          ║ Precision  ║
╠════════╬══════════════╬══════════════════════╬════════════╣
║ float  ║ 4 byte       ║ 1.2E-38 to 3.4E+38   ║ 6 decimal  ║
║ double ║ 8 byte       ║ 2.3E-308 to 1.7E+308 ║ 15 decimal ║
╚════════╩══════════════╩══════════════════════╩════════════╝

<2> Cada iteração do segundo for é necessário zerar a variável.
<3> O segundo for é necessário iniciar de 1 para não existir a primeira multiplicação por 0 que zera o resultado final, na verdade é aqui que está o problema lógico do seu código.
<4> Resumiria a operação matemática.
<5> O printf eu exibiria usando %ld que em outra palavras pode ser lido como long double.

O resultado final pode ser visto em qualquer compilador C online:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000

Fatorial de 0 a 20 usando For


Modern SGML Viewer

Question: I was provided some documentation in SGML format. Not being familiar with the format I searched the web to find a suitable viewer but cant seem to locate one. Is there such a thing as a modern SGML viewer?
Comment: SGML is plain text. Can't you just use a text editor?
Comment: It has graphic elements and some formatting.
Comment: SGML is still used, but it's mostly superseded by XML these days (though in a sense XML *is* SGML: XML is a subset of full SGML). There are powerful editors that can handle both SGML and XML (example: http://www.ptc.com/product/arbortext/editor/), including showing images and using stylesheets. But I would be surprised if there were any "modern SGML viewers".
Answer: There is no such thing as an SGML viewer, because SGML is not a "document format" (or "document type") that could be visually displayed.
SGML is a language that is used to describe a document type.
You need to look for a "viewer" for your specific document type, and not for SGML.
SGML document types
You need to find out which document type your SGML file uses, and then find a viewer for that document type. You can see which document type your SGML file uses at the very top of the SGML file, where it says <!DOCTYPE .... E.g for a file that uses the document type XHTML it looks like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" []>

Document types described using SGML might be:

ATA iSpec 2200 AMM
CMM (Component Maintenance Manual)
HTML4
...

(SGML document types are described by "document type definitions" (DTD).)
Viewers / Editors
Of course, for HTML the "viewer" would be a web browser.
For other formats, the "viewer" (or "editor") will often be some kind of custom software, such as Arbortext Editor with custom extensions, or custom scripts or software that converts this specific document type into e.g. PDF. There is usually some kind of "styling file" involved, like CSS or FOSI, which describes how each element should be formatted and layouted.
Sometimes, the SGML files are not meant to be displayed as a whole at all, but are used to store data or transfer data between data bases and other software, which might only display small portions of the data at once.

Modern SGML Viewer


Show that if A = B + C, then BC = 0

Question: A,B,C are n $\times$ n symmetric and idempotent matrices.
The question is:
If
$$
\textbf{A = B + C }
$$
then show
$$
\textbf{BC = 0 }
$$
I'm not sure where to start?
Comment: Have you tried squaring both sides of the equality ?
Answer: Here's my expansion of Brian's argument:
$A^{2}=A$, $B^{2}=B$, $C^{2}=C$, hence
$A^{2}=(B+C)^{2}\rightarrow BC+CB=0 \implies BC+(BC)^{T}=0$ Hence $BC$ is an anti-symmetric matrix, thus it has only imaginary eigenvalues.
$ BC+CB=0 \implies B(BC+CB)C=0 \implies BC + (BC)^{2}=0$,
If $BC\neq0$ then $BC + (BC)^{2}=0$ is the minimal-polynomial for $BC$, hence $-1$
is an eigenvalue of $BC$, which is a contradiction since $BC$ can have only imaginary eigenvalues
Answer: Recall that a matrix $M$ is idempotent if $M^2=M$.
Thus, since $A=B+C$ where $A$, $B$, and $C$ are idempotent implies that
$$
B+C=(B+C)^2=B^2+C^2+BC+CB=B+C+BC+CB
$$
Simplifying this equation gives
$$
0=BC+CB=BC+(B^\top C^\top)^\top
$$
How might we proceed from here?
Comment: I have tried to extend your argument to get to a contradiction; take a look. Thanks
Comment: At this point, since we have, BC = -(B'C')', can we not argue that BC has to equal zero for this to be true?
Comment: Note that for symmetric matrices $S$, we have $S = S^T$.
Comment: Just from the symmetric argument, neither $BC=CB$ must be true, nor $BC$ is necessarily symmetric as answered here https://math.stackexchange.com/questions/874469/symmetric-matrix-multiplication
Answer: We can also proceed from the step $0=BC+CB$ this way:
Multiply both sides by $B$ we have
$0=B^2C+BCB=BC+BCB=BC(I+B)$,
but $I+B$ is full rank matrix  (it doesn't have zero eigenvalue because for $B+I$ all eigenvalues: - $0,1$ for idempotent matrix $B$,  were shifted by $+1$ with reference to eig. of $B$) so $BC$ annihilates full rank matrix,
hence  $BC$ has to be zero matrix.
Answer: Note that the claim is not true over a field of characteristic $2$: consider the matrices $B=C=\mathbf 1$ and $A=\mathbf0$.
This counterexample shows that you're not going to be able to prove the claim simply by performing the sort of algebraic manipulations that work over all fields, such as $(XY)^T=Y^TX^T$ and so on. You're going to need some argument that involves the base field. For example, see zimbra314's answer in terms of complex eigenvalues.
Comment: How about using the spectrum decomposition in some way?

Show that if A = B + C, then BC = 0


How to mount data with Azure Blob Storage?

Question: I'm brand new to Azure Databricks, and my mentor suggested I complete the Machine Learning Bootcamp at
https://aischool.microsoft.com/en-us/machine-learning/learning-paths/ai-platform-engineering-bootcamps/custom-machine-learning-bootcamp
Unfortunately, after successfully setting up Azure Databricks, I've run into some issues in step 2.  I successfully added the 1_01_introduction file to my workspace as a notebook.  However, while the tutorial talks about teaching how to mount data in Azure Blob Storage, it seems to skip that step, which causes all of the next tutorial coding steps to throw errors.  The first code bit (which the tutorial tells me to run), and the error that comes up afterwards, are included below.
%run "../presenter/includes/mnt_blob"
Notebook not found: presenter/includes/mnt_blob. Notebooks can be specified via a relative path (./Notebook or ../folder/Notebook) or via an absolute path (/Abs/Path/to/Notebook). Make sure you are specifying the path correctly.
Stacktrace:
  /1_01_introduction: python
As far as I can tell, the Azure Blob storage just isn't set up yet, and so the code I run (as well as the code in all of the following steps) can't find the tutorial items that are supposed to be stored in the blob.  Any help you fine folks can provide would be most appreciated.
Answer: Setting up and mounting Blob Storage in Azure Databricks does take a few steps.
First, create a storage account and then create a container inside of it.
Next, keep a note of the following items:

Storage account name: The name of the storage account when you created it
Storage account key: This can be found in the Azure Portal on the resource page.
Container name: The name of the container

In an Azure Databricks notebook, create variables for the above items.
storage_account_name = "Storage account name"
storage_account_key = "Storage account key"
container = "Container name"

Then, use the below code to set a Spark config to point to your instance of Azure Blob Storage.
spark.conf.set("fs.azure.account.key.{0}.blob.core.windows.net".format(storage_account_name), storage_account_key)

To mount it to Azure Databricks, use the dbutils.fs.mount method. The source is the address to your instance of Azure Blob Storage and a specific container. The mount point is where it will be mounted in the Databricks File Storage on Azure Databricks. The extra configs is where you pass in the Spark config so it doesn't always need to be set.
dbutils.fs.mount(
 source = "wasbs://{0}@{1}.blob.core.windows.net".format(container, storage_account_name),
 mount_point = "/mnt/<Mount name>",
 extra_configs = {"fs.azure.account.key.{0}.blob.core.windows.net".format(storage_account_name): storage_account_key}
)

With those set, you can now start using the mount. To check it can see files in the storage account, use the dbutils.fs.ls command.
dbutils.fs.ls("dbfs:/mnt/<Mount name>")

Hope that helps!
Comment: Thanks a lot for the help Jon.  I'll use this as a guide to get set up.  Still not sure what happened with the tutorial, but this should work just as well, if not better.
Comment: What is the point of the `spark.conf.set()` command?
Comment: Do I understand correctly that all data that we write to `dbfs:/mnt/` should be automatically uploaded to the container of the blob storage?
Comment: @Fluxy: indeed, if you write to the mount point, it will write into the blob container.


Strapi v4: How to enable graphql playground in prod?

Question: my-app.herokuapp.com/graphql responses with 'GET query missing.' and doesn't provide graphql playground interface.
Conf from https://docs.strapi.io/developer-docs/latest/plugins/graphql.html#configurations doesn't work for me.
./config/plugins.js

module.exports = ({ env }) => ({
  //
  graphql: {
    config: {
      endpoint: "/graphql",
      shadowCRUD: true,
      playgroundAlways: true,
      depthLimit: 100,
      apolloServer: {
        tracing: false,
      },
    }
  },
});

and this from forums too..
module.exports = ({ env }) => ({
  //
  graphql: {
    endpoint: "/graphql",
    shadowCRUD: true,
    playgroundAlways: true,
    depthLimit: 100,
    apolloServer: {
      tracing: false,
    },
  },
});
```

Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Are you sure you didn't misspelled ./config/plugins.js ? I had the same issue and it was because I used ./config/plugin.js without the s at plugins
Answer: When I tried to query my GraphQL API on Heroku with Postman, at first it said "restricted access" or something like that. Then I realised that, unlike with MongoDB, when you deploy PostgreSQL on Heroku, the latter creates it's own database, different from the one created in dev environment
So, in prod, Strapi content-types are saved, but naturally some things are wiped, like the entries in collections and permissions settings. I had "find" and "findOne" checkboxes unchecked there, so I checked them back on. Prod API still shows "GET query missing", but the data appeared in Postman and the app worked as expected
If you have PostgreSQL deployed, check your Strapi settings (Settings -> Users & Permissions Plugin -> Roles -> Permissions -> name of your collection type) and see if the checkboxes are unchecked and try to check them back. That did the trick for me
Answer: This worked for me Strapi v.4 on Heroku with postgreSQL
config/plugins.js
module.exports = ({ env }) => ({
  graphql: {
    enabled: true,
    config: {
      endpoint: "/graphql",
      shadowCRUD: true,
      playgroundAlways: true,
      defaultLimit: 10,
      maxLimit: 20,
      apolloServer: {
        tracing: true,
      },
    },
  },
});

Answer: Just make sure
playgroundAlways: true
in config/plugin.js
By default it is false and since I changed it to true it started working
for more : https://github.com/strapi/strapi/issues/2309


Representing a subset of observation using weights

Question: I have $n$ observations for $m$ variables that are sorted by time, e.g. observation $1$ is the oldest, whereas observation $n$ is the newest. I represent this data as an $n\times m$-dimensional matrix $D$. I would like to compute the mean and covariances between these variables, but having a freedom to give different importance to observations made at different times. The two extreme cases are:

I consider a lower sub-matrix $D_t$ of $D$ which is $t\times m$, and $t<n$ is a number of the latest observations I would like to take into account when computing mean and covariances.
I use the whole matrix $D$ for the computation, to take into account all the data I have, giving it same importance regardless of the observation time.

Other cases lie in between, e.g. I can multiply column-wise $D$ by some weight vector $w$, say to increase the later observation values, and decrease the older observation values.
As an example,
$$
D = \left(
\begin{split}
1 &\; &0.5
\\
-1&\;&2.5
\\
2&\;&7
\end{split}
\right)
,
\quad
w = \left(
\begin{split}
0.1
\\
0.5
\\
1
\end{split}
\right)
,
\quad
wD = \left(
\begin{split}
0.1 &\; &0.05
\\
-0.5&\;&1.25
\\
2&\;&7
\end{split}
\right)
$$
At the same time, I am not sure whether this is the best way to assign different importance to different observation times. For example, if all the output were binary (true/false), then scaling does not even seem to make any sense, although it looks more natural when output are numerical.
More importantly, I would be happy to incorporate the case 1. as a special case. Unfortunately, when I use the weighting vector $w$ that has $n-t$ zeros at $t$ ones (looks like a natural choice for me), the result is mush different from the case 1 with a matrix $D_t$. Of course, the means are the same up to a scaling factor of $t/n$, but the entries of the covariance matrix do not seem to be changed just by a scaling factor. Any hints on how to approach this problem are appreciated.
Answer: The thing you are trying to do is not very difficult, just be more careful and it will work.
For the weighted means, take a normalized weight vector $w$, that is a vector with the sum of weights equal to 1. With such vector your life becomes very easy, as $w^TD$ (using your notation for $w$ and $D$, and multiplication meaning matrix multiplication) will be $1\times m$ vector of weighted means.
If you want to ignore the first $n-t$ observations, corresponding vector $w$ will be $(0,\dots, 0, 1/t, \dots, 1/t)$ with $n-t$ zeros and $t$ values $1/t$. That's it!
I will not rewrite formulas for weighted covariances, you can find them in wikipedia.
Comment: Thanks for the answer, can't upvote it since my reputation is low.
Comment: You are welcome, I hope it helped.


Switch off heading if there are no related products inside an if_array inside a foreach loop

Question: I want to display a heading title 'Related Products' if there are matches in an array and hide the title if there are not. My code below shows the title regardless. How do i switch it off if there are no products?
As you can see I have commented out the original code whereby I tried to do the checking inside the query but that did not work, otherwise I could have just places teh heading below the if ($related_products->have_posts()){ line.
            <?php

                // Query products where product title matches a tag in the current article

                $current_article_tags = wp_get_object_terms(get_the_ID(), 'knowledge_hub_tag', array('fields' => 'names'));

                echo '
'; print_r($current_article_tags); echo '
';

                $related_products = new WP_Query(array(
                  'posts_per_page' => -1,
                  'post_type'=> 'product',
                  /*'post_title' => array(
                      array(
                          //'taxonomy' => $current_article_tags,
                          'post_title' => 'varilite icon mid',
                          'operator'=> 'IN' //Or 'AND' or 'NOT IN'
                      ),
                  )*/
                ));

                //echo '
'; print_r($related_products); echo '
';

                $products = $related_products->posts;

                //echo '
'; print_r($products); echo '
';

                if ($related_products->have_posts()){

                    echo '
Related products
';

                    foreach($products as $product) {
                        if(in_array($product->post_title, $current_article_tags, true)) {
                            echo '
'.get_the_title($product).'
';
                        }
                    }

                }

                //wp_reset_postdata();
            ?>

Comment: You have to call `have_posts` on the appropriate object - that is a method of WP_Query, so you need to call it on `$related_products`.
Comment: I tried that but couldn't get it to work, check out my code where I have commented it out. For some reason that didn't work :(
Comment: _"I only want to display the title if any of the product post titles match any of the current article tags"_ - ah, so then this is not about whether the query _had_ any posts. You are not filtering for any such kind of condition in your database query - so that will _have_ posts either way. You will either have to add this as a selection criterion to your query in the first place; or you have to loop over all the posts in the result first, to be able to determine that _none_ of them satisfied your condition.
Comment: I tried looping which worked for the products but repeated the title 'related products' when i only want to display that once and only if there is a match in the array.
Comment: Sounds like you output the title _inside_ the loop, instead of after …
Comment: If you don't want to loop twice - then don't `echo` your posts inside the loop, but append them to a string variable. If that string is _not_ empty after the loop, then output your title, followed by the string contents.
Comment: I tried outputting the title inside loop but it repeated, after isn't useful visually.
Comment: I did not say that you should output it after you output the titles already, I said that you should output it after a loop that checks if your condition is fulfilled for any of the posts. (And if you don't want to loop _twice_, to first check your condition against all posts, then do as I said in the previous comment.)
Comment: ah ok, i'll give it a go, thanks
Answer: Try this.
<?php

// Query products where product title matches a tag in the current article

$current_article_tags = wp_get_object_terms(get_the_ID(), 'knowledge_hub_tag', array('fields' => 'names'));

echo '
'; print_r($current_article_tags); echo '
';

$related_products = new WP_Query(array(
  'posts_per_page' => -1,
  'post_type'=> 'product',
  /*'post_title' => array(
      array(
          //'taxonomy' => $current_article_tags,
          'post_title' => 'varilite icon mid',
          'operator'=> 'IN' //Or 'AND' or 'NOT IN'
      ),
  )*/
));

//echo '
'; print_r($related_products); echo '
';

$products = $related_products->posts;

$show_title = false;

foreach($products as $product) {
    if(in_array($product->post_title, $current_article_tags, true)) {
        $show_title = true;
        break;
    }
}

if ($show_title){

    echo '
Related products
';

    foreach($products as $product) {
        if(in_array($product->post_title, $current_article_tags, true)) {
            echo '
'.get_the_title($product).'
';
        }
    }

}
//wp_reset_postdata();
?>

Just check if the array has any item. If it does then only show the title and the products.
Comment: @Amesey I have updated the answer, this should work, pls give it a go.
Comment: This still displays the title regardless, I may have not bee clear in my post, I only want to display the title if any of the product post titles match any of the current article tags.
Comment: Basically, the related posts would be all the products having the same tag as current product ?
Comment: Nearly, it will be all the products who's title match that of the current article tags. So I would add product title as tags in an article to link them to the product - which works, but I only want to display the section heading 'related products' if there is a match.
Comment: Thank my man, that works perfectly, you're a scholar! :)
Comment: is there a way to query the tag slug instead of name? This way the comparison doesn't have to be case sensitive.


How do you make an existing variable (from a module) available for use in my__node.tpl.php? D7

Question: The contrib module i'm using (media gallery) outputs a block with a single thumbnail used to trigger a lightbox gallery.
The module has a tpl file used to render the thumbnail.
I want to isolate the single block thumbnail image ($media_gallery_item used in media_gallery_media_item_thumbnail.tpl.php) and insert it directly into a new node template (node--media-gallery.tpl.php)so that I can float the image in the body field (and preserve the lightbox trigger).
This is my first attempt at using a preprocessor.
Incidentally, I posted in the modules issue queue two weeks ago. I'm posting here as well to hopefully get a quicker response.
Answer: The only variables different template files have in common are the ones returned from template_preprocess(), or hook_preprocess(). See also _template_preprocess_default_variables(), which defines the default values for some of those variables.
Comment: Thank you. Im looking into template_preprocess now. Im looking for some working examples of template_preprocess() that I could fill in the blanks.


Use map() function with string

Question: Is there a way to use map() function with a string instead of a list? Or the map() function is meant only to work with lists?
For instance, ignoring the content of the lambda function, this code returns a map object and not a string:
def rot_13(string):
    alph = 'abcdefghijklmnopqrstuwxyz'
    return str(map(lambda i: alph[(alph.find(i)+13) % len(alph)], string))

Comment: `map` returns a generator in Python3, try: `return "".join(list(map(lambda i: alph[(alph.find(i)+13) % len(alph)], string)))`
Comment: @MauriceMeyer map returns a map object, not a generator
Comment: You can turn a string into a list with something like `a_list = list(a_string)`.
Comment: Yes. `map` **always** returns a map object. No matter the iterable you are napping over. It is meant to work with any iterable.
Answer: Using list/generator comprehensions is preferable (more Pythonic) to map():
def rot_13(string):
    alph = 'abcdefghijklmnopqrstuwxyz'
    return ''.join(alph[(alph.find(i)+13) % len(alph)] for i in string)

Answer: python3 map returns a generator, so you have to consume it, using str.join is the easiest way:
"".join(map(lambda i: alph[(alph.find(i)+13) % len(alph)], string))

It is similar to this code:
my_string = ""
for l in map(lambda i: alph[(alph.find(i)+13) % len(alph)], string):
    my_string += l

Comment: `map` does not return a generator, it returns a map-object, which is an iterator but not a generator.

Use map() function with string


Does a scalar represent a linear map?

Question: I have been wondering recently if a $1 \times 1$ matrix reprsents a scalar, and after doing some reading I'm still not satisfied. I've decided to ask this question from a different perspective: does a scalar represent a $1 \times 1$ map?
Because any matrix is a linear map between two bases, that would imply that a $1 \times 1$ matrix is an isomorphism between two 1 dimensional spaces.
So in the function/map $ f(x) = rx $ where r is some number, isn't $r$ just a scalar? This is a map and so can't this map be represented by the matrix $(r)$? Does that not, then, imply that a $1 \times 1$ and a scalar are the same?
Obviously, multiplication between a $1 \times 1$ matrix and a $n\times m$ matrix where $n \neq 1$ is not defined, but $1 \times 1$ matrices seem to behave like scalars in all other cases, so why isn't an exception made? And what is the fundamental difference between a $1 \times 1$ map and a scalar, if there is one?
Comment: Once you've chosen a basis for both the domain and codomain sure -- a matrix can *represent* a linear map.
Comment: I wouldn't say a matrix *is* a linear map.
Comment: Why? Any matrix represents a linear map.
Comment: I don't see how the answer you accepted answers your question. It only talks about scalars for a **one**-dimensional vector space, which is so trivial as to be a field itself.
Comment: @user21820 I believe (but could be entirely wrong) that's what OP meant by "$1\times 1$ map": a map between 1D vector spaces.
Comment: @Bye_World: I'm quite sure that the asker was asking about scalar multiplication on matrices, otherwise why say "Obviously, multiplication between a 1×1 matrix and a n×m matrix where n≠1 is not defined, but 1×1 matrices seem to behave like scalars in all other cases, so why isn't an exception made?"?
Comment: @user21820 My interpretation is that OP is conflating different ideas.  But that's OK -- with all the different answers here OP should get a better understanding of what's going on.
Comment: @Bye_World: Ok I see that it's possible that the asker is conflating things. We'll see I guess.
Answer: Any linear map from a one dimensional vector space to another is given by multiplication by a constant, or a $1\times 1$ matrix, once you've chosen basis (bases).
The $1\times 1$ matrix however changes depending on the choice of basis. A scalar in linear algebra is usually and element of the field the vector space is over, which is independent of the choice of basis for the vector space itself.
Answer: I'll expand on snulty's answer by giving an example.
Let's take a linear map $f:\Bbb R\to \Bbb R$ defined by $f(x) = 3x$.  First I choose the standard basis, $\{1\}$, for both the domain and codomain of this map.  Then clearly the matrix which represents this map is $(3)$.
But let's try a different pair of bases. I'll choose the basis $\{2\}$ for the domain and $\{3\}$ for the codomain of this function.  Then the matrix which represents this map is $\left(2\right)$.  How do I know?  Well let's check what happens when we try to transform the "vector" $6$.  The component of $6$ wrt the basis $\{2\}$ is $(3)$ so we multiply out the matrices $$\left(2\right)(3) = \left(6\right)$$ which is the component of the vector $18$ wrt the basis $\{3\}$.
So as you can see the $3$ in the definition of the map is a member of the field $\Bbb R$ and is independent of the bases chosen for the domain and codomain of the linear function.  However, the sole entry of the matrix which represents the function depends on the bases we choose for the domain and codomain of our mapping.
Comment: It's probably worth noting that if you demand that the bases of domain and codomain be the same, then the matrix is definitely just $(3)$. One can certainly find situations where this interpretation is useful (e.g. $f$ is a map from a vector space to itself) and situations where the interpretation elaborated in your post is useful (e.g. $f$ is a map between unrelated copies of a vector space).
Answer: If $A$ is an $n \times m$ matrix representing some linear map from $\mathbb{R}^m$ to $\mathbb{R}^n$, then it is helpful to note that the $j$th column of $A$ is the image of the $j$th basis vector (e.g., if you are using the standard basis, then it is the vector with a $1$ in the $j$th component, and all other components zero). Sticking with the standard basis, the columns of $A$ are elements of the image space $\mathbb{R}^n$.
If $A=[r]$ is $1 \times 1$, then yes it is a linear map $\mathbb{R} \to \mathbb{R}$. Under the standard basis, this does take the form $x \mapsto rx$ as you noted. From the previous paragraph, you can also think of the single entry $r$ as the image of the element $1$ (since $r \cdot 1 = r$), and clearly $r$ is an element of the image space $\mathbb{R}$.
I am not sure what your confusion is concerning scalars. The entries of vectors and matrices are scalars. In particular, a $1$-dimensional vector and a $1\times 1$ matrix can be thought of as a scalar, but can also still be interpreted as a vector or a matrix / linear map respectively.
Answer: A vector space is a two-sorted structure, one sort being vectors and the other sort being scalars. Scalars act linearly on vectors via scalar multiplication, and a scalar multiplication is nothing more than a scaling operation, so it is no surprise why "scalar" has that name. Of course, scaling operations are (meant to be) linear operators on vectors, and for finite-dimensional vector spaces, linear operators on vectors are isomorphic to matrices (with operator composition corresponding to matrix multiplication).
Specifically, given any finite-dimensional vector space $V$:

$c \cdot v = \pmatrix{ c & 0 & \cdots & 0 \\ 0 & c & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & c } \pmatrix{ x \\ y \\ \vdots \\ z }$ for any scalar $c$ and vector $v$ in $V$, where $\pmatrix{ x \\ y \\ \vdots \\ z }$ represents $v$.

Note that the above is valid regardless of which basis we use for $V$. If you choose a different basis then $v$ will have a different representation, but the result after the matrix multiplication will be the representation of the same scaled $v$, namely $c \cdot v$ here.
So it is not correct to think of a scalar as a $1 \times 1$ matrix, even though it is true that the field of scalars alone by itself is isomorphic to the field of $1 \times 1$ matrices. That is just a natural coincidence, but whenever we think of scalars it is with respect to a larger vector space structure, in which case scalars are not at all $1 \times 1$ matrices. For an $n$-dimensional vector space, scalars correspond to a certain kind of $n \times n$ matrices as shown above.
Note that the correspondence is not at all equality. That is why the same collection of scalars can be used in many different vector spaces with different (or even non-existent) dimension. It is only with respect to each vector space structure that scalars are isomorphic to a particular collection of matrices.
Since not all vector spaces have matrix representations, scalars are in general just (isomorphic to) a special collection of linear maps that are also a field under pointwise addition and composition.
Exactly the same thing applies to scalar multiplication of matrices, which is nothing more than composition of a scaling operation after the linear map represented by the matrix.
Specifically, given any finite-dimensional vector space $V$:

$c M = \pmatrix{ c & 0 & \cdots & 0 \\ 0 & c & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & c } M$ for any scalar $c$ in $V$ and matrix $M$ over a basis of $V$.
Comment: Thank you for this long answer. As far as I can tell, you are essentially saying the same thing as snulty and Bye_World, but this definitely clarifies the entire thing and the foundations more.
Comment: There is another approach of considering $c \cdot v$ to be $v \pmatrix{c}$ where $\pmatrix{c}$ would be a $1 \times 1$ matrix, but this is not the intended meaning of matrices, which represent linear maps, unless you first show that vectors themselves can be treated as linear maps, which depending on your point of view may not be valid even though it works out for finite-dimensional vector spaces.
Comment: "in many different vector spaces with different (or even non-existent) dimension." — what would be a vector space without dimension?
Comment: @celtschk: It depends heavily on your set-theoretic axioms. If you only have ZF, some vector spaces may not even have a basis, and even if it does it may have bases with different cardinality (http://mathoverflow.net/q/93242).
Comment: @user3210986: You're welcome and I'm glad that my answer has cleared it up. If you have any further queries I'll be glad to help.
Answer: Yes, a scalar $s \in \mathbb{F}$ does represent the map
$$
T : \mathbb{F} \to \mathbb{F} : T(x) = s x
$$
Because of
$$
T(\alpha x + \beta y)
= s(\alpha x + \beta y)
= \alpha s x + \beta s y
= \alpha T(x) + \beta T(y)
\quad (\alpha, \beta, x, y \in \mathbb{F})
$$
it is a linear map.
Answer: In terms of matrix algebra, there are two senses in which a scalar $r$ determines a map:

It acts on vector spaces, sending $v \mapsto rv$
It acts on linear transformations, sending $T \mapsto rT$.

The former should be thought of as the linear transformation $r I_V$, where $I_V$ is the identity transformation on the vector space $V$.
For the the second form, there is a way to equate a scalar with a $1 \times 1$ matrix by using the tensor product: specifically, the linear transformation
$$ V \xrightarrow{rT} W $$
that sends $v \mapsto r T(v)$ can be rewritten as a linear transformation
$$ V \to \mathbb{R} \otimes V \xrightarrow{[r] \otimes T} \mathbb{R} \otimes W \to W $$
where the maps send:

$v \mapsto 1 \otimes v$
$[s] \otimes v \mapsto ([r][s]) \otimes T(v)$
$[s] \otimes w \mapsto sw$

where I've identified vectors in $\mathbb{R}^n$ with $n \times 1$ matrices.
So, if we always identify $V$ and $\mathbb{R} \otimes V$ with the standard maps used above, then
$$ rT = [r] \otimes T$$
For example, we can see this when $V$ is a standard vector space and $T$ a matrix, by the Kronecker product of matrices.

Does a scalar represent a linear map?


What's the Scala for a declaration of "Class"

Question: I'm obviously missing something about why the following does not compile:
trait SomeTrait{
def homepageClass[A <: SomeType]: Class[A]
}

class SomeOtherType extends SomeType

object SomeObject extends SomeTrait{
def homepageClass = classOf[SomeOtherType]
}

Answer: The problem here is that the following two declarations are different:
def homepageClass[A <: SomeType]: Class[A]  // has type parameters
def homepageClass = classOf[SomeOtherType]  // doesn't have type parameters

To accomplish what you want you need to declare an abstract type, like this:
trait SomeTrait{
  type A <: SomeType
  def homepageClass: Class[A]
}

object SomeObject extends SomeTrait {
  type A = SomeOtherType
  def homepageClass: Class[A] = classOf[SomeOtherType]
}

Or
trait SomeTrait[A <: SomeType] {
  def homepageClass: Class[A]
}

object SomeObject extends SomeTrait[SomeOtherType] {
  def homepageClass: Class[SomeOtherType] = classOf[SomeOtherType]
}

Answer: def homepageClass[A <: SomeType]: Class[A]

says "whatever subclass A of SomeType you give, I can return a Class[A]. In particular, it can be called like this:
class SomeThirdType extends SomeType

val x: Class[SomeThirdType] = SomeObject.homepageClass[SomeThirdType]

A more direct equivalent than Daniel gives is an existential type:
trait SomeTrait{
  def homepageClass: Class[A forSome {type A <: SomeType}]
}

or
trait SomeTrait{
  def homepageClass: Class[_ <: SomeType]
}

UPDATE: Two differences between solutions I can think about:

Existential types produce the same bytecode as Java wildcards (and their major intended use is interoperation with wildcards).
You can write a refinement type for the abstract type member solution:
 val x: SomeTrait {type A = SomeOtherType} = SomeObject

I don't think you can for existential types.

Any others?
Comment: If you now explain the difference between my suggestion and the existential type version, that would be great! :-)


ldapscripts ldapaddgroup fails with "No such object (32)" and "Error adding group ${groupname} to LDAP"

Question: I had some issues and fixed them, but there is no post on stackexchange about it, so I'll post a question and answer too.
(EDIT: apparently there is a very related post...which I couldn't find any way other than looking for "GSUFFIX"... already knowing the answer)
I installed the packages that come with the distro:
apt install slapd ldap-utils ldapscripts libnss-ldap

And then I upgraded from something older to Ubuntu 16.04. (the cause of the 2nd problem?)
or you can change that to the older way using nslcd which works way better (doesn't make systemd-logind eat 100% cpu and never fully start, and some strange boot up race conditions... nssldap-update-ignoreusers is supposed to fix such things but doesn't):
apt install libnss-ldapd libpam-ldap

Take the default for everything, except set things like your distinguished name and password.
And now you'd think it would just work... the distro of course has a setup that works since you used only their packages, right? But instead ldapscripts fails in a few ways.
problem 1 - already solved
is that the debian prompts and things asked for a password, and it put it in a file, but it will put it with a new line, and the scripts don't work unless you remove that.
So you can fix that:
echo -n "secretgoeshere" > /etc/ldap.secret
echo -n "secretgoeshere" > /etc/ldapscripts/ldapscripts.passwd

# just in case...
chown root:root /etc/ldap.secret /etc/ldapscripts/ldapscripts.passwd
chmod go= /etc/ldap.secret /etc/ldapscripts/ldapscripts.passwd

# and because you can't be sure it won't break it again next time debconf runs, but I can assure you it will
chattr +i /etc/ldap.secret /etc/ldapscripts/ldapscripts.passwd

problem 2 - which I'll answer separately
# ldapaddgroup test
Error adding group test to LDAP

You can get a tiny bit more detail from the log
# tail /var/log/ldapscripts.log
Apr 09 16:51:57 ldapservername ldapscripts: ldapaddgroup(peter): /usr/sbin/ldapaddgroup test
No such object (32)
Matched DN: dc=example,dc=com
No such object (32)
Matched DN: dc=example,dc=com
ldap_add: No such object (32)
        matched DN: dc=example,dc=com
  -> Error adding group test to LDAP

And of course it doesn't say which object you referred to that doesn't exist. Obviously not the group name since it should only complain when it already exists, and not existing is a requirement. And ldapscripts deletes the temp files, so you can't even see the ldif.
So this is the problem to solve in an answer, which I found nowhere online.
Answer: So to investigate, I took the ldapaddgroup script, and copied it and modified it:
mkdir ~/ldapscripts-mod
cd ~/ldapscripts-mod

cp /usr/sbin/ldapaddgroup .
cp /usr/share/ldapscripts/runtime .

vim ldapaddgroup
    change the runtime source line like this (optional... just do this if you customize the runtime script):

    -_RUNTIMEFILE="/usr/share/ldapscripts/runtime"
    +#_RUNTIMEFILE="/usr/share/ldapscripts/runtime"
    +_RUNTIMEFILE="/root/ldapscripts-mod/runtime"

    you could also output the ldif if you like:

    -$_getldif | _filterldif | _askattrs | _utf8encode | _ldapadd
    +$_getldif | _filterldif | _askattrs | _utf8encode | tee ~/ldapscripts-mod/test.ldif | _ldapadd

vim runtime
    I added echos everywhere (make sure to >&2 or they end up in that pipe above)... but nothing really worth noting here.

    One of the echos showed which ldapadd command it used so I could use it below (with the cat added).

And so I saw that the ldif had ou=Groups but my database has no such ou... it has ou=Group. I confirmed that is the problem by editing the ldif and adding it manually:
cat ~/ldapscripts-mod/test.ldif | /usr/bin/ldapadd -y /etc/ldapscripts/ldapscripts.passwd -D cn=admin,dc=example,dc=com -xH ldap://ldapservername/

And you can basically see it like this too:
# slapcat | grep -Eo "ou=[^,]+" | sort -u
ou=Group
ou=Hosts
ou=Idmap
ou=people
ou=People

Luckily, this is configurable easily...
vim /etc/ldapscripts/ldapscripts.conf
    GSUFFIX="ou=Group"
    USUFFIX="ou=People"
    MSUFFIX="ou=Hosts"

I don't really know what MSUFFIX is or whether I fixed anything...but I at least set it to something that exists. The other 2 are obviously correct. And now it works.


Calculation of codimension

Question: I've just learnt the idea of codimension, then I try to find some exercises to calculate the codimension of some maximal ideal $J$ in the ring $R=k[x,y,z]/I$, I find it somewhat tricky. For example,

If $R=k[x,y,z]/(x^2y^2z^2,xy^3z^2)$ and $J=(x,y,z)$.

Then I just need to find the prime ideals $P_i$ in $k[x,y,z]$ so that $(x^2y^2z^2,xy^3z^2)\subsetneq P_0\subsetneq P_1 \subsetneq ... \subsetneq P_n=(x,y,z)$ is a chain of primes of maximal length. After some trial and error, I find $P_0=(x)\subsetneq (x,y)=P_1$ can be put in the chain. Since Krull dimension of $k[x,y,z]$ is 3, I'm sure this is the longest I can find.
Sometimes life is not so beautiful, for example,

If $R=k[x,y,z]/(x)(y,z)$ and $J=(x+1,y,z)$.

This time I only find $P_0=(y,z)$ can be put in the chain. But I can't prove it's the maximal chain.
Sometimes I'm even stuck from the start, for example,

If $R=k[x,y,z]/(x^5-y^2,x^3-z^2,z^5-y^3)$ and $J=(x,y,z)$.

This time I don't even know if $(x^5-y^2,x^3-z^2,z^5-y^3)$ is prime or not.
Anybody can show me some more general methods of finding primes that can be put into the chain that both end are known, and prove the maximality? You can use your own examples.
Answer: Well, maybe some dimension formulas are welcome. The best for you is the following:

Let $R=K[X_1,\dots,X_n]$ and $I\subset R$. Then $\operatorname{ht}(I)=\dim R-\dim R/I$.

Of course, $\dim R=n$, and $\operatorname{ht}(I)$ is by definition the minimum of $\operatorname{ht}(P)$ with $P\supseteq I$.

$I=(x^2y^2z^2,xy^3z^2)$. This ideal has exactly three minimal primes, all of height $1$, so $\dim R/I=3-1=2$.
$I=(x)(y,z)$. This ideal has two minimal primes, one of height one and one height two, so its height is $1$.
$I=(x^5-y^2,x^3-z^2,z^5-y^3)$. Well, this can be done by noticing that $I$ is not contained in a prime of height one (which must be principal, and thus generated by an irreducible polynomial). This shows that $\operatorname{ht}(I)\ge 2$. Now let's define a homomorphism $\varphi:k[x,y,z]\to k[t]$ by sending $x\mapsto t^2$, $y\mapsto t^5$, and $z\mapsto t^3$. Then $I\subseteq \ker\varphi$ and $k[x,y,z]/\ker\varphi\simeq k[t]$, so $\ker\varphi $ is a prime ideal of height $2$. In conclusion, $\operatorname{ht}(I)=2$. (If $I$ would be prime, then $I=\ker\varphi$, but this is not true since $xz-y\in\ker\varphi$ and $xz-y\notin I$.)
Comment: Certainly there are more elementary approaches, on the direction you started to think, but I find them rather tricky.
Answer: Have you tried drawing pictures?
E.g. $k[x,y,z]/(x)(y,z)$ corresponds to the algebraic set which is the union of the plane $x = 0$ and the line $y = z = 0$.
The ideal $J = (x+1,y,z)$ corresponds to the point $(-1,0,0)$, which lies on
both the line but not the plane.  A point has coim'n 1 in a line, and so the codim'n is 2.
E.g. For $k[x,y,z]/(x^5 - y^2, z^5 - y^3, x^3 - z^2)$,
think first about $k[x,y,z]/(x^5 - y^2, z^5 - y^3).$
This is a curve: $y$ can take whatever value you want, then $x$ and $z$ are determined from $y$ up to $5$th roots of $1$ (i.e. $x = y^{2/5}, z = y^{3/5}$).
Now the additional condition $x^3 = z^2$ just says that these $5$th roots of unity are
not independent, i.e. having chosen the $5$th root of $y^2$ giving $x$, the $5$th root giving $z$ is pinned down.  So this last equation just cuts out a particular component of the initial curve.  A point on a curve has codimension $1$, so the codimension is $1$.

Calculation of codimension


IOS - Como criar Célula customizada para TableView?

Question: Quero fazer uma  célula customizada para minha TableView. Mas ela está apresentando problemas que não estou conseguindo resolver.
Ela funcionou normalmente quando fiz com a célula padrão, mas quando fiz customizada deu problema
Estava usando esta explicação como ajuda:
http://www.appcoda.com/customize-table-view-cells-for-uitableview/
Fiz minha célula desta forma..
SimpleTableCell.xib e SimpleTableCell.h:

SimpleTableCell.m
<code>import "SimpleTableCell.h"

@interface SimpleTableCell ()
@end
@implementation SimpleTableCell

@synthesize nome = _nome;
@synthesize texto = _texto;
@synthesize data = _data;
@synthesize foto = _foto;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
}
</code>
A minha ViewController (Onde esta a TableView), esta desta forma.
ViewController.m
<code>#import "ViewController.h"
#import "SimpleTableCell.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //________________________
    _tabela.dataSource = self;
    _tabela.delegate = self;
    //________________________
    //Na ViewDidLoad eu pego um Json e armazenando seus dados em uma lista (lista manda dados para célula)
    _users = [[NSMutableArray alloc] init];

    NSURLRequest *requisicao = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.meuSite.com.br/mural/listener.php?a=10"]];
    NSData *resposta = [NSURLConnection sendSynchronousRequest:requisicao
                                             returningResponse:nil
                                                         error:nil];
    NSError *jsonParsingError = nil;
    NSArray *array = [NSJSONSerialization JSONObjectWithData: resposta options: nil error: &jsonParsingError];
    NSLog(@"result = %@", array.firstObject);
    int total = [array count];

    for (int x =0; x<total; x++) {
        [_users addObject:[array objectAtIndex:x]];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{//tamanho da lista
    return [_users count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableCell";
    SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {
        NSLog(@"QUANDO COMPILO SÓ VEM ATÉ AQUI. . .");
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
        NSLog(@"%d", 23);
        cell = [nib objectAtIndex:0];
        NSLog(@"%d", 3);
    }
    NSDictionary * usuario = [_users objectAtIndex:indexPath.row];
    cell.nome.text = [usuario objectForKey:@"nome"];
    cell.texto.text = [usuario objectForKey:@"texto"];
    cell.data.text = [usuario objectForKey:@"data"];
    NSString *img = @"http://diegocavalca.com/wp-content/uploads/2016/01/iphone_6_home_screen_hero.jpg";

    NSString *url_imagem = [NSString stringWithFormat:img];
    NSLog(@"%@", url_imagem);

    NSURL *url=[NSURL URLWithString:url_imagem];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         cell.foto.image =[UIImage imageWithData:data];
     }];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
@end
</code>
ViewController.h
<code>#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>
@property NSMutableArray * users;
@property NSIndexPath * selecionado;
@property (weak, nonatomic) IBOutlet UITableView *tabela;

@end
</code>
Erro Apresentado. . .
-[NSNull length]: unrecognized selector sent to instance 0x381cf588'
Caso alguém saiba como posso resolver isso, agradeço desde já.
Comment: O **nib** no caso, é o seu arquivo de interface, que pelo que eu entendi é o `MuralCell.xib`, mas sua classe tem o nome de `SimpleTableCell` e parece que o nome do arquivo é `MuralCellM.h`. Enfim, fiquei bem confuso em relação a estes nomes, e caso seja isso, esta é a razão. O erro diz que não consegue carregar um "nib" de nome *SimpleTableCell*.
Comment: Coloca um "breakpoint for all execptions" no menu debug, ai ele para na linha em que ocorre o problema. Desse jeito fica difícil dizer o que pode ser.
Comment: Você precisa implementar o seguinte método também: `- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; }`
Comment: Nunca trabalhei com célula criando XIB, eu faço pelo InterfaceBuilder mesmo... você já tentou debugar seu código linha a linha para ver onde está logando esse error? Eu chutaria que é na hora de ler o json que não está achando alguma key, mas pode ser na hora de carregar o XIB também. Enfim, só debugando pra resolver.
Comment: Obrigado Paulo, vou corrigir isso agora mesmo!
caso consiga ou não aviso logo logo.
Comment: Tinha Razão, estava ocorrendo conflito entre os nome, já corrigi aqui e na pergunta também. Mas agora ele pega todas as informações do JSON e após isso, apresenta um erro informando o problema que atualizei na pergunta.
Comment: Ele não esta mais apresentando erros, porem quando mando compilar, não mostra nenhuma informação na lista. A tela fica toda em branco. Estou trabalhando em cima disso pra ver se consigo resolver. A unica coisa que aparece após a execução eu deixei informado em (Erros Apresentado) na pergunta
Comment: Obrigado pela dica Luis, implementei na ViewController.m mas o problema mencionado antes permaneceu.
Comment: Os JSON estão ok Henrique, estava fazendo isso agora. Vou tentar resolver isso hoje a noite. Amanha informo aqui caso tenha conseguido, de qualquer forma caso encontre alguma solução, informe que a noite eu volto aqui. Abraço!
Answer: Bom, o exemplo que peguei como base, era um exemplo antigo, não possuía nem uma storyboard, apenas arquivos .xib, decidi fazer um novo projeto e com ajuda de algumas páginas da internet, consegui fazer desta forma.
Utilizei esta página como base: http://www.makemegeek.com/custom-uitableviewcell-example-ios/
Alterei o nome SimpleTableCell para CustomCell.
ficou desta forma:
CustomCell.h
<code>#import <UIKit/UIKit.h>

@interface CustomCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *name;
@property (weak, nonatomic) IBOutlet UILabel *dataS;
@property (weak, nonatomic) IBOutlet UITextView *texto;

@end
</code>
CustomCell.m
<code>#import "CustomCell.h"

@implementation CustomCell
@synthesize name,imageView,dataS;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {}
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:selected animated:animated];
}

@end
</code>
Alterei o nome da ViewController para MuralViewController.
Ficou desta forma:
MuralViewController.h
<code>#import <UIKit/UIKit.h>

@interface MuralViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray *ImageArray;//foodImageArray
}
@property (weak, nonatomic) IBOutlet UITableView *tableViewObject;
@property NSMutableArray * users;

@end
</code>
MuralViewController.m
<code>#import "MuralViewController.h"
#import "CustomCell.h"

@interface MuralViewController ()

@end

@implementation MuralViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    ImageArray = [[NSMutableArray alloc] initWithObjects:@"image0.png", nil];
    //ADICIONADO . . .

    _users = [[NSMutableArray alloc] init];//Array de objétos json pegados de um link. . .

    NSURLRequest *requisicao = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.meuSite.com.br/mural/listener.php?a=50"]];

    NSData *resposta = [NSURLConnection sendSynchronousRequest:requisicao
                                             returningResponse:nil error:nil];
    NSError *jsonParsingError = nil;
    NSArray *array = [NSJSONSerialization JSONObjectWithData: resposta options: nil error: &jsonParsingError];

    NSDictionary *resultado = [NSJSONSerialization JSONObjectWithData:resposta
                                                              options:0 error:&jsonParsingError];

    NSLog(@"result = %@", resultado);
    int total = [array count];
    for (int x =0; x<total; x++) {
        NSLog(@"%@", [array objectAtIndex:x]);
        [_users addObject:[array objectAtIndex:x]];//Armazena na lista os dados json. . .
    }
}

- (void)didReceiveMemoryWarning{[super didReceiveMemoryWarning];}

#pragma - mark UITableView Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_users count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;//define o tamanho em que a célula vai aparecer. . .
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"CustomCell";

    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        cell = [nibArray objectAtIndex:0];
    }

    NSDictionary * usuario = [_users objectAtIndex:indexPath.row];

    //ALOCA DADOS EM UMA STRING. . .
    NSString *nome345 = [usuario objectForKey:@"nome"];
    NSString *data = [usuario objectForKey:@"data"];
    NSString *textok = [usuario objectForKey:@"texto"];

    nome345 = [NSString stringWithFormat:@"%@", nome345];//Tive que sobreescrever, quando mandava direto dava eero no if logo abaixo. . .
    NSLog(@"%@", nome345);

    //ESCREVE DADOS NA CÉLULA. . .
    if([nome345 isEqualToString:@"<null>"]){//Se o nome for null, ele carrega a imagem no lugar no nome, assim nunca vai ter nome e imagem juntos. . .
        cell.imageView.image = [UIImage imageNamed:[ImageArray objectAtIndex:0]];
    }else{
        cell.Name.text = [NSString stringWithFormat:@"%@", nome345];
    }

    cell.dataS.text = [NSString stringWithFormat:@"%@", data];
    cell.texto.text = [NSString stringWithFormat:@"%@", textok];
    return cell;
}
@end
</code>
Desta forma ele esta funcionando bem, lembrando que tive que utilizar:
-Foundation.framework
-CoreGraphics.framework
-UIKit.framework
E também na .storyboard, adicionei à TableView os Outlets dataSource e delegate


How is $2(\ln \tan x + c)$ simplified to $A \tan^2 x$ where $A =2c$

Question: I'm trying to follow this reasoning:
$1/2 \ln(4 +y^2) = \ln(\tan x) + C$
$\ln(4 +y^2) = 2\ln(\tan x) + \ln A$  ( constant 2C = A)
$4 + y^2 = A \tan^2 x$
Comment: Try seeing what happens when you use $\exp()$ on both sides.
Comment: Recall $a=b\implies $e^a=e^b$. Now apply this statement to yours and utilize properties of logarithms and exponentiation.
Comment: Between 1) and 2) where did the ln A come from?  Isn't he setting 2C = ln A, not 2C = A, as he said?  Or am I missing something?
Comment: When you take the 2 into the ln, it becomes ln (tan x)$^2$?
Answer: $\frac{1}{2}ln(4+ y^2)= ln(tan(x))+ C$
Multiply on both sides by 2:
$ln(4+ y^2)= 2ln(tan(x))+ 2C$
Taking $A= e^{2C}$ (NOT A= 2C) we have $2C= ln(A)$ so
$ln(4+ y^2)= ln(tan^2(x))+ ln(A)= ln(Atan^2(x))$
Now take the exponential of both sides:
$e^{ln(4+ y^2)}= e^{ln(Atan^2(x))}$
$4+ y^2= Atan^2(x)$
I have used:
1)  $2ln(x)= ln(x^2)$
2)  $ln(a)+ ln(b)= ln(ab)$
3)  $e^{ln(x)}= x$
Comment: Please use \ln, \tan etc, it looks better.
Comment: So the author made a mistake?