how to update field of attendance via an attendance request modification

Question: i'm using odoo 11. i'm working on the attendance module i want to create an attendance modification request  which be approuved by the manager (to create a new attendance or modify an attendance already existe) and the attendances automatically updated. the probleme is when i press approuve my request was approuved but the attendances were not updated (in the hr.attendance model). Any idea for help please ??
 here is  my code
regularization.py
class Regular(models.Model):

_name = 'attendance.regular'
_rec_name = 'employee'
_description = 'Approval Request'
_inherit = ['mail.thread', 'mail.activity.mixin']

def _get_employee_id(self):
    employee_rec = self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)
    return employee_rec.id

reg_category = fields.Many2one('reg.categories',
                                string='Regularization Category', required=True)
from_date = fields.Datetime(string='Check in', required=False)
to_date = fields.Datetime(string='Check out', required=False)
reg_reason = fields.Text(string='Reason', required=False)
employee = fields.Many2one('hr.employee', string="Employee", default=_get_employee_id, readonly=False, required=True)
state_select = fields.Selection([('draft', 'Draft'), ('requested', 'Requested'), ('reject', 'Rejected'),
                                 ('approved', 'Approved')
                                 ], default='draft', track_visibility='onchange', string='State')
attendance_id = fields.Many2one('hr.attendance', string='Attendance')

@api.multi
def submit_reg(self):
    self.ensure_one()
    self.sudo().write({
        'state_select': 'requested'
    })
    return
   @api.multi
   def regular_approval(self):
    for record in self:
              if self.reg_category.type ==" Check in":
                    record.attendance_id.check_in = record.from_date
                    record.attendance_id.employee_id = record.employee.id
              elif self.reg_category.type ==" Check out":
                  record.attendance_id.check_out = record.to_date
                  record.attendance_id.employee_id = record.employee.id

    return  self.write({ 'state_select': 'approved' })

regularization.xml
  <?xml version="1.0" encoding="utf-8"?>
  <odoo>
   <data>
   <record id="attendance_regular11" model="ir.ui.view">
        <field name="name">attend.regular</field>
        <field name="model">attendance.regular</field>
        <field name="arch" type="xml">
           <form string="Regularization">

                       <button name="submit_reg" string="Submit" type="object" class="btn-primary"
                       attrs="{'invisible': [('state_select','not in','draft')]}"/>
                       <button name="regular_approval" type="object" string="Approve" class="oe_highlight"
                               groups="hr_attendance.group_hr_attendance_manager"
                       attrs="{'invisible': [('state_select','not in','requested')]}"/>
                       <button name="regular_rejection" type="object" string="Reject" class="oe_highlight"
                               groups="hr_attendance.group_hr_attendance_manager"
                       attrs="{'invisible': [('state_select','not in','requested')]}"/>
                       <field name="state_select" widget="statusbar" statusbar_visible="draft,requested,approved"/>

               <sheet>
                   <group col="4" colspan="4">
                       <field name="reg_category"/>
                       <field name="from_date" attrs="{'invisible':[('reg_category', '=',5)]}" />
                       <field name="reg_reason"/>
                       <field name="to_date" attrs="{'invisible':[('reg_category', '=',4)]}"/>
                       <field name="employee"/>

                   </group>
               </sheet>
             <field name="message_follower_ids" widget="mail_followers" groups="base.group_user"/>
                    <field name="activity_ids" widget="mail_activity"/>
                    <field name="message_ids" widget="mail_thread"/>
           </form>
        </field>
    </record>

Answer: I guess the problem is the field type you choice fields.Many2one.
It's should be m2m type.
I have a similar example for you.

<record model="ir.ui.view" id="course_form_view">
     <field name="name">course.form</field>
     <field name="model">openacademy.course</field>
     <field name="arch" type="xml">
         <form string="Course Form">
             <sheet>
                 <group>
                     <field name="name"/>
                     <field name="responsible_id"/>
                 </group>
                 <notebook>
                    <page string="Description">
                        <field name="description"/>
                    </page>
                    <page string="Sessions">
                        <field name="session_ids">
                             <tree string="Registered sessions">
                                 <field name="name"/>
                                 <field name="instructor_id"/>
                             </tree>
                        </field>
                    </page>
                    <page string="About">
                        This is an example of notebooks
                    </page>
                 </notebook>
             </sheet>
         </form>
    </field>
 </record>

<record model="ir.ui.view" id="session_form_view">
     <field name="name">session.form</field>
     <field name="model">openacademy.session</field>
     <field name="arch" type="xml">
         <form string="Session Form">

                 <button name="action_draft" type="object" string="Reset to draft" states="confirmed,done"/>
                 <button name="action_confirm" type="object" string="Confirm" states="draft" class="oe_highlight"/>
                 <button name="action_done" type="object" string="Mark as done" states="confirmed" class="oe_highlight"/>

                 <field name="state" widget="statusbar"/>

             <sheet>
                 <group string="General">
                     <field name="course_id"  options="{'limit': 3}"/>
                     <field name="name"/>
                     <field name="instructor_id"/>
                     <field name="active"/>
                 </group>
                 <group string="Schedule">
                     <field name="start_date"/>
                     <field name="duration"/>
                     <field name="seats"/>
                     <field name="taken_seats" widget="progressbar"/>

                 </group>

                 <field name="attendee_ids"/>
             </sheet>
         </form>
     </field>
 </record>

class Course(models.Model):
    _name = 'openacademy.course'

    name = fields.Char(string="Title", required=True)
    description = fields.Text()

    responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True)
    session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions")

    # 去改寫action的Duplicate
    @api.multi
    def copy(self, default=None):
        default = dict(default or {})

        copied_count = self.search_count([('name', '=like', u"Copy of {}%".format(self.name))])

        if not copied_count:
            new_name = u"Copy of {}".format(self.name)
        else:
            new_name = u"Copy of {} ({})".format(self.name, copied_count)

        default['name'] = new_name
        return super(Course, self).copy(default)

    # unlink 是 改寫Action的Delete

    _sql_constraints = [
        ('name_description_check',
         'CHECK(name != description)',
         "The title of the course should not be the description"),
        ('name_unique',
         'UNIQUE(name)',
         "The course title must be unique"),
    ]

class Session(models.Model):
    _name = 'openacademy.session'

    name = fields.Char(required=True)
    start_date = fields.Date(default=fields.Date.today)
    duration = fields.Float(digits=(6, 2), help="Duration in days")
    seats = fields.Integer(string="Number of seats")
    active = fields.Boolean(default=True)
    color = fields.Integer()

    instructor_id = fields.Many2one('res.partner', string="Instructor", domain=['|', ('instructor', '=', True), ('category_id.name', 'ilike', "Teacher")])
    course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True)
    attendee_ids = fields.Many2many('res.partner', string="Attendees")
    taken_seats = fields.Float(string="Taken seats", compute='_taken_seats')
    end_date = fields.Date(string="End Date", store=True, compute='_get_end_date', inverse='_set_end_date')
    hours = fields.Float(string="Duration in hours", compute='_get_hours', inverse='_set_hours')
    attendees_count = fields.Integer(string="Attendees count", compute='_get_attendees_count', store=True)
    state = fields.Selection([('draft', "Draft"),('confirmed', "Confirmed"),('done', "Done"),], default='draft')

    @api.multi
    def action_draft(self):
        self.state = 'draft'

    @api.multi
    def action_confirm(self):
        self.state = 'confirmed'

    @api.multi
    def action_done(self):
        self.state = 'done'

    @api.depends('seats', 'attendee_ids')
    def _taken_seats(self):
        for r in self:
            if not r.seats:
                r.taken_seats = 0.0
            else:
                r.taken_seats = 100.0 * len(r.attendee_ids) / r.seats

    @api.depends('attendee_ids')
    def _get_attendees_count(self):
        for r in self:
            r.attendees_count = len(r.attendee_ids)

    @api.depends('duration')
    def _get_hours(self):
        for r in self:
            r.hours = r.duration * 24

    def _set_hours(self):
        for r in self:
            r.duration = r.hours / 24

    @api.depends('start_date', 'duration')
    def _get_end_date(self):
        for r in self:
            if not (r.start_date and r.duration):
                r.end_date = r.start_date
                continue
            start = fields.Datetime.from_string(r.start_date)
            duration = timedelta(days=r.duration, seconds=-1)
            r.end_date = start + duration

    def _set_end_date(self):
        for r in self:
            if not (r.start_date and r.end_date):
                continue
            start_date = fields.Datetime.from_string(r.start_date)
            end_date = fields.Datetime.from_string(r.end_date)
            r.duration = (end_date - start_date).days + 1

    @api.onchange('seats', 'attendee_ids')
    def _verify_valid_seats(self):
        if self.seats < 0:
            return {
                'warning': {
                    'title': "Incorrect 'seats' value",
                    'message': "The number of available seats may not be negative",
                },
            }

        if self.seats < len(self.attendee_ids):
            return {
                'warning': {
                    'title': "Too many attendees",
                    'message': "Increase seats or remove excess attendees",
                },
            }

    @api.constrains('instructor_id', 'attendee_ids')
    def _check_instructor_not_in_attendees(self):
        for r in self:
            if r.instructor_id and r.instructor_id in r.attendee_ids:
                raise exceptions.ValidationError("A session's instructor can't be an attendee")


Python, openpyxl column with adjustment

Question: Hopefully someone can help explain a line of code for me in the block blow. I got this from another post but was unable to ask the question using comments because I'm a new user and do not have enough reputation points..
Anyways, Python noob here, please forgive me. How did the poster know col[0].column will get the column name? I couldn't find in the openpyxl docs where the .column properties came from.
for col in worksheet.columns:
     max_length = 0
     column = col[0].column # Get the column name
     for cell in col:
         try: # Necessary to avoid error on empty cells
             if len(str(cell.value)) > max_length:
                 max_length = len(cell.value)
         except:
             pass
     adjusted_width = (max_length + 2) * 1.2
     worksheet.column_dimensions[column].width = adjusted_width

Comment: *"How did `col[0].column` get the column name?"* The doc says `.column` **Column number of this cell (1-based)**. No *name*, but the index of the given **cell** `col[0]`. E.g. `2` for column `B`.
Comment: https://linux.die.net/diveintopython/html/power_of_introspection/getattr.html
Answer: col[0].column is returning number while worksheet.column_dimensions[column] accepts only character such as 'A', 'B', 'C' in place of column. I've modified the code and it is working fine now.
import re

for col in _ws.columns:
max_lenght = 0
print(col[0])
col_name = re.findall('\w\d', str(col[0]))
col_name = col_name[0]
col_name = re.findall('\w', str(col_name))[0]
print(col_name)
for cell in col:
    try:
        if len(str(cell.value)) > max_lenght:
            max_lenght = len(cell.value)
    except:
        pass
adjusted_width = (max_lenght+2)
_ws.column_dimensions[col_name].width = adjusted_width

Python, openpyxl column with adjustment


how to search a username in php ajax

Question: hey guys I need some help please guide me where I am doing wrong in coding. This is table of showing record of users
I want pagination operation and search operation on my index.php file. Pagination is working but when I am type a single letter (example: a or Haris) on search bar then show me message that data not found this is message showing when type a username on search bar
This my ajax function that on index.php file I am pagination or search

This my search.php file
<?php
  include("common/config.php");
   $output = '';

    if(isset($_POST["query"]))
   {
    $search =  $_POST["query"];

   $where = "id LIKE '%".$search."%'
      OR name LIKE '%".$search."%'
      OR email LIKE '%".$search."%'
      OR phone LIKE '%".$search."%'";

   $query = $db->select(array("*"),"user","$where","","id desc","");
   }
    else
   {
    $limit = 5;

    $page = '';
   if (isset($_GET["page"] ))
      {
    $page  = $_GET["page"];
    }
else
   {
    $page=1;
   }

   $record_index= ($page-1) * $limit;

    $query = $db->select(array("*"),PREFIX."user", "", "", "id desc", "$record_index, $limit");
    }

  if($query)
 {
    $output .= '

         <input type="checkbox" name="select_all" id="select_all" value=""/>
         ID
         Name
         Email
         Phone
         Action

    ';
      foreach($query as $row)

   {
      $output .= '

      <input type="checkbox"  name="checked_id[]"
  class="checkbox" value="'.$row->id.'"/>
      '.$row->id.'
      '.$row->name.'
      '.$row->email.'
      '.$row->phone.'
      id.'">Edit
      id.'">Delete

';
    }

    $output .= '

';
     $total_pages = ceil($db->countfields("*","user") / $limit);
    for($i=1; $i<=$total_pages; $i++)
   {
        $output .= "".$i."";
 }

    $output .= '

';
    echo $output;
  }
else
  {
 echo 'Data Not Found';
 }

 ?>

When I am change the name of function,pagination is working but its still search a user record not working.

Comment: Your code is vulnerable to SQL injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. Never insert unsanitised data directly into your SQL.
Comment: And can you please format and indent your code properly? It's impossible to see the flow of control clearly with those brackets all over the place. I don't know how people can work efficiently with code laid out like that.
Comment: I am using dbase file that some functions are defined that'why I am using insert query that send directly to sql.
Comment: that still doesn't excuse the complete lack of any validation of the input whatsoever. A user could easily include SQL statements in their search terms that could steal, corrupt or destroy your data
Comment: Anyway there's not enough info. We don't know precisely what SQL statement is formed by your unseen "select" function, or whether you have any data which matches it. You haven't said whether the data is transmitted to the server correctly (have you checked the ajax request in your network tab). There are also two different calls to search.php implemented in your JS, and three different SELECT queries which could be run. You haven't told us specifically which ones of these are being used? It would help to narrow down the problem. What's the flow of control that reproduces the issue?
Comment: It's no good saying " I am type a single letter (example: a or Haris) on search bar " because we can't see your "search bar" and we don't know which piece of Javascript that runs. I'm _guessing_ it maybe triggers the "keyup" event on the "message" element? That's a guess though because an element called "message" doesn't immediately make me think it's a "search" input.
Comment: @ ADyson (This is table of showing record of users)-> please click on this line in above my question then you will see the search bar
Comment: my query is running perfectly but I think that may be I have a issue in my ajax function that written in my index.php file
Comment: Seeing the search bar in a screenshot is nice but it tells me nothing about which code it calls. Your suggestion doesn't answer my questions at all. Please read my comments again properly and answer the questions I asked. If you aren't able to do that, it will be very difficult for me (and probably others) to offer you any meaningful help.
Comment: Actually DanielW below makes a good point, which I hadn't noticed. You can't have 2 functions with the same name within the same scope in JS. The first one can never be used because the second one has already taken its place before you execute it. So chances are you're not calling the bit of PHP code that you thought you were. Again if you'd done some basic debugging as I suggested and checked the actual request being sent (using your browser tools) you might notice which parameter name is being transmitted. If you want to use ajax successfully you need learn to use the debug tools available
Comment: There is no `dataType` in you ajax request
Comment: Robert Rocha I can't understand what you are saying, can you explain it through write a code?
Comment: In your `AJAX` you need to show what type of data you're expecting back from the server with out telling the `JQuery` what type pf data is returning back `JQuery` won't work. Here read [this](http://api.jquery.com/jQuery.ajax/) it'll clear things up for you.
Answer: I don't see from your code what "PREFIX" is, but in the search query it is missing while it is present in the pagination query. Hope it helps
Comment: You have 2 load_data functions, the second function overwrites the first one, so the search is also calling the second function, which is intended to do the pagination. Try to rename your functions to load_data_1 and load_data_2.
Comment: No sir prefix is not a issue.
Comment: @ Daniel W see my above question I updated it as you said that change the function
Comment: At one place you forget to rename the function: `if(srch != '')
      {
      load_data(srch);
       }`
This should be:
`if(srch != '')
      {
      load_data_1(srch);
       }`
Comment: Could you please post a screenshot from the inspector's network tab, when you try to do the search? I would like to see the request details which is sent to the server.
Comment: In above my question there is some blue lines please click on it then you will see error message when I am type a letter on search bar
Comment: I've tried the ajax part and if you corrected the function name I've mentioned above, it should work, and it posts the query variable properly. Did you try to run the search query manually from php without the ajax request? Please provide additional details for us to be able to help. (code of the $db->select function, debug output of the variables etc)

how to search a username in php ajax


Obter data-ref de diferentes botões

Question: Criei um sistema em que exibe os dados de uma tabela mysqlpor meio do plugin datable. Um dos dados exbidos é um modal. O codigo javascript  pega o data-ref, que contem o id. Este id vai ser usado em querys mysql futuras.
A Duvida: quando são geradas mais de uma linha, o ajax sempre retorna o id da primeira linha, e não o id referente a linha clica. Quero saber como retornar o id (que esta em um atributo data-ref) da linha especifica.
Esse é codigo javascript que obtem o "id" e dispara o ajax:
        $('#verpedido').on('show.bs.modal', function (e) {
        let id_pedido = $("#detalha").attr('data-ref');
        $.ajax({
        url: 'http://notasfiscais-ipc.stackstaging.com/edita.php',
        data: {id: id_pedido},
        type: 'POST',

        success: function(response){

        $('#teste').empty();
        $('#teste').html(response);
        }
        });
        });

Esse é o HTML da table:
            34592	005_17	CLIENTE 01	2017-04-12

35194	2689	CLIENTE 02	2017-05-16

`

Comment: Tem q criar um id diferente para cada linha. Seu código já jaz isso?
Comment: Formata melhor esse código aí...
Answer: Precisamos analisar que #detalha é um id único. O que podemos fazer é da seguinte forma:
$('#verpedido').on('show.bs.modal', function (e) {
    let id_pedido = $(".detalha").attr('data-ref');
        $.ajax({
            url: 'http://notasfiscais-ipc.stackstaging.com/edita.php',
            data: {id: id_pedido},
            type: 'POST',
            success: function(response){
                $('#teste').empty();
                $('#teste').html(response);
            }
        });
});

Sendo assim, aplicando a classe, conseguirá obter o resultado esperado.
Note que removi o id="detalha" e apliquei o detalha como classe.
Answer: 1º voce não pode (pelo menos não deve) ter elementos com o mesmo id.
2º Voce tem que manipular o button ou linkque foi clicado e depois chamar o modal. Uma forma de fazer seria assim:
$('.btn').on('click', function (e) {
    let id_pedido = $(this).attr('data-ref');

    // chamar o modal dentro do click

    alert(id_pedido);

    $.ajax({
       url: 'http://notasfiscais-ipc.stackstaging.com/edita.php',
       data: {id: id_pedido},
       type: 'POST',

       success: function(response){
          $('#teste').empty();
          $('#teste').html(response);
       }
    });
 });

Obter data-ref de diferentes botões


Probability - Screening off/ Casuality

Question:
Let   ,   , and    be events. If  $(|∩)=(|)$ , then    is said to screen    off from   . Suppose that  $(∩)>0$.  Show that screening off is equivalent to saying that  $$(∩|)=(|)(|).$$  What does this latter equation say in terms of independence?

I am struggling to find a way to formulate an answer to this.
Essentially what I am thinking is something along the lines of:
As
$$
   P(E|C) = \frac{P(E∩C)}{ P(C)}
$$
And
$$
   P(A∩C) = P(A|C)P(C)
$$
Then something along the lines of:
$$
   \frac{P(E∩(P(A∩C)P(C))) }{P(A∩C)P(C)} = \frac{P(E∩C) }{P(C)}
$$
That is a very rough idea. I am not sure if that is even remotely close to what I need to be doing. Any suggestions would be great. Ideally I would like to figure this out myself but a nudge in the right direction would be great.

The later equation indicates that event E and A are independent of one another as knowing the outcome of event A does not interfere with the outcome of event E.
Comment: 1. The questions specifies that E and C are not mutually exclusive, but I don't see why this condition is necessary. $\quad$  2. "*What does this latter equation say in terms of independence?*" The latter equation says that A is conditionally independent of E, given C.
Comment: @ryang For the best explanation possible. Check out this section [ScreeningOff](https://plato.stanford.edu/entries/causation-probabilistic/#ScreOff)      Section 2.2) Screening Off Prior to finding this article, I roughly understood how it was used but I am not quite confident enough to explain it to the level they are capable of.
Comment: @ryang Initially yes as a rough example to see if I was heading in the right direction but after revising and the assistance from the gentleman below I realised that was not meant to be the case. I was under the impression I needed to substitute for both sides when in actual fact just the one would have sufficed. This is the first example of this I have ever had to work with. It is apart of a homework assignment. We have not learnt about Screening off and I could not seem to find any examples in the section of the textbook/ lectures we have covered as of yet hence the reason I asked.
Comment: I don't understand what you're trying to say. To be super clear: I think that the given condition $\quad$ "Suppose that $P(E∩C)>0$" $\quad$ is **redundant**, because *even if* $P(E∩C)=0,$ the required result $P(A∩E|C)=P(A|C)P(E|C)$ *still holds*.
Comment: @ryang Oh that statement is what you are referring too. That makes more sense now. That is not a claim of mine, it is their question. I don't know why they felt the need to include it as long as P(C) ≠ 0 Then the theory of causality will hold. I do agree with you on that, they have a weird way of wording their questions sometimes.
Answer: Your attempt is close. Applying the definition of conditional probability,
$$\begin{align*}
P(E\mid A\cap C) &= P(E\mid C)\\
\frac{P(E\cap A \cap C)}{P(A\cap C)} &= P(E\mid C)\\
\frac{P(A\cap E\mid C)P(C)}{P(A\mid C)P(C)} &= P(E\mid C)\\
P(A\cap E\mid C) &= P(A\mid C)P(E\mid C)
\end{align*}$$

Compare these, with or without condition:
$$\begin{align*}
P(E\mid A\cap C) &= \frac{P(E\cap A\mid C)}{P(A\mid C)} &&(P(C)\ne 0)\\
P(E\mid A) &= \frac{P(E\cap A)}{P(A)}
\end{align*}$$
Compare these, for 1) independent $A$ and $E$ given $C$, and 2) independent $X$ and $Y$:
$$\begin{align*}
P(A \cap E\mid C) &= P(A\mid C)P(E\mid C)\\
P(X\cap Y) &= P(X)P(Y)
\end{align*}$$
Comment: Perfect, thank you very much!

Probability - Screening off/ Casuality


GAM factor-smooth interactions and model selection

Question: I'm working with a dataset which is a long-term animal abundance survey collected from 11 sites, which have different average temperature(also there are some missing years for some sites). Here, the abundance [referred to as TrapRate3 (a probability of capture ranging from 0~1) in the code] from all sites suggest a decreasing trend, which I hypothesis influenced by the increasing temperature (referred to as PT36). My aim is to model the temperature effect on abundance while accounting for Site as a random effect and make predictions to see abundance change if temperature continue increase in the future.
For clarify, here are simple plots of my dataset, TrapRate3 vs. Year, PT36 (Temperature factor) vs. Year and TrapRate3 vs. PT36,respectively.

Because I'm interested in the global temperature effect, so I fitted as
TrapRate3 ~ Site + s(T) + s(T, by = Site, m = 1) + s(Year):
m1<-gam(TrapRate3~Site+s(PT36, k=5,m=2,bs="tp")+s(PT36, by=Site, k=5, bs="tp",m=1)+s(Year,bs="tp",k=5), method="REML", family = binomial,weights = March,data=c2)
summary(m1)
Family: binomial
Link function: logit

Formula:
TrapRate3 ~ Site + s(PT36, k = 5, m = 2, bs = "tp") + s(PT36,
by = Site, k = 5, bs = "tp", m = 1) + s(Year, bs = "tp",
k = 5)

Parametric coefficients:
        Estimate Std. Error z value Pr(>|z|)
(Intercept) -4.37220    0.23710 -18.440  < 2e-16 ***
 SiteDF      -0.33215    0.68777  -0.483 0.629144
 SiteDY       0.01839    0.26379   0.070 0.944432
 SiteLS       0.57169    0.27442   2.083 0.037227 *
 SiteLZ       0.85859    0.24881   3.451 0.000559 ***
 SiteSN       1.33748    0.24921   5.367 8.01e-08 ***
 SiteTZ       0.33294    0.46194   0.721 0.471073
 SiteWA       0.82360    0.26247   3.138 0.001702 **
 SiteXF       1.05429    0.24690   4.270 1.95e-05 ***
 SiteYQ       1.00026    0.30197   3.312 0.000925 ***
 SiteZY       0.13089    0.29959   0.437 0.662192
 ---
 Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

 Approximate significance of smooth terms:
                  edf Ref.df  Chi.sq  p-value
 s(PT36)         1.000e+00  1.001   4.049 0.044225 *
 s(PT36):SiteCG  1.636e+00  4.000  11.544 0.000747 ***
 s(PT36):SiteDF  5.911e-01  4.000   1.347 0.129350
 s(PT36):SiteDY  9.294e-06  4.000   0.000 0.929926
 s(PT36):SiteLS  1.986e+00  4.000   4.791 0.073857 .
 s(PT36):SiteLZ  1.642e-04  4.000   0.000 0.489253
 s(PT36):SiteSN  2.053e-04  4.000   0.000 0.897176
 s(PT36):SiteTZ  1.964e+00  4.000  13.838 0.000445 ***
 s(PT36):SiteWA  8.051e-05  4.000   0.000 0.573009
 s(PT36):SiteXF  3.634e-04  4.000   0.000 0.645788
 s(PT36):SiteYQ  2.310e+00  4.000  21.165 1.47e-05 ***
 s(PT36):SiteZY  1.735e+00  4.000  10.338 0.001272 **
 s(Year)         3.929e+00  3.996 192.603  < 2e-16 ***
 ---
 Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

 R-sq.(adj) =  0.606   Deviance explained = 64.5%
 -REML =    684  Scale est. = 1         n = 218

draw(m1)

My questions are:
1, Does this model appropriate for my issue? I could understand this kind modeling could account for the random intercept and slope, but I'm not sure for the different range of predictor (in my case, sites have a different average temperature---PT36). I mean, if site that experience colder temperatures on average also have a lower abundance (eg. site DF), then the model will suggest a global temperature effect with a rise of abundance with the increasing temperature. However, this wrong message is given by the site character, rather than the actual temperature-abundance relationship. (Is that right?? Or I misunderstand).
2, I'm not sure the Year trends I add with a right way. Should I need include a Year effect by Site: s(Year,by=Site)or s(Year)+s(Year,by=Site),which one?
For the model, could anyone give me any advices for improvement.
3,For the result, I could understand "s(PT36):Site" indicating how the functional response of that site differs from the global smoother, but does the significance means PT36 has a significant effect on TrapRate3 for this site or has a significant different effect from global smoother?? If the global smoother is significant, could I say 'for all sites, PT36 has a significant effect on TrapRate3'?
4, I'm a little confused about y ~ Site + s(x, by = Site) and y ~ s(x, by = Site) + s(Site, bs="re"). Are they both for the random intercept but with different way??
5, Besides the temperature (PT36) in my case, I also have other alternate climate factors, for example different period temperature and rainfall. I want to make model selection to choose the most influencing factor. My question is could I perform this kind of model selection just depend AIC? Also, in my case, models with different climate factor give similar AIC, so I guess I'd better check the prediction performance, right??
Really appreciate for any explanation and advices.
Comment: Be careful when you talk about "random effects" in context of penalized spline-based GAMs; if following advice to choose smoothness parameters by REML or ML, pretty much everything is a random effect...
Comment: "interested in how the abundance has changed through time across all the sites and the difference among the sites." and " to model the temperature effect on abundance through time while accounting for Site as a random effect" cannot be realize in one model.
Comment: Thanks. I might not have explained it clearly. I actually want to model the temperature effect on abundance while also taking account the difference by a site-specific term, then using the global and site-specific smoothers combine to predict abundance for individual site. Maybe I need re-edit my question.
Comment: is "predict abundance for individual site" your ultimate aim? If yes, the "individual sites" means 11 sites included in the data, or other sides not appeared in the data?
Comment: just the 11 sites included in the data
Comment: Actually also give a global function of temperature
Comment: Therefore, there is no random effect in your model based on you want applied your model to 11 sites appeared in data and have no plan to extent the model to other sites.
Comment: Did you mean using group (Site in my case) as a random effect could be used to simulate functional variation for unobserved group levels, but not possible as a fix effect? So in my case I should use 'Site' instead of 's(Site, bs="re")'. Right??
Answer: Q1
In words your model
TrapRate3 ~ Site +
  s(PT36, k = 5, m = 2, bs = "tp") +
  s(PT36, by = Site, k = 5, bs = "tp", m = 1) +
  s(Year, bs = "tp", k = 5)

posits that the response can be decomposed into

a fixed Site effect; each Site has it's own mean,
an average smooth effect of PT36 over all levels of Site,
a separate Site-specific smooth effect of PT36 which measures the deviation from the average smooth for the $j$th level of Site, and
a smooth effect of sample Year

The site-specific "difference" smooths are really estimating an entirely separate smooth for each level of Site; there is no shared information here and that implies that you are focused on this specific set of sites as you model can't generalise to other Sites. These smooths are also centred, which is why we require something in the model to account for the potentially different mean response values for each level of Site.
This model isn't saying that the population smooth effect of PT36, $f(\mathsf{PT36})$, applies to all unmeasured sites, sensu a random slope model in classical mixed effects modelling. However, it would be your best estimate of the effect of PT36 on the response for some unmeasured new Site. Whether you can use your model to predict the response at this unmeasured Site in another matter; you won't have an estimate for the mean response at any site because of the fixed effects Site term in the model.
One motivation for this model is that it can be more parsimonious than
TrapRate3 ~ Site +
  s(PT36, by = Site, k = 5, bs = "tp") +
  s(Year, bs = "tp", k = 5)

if all or most of the $f_{\mathrm{Site}}(\mathsf{PT36})$ have a very similar shape; why estimate 11 very similar smooth functions when you can estimate a single average function and 11, potentially simpler "difference" functions?
But, having said that, one of the ways of thinking about a random effect if that the effects are penalized towards some average effect; in a random intercept, the random effects are shrunk toward the overall intercept in the model, random slopes are shrunk towards the average or population "slope" in the model. Here, the estimated smooth effects for each Site are shrunk towards the average smooth effect but not with regard to the overall model intercept - the model includes fixed effect of Site. So, if it walks like a duck and quacks like one too...
Q2
Which you choose will depend entirely on how you hypothesise the Year effect to vary between Sites? If all Sites have largely been exposed to the same environment then one might expect a single common smooth effect of Year, so use + s(year) only. If you hypothesise that each of the 11 sites has experienced it's own, different, set of temporal events not related to Temperature, then + s(year, by = Site) would be warranted. If, however, you think that each site has experienced roughly the same set of temporally-ordered events or forcing but with some Site-specific idiosyncrasies, then you could use the + s(Year) + s(Year, by = Site, m = 1) form.
We can't answer that question for you I'm afraid.
Q3
The outputs in the summary are analogues of the $t$ tests of the null hypothesis that $\hat{\beta}_i = 0$ for the $i$th coefficient in the model. The difference here is that the null hypothesis assumes that the estimated function $\hat{f}_{\mathrm{Site}}(\mathsf{PT36}) = 0$, i.e. is a constant function. Is the estimated function and hence are the data consistent with this assumption?
Because of the way this smooth effect is penalized — m=1 means a first derivative penalty penalising deviation from a flat or constant function — and the way you've set this model up, there isn't anything in this model summary that you can point to that says PT36 has a significant effect on the response for this particular site. You couldn't do this, nor might one philosophically want to do so, if you'd estimate a random slope for each site about some population effect of PT36 in a mixed effects model.
Here you would most likely need to predict the response for each level of Site, whilst holding Year at the average Year, over the range of PT36 and plot the estimated values and the classic 95% point-wise confidence interval ($\pm$ 2 $\times$ SE($\hat{y}))$ and then look to see if the response varies over the range of PT36 and with what level of uncertainty. (Note this 95% interval has an across-the-function interpretation, not the usual 95% pointwise interpretation as it is really a Bayesian credible interval given improper priors on the smoothness parameters).
Q4
I've already touched on this but these two specifications are different:

y ~ Site + s(x, by = Site) estimates a separate mean for each level of Site; there's no shrinkage towards the overall model intercept in the coefficients implied by how Site enters the model (by default the coefficients for Site are parameterised into differences from the model intercept), whereas with
y ~ s(x, by = Site) + s(Site, bs = "re") the Site specific means are shrunk towards the overall model intercept (they're shrunk towards zero but then we add on the model intercept to get each Sites mean).

Q5
You could use AIC but you do have to be sure that the model is fully penalised if you are using REML. You can switch to estimating via ML if you aren't sure to do the selection and then refit the chosen model using REML to get the best estimates for the smoothness parameters.
AIC is an estimator of the leave-one-out (IIRC) MSE of the model so your selection if using it is based on prediction error.
Instead, you could embrace the world of penalties and use select = TRUE in your gam() code, which will put a separate penalty on any unpenalized term in the bases of the smooth function in the model (not the Site fixed effect, you'd need to do something else to penalize that, see paraPen argument). This extra penalty can shrink a term entirely out of the model — i.e. do model selection for you — whilst taking into account your uncertainty about whether and which covariates were related to the response; the summary() output will account for this extra uncertainty.
Comment: Great, you have clarified things nicely. I think I have a deeper understanding of the model. Much appreciate. There still one following question for Q3, is that means "  when average smooth is significant, means PT36 has a significant effect over all levels of Site; and when the difference smooth (̂Site()) is significantly different (from 0), we can conclude that the sites follow a different effect from the global effect?
Comment: Here because I want to demonstrate all the sites have a similar climate factor effect (slope could different but the inverse effect for some sites is not expected). Furthermore the inverse effect couldn't be explained because all the sites have experienced a similar decreasing trend and exposed to a same changing climate. Thanks.
Comment: One more question about the interpretation of difference smooth.  I could understand the flat line means similar shape with global smoother with differing only in intercept, but I'm confused why a similar trend means a reverse pattern? (e.g.,Fig.13 smooth for Mn1 in your paper"HGAM in ecology: an introduction with mgcv"). Much appreciate.
Comment: I think my data is probably a case of what's called Simpson's Paradox, which is  appears abundance goes up with temperature, but at any given site, abundance is going down with temperature. I'm going include two variables for temperature: an average temperature in a reference period and a year-to-year deviance from average.
Comment: C1: if `s(PT36)` is significant, it means that, conditional upon the other terms in the model, that the data provide evidence against the null hypothesis that the true function $\hat{f}(\mathsf{PT36})$ is a flat constant function. If a site specific smooth is significant, this means that conditional on the other terms in the model, the deviations of the smooth function from the average is not a constant function.
Comment: C2: I'm not sure you can do this. We assume the null is true when doing these frequentist tests, where data is assessed for evidence against, not for, the null. All you can do here is show that you don't need different smooths for each level of `Site` given some metric like AIC (i.e. some prediction level measure).
Comment: C3: With `Mn1`, the 0 line would be no variation from average. As the estimated curve is lower than the average at low concentrations  and higher than average at high concentrations, this is consistent with what we wrote; that the `Mn1` curve differs from the average conversely to those for `Mc1` or `Qn1` which trend in the opposite direction.
Comment: Much appreciate @Gavin, your explanation helps me a lot. I'll think about your suggestions.


Scrape TripAdvisor Hotel Page with Python

Question: I'm currently building a scraper to get reviews and ratings.
Have it working for Restaurants but it gives me a 400 for Hotels
Here's the code: https://gist.github.com/jamieaitken/e6df15db9f1204fe67c16f1404996c6f
Comment: Please show some proof of attempt for the scraping.
Comment: Fun Fact: `request('GET', url=urlNotWork)` did work. So i guess something is wrong with the headers ...
Comment: @yogkm Updated post so that all the code is in a gist
Comment: @meissner_ Could you post that as an answer please? It worked so thanks
Answer: Hhm, regular requests should work just fine here, like:
<code>from requests import request as req

url = 'https://www.tripadvisor.co.uk/Hotel_Review-g60745-d121009-Reviews-Holiday_Inn_Express_Boston-Boston_Massachusetts.html'
rsp = req('GET', url)

if rsp.status_code == 200:
    print(rsp.text.encode('utf-8'))
</code>


How to find a bug that only happens in the Javascript version of a Dart program?

Question: I've written a program that runs perfectly in Dart but fails to run in the transpiled Javascript version. I suspect it's an infinite loop (because CPU usage goes up). Has anybody experienced such a behavior before? Maybe even more important, how can I find out the problem?
Comment: What happens when you step through the code?
Comment: Have you checked the console output of the developer tools of the browser for error messages?.
When you build with `pub build --mode=debug` you get readable JavaScript and can use the debugger of the developer tools.
Comment: @Günther: that was exacatly the hint I was looking for. Thanks!

Yes, of course I've checked the console. It's empty. Most likely the debug flag will help me. Too bad it doesn't seem to be possible to activate it in DartEditor.
Answer: Yes; this is a big part of my day job.
First, understand that you are most likely dealing with a dart2js bug, not a bug in your code.  Your immediate goal is to work around the problem.  The end goal, though, is to construct a small test case that you can file on dartbug.com.
Checked mode is your friend
If you are really lucky, enabling checked mode will throw an assertion that will point to the problem.  If not, you'll need to dig into the JS.
Using pub serve or pub build --mode=debug will give you more readable code.  I usually set my pubspec.yaml up like so:
transformers:
- $dart2js:
  minify: false
  checked: true

(or checked=false if I'm chasing a performance issue).  Then running pub build (without any arguments) will produce to desired output.
Produce a smaller use-case
If you can get Angular out of the mix, the Dart Team will have a much easier time debugging.  Failing that, generate a AngularDart application that shows the error on page load.
Print statements
Adding print statements in Dart help you understand the execution flow, but also make it easy to search the dart2js output for good places to add breakpoints.
I find that source maps only confuse things and always disable them.
git bisect
Once you have a small enough use-case that triggers on page load, using git bisect to search your history for the breaking change is quick and impresses your friends.
Comment: More options on $dart2js can be found at [the pub documentation](https://www.dartlang.org/tools/pub/dart2js-transformer.html).
Comment: As it seems the transformers should not be the last entry in pubspec.yaml. After some trying, [this version](https://github.com/stephanrauh/AngularPrime-Dart/blob/master/pubspec.yaml) worked fine with me.
(Sorry for giving a link to my repository, I'd prefer to show it here, but formatting doesn't seem to work in a comment).
Comment: I like the "print statement" hint. Such a simple idea, and so useful!
Answer: You can get readable JavaScript by running dart2js in debug mode. If you are using pub build you need to use pub build --mode=debug.
Answer: Dart can generate source maps since a while which makes it quite easy to debug generated JS.
With source maps the browsers show Dart code and stack traces when debugging built JS code.
Source maps need to be enabled in the browser (see https://www.dartlang.org/tools/dart2js/ for details) and in the $dart2js transformer (see https://www.dartlang.org/tools/pub/dart2js-transformer.html for details)


ruby sqlite error 'ensure in insert_row': undefined local variable or method 'stmt'

Question: I have the following method in a dbmgr ruby class, which I'm using within a loop to insert data from a csv into a sqlite3 db:
  def insert_row(aRow)
    begin
    @db = SQLite3::Database.open("#{@dbn}")
    rhash = aRow.row_hash

    stm = @db.prepare("INSERT INTO programs (programName, episodeName) VALUES (? , ? )")
        stm.bind_param(1, '#{rhash["Program"]}' )
        stm.bind_param(2, '#{rhash["Episode Name"]}' )
        stmt.execute()
        programId = @db.last_insert_row_id

     rescue SQLite3::Exception => e
        puts "Exception occured"
        puts e.message
        puts e.backtrace

    ensure
        stmt.close if stmt
        @db.close if @db

    end #db

When I do that on the console after the 1st insertion I get the following error:
  `ensure in insert_row': undefined local variable or method `stmt' for #<Dbmgr:0x007f9511050188> (NameError)

Initially, I did not use the prepare and bind_params features of ruby for sqlite. However, after some characters like " ' " in the text I was inserting generated exceptions, I read somewhere that using bind_params would clean the input so I used bind_params. But now I'm getting this error.
Answer: stm = @db.prepare("INSERT INTO programs (programName, episodeName) VALUES (? , ? )")
    stm.bind_param(1, '#{rhash["Program"]}' )
    stm.bind_param(2, '#{rhash["Episode Name"]}' )
    stmt.execute() # <-- you're referring to stmt instead of stm here
    programId = @db.last_insert_row_id

You've used stm throughout this statement, then refer to stmt.execute() and stmt.close
Comment: OH MAN. thats what it was, thanks to XCode not autosaving my edits to the code. haha, now I feel stupid for asking.


Four dots over tremolo minim (half note with slash)

Question: I'm working on National Emblem by E. E. Bagley. In the second strain, there is a minim with the tremolo mark. Above it are four dots. What do they mean?
Here is a picture. The mark in question is found in the third measure of the second line. It is also found throughout other parts of the piece.
Comment: Do you want [red freehand circles](http://meta.stackexchange.com/a/19775/192187) too? :D
Comment: Surely it would be just as easy to write out the four staccato quavers - then everyone would get it exactly right?
Answer: It is not actually a tremolo.  The thick line represents an eighth-note beam, and is shorthand for four eighth notes.  And yes, the four dots -- one for each eighth-note -- indicate staccato.
In drum music, a roll is frequently indicated by two thick beams over a long note.  This is exactly the same notation as sixteenth notes.  How do you know whether to play exact sixteenth notes instead of a roll?  Sometimes the composer will write out all the sixteenth notes, and sometimes he or she will instead write the staccato dots, one for each intended sixteenth note.
Comment: Yes, it is a tremolo. "One-Note Tremolo" is in fact the technical term for this type of notation, the slash through the stem of the notehead. (it may also go by other names.) That is how this symbol is referred to in the Sibelius and Finale music notation programs, and in texts on music engraving.
Comment: There is another kind of notation for a "two-note tremolo" which is an alternation back and forth between two notes or two chords. In that kind of notation, the slash strokes are positioned between the stems of two adjacent notes or chords.
Answer: I believe it is an indication that the (four) notes of the tremolo should be played staccato.
In your example this would mean that you should start that bar with four "staccatoed" eighth notes (of A) instead of a half note "tremoloed" in some other way (such as legato or with alternate fingerings).
When I have encountered this notation style - typically in trumpet parts - there has been no tremolo mark and the tremolo, or division of the underlying note into fractions, was infered by the dots. It then constitutes a sort of shorthand in place of writing out all the notes (and as such not nessecarily to be performed as staccato; I've played tuba parts with whole notes decorated with four dots above them that I was instructed to play as four regular quarter notes).
My experience with dots like that is mainly from old sheet music for Scandinavian marches. There might be cultural differences, but I guess that staccato is what it means also in your music
Answer: NO! NO! NO! NO!  IT IS NOTTTTT!!! a roll. The dots indicate a four note subdivision in the time of the note they are over: a half note with a single slash indicates play eighth notes (four of them). A quarter note with a double slash and four dots means to play sixteenth notes.
Answer: Here's another example of 4 dots over a half note with a slash from Chopin's Prelude No. 15:

The same bars from IMPSL:

And here's the more commonly used notation:

Sources:

https://en.wikipedia.org/wiki/Prelude,_Op._28,_No._15_%28Chopin%29#/media/File:Full_page,_Chopin_Prelude_15.png
https://imslp.org/wiki/Special:ReverseLookup/85374
https://imslp.org/wiki/Special:ReverseLookup/63317


Multiple orWhere() in whereHas() in Laravel 5

Question: Contact Model
class Contact extends Model
{
    public function Account()
    {
        return $this->belongsTo('app\Account');
    }
}

Account Model
class Account extends Model
{
    public function Contact()
    {
        return $this->hasMany('app\Contact');
    }
}

I want to get query of all Contacts that have account_name = 'test' or account_city ='test2'.
$query = Contact::query();
    $query->whereHas('Account', function ($q) {
        $q->orwhere('account_name' ,'=', 'test');
        $q->orwhere('account_city','=','test2');
    });
$query->get;

This query shows me all Contacts that have an Account but I want to get only Contacts that have account_name = 'test' or account_city ='test2'
Result of $query->tosql();
select * from `contacts` where exists (select * from `accounts` where (`contacts`.`account_id` = `accounts`.`id` or (`account_name` = ? or `account_city` = ?)) and `accounts`.`deleted_at` is null) and `contacts`.`deleted_at` is null

Comment: could you help to do [`$query->toSql()`](https://laravel.com/api/5.7/Illuminate/Database/Query/Builder.html#method_toSql) to see the actual generated sql query?
Comment: I edit my post ....
Answer:  $query=Contact::query();
 $query  =  $query->whereHas('Account', function ($q)  {
       $q->orwhere('account_name',test');
       $q->orwhere('account_city','test2');
 });
 $query->get;

I think it will do the trick.
Comment: I know this but I create dynamic query and maybe I have `like` or '>' ,....
Comment: these can also be done.Go through Laravel Docs .These are very helpful
Answer: try this:
$query=Contact::query();
$query->whereHas('Account', function ($q) {
    $q->where(function($query) {
       $query->where('account_city','test2')->orWhere('account_name','test');
    });
});
$query->get();


How to strip unused parameters from the url?

Question: I'm using Zend Framework and the URL View Helper to create URLs
I have some lines like this in my navigation:
$this->url(array('controller' => 'index', 'action' => 'index'))
$this->url(array('controller' => 'who', 'action' => 'view', 'id' => $row->who_id));
$this->url(array('controller' => 'projects', 'action' => 'view', 'id' => $row->mai_id));
$this->url(array('controller' => 'content', 'action' => 'view', 'type' => 'theater', 'id' => $row->the_id));
$this->url(array('controller' => 'shows', 'action' => 'view'));

This way, at first, I have some URL like this
http://ccgss.local/information/location
http://ccgss.local/who/view/id/1

But when I access another link with more parameters like http://ccgss.local/content/view/id/1/type/theater
it messes up with the parameters that still were there: http://ccgss.local/who/view/id/1/type/theater
I mean, the parameters don't clean up when I access another page.
How do I fix this?
Answer: You need to reset parameters when calling url helper.

$this->url(array('controller' => 'index', 'action' => 'index'), null, true);

The second argument is the name of the route to use. Keep it null if you want to use the current route.
The third argument tells whether or not to reset parameters. It's false by default.
So, just set it to true to get rid of existing parameters.


How to use Views and Rules to activate a new node flag for existing OG members?

Question: We have a flag for nodes called subscribe_og.
From this point in time users will click that flag to join, or leave, a group.
If you are not a member of the group, the flag says 'Join'. If you are a member the flag says 'leave'.
Old members of a group currently see 'leave' as they have not clicked the flag.
Is it possible to use Views and Rules to generate a list of group members, check if they have have activated the node flag, and if not, activate the node flag for them?
I had a little look at Rules Components and came up with this, which seems to do nothing.
    { "rules_gerw" : {
    "LABEL" : "gerw",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "og" ],
    "IF" : [
      { "NOT flag_flagged_node" : {
          "flag" : "subscribe_og",
          "node" : [ "site:og-context--node" ],
          "flagging_user" : [ "site:current-user" ]
        }
      },
      { "AND" : [
          { "og_user_in_group" : {
              "account" : [ "site:current-user" ],
              "group" : [ "site:og-context--node" ],
              "states" : { "value" : { "1" : "1" } }
            }
          }
        ]
      }
    ],
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "subscribe_og",
          "node" : [ "site:og-context--node" ],
          "flagging_user" : [ "site:current-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

Answer: Step 1: Fix your rules Component
The "... seems to do nothing ..."-part of your question, is like a variation of "it doesn't work" ... which is extremely hard to debug without access to your site.
However, what I find bizarre about your Rules Component is:

You're using token site:og-context--node, but there is nothing in your rule that assigns a value to it. So wild guess: it's value is blank or something like that. If my guess is correct, then your rule "works as implemented, ie "it is doing nothing", because not both Rules Conditions are satisfied.
It is related to user = site:current-user. So you've to be a bit lucky to have this Rules Condition satisfied (it depends if the current user is yes or no member of some group which might be blank).

What I think is needed, at a minimum, is that you use appropriate parameters for this Rules Component, actually for all of your tokens you're using that start with site:.
To do so, have a look at this improved version of your Rules Component. The main difference with yours is that I introduced 2 parameters, and replaced all site:
{ "rules_using_parameters" : {
    "LABEL" : "A Rules component using parameters",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "og" ],
    "USES VARIABLES" : {
      "flagging_user" : { "label" : "Flagging user", "type" : "user" },
      "node_to_flag" : { "label" : "Node to be flagged", "type" : "node" }
    },
    "IF" : [
      { "NOT flag_flagged_node" : {
          "flag" : "subscribe_og",
          "node" : [ "node-to-flag" ],
          "flagging_user" : [ "flagging-user" ]
        }
      },
      { "AND" : [
          { "og_user_in_group" : {
              "account" : [ "flagging-user" ],
              "group" : [ "node-to-flag" ],
              "states" : { "value" : { "1" : "1" } }
            }
          }
        ]
      }
    ],
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "subscribe_og",
          "node" : [ "node-to-flag" ],
          "flagging_user" : [ "flagging-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

You should be able to just copy the exported rule above, and simply import this Rules Component in your own environment.
After you did this, navigate to admin/config/workflow/rules/components in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some Node to be flagged. Use a similar technique to specify the Flagging and hit the Execute mode.
If both Rules Conditions are satisfied, then the node you selected will be marked as flagged by the user you specified.
So please do some QA-testing of this variation of your rule. And make sure to select accurate testcase (different from your own userid, aka site:current-user).
And if this QA-testing results in "... it still does nothing ...", then perform appropriate Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".
Move on to Step 2 after your QA-testing is completed (and you're sure the rule works as designed).
Step 2: Let VBO do the bulk of the work
This step is pretty easy ... Just create an appropriate view of all your nodes to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: Execute the Rules Component from Step 1.
If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.
Attention: to process many nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...
Happy VBO-ing while Rules-ing!
Comment: Yay, we are up and running.

In the View, I set the Bulk Operation to Enqueue the operation instead of executing it directly, then we run it in Cron and it works.

Right now, I set all the nodes to be checked then I manually type in a User ID. Is there a way for the Rule to use a list of users instead of a single user?
Comment: @studiocomms sorry your prior comment slipped my mind. Do you mean that using what I suggested here does work for you now, though you had to adapt VBO settting with that enqueue? Also, I don't really understand the "Right now, ... single user?" part of your last comment. Can you try again? Or maybe this is like a followup-question or so that you may want to post as a new question (which gives us more "room" to phrase the question, and possible answers)?


Add the positive multiples of 2 that are less than or equal to 300.

Question: When I did this problem, I got $$\sum_{n=1}^{150}2n=22650$$
However, the correct answer that the professor stated was 45300 which is $$45300=22650\cdot2$$
Comment: There are $150$ numbers in the list, and the average of them is $151$. So the sum is $150\times151$.
Comment: Wolfram Alpha can be a good sanity check for these things. It's [surprisingly good](https://www.wolframalpha.com/input/?i=2+%2B+4+%2B+6+%2B+...+%2B+300) at interpreting less than rigorous inputs too.
Comment: @Mutternibic Yes, the sum of the numbers in the set $\{2,4,6,\ldots,300\}$ is $150\times151=22650$.
Comment: @LordSharktheUnknown Isn't that still 22650?
Answer: The professors answer was incorrect, and it seems like the the correct answer is:$\sum_{n=1}^{150}2n=22650$


Amazon S3 Getting 501 Error on PUT

Question: In testing a new app one tester always has his uploads to S3 fail.  We're sending a PUT request of a ~1.2mb file to S3 and setting it's ACL perms.  For him, he always gets a 501 - Not Implemented error.
Here are his headers on the request:
"Accept-Encoding" = gzip;
Authorization = "AWS ###:###";
"Content-Encoding" = gzip;
"Content-Length" = 1420267;
"Content-Type" = "application/octet-stream";
Date = "Thu, 6 Oct 2011 02:59:47 +0000";
"User-Agent" = "MyApp 1.0 (iPhone; iPhone OS 4.3.1; en_US)";
"x-amz-acl" = "public-read-write";

Here are the response headers:
Connection = close;
"Content-Length" = 321;
"Content-Type" = "application/xml";
Date = "Thu, 06 Oct 2011 03:00:14 GMT";
Server = AmazonS3;

Any thoughts are welcome!
Response comes back with status code 501 and string - "A header you provided implies functionality that is not
implemented"
Comment: Is there a response? What is it?
Comment: Edited post to include response status code and string
Comment: I hope your question gets answered.  The same thing is happening to me.  https://github.com/LearnBoost/knox/issues/43
Answer: 501 response code from Amazon may be sent if no Content-Length is supplied.
Since you are saying that you do, I suggest running the request through a proxy ( Charles for Mac or Fiddler for Windows) and making sure that the request that's being sent actually includes the Content-Length header
Comment: I know this was like, almost 10 years ago, but thanks for commenting this. I'm very new to S3, and that's what my company's CRM uses for hosting, and the API docs for that CRM don't specify including Content-Length, and seeing this finally got it working.
Answer: The response body contains XML that lists the header it's not happy with, like this:
<?xml version="1.0" encoding="UTF-8"?>
<Error>
NotImplemented
<Message>A header you provided implies functionality that is not implemented</Message>
If-Modified-Since
</Error>

I set the cache policy on my NSURLRequest to NSURLRequestReloadIgnoringCacheData and it stopped adding the unwanted If-Modified-Since header:
    mutableURLRequest = [[NSMutableURLRequest alloc] initWithURL:theURL];
    [mutableURLRequest setCachePolicy:NSURLRequestReloadIgnoringCacheData];

Answer: as @Alon Burg has pointed out that S3 expects the Content-Length header to be set. You cant directly use streams (or I didnt figure out how); Fetch (or node-fetch) when passing in a ReadStream as the body, it sets the transport-encoding header to chunked which S3 does not support (when using putObject).
The fix is to first convert the ReadStream to a Buffer (or string) and pass that as a body which allows fetch to calculate the Content-Length behind the door
Answer: Some update on this topic, as I was searching for answers myself. This seems to be a rather general error message, with more than one possible reason.
For javascript api, there was a bug fix for empty body on 24 Dec 2012:

RestXMLClient include Content-Length header for empty bodies https://github.com/aws/aws-sdk-js/issues/15

Recently on IOS 8, there are problems with aggressive (and non-standard) caching, which Amazon does not like. If there was any GetObject before, If-Modified-Since header is sent for subsequent requests for same object/url, even for PUT requests:

aws-sdk-ios: https://github.com/aws/aws-sdk-ios/issues/40 AWSS3PutObjectRequest Failed on iOS8 Beta 5 with Not Implemented error.
aws-sdk-js: https://github.com/aws/aws-sdk-js/issues/376 PutObject on IOS 8
Comment: As @Alon Burg mentioned, AWS is trying and failing to tell you that you're missing the `Content-Length`
Comment: I only found about "content-length" when Googling for error - as I see, Javascript API takes care of length.
I was interested in "PutObject on IOS 8" (aws-sdk-js) issue, where I see no mention that content-length is the problem, but caching.
I was probably unclear with this post.
Answer: I had this problem in Perl with CPAN's Net::Amazon::S3::Client. I examined the request and response and I pieced together the problem, which was that I lacked the ability to request via HTTPS. I fixed it by installing LWP::Protocol::https.
Answer: I too faced this problem , while implementing putObject in node js code , and found that i didn't stringfy the JSON body , which resulted in the same error.

Amazon S3 Getting 501 Error on PUT


Cypress - How to verify data from a PDF file using cypress command

Question: Below is my code in cypress. How to print 'pdf' content and verify content using cypress .contains or .eq? when I run the code it prints object{6} but I want to print my pdf file content. I would really appreciate the help.
**Plugins/index.js:**

const fs = require('fs')
const pdf = require('pdf-parse')
const path = require('path')

const repoRoot = path.join("C:/Users/XXXXX/Downloads/loginCy-excel")

const parsePdf = async (pdfName) => {
  const pdfPathname = path.join(repoRoot, pdfName)
  let dataBuffer = fs.readFileSync(pdfPathname);
  return await pdf(dataBuffer)
}

module.exports = (on, config) => {
on('task', {
        getPdfContent (pdfName) {
          return parsePdf(pdfName)
        },
      })

}

**cypress spec file has these code:**

it('tests a pdf', () => {
    cy.task('getPdfContent', 'sample.pdf').then(content => {
        cy.log(content)
})
  })

Answer: Anyone struggling with testing PDF files with cypress can refer to these two very good blog posts precisely on this topic:

https://filiphric.com/testing-pdf-file-with-cypress
https://glebbahmutov.com/blog/cypress-pdf/

It wasn't asked in this question, but here is a little addition from me on how to download files (was tested on PDFs) from a URL:
cy.request({
        url: '<file url>',
        gzip: false,
        encoding: 'base64',
    }).then((response) => {
        cy.writeFile(
            Cypress.config('downloadsFolder') + '/<name of the file>.pdf',
            response.body,
            { encoding: 'base64' }
        );

Answer: pdf method will return an object, so I guess cy.log() can't print it like that. If you want to see what the function gathered in your pdf file, you can stringify the result:
cy
  .log(JSON.stringify(content));

If you want to get only text from your pdf, you need to work with text property:
cy
  .log(content.text);

Comment: Thanks for the reply @pavelsaman How can I add assertion to verify particular text present in the pdf ? I can't do this:cy.log(content.text).should('have.text', 'Hello') How can I add assertion?
Comment: Read the documentation first https://docs.cypress.io/guides/references/assertions
Comment: From the Cypress document you shared I got these assertion. Any thoughts?
           cy.wrap(content.text).should('have.string', 'Hello World!')
           expect(content.text).to.have.string('Hello world!')
Comment: Do they work as expected? Do they correctly report "no match"?


$_POST empty in custom callback

Question: I'm trying to write a custom listener for PayPal Instant Payment Notifications. I've defined a page callback in hook_menu as
$items['paypal-listener'] = array(
    'title' => 'PayPal IPN Listener',
    'description' => 'Simple test for receiving PayPal notifications',
    'page callback' => 'ipn_test',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);

and my custom callback is
function ipn_test() {
    var_dump($_POST);
    watchdog('paypal_ipn', print_r($_POST, TRUE));
}

but it's always empty. When testing with postman the response is always
array(0) {}

Is there something I'm missing? Something that empties out the $_POST array?
The $_POST from PayPal is Content-Type: application/x-www-form-urlencoded in case that matters.
I have already checked this question, this question and this one but none seem to have the answer to why the data is gone.
This doesn't work either
$data = file_get_contents("php://input");
$data = json_decode($data, TRUE);

Update:
OK, it seems as if the chrome app postman can't send POST varibale to a local server properly. I created a simple php script with just var_dump($_POST) and while it works fine on an online server, it is empty on my local server.
Answer: There must have been some kind of bug or I set it up wrong because the next day it started working fine.

$_POST empty in custom callback


PHP - UNSET values in array not containing prefix

Question: I have an array like:
$array  = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');

I want to UNSET the values in the array that are not prefixed with OPTM.
How should that be done?
PHP 5.5
Comment: unset or remove? Do you want to preserve in index positions (e.g. OPTM3002 stays at index 2 or does it become 1)?
Comment: Does this answer your question? [Unset array Items matching a pattern](https://stackoverflow.com/questions/9444427/unset-array-items-matching-a-pattern)
Comment: @thchp  Not really.  I have posted an answer
Answer: // Don't need this if using PHP 8
if (!function_exists('str_starts_with')) {
    function str_starts_with($haystack, $needle) {
        return (string)$needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
    }
}

$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
for ($i = 0; $i < count($array); ++$i) {
    if (!str_starts_with($array[$i], 'OPTM'))
        unset($array[$i]);
}

// Optional to re-index array
$array = array_values($array);

Answer: You can use foreach/str_contains/unset like:
$array  = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
foreach($array as $key => $value){
    if(!str_contains($value,'OPTM')){
        unset($array[$key]);
    }
}
print_r($array);
/*
Array
(
    [0] => OPTM3000
    [2] => OPTM3002
    [5] => OPTM3004
)

*/

Reference:

foreach
str_contains
unset
Comment: PS str_contains is php8+, but this will check if the prefix is *anywhere in the string*, but OP want to check if it's a *prefix*, which means you'll have to use str_starts_with
Answer: Use this
$array  = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');

$new_array = array_filter($array, function($v,$k) {
    return strpos($v,'OPTM') !==false;
}, ARRAY_FILTER_USE_BOTH);

Comment: This unexplained answer will match any string the "contains" the needle, not only if the "starts with" the needle.  This question asks to match "prefixes".
Answer: try this
$array  = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');

$newArray = array();

foreach($array as $value) {
  if ( 'OPTM' == substr($value, 0, 4) ) {
     $newArray[] = $value;
  }
}

Answer: Use Unset or if you don like to use unset function one possible way will be to work with array_map and array_filter:
$array  = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$arr = array_map(function($item) {
    if ( str_contains($item,'OPTM')) {
      return $item;
    }
}, $array);

$arr = array_filter($arr);
print_r($arr);

Comment: This unexplained answer will match any string the "contains" the needle, not only if the "starts with" the needle.  This question asks to match "prefixes".
Answer: A short approach to reach the same value
$array  = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');

$filtred = array_filter($array, function($item){
    return  (strncmp($item, 'OPTM', 4)==0);
});

var_dump($filtred);

to make your code more dynamic and optimal you can do like this
$array  = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');

$prefix = 'OPTM';
$array = array_filter($array, function($item) use($prefix){
    return  (strncmp($item, $prefix, strlen($prefix))==0);
});

var_dump($array);

Answer: You can iterate the elements in your array using a regex like:
foreach($array as $element){
    $pattern = "OPTM/";
    if(echo preg_match($pattern, $element) == 0){
        $key = array_search($element, $array);
        unset($array[$key]);
    }
}

Comment: This is not efficient code. The `foreach()` will deliver the key if you declare it.
Answer: OK, this works for me.
$array  = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');

$allowed_prefix = 'OPTM';

foreach ( $array as $key => $text )
{
    if (strpos($text, $allowed_prefix) !== 0) {
        unset($array[$key]);
    }
}


how can you retrieve source code in python, inspect gives type error

Question: In order to get better at programming, analysing numpy and scipy's source code could come in handy.
import inspect,numpy as np

x = [1,2]
inspect.getsource(np.max(x))

gives TypeError

please help,kind regards
Comment: Your error message tells you `TypeError: module, class, method, function, traceback, frame, or code object was expected, got int64`.
Answer: For numpy and scipy code, check the official documentation.
https://numpy.org/doc/stable/reference/generated/numpy.amax.html
Often these have a [source] link. Or it running ipython, just using np.max?? gives the same thing.
In this case, most of the display is the docs, and the actual code is short:
def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
         where=np._NoValue):
    return _wrapreduction(a, np.maximum, 'max', axis, None, out,
                          keepdims=keepdims, initial=initial, where=where)
File:      /usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py

This tells us that np.max (or amax) delegates the action to a similarly name max method.  And if we dig further we see that the method is built-in, that is, it is compiled code that we cannot readily read.  This is a rather common situation in numpy.  Functions delegate to similarly named methods. Unless you are prepared to do some serious reading of c code, this is as far as you'll get.  And as far as you need to go, unless you want to be numpy developer/contributor.
Answer: np.max(x) is an integer, 2.  An integer has no source code.
Try simply
inspect.getsource (np.max)

Answer: From the python documentation

inspect.getsource(object)

Return the text of the source code for an object. The argument may be a module, >class, method, function, traceback, frame, or code object. The source code is >returned as a single string. An OSError is raised if the source code cannot be >retrieved.

It appears in your example that you are calling the function.
Try just inspect.getsource(np.max)


Buildbot Docker BUILDBOT_CONFIG_URL how to setup with SSH keys?

Question: In the Buildbot Docker tutorial documentation it says:
"You will need to change docker-compose.yml the variable BUILDBOT_CONFIG_URL in order to point to your github fork"
But how would I do this if the URL points to a private repository accessible via SSH keys?
I can't seem to find an environment variable to specify the BUILDBOT_CONFIG_URL credentials.
An example would be very much appreciated.
Answer: You need to mount ssh to get access under docker container.
Try to add next few lines into your docker-compose.yml
<code>volumes:
  - ~/.ssh:/root/.ssh:ro
</code>


Vmware View & PCoIP Host Card

Question: Does anyone know what the performance will be with or without a host card on a laptop running a vmware view client to a server which is 50-100m away on LAN Gigabit.
The specs say that it can handle 60fps @ 1080p but is this true with a soft client like vmware view? I would like to use it for CAD/CAM software on a remote server via laptop but have no idea what the performance will be like.
Comment: Clarify, you have a gigabit point to point circuit? You have a Gigabit LAN hooked to an Internet connection? What's the latency?
Comment: @SpacemanSpiff I have A to B Gigabit LAN in our test LAB. Latency is <1ms
Comment: This seems relevant: http://www.unidesk.com/blog/adjusting-vmware-view-pcoip-video-intense-applications I think you will just need to test this to get an acceptable answer though, and bandwidth will be more of a problem than video performance.
Comment: @SpacemanSpiff Yes however thin client with host card is limited to 20mbps. So i don't know if this limit can be lifted..
Comment: @SpacemanSpiff By the way the link you posted is thin client without hostcard. Thats why the crappy performance.
Comment: Well, just based on the numbers... 20Mbps should be enough to stream 1080p video twice over... it should be alright. I certainly would lab this though.
Answer: PCoIP at that bitrate will handle CAD/CAM fine - your issue will be the virtual GPU's ability to render the display in the first place.
Comment: It will be from a Quadro6000 via host card. No virtual GPU.

Vmware View & PCoIP Host Card


question on a notation in Big Rudin

Question: I am wondering why Rudin used the following notation in his "Real and Complex Analysis". It is in Definition 8.7, as following.
If $(X, \mathscr{S}, \mu)$ and $(Y, \mathscr{T}, \lambda)$ are two $\sigma$-finite measure spaces, and $Q\in \mathscr{S}\times \mathscr{T}$, then define $(\mu\times \lambda)(Q)=\int_{X}{\lambda(Q_x) d\mu(x)}=\int_{Y}{\mu(Q^y) d\lambda(y)}$.
My question is why $\mu$ and $\lambda$ depend on $x$ and $y$ respectively? Aren't they fixed once the measure spaces $(X, \mathscr{S}, \mu)$ and $(Y, \mathscr{T}, \lambda)$ are given? What is the meaning of $\mu(x)$ and $\lambda(y)$ or the author wants to emphasize here?
Thanks.
Comment: My understanding is it's by analogy with $dx$ for ordinary integration with respect to the Lebesgue measure. It describes the infinitesimal size of a small measurable set containing $x$.
Comment: @Qiaochu: thanks. I thought initially there were some measures generated/induced by $x$ and $y$ by looking at the notation! But on the other hand, if you say $d\mu(x)$ is analogous to $dx$ as in the Riemannian case, isn't this in disagreement with the definition of Lebesgue's integral?
Comment: By the way: this question reproduces http://math.stackexchange.com/q/5230/6179 (and note that Arturo's assertion in the comments on the main question is later on withdrawn in the comments on Byron's answer).
Answer: There is no meaning to $\mu(x)$ (and Rudin does not use this notation). On the other hand the integral of a function $f$ with respect to a measure $\mu$ is denoted in a variety of ways, and amongst these,
$$
\int f \mathrm{d}\mu=\mu(f)=\int f(x) \mathrm{d}\mu(x)=\int f(x) \mu(\mathrm{d}x).
$$
Comment: thanks. Fair enough! Just thought $\mu(x)$ implies some function dependence as I am used to understand. This notation is confusing to me.
Comment: Once again: you will not find $\mu(x)$ anywhere. What some people use is $\mathrm{d}\mu(x)$.

question on a notation in Big Rudin


Google Places Api is picking up wrong address or wrong location

Question: I have just started to use google places api. When I put in the address of 2669 Davis Blvd, Naples Fl, its shows me the correct address on the drop down but when I pickup the address its populating 2669 Naples Cir, SomeOtherCityInFlorida, Florida
I used to be using google's geocode. However I have noticed that in the last 2-3 days, its not recognizing certain street names but recognizes the Route numbers: Example 2669 Davis Blvd, Naples Florida wouldnt be recognized but 2669 Route 84 Naples OR 2669 Hwy 84, Naples would pickup the location correction
Has anyone else faced this problem in the last few days (May 13th 2013)
Comment: I'm having the same problem. Just submitted a bug to the Places API issue tracker, here: https://code.google.com/p/gmaps-api-issues/issues/detail?id=6666&thanks=6666&ts=1399400982
Answer: Finding the same thing here.  A lot of previously correct addresses are now not Geo-coding.
Had mixed results using different devices / apps.  Seems to work sometimes but not others.  The auto complete seems to still be working as it should but any details requests on certain places will fail.


Spark Streaming using Tweepy

Question: I'm trying to stream twitter data using python library Tweepy. I have setup working environment googled about the stuff but i'm not getting how things are working. I want to use spark streaming (DStream - Batch processing) with python (tweepy). I have go through at least following links:

How to get tweets of a particular hashtag in a location in a tweepy?
http://spark.apache.org/docs/latest/streaming-programming-guide.html
http://docs.tweepy.org/en/v3.5.0/streaming_how_to.html
Retrieving Twitter data using Tweepy
http://www.awesomestats.in/spark-twitter-stream

Following tweepy code is working fine for me:
<code>import tweepy

consumer_key = ''
consumer_secret = ''
access_token = ''
access_secret = ''

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)

politicsTweets = tweepy.Cursor(api.search, q='#GONAWAZGO').items(100)

for tweet in politicsTweets:
    print tweet.created_at, tweet.text, tweet.lang
</code>
but it's not using spark streaming. How should I update the aforementioned code to use Spark Streaming? I'm not getting why do I need two separate files? Overall I'm trying to do the followings:

Get top 10 hashtags from 1st May, 2017. (Tweepy search function accepts parameter 'since_id', not getting how to use it [http://docs.tweepy.org/en/latest/api.html#help-methods ]?)
Count how many times #GONAWAZGO found since 11th May, 2013.
Count how many #gonawazgo were done by people outside of Pakistan. (Without any date limit, Tweepy cursor method accepts geocode but I want tweets from locations other than the provided geocode.)
Observe the trend about France Elections on Twitter.
Find the most recent tweets done by [https://twitter.com/imrankhanpti ] twitter account. (Tweepy search method accepts userID, how I can get that?)

Above all I'm a bit confused about when to use Twitter REST/Streaming API. I think for 1st and 2nd point REST API should be used as we are processing past data till date and for remaining Streaming API should be used.
Answer: Twitter search API has a 7-day limit. That means you can not get any data older than 7 days. Here is a link to Twitter search API documentation. Have a look at the description mentioned for "until" parameter:
https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
I hope that helps!

Spark Streaming using Tweepy


Html.BeginForm erro com area

Question: Tenho uma view com o seguinte formulario:
@using (Html.BeginForm("Salva", "Blog", new { area = "admin" }, FormMethod.Post, false, new { id = "formCadastro" }))

Porem ao clicar no submit a url que aparece é a seguinte

http://localhost:1378/Blog/Salva?area=admin

Mas preciso que ela apareça assim:

http://localhost:1378/Admin/Blog/Salva

Meu mapeamento está da seguinte maneira:
app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            endpoints.MapAreaControllerRoute(
                name:"Admin",
                areaName: "Admin",
                pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
        });

Porem ja usei tambem:
app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapControllerRoute("Admin", "{controller=Home}/{action=Index}/{id?}");
        });

Comment: Eu recomendaria você a parar de usar esse tipo de sintaxe nessa versão do mvc e mudar para o novo modelo de marcação do Razor. Dê uma olhada nesse tutorial
https://docs.microsoft.com/pt-br/aspnet/core/tutorials/razor-pages/?view=aspnetcore-2.2
Answer: Ao usar Asp.net Core evite usar as TagHelpers do framework. Em vez disso utilize a nova sintaxe do Razor, que deixa o código mais claro e está mais estável.
Ex:
<form asp-controller="blog" asp-action="salva" asp-area="admin" method="post" id = "formCadastro">

</form>

Esse artigo explica em detalhes como usar a nova sintaxe.
https://docs.microsoft.com/pt-br/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-3.1#the-form-tag-helper
Comment: Eu cheguei a usar dessa maneira também, e não deu certo. acredito que seja algo relacionado ao roteamento da área.
Comment: Se o front-end está chamando a url errada acho pouco provável ser a configuração das rotas. Mas se você acha mesmo que é configuração das rotas, experimente adicionar esse atributo no seu contrller: `[Area("Admin")]`
Comment: Coloquei isso e ainda não funcionou
Comment: Qual versão do Asp.net Core você está usando?
Comment: se não me engano é o 3.0

Html.BeginForm erro com area


Centrar imagem de background

Question: Estou a tentar meter como imagem de background uma imagem que quero que fique exactamente centrada verticalmente e horizontalmente (a imagem é uma bola). Portanto o objectivo é ficar horizontalmente match_parent e verticalmente wrap_content para que fique bemno centro do ecrã.
Não estou a conseguir este efeito porque tambem estou a usar a Toolbar e ao conseguir colocar a imagem bem a Toolbar vem também para o centro.
Alguém me pode ajudar por favor?
Código:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" android:layout_gravity="center"
    android:orientation="vertical"
    android:background="@drawable/ball"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:minHeight="?attr/actionBarSize"
        android:background="@color/grey0">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textColor="@color/white"
            android:textSize="26sp"
            android:textStyle="bold"
            android:gravity="center"
            android:id="@+id/toolbar_title"/>

    </android.support.v7.widget.Toolbar>

    <LinearLayout

        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:gravity="center"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"> (...) </LinearLayout> </LinearLayout>

Comment: Experimente tirar o atributo `android:layout_gravity` do *Toolbar*.
Comment: @ramaral, fica igual :\
Comment: Olá, de uma olhada no item 2) desta resposta e veja se te ajuda! O conceito é o mesmo http://pt.stackoverflow.com/questions/59276/imagem-de-background-distorcida-no-android-studio/59336#59336
Comment: @sicachester mas ao utilizar o ImageView como é que colocas a imagem como background?
Answer: Minha sugestão é organizar suas View's em "camadas", tendo um ImageView ao fundo, com o Drawable que tem a imagem que quer centralizar. Fazendo isso você pode centralizar uma certa "camada" sem interferir no alinhamento das demais View's.
Usando o FrameLayout ficaria:
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/ball" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/toolbar"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:minHeight="?attr/actionBarSize"
            android:background="@color/grey0">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="@color/white"
                android:textSize="26sp"
                android:textStyle="bold"
                android:gravity="center"
                android:id="@+id/toolbar_title"/>

        </android.support.v7.widget.Toolbar>

        <LinearLayout
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

        </LinearLayout>
    </LinearLayout>
</FrameLayout>

Para entender melhor o FrameLayout, recomendo uma visita a essa pergunta: Como deixar imageView atras dos botoes?.
Comment: Muito Obrigada!

Centrar imagem de background


Compute the dimension of a 5x5 matrix

Question: The matrix is given like this: all A(ii) entry= 1/2 while A(ij) entry= -A(ji) entry.
(In other words, all the diagonal entries of this 5x5 matrix is 1/2 and all the off-diagonals is A(ij) entry=-A(ji) entry
How to compute the dimension of this matrix? Appreciate your help!
thx!
Comment: What do you mean by "dimension"? Is it the rank, perhaps?
Comment: Sorry is dimension typo
Comment: @egreg ya is equivalent to rank!
Answer: Suppose $Av=0$, for some vector $v$. If we show that $v=0$, then we know that $A$ has rank $5$.
Set $B=A-\frac{1}{2}I_5$ and observe that $B^T=-B$. Then, from $Av=0$, we get
$$
Bv=-\frac{1}{2}v.
$$
Multiply both sides by $v^T$:
$$
v^TBv=-\frac{1}{2}v^Tv.\tag{*}
$$
Transpose both sides:
$$
v^TB^Tv=-\frac{1}{2}v^Tv.
$$
Since $B^T=-B$, we get
$$
-v^TBv=-\frac{1}{2}v^Tv.\tag{**}
$$
Putting together (*) and (**), we get $v^TBv=-v^TBv$, which implies $v^TB^Tv=0$. Therefore
$$
\frac{1}{2}v^Tv=0
$$
which implies $v=0$.
Comment: @user3437854 Certainly wrong: the transpose of $AB$ is $B^TA^T$, so the transpose of $v^Tv$ is $v^T(v^T)^T=v^Tv$: it's a $1\times 1$ matrix, by the way, so it *must* equal its transpose.
Comment: @user3437854 You're right
Comment: Actually I have no idea of your explanation.I am learning Linear Algebra I , so any easier method to explain? would appreciate that!
Comment: @user3437854 I added the full solution, please look at it carefully. It's basically the proof that an antisymmetric matrix has purely imaginary eigenvalues.
Comment: erm, can you tell me what is the dimension you found?
Comment: @user3437854 It's written at the beginning! The null space of $A$ is $\{0\}$, so by the rank-nullity theorem the rank is $5$.
Comment: how do you get Bv=0.5v
Comment: and when you take the transpose, shouldnt the RHS be 0.5vv^T?
Comment: counting from last line, the third line should be v^TB^Tv=-v^TBv?
Comment: @user3437854 Yes, I forgot to remove the T
Comment: how about my other comments?true?
Comment: why isnt Bv= -0.5v the negative sign
Comment: thanks so much! I understand alrdy.Can vote for me ?xd

Compute the dimension of a 5x5 matrix


XMLHttpRequest cannot load and Sencha touch

Question: everybody! I have a problem. When i use Ạjax or getStore, i see a error in console Chrome.
XMLHttpRequest cannot load . Origin is not allowed by Access-Control-Allow-Origin.
And, My response result is failed. I don't know this problem relate to this result. Help me, If you have a sulutions. :) Thanks.
When I use Ạjax or getStore, I see an error in Chrome's console.
XMLHttpRequest cannot load. Origin is not allowed by Access-Control-Allow-Origin.
And my response result is failed. I don't know this problem relates to the result.
Comment: Are you running this from a local webserver like xampp or mamp? If not, you should try running using a webserver.
Comment: Posting ajax code and screen short of you browser helps more for us to answer your question exactly.
Comment: I'm using Xampp.So,How resolve it? thanks!
Answer: You cannot call any webservice from your browser because of security reasons so either you have to use JSONP proxy on app side or you have to enable CORS on your server side. If you are planning to build this as app then you don't have to do this, all you have to do is change security setting of your browser when you are testing. More details here : How to use json proxy to access remote services during development
Answer: This problem appears when i code like here:
Ext.Ajax.request({
url: 'http://api....api.php/national',
useDefaultXhrHeader: false,
success : function(response, opt) {
Ext.Msg.alert('Success', response.responseText);
},
failure : function(response, opt) {
Ext.Msg.alert('Failed', response.responseText);
}
});

Or:
var onlineStore = Ext.getStore('NationStore');
 onlineStore.load();

This is screen shot about error! Thanks!
Answer: This appears to be cross domain Ajax call. Browser won't allow it by default. http://en.wikipedia.org/wiki/Same_origin_policy
You need to implement CORS http://en.wikipedia.org/wiki/Cross-origin_resource_sharing


How to resolve keyerror in pandas using python?

Question: I have three CSV files. The first (csv1) can be considered a positive dataset where the first column (column 1) consists of certain IDs. The same goes second column as well. The data in csv1 are paired data meaning the corresponding entries in the CSV cells are pairs. Ex:
colA    colB
 A.1     B.1
 C.1     D.1

Here, A.1 and B.1 can be considered a pair, and the same goes for C.1 and D.1. In the second file (csv2), it only consists of the data of entries of Column A of file 1. Ex:
Col   X1    X2    X3    X4
A.1  0.1   0.2   0.3   0.4
C.1  0.2   0.3   0.4   0.5

And similarly, the third file (csv3) consists of the data of entries of Column B of file 1. Ex:
Col   X1    X2    X3    X4
B.1  0.1   0.2   0.3   0.4
D.1  0.2   0.3   0.4   0.5

I am writing a code where I first import all the three files and then iterate through the length of column A of file 1 and assign the values of the first cell of Column A and Column B to x and y respectively. I want to write a code where after assigning the respective values to x and y I will search whether these values are in file2 (x value) and file 3 (y value). If it is there then I want to extract the corresponding rows and concatenate them and save them in a separate CSV.
So, if my "x" is assigned a value of A.1 (hereby assigning I am assigning the string A.1) and "y" is assigned a value of B.1, then I want my code to first search if A.1 is there in file2 and B.1 is there in file3. If it is there, I want to extract the corresponding row values for A.1 (0,1,0.2,0.3,0.4...) and B.1 (0.2,0.3,0.4,0.5...) and concatenate their values:
  col     x1    x2    x3    x4   x5   x6
A.1_B.1   0.1   0.2   0.3   0.4  0.2  0.3

This is what I have written, but I am facing a "Keyerror". Whereas, when I checked my CSV file the ID is there. Any help would be much appreciated.
file1 = pd.read_csv("/home/file1.csv")
file2 = pd.read_csv("/home/file2.csv")
file3 = pd.read_csv("/home/file3.csv")

for i in range(len(file1['ID'])):
    x = ID_A[i]
    y = ID_B[i]
    if x in CT_ID_A:
        if y in CT_ID_B:
            d1 = file2.loc[x]
            d2 = file3.loc[y]
            d3 = pd.concat([d1,d2],axis=1)

here, ID_A and ID_B consist of the corresponding IDs of columns of file1, and CT_ID_A and CT_IS_B consist of IDs of file2 and file3, that is:
ID_A = ['A.1','C.1']
ID_B = ['B.1','D.1']
CT_ID_A = ['A.1','C.1']
CT_ID_B = ['B.1','C.1']

Answer: If your key error is ID then there is a possibility that yoyr csv file header does not have any column with the name ID
Comment: This answer is right. Also you are using ID_A, ID_B, CT_ID_A and CT_ID_B when you haven't declared them.


Robotics: Homogenous Transformation Matrix for DH parameters

Question: I'm studying Introduction to robotic and found there is different  equations to determine the position and orientation for the end effector of a robot using DH parameters transformation matrix, they are :
1.
Translate by  d_i along the  z_i-axis.
Rotate counterclockwise by theta_i about the  z_i-axis.
Translate by  a_{i-1} along the  x_{i-1}-axis.
Rotate counterclockwise by  alpha_{i-1} about the  x_{i-1}-axis.

2.
Rotate by theta_i about the Z_i-axis.
Translate by d_i along the z_i-axis.
Translate by a_(i-1) along the x(i-1)-axis.
Rotate by alpha_(i-1)along the x(i-1)-axis.

3.
Rotate by alpha_(i-1)along the x(i-1)-axis.
Translate by a_(i-1)along the x(i-1)-axis.
Rotate by theta_i about the Z_i-axis.
Translate by d_i about the Z_i-axis.

What is the difference between them? Will the result be different?
Which one should I use when calculating the position and orientation?
Comment: Perhaps this would be better asked at robotics.stackexchange.com, there seems to be no programming question here.
Answer: As far as I know there is no difference. They should all give you the same end result, but be consistent. pick one form and stick with it.
The main problem comes when you are trying to reverse the process. Using method 1 to got from time t to t+1 is fine, but if you wanted to go from t+1 to t you would need to use method 1. Using another method to do the transform (though it should technically work) usually doesn't because nonlinearities in modeling and rounding errors for rotation (cos and sin terms).
This isn't really surprising though, it's the same issue you encounter when going from a local reference(with respect to a robot) to a global reference. The order of translations and rotations must be maintained for forward and backword transformations