问:
Getting undeclared args when trying to bind std::function using parameter pack
I'm trying to create a variadic template class that looks like this :

```<code>template <class... Args>
class Message
{
    private:

        std::function<void(Args...)> _function;
    public:
    //stuff

};
</code>```

I want to have an option to bind so the user can bind any function (with corresponding arguments) when he wants. I've tried this approach (this function is a part of the Message class, so Args... comes from the template argument of the class):

```<code>    template<class T>
    void Message::bindFunction(void(T::*function)(Args... args), T* ownerPtr)
    {
        //This doesn't work
        _function = boost::bind(function,args, ownerPtr);
    }
</code>```

However the above doesn't work, I've tried to create the tuple from the args in the bind function, but the compiler keeps saying:

```<code><args_0> undeclared identifier.
</code>```

(If I pass more arguments it changes)

From the user's point of view it should look like this:

```<code>class Foo
{
public:

    void test2(int a, float b, double c)
    {
        std::cout << "bla";
    }
};

int main()
{
    Foo f;

    Message<int,float,double> Mess;

    Mess.bindFunction(&Foo::test2, &f);
}
</code>```

I've seen a lot of articles talking about forwarding the parameters, however most of the answers confuse me more than I am already with different template structures without explaining them.

答:
Use a lambda because they're much nicer (Live Demo (C++11)):

```<code>template<class T>
void bindFunction(void(T::*function)(Args...), T* ownerPtr)
{
    _function = [function, ownerPtr](Args... args)
    {
        (ownerPtr->*function)(args...);
    };
}
</code>```

We are capturing the function pointer and pointer to instance of the class with [function, ownerPtr] in the lambda declaration.

The lambda accepts a list of arguments whose types are specified in the variadic template for the Message class: Args... args.

Internally we call the function using our instance with the (ownerPtr->*function) syntax, and then pass in the arguments by expanding the parameter pack (args...)

To call the function you might write something like this:

```<code>void callFunction(Args&&... args)
{
    _function(std::forward<Args>(args)...);
}
</code>```

We use perfect forwarding to pass our arguments to the std::function<void(Args...)> member.

Body:
I'm trying to create a variadic template class that looks like this :

template <class... Args>
class Message
{
    private:

        std::function<void(Args...)> _function;
    public:
    //stuff

};

I want to have an option to bind so the user can bind any function (with corresponding arguments) when he wants. I've tried this approach (this function is a part of the Message class, so Args... comes from the template argument of the class):

    template<class T>
    void Message::bindFunction(void(T::*function)(Args... args), T* ownerPtr)
    {
        //This doesn't work
        _function = boost::bind(function,args, ownerPtr);
    }

However the above doesn't work, I've tried to create the tuple from the args in the bind function, but the compiler keeps saying:

<args_0> undeclared identifier.

(If I pass more arguments it changes)

From the user's point of view it should look like this:

class Foo
{
public:

    void test2(int a, float b, double c)
    {
        std::cout << "bla";
    }
};

int main()
{
    Foo f;

    Message<int,float,double> Mess;

    Mess.bindFunction(&Foo::test2, &f);
}

I've seen a lot of articles talking about forwarding the parameters, however most of the answers confuse me more than I am already with different template structures without explaining them.

Body:
Use a lambda because they're much nicer (Live Demo (C++11)):

template<class T>
void bindFunction(void(T::*function)(Args...), T* ownerPtr)
{
    _function = [function, ownerPtr](Args... args)
    {
        (ownerPtr->*function)(args...);
    };
}

We are capturing the function pointer and pointer to instance of the class with [function, ownerPtr] in the lambda declaration.

The lambda accepts a list of arguments whose types are specified in the variadic template for the Message class: Args... args.

Internally we call the function using our instance with the (ownerPtr->*function) syntax, and then pass in the arguments by expanding the parameter pack (args...)

To call the function you might write something like this:

void callFunction(Args&&... args)
{
    _function(std::forward<Args>(args)...);
}

We use perfect forwarding to pass our arguments to the std::function<void(Args...)> member.


来源: stackexchange

问:
Execute button's command after the animation
In my application i have added a frame-by-frame animation to my button's selector. So, when I press the button the application is started and another activity is launched. The problem is that if I press the button very quickly the application reaches only to the second frame. I would like to launch the next activity after the animation is ended. Is that possible?</p>

答:
The button should launch a new Thread instead new Activity directly, and then this new Thread will launch the activity after a few secconds using "Thread.sleep(xxxx);"</p>
```<code>btn.setOnClickListener(new OnClickListener()
{
  @Override
  public void onClick(View v)
  {
    new Thread()
    {
       public void run()
       {
          Thread.sleep(1000);
          //LAUNCH NEW ACTIVITY HERE
       }
    }.start();
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The button should launch a new Thread instead new Activity directly, and then this new Thread will launch the activity after a few secconds using "Thread.sleep(xxxx);"

btn.setOnClickListener(new OnClickListener()
{
  @Override
  public void onClick(View v)
  {
    new Thread()
    {
       public void run()
       {
          Thread.sleep(1000);
          //LAUNCH NEW ACTIVITY HERE
       }
    }.start();
  }
}


问:
Restrict a child's required attribute from a parent's derived type (XSD)
So the following is an XSD file that I need to use to validate this xml.

```<code><?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                  targetNamespace="schedule"
                  xmlns="schedule"
                  elementFormDefault="qualified">

<xsd:element name="Schedule">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element ref="Event" maxOccurs="unbounded"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

<!-- Event and eventType declaration-->
<xsd:element name="Event" type="eventType"/>
<xsd:complexType name="eventType">
    <xsd:sequence>
        <xsd:element name="Title" type="xsd:string" />
        <xsd:element name="Lecture" type="lectureType" maxOccurs="9" minOccurs="1" />
    </xsd:sequence>
</xsd:complexType>

<!-- default data that a lecture must contain -->
<xsd:group name="lectureContentGroup">
    <xsd:sequence>
        <xsd:element name="Day">
            <xsd:simpleType>
                <xsd:restriction base="xsd:string">
                    <xsd:enumeration value="Monday"/>
                    <xsd:enumeration value="Tuesday"/>
                    <xsd:enumeration value="Wednesday"/>
                    <xsd:enumeration value="Thursday"/>
                    <xsd:enumeration value="Friday"/>
                    <xsd:enumeration value="Saturday"/>
                    <xsd:enumeration value="Sunday"/>
                </xsd:restriction>
            </xsd:simpleType>
        </xsd:element>
        <xsd:element name="Time">
            <xsd:simpleType>
                <xsd:restriction base="xsd:string">
                    <xsd:pattern value="[0-9][0-9][:][0-9][0-9][\-][0-9][0-9][:][0-9][0-9]"/>
                </xsd:restriction>
            </xsd:simpleType>
        </xsd:element>
    </xsd:sequence>
</xsd:group>

<!-- base lecture type without any attributes -->
<xsd:complexType name="baseLectureType">
    <xsd:group ref="lectureContentGroup" />
</xsd:complexType>

<!-- lecture type that contains the required attribute Classroom -->
<xsd:complexType name="lectureType">
    <xsd:complexContent>
        <xsd:extension base="baseLectureType">
            <xsd:group ref="lectureContentGroup" />
            <xsd:attribute name="Classroom" use="required">
                <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                        <xsd:maxLength value="7"/>
                    </xsd:restriction>
                </xsd:simpleType>
            </xsd:attribute>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>

<!-- lecture type that contains a prohibited Classroom attribute -->
<xsd:complexType name="labLectureType">
    <xsd:complexContent>
        <xsd:extension base="baseLectureType">
            <xsd:group ref="lectureContentGroup" />
            <xsd:attribute name="Classroom" use="prohibited">
                <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                        <xsd:maxLength value="7"/>
                    </xsd:restriction>
                </xsd:simpleType>
            </xsd:attribute>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>

<!-- lessonType, seminarType and labType declaration -->
<xsd:complexType name="lessonType">
    <xsd:complexContent>
        <xsd:extension base="eventType">
            <xsd:sequence>
                <xsd:element name="Professor" type="xsd:string" />
            </xsd:sequence>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>

<xsd:complexType name="seminarType">
    <xsd:complexContent>
        <xsd:restriction base="eventType">
            <xsd:sequence>
                <xsd:element name="Title" type="xsd:string" />
                <xsd:element name="Lecture" type="lectureType" />
            </xsd:sequence>
        </xsd:restriction>
    </xsd:complexContent>
</xsd:complexType>

<xsd:complexType name="labType">
    <xsd:complexContent>
        <xsd:restriction base="eventType">
            <xsd:sequence>
                <xsd:element name="Title" type="xsd:string" />
                <xsd:element name="Lecture" type="labLectureType" maxOccurs="9" minOccurs="1" />
            </xsd:sequence>
        </xsd:restriction>
    </xsd:complexContent>
</xsd:complexType>

<!-- Lesson, Seminar, Lab -->
<xsd:element name="Lesson" type="lessonType" substitutionGroup="Event" />
<xsd:element name="Seminar" type="seminarType" substitutionGroup="Event" />
<xsd:element name="Lab" type="labType" substitutionGroup="Event" />

</xsd:schema>
</code>```

So a little explanation first. Ι have defined a Schedule element that can contain multiple Event elements (of type "eventType"). Furthermore I have defined the elements Lesson, Seminar and Lab that substitute the element Event (substitution group), so as:

Lesson must include a Professor element

Seminar must contain only one Lecture element

The lectures of Lab element should not contain the Classroom attribute (prohibited). In every other case the classroom is required.

I have been having problems with the last one. Basically to solve it I have created a base type for the lectures (baseLectureType) that contains only the elements a lecture needs, and I have derived 2 other types from this:

lectureType that contains the required Classroom attribute and

labLectureType that contains the prohibited Classroom attribute

However when I try to validate, I get the following errors:

Error - Line 109, 37: org.xml.sax.SAXParseException; lineNumber: 109; columnNumber: 37; rcase-Recurse.2: There is not a complete functional mapping between the particles.
Error - Line 109, 37: org.xml.sax.SAXParseException; lineNumber: 109; columnNumber: 37; derivation-ok-restriction.5.4.2: Error for type 'labType'.  The particle of the type is not a valid restriction of the particle of the base.

Any tips would be appreciated.

答:
XSD extension only adds; XSD restriction only takes away.

Note, however, that restriction cannot undo requiredness of mandatory elements or attributes.

In XSD 1.1, you could use assertions to gain finer control over types, but even with assertions, you couldn't prohibit (or make optional) required elements or attributes.

ContentLicense: CC BY-SA 3.0

Body:
So the following is an XSD file that I need to use to validate this xml.

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                  targetNamespace="schedule"
                  xmlns="schedule"
                  elementFormDefault="qualified">

<xsd:element name="Schedule">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element ref="Event" maxOccurs="unbounded"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

<xsd:element name="Event" type="eventType"/>
<xsd:complexType name="eventType">
    <xsd:sequence>
        <xsd:element name="Title" type="xsd:string" />
        <xsd:element name="Lecture" type="lectureType" maxOccurs="9" minOccurs="1" />
    </xsd:sequence>
</xsd:complexType>

<xsd:group name="lectureContentGroup">
    <xsd:sequence>
        <xsd:element name="Day">
            <xsd:simpleType>
                <xsd:restriction base="xsd:string">
                    <xsd:enumeration value="Monday"/>
                    <xsd:enumeration value="Tuesday"/>
                    <xsd:enumeration value="Wednesday"/>
                    <xsd:enumeration value="Thursday"/>
                    <xsd:enumeration value="Friday"/>
                    <xsd:enumeration value="Saturday"/>
                    <xsd:enumeration value="Sunday"/>
                </xsd:restriction>
            </xsd:simpleType>
        </xsd:element>
        <xsd:element name="Time">
            <xsd:simpleType>
                <xsd:restriction base="xsd:string">
                    <xsd:pattern value="[0-9][0-9][:][0-9][0-9][\-][0-9][0-9][:][0-9][0-9]"/>
                </xsd:restriction>
            </xsd:simpleType>
        </xsd:element>
    </xsd:sequence>
</xsd:group>

<xsd:complexType name="baseLectureType">
    <xsd:group ref="lectureContentGroup" />
</xsd:complexType>

<xsd:complexType name="lectureType">
    <xsd:complexContent>
        <xsd:extension base="baseLectureType">
            <xsd:group ref="lectureContentGroup" />
            <xsd:attribute name="Classroom" use="required">
                <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                        <xsd:maxLength value="7"/>
                    </xsd:restriction>
                </xsd:simpleType>
            </xsd:attribute>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>

<xsd:complexType name="labLectureType">
    <xsd:complexContent>
        <xsd:extension base="baseLectureType">
            <xsd:group ref="lectureContentGroup" />
            <xsd:attribute name="Classroom" use="prohibited">
                <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                        <xsd:maxLength value="7"/>
                    </xsd:restriction>
                </xsd:simpleType>
            </xsd:attribute>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>

<xsd:complexType name="lessonType">
    <xsd:complexContent>
        <xsd:extension base="eventType">
            <xsd:sequence>
                <xsd:element name="Professor" type="xsd:string" />
            </xsd:sequence>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>

<xsd:complexType name="seminarType">
    <xsd:complexContent>
        <xsd:restriction base="eventType">
            <xsd:sequence>
                <xsd:element name="Title" type="xsd:string" />
                <xsd:element name="Lecture" type="lectureType" />
            </xsd:sequence>
        </xsd:restriction>
    </xsd:complexContent>
</xsd:complexType>

<xsd:complexType name="labType">
    <xsd:complexContent>
        <xsd:restriction base="eventType">
            <xsd:sequence>
                <xsd:element name="Title" type="xsd:string" />
                <xsd:element name="Lecture" type="labLectureType" maxOccurs="9" minOccurs="1" />
            </xsd:sequence>
        </xsd:restriction>
    </xsd:complexContent>
</xsd:complexType>

<xsd:element name="Lesson" type="lessonType" substitutionGroup="Event" />
<xsd:element name="Seminar" type="seminarType" substitutionGroup="Event" />
<xsd:element name="Lab" type="labType" substitutionGroup="Event" />

</xsd:schema>

So a little explanation first. Ι have defined a Schedule element that can contain multiple Event elements (of type "eventType"). Furthermore I have defined the elements Lesson, Seminar and Lab that substitute the element Event (substitution group), so as:

Lesson must include a Professor element

Seminar must contain only one Lecture element

The lectures of Lab element should not contain the Classroom attribute (prohibited). In every other case the classroom is required.

I have been having problems with the last one. Basically to solve it I have created a base type for the lectures (baseLectureType) that contains only the elements a lecture needs, and I have derived 2 other types from this:

lectureType that contains the required Classroom attribute and

labLectureType that contains the prohibited Classroom attribute

However when I try to validate, I get the following errors:

Error - Line 109, 37: org.xml.sax.SAXParseException; lineNumber: 109; columnNumber: 37; rcase-Recurse.2: There is not a complete functional mapping between the particles.
Error - Line 109, 37: org.xml.sax.SAXParseException; lineNumber: 109; columnNumber: 37; derivation-ok-restriction.5.4.2: Error for type 'labType'.  The particle of the type is not a valid restriction of the particle of the base.

Any tips would be appreciated.


问:
Issue w/ image crossing dateline in imshow & cartopy
I'm trying to plot a square grid of equally-spaced (in lat/lon) data using cartopy, matplotlib, and imshow.  The data crosses the dateline, and I've had issues getting a map to work properly.

Here's an example of my issue:

```<code>import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

lat = np.arange(6000)*0.02 + (-59.99)
lon = np.arange(6000)*0.02 + (85.01)

dat = np.reshape(np.arange(6000*6000),[6000,6000])

tran = ccrs.PlateCarree()
proj = tran

plt.figure(figsize=(8,8))

ax = plt.axes(projection=proj)
print([lon[0],lon[-1],lat[0],lat[-1]])
ax.imshow(dat, extent=[lon[0],lon[-1],lat[0],lat[-1]],transform=tran,interpolation='nearest')
ax.coastlines(resolution='50m', color='black', linewidth=2)
ax.gridlines(crs=proj,draw_labels=True)
plt.show()

tran = ccrs.PlateCarree(central_longitude=180)
proj = tran

plt.figure(figsize=(8,8))

ax = plt.axes(projection=proj)
print([lon[0]-180,lon[-1]-180,lat[0],lat[-1]])
ax.imshow(dat, extent=[lon[0]-180,lon[-1]-180,lat[0],lat[-1]],transform=tran,interpolation='nearest')
ax.coastlines(resolution='50m', color='black', linewidth=2)
ax.gridlines(crs=tran,draw_labels=True)
plt.show()
</code>```

The first plot yields this image, chopping off at 180E:

The second fixes the map issue, but the grid ticks are now wrong:

I've tried reprojecting, I think (where tran != proj), but it seemingly either hung or was taking too long.

I basically want the bottom image, but with the proper labels.  I'm going to have more geolocated data to overplot, so I'd like to do it correctly instead of what seems like a hack right now.

答:
With Cartopy, drawing a map crossing dateline is always challenging. Here is the code that plots the map you want.

```<code>import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

# demo raster data
n1 = 300
m1 = 0.4
lat = np.arange(n1)*m1 + (-59.99)
lon = np.arange(n1)*m1 + (85.01)
dat = np.reshape(np.arange(n1*n1), [n1,n1])

cm_lon=180  # for central meridian

tran = ccrs.PlateCarree(central_longitude = cm_lon)
proj = tran

plt.figure(figsize=(8,8))
ax = plt.axes(projection=proj)

ext = [lon[0]-cm_lon, lon[-1]-cm_lon, lat[0], lat[-1]]
#print(ext)

ax.imshow(dat, extent=ext, \
              transform=tran, interpolation='nearest')

ax.coastlines(resolution='110m', color='black', linewidth=0.5, zorder=10)

# this draws grid lines only, must go beyond E/W extents
ax.gridlines(draw_labels=False, xlocs=[80,100,120,140,160,180,-180,-160,-140])

# this draw lables only, exclude those outside E/W extents
ax.gridlines(draw_labels=True, xlocs=[100,120,140,160,180,-160])

plt.show()
</code>```

The resulting map:

Body:
I'm trying to plot a square grid of equally-spaced (in lat/lon) data using cartopy, matplotlib, and imshow.  The data crosses the dateline, and I've had issues getting a map to work properly.

Here's an example of my issue:

import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

lat = np.arange(6000)*0.02 + (-59.99)
lon = np.arange(6000)*0.02 + (85.01)

dat = np.reshape(np.arange(6000*6000),[6000,6000])

tran = ccrs.PlateCarree()
proj = tran

plt.figure(figsize=(8,8))

ax = plt.axes(projection=proj)
print([lon[0],lon[-1],lat[0],lat[-1]])
ax.imshow(dat, extent=[lon[0],lon[-1],lat[0],lat[-1]],transform=tran,interpolation='nearest')
ax.coastlines(resolution='50m', color='black', linewidth=2)
ax.gridlines(crs=proj,draw_labels=True)
plt.show()

tran = ccrs.PlateCarree(central_longitude=180)
proj = tran

plt.figure(figsize=(8,8))

ax = plt.axes(projection=proj)
print([lon[0]-180,lon[-1]-180,lat[0],lat[-1]])
ax.imshow(dat, extent=[lon[0]-180,lon[-1]-180,lat[0],lat[-1]],transform=tran,interpolation='nearest')
ax.coastlines(resolution='50m', color='black', linewidth=2)
ax.gridlines(crs=tran,draw_labels=True)
plt.show()

The first plot yields this image, chopping off at 180E:

The second fixes the map issue, but the grid ticks are now wrong:

I've tried reprojecting, I think (where tran != proj), but it seemingly either hung or was taking too long.

I basically want the bottom image, but with the proper labels.  I'm going to have more geolocated data to overplot, so I'd like to do it correctly instead of what seems like a hack right now.

Body:
With Cartopy, drawing a map crossing dateline is always challenging. Here is the code that plots the map you want.

import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

# demo raster data
n1 = 300
m1 = 0.4
lat = np.arange(n1)*m1 + (-59.99)
lon = np.arange(n1)*m1 + (85.01)
dat = np.reshape(np.arange(n1*n1), [n1,n1])

cm_lon=180  # for central meridian

tran = ccrs.PlateCarree(central_longitude = cm_lon)
proj = tran

plt.figure(figsize=(8,8))
ax = plt.axes(projection=proj)

ext = [lon[0]-cm_lon, lon[-1]-cm_lon, lat[0], lat[-1]]
#print(ext)

ax.imshow(dat, extent=ext, \
              transform=tran, interpolation='nearest')

ax.coastlines(resolution='110m', color='black', linewidth=0.5, zorder=10)

# this draws grid lines only, must go beyond E/W extents
ax.gridlines(draw_labels=False, xlocs=[80,100,120,140,160,180,-180,-160,-140])

# this draw lables only, exclude those outside E/W extents
ax.gridlines(draw_labels=True, xlocs=[100,120,140,160,180,-160])

plt.show()

The resulting map:


问:
What is an unsigned int in c?
I have some code that I have to study and I'm not understanding what is a unsigned int and how it works.

```<code>void print_all_sums(unsigned int n,double a[n])
{ // 1 <= n <= 30
   unsigned int i,j,mask;
   double s;
</code>```

Something like this.

答: An unsigned int in C is a data type which has a non-negative value. (Eg. 0,1,2,3,4...)

Title: What is an unsigned int in c?

Body:
I have some code that I have to study and I'm not understanding what is a unsigned int and how it works.

void print_all_sums(unsigned int n,double a[n])
{ // 1 <= n <= 30
   unsigned int i,j,mask;
   double s;

Something like this.


问:
Reading a File in C isn't working?
so I tried looking around and I couldn't find an answer. I'm trying to read from a file I write in a different program. Writing it works fine, but when I try and read it, there is no output at all. Here's the code.

```<code>struct data{
    int tp, gpm, deg;
};

int main()
{
    struct data list[21];
    int p[21];
    list[0].tp = 10;
    FILE * fout;
    fopen("data_list", "r");
    for(int i = 0; i < 21; i++){
        fscanf(fopen, "%d:\t%d\t%d\t%d\n", &p[i], &list[i].tp, &list[i].gpm, &list[i].deg);
    }

    for(int i = 0; i < 21; i++){
        printf("%d:\t%d\t%d\t%d\n", p[i], list[i].tp, list[i].gpm, list[i].deg);
    }
    fclose(fout);
    return 0;
}
</code>```

Here's the file I'm trying to read

```<code>-10:651 17  108
-9: 514 16  142
-8: 588 16  169
-7: 542 10  160
-6: 531 17  127
-5: 688 15  158
-4: 619 18  122
-3: 658 14  170
-2: 588 11  182
-1: 541 12  139
+0: 641 19  114
+1: 668 17  200
+2: 517 19  157
+3: 589 13  121
+4: 696 13  140
+5: 526 12  157
+6: 630 12  137
+7: 685 11  105
+8: 556 11  120
+9: 645 15  188
+10:624 19  185
</code>```

Can anyone help me out? I've only been learning C for a couple months, most of it selftaught

答:
```<code>fscanf(fopen, "%d:\t%d\t%d\t%d\n"
</code>```

I have no idea how that possibly even compiled, but you are passing a function pointer where a FILE* is required.  That definitely will not work correctly.

The correct thing to pass there is the return value from your fopen() call (which at the moment you've been discarding).

Title: Reading a File in C isn't working?

Body:
so I tried looking around and I couldn't find an answer. I'm trying to read from a file I write in a different program. Writing it works fine, but when I try and read it, there is no output at all. Here's the code.

struct data{
    int tp, gpm, deg;
};

int main()
{
    struct data list[21];
    int p[21];
    list[0].tp = 10;
    FILE * fout;
    fopen("data_list", "r");
    for(int i = 0; i < 21; i++){
        fscanf(fopen, "%d:\t%d\t%d\t%d\n", &p[i], &list[i].tp, &list[i].gpm, &list[i].deg);
    }

    for(int i = 0; i < 21; i++){
        printf("%d:\t%d\t%d\t%d\n", p[i], list[i].tp, list[i].gpm, list[i].deg);
    }
    fclose(fout);
    return 0;
}

Here's the file I'm trying to read

-10:651 17  108
-9: 514 16  142
-8: 588 16  169
-7: 542 10  160
-6: 531 17  127
-5: 688 15  158
-4: 619 18  122
-3: 658 14  170
-2: 588 11  182
-1: 541 12  139
+0: 641 19  114
+1: 668 17  200
+2: 517 19  157
+3: 589 13  121
+4: 696 13  140
+5: 526 12  157
+6: 630 12  137
+7: 685 11  105
+8: 556 11  120
+9: 645 15  188
+10:624 19  185

Can anyone help me out? I've only been learning C for a couple months, most of it selftaught

Body:
fscanf(fopen, "%d:\t%d\t%d\t%d\n"

I have no idea how that possibly even compiled, but you are passing a function pointer where a FILE* is required.  That definitely will not work correctly.

The correct thing to pass there is the return value from your fopen() call (which at the moment you've been discarding).


问:
PHP insert elements before, between and after some array elements
I've a multidimensional array of some arrays, in which the first values are ordered and included in a specific range.

Example:

```<code>A1=[[0,a],[3,b],[5,c],[6,a],[9,c]]
</code>```

in which A1[i][0] are in range (0,10)

How can I obtain an array where, if the first value
 (A1[i][0]) isn't a value present in the first array, e.g.

```<code>A1[i][0]==2
</code>```

I insert an array with that value in the right position, with a specified second value (example A)?

Example of output i want:

```<code>A1=[[0,a],[1,A],[2,A],[3,b],[4,A],[5,c],[6,a],[7,A],[8,A],[9,c]]
</code>```

答:
This will help </p>

```<code>$A1 = [[0,'a'],[3,'b'],[5,'c'],[6,'a'],[9,'c']];
foreach($A1 as $A2) $A3[] = $A2[0];//make a new array contain keys of the first array.
for($i=0;$i<=9;$i++){
    if(!in_array($i, $A3)){
        $A1[] = [$i, 'A']; //check if the key not exist, make a new array with key who does not exist.
    }
}
asort($A1);//sort the new element inside the array
print_r($A1);
</code>```

<p>output is, </p>

```<code>[[0,a],[1,A],[2,A],[3,b],[4,A],[5,c],[6,a],[7,A],[8,A],[9,c]]
</code>```

Body:
I've a multidimensional array of some arrays, in which the first values are ordered and included in a specific range.

Example:

A1=[[0,a],[3,b],[5,c],[6,a],[9,c]]

in which A1[i][0] are in range (0,10)

How can I obtain an array where, if the first value
 (A1[i][0]) isn't a value present in the first array, e.g.

A1[i][0]==2

I insert an array with that value in the right position, with a specified second value (example A)?

Example of output i want:

A1=[[0,a],[1,A],[2,A],[3,b],[4,A],[5,c],[6,a],[7,A],[8,A],[9,c]]

Body:
This will help

$A1 = [[0,'a'],[3,'b'],[5,'c'],[6,'a'],[9,'c']];
foreach($A1 as $A2) $A3[] = $A2[0];//make a new array contain keys of the first array.
for($i=0;$i<=9;$i++){
    if(!in_array($i, $A3)){
        $A1[] = [$i, 'A']; //check if the key not exist, make a new array with key who does not exist.
    }
}
asort($A1);//sort the new element inside the array
print_r($A1);

output is,

[[0,a],[1,A],[2,A],[3,b],[4,A],[5,c],[6,a],[7,A],[8,A],[9,c]]


问:
Auto Increment Composite Primary Key
I have an Access database that I am trying to create. I want to use two columns from the table to create the primary key.

```<code>Projectbl (ProjectID, ProjectRegion, other columns)
</code>```

I want the ProjectID to autoincrement. That's fine. So far whenever I add a new project, the ProjecID increments by itself.

I want to create a new column in that same table that will be the ProjectRef where the new number would be a composite of ProjectID and ProjectRegion.

So for example

```<code>ProjectID ProjectRegion OtherCol
---------------------------------
1            500          ...
2            100          ...
3            200          ...
4            500          ...
5            500          ...
6            100          ...
</code>```

I want the table to actually look like that

```<code>ProjectRef ProjectID ProjectRegion OtherCol
--------------------------------------------
5001        1            500          ...
1002        2            100          ...
2003        3            200          ...
5004        4            500          ...
5005        5            500          ...
1006        6            100          ...
</code>```

So I am trying to add a new project: the projectID will autoincrement to 7, but the ProjectRef will be 'ProjectReg'7 whatever the ProjectReg is.

I know I can create a composite key with

```<code>CREATE TABLE 'Projectbl'
(
     ProjectID INT(10) NOT NULL AUTO_INCREMENT,
     ProjectRegion INT(10) NOT NULL,
     other columns VARCHAR(100),

     CONSTRAINT ProjectRef
         PRIMARY KEY ('ProjectRegion', 'ProjectID')
)
</code>```

How can I actually display ProjectRef in the table?

答: You shouldn't have the ProjectRef column at all. This violates basic rules of database normalization. If you want your front end to display the ProjectRef then just calculate it from the columns that you have.

Title: Auto Increment Composite Primary Key

Body:
I have an Access database that I am trying to create. I want to use two columns from the table to create the primary key.

Projectbl (ProjectID, ProjectRegion, other columns)

I want the ProjectID to autoincrement. That's fine. So far whenever I add a new project, the ProjecID increments by itself.

I want to create a new column in that same table that will be the ProjectRef where the new number would be a composite of ProjectID and ProjectRegion.

So for example

ProjectID ProjectRegion OtherCol
---------------------------------
1            500          ...
2            100          ...
3            200          ...
4            500          ...
5            500          ...
6            100          ...

I want the table to actually look like that

ProjectRef ProjectID ProjectRegion OtherCol
--------------------------------------------
5001        1            500          ...
1002        2            100          ...
2003        3            200          ...
5004        4            500          ...
5005        5            500          ...
1006        6            100          ...

So I am trying to add a new project: the projectID will autoincrement to 7, but the ProjectRef will be 'ProjectReg'7 whatever the ProjectReg is.

I know I can create a composite key with

CREATE TABLE 'Projectbl'
(
     ProjectID INT(10) NOT NULL AUTO_INCREMENT,
     ProjectRegion INT(10) NOT NULL,
     other columns VARCHAR(100),

     CONSTRAINT ProjectRef
         PRIMARY KEY ('ProjectRegion', 'ProjectID')
)

How can I actually display ProjectRef in the table?


问:
Connection string in constructor vs. app.config?
When referencing the configuration value in my context constructor, I face no issues with database connectivity:

```<code>public class MyDbContext : DbContext
{
    public MyDbContext ()
        : base("Name=Model1")
    {
    }
}
</code>```

My App.config connection string looks like this:

```<code><connectionStrings>
    <add name="Model1"
         connectionString="data source=10.4.4.3;initial catalog=mydatabase;persist security info=True;user id=myuser;password=mypass;MultipleActiveResultSets=True;App=EntityFramework"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
</code>```

However, when I hard-code the connection like so:

```<code>public class MyDbContext : DbContext
{
    public MyDbContext ()
        : base(@"data source=10.4.4.3;initial catalog=mydatabase;persist security info=True;user id=myuser;password=mypass;MultipleActiveResultSets=True;App=EntityFramework")
    {
    }
}
</code>```

The exception I am getting is:

```<code>{System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized element. (C:\ProgramData\SF\vm0\Fabric\work\Applications\abc.API.ProdAndPrice.O720.ProdLinesType_App285\ComponentsPkg.Code.1.0.0\Components.exe.Config line 38)
   at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
   at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
   at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
   --- End of inner exception stack trace ---
   at System.Configuration.ConfigurationManager.PrepareConfigSystem()
   at System.Configuration.ConfigurationManager.GetSection(String sectionName)
   at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
   at System.Diagnostics.DiagnosticsConfiguration.GetConfigSection()
   at System.Diagnostics.DiagnosticsConfiguration.Initialize()
   at System.Diagnostics.DiagnosticsConfiguration.get_IndentSize()
   at System.Diagnostics.TraceInternal.InitializeSettings()
   at System.Diagnostics.TraceInternal.get_Listeners()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
   at Microsoft.Owin.Hosting.Utilities.SettingsLoader.FromConfigImplementation..ctor()
   at Microsoft.Owin.Hosting.Utilities.SettingsLoader.<LoadFromConfig>b__0()
   at System.Threading.LazyInitializer.EnsureInitializedCore[T](T& target, Func`1 valueFactory)
   at Microsoft.Owin.Hosting.Utilities.SettingsLoader.LoadFromConfig(IDictionary`2 settings)
   at Microsoft.Owin.Hosting.Engine.StartContext..ctor(StartOptions options)
   at Microsoft.Owin.Hosting.WebApp.StartImplementation(IServiceProvider services, StartOptions options, Action`1 startup)
   at Microsoft.Owin.Hosting.WebApp.Start(String url, Action`1 startup)
   at Components.OwinCommunicationListener.OpenAsync(CancellationToken cancellationToken) in F:\TFS\ooo720 Res\ooo720\DEV\Source\enterprise\abc.API.ProdAndPrice.O720.ProdLines\Components\OwinCommunicationListener.cs:line 78
   at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.<OpenCommunicationListenersAsync>d__19.MoveNext()}
</code>```

What am I doing wrong? Why is the connection failing?

答: You don't need the connection string in app.config when you are assigning a key to it, and not using it and just passing the connection string in constructor</p>

Body:
When referencing the configuration value in my context constructor, I face no issues with database connectivity:

public class MyDbContext : DbContext
{
    public MyDbContext ()
        : base("Name=Model1")
    {
    }
}

My App.config connection string looks like this:

<connectionStrings>
    <add name="Model1"
         connectionString="data source=10.4.4.3;initial catalog=mydatabase;persist security info=True;user id=myuser;password=mypass;MultipleActiveResultSets=True;App=EntityFramework"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

However, when I hard-code the connection like so:

public class MyDbContext : DbContext
{
    public MyDbContext ()
        : base(@"data source=10.4.4.3;initial catalog=mydatabase;persist security info=True;user id=myuser;password=mypass;MultipleActiveResultSets=True;App=EntityFramework")
    {
    }
}

The exception I am getting is:

{System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized element. (C:\ProgramData\SF\vm0\Fabric\work\Applications\abc.API.ProdAndPrice.O720.ProdLinesType_App285\ComponentsPkg.Code.1.0.0\Components.exe.Config line 38)
   at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
   at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
   at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
   --- End of inner exception stack trace ---
   at System.Configuration.ConfigurationManager.PrepareConfigSystem()
   at System.Configuration.ConfigurationManager.GetSection(String sectionName)
   at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
   at System.Diagnostics.DiagnosticsConfiguration.GetConfigSection()
   at System.Diagnostics.DiagnosticsConfiguration.Initialize()
   at System.Diagnostics.DiagnosticsConfiguration.get_IndentSize()
   at System.Diagnostics.TraceInternal.InitializeSettings()
   at System.Diagnostics.TraceInternal.get_Listeners()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
   at Microsoft.Owin.Hosting.Utilities.SettingsLoader.FromConfigImplementation..ctor()
   at Microsoft.Owin.Hosting.Utilities.SettingsLoader.<LoadFromConfig>b__0()
   at System.Threading.LazyInitializer.EnsureInitializedCore[T](T& target, Func`1 valueFactory)
   at Microsoft.Owin.Hosting.Utilities.SettingsLoader.LoadFromConfig(IDictionary`2 settings)
   at Microsoft.Owin.Hosting.Engine.StartContext..ctor(StartOptions options)
   at Microsoft.Owin.Hosting.WebApp.StartImplementation(IServiceProvider services, StartOptions options, Action`1 startup)
   at Microsoft.Owin.Hosting.WebApp.Start(String url, Action`1 startup)
   at Components.OwinCommunicationListener.OpenAsync(CancellationToken cancellationToken) in F:\TFS\ooo720 Res\ooo720\DEV\Source\enterprise\abc.API.ProdAndPrice.O720.ProdLines\Components\OwinCommunicationListener.cs:line 78
   at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.<OpenCommunicationListenersAsync>d__19.MoveNext()}

What am I doing wrong? Why is the connection failing?


问:
selecting not None value from a dataframe column
I would like to use the fillna function to fill None value of a column with its own first most frequent value that is not None or nan.

Input DF:

```<code>Col_A
a
None
None
c
c
d
d
</code>```

The output Dataframe could be either:

```<code>Col_A
a
c
c
c
c
d
d
</code>```

Any suggestion would be very appreciated.
Many Thanks, Best Regards,
Carlo

答:
fillna + mode

```<code>df.Col_A.fillna(df.Col_A.mode()[0])
Out[963]:
0    a
1    c
2    c
3    c
4    c
5    d
6    d
Name: Col_A, dtype: object
</code>```

Body:
I would like to use the fillna function to fill None value of a column with its own first most frequent value that is not None or nan.

Input DF:

Col_A
a
None
None
c
c
d
d

The output Dataframe could be either:

Col_A
a
c
c
c
c
d
d

Any suggestion would be very appreciated.
Many Thanks, Best Regards,
Carlo

Body:
fillna + mode

df.Col_A.fillna(df.Col_A.mode()[0])
Out[963]:
0    a
1    c
2    c
3    c
4    c
5    d
6    d
Name: Col_A, dtype: object


问:
Photoshop Script to Randomly Select Images
I am trying to use Javascript to select two random images from a local folder and place on separate Photoshop layers. I have created an array with the filepaths to choose from.

```<code>#target photoshop
var allImages = [“file path/img-1.jpg”, "file path/img-2.jpg", "file path/img-3.jpg"];
//this is a large array of file paths to 100 different images
var pickImage = allImages[Math.floor(Math.random() *
allImages.length)];
var imgFile = File(pickImage);
var openFile = app.open(imgFile);
var secondImage = allImages[Math.floor(Math.random() * allImages.length)];
app.activeDocument.artLayers.add(secondImage);
</code>```

This opens the first image and creates a blank layer above but does not insert the second image. What am I missing?

答:
In javascript, you must first create a file object before you may open an image. All you have to do is create the variable and then point it at secondImage. Just like you did with the first image:

```<code>var imgFile = File(pickImage);
</code>```

In your current approach, your easiest solution would probably be to just make a variable secondPickedImage and assign it to the same thing as pickImage. Although, this leaves the possibility of you picking the same image, you could fix that with an if statement.
   I would recommend changing your approach and turning pickImage into a function that you can call that will return a random number for your array - saves space, and cleans up your code. Then put the secondImage assignment in a do while loop that keeps picking a random number until you pick a number different from the pickImage number so your first and second pictures are different.

Source: http://wwwimages.adobe.com/www.adobe.com/content/dam/acom/en/devnet/photoshop/pdfs/photoshop-cc-scripting-guide.pdf  page 29.

Body:
I am trying to use Javascript to select two random images from a local folder and place on separate Photoshop layers. I have created an array with the filepaths to choose from.

#target photoshop
var allImages = [“file path/img-1.jpg”, "file path/img-2.jpg", "file path/img-3.jpg"];
//this is a large array of file paths to 100 different images
var pickImage = allImages[Math.floor(Math.random() *
allImages.length)];
var imgFile = File(pickImage);
var openFile = app.open(imgFile);
var secondImage = allImages[Math.floor(Math.random() * allImages.length)];
app.activeDocument.artLayers.add(secondImage);

This opens the first image and creates a blank layer above but does not insert the second image. What am I missing?

Body:
In javascript, you must first create a file object before you may open an image. All you have to do is create the variable and then point it at secondImage. Just like you did with the first image:

var imgFile = File(pickImage);

In your current approach, your easiest solution would probably be to just make a variable secondPickedImage and assign it to the same thing as pickImage. Although, this leaves the possibility of you picking the same image, you could fix that with an if statement.
   I would recommend changing your approach and turning pickImage into a function that you can call that will return a random number for your array - saves space, and cleans up your code. Then put the secondImage assignment in a do while loop that keeps picking a random number until you pick a number different from the pickImage number so your first and second pictures are different.

Source: http://wwwimages.adobe.com/www.adobe.com/content/dam/acom/en/devnet/photoshop/pdfs/photoshop-cc-scripting-guide.pdf  page 29.


问:
Lodash _forEach breaks typeguard in TypeScript

Background

Creating a variable notifications that I want to be false when I have no data, otherwise an array of objects. So I did a union type: let notifications: object[] | boolean = []; Fine except when I do notifications.push(notification); I got

```<code>Property 'push' does not exist on type 'boolean | object[]'.
  Property 'push' does not exist on type 'true'.
</code>```

Right, TS isn't sure that it's an array. I'll let it know. notifications = []; Same error. Bunch more digging, realize the guard is working fine, it's only when I have my .push inside lodash's _forEach that I get the error.

Current state:

```<code>let notifications: object[] | boolean;

if (noNotifications) {
  notifications = false;
} else {
  notifications = [];
  _forEach(notificationsObj, function (notification, type) { // Culprit
    notification['type'] = type;
    notifications.push(notification); // <-- TS error on push
  });
}
return notifications;
</code>```

What I've tried

A bunch of different ways of type guarding. Don't understand the reason _forEach is breaking it, so not sure what to try next.

Question

Is is possible to  use push on my variable inside _forEach? If so, how?

答:
jcalz's answer addresses your specific question, but I just wanted to offer a different way of solving your problem. By writing it in a functional style, you can avoid a lot of these problems entirely.

```<code>import * as _ from 'lodash';

function getNotifications(notificationsObj: {[type: string]: object}): object[] | boolean {
  if (_.isEmpty(notificationsObj)) {
    return false;
  } else {
    // note: lodash map will turn an object into an array
    return _.map(notificationsObj, (notification, type) => {
      return {...notification, type};
    });
  }
}
</code>```

Note I also avoid mutating the original notification objects, in contrast with your original solution. If you rely on that mutation taking place then you should change that part back.

Body:
Background

Creating a variable notifications that I want to be false when I have no data, otherwise an array of objects. So I did a union type: let notifications: object[] | boolean = []; Fine except when I do notifications.push(notification); I got

Property 'push' does not exist on type 'boolean | object[]'.
  Property 'push' does not exist on type 'true'.

Right, TS isn't sure that it's an array. I'll let it know. notifications = []; Same error. Bunch more digging, realize the guard is working fine, it's only when I have my .push inside lodash's _forEach that I get the error.

Current state:

let notifications: object[] | boolean;

if (noNotifications) {
  notifications = false;
} else {
  notifications = [];
  _forEach(notificationsObj, function (notification, type) { // Culprit
    notification['type'] = type;
    notifications.push(notification); // <-- TS error on push
  });
}
return notifications;

What I've tried

A bunch of different ways of type guarding. Don't understand the reason _forEach is breaking it, so not sure what to try next.

Question

Is is possible to  use push on my variable inside _forEach? If so, how?

Body:
jcalz's answer addresses your specific question, but I just wanted to offer a different way of solving your problem. By writing it in a functional style, you can avoid a lot of these problems entirely.

import * as _ from 'lodash';

function getNotifications(notificationsObj: {[type: string]: object}): object[] | boolean {
  if (_.isEmpty(notificationsObj)) {
    return false;
  } else {
    // note: lodash map will turn an object into an array
    return _.map(notificationsObj, (notification, type) => {
      return {...notification, type};
    });
  }
}

Note I also avoid mutating the original notification objects, in contrast with your original solution. If you rely on that mutation taking place then you should change that part back.


问:
Can we configure refresh token expiration time to unlimited in WSO2 API manager by setting -1 for RefreshTokenValidityPeriod
We have tried to set the RefreshTokenValidityPeriod in the identity.xml as -1 to make the refresh token valid forever. But the refresh token was expired immediately when it was set to -1. We are using wso2 API manager 2.1.0 and deployed with docker.</p>

答: You can't do that. But, if you're fine with the security risk of having a non-expiring refresh token, you can have a non-expiring access token, instead. Both the advantage and risk are the same in 2. </p>


问:
how could I convert c++ to python
```<code>#include <iostream>
using namespace std;

int main() {
  int n;
  int i;
  int k;
  cout << "please insert n";

  cin >> n; k=0 ;

  for (i = n; i > 1; i--) {
    cout << "/n "<< k << "+" << i << "=" << i + k++;
  }

  return 0;
}
</code>```

I'm trying to reproduce the above code in python, but I'm not sure what I'm getting wrong. I'm not sure how to start at a number, then decrement until the condition is met. Here's what I have so far:

```<code>k=0
n=4
for i in range(n)
 if i > 1 :
  i-=1
  k+=1
print(i+k++)
</code>```

What am I doing wrong?

答:
```<code>n = int(input("please insert n : "))
k = 0
for i in range(n,1,-1):
    print('\n',k,'+',i,'=',i+k)
    k=k+1
</code>```

range solves half of the problem itself. Rest of the thing is just formatting and inputting the number.

range(n,1,-1) means the range starts from n and ends in 1 and there is a step of -1 in between them.

n, n+(-1), n+(-2),...,1.

Your C++ program generates wrong output:-

/n 1+4=4/n 2+3=4/n 3+2=4

Correct code:

```<code>for(i=n,k=0; i > 1 ; i--,k++){
   cout << "\n "<< k << "+" << i << "=" << i + k;
}
</code>```

You meant \n (newline) in C++ not /n.

Title: how could I convert c++ to python

Body:
#include <iostream>
using namespace std;

int main() {
  int n;
  int i;
  int k;
  cout << "please insert n";

  cin >> n; k=0 ;

  for (i = n; i > 1; i--) {
    cout << "/n "<< k << "+" << i << "=" << i + k++;
  }

  return 0;
}

I'm trying to reproduce the above code in python, but I'm not sure what I'm getting wrong. I'm not sure how to start at a number, then decrement until the condition is met. Here's what I have so far:

k=0
n=4
for i in range(n)
 if i > 1 :
  i-=1
  k+=1
print(i+k++)

What am I doing wrong?

Body:
n = int(input("please insert n : "))
k = 0
for i in range(n,1,-1):
    print('\n',k,'+',i,'=',i+k)
    k=k+1

range solves half of the problem itself. Rest of the thing is just formatting and inputting the number.

range(n,1,-1) means the range starts from n and ends in 1 and there is a step of -1 in between them.

n, n+(-1), n+(-2),...,1.

Your C++ program generates wrong output:-

/n 1+4=4/n 2+3=4/n 3+2=4

Correct code:

for(i=n,k=0; i > 1 ; i--,k++){
   cout << "\n "<< k << "+" << i << "=" << i + k;
}

You meant \n (newline) in C++ not /n.


问:
How to make a TextView multiline programmatically in Android (Java)
I want to make my textview multiline.

Image : http://s13.postimg.org/y0q78e1yv/Capture.png

But how can I make my text multiline ?

Which atribut ?

```<code>TextView txt_tweet = (TextView) View.inflate(this, R.layout.special_textview, null);
</code>```

special_textview

```<code>    <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"

    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:paddingBottom="5dp"
    android:inputType="textMultiLine"
    android:scrollHorizontally="false">

</TextView>
</code>```

答:
Adding to the answers: the order matters!

Make sure you call setInputType before setMinLines!

Body:
I want to make my textview multiline.

Image : http://s13.postimg.org/y0q78e1yv/Capture.png

But how can I make my text multiline ?

Which atribut ?

TextView txt_tweet = (TextView) View.inflate(this, R.layout.special_textview, null);

special_textview

    <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"

    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:paddingBottom="5dp"
    android:inputType="textMultiLine"
    android:scrollHorizontally="false">

</TextView>


问:
Why don't we instantiate delegating classes with their delegate objects?
I can't imagine a delegating downloader class or CLLLocationManager or tableView be without a delegate. So why do we need create it as an optional?

Why do we do

```<code>tableview = UITableView()
tableview.delegate = self
tableview.dataSource = self
</code>```

Why isn't the API made so we could just do:

```<code>tableview = UITableView(delegate: self, dataSource: self)
</code>```

Is this because memory cycles, so we could first nil either the delegating class or the delegate class and then the other? Is that the only reason?

Even if that's the case, still isn't it just more convenient to make it insatiable using

```<code>class tableView{
    var delegate: UITableViewDelegate?
    var dataSource: UITableViewDataSource?

    init(delegate: UITableViewDelegate? = nil, dataSource: UITableViewDataSource?){
        self.delegate = delegate
        self.dataSource = dataSource
    }
}

var tableView = tableView()
</code>```

答:
Requiring a delegate to be declared on instantiation adds no real benefit to the language itself. It's a convenience that you as the developer could easily add, if you really felt the need, but it doesn't belong in UIKit.

But digging deeper, you wouldn't always want to instantiate the tableview with a delegate anyway. What if the delegate doesn't exist yet? Delegates are not always self. You may need to build out your tableview with attributes for displaying or implementing at a later point.

You may also want to change the delegate, which for someone reading code, could add a lot of unnecessary obfuscation to debugging. Consider the following pseudo-code:

```<code>var tableview = UITableView(delegate:self)

var childController = ChildControllerWithTableView()
childController.prepareForSegue() {
    childController.tableview = tableview
    childController.tableview.delegate = childcontroller
}
</code>```

Not only have you changed the delegate, confusing future developers (probably yourself included!) but you also had to (unnecessarily) set the delegate to self, simply because childController didn't exist yet.

Or what if the delegator is the delegate, as Josh points out?

```<code>var tableview = UITableView(delegate:tableview)
</code>```

Wait, what? That's not gonna fly!

Still, you can add this to all your projects if you like - if there's a business need (or convenience) reason to do it! It's what makes Swift so awesome:

```<code>extension UITableView {
    convenience init(delegate: UITableViewDelegate? = nil, dataSource: UITableViewDataSource?){
        self.delegate = delegate
        self.dataSource = dataSource
    }
}
</code>```

Body:
I can't imagine a delegating downloader class or CLLLocationManager or tableView be without a delegate. So why do we need create it as an optional?

Why do we do

tableview = UITableView()
tableview.delegate = self
tableview.dataSource = self

Why isn't the API made so we could just do:

tableview = UITableView(delegate: self, dataSource: self)

Is this because memory cycles, so we could first nil either the delegating class or the delegate class and then the other? Is that the only reason?

Even if that's the case, still isn't it just more convenient to make it insatiable using

class tableView{
    var delegate: UITableViewDelegate?
    var dataSource: UITableViewDataSource?

    init(delegate: UITableViewDelegate? = nil, dataSource: UITableViewDataSource?){
        self.delegate = delegate
        self.dataSource = dataSource
    }
}

var tableView = tableView()

Body:
Requiring a delegate to be declared on instantiation adds no real benefit to the language itself. It's a convenience that you as the developer could easily add, if you really felt the need, but it doesn't belong in UIKit.

But digging deeper, you wouldn't always want to instantiate the tableview with a delegate anyway. What if the delegate doesn't exist yet? Delegates are not always self. You may need to build out your tableview with attributes for displaying or implementing at a later point.

You may also want to change the delegate, which for someone reading code, could add a lot of unnecessary obfuscation to debugging. Consider the following pseudo-code:

var tableview = UITableView(delegate:self)

var childController = ChildControllerWithTableView()
childController.prepareForSegue() {
    childController.tableview = tableview
    childController.tableview.delegate = childcontroller
}

Not only have you changed the delegate, confusing future developers (probably yourself included!) but you also had to (unnecessarily) set the delegate to self, simply because childController didn't exist yet.

Or what if the delegator is the delegate, as Josh points out?

var tableview = UITableView(delegate:tableview)

Wait, what? That's not gonna fly!

Still, you can add this to all your projects if you like - if there's a business need (or convenience) reason to do it! It's what makes Swift so awesome:

extension UITableView {
    convenience init(delegate: UITableViewDelegate? = nil, dataSource: UITableViewDataSource?){
        self.delegate = delegate
        self.dataSource = dataSource
    }
}


问:
PUT with nested object
I have Dish and Comment models like below in my Rails 5.1 API app - code repo here . I need help with adding a  new Comment to a Dish.

Post

```<code>class Dish < ApplicationRecord
    has_many :comments
end
</code>```

Comment

```<code>class Comment < ApplicationRecord
    belongs_to :dish
end
</code>```

Post Serializer (uses ActiveModel Seriazlier)

```<code>class DishSerializer < ActiveModel::Serializer
  attributes :id, :name, :image, :category, :label, :price, :featured, :description, :created_at

  has_many :comments
end
</code>```

Comment Serializer

```<code>class CommentSerializer < ActiveModel::Serializer
  attributes :id, :rating, :comment, :author, :date

  def date
    object.created_at
  end
end
</code>```

Post Controller - default rails scaffold

```<code>class DishesController < ApplicationController
  before_action :set_dish, only: [:show, :update, :destroy]

  # GET /dishes
  def index
    @dishes = Dish.all

    render json: @dishes
  end

  # GET /dishes/1
  def show
    render json: @dish
  end

  # POST /dishes
  def create
    @dish = Dish.new(dish_params)

    if @dish.save
      render json: @dish, status: :created, location: @dish
    else
      render json: @dish.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /dishes/1
  def update
    # byebug
    if @dish.update(dish_params)
      render json: @dish
    else
      render json: @dish.errors, status: :unprocessable_entity
    end
  end

  # DELETE /dishes/1
  def destroy
    @dish.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_dish
      @dish = Dish.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def dish_params
      params.require(:dish).permit(:name, :image, :category, :label, :price, :featured, :description)
    end
end
</code>```

Comment Controller - default rails scaffold

```<code>class CommentsController < ApplicationController
  before_action :set_comment, only: [:show, :update, :destroy]

  # GET /comments
  def index
    @comments = Comment.all

    render json: @comments
  end

  # GET /comments/1
  def show
    render json: @comment
  end

  # POST /comments
  def create
    @comment = Comment.new(comment_params)

    if @comment.save
      render json: @comment, status: :created, location: @comment
    else
      render json: @comment.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /comments/1
  def update
    if @comment.update(comment_params)
      render json: @comment
    else
      render json: @comment.errors, status: :unprocessable_entity
    end
  end

  # DELETE /comments/1
  def destroy
    @comment.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_comment
      @comment = Comment.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def comment_params
      params.require(:comment).permit(:rating, :comment, :author)
    end
end
</code>```

Issue

When a user visits /dishes/:id and adds a comment to a dish via the front-end app ( Angular 2) , the comment is push to the array of current comments and I'm calling PUT /dishes:id with the dish object nested with the existing comments and the new comment. However the new comment is not saved by rails - no error returned, rather the dish object is returned. However I do see Unpermitted parameters: :id, :created_at in rails s console. How do I get rails to save the new comment ?

The page ( dishes/9 ) from where I'm adding the comment to a dish looks like below on the Angular client side.

Rails Server logs

On the rails side, below is what I see in params - I do see the new comment - {"author"=>"JANE7777", "rating"=>3, "comment"=>"COMMENT7777", "date"=>"2017-11-12T12:58:12.555Z"} in there.

```<code>Started PUT "/dishes/9" for 127.0.0.1 at 2017-11-12 18:28:12 +0530
Processing by DishesController#update as HTML
  Parameters: {"id"=>"9", "name"=>"Uthappizza", "image"=>"images/uthappizza.png", "category"=>"mains", "label"=>"Hot", "price"=>"4.99", "featured"=>true, "description"=>"A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.", "created_at"=>"2017-11-01T04:30:09.407Z", "comments"=>[{"id"=>46, "rating"=>5, "comment"=>"Imagine all the eatables, living in conFusion!", "author"=>"John Lemon", "date"=>"2012-10-16T17:57:28.556Z"}, {"id"=>47, "rating"=>4, "comment"=>"Sends anyone to heaven, I wish I could get my mother-in-law to eat it!", "author"=>"Paul McVites", "date"=>"2014-09-05T17:57:28.556Z"}, {"id"=>48, "rating"=>3, "comment"=>"Eat it, just eat it!", "author"=>"Michael Jaikishan", "date"=>"2015-02-13T17:57:28.556Z"}, {"id"=>49, "rating"=>4, "comment"=>"Ultimate, Reaching for the stars!", "author"=>"Ringo Starry", "date"=>"2013-12-02T17:57:28.556Z"}, {"id"=>50, "rating"=>2, "comment"=>"It's your birthday, we're gonna party!", "author"=>"25 Cent", "date"=>"2011-12-02T17:57:28.556Z"}, {"id"=>51, "rating"=>4, "comment"=>"great dish", "author"=>"Jogesh", "date"=>"2017-10-30T05:03:39.656Z"}, {"author"=>"JANE7777", "rating"=>3, "comment"=>"COMMENT7777", "date"=>"2017-11-12T12:58:12.555Z"}], "dish"=>{"id"=>"9", "name"=>"Uthappizza", "image"=>"images/uthappizza.png", "category"=>"mains", "label"=>"Hot", "price"=>"4.99", "featured"=>true, "description"=>"A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.", "created_at"=>"2017-11-01T04:30:09.407Z"}}
  Dish Load (1.0ms)  SELECT  "dishes".* FROM "dishes" WHERE "dishes"."id" = $1 LIMIT $2  [["id", 9], ["LIMIT", 1]]

[25, 34] in C:/apps/railsApi/app/controllers/dishes_controller.rb
   25:   end
   26:
   27:   # PATCH/PUT /dishes/1
   28:   def update
   29:     byebug
=> 30:     if @dish.update(dish_params)
   31:       render json: @dish
   32:     else
   33:       render json: @dish.errors, status: :unprocessable_entity
   34:     end
(byebug) params
<ActionController::Parameters {"id"=>"9", "name"=>"Uthappizza", "image"=>"images/uthappizza.png", "category"=>"mains", "label"=>"Hot", "price"=>"4.99", "featured"=>true, "description"=>"A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.", "created_at"=>"2017-11-01T04:30:09.407Z", "comments"=>[{"id"=>46, "rating"=>5, "comment"=>"Imagine all the eatables, living in conFusion!", "author"=>"John Lemon", "date"=>"2012-10-16T17:57:28.556Z"}, {"id"=>47, "rating"=>4, "comment"=>"Sends anyone to heaven, I wish I could get my mother-in-law to eat it!", "author"=>"Paul McVites", "date"=>"2014-09-05T17:57:28.556Z"}, {"id"=>48, "rating"=>3, "comment"=>"Eat it, just eat it!", "author"=>"Michael Jaikishan", "date"=>"2015-02-13T17:57:28.556Z"}, {"id"=>49, "rating"=>4, "comment"=>"Ultimate, Reaching for the stars!", "author"=>"Ringo Starry", "date"=>"2013-12-02T17:57:28.556Z"}, {"id"=>50, "rating"=>2, "comment"=>"It's your birthday, we're gonna party!", "author"=>"25 Cent", "date"=>"2011-12-02T17:57:28.556Z"}, {"id"=>51, "rating"=>4, "comment"=>"great dish", "author"=>"Jogesh", "date"=>"2017-10-30T05:03:39.656Z"}, {"author"=>"JANE7777", "rating"=>3, "comment"=>"COMMENT7777", "date"=>"2017-11-12T12:58:12.555Z"}], "controller"=>"dishes", "action"=>"update", "dish"=>{"id"=>9, "name"=>"Uthappizza", "image"=>"images/uthappizza.png", "category"=>"mains", "label"=>"Hot", "price"=>"4.99", "featured"=>true, "description"=>"A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.", "created_at"=>"2017-11-01T04:30:09.407Z"}} permitted: false>
(byebug) c
Unpermitted parameters: :id, :created_at
   (0.0ms)  BEGIN
   (0.0ms)  COMMIT
[active_model_serializers]   Comment Load (0.0ms)  SELECT "comments".* FROM "comments" WHERE "comments"."dish_id" = $1  [["dish_id", 9]]
[active_model_serializers] Rendered DishSerializer with ActiveModelSerializers::Adapter::Attributes (31.29ms)
Completed 200 OK in 1901725ms (Views: 37.5ms | ActiveRecord: 5.0ms)
</code>```

Client-side models

The Dish model has Comment[] as one of the members. When a new comment is added via the form the comment is push to dish.comments array before sending the Dish object to the Rails API back-end.

Comment model in client side

```<code>export class Comment {
    rating: number;
    comment: string;
    author: string;
    date: string;
}
</code>```

Post model in client side

```<code>import { Comment } from './comment';
export class Dish {
  id: number;
  name: string;
  image: string;
  category: string;
  label: string;
  price: string;
  featured: boolean;
  description: string;
  comments: Comment[];
}
</code>```

答:
I’d recommend you use the Comments controller and form a nested route to be RESTful.

Firstly, POST the request, including the dish_id to /comments. You’re trying to create a Comment, not update the Dish.

Secondly, form the nested route:
/dishes/:dish_id/comments

Here’s a guide to nesting resources like this: http://guides.rubyonrails.org/routing.html#nested-resources

The reason for your error is that you’ve broken the expected parameter structure. For a PUT your params should be:

```<code>{
   id: <record to update>,
   dish: {
      name: “blah”,
      comments: [{...},{...}]
   }
 }
</code>```

Again, I really recommend you don’t PUT to Dish if you just want to add a Comment. For instance: the above would be desired to replace all comments on the Dish! If you’re creating a record, create that record, don’t update it’s parent.

If you wanted to update the Dish when a new Comment is added you can add a callback to the Comment model on create or do it in the Comment create controller action.

Title: PUT with nested object

Body:
I have Dish and Comment models like below in my Rails 5.1 API app - code repo here . I need help with adding a  new Comment to a Dish.

Post

class Dish < ApplicationRecord
    has_many :comments
end

Comment

class Comment < ApplicationRecord
    belongs_to :dish
end

Post Serializer (uses ActiveModel Seriazlier)

class DishSerializer < ActiveModel::Serializer
  attributes :id, :name, :image, :category, :label, :price, :featured, :description, :created_at

  has_many :comments
end

Comment Serializer

class CommentSerializer < ActiveModel::Serializer
  attributes :id, :rating, :comment, :author, :date

  def date
    object.created_at
  end
end

Post Controller - default rails scaffold

class DishesController < ApplicationController
  before_action :set_dish, only: [:show, :update, :destroy]

  # GET /dishes
  def index
    @dishes = Dish.all

    render json: @dishes
  end

  # GET /dishes/1
  def show
    render json: @dish
  end

  # POST /dishes
  def create
    @dish = Dish.new(dish_params)

    if @dish.save
      render json: @dish, status: :created, location: @dish
    else
      render json: @dish.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /dishes/1
  def update
    # byebug
    if @dish.update(dish_params)
      render json: @dish
    else
      render json: @dish.errors, status: :unprocessable_entity
    end
  end

  # DELETE /dishes/1
  def destroy
    @dish.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_dish
      @dish = Dish.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def dish_params
      params.require(:dish).permit(:name, :image, :category, :label, :price, :featured, :description)
    end
end

Comment Controller - default rails scaffold

class CommentsController < ApplicationController
  before_action :set_comment, only: [:show, :update, :destroy]

  # GET /comments
  def index
    @comments = Comment.all

    render json: @comments
  end

  # GET /comments/1
  def show
    render json: @comment
  end

  # POST /comments
  def create
    @comment = Comment.new(comment_params)

    if @comment.save
      render json: @comment, status: :created, location: @comment
    else
      render json: @comment.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /comments/1
  def update
    if @comment.update(comment_params)
      render json: @comment
    else
      render json: @comment.errors, status: :unprocessable_entity
    end
  end

  # DELETE /comments/1
  def destroy
    @comment.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_comment
      @comment = Comment.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def comment_params
      params.require(:comment).permit(:rating, :comment, :author)
    end
end

Issue

When a user visits /dishes/:id and adds a comment to a dish via the front-end app ( Angular 2) , the comment is push to the array of current comments and I'm calling PUT /dishes:id with the dish object nested with the existing comments and the new comment. However the new comment is not saved by rails - no error returned, rather the dish object is returned. However I do see Unpermitted parameters: :id, :created_at in rails s console. How do I get rails to save the new comment ?

The page ( dishes/9 ) from where I'm adding the comment to a dish looks like below on the Angular client side.

Rails Server logs

On the rails side, below is what I see in params - I do see the new comment - {"author"=>"JANE7777", "rating"=>3, "comment"=>"COMMENT7777", "date"=>"2017-11-12T12:58:12.555Z"} in there.

Started PUT "/dishes/9" for 127.0.0.1 at 2017-11-12 18:28:12 +0530
Processing by DishesController#update as HTML
  Parameters: {"id"=>"9", "name"=>"Uthappizza", "image"=>"images/uthappizza.png", "category"=>"mains", "label"=>"Hot", "price"=>"4.99", "featured"=>true, "description"=>"A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.", "created_at"=>"2017-11-01T04:30:09.407Z", "comments"=>[{"id"=>46, "rating"=>5, "comment"=>"Imagine all the eatables, living in conFusion!", "author"=>"John Lemon", "date"=>"2012-10-16T17:57:28.556Z"}, {"id"=>47, "rating"=>4, "comment"=>"Sends anyone to heaven, I wish I could get my mother-in-law to eat it!", "author"=>"Paul McVites", "date"=>"2014-09-05T17:57:28.556Z"}, {"id"=>48, "rating"=>3, "comment"=>"Eat it, just eat it!", "author"=>"Michael Jaikishan", "date"=>"2015-02-13T17:57:28.556Z"}, {"id"=>49, "rating"=>4, "comment"=>"Ultimate, Reaching for the stars!", "author"=>"Ringo Starry", "date"=>"2013-12-02T17:57:28.556Z"}, {"id"=>50, "rating"=>2, "comment"=>"It's your birthday, we're gonna party!", "author"=>"25 Cent", "date"=>"2011-12-02T17:57:28.556Z"}, {"id"=>51, "rating"=>4, "comment"=>"great dish", "author"=>"Jogesh", "date"=>"2017-10-30T05:03:39.656Z"}, {"author"=>"JANE7777", "rating"=>3, "comment"=>"COMMENT7777", "date"=>"2017-11-12T12:58:12.555Z"}], "dish"=>{"id"=>"9", "name"=>"Uthappizza", "image"=>"images/uthappizza.png", "category"=>"mains", "label"=>"Hot", "price"=>"4.99", "featured"=>true, "description"=>"A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.", "created_at"=>"2017-11-01T04:30:09.407Z"}}
  Dish Load (1.0ms)  SELECT  "dishes".* FROM "dishes" WHERE "dishes"."id" = $1 LIMIT $2  [["id", 9], ["LIMIT", 1]]

[25, 34] in C:/apps/railsApi/app/controllers/dishes_controller.rb
   25:   end
   26:
   27:   # PATCH/PUT /dishes/1
   28:   def update
   29:     byebug
=> 30:     if @dish.update(dish_params)
   31:       render json: @dish
   32:     else
   33:       render json: @dish.errors, status: :unprocessable_entity
   34:     end
(byebug) params
<ActionController::Parameters {"id"=>"9", "name"=>"Uthappizza", "image"=>"images/uthappizza.png", "category"=>"mains", "label"=>"Hot", "price"=>"4.99", "featured"=>true, "description"=>"A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.", "created_at"=>"2017-11-01T04:30:09.407Z", "comments"=>[{"id"=>46, "rating"=>5, "comment"=>"Imagine all the eatables, living in conFusion!", "author"=>"John Lemon", "date"=>"2012-10-16T17:57:28.556Z"}, {"id"=>47, "rating"=>4, "comment"=>"Sends anyone to heaven, I wish I could get my mother-in-law to eat it!", "author"=>"Paul McVites", "date"=>"2014-09-05T17:57:28.556Z"}, {"id"=>48, "rating"=>3, "comment"=>"Eat it, just eat it!", "author"=>"Michael Jaikishan", "date"=>"2015-02-13T17:57:28.556Z"}, {"id"=>49, "rating"=>4, "comment"=>"Ultimate, Reaching for the stars!", "author"=>"Ringo Starry", "date"=>"2013-12-02T17:57:28.556Z"}, {"id"=>50, "rating"=>2, "comment"=>"It's your birthday, we're gonna party!", "author"=>"25 Cent", "date"=>"2011-12-02T17:57:28.556Z"}, {"id"=>51, "rating"=>4, "comment"=>"great dish", "author"=>"Jogesh", "date"=>"2017-10-30T05:03:39.656Z"}, {"author"=>"JANE7777", "rating"=>3, "comment"=>"COMMENT7777", "date"=>"2017-11-12T12:58:12.555Z"}], "controller"=>"dishes", "action"=>"update", "dish"=>{"id"=>9, "name"=>"Uthappizza", "image"=>"images/uthappizza.png", "category"=>"mains", "label"=>"Hot", "price"=>"4.99", "featured"=>true, "description"=>"A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.", "created_at"=>"2017-11-01T04:30:09.407Z"}} permitted: false>
(byebug) c
Unpermitted parameters: :id, :created_at
   (0.0ms)  BEGIN
   (0.0ms)  COMMIT
[active_model_serializers]   Comment Load (0.0ms)  SELECT "comments".* FROM "comments" WHERE "comments"."dish_id" = $1  [["dish_id", 9]]
[active_model_serializers] Rendered DishSerializer with ActiveModelSerializers::Adapter::Attributes (31.29ms)
Completed 200 OK in 1901725ms (Views: 37.5ms | ActiveRecord: 5.0ms)

Client-side models

The Dish model has Comment[] as one of the members. When a new comment is added via the form the comment is push to dish.comments array before sending the Dish object to the Rails API back-end.

Comment model in client side

export class Comment {
    rating: number;
    comment: string;
    author: string;
    date: string;
}

Post model in client side

import { Comment } from './comment';
export class Dish {
  id: number;
  name: string;
  image: string;
  category: string;
  label: string;
  price: string;
  featured: boolean;
  description: string;
  comments: Comment[];
}

Body:
I’d recommend you use the Comments controller and form a nested route to be RESTful.

Firstly, POST the request, including the dish_id to /comments. You’re trying to create a Comment, not update the Dish.

Secondly, form the nested route:
/dishes/:dish_id/comments

Here’s a guide to nesting resources like this: http://guides.rubyonrails.org/routing.html#nested-resources

The reason for your error is that you’ve broken the expected parameter structure. For a PUT your params should be:

{
   id: <record to update>,
   dish: {
      name: “blah”,
      comments: [{...},{...}]
   }
 }

Again, I really recommend you don’t PUT to Dish if you just want to add a Comment. For instance: the above would be desired to replace all comments on the Dish! If you’re creating a record, create that record, don’t update it’s parent.

If you wanted to update the Dish when a new Comment is added you can add a callback to the Comment model on create or do it in the Comment create controller action.


问:
First byte is not printed when using lseek
I am trying to output the content of a file using system calls. The code is working nice until we have a file that contains only one line. in that case, the output is the line without the first char. Where does this char get lost?

```<code>ssize_t rres,wres;
char buff[1];
off_t offset;
int fd = open("tester.txt",O_CREAT | O_RDWR , 0664 );
int line_count = 5;
for(count = 0;line_count != 0;count--){
    offset = lseek(fd, count, SEEK_END);
    rres = read(fd,buff,1);
    if(rres < 0){
        return -1;
    }
    if(*buff =='\n') line_count--;

}

count *= -1; // get abs value of bytes
count++;
while(count--){
    wres = write(STDOUT_FILENO,buff,read(fd, buff,1)); // output
}
</code>```

I am trying to output the last 5 lines of a file. But if I have less than 5 lines, the first char is not outputed.

答:
The for loop is reading a character from the file before it ends. If there are at least 5 lines, it reads a newline the last time, and then the rest of the code starts reading from after that newline.

But if it gets to the beginning of the file without finding 5 newlines, the last read() reads the first character of the file, and the rest of the code starts reading from after that.

When *buff != '\n' you need to print that character first.

```<code>if (*buff != '\n') {
    write(STDOUT_FILENO, buff, 1);
}
count *= -1; // get abs value of bytes
count++;
while(count--){
    wres = write(STDOUT_FILENO,buff,read(fd, buff,1)); // output
}
</code>```

Body:
I am trying to output the content of a file using system calls. The code is working nice until we have a file that contains only one line. in that case, the output is the line without the first char. Where does this char get lost?

ssize_t rres,wres;
char buff[1];
off_t offset;
int fd = open("tester.txt",O_CREAT | O_RDWR , 0664 );
int line_count = 5;
for(count = 0;line_count != 0;count--){
    offset = lseek(fd, count, SEEK_END);
    rres = read(fd,buff,1);
    if(rres < 0){
        return -1;
    }
    if(*buff =='\n') line_count--;

}

count *= -1; // get abs value of bytes
count++;
while(count--){
    wres = write(STDOUT_FILENO,buff,read(fd, buff,1)); // output
}

I am trying to output the last 5 lines of a file. But if I have less than 5 lines, the first char is not outputed.

Body:
The for loop is reading a character from the file before it ends. If there are at least 5 lines, it reads a newline the last time, and then the rest of the code starts reading from after that newline.

But if it gets to the beginning of the file without finding 5 newlines, the last read() reads the first character of the file, and the rest of the code starts reading from after that.

When *buff != '\n' you need to print that character first.

if (*buff != '\n') {
    write(STDOUT_FILENO, buff, 1);
}
count *= -1; // get abs value of bytes
count++;
while(count--){
    wres = write(STDOUT_FILENO,buff,read(fd, buff,1)); // output
}


问:
Get Google Assistant Action to respond to "Quit" or "Cancel"
I've tried to follow the documentation about App Exit handling, but it doesn't seem to be working correctly. (See the screen shot of my Intent below).

When I do it this way, it seems to resort to my Default Fallback Intent, although it does indicate that the resolvedQuery is actions_intent_CANCEL, which should be correct. (See the JSON body below.)

Am I doing something wrong, or is the documentation wrong?

Intent trying to handle it:

JSON Body:

```<code>
{
    "originalRequest": {
        "source": "google",
        "version": "2",
        "data": {
            "isInSandbox": true,
            "surface": {
                "capabilities": [
                    {
                        "name": "actions.capability.AUDIO_OUTPUT"
                    },
                    {
                        "name": "actions.capability.SCREEN_OUTPUT"
                    }
                ]
            },
            "inputs": [
                {
                    "rawInputs": [
                        {}
                    ],
                    "intent": "actions.intent.CANCEL"
                }
            ],
            "user": {
                "locale": "en-US",
                "userId": "AETml1QP6omTPEXBfrOBdvNlwHxY"
            },
            "conversation": {
                "conversationId": "1509314271837",
                "type": "ACTIVE",
                "conversationToken": "[]"
            },
            "availableSurfaces": [
                {
                    "capabilities": [
                        {
                            "name": "actions.capability.AUDIO_OUTPUT"
                        },
                        {
                            "name": "actions.capability.SCREEN_OUTPUT"
                        }
                    ]
                }
            ]
        }
    },
    "id": "bbd363aa-f555-4543-a748-294751194fa9",
    "timestamp": "2017-10-29T21:58:00.691Z",
    "lang": "en-us",
    "result": {
        "source": "agent",
        "resolvedQuery": "actions_intent_CANCEL",
        "speech": "",
        "action": "input.unknown",
        "actionIncomplete": false,
        "parameters": {},
        "contexts": [
            {
                "name": "actions_intent_cancel",
                "parameters": {},
                "lifespan": 0
            },
            {
                "name": "actions_capability_screen_output",
                "parameters": {},
                "lifespan": 0
            },
            {
                "name": "actions_capability_audio_output",
                "parameters": {},
                "lifespan": 0
            }
        ],
        "metadata": {
            "intentId": "25f6e14b-a92c-479b-8943-76c4b6914579",
            "webhookUsed": "true",
            "webhookForSlotFillingUsed": "false",
            "nluResponseTime": 2,
            "intentName": "Default Fallback Intent"
        },
        "fulfillment": {
            "speech": "I'm sorry. I didn't quite grasp what you just said.",
            "messages": [
                {
                    "type": 0,
                    "id": "535c3b80-f13d-4b61-8c1d-bb58fa3f5e44",
                    "speech": "I'm a bit confused by that last part."
                }
            ]
        },
        "score": 1
    },
    "status": {
        "code": 200,
        "errorType": "success"
    },
    "sessionId": "1509314271837"
}
</code>```

答:
In addition to the steps in the documentation, I found that I had to tell the simulator to update to the most recent version!

Here is my video outlining the steps I took.
https://www.youtube.com/watch?v=ZvZDokjhUIY

Body:
I've tried to follow the documentation about App Exit handling, but it doesn't seem to be working correctly. (See the screen shot of my Intent below).

When I do it this way, it seems to resort to my Default Fallback Intent, although it does indicate that the resolvedQuery is actions_intent_CANCEL, which should be correct. (See the JSON body below.)

Am I doing something wrong, or is the documentation wrong?

Intent trying to handle it:

JSON Body:

{
    "originalRequest": {
        "source": "google",
        "version": "2",
        "data": {
            "isInSandbox": true,
            "surface": {
                "capabilities": [
                    {
                        "name": "actions.capability.AUDIO_OUTPUT"
                    },
                    {
                        "name": "actions.capability.SCREEN_OUTPUT"
                    }
                ]
            },
            "inputs": [
                {
                    "rawInputs": [
                        {}
                    ],
                    "intent": "actions.intent.CANCEL"
                }
            ],
            "user": {
                "locale": "en-US",
                "userId": "AETml1QP6omTPEXBfrOBdvNlwHxY"
            },
            "conversation": {
                "conversationId": "1509314271837",
                "type": "ACTIVE",
                "conversationToken": "[]"
            },
            "availableSurfaces": [
                {
                    "capabilities": [
                        {
                            "name": "actions.capability.AUDIO_OUTPUT"
                        },
                        {
                            "name": "actions.capability.SCREEN_OUTPUT"
                        }
                    ]
                }
            ]
        }
    },
    "id": "bbd363aa-f555-4543-a748-294751194fa9",
    "timestamp": "2017-10-29T21:58:00.691Z",
    "lang": "en-us",
    "result": {
        "source": "agent",
        "resolvedQuery": "actions_intent_CANCEL",
        "speech": "",
        "action": "input.unknown",
        "actionIncomplete": false,
        "parameters": {},
        "contexts": [
            {
                "name": "actions_intent_cancel",
                "parameters": {},
                "lifespan": 0
            },
            {
                "name": "actions_capability_screen_output",
                "parameters": {},
                "lifespan": 0
            },
            {
                "name": "actions_capability_audio_output",
                "parameters": {},
                "lifespan": 0
            }
        ],
        "metadata": {
            "intentId": "25f6e14b-a92c-479b-8943-76c4b6914579",
            "webhookUsed": "true",
            "webhookForSlotFillingUsed": "false",
            "nluResponseTime": 2,
            "intentName": "Default Fallback Intent"
        },
        "fulfillment": {
            "speech": "I'm sorry. I didn't quite grasp what you just said.",
            "messages": [
                {
                    "type": 0,
                    "id": "535c3b80-f13d-4b61-8c1d-bb58fa3f5e44",
                    "speech": "I'm a bit confused by that last part."
                }
            ]
        },
        "score": 1
    },
    "status": {
        "code": 200,
        "errorType": "success"
    },
    "sessionId": "1509314271837"
}