record update in different row vb.net

Question: I have a stored procedure that works perfectly when updating in sql server. The problem here is that when execute to vb.net. Records of different row is updated.
From the image shown,For instance i have selected the studentID 383 in datagridview, student 382 will be updated. and if i selected student 380 ,student 379 will be updated and so on.

stored procedure code:
ALTER PROCEDURE [dbo].[uspUpdate]
-- Add the parameters for the stored procedure here
  @SurName     NVARCHAR(20),
  @FirstName   NVARCHAR(20),
  @middleName  NVARCHAR(20),
  @StudAddress NVARCHAR(20),
  @Birthday    DATE,
  @Gender      NVARCHAR(20),
  @Nationality NVARCHAR(20),
  @BirthPlace  NVARCHAR(20),
  @TelNum      NVARCHAR(20),
  @SWG         NVARCHAR(20),
  @DWG         DATE ,
  @SLA         NVARCHAR(20),
  @Note        NVARCHAR(20),
  @StudPic IMAGE ,
  @FFirstName  NVARCHAR(20),
  @FLastName   NVARCHAR(20),
  @FMI         NVARCHAR(20),
  @FOccupation NVARCHAR(20),
  @FTelNum     NVARCHAR(20),
  @MFirstName  NVARCHAR(20),
  @MLastName   NVARCHAR(20),
  @MMI         NVARCHAR(20),
  @MOccupation NVARCHAR(20),
  @MTelNum     NVARCHAR(20),
  @CFirstName  NVARCHAR(20),
  @CLastName   NVARCHAR(20),
  @CMI         NVARCHAR(20),
  @CAddress    NVARCHAR(20),
  @CTelNum     NVARCHAR(20),
  @CMobile     NVARCHAR(20),
  @studID      INT
AS
  BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET nocount ON;
    BEGIN try
      BEGIN TRAN
      UPDATE parentinformation
      SET    father_firstname = @FFirstName,
             father_lastname = @FLastName,
             father_mi = @FMI,
             father_occupation = @FOccupation,
             father_telnum = @FTelNum ,
             mother_firstname = @MFirstName,
             mother_lastname = @MLastName,
             mother_mi = @MMI,
             mother_occupation = @MOccupation,
             mother_telnum = @MTelNum,
             contact_firstname = @CFirstName ,
             contact_lastname = @CLastName,
             contact_mi = @CMI,
             contact_mobile = @CMobile,
             contact_telnum = @CTelNum
      FROM   parentinformation PI,
             studentinformation SI
      WHERE  pi.parentid = si.parentid
      AND    pi.parentid = @studID
      UPDATE studentinformation
      SET    surname = @SurName,
             firstname = @FirstName,
             middlename = @middleName,
             studaddress =@StudAddress,
             birthday = @Birthday,
             gender = @Gender,
             nationality = @Nationality,
             birthplace = @BirthPlace,
             telnum = @TelNum,
             schoolwheregraduated = @SWG,
             dateswhengraduated = @DWG,
             schoollastattended = @SLA,
             note = @Note,
             studimage = @StudPic
      FROM   parentinformation PI,
             studentinformation SI
      WHERE  pi.parentid = si.parentid
      AND    pi.parentid = @studID
      COMMIT TRAN
    END try

vb.net code when executing the update statement
  Using cmd As New SqlClient.SqlCommand("dbo.uspUpdate", cn)
            cmd.Parameters.AddWithValue("@StudID", frmView.dgv1.SelectedCells(0).Value)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.Add("@SurName", SqlDbType.VarChar, 100).Value = txtStudLN.Text
            cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 100).Value = txtStudFN.Text
            cmd.Parameters.Add("@middleName", SqlDbType.VarChar, 100).Value = txtStudMN.Text
            cmd.Parameters.Add("@StudAddress", SqlDbType.VarChar, 100).Value = txtAddress.Text
            cmd.Parameters.Add("@BirthDay", SqlDbType.VarChar, 100).Value = dtpBirthday.Text
            cmd.Parameters.Add("@Gender", SqlDbType.VarChar, 100).Value = Male
            cmd.Parameters.Add("@Nationality", SqlDbType.VarChar, 100).Value = cboNationality.Text
            cmd.Parameters.Add("@BirthPlace", SqlDbType.VarChar, 100).Value = txtPlaceOfBirth.Text
            cmd.Parameters.Add("@TelNum", SqlDbType.VarChar, 100).Value = txtStudentCP.Text
            cmd.Parameters.Add("@SWG", SqlDbType.VarChar, 100).Value = txtSWG.Text
            cmd.Parameters.Add("@DWG", SqlDbType.VarChar, 100).Value = dtpDWG.Text
            cmd.Parameters.Add("@SLA", SqlDbType.VarChar, 100).Value = txtSLA.Text
            cmd.Parameters.Add("@Note", SqlDbType.VarChar, 100).Value = txtNote.Text
            cmd.Parameters.Add("@FFirstName", SqlDbType.VarChar, 100).Value = txtFatherGN.Text
            cmd.Parameters.Add("@FLastName", SqlDbType.VarChar, 100).Value = txtFatherLN.Text
            cmd.Parameters.Add("@FMI", SqlDbType.VarChar, 100).Value = txtFatherMI.Text
            cmd.Parameters.Add("@FOccupation", SqlDbType.VarChar, 100).Value = txtFatherOccupation.Text
            cmd.Parameters.Add("@FTelNum", SqlDbType.VarChar, 100).Value = txtFatherCP.Text
            cmd.Parameters.Add("@MFirstName", SqlDbType.VarChar, 100).Value = txtMotherGN.Text
            cmd.Parameters.Add("@MLastName", SqlDbType.VarChar, 100).Value = txtMotherLN.Text
            cmd.Parameters.Add("@MMI", SqlDbType.VarChar, 100).Value = txtMotherMI.Text
            cmd.Parameters.Add("@MOccupation", SqlDbType.VarChar, 100).Value = txtMotherOccupation.Text
            cmd.Parameters.Add("@MTelNum", SqlDbType.VarChar, 100).Value = txtMotherCP.Text
            cmd.Parameters.Add("@CFirstName", SqlDbType.VarChar, 100).Value = txtContactGN.Text
            cmd.Parameters.Add("@CLastName", SqlDbType.VarChar, 100).Value = txtContactLN.Text
            cmd.Parameters.Add("@CMI", SqlDbType.VarChar, 100).Value = txtContactMI.Text
            cmd.Parameters.Add("@CAddress", SqlDbType.VarChar, 100).Value = txtContactAddress.Text
            cmd.Parameters.Add("@CTelNum", SqlDbType.VarChar, 100).Value = txtContactTelNum.Text
            cmd.Parameters.Add("@CMobile", SqlDbType.VarChar, 100).Value = txtContactCP.Text
            cmd.Parameters.Add(New SqlClient.SqlParameter("@StudPic", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)
            cmd.ExecuteNonQuery()
            MsgBox("Save Updated Successfully")
End using

Comment: It sounds like `frmView.dgv1.SelectedCells(0).Value` is not what you think it is. Also, this is weird: `WHERE PI.ParentID = SI.ParentID  AND PI.ParentID = @studID` - is this really the filter  you want?
Comment: @Crowcoder , yes , it is working in updating two tables. I know its kinda weird. Can you give me some idea on how to check if its really the StudentID that  will be updated.? thanks
Comment: Assign this : `frmView.dgv1.SelectedCells(0).Value` to a variable before adding it as a parameter and look at it in the debugger.
Comment: @Crowcoder where can i find the StudentID ? i did something like this [Debugging](http://img8.uploadhouse.com/fileuploads/21910/21910338ec54acc3383dc618486752aa39ec575b.png)
Comment: that is  how you would do it if the first selected cell contained the student id but clearly it doesn't. Are you sure you want the selected cell, or do you want the first cell in the selected row?
Comment: @Crowcoder I assign the value of `frmView.dgv1.SelectedCells(0).Value` to a variable and it has the right studentID as picture shown. [Variable assign](http://img7.uploadhouse.com/fileuploads/21910/2191069711d34f5748aea6e503927c749ae9a086.png).. what are some possible cause of the this if studID is right?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/99547/discussion-between-crowcoder-and-diether-silverious).
Answer: So after some side discussion it was determined that the joins that looked funny to me from the start were the problem. Student id is not the same as parent id. The parentinformation update needed to be:
UPDATE p
SET p.father_firstname = @FFirstName,
    p.father_lastname = @FLastName,
    ...
    ...
FROM parentinformation p
INNER JOIN studentinformation s
    ON p.parentid = s.parentid
WHERE s.StudentID = @studID;

And the student information requires no join at all, just a simple update where StudentID = @studID;
Answer: It is vital that you remember that when representing data from a database table in grids that grids use a zero (0) based array to display records.  So for example if you have a sql database in which you have a table whose primary key is of type integer and you set that to auto increment by 1 then as you add records to that table they will gain primary keys along the lines of 1,2,3 etc.
Now when you take that table and add it to a grid and set the leftmost column to show your primary keys you'll end up seeing rows as you do in your illustration above, incremented one by one.  HOWEVER, and this is the bit you need to take note of, the grid has actually numbered its own internal row collection starting at 0 and not at 1, so you cannot just take the index value of the grid's row and assume that it will relate to the primary key in your database because in fact it will be out by one.
So looking at your illustration above if you want to update information belonging to the primary key 381 and you select that row its index (the grid row that is) is in fact 380 NOT 381. If you use the grid row index to point to the primary key in your database then you need to add 1 to it;
grid.row(I) +1

Alternatively you need to take the value in the cell in the row you wish to update, convert it to and integer and use that.
It's also important to realise that this will also have bearings on any looping through grid rows that you may do.
Comment: while this is all true, OP is not using row index.
Comment: @Dom thanks for your comment. Base on the given code. Where can i put the `grid.row(I) + 1`. I get your point but i'm just a beginner in vb.net, that's why sometimes i'm kinda confuse.
Comment: If you place a break point on the Cmd.Execute nonquery line and then and then examine the value of frmView.dgv1.SelectedCells(0).Value when you have for example selected row 383 what value do you get?
Comment: Where exactly are you setting the value to be associated with @StudID?  .  It may well be that you need to set that as well.
Comment: @DomSinclair I assign the value of `frmView.dgv1.SelectedCells(0).Value` to a variable and it has the right studentID as picture shown. [Variable assign](http://img7.uploadhouse.com/fileuploads/21910/2191069711d34f5748aea6e503927c749ae9a086.png).. what are some possible cause of the this if studID is right?
Comment: @DomSinclair `@StudID` is in my stored procedure.. however.. When i test that procedure to an sql server. It works well.. My problem is kinda weird. Anyway base on my stored procedure, can u see any problem with my query that might cause the issue?
Comment: I can see that @StudID is in your stored Procedure but where is it being specifically set to a value.  I Suspect that when you've tested this in sql management studio you assigned a value to it , but I can't see you doing that in your vb.net code.

record update in different row vb.net


check at least one checkbox validation in jquery

Question: I have some checkboxes, something like this:
<form name="submit-form" name="submit-form">
property1
<input type="checkbox" name="property1">

property2
<input type="checkbox" name="property2">

property3
<input type="checkbox" name="property3">

property4
<input type="checkbox" name="property4">

property5
<input type="checkbox" name="property5">

property6
<input type="checkbox" name="property6">

<input type="submit">
</form>

I would like to validate that atleast one checkbox at a time. plz help me. thanks in advance
Comment: place actual html please
Answer: $("#YourbuttonId").click(function(){
    if($('#YourTableId').find('input[type=checkbox]:checked').length == 0)
    {
        alert('Please select atleast one checkbox');
    }
});

Update:
i saw your code and seems like you are using jquery validation plugin in that case this post will help you
and try giving your checkbox same name which exist in a group
http://forum.jquery.com/topic/check-that-at-least-1-checkbox-is-checked-using-jquery-validate-plugin
Comment: it works only when I refresh the page, not on submit the form.
Comment: it not works. there are some other validations, all are working except this
Comment: http://royalgroupinternational.com/add_enquiry/ check the source code of this for html.
Comment: for which checkbox group you want this
Comment: thanks, you help me a lot... that link helped me to solve the problem and all credit goes to you. thanks once again...
Answer: I'd wrap them all in a container with a div just for easier selecting, and then you can use:
if($('#wrapperID input:checked').length > 0) {
    'at least one is checked
}

Comment: OK. Then put the ID on the table.
Answer: try this
$('form').submit(function(e) {
    if($("input:checked").length == 0){
    alert('please checked atleast one');
    }
});

Answer: See this demo: http://jsfiddle.net/RGUTv/ OR your specific case demo here: http://jsfiddle.net/J98Ua/
My old response here: validation for at least one checkbox
hope rest fits the needs! :)
code
$(document).ready(function() {
    $('#my-form').submit(function() {
        amIChecked = false;
        $('input[type="checkbox"]').each(function() {
            if (this.checked) {
                amIChecked = true;
            }
        });
        if (amIChecked) {
            alert('atleast one box is checked');
        }
        else {
            alert('please check one checkbox!');
        }
        return false;
    });
});

Comment: it not works. I know u solve many of the problems of checkbox validation before this but it not works and I don't want it in alert...
Comment: @Ravneet'Abid' Cool man, lol can you make a demo of your problem of flick the JQ code please? Lemme know what part actually doesn't work.


Loop only when between 2 numbers

Question: I have been putting off asking this questions as it seemed like such a simple problem I could solve but i have be racking my brains and now cant think. I have tried loads of different combinations of code but cant seem to find the correct one.
My 2 porblems:

I need to create a loop that will only fire when a variable is between 2 numbers. Example (this does not work) : Do While SOPickRS.RecordCount >=1 and <=4
I need to a variable that monitors what record the loop is on. A counter could work however is there not an actual ADODB variable for it?

My Current Code:
While Not SOPickRS.EOF

        Do Until SOPickRS.RecordCount = 4

            'Do Stuff

        Loop

        Do Until SOPickRS.RecordCount = 8

             'Do Stuff

        Loop

        Do Until SOPickRS.RecordCount = 12

           'Do Stuff

        Loop

SOPickRS.MoveNext

Wend

GTG has also pointed that RecordCount will not work as it never changes.
Comment: RecordCount is the number of records in the recordset, not the index of the item you are currently looking at, so your Do While loop will either not run at all (if the recordset is empty or contains more than 3 items) or never stop.
Comment: what is the requirement is not clear. As @GTG said, recordcount gives number of records and it does not change, and either loop will not be executed or will not be terminated
Comment: I have just added some more of my current code to save confusion. My Loops are running however I need to limit them so they only run when the Record Count Is between two numbers
Comment: Ah yes I see what you mean now. I have updated my question again. (Bottom of post)
Comment: what is wrong with keeping track of the record index you have looped to in a simple variable?
Answer: Are you trying for something like this :
currentRecord = 1
While Not SOPickRS.EOF

    if (currentRecord  >=1 and currentRecord  <=4)
        'Do Stuff
    end if
    currentRecord = currentRecord + 1
wend

Loop only when between 2 numbers


Unable to add content?

Question: I am working on a project with a fresh install of Drupal 7.41 and the customer wanted to use a Themeforest layout.
Installation of core, theme and modules went without a problem, however, when I try to create content via 'article or basic page' nothing happens except a page refresh. No content shows in the content list and no content is created.
Yet, I am able to create a webform with the webform module.
Notes

I have checked my logs and there are no errors.  None!
I cleared my cache several times
I am running as Admin and the proper permissions have been checked.
My roles are in the proper order.  (Admin being at the bottom)
I created a new custom content type and that does not work either.  Even after enabling permissions.

Any insight would be greatly appreciated as I have never encountered this issue before.
Answer: Apparently there is an issue with the CKEditor module.  Once I disabled it I am now able to post content as normal.  I will have to find another WYSIWYG to replace it.
Comment: Have you checked that the ckeditor javascript library is correctly installed in your sites/all/libraries folder? Is it the correct version of the library? Visit admin/config/content/ckeditor . If there are any problems with th elibrary it will show there.

Unable to add content?


Python Selenium - Try/Except does not work

Question: I have a Selenium script, where I enter a series of websites, and get some data. Sometimes the data does not exist, and I simply want to write something like "Cant find x data" onto my string. The current script does this:
#Getting "Status"
try:
    strValue = strValue + ',' + browser.find_element_by_css_selector('#visKTTabset > div.h-tab-content > div.h-tab-content-inner > div:nth-child(12) > table > tbody > tr.stripes-even > td:nth-child(3) > span').text
except webdriver.NoSuchElementException:
    StrValue = strValue + ',' + "Status not found"

The script works when the "Status" actually exists, but id does not get into the "except" part. The top of my script has this:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException

browser = webdriver.Chrome(executable_path=r'C:\Selenium\chromedriver.exe')
browser.get('https://motorregister.skat.dk/dmr-front/dmr.portal?_nfpb=true&_nfpb=true&_pageLabel=vis_koeretoej_side&_nfls=false')
browser.implicitly_wait(10)  # Will set the global wait to 10 seconds.gnash

I tried the solution here: Try except in python/selenium still throwing NoSuchElementException error but it didnt work.
Comment: Do you define `strValue` before the `try/except` ?
Comment: It returns an exit code so it doesn't qualify for the exception
Comment: @anonjnr I get this error:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"#visKTTabset > div.h-tab-content > div.h-tab-content-inner > div:nth-child(12) > table > tbody > tr.stripes-even > td:nth-child(4) > span"}
Comment: @andreihondrari I do :)
Comment: See answer below. Also you could do something like strValue = 0 and use an if Statement instead of the try block?
Answer: Python names are case sensitive, so perhaps you need:
strValue = strValue + ',' + "Status not found"

Comment: Good point! That fixed some other issues that I had! Thank you
Comment: Just one other note: the Pythonic way of naming variables is dash_case not camelCase. So str_value is more appropriate. :)
Answer: NoSuchElementException is not part of webdriver, it's part of selenium.common.exceptions
try:
    strValue = strValue + ',' + browser.find_element_by_css_selector('#visKTTabset > div.h-tab-content > div.h-tab-content-inner > div:nth-child(12) > table > tbody > tr.stripes-even > td:nth-child(3) > span').text
except NoSuchElementException:  # without webdriver.
    StrValue = strValue + ',' + "Status not found"

And make sure strValue is declared before the try except block.
As a side note, in Python strValue should be str_value
Comment: Thank you so much. I've been stuck with this, for far too long, your solution - along with Brunns answer helped out


Find minimum surface area of half cylinder given volume

Question: I want to build a half-cylinder structure, with the volume $1200$ cubic feet. But I want to find the minimum surface area needed to achieve this volume. I'm struggling.
I know that the equation for the surface area I'll need is
$A=\pi r^2+h\pi r.$
as well as the volume equation
$V=\pi r^2h/2.$
I'd like $r \geq 6.5$ ft.
Comment: Do you know how to find maxima using the first derivative?  By plugging in 1200 for V in the Volume equation, you can get $h$ or $r$ in terms of the other.  Then you can substitute that into the SA formula and have an equation of one variable, for which the maximum can be found via first derivative.
Answer: The standard approach appears to use calculus, but we can also do it neatly using the AM-GM inequality.
Solving for $h$ using the equation for volume, we get
$$h=\frac{2400}{\pi r^2}$$
and hence
$$A=\pi r^2+\frac{2400}{r}$$
Now, by the AM-GM inequality, we have
$$A=\pi r^2+\frac{1200}{r}+\frac{1200}{r}\ge3\sqrt[3]{\pi r^2\times\frac{1200}{r}\times\frac{1200}{r}}=3\sqrt[3]{1200^2\pi}\approx496$$
with equality when
$$\pi r^2=\frac{1200}{r}=\frac{1200}{r}$$
which occurs at
$$r=\sqrt[3]\frac{1200}{\pi}\approx 7.26$$
Hence the minimum surface area of $\approx 496 \text{ ft}^2$ is achieved when $r\approx 7.26\text{ ft}$.
By the way, if you want a calculus solution as well, I can include it since I wrote it up before I realized there was a nice way to go about it.


Commerce product with customer defined attributes

Question: Is it possible to create a product, for which before adding to the cart, customer must define some attributes. For example, I need a number field where the customer defines the size of the product (105x200mm, or 1000x600mm). There are no predefined sizes, I only need an empty text field for width and height where the customer can type their specific size.
After that I want to add it to the cart but without price. I only want to collect customer orders where the products have sizes. Information about final prices will be sent later by email. We don't want to display prices and no payment.
Thanks a lot
Answer: Absolutely.  What you need is the Commerce Customizable Products module.
That allows you to set up Line Item Types that are entirely fieldable!  You can add text fields, select boxes, radio buttons and any field you want to be displayed as the user is adding the product to their cart.
Once the module is enabled, do the following

Add a new Line Item Type at /admin/commerce/config/line-items
Add any fields you need to it (in your case, just a text field)

Make sure to check the box that asks whether this is a field you want added to the 'Add to Cart' form

Finally, go to the 'Manage display' tab of the content type you have that displays your product, and go into the settings of the 'Product' field.  You will see a new option which allows you to choose a 'Line item type' to display.  Select the one you just created, Update, and Save!

Final result:

Let us know if this works for you...
Comment: yes.. perfekt, thanks a lot Boriana. I was looking for this.
Comment: Great tutorial, Boriana! : )


How to use full_html format for custom field?

Question: How can I use a the full_html format for my custom field in my custom node type?  I'd prefer a solution that didn't use any third-party modules.
I've essentially followed this guide, but my custom fields have their HTML tags escaped when rendered.
I've been searching for hours, and can't seem to quite come up with a solution.
I've added 'format' => 'full_html' like in this answer: Specifying text format when creating field on custom node type, but it didn't do anything.
After my changes I used the Devel module to uninstall and reinstall my module.
Edit: added code.
biolawnorganics_content_types.install:
<?php

require_once 'include/nodetypes.inc';

function _biolawnorganics_add_missing_fields() {
  node_types_rebuild();

  $nodeTypes = node_type_get_types();
  $fieldInfoMap = field_info_field_map();

  $fieldsArr = _biolawnorganics_build_all_fields();
  $fieldsInstancesArr = $fieldsArr['instance'];
  $fieldsTypesArr = $fieldsArr['type'];

  foreach ($fieldsTypesArr as $ft) {
    $fieldName = $ft['field_name'];

    if (!isset($fieldInfoMap[$fieldName]))
      field_create_field($ft);
  }

  $contentTypesArr = _biolawnorganics_build_all_content_types($fieldsInstancesArr);
  $contentInfosArr = $contentTypesArr['info'];
  $contentFieldsArr = $contentTypesArr['fields'];

  foreach ($contentFieldsArr as $ck => $cfs) {
    if (!isset($nodeTypes[$ck])) {
      error_log("WARNING: Content type mismatch on $ck.");
      continue;
    }

    $bodyFieldInstance = field_info_instance('node', 'field_body', $ck);

    if (is_null($bodyFieldInstance))
      node_add_body_field($nodeTypes[$ck]);

    foreach ($cfs as $cf) {
      $fieldInstance = field_info_instance('node', $cf['field_name'], $ck);

      if (is_null($fieldInstance))
        field_create_instance($cf);
    }
  }
}

function biolawnorganics_content_types_install() {
  _biolawnorganics_add_missing_fields();

  drupal_set_installed_schema_version('biolawnorganics_content_types', 7001);
}

function biolawnorganics_content_types_update_7001(&$sandbox) {
  biolawnorganics_content_types_install();
}

function biolawnorganics_content_types_uninstall() {
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';

  foreach (array_keys(_BIOLAWNORGANICS_CONTENT_TYPES) as $t) {
    $result = db_query($sql, array(':type' => $t));

    $nodeIds = array();

    foreach ($result as $r)
      array_push($nodeIds, $r->nid);

    node_delete_multiple($nodeIds);
    node_type_delete($t);
  }

  foreach (array_keys(_BIOLAWNORGANICS_FIELDS) as $f) {
    $fieldInstances = field_info_instances('node', $f);

    foreach ($fieldInstances as $fi)
      field_delete_instance($fi);

    field_delete_field($f);
  }
}

// vim: set ts=2 sw=2 et syn=php:

include/nodetypes.inc:
<?php

define(
  '_BIOLAWNORGANICS_FIELDS', array(
    'biolawnorganics_promos'  => array(
      'type' => array(
        'label'  => 'Promotions Sidebar',
        'type'   => 'text_long',
        'format' => 'full_html'
      ),
      'instance'  => array(
        'widget'  => array(
          'type'   => 'text_textarea',
          'format' => 'full_html'
        )
      )
    )
  )
);
define(
  '_BIOLAWNORGANICS_CONTENT_TYPES', array(
    'biolawnorganics_home'  => array(
      'info'    => array(
        'name'        => 'bioLawn Organics Home',
        'description' => 'bioLawn Organics Home Page',
        'has_title'   => FALSE
      ),
      'fields'  => array(
        'biolawnorganics_promos'  => NULL
      )
    ),
    'biolawnorganics_page'  => array(
      'info'    => array(
        'name'        => 'bioLawn Organics Page',
        'description' => 'bioLawn Organics Generic Page',
        'has_title'   => TRUE,
        'title_label' => 'Title'
      ),
      'fields'  => array(
        'biolawnorganics_promos'  => NULL
      )
    )
  )
);

function _biolawnorganics_build_field_type($fieldName, $fieldTypePartial) {
  $fieldType = $fieldTypePartial;

  $t = get_t();

  $fieldType['field_name']  = $fieldName;
  $fieldType['label']       = $t($fieldType['label']);

  return $fieldType;
}

function _biolawnorganics_build_field_instance($fieldType, $fieldInstancePartial) {
  $fieldInstance = $fieldInstancePartial;

  $fieldName = $fieldType['field_name'];

  #$t = get_t();

  $fieldInstance['field_name']  = $fieldName;
  $fieldInstance['label']       = $fieldType['label'];
  $fieldInstance['type']        = $fieldType['type'];
  $fieldInstance['entity_type'] = 'node';

  $fieldInstance['display'] = array(
    'example_node_list' => array(
      'label' => $fieldType['label'],
      'type'  => $fieldType['type']
    )
  );

  return $fieldInstance;
}

function _biolawnorganics_build_content_info($contentName, $contentInfoPartial) {
  $contentInfo    = $contentInfoPartial;

  $t = get_t();

  $contentInfo['base']          = $contentName;
  $contentInfo['name']          = $t($contentInfo['name']);
  $contentInfo['description']   = $t($contentInfo['description']);
  if ($contentInfo['has_title'])
    $contentInfo['title_label'] = $t($contentInfo['title_label']);

  return $contentInfo;
}

function _biolawnorganics_build_content_fields(
    $contentName,
    $contentFieldsPartial,
    $fieldInstancesArr) {
  $contentFields = $contentFieldsPartial;

  foreach (array_keys($contentFields) as $fn) {
    $fieldInstance = $fieldInstancesArr[$fn];

    if (is_null($fieldInstance)) {
      error_log("WARNING: Missing field instance for $fn.");
      continue;
    }

    $fieldInstance = (array)clone (object)$fieldInstance;

    $fieldInstance['bundle'] = $contentName;

    $contentFields[$fn] = $fieldInstance;
  }

  return $contentFields;
}

function _biolawnorganics_build_all_fields() {
  $fieldTypesArr = array();
  $fieldInstancesArr = array();

  foreach (_BIOLAWNORGANICS_FIELDS as $fk => $fv) {
    $ft = _biolawnorganics_build_field_type($fk, $fv['type']);
    $fi = _biolawnorganics_build_field_instance($ft, $fv['instance']);

    $fieldTypesArr[$fk] = $ft;
    $fieldInstancesArr[$fk] = $fi;
  }

  $fieldsArr = array(
    'type' => $fieldTypesArr,
    'instance' => $fieldInstancesArr
  );

  return $fieldsArr;
}

function _biolawnorganics_build_all_content_types($fieldInstancesArr) {
  $contentInfosArr = array();
  $contentFieldsArr = array();

  foreach (_BIOLAWNORGANICS_CONTENT_TYPES as $ck => $cv) {
    $ci = _biolawnorganics_build_content_info($ck, $cv['info']);
    $cf = _biolawnorganics_build_content_fields($ck, $cv['fields'], $fieldInstancesArr);

    $contentInfosArr[$ck] = $ci;
    $contentFieldsArr[$ck] = $cf;
  }

  $contentTypesArr = array(
    'info' => $contentInfosArr,
    'fields' => $contentFieldsArr
  );

  return $contentTypesArr;
}

// vim: set ts=2 sw=2 et syn=php:

Comment: can you add some piece of code?
Comment: @AdrianCidAlmaguer Yes, and I did, but it's very long and would be a pain to trim down very much.
Comment: I can't see the 'format' => 'full_html' in your code
Comment: @AdrianCidAlmaguer Your right, I had removed it when I checked back out master (to remove all my breadcrumbs), but I put it in both the _BIOLAWNORGANICS_FIELDS['biolawnorganics_promos']['type'] and  _BIOLAWNORGANICS_FIELDS['biolawnorganics_promos']['instance'] arrays.  I'll edit my post now.
Answer: If you want to have a text with full_html format you can use the text_format like this:
  $form['comment'] = array(
    '#type' => 'text_format',
    '#base_type' => 'textarea', // #base_type is optional.
    '#title' => t('Comment'),
    '#default_value' => $default,
    '#format' => isset($edit['format']) ? $edit['format'] : NULL,
  );

Comment: @IsabellCowan can you check this: https://www.drupal.org/node/2031543#comment-7605995
Comment: I'm not really sure where $form comes from, I'm pretty sure it's not defined this context.  However, I changed _BIOLAWNORGANICS_FIELDS['biolawnorganics_promos']['type'] to 'text_format' and get (unsurprisingly) `FieldException: Attempt to create a field of unknown type text_format. in field_create_field() (line 110 of /srv/http/drupal/modules/field/field.crud.inc).`
Comment: I'm sorry if I'm "just not getting it", I hadn't even heard of Drupal until last week.
Answer: Thank you for your help @AdrianCidAlmaguer, I was just missing 'settings' => array('text_processing' => 1), all 'format' => 'my_format' does is set the default text_processing mode, and has no apparent effect without 'settings' => array('text_processing' => 1).  I used this diff and it just worked (I knew it had to be something simple.):
diff --git a/include/nodetypes.inc b/include/nodetypes.inc
index 02d18e5..ad6b2a3 100644
--- a/include/nodetypes.inc
+++ b/include/nodetypes.inc
@@ -4,8 +4,12 @@ define(
   '_BIOLAWNORGANICS_FIELDS', array(
     'biolawnorganics_promos'  => array(
       'type' => array(
-        'label' => 'Promotions Sidebar',
-        'type'  => 'text_long'
+        'label'     => 'Promotions Sidebar',
+        'type'      => 'text_long',
+        'format'    => 'full_html',
+        'settings'  => Array(
+          'text_processing' => 1  // Allow text processing
+        )
       ),
       'instance'  => array(
         'widget'  => array(
@@ -170,9 +174,16 @@ function _biolawnorganics_build_field_instance($fieldType, $fieldInstancePartial
   $fieldInstance['field_name']  = $fieldName;
   $fieldInstance['label']       = $fieldType['label'];
   $fieldInstance['type']        = $fieldType['type'];
+
+  if (isset($fieldType['format']))
+    $fieldInstance['format`']   = $fieldType['format'];
+
+  if (isset($fieldType['settings']))
+    $fieldInstance['settings']  = $fieldType['settings'];
+
   $fieldInstance['entity_type'] = 'node';

-  $fieldInstance['display'] = array(
+  $fieldInstance['display']     = array(
     'example_node_list' => array(
       'label' => $fieldType['label'],
       'type'  => $fieldType['type']


Issue using Exposed filters along with contextual filters in views

Question: I have a view page listing my stories/articles. I have a contextual filter based on the field Country which is a taxonomy term reference field. I have defined the path of the page as article-search/% to accommodate the contextual filter value.
I have an exposed filter on the field article-category which is also of type taxonomy term reference. I use better exposed filters to display the exposed filter values as links.
The contextual filter works fine and I configured the url to display taxonomy name instead of term id. This part works fine but when I click on any of the links in the exposed filter the taxonomy term name for the contextual filter value changes to %25 instead of the taxonomy name and the contextual filter fails. It works fine if I use the default dropdown option for the exposed filter instead of better exposed forms.
Any idea if there is an issue with better exposed filters when used along with contextual filters?
Comment: Sounds like it, have you checked the issue queue?
Comment: Have you added any `hook_form_alter` for expose filter?
Comment: It is an issue with BEF module and provided the solution in my answer below. Thanks Darvanen and Sumit.
Answer: Sorry! I should have looked at the issue queue. There is already an issue logged for this. Here is the link to the issue https://www.drupal.org/node/2179169
The issue got resolved when I applied the patch provided by Jim Keller in the issue link
https://www.drupal.org/files/issues/better_exposed_filters-fix_exposed_block_link_path-2179169-1.patch


21st Century Electronic Keyboard Techniques

Question: For a while now there have been electronic musical keyboard controllers (the most recent one is Osmose) that feature pressure sensing and side-to-side sensing in addition to velocity sensing.
There are loads of books that discuss techniques for improving performance on piano. And there are corresponding technique books for organ and harpsichord, which are non-velocity sensing. You could use those technique books with something like the Osmose, but none of them would exercise the pressure sensing feature of the controller.
My question is, what techniques would you need to practise on one of the newer controller keyboards? Would it be a keyboard book? Could you learn by performing woodwind exercises?
The Ondes Martenot was considered a proper musical instrument in the early 20th Century - you could study it in conservatoire. I expect there'd be some crossover between Ondes technique books and Osmose, but what else would you need to study?
Comment: What effects do pressure and side-to-side motion have on the signals produced by the keyboard?
Comment: I think it depends on what you are emulating. I have maps into my DAW for wind/string instrs where velocity is part of the wind pressure/volume [which feels right for a keyboard player] but aftertouch adds to that, so you can vary within a single note. I also have an iPhone app, TouchOSC, so I can 'waggle a finger' to produce variations, mod speed/intensity etc all in a single 2-handed monophonic performance. Frankly, it took me a while to get a handle on how to play it. I did it by tweaking parameters until my dodgy playing got close to what my brain wanted to hear for a given set of actions.
Answer: Perhaps the closest acoustic keyboard equivalent would be the clavichord, which was sensitive to pressure and side-to-side movement to a limited degree. A bibliography of clavichord technique books can be found on Terence Charlston's "Clavichord Technique & Bibliography" page.
A couple of items in the bibliography that stand out to me because of the author's names:

P. Badura-Skoda, Interpreting Bach at the Keyboard (Oxford University Press, 1993)
R. Kirkpatrick, "On Playing the Clavichord", Early Music, Vol. 9, No. 7 (July 1981), pp. 293-305

The bibliography implies also that some piano technique books discussed clavichord, with authors like Turk, Clementi, Dussek, and Hummel.
The webpage includes an interesting quote from C.P.E. Bach:

Every keyboardist should own a good harpsichord and a good clavichord ... a good clavichordist makes an accomplished harpsichordist, but not the reverse. The clavichord is needed for the study of good performance. ... Those who concentrate on the harpsichord grow accustomed to playing in only one colour, and the varied touch which the competent clavichordist brings to the harpsichord remains hidden from them. (From [CPE Bach's Essay on the True Art of Keyboard Playing, Berlin, 1759] translation by. William J Mitchell, Introduction to Part 1, pp. 37-38.)
Comment: Osmose and clavichord do have some things in common. But Osmose starts sending MIDI CC data from the moment you touch a key. Compare that with clavichord which only modifies the note once it has sounded. If CC data was mapped onto volume, you could do infinite sustain with crescendo/descrescendo using Osmose. With clavichord, you're limited by the fact that the vibrating string decays to silence - you can't do infinite sustain.


Is it okay to store a $node object as a $_SESSION variable

Question: My contrib module currently stores a $node object temporarily in the variable table, and stores the nid for that $node in the $_SESSION variable so that the $node can be retrieved from the variable table at a later point.
Would it be okay to store the $node directly in the $_SESSION variable? Or would there perhaps be a performance of security impact?
If it is okay to store a $node object in the $_SESSION variable, do I need to serialize it first?
Comment: What is the szenario? Why can't you store the nid in the session and load the node again when you need it?
Comment: Good question! My module (http://drupal.org/project/csm) sometimes does stuff with $node when it hasn't been saved to the database, so I have to temporarily store the node somewhere else so the module can access various parts of it.
Answer: I think you want the ctools object cache API here, this is what views uses to store edits to a view until they are saved and is what Drupal 8 uses for node preview. In D8 it's called user temp store.
Comment: Cool, so the relevant API is in D8 core? I suspect that including ctools as a dependancy for my module is no the way to go, as my module is pretty tiny and ctools is a lot of code, but will definitely consider using anything that's in core when I do the D8 port.
Comment: Well views requires ctools, so most sites have it already. But yeah the API is in core in D8, node preview is a good example to check
Answer: Your concerns and this answer point toward no, storing objects in session is bad practice for security and performance. If you dont want to create your own table to track these items, you can also use the data field in the user table/object. This data is also serialized.
However, as your question is written, "yes" you "can" store nodes in $_SESSION... php/drupal will allow it. But as mentioned, this is bad practice.
Comment: Thanks! I don't have any concerns per se; I'm just not sure about whether I should have concerns! I think for now I'll keep doing what I've been doing to this point (storing $node in the variable table) and storing the nid in $_SESSION.


Can explicit(bool) act on the length of a character literal argument?

Question: I'm writing a custom string class that favors space efficiency above almost any other considerations. It has a small-string-optimization for strings of 6 characters or less and uses interning for anything larger. There's a somewhat cut-down version included below (Compiler Explorer).
For convenience, I'd like to have a converting constructor from string literals that is implicitly used only when the string literal is short enough that it fits in the sso buffer. For longer strings, I would like the constructor to be explicit to prevent it being used accidentally (because of the performance implications of interning).
In the code below, I expected the initialization Str b = "not so short" to cause a compiler error because the conditional explicit specifier expression is true. However, I do not get an error on any of the three major compilers. Note: the Str a = "short" initialization works correctly.
At least one "compiler" thinks this should work as I expected: the EDG front-end used by Visual Studio's Intellisense feature gives me a red squiggle with the error no suitable constructor exists to convert from "const char[13]" to "Str".
class Str final {
public:
    using value_type = char;
    using pointer = value_type const*;
    using size_type = unsigned long long;

    // maximum length of a sso string
    static auto constexpr ssoMaxLen = sizeof(pointer) - 2;

    // construct from a character literal
    template <size_type N>
    explicit(N > ssoMaxLen + 1) Str(char const (&str)[N]);

    // construct from a zero-terminated string (other than a literal)
    explicit Str(pointer&& rstr);

    size_type size() const noexcept;

private:
    // the only non-static data is in this union
    union {
        size_type integral;
        pointer ptr;
        value_type text[sizeof(pointer)];
    };

    // index of the sso data and size in the text member when using sso
    // this assumes little endian
    static auto constexpr ssoData = 1;
    static auto constexpr ssoSize = 0;

    // masks for the different parts of the instance data
    static auto constexpr ssoSizeMask = sizeof(pointer) - 1;
    static auto constexpr ssoDataMask = ~ssoSizeMask;

    // perform interning of long strings
    static pointer InitLong(pointer str, size_type len);
};

template <Str::size_type N>
Str::Str(char const(&str)[N]) {
    // construct an empty string and return if length is 0
    auto const len = N - 1;
    if (len == 0) {
        ptr = nullptr;
        return;
    }

    // do interning and return if length is long enough
    if (len > ssoMaxLen) {
        ptr = InitLong(str, len);
        return;
    }

    // otherwise intinialize in sso mode
    text[ssoSize] = len;
    text[ssoData + 0] = str[0];
    text[ssoData + 1] = len > 1? str[1] : 0;
    text[ssoData + 2] = len > 2? str[2] : 0;
    if constexpr (ssoMaxLen >= 3) text[ssoData + 3] = len > 3? str[3] : 0;
    if constexpr (ssoMaxLen >= 4) text[ssoData + 4] = len > 4? str[4] : 0;
    if constexpr (ssoMaxLen >= 5) text[ssoData + 5] = len > 5? str[5] : 0;
    if constexpr (ssoMaxLen >= 6) text[ssoData + 6] = 0;
}

int main() {
    Str a = "short";
    Str b = "not so short";
    return a.size() + b.size();
}

Comment: [mcve], please. 90% of this code is not relevant.
Comment: After writing all that, I realize this is way too "clever" (a.k.a. stupid) and that I should probably have the constructor unconditionally explicit. I leave the question up anyway in case anybody finds it interesting.
Comment: I'm currious to know what *actual*, *real life* benefits you gain by using this over a plain, boring, `std::string`? Can you *actually* meassure any difference that makes a real difference? If so, in what situation? If not, why bother?
Comment: If your goal is to disable constructor if the string is too long for SSO, you should "simply" use SFINAE, not conditional explicit. I mean if someone writes `Str b("not so short")` what should happen then? Another question is why on earth should a constructor of a string-like class that accepts a c-string should ever be explicit?
Comment: @JesperJuhl The current test case I'm working with shows a difference of several hundred MBs of memory usage (sizeof(std::string) == sizeof(Str) * 4). Whether that difference is real enough in a world where we have so much memory available for so little money...
Comment: @r3musn0x I don't want to disable the constructor completely, I just want an error if it's used unwittingly. Because of interning, constructing a long string means looking at other strings previously constructed for one to reuse and that's more costly than one would expect of a typical string class constructor (O(n log n) vs. O(n) in my case).
Comment: @T.C. You're right, I should've done better.
Answer: Here's a short repro:
using size_t = decltype(sizeof(0));

struct Str {
    template <size_t N>
    explicit(N > 7) Str(char const (&str)[N]);
};

#ifdef OUT_OF_LINE
template <size_t N>
Str::Str(char const(&str)[N]) { }
#endif

Str a = "short";
Str b = "not so short";

As is, both gcc and clang correctly reject. If you define OUT_OF_LINE, both compilers accept. Filed gcc 91429 and llvm 42980.
Comment: Implementing the constructor inline of the class definition works on VC++ as well, thanks.


Assistance evaluating $\int_0^{2\pi}\frac{1}{2}\left(2 \sin \theta + \cos \theta\right)d\theta$

Question: I need help with evaluating the following integral
$$\int_0^{2\pi}\frac{1}{2}\left(2 \sin \theta + \cos \theta\right)d\theta$$
I have attempted this but I am not sure how to complete the problem.
Comment: Please tell us what you've tried.
Answer: It's an integration interval of length $2\pi$ over a linear combination of $2\pi$-periodic functions with mean $0$, i.e.
$$\int_0^{2\pi} \sin(x) dx = \int_0^{2\pi} \cos(x) dx = 0$$
That gives
$$\int_0^{2\pi} \frac{1}{2} (2\sin \theta + \cos \theta) d\theta= 0$$
without "computation".

More generally
$$\int_0^{2\pi k} \alpha \sin\left(\frac{x}{k}\right)
+ \beta \cos\left(\frac{x}{k}\right) dx = 0 \qquad \forall\ \alpha,\beta,k \in \mathbb R$$
Comment: You mean, the "computation" was hidden in "$2\pi$-periodic functions with mean $0$". (Not really a problem of course, just pointing it out.)
Comment: @Lord_Farin yep, but for $\sin$ and $\cos$ (and more generally $\exp(ik\cdot)$), this is a very common fact. And I think it's more elegant than computing directly, as this even applies to uglier combinations ;-)
Comment: Indeed; nice addition in your edit. +1.
Answer: $$ \int \sin\theta + \frac{\cos\theta}{2} d\theta=\cos\theta-\frac{\sin\theta}{2}$$
So $$ \int_0^{2\pi}\sin\theta + \frac{\cos\theta}{2} d\theta=1-1-0+0=0$$
Comment: Someone edited your question to use `\sin` and `\cos`, which render as $\sin$ and $\cos$ (built-in shorthands looking better than $sin$ and $cos$). For further information about writing maths at this site see e.g. [here](http://meta.math.stackexchange.com/questions/5020/), [here](http://meta.stackexchange.com/a/70559/155238), [here](http://meta.math.stackexchange.com/questions/1773/) and [here](http://math.stackexchange.com/editing-help#latexhelp/notation).


Is ARMA model possible for series with non significant ACF/PACF?

Question: I am playing around with SP500 data from the MASS package. From observation of the ACF and PACF there seem to be no significant autocorrelation. Now I want to model the volatility of the returns but I also want a mean equation. I'm not sure how I will get my mean equation as the ACF and PACF suggest that I can't use MA or AR terms in my mean equation.
Also, applying the auto.arima function from the forecast package yields an ARIMA(3,0,5) model. I am confused with such results as the ACF/PACF do not even show significance.
I am using the Box-Jenkins approach in my project and it wouldn't make sense to say that there are 3 AR and 5 MA terms when the ACF and PACF don't support what I say. I need to be able to explain why I am choosing this rank.
Comment: Did you manage to understand why the auto-arima function chooses the particular lag structure compared to all other possibilities? Perhaps these lags have low but comparatively higher correlation? Perhaps _exactly because_ ACF is low, the auto.arima function generated a many-lags structure in order to "compensate" for the low ACF? (in the same spirit with blindly increasing the number of regresors in a linear regression to increase the R-square, although this may create a useless mean equation with good fit?
Comment: I think I understood where I went wrong thanks to Rob.
Answer: Here are the ACF and PACF plots:
library(MASS)
library(forecast)
tsdisplay(SP500)

So contrary to what the question states, there are significant correlations at many lags. Naturally auto.arima() tries to model the correlation structure as best it can. Because the default maximum number of AR and MA parameters are both set to 5, it cannot handle all the significant correlations seen here, but it does quite a good job as is seen when the residuals are plotted.
fit <- auto.arima(SP500)
tsdisplay(residuals(fit))

You can get a better model by making auto.arima() work harder:
fit <- auto.arima(SP500, approximation=FALSE, stepwise=FALSE, max.order=10)

This returns an ARIMA(5,0,2) with better residual plots than those shown above and which passes a Ljung-Box test:
> Box.test(residuals(fit), lag=20, fitdf=8, type="Ljung")

    Box-Ljung test

data:  residuals(fit)
X-squared = 17.365, df = 12, p-value = 0.1364

The model chosen has the smallest AICc value for all ARIMA($p,0,q$) models with $p\le 5$ and $q\le 5$.
Comment: Oh I used the default acf function in R and the lags didn't seem to be significant. In the book Introductory Time Series with R the author says that usually return data tend to be uncorrelated but the squared return is correlated. If this is true how can we use AR terms or MA terms? thanks your illustration made things clearer.
Comment: When you make a Ljung-Box test what statistic should you look at for conclusion?I tried using this function fit <- auto.arima(SP500, approximation=FALSE, stepwise=FALSE, max.order=10) and my computer took around 2mins to do it, is that normal?


Como plotar vários gráficos em uma folha A4 com margens definidas?

Question: Para ilustrar a questão considerei a situação hipotética abaixo, utilizando as bibliotecas ggplot2 e gridExtra.
 library(ggplot2)
 library(gridExtra)

 df<-data.frame(x=1:10,y=1:10)
 a<-ggplot(data = df, aes(x = x, y=y^2)) + xlab("Posição") + ylab("Função") + ggtitle("Posição x Função")+geom_point()
 b<-ggplot(data = df, aes(x = x, y=y^3)) + xlab("Posição") + ylab("Função") + ggtitle("Posição x Função")+ geom_point()
 c<-ggplot(data = df, aes(x = x, y=y^4)) + xlab("Posição") + ylab("Função") + ggtitle("Posição x Função") + geom_point()
 d<-ggplot(data = df, aes(x = x, y=y^5)) + xlab("Posição") + ylab("Função") + ggtitle("Posição x Função") + geom_point()
 e<-ggplot(data = df, aes(x = x, y=y^6)) + xlab("Posição") + ylab("Função") + ggtitle("Posição x Função") + geom_point()
 f<-ggplot(data = df, aes(x = x, y=y^7)) + xlab("Posição") + ylab("Função") + ggtitle("Posição x Função") + geom_point()
 grid.arrange(a,b,c,d,e,f)

Como posso plotar os gráficos gerados por esta rotina em uma folha A4 levando em conta que:

A orientação da folha seja Retrato e, as suas mas margens esquerda, superior, direita e inferior tenham respectivamente 3,3,2 e 2 centímetros;
Os gráficos estejam dispostos lado a lado em duas colunas com 0,5cm de distância entre elas, um grid de 3x2;
O tamanho das fontes do título seja 12 e das legendas 10.
Comment: Jean, dois detalhes: 1. Tem um parêntesis sobrando/faltando na sua primeira linha. 2. Sempre coloque o código de carregar os pacotes quando fizer uma pergunta ou der uma resposta, pelo código não é possível saber quais pacotes são necessários.
Comment: Você se importa apenas com a margem, ou também com o espaço que os gráficos vão ocupar? E o alinhamento na página?
Comment: @Jean, desculpe a pergunta, mas qual o objetivo disso? Talvez usar o `sweave` seja uma abordagem mais adequada, dependendo do seu objetivo.
Comment: @Molx - Obrigados pelas correções. Não havia pensado em detalhes além das margens... mas vou melhorar a pergunta.
Comment: @Bernado, tentei criar um problema parecido ao que me deparei, criei vários gráficos e preciso imprimi-los de uma forma organizada. Vou verificar o `sweave`. Obrigado!
Answer: Isso foi um pouco mais difícil do que o planejado, porque não consegui fazer o pdf funcionar com o par(mai), para definir as margens. Para funcionar, fiz uma estratégia bem não-elegante, mas parece ter funcionado.
O que fiz foi zerar todas as margens dos gráficos e criar o pdf com área de plotagem de tamanho igual à uma folha A4. Então preenchi os espaços de margens/entre gráficos com grobs vazios.
library(ggplot2)
library(gridExtra)
library(grid)

df<-data.frame(x=1:10,y=1:10)
a<-ggplot(data = df, aes(x = x, y=y^2)) + xlab("Posição") + ylab("Função") +
  ggtitle("Posição x Função") + geom_point() + theme(plot.margin=unit(rep(0, 4), "in"))
b<-ggplot(data = df, aes(x = x, y=y^3)) + xlab("Posição") + ylab("Função") +
  ggtitle("Posição x Função") + geom_point() + theme(plot.margin=unit(rep(0, 4), "in"))
c<-ggplot(data = df, aes(x = x, y=y^4)) + xlab("Posição") + ylab("Função") +
  ggtitle("Posição x Função") + geom_point() + theme(plot.margin=unit(rep(0, 4), "in"))
d<-ggplot(data = df, aes(x = x, y=y^5)) + xlab("Posição") + ylab("Função") +
  ggtitle("Posição x Função") + geom_point() + theme(plot.margin=unit(rep(0, 4), "in"))
e<-ggplot(data = df, aes(x = x, y=y^6)) + xlab("Posição") + ylab("Função") +
  ggtitle("Posição x Função") + geom_point() + theme(plot.margin=unit(rep(0, 4), "in"))
f<-ggplot(data = df, aes(x = x, y=y^7)) + xlab("Posição") + ylab("Função") +
  ggtitle("Posição x Função") + geom_point() + theme(plot.margin=unit(rep(0, 4), "in"))

pdf("gg.pdf", width=21/2.54, height=29.7/2.54) #Tamanho da A4, de cm para in
blank <- rectGrob(gp=gpar(col="white"))
grid.arrange(blank, blank, blank, blank, blank,
             blank, a, blank, b, blank,
             blank, blank, blank, blank, blank,
             blank, c, blank, d, blank,
             blank, blank, blank, blank, blank,
             blank, e, blank, f, blank,
             ncol = 5,
             widths = c(3, 7.75, 0.5, 7.75, 2), #Calculado a partir da largura da A4 e das margens
             heights = c(3, 7.9, 0.5, 7.9, 0.5, 7.9,2)) #Calculado a partir da altura da A4 e das margens
dev.off()

A resposta ainda é parcial, porque não tentei resolver a parte da fonte. Não sei se é possível usar essa definição de tamanho 12 ou 10, talvez seja melhor fazer os testes no ggplot e então definir manualmente.
Comment: qual a largura de blank?
Comment: @Jean A largura é definida em `widths`. São as larguras das margens e do espaçamento entre as figuras.
Comment: tudo funcionou perfeitamente! Caso você tenha mais alguma dica sobre o assunto ficarei agradecido.


Prove that this kernel is a valid kernel

Question: How would you argument or prove that this is a valid kernel:
$$ K_a(x, t) = \prod_{i=1}^{n} (1 + x_it_i + (1-x_i)(1-t_i)). $$
I know that there are two conditions that a kernel must satisfy to be a valid kernel: symmetry and positive-semidefiniteness. Clearly the first condition is satisfied. But I am not sure how to prove the second.
I have re-arranged the expression as:
$$ K_a(x, t) = \prod_{i=1}^{m}2\left(x_i - \frac{1}{2}\right)\left(t_i - \frac{1}{2}\right) + \frac{3}{2},$$
but I am unsure if this is of any help. Thanks.
Answer: Let's build this kernel up piecewise, using a bunch of properties that allow you to do that. The two forms are about the same for doing that, but let's use the second one.

Scaling: If $k$ is a psd kernel, then so is $\gamma k$ for $\gamma \ge 0$.

Sum: If $k_1$ and $k_2$ are psd kernels, then $k_1 + k_2$ is psd.

Product: If $k_1$ and $k_2$ are psd kernels, then so is $f(x, y) = k_1(x, y) k_2(x, y)$.

(These are proved e.g. in this answer.)

Shift: If $k(x, y)$ is a valid kernel, so is $k_\delta(x, y) = k(x + \delta, y + \delta)$ for any constant $\delta$.
Proof: if $\varphi(x)$ is the feature map for $k$, then $x \mapsto \varphi(x + \delta)$ is the feature map for $k_\delta$.

Projection: if $k(x, y)$ is a valid kernel on $\mathcal X$, then $k'(\vec x, \vec y) = k(x_\ell, y_\ell)$ is a valid kernel on $\mathcal X^d$ for any dimension $\ell \in \{1, \dots, d\}$.
Proof: For any points $\{\vec x_j \}_{j=1}^n$ and corresponding constants $a_i$,
$$\sum_{i,j} a_i k'(\vec x_i, \vec x_j) a_j = \sum_{i,j} a_i k(x_{i,\ell}, y_{j,\ell}) \ge 0$$
since $k$ is a psd kernel.

Constants: $k(x, y) = \gamma$ is psd for any $\gamma \ge 0$, on any input set.
Proof: $\sum_{i,j} a_i k(x, y) a_j = \gamma \sum_{i,j} a_i a_j = \gamma \lVert a \rVert^2 \ge 0.$

Now:

The linear kernel on $\mathbb R$ is $(x, t) \mapsto x t$ is psd.
By shift, so is $(x, t) \mapsto (x - \frac12) (t - \frac12)$.
By projection, so is $(\vec x, \vec t) \mapsto (x_i - \frac12) (t_i - \frac12)$ for each $i$.
By scaling, so is $(\vec x, \vec t) \mapsto 2 (x_i - \frac12) (t_i - \frac12)$.
By repeated application of product, so is $(\vec x, \vec t) \mapsto \prod_{i=1}^m 2 (x_i - \frac12) (t_i - \frac12)$.
By constants and sum, so is $(\vec x, \vec t) \mapsto \prod_{i=1}^m 2 (x_i - \frac12) (t_i - \frac12) + \frac32$.


Sair do laço assim que a string nome for igual a 0

Question: <code>#include <iostream>
#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

using namespace std;

int main()
{
    setlocale(LC_ALL, "portuguese");

   int idade[20];
   string nome[20];
   char sexo[20],expe[20];

    for (int i=0; i <3; i++){

        do{
            cout << "digite o seu " << i+1 <<"º nome, idade, sexo e se tem experiência no serviço: ";
            cin >> nome[i];
            cin >> idade[i];
            cin >> sexo[i];
            cin >> expe[i];

        }while (strcmp(nome, ab)); /* está linha é que está com problema*/

    }

    return 0;
}
</code>
Comment: "está linha é que está com problema" -> qual problema? Isto é, que erro ocorre? P.S.: não seria a variável `ab`, que não está definida em lugar algum?
Comment: Comece estudar essas coisas. Sair atirando para todo lado, sem um objetivo, sem um caminho traçado, não vai te levar a lugar algum. Você vai se iludir achando que está aprendendo alguma coisa e estará só seguindo fórmulas que não servirão pra nada na prática. O que você está querendo fazer não faz sentido, o problema está aí. Mas se insiste eu vou arrumar a sintaxe.
Comment: Tem alguns problemas, o primeiro é que isto não parece ter objetivo algum. Porque precisa fazer isto? Explique o objetivo, a lógica toda deve estar errada. E já lhe falei para não misturar C com C++.
Comment: é que eu não sei direto o que é C e o que é C++. A lógica é sair do laço assim que que a variável "nome" receba o valor 0.
Answer: <code>#include <iostream>
#include <locale>
#include <string>
using namespace std;

int main() {
    setlocale(LC_ALL, "portuguese");
    int idade[20];
    string nome[20];
    char sexo[20], expe[20];
    for (int i = 0; i < 3; i++) {
        do {
            cout << endl << "digite o seu " << i + 1 << "º nome, idade, sexo e se tem experiência no serviço: ";
            cin >> nome[i];
            cin >> idade[i];
            cin >> sexo[i];
            cin >> expe[i];
        } while (nome[i] == "0");
    }
}
</code>
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Algumas coisas podem ser melhoradas. Idealmente seria melhor usar os recursos do C++ e evitar os do C.
Comment: Posso estar enganado, mas eu acho que ele só quer popular de informações nesse array. Seria um único FOR usando o tamanho do array. Esse "0" que ele citou deve ser do índice do array, que para ele 0 é o último.


Cliente.java:7: error: invalid method declaration; return type required

Question: Nome do erro completo:

Cliente.java:7: error: invalid method declaration; return type required
  public cliente() {
         ^

Código que usei:
import java.net.Socket;

public class Cliente extends javax.swing.JFrame {
     private static Socket cliente;

public teste() {
    initComponents();

}

public static void main(String[] args){

}
private static void iniciaCliente(){
    try{
        cliente = new Socket("127.0.0.1 ",4444);
        System.out.println("Conexão feita com sucesso");
    } catch (IOException ex){

        System.out.println("ErroConnect:");

        }

    }

}

Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer: O erro em si é exatamente esse que está descrito pelo compilador, fala o tipo de retorno do método. Se não tiver retorno algum então o tipo é void, assim:
public cliente() {

Coloquei no GitHub para referência futura.
Mas todo método que retorna void tende a ser equivocado, então pense bem se deveria ter esse método assim.
Se você retorna alguma coisa então o tipo deve ser exatamente do objeto que está retornando. Java é uma linguagem de tipagem estática, nominal e praticamente toda explícita, então tem que dizer o tipo de tudo.
Porém tem um método que não tem tipo porque ele deve ser sempre o tipo da classe que está declarando. Este é o método construtor. Se for o caso, e parece ser, então seu erro é apenas de digitação, e escreveu um método cliente() (c minúsculo) quando deveria ser Cliente() (C maiúsculo), aí se o método não tem o mesmo nome da classe o compilador acha que não é o construtor e indica um erro equivocado, o seu erro causou uma interpretação errada no compilador.
Comment: Imagino que dará bastante erro, você tem que entender o que está fazendo, se jogar coisas aleatórias pode acontecer de tudo, eu tenho quase certeza que é erro de digitação novamente. Você não pode ficar editando a pergunta para colocar novas questões. Dê uma lida no [tour] e na [help] como o site funciona.
Comment: agora fica dando o erro "Cliente.java:8: error: cannot find symbol"" "InitComponentes" vou colocar na edição da pergunta


Change page title

Question: I've created a view to display products based on the taxonomy vocabulary Categories.
I followed a few how tos and check for answers on drupal.org, here & other websites but none is working.
I would like the title of the view to be the name of taxonomy term displayed.
The Path is : taxonomy/term/%
Contextual filter:
-- When the filter value is NOT in the URL > Provide default value > Taxonomy Term ID from URL
-- When the filter value IS in the URL or a default is provided > Specify validation criteria > Taxonomy Term ID
--   -- Vocabulary > Categories
To overwrite the title, I have 2 Replacement patterns available :
{{ arguments.field_categories_target_id }} == Product: Catégories (field_categories) title
{{ raw_arguments.field_categories_target_id }} == Product: Catégories (field_categories) input

The both display the Taxonomy term ID, not the name.
I've tried with other replacement patterns, nothing is displayed.
I'm running Drupal 8.9.13.
Thanks for your help!

This is the .yml file.
uuid: cb266220-13c8-434d-8371-cabb6d7af36f
langcode: fr
status: true
dependencies:
  config:
    - commerce_product.commerce_product_type.dropixx
    - core.entity_view_mode.commerce_product.vignette
    - field.storage.commerce_product.field_categories
    - taxonomy.vocabulary.categories
    - taxonomy.vocabulary.marques_cat
  module:
    - commerce
    - commerce_product
    - ds
    - taxonomy
id: taxonomy
label: Taxonomy
module: views
description: ''
tag: ''
base_table: commerce_product_field_data
base_field: product_id
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: none
        options: {  }
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: full
        options:
          items_per_page: 12
          offset: 0
          id: 0
          total_pages: null
          tags:
            previous: ‹‹
            next: ››
            first: ««
            last: »»
          expose:
            items_per_page: false
            items_per_page_label: 'Items per page'
            items_per_page_options: '5, 10, 25, 50'
            items_per_page_options_all: false
            items_per_page_options_all_label: '- All -'
            offset: false
            offset_label: Offset
          quantity: 5
      style:
        type: default
        options:
          row_class: 'col-xs-12 col-sm-6 col-md-6 col-lg-4 col-xl-3 vg-box'
          default_row_class: true
          uses_fields: false
      row:
        type: 'ds_entity:commerce_product'
        options:
          relationship: none
          view_mode: vignette
          alternating_fieldset:
            alternating: false
            allpages: false
            item_0: default
            item_1: default
            item_2: default
            item_3: default
            item_4: default
            item_5: default
            item_6: default
            item_7: default
            item_8: default
            item_9: default
          grouping_fieldset:
            group: false
          advanced_fieldset:
            advanced: false
      fields:
        title:
          table: commerce_product_field_data
          field: title
          id: title
          entity_type: null
          entity_field: title
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings: {  }
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
        field_categories:
          id: field_categories
          table: commerce_product__field_categories
          field: field_categories
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: true
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: target_id
          type: entity_reference_label
          settings:
            link: true
          group_column: target_id
          group_columns: {  }
          group_rows: true
          delta_limit: 1
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          plugin_id: field
        nothing:
          id: nothing
          table: views
          field: nothing
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: true
            text: "
title {{ title }}\r\n
categories {{ field_categories }}\r\n
target id {{ arguments.field_categories_target_id }} "
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: false
          plugin_id: custom
      filters:
        status:
          value: '1'
          table: commerce_product_field_data
          field: status
          plugin_id: boolean
          entity_type: commerce_product
          entity_field: status
          id: status
          expose:
            operator: ''
            operator_limit_selection: false
            operator_list: {  }
          group: 1
        type:
          id: type
          table: commerce_product_field_data
          field: type
          value:
            dropixx: dropixx
          entity_type: commerce_product
          entity_field: type
          plugin_id: commerce_entity_bundle
          expose:
            operator_limit_selection: false
            operator_list: {  }
        field_stock_qty_value:
          id: field_stock_qty_value
          table: commerce_product__field_stock_qty
          field: field_stock_qty_value
          relationship: none
          group_type: group
          admin_label: ''
          operator: '!='
          value:
            min: ''
            max: ''
            value: '0'
          group: 1
          exposed: false
          expose:
            operator_id: ''
            label: ''
            description: ''
            use_operator: false
            operator: ''
            operator_limit_selection: false
            operator_list: {  }
            identifier: ''
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
            placeholder: ''
            min_placeholder: ''
            max_placeholder: ''
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          plugin_id: numeric
        field_marque_target_id:
          id: field_marque_target_id
          table: commerce_product__field_marque
          field: field_marque_target_id
          relationship: none
          group_type: group
          admin_label: ''
          operator: or
          value: {  }
          group: 1
          exposed: true
          expose:
            operator_id: field_marque_target_id_op
            label: 'Marques :'
            description: ''
            use_operator: false
            operator: field_marque_target_id_op
            operator_limit_selection: false
            operator_list: {  }
            identifier: field_marque_target_id
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
              anonymous: '0'
              administrator: '0'
            reduce: false
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          reduce_duplicates: false
          type: select
          limit: true
          vid: marques_cat
          hierarchy: false
          error_message: true
          plugin_id: taxonomy_index_tid
      sorts: {  }
      title: '<none>'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments:
        field_categories_target_id:
          id: field_categories_target_id
          table: commerce_product__field_categories
          field: field_categories_target_id
          relationship: none
          group_type: group
          admin_label: ''
          default_action: default
          exception:
            value: all
            title_enable: false
            title: '{{ arguments.field_marque_target_id }}'
          title_enable: true
          title: '{{ arguments.field_categories_target_title }}'
          default_argument_type: taxonomy_tid
          default_argument_options:
            term_page: '1'
            anyall: ','
            node: false
            limit: false
            vids: {  }
          default_argument_skip_url: false
          summary_options:
            base_path: ''
            count: true
            items_per_page: 25
            override: false
          summary:
            sort_order: asc
            number_of_records: 0
            format: default_summary
          specify_validation: true
          validate:
            type: 'entity:taxonomy_term'
            fail: 'not found'
          validate_options:
            bundles:
              categories: categories
            access: true
            operation: view
            multiple: 0
          break_phrase: false
          not: false
          plugin_id: numeric
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - user
      tags:
        - 'config:field.storage.commerce_product.field_categories'
  taxonomy_category_contextual:
    display_plugin: page
    id: taxonomy_category_contextual
    display_title: Page
    position: 1
    display_options:
      display_extenders:
        metatag_display_extender: {  }
      path: taxonomy/term/%
      enabled: true
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - user
      tags:
        - 'config:field.storage.commerce_product.field_categories'

Comment: See [my D7 answer here](https://drupal.stackexchange.com/a/220249/27710). Same procedure except in D8/D9 you use `{{ name }}`.
Comment: ThX, but it partially works. Taxonomy Term : name is not available. I'm displaying product fileds. With {{ field_categories }} in the title field, It displays all categories. If I select in Multiple field settings Display 1. It display the first Category title in all categories of the tree.
Comment: In that case, you'll have to solve it programmatically. I show in [this answer](https://drupal.stackexchange.com/a/298040/27710) how to programmatically alter the view title.
Answer: Hey there is there any particular reason you are using that filter?
I believe that if you use the "Has Taxonomy Term ID" contextual filter , it will work as you intend it to.
Let me know if i did not understand your question correctly.
Best Regards.
Comment: You understaood right. I am using the Overwrite Title field.
It doesn't work. Nothing is displayed when I add {{ arguments.tid }}. Thanks for your suggestion.
Comment: That pattern is not one that Views gave you?
Comment: @mChamps I am suggesting also that you should use a different contextual filter, not just the different token. Have you tried that?
Comment: I've created the view from scratch. I am building a shop with Drupal Commerce and I want to be able to navigate with a category hierarchy, so I use Taxonomy. When I click on overwrite title, view gives me 2 replacement patterns. They display the taxonomy ID instead of the Taxonomy Name. How can I use a different contextual filter? It is the only available filter related to Taxonomy.
Comment: You delete the one you have and use the one I suggester. I am sorry if I don't understand what the issue is. Would you mind sharing the whole yml file so that I can get some better insight on your problem and maybe help more actively?

Change page title


Entity Reference - Not required to be in database

Question: I have a content type Proposal with a entity reference field Proposed by. This is an autocomplete field that targets Users in the application. You can give in multiple users that are in the application.
But now I would like to give the possibility to the user that they can give in user that are NOT in the application. So they can enter email addresses from random persons, they will receive an email with a link to register. But how can I get this data? Because it's not saved when the user isn't in the application.
I tried to do this with hook_node_validate but this is the result I get:
array (size=1)
'und' =>
  array (size=4)
    0 =>
      array (size=2)
        'target_id' => string '26' (length=2)
        '_weight' => string '0' (length=1)
    1 =>
      array (size=2)
        'target_id' => null
        '_weight' => string '1' (length=1)
    2 =>
      array (size=2)
        'target_id' => string '' (length=0)
        '_weight' => string '2' (length=1)
    'add_more' => string 'Add another item' (length=16)

So no email address that I gave in.. Just a target_id = null. How could I do this?
Answer: Entity Reference can reference entities only. It would be a really big hack to the module to allow non-entities to be referenced. But there is no need to.
There are dedicated modules for exactly what you are trying to do. Instead of Entity Reference, create User Relationships. Use User Relationship Invites submodule, it

allows users to specify a relationship to a user that they invite to join the site.

Invitation is done by using e-mail, so it seems this will fully satisfy your use case.


Why would Apache log different response sizes for the same url?

Question: I noticed a couple (ostensibly-)harmless log entries, and--I'm admittedly overthinking this by a mile--got curious about Apache2 response sizes.
This Ukranian crawler † hit my web daemon, two seconds later requesting a duplicate.  Apache2 replied with 41,298 bytes and then 41,244.
My question is:
Why are the response sizes different--by only 54 bytes--for the same URL?
I have not customized Apache's default cache declarations.  If something were cached, I'd expect a difference near 100% of the requested content (or at least more than 0.01%).
All I can think of is a small file--a tiny GIF or .css file?--that inexplicably is the only component that's cached, but a search for files that size produced no results:
find . -type f -size -55c -size +53c
...searching 53 or 55 finds small .GIF files, and widening by several bytes yields a lot more.  Expanding this assumption guess, the "missing" response data may be a file and its respective path--but that seems counter to how I thought caching works.
What am I seeing here?

ANCILLARY
They're the only two entries:
# grep -r 220.127.116.11 /var/log
/var/log/apache2/example.com-access.log:126.96.36.199 - - [26/Apr/2020:19:56:20 -0600] "GET / HTTP/1.0" 200 41298 "http://www.example.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.64 (Edition Yx)"
/var/log/apache2/example.com-access.log:18.104.22.168 - - [26/Apr/2020:19:56:22 -0600] "GET / HTTP/1.0" 200 41244 "http://www.example.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.64 (Edition Yx)"

† Around nine hours earlier it hit one of my other servers, and shortly afterward yet another.  While not actively seeking vulns, it's clearly crawling the web, so I've blocked it out of principle--no immediate or planned need to be indexed outside the US.
Answer: Try wireshark or tcpdump to capture the network traffic. Should be easy enough to look at both responses and find the difference.
It's probably response headers changing slightly. Some headers vary with clients and time.
Comment: Wireshark is a good idea.  Except I won't know if/when it'll happen again.
Comment: I forget that I can't hit [enter] in a comment.  This guy hit the server two seconds apart and (I just confirmed what eyeballs were pretty sure) the same user agent.  That said, I think your headers idea is likely what's happened here.


Bloquear redirect de extensões e pastas com .htaccess

Question: Estou de todas as formas tentando criar um redirect com htaccess e consegui da seguinte forma:
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
Options +FollowSymLinks
RewriteCond %{REQUEST_URI} !^/(?:index\.php|robots\.txt)$
RewriteRule (.*) http://meusite.com/novapasta/$1 [R=301,L]
</ifModule>

O problema que na hora que digito na URL qualquer outro arquivo que não seja index.php ou robots.txt ele joga para essa pasta.
Ex: sitemap.xml ele está direcionando meusite.com/novapasta/sitemap.xml e não quero isso.
Tentei colocar:
RewriteCond %{REQUEST_URI} !^/(?:index\.php|robots\.txt|sitemap\.xml)$

Mas ele não aceita e direciona da raiz para pasta /novapasta/sitemap.xml
Até pastas ele está direcionando.
Ex: meusite.com/imagens para meusite.com/novapasta/imagens/
Como posso barrar isso?
O que eu preciso:
Então sempre testo em modo privado e ele ainda direciona. Na verdade tenho um site que ele tinha uma querystring que faz os links ficarem

http://meusite.com/produto.php?produto=$1
http://meusite.com/produto

Agora quero jogar tudo para essa nova pasta

http://meusite.com/novapasta/produto

Só que com esse redirect se eu tento acessar:
http://meusite.com/sitemap.xml, http://meusite.com/imagens/ e http://meusite.com/diretorioqualquer
ele joga para:
http://meusite.com/novapasta/sitemap.xml, http://meusite.com/novapasta/imagens/ e
http://meusite.com/novapasta/diretorioqualquer
Os únicos que ele não joga são o index e o robots e gostaria de jogar apenas o que vem do produto.php?produto=$1

Então sempre testo em modo privado e ele ainda direciona.
Na verdade tenho um site que ele tinha uma querystring que faz os links ficarem
http://meusite.com/produto.php?produto=$1
http://meusite.com/produto
Agora quero jogar tudo para essa nova pasta
http://meusite.com/novapasta/produto
Só que com esse redirect se eu tento acessar
http://meusite.com/sitemap.xml
http://meusite.com/imagens/
http://meusite.com/diretorioqualquer
ele joga para
http://meusite.com/novapasta/sitemap.xml
http://meusite.com/novapasta/imagens/
http://meusite.com/novapasta/diretorioqualquer
Os únicos que ele não joga são o index e o robots e gostaria de jogar apenas o que vem do produto.php?produto=$1
Comment: Respondi brevemente, mas pelo que entendi parece que você está usando um `.htaccess` sem saber exatamente o que quer, quero dizer você quer uma coisa, mas o teu htaccess está fazendo uma coisa totalmente diferente do que você precisa. Diga-me você quer realmente bloquear todas urls e liberar apenas algumas? Por que se for isto, o teu htaccess está ok, mas se não então o teu htaccess não tem sentido para o teu projeto.
Comment: Na verdade não tenho muito conhecimento no .htaccess por isso estou quebrando a cabeça com vários testes
Comment: Diga-me você quer realmente bloquear todas urls e liberar apenas algumas?
Comment: Depende o servidor tem permissão configurar **htaccess**, e nada fácil configurar, se for locaweb é reclamar suporte, recomendo de usar **cPanel** é util de usar e vai ajudar, e o servidor IIS pode muito trampo. Pesquise sobre "URL amigável" pode ajudar.
Answer: Rafael quando o navegador recebe um 301 isto fica no cache, portanto isto funciona:
RewriteCond %{REQUEST_URI} !^/(?:index\.php|robots\.txt|sitemap\.xml)$

O problema é que para o navegador a página antiga não existe mais por que você usou a flag R=301.
Para resolver isto, limpe o cache e abra novamente o navegador ou abra o navegador em modo Privado.
Note que o seu rewritecond bloqueia qualquer url, exceto: index.php e robots.txt e sitemap.xml.
Você perguntou:

Como posso barrar isso?

Eu não entendi bem o que você quer, se você não quer que nenhuma url seja bloqueada, então você vai ter que entender o que está a fazer, pois o seu código manda fazer isto exatamente. A solução pratica seria não usar o .htaccess.


Get the complete month name in English

Question: I use DateTime.Now.ToString("MMMM") in order to get the current month's full name. It works well, but I get it in Hebrew.
Is there an option to control the output language?
I need it to be English.
Answer: You can pass a CultureInfo object as an argument DateTime.ToString():
CultureInfo ci = new CultureInfo("en-US");
var month = DateTime.Now.ToString("MMMM", ci);

// alternatively you can use CultureInfo.InvariantCulture:
var month = DateTime.Now.ToString("MMMM", CultureInfo.InvariantCulture);

Answer: Pass in the culture in which you want the name formatted. Like this:
DateTime.Now.ToString("MMMM", new CultureInfo("en-GB"));

Answer: An alternative option to the ones given by other posters:
int month = DateTime.Now.Month;

// Or use CultureInfo.InvariantCulture if you want
CultureInfo usEnglish = new CultureInfo("en-US");
DateTimeFormatInfo englishInfo = usEnglish.DateTimeFormat;
string monthName = englishInfo.MonthNames[month - 1];

I'm not saying it's better or worse than anything else - just an alternative.
Comment: This is most useful when you have the month number but not an actual DateTime object to begin with. Thanks!
Answer: you can use CultureInfo.CreateSpecificCulture(CultureName) to get month name in different languages.
Refer this
Creates a CultureInfo that represents the specific culture that is associated with the specified name.
string MonthName =  DateTime.Now.ToString("MMMM", CultureInfo.CreateSpecificCulture(CultureName));

For a list of predefined culture names, see the National Language Support (NLS) API Reference at the Go Global Developer Center
//    CULTURE                                              SPECIFIC CULTURE
//                 Invariant Language (Invariant Country)
//    af           Afrikaans                               af-ZA
//    am           Amharic                                 am-ET
//    ar           Arabic                                  ar-SA
//    arn          Mapudungun                              arn-CL
//    as           Assamese                                as-IN
//    az           Azerbaijani                             az-Latn-AZ
//    az-Cyrl      Azerbaijani (Cyrillic)                  az-Cyrl-AZ
//    az-Latn      Azerbaijani (Latin)                     az-Latn-AZ
//    ba           Bashkir                                 ba-RU
//    be           Belarusian                              be-BY
//    bg           Bulgarian                               bg-BG
//    bn           Bengali                                 bn-IN
//    bo           Tibetan                                 bo-CN
//    br           Breton                                  br-FR
//    bs           Bosnian                                 bs-Latn-BA
//    bs-Cyrl      Bosnian (Cyrillic)                      bs-Cyrl-BA
//    bs-Latn      Bosnian (Latin)                         bs-Latn-BA
//    ca           Catalan                                 ca-ES
//    co           Corsican                                co-FR
//    cs           Czech                                   cs-CZ
//    cy           Welsh                                   cy-GB
//    da           Danish                                  da-DK
//    de           German                                  de-DE
//    dsb          Lower Sorbian                           dsb-DE
//    dv           Divehi                                  dv-MV
//    ...
//    ta           Tamil                                   ta-IN
//    te           Telugu                                  te-IN
//    tg           Tajik                                   tg-Cyrl-TJ
//    tg-Cyrl      Tajik (Cyrillic)                        tg-Cyrl-TJ
//    th           Thai                                    th-TH
//    tk           Turkmen                                 tk-TM
//    tn           Setswana                                tn-ZA
//    tr           Turkish                                 tr-TR
//    tt           Tatar                                   tt-RU
//    tzm          Tamazight                               tzm-Latn-DZ
//    tzm-Latn     Tamazight (Latin)                       tzm-Latn-DZ
//    ug           Uyghur                                  ug-CN
//    uk           Ukrainian                               uk-UA
//    ur           Urdu                                    ur-PK
//    uz           Uzbek                                   uz-Latn-UZ
//    uz-Cyrl      Uzbek (Cyrillic)                        uz-Cyrl-UZ
//    uz-Latn      Uzbek (Latin)                           uz-Latn-UZ
//    vi           Vietnamese                              vi-VN
//    wo           Wolof                                   wo-SN
//    xh           isiXhosa                                xh-ZA
//    yo           Yoruba                                  yo-NG
//    zh           Chinese                                 zh-CN
//    zh-CHS       Chinese (Simplified) Legacy             zh-CN
//    zh-CHT       Chinese (Traditional) Legacy            zh-HK
//    zh-Hans      Chinese (Simplified)                    zh-CN
//    zh-Hant      Chinese (Traditional)                   zh-HK
//    zu           isiZulu                                 zu-ZA

Answer: Use the overload that takes a IFormatProvider:
  CultureInfo culture = new CultureInfo("en-GB");
  DateTime.Now.ToString("MMMM", culture));

Source
Answer: You can either set the culture of the thread:
  DateTime dt = DateTime.Now;
  // Sets the CurrentCulture property to U.S. English.
  Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
  // Displays dt, formatted using the ShortDatePattern
  // and the CurrentThread.CurrentCulture.
  Console.WriteLine(dt.ToString("MMMM"));

Or you can pass a CultureInfo to the DateTime.ToString() function.
  // Creates a CultureInfo for U.S. English.
  CultureInfo ci = new CultureInfo("en-US");
  // Displays dt, formatted using the ShortDatePattern
  // and the CultureInfo.
  Console.WriteLine(dt.ToString("MMMM", ci));

Note that you could also choose CultureInfo.InvariantCulture.

Get the complete month name in English


Is there a way to create .doc files in PHP like one would use TCPDF to create pdf?

Question: I've already got the functionality to print pdf reports and bills in my application, but now I need to also be able to export in .doc format. I'm using TCPDF's writeHTML function to write and format the pdf files, and I was wondering if there's a way to do the same for .doc files.
Comment: PHPWord - http://phpword.codeplex.com/ - can create .docx files (the default format for MS Word 2007 and 2010)
Comment: If you're planning on making invoices and bills in DOC format, I'll advice against it. DOC is easily changeable, someone will easily be able to fabricate a report of yours.
Comment: Easiest way is to simply produce an RTF file and serve it up as a .doc.
Comment: Well I won't question my manager's decision but we're only gonna use the .doc functions internally. I personally think bills and invoices in doc are a bad idea as well, but hey, it's the manager's job to manage and mine to make stuff happen when people click on things.
Answer: This is pretty straight forward. A .doc file can just contain HTML. If you pass along the Word header, you can just start printing HTML. So, for example:
<?php
header("Content-Type: application/vnd.ms-word");
print "

field1	field2
";
print "
value1 	value2 in blue cell bakground

";
?>

Source: here (verified it to be working).
Comment: Thanks, I was aware you could just print doc files in php but i wasn't sure you can just stick html in it. will try to see how it works
Comment: Not strictly true.... a "real" .doc file cannot contain html. However, MS word is pretty forgiving, detects that you're lying to it, and loads the html anyway.
Comment: I have just one question to ask tho, when I enter the exact thing you posted it prompts me to save or open a php file, can I have it create a .doc file instead (the php file contains the code, if that helps) Nevermind, i found the answer in the forum thread you linked. many thanks.
Comment: @Bogdan using the `Content-Disposition` header should take care of that.
Comment: Thanks for the help. one more question, if I may: is there any way to set margins and things like that for the document?


What is this stylish R-like symbol?

Question:
What is that stylish R-like symbol at the end of the statement? I combed the lists of linear algebra symbols from almost every source online. Some guesses were Row space (which might make sense, just that I can't find any sources) and Rank (which doesn't make any sense...)
The book is Sliding Mode Control: Theory And Applications (by Christopher Edwards and Sarah Spurgeon) page 37.
Comment: Notation means whatever the author intends it to mean.  Not every author uses the same notation.  Notation used in a textbook should hopefully be defined during the relevant chapters when it was introduced or included in an index or appendix at the front or back.
Comment: That said, it makes sense for $\mathcal{R}$ to denote *range* (*not rowspace*) and $\mathcal{N}$ to denote nullspace given the context.
Comment: @JMoravitz You're right. I assumed the book did not have such a list. I did find one though, in the appendix. And it is the range of A.
Comment: For the record, it's (perhaps up to some hardly perceivable differences) a capital R in "Calligraphic" font (latex command mathcal) $\mathcal R$.
Answer: $\mathcal R(A)$ is not an uncommon notation for the row space of $A$. Neither is just $R(A)$. I'm not sure which sources you're consulting, but I've seen both.
However, the ultimate authority on notation is the textbook itself. If you go to p. 207 of the textbook (A.1 Mathematical Notation in the table of contents), you see the line

$\mathcal R(A) \quad$ the range space of the matrix $A$ (viewed as a linear operator)

and so that's what it is. You might be more used to saying "column space" instead of "range space".

What is this stylish R-like symbol?