问:
ORA-02253: constraint specification not allowed here - foreign key
I'm new to this sql and I wanted to know what the problem is in this case.

"constraint specification not allowed here"
  Cause:    Constraint specification is not allowed here in the statement.

```<code>CREATE TABLE CLIENTE(
RUT VARCHAR2(10) CONSTRAINT CLIENTE_PK PRIMARY KEY,
NOMBRE VARCHAR2(20) CONSTRAINT NOMBRE_CLIENTE NOT NULL,
APELLIDOP VARCHAR2(30) CONSTRAINT APELLIDOP_CLIENTE NOT NULL,
APELLIDOM VARCHAR2(30) CONSTRAINT APPELIDOM_CLIENTE NOT NULL,
DIRECCION VARCHAR2(100) CONSTRAINT DIRECCION_CLIENTE NOT NULL,
TELEFONO NUMBER(8) CONSTRAINT TELEFONO_CLIENTE NOT NULL,
EMAIL VARCHAR2(255) CONSTRAINT EMAIL_CLIENTE NOT NULL,
FECHA_NACIMIENTO DATE CONSTRAINT FECHA_NACIMIENTO_CLIENTE NOT NULL,
SEXO CHAR(1) CONSTRAINT SEXO_CLIENTE NOT NULL,
COD_CIUDAD NUMBER(3) CONSTRAINT CLIENTE_CIUDAD_FK FOREIGN KEY (COD_CIUDAD)
REFERENCES CIUDAD (COD_CIUDAD)
);
</code>```

答:
you must seperate the constraint from the column declaration

Just use the following command

```<code>CREATE TABLE CLIENTE(
RUT VARCHAR2(10) CONSTRAINT CLIENTE_PK PRIMARY KEY,
NOMBRE VARCHAR2(20) CONSTRAINT NOMBRE_CLIENTE NOT NULL,
APELLIDOP VARCHAR2(30) CONSTRAINT APELLIDOP_CLIENTE NOT NULL,
APELLIDOM VARCHAR2(30) CONSTRAINT APPELIDOM_CLIENTE NOT NULL,
DIRECCION VARCHAR2(100) CONSTRAINT DIRECCION_CLIENTE NOT NULL,
TELEFONO NUMBER(8) CONSTRAINT TELEFONO_CLIENTE NOT NULL,
EMAIL VARCHAR2(255) CONSTRAINT EMAIL_CLIENTE NOT NULL,
FECHA_NACIMIENTO DATE CONSTRAINT
FECHA_NACIMIENTO_CLIENTE NOT NULL,
SEXO CHAR(1) CONSTRAINT SEXO_CLIENTE NOT NULL,
COD_CIUDAD NUMBER(3),
CONSTRAINT CLIENTE_CIUDAD_FK FOREIGN KEY (COD_CIUDAD)
REFERENCES CIUDAD (COD_CIUDAD)
);
</code>```

Body:
I'm new to this sql and I wanted to know what the problem is in this case.

"constraint specification not allowed here"
  Cause:    Constraint specification is not allowed here in the statement.

CREATE TABLE CLIENTE(
RUT VARCHAR2(10) CONSTRAINT CLIENTE_PK PRIMARY KEY,
NOMBRE VARCHAR2(20) CONSTRAINT NOMBRE_CLIENTE NOT NULL,
APELLIDOP VARCHAR2(30) CONSTRAINT APELLIDOP_CLIENTE NOT NULL,
APELLIDOM VARCHAR2(30) CONSTRAINT APPELIDOM_CLIENTE NOT NULL,
DIRECCION VARCHAR2(100) CONSTRAINT DIRECCION_CLIENTE NOT NULL,
TELEFONO NUMBER(8) CONSTRAINT TELEFONO_CLIENTE NOT NULL,
EMAIL VARCHAR2(255) CONSTRAINT EMAIL_CLIENTE NOT NULL,
FECHA_NACIMIENTO DATE CONSTRAINT FECHA_NACIMIENTO_CLIENTE NOT NULL,
SEXO CHAR(1) CONSTRAINT SEXO_CLIENTE NOT NULL,
COD_CIUDAD NUMBER(3) CONSTRAINT CLIENTE_CIUDAD_FK FOREIGN KEY (COD_CIUDAD)
REFERENCES CIUDAD (COD_CIUDAD)
);

Body:
you must seperate the constraint from the column declaration

Just use the following command

CREATE TABLE CLIENTE(
RUT VARCHAR2(10) CONSTRAINT CLIENTE_PK PRIMARY KEY,
NOMBRE VARCHAR2(20) CONSTRAINT NOMBRE_CLIENTE NOT NULL,
APELLIDOP VARCHAR2(30) CONSTRAINT APELLIDOP_CLIENTE NOT NULL,
APELLIDOM VARCHAR2(30) CONSTRAINT APPELIDOM_CLIENTE NOT NULL,
DIRECCION VARCHAR2(100) CONSTRAINT DIRECCION_CLIENTE NOT NULL,
TELEFONO NUMBER(8) CONSTRAINT TELEFONO_CLIENTE NOT NULL,
EMAIL VARCHAR2(255) CONSTRAINT EMAIL_CLIENTE NOT NULL,
FECHA_NACIMIENTO DATE CONSTRAINT
FECHA_NACIMIENTO_CLIENTE NOT NULL,
SEXO CHAR(1) CONSTRAINT SEXO_CLIENTE NOT NULL,
COD_CIUDAD NUMBER(3),
CONSTRAINT CLIENTE_CIUDAD_FK FOREIGN KEY (COD_CIUDAD)
REFERENCES CIUDAD (COD_CIUDAD)
);


来源: stackexchange

问:
Using directive and Partial Specialization
I have a templatized interface class, with a couple of implemented methods and a couple of virtual ones.

I need to specialize it in order to modify the signature of some methods, but others would remain the same.

Is there a way to bring the methods that remain the same back from the original template, either via using directive, by directly calling back to them or in another way, or I must copy/paste every single method back into the specialization?

```<code>template <typename T>
struct X {
    void faa(T t) const { std::cout << t << '\n'; }
    void foo() const { std::cout << "foo\n"; }
};

template <>
struct X<void> {
    void faa() const { std::cout << "none\n"; }

    // Something along these lines
    // using X<T>::foo;
    // void foo() const { X<T>::foo(); }
};
</code>```

答:
Seems so. You can't get the functions in X with different signatures using using directives. There is a better workaround than copying everything from the template to the specialization. You can use a "common base class".

```<code>template <typename T>
struct X_base {
    void foo() const { std::cout << "foo\n"; }
};

template <typename T>
struct X : public X_base<T> {
    void faa(T t) const { std::cout << t << '\n'; }
};

template <>
struct X<void> : public X_base<void> {
    void faa() const { std::cout << "none\n"; }
};
</code>```

In this way, X<void>::foo acts just like X_base<void>::foo, while X<T>::faa and X<void>::faa do not interfere with each other.

ContentLicense: CC BY-SA 3.0

Body:
I have a templatized interface class, with a couple of implemented methods and a couple of virtual ones.

I need to specialize it in order to modify the signature of some methods, but others would remain the same.

Is there a way to bring the methods that remain the same back from the original template, either via using directive, by directly calling back to them or in another way, or I must copy/paste every single method back into the specialization?

template <typename T>
struct X {
    void faa(T t) const { std::cout << t << '\n'; }
    void foo() const { std::cout << "foo\n"; }
};

template <>
struct X<void> {
    void faa() const { std::cout << "none\n"; }

    // Something along these lines
    // using X<T>::foo;
    // void foo() const { X<T>::foo(); }
};

Body:
Seems so. You can't get the functions in X with different signatures using using directives. There is a better workaround than copying everything from the template to the specialization. You can use a "common base class".

template <typename T>
struct X_base {
    void foo() const { std::cout << "foo\n"; }
};

template <typename T>
struct X : public X_base<T> {
    void faa(T t) const { std::cout << t << '\n'; }
};

template <>
struct X<void> : public X_base<void> {
    void faa() const { std::cout << "none\n"; }
};

In this way, X<void>::foo acts just like X_base<void>::foo, while X<T>::faa and X<void>::faa do not interfere with each other.


问:
While clicking on tab i need to load particular component in angular2
I am trying to load components in tab. while clicking on particular tab i need to load the particular component.But it's loading all component while navigating to that component.

.html

```<code><p-tabView orientation="left" (onChange)="onTabChange($event)">
       <p-tabPanel *ngFor="let item of items" style="border: solid 1px; padding: 20px;margin: 20px;" [selected]="activeTabIndex==i">
              <strong> When you click here,
              I should load the <span style="color:red"> {{item.name}} </span>
              component below</strong> <br />

              <ng-container *ngComponentOutlet="childmap[item.name] "></ng-container>

          <br />
        </p-tabPanel>
</p-tabView>
</code>```

.ts

```<code>@Component({
  selector: 'my-app',
  templateUrl:'dashboard.html'
  `
})
export class App {
 activeTabIndex: number = 0;

childmap = {
        'slider': sliderComponent,
        'user': usersComponent,
        'alert danger': AlertDangerComponent
         }

items:Array<any> = [
    {
      name: 'slider'
    },
    {
      name: 'user'
    },
    {
      name: 'alert danger'
    }

      ]
 onTabChange(event: any) {
        this.activeTabIndex = event.index;
    }
  }
</code>```

答:
There are many solution for this kind of things. Please What I have done by using ngComponentOutlet.

Here is the tab-container:

```<code>import {Component, Input} from '@angular/core'
import {TabContentAlternativeComponent} from './tab-content-alternative.component'
import {BasicContent} from './basic-content'

@Component({
  selector: 'tab',
  template: ''
})
export class TabComponent {
  @Input() title: string;
  @Input() contentRef: BasicContent;
  active = false;
}
</code>```

This is a very simple component which knows its own tab name, an active state and the body component reference which should be loaded when somebody selects the tab.

Then we create several body components which will be loaded dynamically:

```<code>export class BasicContent {

}
</code>```

Component 1

```<code>  import {Component, Input, OnInit} from '@angular/core'
import {BasicContent} from './basic-content'

@Component({
  selector: 'tab-content',
  template: `
      <p>Hey</p>
  `,
})
export class TabContentComponent extends BasicContent {
}
</code>```

Component 2

```<code>   import {Component, Input} from '@angular/core'
import {BasicContent} from './basic-content'

@Component({
  selector: 'tab-content-alternative',
  template: `
      <p>Hey, this is an alternative content</p>
  `,
})
export class TabContentAlternativeComponent extends BasicContent {
}
</code>```

Here is the tabs-container component with tabs rendering and an empty placeholder for dynamic body components:

```<code>    import {AfterContentInit, Component, ContentChildren, QueryList} from '@angular/core'
import {TabComponent} from './tab.component'
import {BasicContent} from 'basic-content'

import 'rxjs/Rx';
import {Observable, BehaviorSubject} from 'rxjs/Rx';

@Component({
  selector: 'tab-container',
  template: `
    <div class="tab-header">
      <div class="tab" *ngFor="let tab of tabs" (click)="selectTab(tab)" [class.active]="tab.active">{{tab.title}}</div>
    </div>

    <div class="tab-content">
      <ng-container *ngComponentOutlet="content | async"></ng-container>
    </div>
  `,
})
export class TabContainerComponent implements AfterContentInit {
  @ContentChildren(TabComponent) tabs: QueryList<TabComponent>;

  private contentSbj = new BehaviorSubject<BasicContent>(null);
  content = this.contentSbj.asObservable();

  ngAfterContentInit() {
    const activeTabs = this.tabs.filter((tab) => tab.active);
    if (activeTabs.length === 0) {
      this.selectTab(this.tabs.first);
    }
  }

  selectTab(tab: TabComponent) {
    this.tabs.toArray().forEach(tab => tab.active = false);
    tab.active = true;
    this.contentSbj.next(tab.contentRef);
  }
}
</code>```

TitleMapping

```<code>import {TabContentComponent} from './tab-content.component';
import {TabContentAlternativeComponent} from './tab-content-alternative.component';

interface TitleMapping {
  title: string;
  contentComponent: BasicContent;
}

export const allTabs: TitleMapping[] = [
  {title: "Tab 1", contentComponent: TabContentComponent},
  {title: "Tab 2", contentComponent: TabContentAlternativeComponent},
  {title: "Tab 3", contentComponent: TabContentComponent}
]
</code>```

And this is how it can be used in some parent component:

```<code>import {TabContentComponent} from './tab/tab-content.component'
import {TabContentAlternativeComponent} from './tab/tab-content-alternative.component'

@Component({
  selector: 'my-app',
  template: `
    <tab-container>
      <tab title="Tab 1" [contentRef]="normalContent"></tab>
      <tab title="Tab 2" [contentRef]="alternativeContent"></tab>
    </tab-container>
  `,
})
export class App {
  normalContent = TabContentComponent;
  alternativeContent = TabContentAlternativeComponent;
}
</code>```

Here is working Plunkr

I have used this with my projects and working fine as your requirement.

Body:
I am trying to load components in tab. while clicking on particular tab i need to load the particular component.But it's loading all component while navigating to that component.

.html

               When you click here,
              I should load the  {{item.name}}
              component below

              <ng-container *ngComponentOutlet="childmap[item.name] "></ng-container>

.ts

@Component({
  selector: 'my-app',
  templateUrl:'dashboard.html'
  `
})
export class App {
 activeTabIndex: number = 0;

childmap = {
        'slider': sliderComponent,
        'user': usersComponent,
        'alert danger': AlertDangerComponent
         }

items:Array<any> = [
    {
      name: 'slider'
    },
    {
      name: 'user'
    },
    {
      name: 'alert danger'
    }

      ]
 onTabChange(event: any) {
        this.activeTabIndex = event.index;
    }
  }

Body:
There are many solution for this kind of things. Please What I have done by using ngComponentOutlet.

Here is the tab-container:

import {Component, Input} from '@angular/core'
import {TabContentAlternativeComponent} from './tab-content-alternative.component'
import {BasicContent} from './basic-content'

@Component({
  selector: 'tab',
  template: ''
})
export class TabComponent {
  @Input() title: string;
  @Input() contentRef: BasicContent;
  active = false;
}

This is a very simple component which knows its own tab name, an active state and the body component reference which should be loaded when somebody selects the tab.

Then we create several body components which will be loaded dynamically:

export class BasicContent {

}

Component 1

  import {Component, Input, OnInit} from '@angular/core'
import {BasicContent} from './basic-content'

@Component({
  selector: 'tab-content',
  template: `
      <p>Hey</p>
  `,
})
export class TabContentComponent extends BasicContent {
}

Component 2

   import {Component, Input} from '@angular/core'
import {BasicContent} from './basic-content'

@Component({
  selector: 'tab-content-alternative',
  template: `
      <p>Hey, this is an alternative content</p>
  `,
})
export class TabContentAlternativeComponent extends BasicContent {
}

Here is the tabs-container component with tabs rendering and an empty placeholder for dynamic body components:

    import {AfterContentInit, Component, ContentChildren, QueryList} from '@angular/core'
import {TabComponent} from './tab.component'
import {BasicContent} from 'basic-content'

import 'rxjs/Rx';
import {Observable, BehaviorSubject} from 'rxjs/Rx';

@Component({
  selector: 'tab-container',
  template: `
    <div class="tab-header">
      <div class="tab" *ngFor="let tab of tabs" (click)="selectTab(tab)" [class.active]="tab.active">{{tab.title}}</div>
    </div>

    <div class="tab-content">
      <ng-container *ngComponentOutlet="content | async"></ng-container>
    </div>
  `,
})
export class TabContainerComponent implements AfterContentInit {
  @ContentChildren(TabComponent) tabs: QueryList<TabComponent>;

  private contentSbj = new BehaviorSubject<BasicContent>(null);
  content = this.contentSbj.asObservable();

  ngAfterContentInit() {
    const activeTabs = this.tabs.filter((tab) => tab.active);
    if (activeTabs.length === 0) {
      this.selectTab(this.tabs.first);
    }
  }

  selectTab(tab: TabComponent) {
    this.tabs.toArray().forEach(tab => tab.active = false);
    tab.active = true;
    this.contentSbj.next(tab.contentRef);
  }
}

TitleMapping

import {TabContentComponent} from './tab-content.component';
import {TabContentAlternativeComponent} from './tab-content-alternative.component';

interface TitleMapping {
  title: string;
  contentComponent: BasicContent;
}

export const allTabs: TitleMapping[] = [
  {title: "Tab 1", contentComponent: TabContentComponent},
  {title: "Tab 2", contentComponent: TabContentAlternativeComponent},
  {title: "Tab 3", contentComponent: TabContentComponent}
]

And this is how it can be used in some parent component:

import {TabContentComponent} from './tab/tab-content.component'
import {TabContentAlternativeComponent} from './tab/tab-content-alternative.component'

@Component({
  selector: 'my-app',
  template: `
    <tab-container>
      <tab title="Tab 1" [contentRef]="normalContent"></tab>
      <tab title="Tab 2" [contentRef]="alternativeContent"></tab>
    </tab-container>
  `,
})
export class App {
  normalContent = TabContentComponent;
  alternativeContent = TabContentAlternativeComponent;
}

Here is working Plunkr

I have used this with my projects and working fine as your requirement.


问:
Image upload in a database directory
i am little bit problem in Image upload in a database directory.image upload my avatar folder and can't show my page becouse problem is that in database id, username table show my data but imagelocation table can't show my directory.please any one told me that, what is the problem in my code and correct it specify line

upload.php

```<code><?php

 include("connecton.php");

 $_SESSION['username']="kyle";

 $username = $_SESSION['username'];

  if($_POST['submit'])
  {

      //get file attribute

      $name = $_FILES['myfile']['name'];
      $tmp_name = $_FILES['myfile']['tmp_name'];

      if($name)
      {

          //start upload process

           $location = "avatars/$name";
           move_uploaded_file($tmp_name,$location);

           $query = mysql_query("UPDATE users SET imagelocation='$location' WHERE username='$username'");

           die("Your avatar has been uploaded! <a href='view.php'>HOme</a>");
      }
      else
       die("Please select a file");

  }

 echo "Welcome, ".$username."!<p>";

 echo "Upload Your Image:

<form action='upload.php' method='POST' enctype='multipart/form-data'>

  File: <input type='file' name='myfile'> <input type='submit' name='submit' value='upload!'>

  </form>

 ";

?>
</code>```

view.php

```<code><?php

   include("connecton.php");

   $username = $_SESSION['username'];

   $query = mysql_query("SELECT * FROM users WHERE username='$username'");

   if (mysql_num_rows($query)==0)

   die ("User not found");
   else
   {

       $row = mysql_fetch_assoc($query);
       $location = $row['imagelocation'];

       echo "<img src='$location' width='100' height='100'>";

   }

?>
</code>```

答:
a) You do not check if the upload succeeded. At least do something like:

```<code>if ($_FILES['myfile']['error'] === UPLOAD_ERR_OK) {
     ... upload went ok
}
</code>```

b) You're using the original user's filename to store it on your server, and you do not sanitize the filename. THere is NOTHING to prevent a malicious user from setting a filename such as ../../../../../../../../../some/critical/system/file, which your script will then happily overwrite.

c) You do not check of the move_uploaded_file() succeeded:

```<code>if (!move_uploaded_file(...)) {
     die("Move failed!")
}
</code>```

d) You do not check if the database query succeeded:

```<code>$stmt = mysql_query(...)
if ($stmt === FALSE) {
     die("MySQL query failed: " . mysql_error());
}
</code>```

e) You've not sanitized the $filename, so again a malicious user can subvert your query and directly attack your database with SQL injection attacks.

f) You're doing a SELECT * FROM... to get the image's location. Are you sure your table contains an 'imagelocation' row? YOU didn't check if the insert query succeeded using the same row, so maybe you've got a typo and it's really "imglocation" instead.

ContentLicense: CC BY-SA 2.5

Title: Image upload in a database directory

Body:
i am little bit problem in Image upload in a database directory.image upload my avatar folder and can't show my page becouse problem is that in database id, username table show my data but imagelocation table can't show my directory.please any one told me that, what is the problem in my code and correct it specify line

upload.php

<?php

 include("connecton.php");

 $_SESSION['username']="kyle";

 $username = $_SESSION['username'];

  if($_POST['submit'])
  {

      //get file attribute

      $name = $_FILES['myfile']['name'];
      $tmp_name = $_FILES['myfile']['tmp_name'];

      if($name)
      {

          //start upload process

           $location = "avatars/$name";
           move_uploaded_file($tmp_name,$location);

           $query = mysql_query("UPDATE users SET imagelocation='$location' WHERE username='$username'");

           die("Your avatar has been uploaded! HOme");
      }
      else
       die("Please select a file");

  }

 echo "Welcome, ".$username."!
";

 echo "Upload Your Image:

<form action='upload.php' method='POST' enctype='multipart/form-data'>

  File: <input type='file' name='myfile'> <input type='submit' name='submit' value='upload!'>

  </form>

 ";

?>

view.php

<?php

   include("connecton.php");

   $username = $_SESSION['username'];

   $query = mysql_query("SELECT * FROM users WHERE username='$username'");

   if (mysql_num_rows($query)==0)

   die ("User not found");
   else
   {

       $row = mysql_fetch_assoc($query);
       $location = $row['imagelocation'];

       echo "";

   }

?>

Body:
a) You do not check if the upload succeeded. At least do something like:

if ($_FILES['myfile']['error'] === UPLOAD_ERR_OK) {
     ... upload went ok
}

b) You're using the original user's filename to store it on your server, and you do not sanitize the filename. THere is NOTHING to prevent a malicious user from setting a filename such as ../../../../../../../../../some/critical/system/file, which your script will then happily overwrite.

c) You do not check of the move_uploaded_file() succeeded:

if (!move_uploaded_file(...)) {
     die("Move failed!")
}

d) You do not check if the database query succeeded:

$stmt = mysql_query(...)
if ($stmt === FALSE) {
     die("MySQL query failed: " . mysql_error());
}

e) You've not sanitized the $filename, so again a malicious user can subvert your query and directly attack your database with SQL injection attacks.

f) You're doing a SELECT * FROM... to get the image's location. Are you sure your table contains an 'imagelocation' row? YOU didn't check if the insert query succeeded using the same row, so maybe you've got a typo and it's really "imglocation" instead.


问:
Django queryset NOT INTERSECT for 2 models using postgres
I have a Django app, and I am trying to find out Employee that was NOT in Attendance 2017-12-05. I am trying to find out a queryset to accomplish this.

The following are the details of the model, records, and the outcome I am trying to accomplish.

I have 2 models:

```<code>class Employee(models.Model):
    fullname = models.CharField(max_length=30, blank=False)

class Attendance(models.Model):
    CHECKIN = 1
    CHECKOUT = 2
    ATTENDANCE_TYPE_CHOICES = (
        (CHECKIN, "Check In"),
        (CHECKOUT, "Check Out"),
    )
    employee = models.ForeignKey(Employee)
    activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN)
    timestamp = models.DateTimeField(auto_now_add=True)
</code>```

Assuming I have the records below:

```<code>Employee
{"id":1, "employee":"michael jackson",
"id":2, "fullname":"mariah carey",
"id":3, "fullname":"taylor swift",
"id":4, "fullname":"selena gomez"}

Attendance
{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13",
"id":3, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13",
"id":4, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13",
"id":5, "employee": 3,"activity_type": 1, timestamp: "2017-12-06 08:08"}
</code>```

This is the intended output I am trying to accomplish:

For the date 2017-12-05, this employee was not in attendance (meaning there was no record in Attendance for 2017-12-05)

```<code>{"id":3, "fullname":"taylor swift",
"id":4, "fullname":"selena gomez"}
</code>```

What is the queryset to list out the employee that is not in attendance on a particular date 2017-12-05 ? I believe its an intersect and doing a NOT with the employee.

答:
You can do this with a simple exclude() query:

```<code>from datetime import date

today = date.today()

Employee.objects.exclude(attendance__timestamp__date=today)
</code>```

This will give you all the employees where there was no attendance recorded for that date.

See this section of the documentation for explanation of how to create the lookup.

Body:
I have a Django app, and I am trying to find out Employee that was NOT in Attendance 2017-12-05. I am trying to find out a queryset to accomplish this.

The following are the details of the model, records, and the outcome I am trying to accomplish.

I have 2 models:

class Employee(models.Model):
    fullname = models.CharField(max_length=30, blank=False)

class Attendance(models.Model):
    CHECKIN = 1
    CHECKOUT = 2
    ATTENDANCE_TYPE_CHOICES = (
        (CHECKIN, "Check In"),
        (CHECKOUT, "Check Out"),
    )
    employee = models.ForeignKey(Employee)
    activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN)
    timestamp = models.DateTimeField(auto_now_add=True)

Assuming I have the records below:

Employee
{"id":1, "employee":"michael jackson",
"id":2, "fullname":"mariah carey",
"id":3, "fullname":"taylor swift",
"id":4, "fullname":"selena gomez"}

Attendance
{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13",
"id":3, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13",
"id":4, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13",
"id":5, "employee": 3,"activity_type": 1, timestamp: "2017-12-06 08:08"}

This is the intended output I am trying to accomplish:

For the date 2017-12-05, this employee was not in attendance (meaning there was no record in Attendance for 2017-12-05)

{"id":3, "fullname":"taylor swift",
"id":4, "fullname":"selena gomez"}

What is the queryset to list out the employee that is not in attendance on a particular date 2017-12-05 ? I believe its an intersect and doing a NOT with the employee.

Body:
You can do this with a simple exclude() query:

from datetime import date

today = date.today()

Employee.objects.exclude(attendance__timestamp__date=today)

This will give you all the employees where there was no attendance recorded for that date.

See this section of the documentation for explanation of how to create the lookup.


问:
Converting an octal number to decimal number using char only
I am new here and new to c++ as well.

I just started my first year at school and I have been given an assignment in which one of the questions is to convert an octal number to a decimal number using Char only.

The task is to create a program that receives chars from the user and where the length of the number is not known in advance. The user should press '\t' in order to start calculating to a decimal number.

I don't really understand how it works.Because if I code a simple algorithm such as:

```<code>char ch;
cin<<ch;

cout>>ch>>endl;
</code>```

and I give it 67, it will print 6 only. That means that it reads every char separately, doesn't it?

Could someone please help me understand it by showing me the algorithm for this problem or explaining to me how char works?

Thanks a lot
Coral

答:
You will get enough info on how to read from stdin char by char.

please go through this link.
http://www.cplusplus.com/forum/articles/6046/

```<code>#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

 string input = "";

 // How to get a string/sentence with spaces
 cout << "Please enter a valid sentence (with spaces):\n>";
 getline(cin, input);
 cout << "You entered: " << input << endl << endl;

 // How to get a number.
 int myNumber = 0;

 while (true) {
   cout << "Please enter a valid number: ";
   getline(cin, input);

   // This code converts from string to number safely.
   stringstream myStream(input);
   if (myStream >> myNumber)
     break;
   cout << "Invalid number, please try again" << endl;
 }
 cout << "You entered: " << myNumber << endl << endl;

 // How to get a single char.
 char myChar  = {0};

 while (true) {
   cout << "Please enter 1 char: ";
   getline(cin, input);

   if (input.length() == 1) {
     myChar = input[0];
     break;
   }

   cout << "Invalid character, please try again" << endl;
 }
 cout << "You entered: " << myChar << endl << endl;

 cout << "All done. And without using the >> operator" << endl;

 return 0;
}
</code>```

Body:
I am new here and new to c++ as well.

I just started my first year at school and I have been given an assignment in which one of the questions is to convert an octal number to a decimal number using Char only.

The task is to create a program that receives chars from the user and where the length of the number is not known in advance. The user should press '\t' in order to start calculating to a decimal number.

I don't really understand how it works.Because if I code a simple algorithm such as:

char ch;
cin<<ch;

cout>>ch>>endl;

and I give it 67, it will print 6 only. That means that it reads every char separately, doesn't it?

Could someone please help me understand it by showing me the algorithm for this problem or explaining to me how char works?

Thanks a lot
Coral

Body:
You will get enough info on how to read from stdin char by char.

please go through this link.
http://www.cplusplus.com/forum/articles/6046/

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

 string input = "";

 // How to get a string/sentence with spaces
 cout << "Please enter a valid sentence (with spaces):\n>";
 getline(cin, input);
 cout << "You entered: " << input << endl << endl;

 // How to get a number.
 int myNumber = 0;

 while (true) {
   cout << "Please enter a valid number: ";
   getline(cin, input);

   // This code converts from string to number safely.
   stringstream myStream(input);
   if (myStream >> myNumber)
     break;
   cout << "Invalid number, please try again" << endl;
 }
 cout << "You entered: " << myNumber << endl << endl;

 // How to get a single char.
 char myChar  = {0};

 while (true) {
   cout << "Please enter 1 char: ";
   getline(cin, input);

   if (input.length() == 1) {
     myChar = input[0];
     break;
   }

   cout << "Invalid character, please try again" << endl;
 }
 cout << "You entered: " << myChar << endl << endl;

 cout << "All done. And without using the >> operator" << endl;

 return 0;
}


问:
Angular 4 Cannot read property 'push' of undefined
```<code>export interface IComments{
    comments: string;
}

export interface IReport {
   reportdesc: string;
   comnts: [IComments]
}

export interface IRecord{
   rdesc: string;
   reportcomments: [IReport]
}

In template I get a single value of IRecord using comment
<div>
<input [(ngModel)]="record.rdesc" name="rdesc">
<table>
<thead *ngFor="let d of record.reportcomments">
   <tr>
     <td>{{d.reportdesc}}</td>
  </tr>
  <tr *ngFor="let a of d.comnts">
    <td>{{a.comments}}</td>
   </tr>
</thead>
</table>
</code>```

In component I am trying to push an empty row like this

```<code>record=IRecord[]=[];

addRow(){
   this.record.reportcomments.push({
    rdes:'',
    comnts: {
         comments: ''
});
</code>```

when I call addRow() from template to push the empty row i get error

```<code>Error: TypeError: cannot read property 'push' if undefined.
</code>```

Please let me know how to fix my approach so I can add empty row.
I already checked the previous similar questions without any luck.
Thank

答:
Initialise the variable correctly like following:

```<code>let reports: [IReport] = [{}];
let record:IRecord = {rdesc: "My Report", reportcomments:reports};
</code>```

The model should define all nullable fields should be declared with ? like following:

```<code>export interface IComments{
comments: string;
}

export interface IReport {
reportdesc?: string;
comnts?: [IComments]
}

export interface IRecord{
rdesc?: string;
reportcomments?: [IReport]
}
</code>```

Body:
export interface IComments{
    comments: string;
}

export interface IReport {
   reportdesc: string;
   comnts: [IComments]
}

export interface IRecord{
   rdesc: string;
   reportcomments: [IReport]
}

In template I get a single value of IRecord using comment

<input [(ngModel)]="record.rdesc" name="rdesc">

     {{d.reportdesc}}

    {{a.comments}}

In component I am trying to push an empty row like this

record=IRecord[]=[];

addRow(){
   this.record.reportcomments.push({
    rdes:'',
    comnts: {
         comments: ''
});

when I call addRow() from template to push the empty row i get error

Error: TypeError: cannot read property 'push' if undefined.

Please let me know how to fix my approach so I can add empty row.
I already checked the previous similar questions without any luck.
Thank

Body:
Initialise the variable correctly like following:

let reports: [IReport] = [{}];
let record:IRecord = {rdesc: "My Report", reportcomments:reports};

The model should define all nullable fields should be declared with ? like following:

export interface IComments{
comments: string;
}

export interface IReport {
reportdesc?: string;
comnts?: [IComments]
}

export interface IRecord{
rdesc?: string;
reportcomments?: [IReport]
}


问:
onKeyDown for react-typeahead package, how do i use it?
I have looked through the code on Github and can't understand how to use the onKeyDown prop. The aim is that I have results which are shown like so:

And now I want the onKeyDown to highlight the results when you go through them 1 by 1. And then I need to be able to press enter to select the option.

Can anyone point me in the right direction?

I'm sorry if this is a newbie question but I just can't seem to figure out how to use this functionality. Please see the code below for this section of my app:

import React, {Component} from 'react';
import {Link} from 'react-router';
import LoginModal from '../homePage/LoginModal';
import {connect} from 'react-redux';
import {userLogout} from '../../actions/user.actions';
import $ from 'jquery';
import {Typeahead} from 'react-typeahead';
import {getPlaylists} from '../../actions/playlist.actions';
import {searchPlaylistData} from '../../helper';

class Nav extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modal:false,
      toggleNav:false
    }

    this.toggleModal = this.toggleModal.bind(this);
    this.onToggleNav = this.onToggleNav.bind(this);
    this.onClickLogout = this.onClickLogout.bind(this);
    this.keyDown = this.keyDown.bind(this);
  }

  componentDidMount() {
    this.props.getPlaylists();
//     $('.navbar-nav').on('click', function(){
//       const collapse = $('#navbar').hasClass('collapse');
//       if (collapse === true){
//         // $('#navbar').removeClass('collapse');
//         this.setState({
//           toggleNav: false
//         })
//       }
//       else{
//         // $('#navbar').addClass('collapse');
//         this.setState({
//           toggleNav:true
//         })
//       }
//     });
}
  render () {
    return (

        <button className="navbar-toggler" type="button" onClick={this.onToggleNav}>

        </button>

              <Link onClick={this.onToggleNav} className="nav-link" to={'/'}>Home</Link>

            {this.props.userProfile.role === 'admin' ?

            <Link onClick={this.onToggleNav} className="nav-link" to ={'/addPlaylist'}>Playlists</Link>

 :
            null }

              <Link onClick={this.onToggleNav} className="nav-link" to ={'/contactUs'}>Contact</Link>

            {}

            {/* <input className="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"/> */}
            {console.log(this.props.playlists)}
            <Typeahead
              defaultValue=''
              options={this.props.playlists}
              filterOption='songTitle'
              displayOption={(option) => {
                return option.songTitle;
              }}
              onKeyDown={this.keyDown}
              customClasses={{
                input: "topcoat-text-input",
                results: "results-container"
              }}
              className="form-control mr-sm-2"
              />

            {Object.keys(this.props.user).length !== 0 ?
            <button onClick={this.onClickLogout} type="button" className="btn btn-primary my-2 my-sm-0">LogOut</button> :
            <button onClick={this.toggleModal} type="button" className="btn btn-primary my-2 my-sm-0">Login</button>}

            <LoginModal show={this.state.modal} onClose={this.toggleModal} />

    )
  }

   toggleModal () {
    this.setState({
      modal: !this.state.modal,
      toggleNav: false
    });

  }

  onToggleNav () {
    this.setState({
      toggleNav: !this.state.toggleNav
    })
  }

  onClickLogout () {
    this.props.userLogout();
    this.onToggleNav();
  }

  keyDown (event, event2) {
    console.log(event);
    console.log(event2)
  }
}

function mapStateToProps (state) {
  const searchablePlaylistData = searchPlaylistData(state.playlist.playlists);
  return {
    user: state.user.user,
    userProfile: state.user.userProfile,
    playlists: searchablePlaylistData

  }
}

function mapDispatchToProps (dispatch) {
  return {
    userLogout: () => {
      dispatch(userLogout());
    },
    getPlaylists: () => {
      dispatch(getPlaylists());
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Nav);```

I have tried to see if there are any other parameters but I think its just the event which is passed in.

答:
I believe you're confused about the purpose of the onKeyDown property.

onKeyDown is fired any time any key is pressed. It sounds like you want to allow the user to hit the ▼ key and cycle through the current options, then hit enter to select one.

Thankfully, this is the default behavior of Typeahead, we just need to add some CSS to see it in action.

When the user inserts a value, Typeahead will display maxVisible results, I'm using 4 in the example below. If the user then clicks the ▼ key it will select the first item in the results. Clicking ▼ will cycle through the results. And clicking enter will select the result and insert it into the input. Without the appropriate CSS it won't be possible to see this in action though. So you'll need to use the customClasses prop and give the hover option a style so it's obvious the result is selected.

Unfortunately it's not possible to create a working example in Stackoverflow due to the need for using the react-typeahead npm module, so here's a working WebpackBin, and here's the code:

index.html

```<code><!doctype html>
<html>
  <head>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="app.css" />
  </head>
  <body>
    <div id="app"></div>
    <script src="main.js"></script>
  </body>
</html>
</code>```

main.js

```<code>import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {Typeahead} from 'react-typeahead';

class Nav extends Component {
  constructor(props) {
    super(props);
  }

  render () {
    return (
      <div className="container">
        <Typeahead
          options={[
            'Waylon Dalton',
            'Justine Henderson',
            'Abdullah Lang',
            'Marcus Cruz',
            'Thalia Cobb',
            'Mathias Little',
            'Eddie Randolph',
            'Angela Walker',
            'Lia Shelton',
            'Hadassah Hartman',
            'Joanna Shaffer',
            'Jonathon Sheppard'
          ]}
          maxVisible={4}
          defaultValue="o"
          customClasses={{
            input: "typeahead-text-input",
            results: "typeahead-list__container",
            listItem: "typeahead-list__item",
            hover: "typeahead-active",
          }}
        />
      </div>
    )
  }
}

ReactDOM.render(<Nav/>, document.getElementById("app"));
</code>```

app.css

```<code>html,
body {
  margin: 0;
  padding: 0;
  font-family: Arial;
  font-size: 18px;
}

.container {
  padding: 20px;
}

.typeahead-text-input {
  width: 100%;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border: 2px solid blue;
  font-size: 1em;
}

.typeahead-list__container {
  margin: 0;
  padding: 0;
}

.typeahead-list__item {
  list-style-type: none;
  padding: 5px 10px;
  margin: 0;
  font-size: 1em;
}

.typeahead-active {
  background: #eaeaea;
}
</code>```

Body:
I have looked through the code on Github and can't understand how to use the onKeyDown prop. The aim is that I have results which are shown like so:

And now I want the onKeyDown to highlight the results when you go through them 1 by 1. And then I need to be able to press enter to select the option.

Can anyone point me in the right direction?

I'm sorry if this is a newbie question but I just can't seem to figure out how to use this functionality. Please see the code below for this section of my app:

import React, {Component} from 'react';
import {Link} from 'react-router';
import LoginModal from '../homePage/LoginModal';
import {connect} from 'react-redux';
import {userLogout} from '../../actions/user.actions';
import $ from 'jquery';
import {Typeahead} from 'react-typeahead';
import {getPlaylists} from '../../actions/playlist.actions';
import {searchPlaylistData} from '../../helper';

class Nav extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modal:false,
      toggleNav:false
    }

    this.toggleModal = this.toggleModal.bind(this);
    this.onToggleNav = this.onToggleNav.bind(this);
    this.onClickLogout = this.onClickLogout.bind(this);
    this.keyDown = this.keyDown.bind(this);
  }

  componentDidMount() {
    this.props.getPlaylists();
//     $('.navbar-nav').on('click', function(){
//       const collapse = $('#navbar').hasClass('collapse');
//       if (collapse === true){
//         // $('#navbar').removeClass('collapse');
//         this.setState({
//           toggleNav: false
//         })
//       }
//       else{
//         // $('#navbar').addClass('collapse');
//         this.setState({
//           toggleNav:true
//         })
//       }
//     });
}
  render () {
    return (

        <button className="navbar-toggler" type="button" onClick={this.onToggleNav}>

        </button>

              <Link onClick={this.onToggleNav} className="nav-link" to={'/'}>Home</Link>

            {this.props.userProfile.role === 'admin' ?

            <Link onClick={this.onToggleNav} className="nav-link" to ={'/addPlaylist'}>Playlists</Link>

 :
            null }

              <Link onClick={this.onToggleNav} className="nav-link" to ={'/contactUs'}>Contact</Link>

            {}

            {/* <input className="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"/> */}
            {console.log(this.props.playlists)}
            <Typeahead
              defaultValue=''
              options={this.props.playlists}
              filterOption='songTitle'
              displayOption={(option) => {
                return option.songTitle;
              }}
              onKeyDown={this.keyDown}
              customClasses={{
                input: "topcoat-text-input",
                results: "results-container"
              }}
              className="form-control mr-sm-2"
              />

            {Object.keys(this.props.user).length !== 0 ?
            <button onClick={this.onClickLogout} type="button" className="btn btn-primary my-2 my-sm-0">LogOut</button> :
            <button onClick={this.toggleModal} type="button" className="btn btn-primary my-2 my-sm-0">Login</button>}

            <LoginModal show={this.state.modal} onClose={this.toggleModal} />

    )
  }

   toggleModal () {
    this.setState({
      modal: !this.state.modal,
      toggleNav: false
    });

  }

  onToggleNav () {
    this.setState({
      toggleNav: !this.state.toggleNav
    })
  }

  onClickLogout () {
    this.props.userLogout();
    this.onToggleNav();
  }

  keyDown (event, event2) {
    console.log(event);
    console.log(event2)
  }
}

function mapStateToProps (state) {
  const searchablePlaylistData = searchPlaylistData(state.playlist.playlists);
  return {
    user: state.user.user,
    userProfile: state.user.userProfile,
    playlists: searchablePlaylistData

  }
}

function mapDispatchToProps (dispatch) {
  return {
    userLogout: () => {
      dispatch(userLogout());
    },
    getPlaylists: () => {
      dispatch(getPlaylists());
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Nav);

I have tried to see if there are any other parameters but I think its just the event which is passed in.

Body:
I believe you're confused about the purpose of the onKeyDown property.

onKeyDown is fired any time any key is pressed. It sounds like you want to allow the user to hit the ▼ key and cycle through the current options, then hit enter to select one.

Thankfully, this is the default behavior of Typeahead, we just need to add some CSS to see it in action.

When the user inserts a value, Typeahead will display maxVisible results, I'm using 4 in the example below. If the user then clicks the ▼ key it will select the first item in the results. Clicking ▼ will cycle through the results. And clicking enter will select the result and insert it into the input. Without the appropriate CSS it won't be possible to see this in action though. So you'll need to use the customClasses prop and give the hover option a style so it's obvious the result is selected.

Unfortunately it's not possible to create a working example in Stackoverflow due to the need for using the react-typeahead npm module, so here's a working WebpackBin, and here's the code:

index.html

<!doctype html>
<html>
  <head>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="app.css" />
  </head>
  <body>
    <div id="app"></div>
    <script src="main.js"></script>
  </body>
</html>

main.js

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {Typeahead} from 'react-typeahead';

class Nav extends Component {
  constructor(props) {
    super(props);
  }

  render () {
    return (
      <div className="container">
        <Typeahead
          options={[
            'Waylon Dalton',
            'Justine Henderson',
            'Abdullah Lang',
            'Marcus Cruz',
            'Thalia Cobb',
            'Mathias Little',
            'Eddie Randolph',
            'Angela Walker',
            'Lia Shelton',
            'Hadassah Hartman',
            'Joanna Shaffer',
            'Jonathon Sheppard'
          ]}
          maxVisible={4}
          defaultValue="o"
          customClasses={{
            input: "typeahead-text-input",
            results: "typeahead-list__container",
            listItem: "typeahead-list__item",
            hover: "typeahead-active",
          }}
        />
      </div>
    )
  }
}

ReactDOM.render(<Nav/>, document.getElementById("app"));

app.css

html,
body {
  margin: 0;
  padding: 0;
  font-family: Arial;
  font-size: 18px;
}

.container {
  padding: 20px;
}

.typeahead-text-input {
  width: 100%;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border: 2px solid blue;
  font-size: 1em;
}

.typeahead-list__container {
  margin: 0;
  padding: 0;
}

.typeahead-list__item {
  list-style-type: none;
  padding: 5px 10px;
  margin: 0;
  font-size: 1em;
}

.typeahead-active {
  background: #eaeaea;
}


问:
Uva's 3n+1 problem
I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far. </p>

```<code>   import java.io.*;

public class NewClass{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

        int maxCounter= 0;
        int input;

        int lowerBound;
        int upperBound;
        int counter;
        int numberOfCycles;
        int maxCycles= 0;
        int lowerInt;
        BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
        String line = consoleInput.readLine();
        String [] splitted =  line.split(" ");

        lowerBound = Integer.parseInt(splitted[0]);
        upperBound = Integer.parseInt(splitted[1]);

        int [] recentlyused =  new int[1000001];

if (lowerBound > upperBound )
{
    int h = upperBound;
    upperBound = lowerBound;
    lowerBound = h;

}
lowerInt = lowerBound;
        while (lowerBound <= upperBound)
        {
            counter = lowerBound;
            numberOfCycles = 0;

            if (recentlyused[counter] == 0)
            {
                while ( counter != 1 )
                {

                        if (recentlyused[counter] != 0)
                        {

                        numberOfCycles = recentlyused[counter] + numberOfCycles;
                        counter = 1;
                        }
                        else
                        {
                            if (counter % 2 == 0)
                            {
                            counter = counter /2;
                            }
                            else
                            {
                            counter = 3*counter + 1;
                            }
                            numberOfCycles++;
                        }

                }
            }
            else
            {

            numberOfCycles = recentlyused[counter] + numberOfCycles;
            counter = 1;
            }

            recentlyused[lowerBound] = numberOfCycles;

            if (numberOfCycles > maxCycles)
            {
            maxCycles = numberOfCycles;
            }

            lowerBound++;
        }
        System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));

    }

}
</code>```

答:
Did you make sure that the output was in the same order specified in the input.  I see where you are swapping the input if the first input was higher than the second, but you also need to make sure that you don't alter the order it appears in the input when you print the results out.

ex.

Input

10 1

Output

10 1 20

Title: Uva's 3n+1 problem

Body:
I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far.

   import java.io.*;

public class NewClass{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

        int maxCounter= 0;
        int input;

        int lowerBound;
        int upperBound;
        int counter;
        int numberOfCycles;
        int maxCycles= 0;
        int lowerInt;
        BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
        String line = consoleInput.readLine();
        String [] splitted =  line.split(" ");

        lowerBound = Integer.parseInt(splitted[0]);
        upperBound = Integer.parseInt(splitted[1]);

        int [] recentlyused =  new int[1000001];

if (lowerBound > upperBound )
{
    int h = upperBound;
    upperBound = lowerBound;
    lowerBound = h;

}
lowerInt = lowerBound;
        while (lowerBound <= upperBound)
        {
            counter = lowerBound;
            numberOfCycles = 0;

            if (recentlyused[counter] == 0)
            {
                while ( counter != 1 )
                {

                        if (recentlyused[counter] != 0)
                        {

                        numberOfCycles = recentlyused[counter] + numberOfCycles;
                        counter = 1;
                        }
                        else
                        {
                            if (counter % 2 == 0)
                            {
                            counter = counter /2;
                            }
                            else
                            {
                            counter = 3*counter + 1;
                            }
                            numberOfCycles++;
                        }

                }
            }
            else
            {

            numberOfCycles = recentlyused[counter] + numberOfCycles;
            counter = 1;
            }

            recentlyused[lowerBound] = numberOfCycles;

            if (numberOfCycles > maxCycles)
            {
            maxCycles = numberOfCycles;
            }

            lowerBound++;
        }
        System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));

    }

}


问:
User Authentication for aws using Python
I'm working on a project with Python(3.6) & Django(1.10) in which I'm using aws apis but I'm new to aws and don't know how to authenticate a user.

My scenario is:
I need to access user's aws resources like projects list, buckets list etc, for that, I need to authenticate the user when making a request to a particular API.

How can I do that in python?
I'm new to aws.So, please don't mind my question.

Update:

Here's what i have tried:
From views.py:

```<code>def boto3_with_role(role_arn, session_prefix, external_id, **kwargs):
"""
Create a partially applied session to assume a role with an external id.
A unique session_name will be generated by {session_prefix}_{time}
`session` can be passed, otherwise the default sesion will be used
see: http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html
"""
sts = boto3.client('sts')
res = sts.assume_role(
    RoleArn=role_arn,
    RoleSessionName='{}_{}'.format(session_prefix, int(time.time())),
    ExternalId=external_id,
)
creds = res['Credentials']
return partial(boto3.session.Session,
               aws_access_key_id=creds['AccessKeyId'],
               aws_secret_access_key=creds['SecretAccessKey'],
               aws_session_token=creds['SessionToken']
               )

class AwsAuthentication(LoginRequiredMixin, CreateView):
def post(self, request, *args, **kwargs):
    AwsSession = boto3_with_role('ARN_LINK_FROM_CUSTOMER', 'MyPrefix',
                                 'EXTERNAL_ID_FROM_CUSTOMER')
    my_session = AwsSession()
    client = my_session.resource('s3')
    for bucket in client.buckets.all():
        print(bucket.name)
        return HttpResponse('Your Bucket is: {}'.format(bucket.name))
</code>```

Now, it returns: botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the AssumeRole operation: The security token included in the request is invalid.

Help me, please!

Thanks in advance!

答:
The functionality to have a user log into their AWS account to allow your application to access their AWS resources currently does not exist. A possible work around to consider is to provide the user with a direct link to creating an IAM role with a specific managed policy allowing a specific AWS account. You can then include that in your signup flow, and assume the role when you need to access resources in the user's account.

Example link:

https://console.aws.amazon.com/iam/home?region=us-west-2#/roles$new?step=review&roleType=crossAccount&accountID=123412341234&policies=arn:aws:iam::aws:policy%2FAdministratorAccess&roleName=AdminAccessForServiceName

Body:
I'm working on a project with Python(3.6) & Django(1.10) in which I'm using aws apis but I'm new to aws and don't know how to authenticate a user.

My scenario is:
I need to access user's aws resources like projects list, buckets list etc, for that, I need to authenticate the user when making a request to a particular API.

How can I do that in python?
I'm new to aws.So, please don't mind my question.

Update:

Here's what i have tried:
From views.py:

def boto3_with_role(role_arn, session_prefix, external_id, **kwargs):
"""
Create a partially applied session to assume a role with an external id.
A unique session_name will be generated by {session_prefix}_{time}
`session` can be passed, otherwise the default sesion will be used
see: http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html
"""
sts = boto3.client('sts')
res = sts.assume_role(
    RoleArn=role_arn,
    RoleSessionName='{}_{}'.format(session_prefix, int(time.time())),
    ExternalId=external_id,
)
creds = res['Credentials']
return partial(boto3.session.Session,
               aws_access_key_id=creds['AccessKeyId'],
               aws_secret_access_key=creds['SecretAccessKey'],
               aws_session_token=creds['SessionToken']
               )

class AwsAuthentication(LoginRequiredMixin, CreateView):
def post(self, request, *args, **kwargs):
    AwsSession = boto3_with_role('ARN_LINK_FROM_CUSTOMER', 'MyPrefix',
                                 'EXTERNAL_ID_FROM_CUSTOMER')
    my_session = AwsSession()
    client = my_session.resource('s3')
    for bucket in client.buckets.all():
        print(bucket.name)
        return HttpResponse('Your Bucket is: {}'.format(bucket.name))

Now, it returns: botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the AssumeRole operation: The security token included in the request is invalid.

Help me, please!

Thanks in advance!


问:
Django - how do you decide which model to put foreign key?
Lets say I have two models that looks like this:

```<code>class Album(models.Model):
    pub_date = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=250, blank=False, unique_for_date="pub_date")

class Track(models.Model):
    title = models.CharField(max_length=250, blank=False, unique_for_date="pub_date")
    album = models.ForeignKey(Album)
</code>```

What is the difference between putting the ForeignKey (one-to-many) relationship on the Track model versus having a many-to-many on the Album model?

How does one decide such a thing?

答:
Those would do completely different things.

Like you said, a ForeignKey is a one-to-many relationship. If you put it on Track, that means that many tracks belong to one album (or in other words, one album has many tracks). If you put it on Album, that means that many albums belong to one track, which is clearly not right.

The situation where there is a choice is when you're using a ManyToManyField. There, both sides are "many", so the choice of which side to put the field on is a purely semantic one.

Edit Again, these have different effects. A many-to-many would mean that both sides can have multiple items: an album can have many tracks and a track can belong to many albums.

Body:
Lets say I have two models that looks like this:

class Album(models.Model):
    pub_date = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=250, blank=False, unique_for_date="pub_date")

class Track(models.Model):
    title = models.CharField(max_length=250, blank=False, unique_for_date="pub_date")
    album = models.ForeignKey(Album)

What is the difference between putting the ForeignKey (one-to-many) relationship on the Track model versus having a many-to-many on the Album model?

How does one decide such a thing?


问:
Disabling the title bar in landscape mode
Noob here, having an issue with the action bar in landscape mode (want to keep it in portrait mode).

I post a sample of my manifest xml file having tried the info in other threads.

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

my styles.xml

```<code><resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Primary theme color of the app (sets background color of app bar) -->
    <item name="colorPrimary">#ffcfcf</item>
    <!-- Background color of buttons in the app -->
    <item name="colorButtonNormal">#ff8383</item>
</style>

<style name="AppThemeNoActionBar" parent="AppTheme">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
</code>```

a snippet from my land\activity_main.xml

```<code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:style="@style/AppThemeNoActionBar">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/love3"
    android:scaleType="centerCrop"/>
</code>```

...

I have tried changing the parent in styles.xml from AppTheme to Theme.AppCompat.Light to no avail.

portrait layout xml does not have android:style="@style/AppThemeNoActionBar"

Any pointers would be great!

答:
Try this in onCreate function below setContentView</p>

```<code>    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        getSupportActionBar().hide();
    }
</code>```

Body:
Noob here, having an issue with the action bar in landscape mode (want to keep it in portrait mode).

I post a sample of my manifest xml file having tried the info in other threads.

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

my styles.xml

<resources>

a snippet from my land\activity_main.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:style="@style/AppThemeNoActionBar">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/love3"
    android:scaleType="centerCrop"/>

...

I have tried changing the parent in styles.xml from AppTheme to Theme.AppCompat.Light to no avail.

portrait layout xml does not have android:style="@style/AppThemeNoActionBar"

Any pointers would be great!

Body:
Try this in onCreate function below setContentView

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        getSupportActionBar().hide();
    }


问:
How to use DB link in a variable in for loop
I have below query which I am trying to write in a procedure after begin clause. I dont want to use it as a cursor because of some dependency.

I want to make my db link dynamic instead of hardcoding it and for this reason i put my entire for loop in variable. If i take the variable out then my procedure is working fine. I dont want to change logic of my code while trying to make dblink dynamic.

But this part of loop is not working and throwing an error as

encounter the symbol end of the file when expecting one of the following:

```<code>    PROCEDURE   TMP_CHECK
IS

open CS for NESS_QUERY;
loop
 fetch CS into REC;
exit when CS%notfound;

 INSERT INTO TMP_Data(ID,NAME,ID_TST,CHK_DATE,VALUE,CHECK,SOURCE) VALUES
 (IN_SEQ_NO,DB_NAME,DB_ID,REC.DAY_ID,REC.nb_ord,'ORDS','LEOSOFT');

COMMIT;
END LOOP;
CLOSE CS;

END LOOP;

END;
</code>```

答:
Dynamic SQL is hard because it turns compilation errors into runtime errors.  It looks like your query has several compilation errors: duplicate table aliases, out-of-scope alias references, cross joins between the remote tables (unless that is deliberate, in which case yuck!). So the first thing to do is get the query running as straight SQL, only then make it dynamic.

Also don't include commented code in your template SQL. Things are already hard enough, why make them even harder by doing stuff like this?

```<code>ORDER BY
-- TE.market asc,
-- TE.entity asc,
TE.dayiid ASC)'
</code>```

So, now we've got that out of the way let's look at the logic of what you're trying to do. We cannot drop dynamic segments of PL/SQL into a program. This just won't work ...

```<code>LQUERY='
    FOR REC IN(
    SELECT
</code>```

... because you have not written a complete PL/SQL statement. But there is a way to do what you want: use a cursor variable. We can open a ref cursor for static and dynamic queries. Find out more.

The following is for illustrative purposes only: you haven't explained your business logic, so this is not necessarily the best way of doing things. But it should solve your immediate problem:

```<code>declare
    ....
    l_order number;
    l_dayiid number;
    l_ety_id number;
    rc sys_refcursor;
begin
    ...
    FOR IIS_DB IN C_DB
    LOOP
        IN_DB_LINK:=LEO_DB.DATABASE_LINK;
        IN_DAY:=LEO_DB.DAY_ID;
    open rc for
        'SELECT   order,dayiid,ety_id
        from ...
        ORDER BY TE.dayiid ASC)';
    loop
        fetch rc into l_order, l_dayiid, l_ety_id;
        exit when rc%notfound;
        ...
    end loop;
    close rc;
</code>```

" PLS-00487: Invalid reference to variable 'REC'"

I think your problem is this:

```<code>fetch CS into REC;
</code>```

You have defined REC as a string but clearly it should be a record type, which needs to match the projection of the query you're fetching. So you need to define something like this:

```<code>Type rec_t is record (
     nb_ord number,
     day_id number,
     entity number
);
REC rec_t;
</code>```

Now you can fetch a record into REC and reference its attributes.

Incidentally the nvl() you've written to supply NB_ORD is wrong. The first argument is the one you are testing for null: 500 will never be null so that's what you'll get for every row. You need to swap the parameters round.

Body:
I have below query which I am trying to write in a procedure after begin clause. I dont want to use it as a cursor because of some dependency.

I want to make my db link dynamic instead of hardcoding it and for this reason i put my entire for loop in variable. If i take the variable out then my procedure is working fine. I dont want to change logic of my code while trying to make dblink dynamic.

But this part of loop is not working and throwing an error as

encounter the symbol end of the file when expecting one of the following:

    PROCEDURE   TMP_CHECK
IS

open CS for NESS_QUERY;
loop
 fetch CS into REC;
exit when CS%notfound;

 INSERT INTO TMP_Data(ID,NAME,ID_TST,CHK_DATE,VALUE,CHECK,SOURCE) VALUES
 (IN_SEQ_NO,DB_NAME,DB_ID,REC.DAY_ID,REC.nb_ord,'ORDS','LEOSOFT');

COMMIT;
END LOOP;
CLOSE CS;

END LOOP;

END;

Body:
Dynamic SQL is hard because it turns compilation errors into runtime errors.  It looks like your query has several compilation errors: duplicate table aliases, out-of-scope alias references, cross joins between the remote tables (unless that is deliberate, in which case yuck!). So the first thing to do is get the query running as straight SQL, only then make it dynamic.

Also don't include commented code in your template SQL. Things are already hard enough, why make them even harder by doing stuff like this?

ORDER BY
-- TE.market asc,
-- TE.entity asc,
TE.dayiid ASC)'

So, now we've got that out of the way let's look at the logic of what you're trying to do. We cannot drop dynamic segments of PL/SQL into a program. This just won't work ...

LQUERY='
    FOR REC IN(
    SELECT

... because you have not written a complete PL/SQL statement. But there is a way to do what you want: use a cursor variable. We can open a ref cursor for static and dynamic queries. Find out more.

The following is for illustrative purposes only: you haven't explained your business logic, so this is not necessarily the best way of doing things. But it should solve your immediate problem:

declare
    ....
    l_order number;
    l_dayiid number;
    l_ety_id number;
    rc sys_refcursor;
begin
    ...
    FOR IIS_DB IN C_DB
    LOOP
        IN_DB_LINK:=LEO_DB.DATABASE_LINK;
        IN_DAY:=LEO_DB.DAY_ID;
    open rc for
        'SELECT   order,dayiid,ety_id
        from ...
        ORDER BY TE.dayiid ASC)';
    loop
        fetch rc into l_order, l_dayiid, l_ety_id;
        exit when rc%notfound;
        ...
    end loop;
    close rc;

" PLS-00487: Invalid reference to variable 'REC'"

I think your problem is this:

fetch CS into REC;

You have defined REC as a string but clearly it should be a record type, which needs to match the projection of the query you're fetching. So you need to define something like this:

Type rec_t is record (
     nb_ord number,
     day_id number,
     entity number
);
REC rec_t;

Now you can fetch a record into REC and reference its attributes.

Incidentally the nvl() you've written to supply NB_ORD is wrong. The first argument is the one you are testing for null: 500 will never be null so that's what you'll get for every row. You need to swap the parameters round.


问:
Example CrossEntropyLoss for 3D semantic segmentation in pytorch
I have a network performing 3D convolutions on a 5D input tensor. The output of my network if of size (1, 12, 60, 36, 60) corresponding to ( BatchSize, NumClasses, x-dim, y-dim, z-dim). I need to compute a voxel-wise cross entropy loss. However I keep on getting errors.

When trying to compute cross entropy loss using torch.nn.CrossEntropyLoss(), I keep on getting the following error message:

```<code>RuntimeError: multi-target not supported at .../src/THCUNN/generic/ClassNLLCriterion.cu:16
</code>```

here is the extract of my code:

```<code>import torch
import torch.nn as nn
from torch.autograd import Variable
criterion = torch.nn.CrossEntropyLoss()
images = Variable(torch.randn(1, 12, 60, 36, 60)).cuda()
labels = Variable(torch.zeros(1, 12, 60, 36, 60).random_(2)).long().cuda()
loss = criterion(images.view(1,-1), labels.view(1,-1))
</code>```

Same happens when I create a one-hot tensor for the labels:

```<code>nclasses = 12
labels = (np.random.randint(0,12,(1,60,36,60))) # Random labels with values between [0..11]
labels = (np.arange(nclasses) == labels[..., None] - 1).astype(int) # Converts labels to one_hot_tensor
a = np.transpose(labels,(0,4,3,2,1)) #  Reorder dimensions to match shape of "images" ([1, 12, 60, 36, 60])
b = Variable(torch.from_numpy(a)).cuda()
loss = criterion(images.view(1,-1), b.view(1,-1))
</code>```

Any idea what I'm doing wrong?
Can someone provide an example of computing cross entropy on a 5D output tensor?

答:
Just checked some implementation (fcn) for 2D semantic segmentation, and tried to adapt it to 3D semantic segmentation. No guarantee that this is correct, I'll have to double check...  </p>

```<code> import torch
 import torch.nn.functional as F
 def cross_entropy3d(input, target, weight=None, size_average=True):
    # input: (n, c, h, w, z), target: (n, h, w, z)
    n, c, h, w , z = input.size()
    # log_p: (n, c, h, w, z)
    log_p = F.log_softmax(input, dim=1)
    # log_p: (n*h*w*z, c)
    log_p = log_p.permute(0, 4, 3, 2, 1).contiguous().view(-1, c) # make class dimension last dimension
    log_p = log_p[target.view(n, h, w, z, 1).repeat(1, 1, 1, 1, c) >= 0] # this looks wrong -> Should rather be a one-hot vector
    log_p = log_p.view(-1, c)
    # target: (n*h*w*z,)
    mask = target >= 0
    target = target[mask]
    loss = F.nll_loss(log_p, target.view(-1), weight=weight, size_average=False)
    if size_average:
        loss /= mask.data.sum()
    return loss
images = Variable(torch.randn(5, 3, 16, 16, 16))
labels = Variable(torch.LongTensor(5, 16, 16, 16).random_(3))
cross_entropy3d(images, labels, weight=None, size_average=True)
</code>```

Body:
I have a network performing 3D convolutions on a 5D input tensor. The output of my network if of size (1, 12, 60, 36, 60) corresponding to ( BatchSize, NumClasses, x-dim, y-dim, z-dim). I need to compute a voxel-wise cross entropy loss. However I keep on getting errors.

When trying to compute cross entropy loss using torch.nn.CrossEntropyLoss(), I keep on getting the following error message:

RuntimeError: multi-target not supported at .../src/THCUNN/generic/ClassNLLCriterion.cu:16

here is the extract of my code:

import torch
import torch.nn as nn
from torch.autograd import Variable
criterion = torch.nn.CrossEntropyLoss()
images = Variable(torch.randn(1, 12, 60, 36, 60)).cuda()
labels = Variable(torch.zeros(1, 12, 60, 36, 60).random_(2)).long().cuda()
loss = criterion(images.view(1,-1), labels.view(1,-1))

Same happens when I create a one-hot tensor for the labels:

nclasses = 12
labels = (np.random.randint(0,12,(1,60,36,60))) # Random labels with values between [0..11]
labels = (np.arange(nclasses) == labels[..., None] - 1).astype(int) # Converts labels to one_hot_tensor
a = np.transpose(labels,(0,4,3,2,1)) #  Reorder dimensions to match shape of "images" ([1, 12, 60, 36, 60])
b = Variable(torch.from_numpy(a)).cuda()
loss = criterion(images.view(1,-1), b.view(1,-1))

Any idea what I'm doing wrong?
Can someone provide an example of computing cross entropy on a 5D output tensor?

Body:
Just checked some implementation (fcn) for 2D semantic segmentation, and tried to adapt it to 3D semantic segmentation. No guarantee that this is correct, I'll have to double check...

 import torch
 import torch.nn.functional as F
 def cross_entropy3d(input, target, weight=None, size_average=True):
    # input: (n, c, h, w, z), target: (n, h, w, z)
    n, c, h, w , z = input.size()
    # log_p: (n, c, h, w, z)
    log_p = F.log_softmax(input, dim=1)
    # log_p: (n*h*w*z, c)
    log_p = log_p.permute(0, 4, 3, 2, 1).contiguous().view(-1, c) # make class dimension last dimension
    log_p = log_p[target.view(n, h, w, z, 1).repeat(1, 1, 1, 1, c) >= 0] # this looks wrong -> Should rather be a one-hot vector
    log_p = log_p.view(-1, c)
    # target: (n*h*w*z,)
    mask = target >= 0
    target = target[mask]
    loss = F.nll_loss(log_p, target.view(-1), weight=weight, size_average=False)
    if size_average:
        loss /= mask.data.sum()
    return loss
images = Variable(torch.randn(5, 3, 16, 16, 16))
labels = Variable(torch.LongTensor(5, 16, 16, 16).random_(3))
cross_entropy3d(images, labels, weight=None, size_average=True)


问:
getting error as list index out of range
I have the following program to calculate the percentage of CO2 every year.
I get an error, "list index out of range", once the entire program runs on the following line:

```<code>m= co2level[i+1][1]
</code>```

Code:

```<code># Program to calculate percentage of CO2 every year

co2level = [(2001,320.93),(2003,322.16),(2004,328.07),
             (2006,323.91),(2008,341.47),(2009,348.22)]
i = 0

while i!=len(co2level):

   m= co2level[i+1][1] # I am getting error here as list index out of range
   n= co2level[i][1]
   percentage=((m-n)/n)*100
   print " Change in percentage of CO2 in year %r is"%co2level[i][0],percentage

   i+=1
</code>```

答:
You could avoid the bounds error like this:

```<code>co2level = [(2001,320.93),(2003,322.16),(2004,328.07),
             (2006,323.91),(2008,341.47),(2009,348.22)]
i = 1

while i != len(co2level):
   old = co2level[i-1][1]
   act = co2level[i][1]

   percentage=((act-old)/old)*100
   print (" Change in percentage of CO2 in year %r is " %co2level[i][0],percentage)

   i+=1
</code>```

You start with the 1st year you can get a "delta" for and inspect the one before this. You compare act to old so you are not going over the bound.

Body:
I have the following program to calculate the percentage of CO2 every year.
I get an error, "list index out of range", once the entire program runs on the following line:

m= co2level[i+1][1]

Code:

# Program to calculate percentage of CO2 every year

co2level = [(2001,320.93),(2003,322.16),(2004,328.07),
             (2006,323.91),(2008,341.47),(2009,348.22)]
i = 0

while i!=len(co2level):

   m= co2level[i+1][1] # I am getting error here as list index out of range
   n= co2level[i][1]
   percentage=((m-n)/n)*100
   print " Change in percentage of CO2 in year %r is"%co2level[i][0],percentage

   i+=1

Body:
You could avoid the bounds error like this:

co2level = [(2001,320.93),(2003,322.16),(2004,328.07),
             (2006,323.91),(2008,341.47),(2009,348.22)]
i = 1

while i != len(co2level):
   old = co2level[i-1][1]
   act = co2level[i][1]

   percentage=((act-old)/old)*100
   print (" Change in percentage of CO2 in year %r is " %co2level[i][0],percentage)

   i+=1

You start with the 1st year you can get a "delta" for and inspect the one before this. You compare act to old so you are not going over the bound.


问:
Remove rows from Pandas Dataframe which contain no numbers and no literal
i have a column called 'str' in a Panda Dataframe.
As i intend to delete all rows from it which contain no numerical values [0-9]
or literal [a-z], the following statement did not work:

```<code>data[data['str'].str.contains(r"[a-zA-z0-9]") == True]
</code>```

After the execution I analysed the column values. There are still values in it like:

("[[", "^")

and it deletes values (which is in this case not desired):

("1", "2016", "20160715")

Is there are anyone who could help me?

Best Regards

答:
you can use pandas dropna function it will delete that whole row which contains any null values.

df=df.dropna()

where df is your dataframe

Body:
i have a column called 'str' in a Panda Dataframe.
As i intend to delete all rows from it which contain no numerical values [0-9]
or literal [a-z], the following statement did not work:

data[data['str'].str.contains(r"[a-zA-z0-9]") == True]

After the execution I analysed the column values. There are still values in it like:

("[[", "^")

and it deletes values (which is in this case not desired):

("1", "2016", "20160715")

Is there are anyone who could help me?

Best Regards


问:
Explain this snippet which finds the maximum of two integers without using if-else or any other comparison operator?
Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow

EXAMPLE
Input: 5, 10
Output: 10

I found this solution, can someone help me understand these lines of code

```<code>int getMax(int a, int b) {
    int c = a - b;
    int k = (c >> 31) & 0x1;
    int max = a - k * c;
    return max;
}
</code>```

答: Here we go: (a + b) / 2 + |a - b| / 2

Body:
Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow

EXAMPLE
Input: 5, 10
Output: 10

I found this solution, can someone help me understand these lines of code

int getMax(int a, int b) {
    int c = a - b;
    int k = (c >> 31) & 0x1;
    int max = a - k * c;
    return max;
}

Body: Here we go: (a + b) / 2 + |a - b| / 2


问:
Angular 2/4 pushing in array inside an object
I have been trying to push some comments in an array inside an object(Object is not an array but there is array in it) I spent quite a time cant get it to work. What I have is

```<code>export class test{
     recordname: string;
     comments: [{
         comment: string
      }]
}
</code>```

Each time some one types a comment I want to add it to the comment array something like this

```<code>  addcomment: test;
addRow(){
    this.addcomment.comment.push({
        comment : 'first comment'})
</code>```

I tried to add it using different ways cant seem to make it work. The message i get push is undefined. I cant use addcomment:test[]=[]; since this is form where vlaues are input and saved.
Please let me know how can I push comment values

答:
You have a spelling mistake on addcomment.comment (comments)
Like this. 1. Define comments as an array. 2. Then just use the push function and pass in an object.</p>

```<code>  export class test{
         recordname: string;
         comments: any[];
    }

this.addcomment.comments.push({
    comment : 'first comment'})
</code>```

Body:
I have been trying to push some comments in an array inside an object(Object is not an array but there is array in it) I spent quite a time cant get it to work. What I have is

export class test{
     recordname: string;
     comments: [{
         comment: string
      }]
}

Each time some one types a comment I want to add it to the comment array something like this

  addcomment: test;
addRow(){
    this.addcomment.comment.push({
        comment : 'first comment'})

I tried to add it using different ways cant seem to make it work. The message i get push is undefined. I cant use addcomment:test[]=[]; since this is form where vlaues are input and saved.
Please let me know how can I push comment values

Body:
You have a spelling mistake on addcomment.comment (comments)
Like this. 1. Define comments as an array. 2. Then just use the push function and pass in an object.

  export class test{
         recordname: string;
         comments: any[];
    }

this.addcomment.comments.push({
    comment : 'first comment'})


问:
How to setup Geb 2.0 in IntelliJ (run/debug configurations)?
I'm using Geb 2.0 (http://gebish.org/) and have downloaded the Gradle sample (https://github.com/geb/geb-example-gradle).

All works just fine on my machine with all browsers (Chrome, Firefox, ChromeHeadless).

I have imported the project in IntelliJ (latest Ultimate edition) and all normal code editing functions are working fine.

What fails is attempting to run a spec. I get an exception with the helpful hint of the path to the driver executable must be set by the webdriver.chrome.driver system property.

However, I can't figure out what to point it at. I've tried pointing at the selenium-chrome-driver-3.6.0.jar but that results in failure also.

I'm using -Dgeb.env=chrome and -Dwebdriver.chrome.driver=SOMERANDOMEPATHSHERE

Help?

答: The Gradle example Geb project is set up to generate the appropriately configured IntelliJ project capable fo running the specs from the IDE. Simply run ./gradlew idea and load the project by opening the geb-example-gradle.ipr file in IntelliJ instead of loading the project by importing it's Gradle build the way you do.


问:
Call method from Main Activity into Fragment Adapter
How to call a method from my activity in to my fragment adapter? I use a RecyclerView on my fragment and there is intent inside this fragment adapter. I already make a method in my Main Activity but I'm unable to call it from my Fragment Adapter.

Method in Main Activity

```<code>public void showInterstitial() {
  if(interstitialAd != null && interstitialAd.isLoaded()) {
     interstitialAd.show();
     loadingIklan=true;
  }
}
</code>```

and I want put that method inside intent switch case on fragment adapter

```<code>    public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private TextView homeTitle;

        private Context context;

        public ViewHolder(View itemView) {
            super(itemView);
            context = itemView.getContext();
            homeTitle = (TextView)itemView.findViewById(R.id.homeTitle);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final Intent intent;
                    switch (getAdapterPosition()) {
                        case 0:
                            ((MainActivity) getActivity()).showInterstitial();
                            intent = new Intent(context, AllBlock.class);
                            break;
                        case 1:
                            intent = new Intent(context, BasicBlock.class);
                            break;

                        default:
                            intent = new Intent(context, AllBlock.class);
                            break;
                    }
                    context.startActivity(intent);
                }
            });
        }
    }

    public List<HomeData> homeList;

    public HomeAdapter(List<HomeData> homeList) {

        this.homeList = homeList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.homeTitle.setText(homeList.get(position).getHomeTitle());
    }

    @Override
    public int getItemCount() {
        return homeList.size();
    }
}
</code>```

my main fragment

```<code>public class Home extends Fragment {

    public Home() {
        // Required empty public constructor
    }

    private RecyclerView recyclerView;
    private HomeAdapter homeAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.home, container, false);

        recyclerView = (RecyclerView)view.findViewById(R.id.recyclerview);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        homeAdapter = new HomeAdapter(homeDataList());
        recyclerView.setAdapter(homeAdapter);

        return view;
    }
}
</code>```

anyone can help me with a right code? Thank you.

答:
You should not call activity from RecyclerView adapter. Adapter should only handling the data presentation. Hence, you need to you a Listener/Callback pattern. Because your adapter is called from fragment where the fragment is attached to the activity, then you need to create a nested Listener/Callback.

First, create the listener interface in RecyclerView adapter. The purpose of the interface is to tell the listener (which is Fragment) to do something.

```<code>public class YourAdapter extends RecyclerView.Adapter<YourAdapter.ViewHolder> {

  ...
  private AdapterListener listener;

  // define the listener
  public interface AdapterListener {
    void onItemClicked(int position);
  }

  // register the listener with this method
  public setListener(AdapterListener listener) {
    this.listener = listener;
  }

  ...

  public ViewHolder(View itemView) {
    itemView.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {

         // tell the listener about the click
         if(listener != null) {
           listener.onItemClicked(getAdapterPosition());
         }

       }
  }

}
</code>```

Second, register the Fragment as the listener:

```<code>public class YourFragment extends Fragment {
  ...
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    ...
    // This is an example, you can register the listener in any method

    // sample
    YourAdapter adapter = new YourAdapter(...);

    YourAdapter.AdapterListener listener = new YourAdapter.AdapterListener {
       @Override
       public void onItemClicked(int position) {

         // handle the item click here.
       }
    }
  }
}
</code>```

Third, create listener to communicate between Fragment and Activity (Read more at Communicating with Other Fragments:

```<code>public class YourFragment extends Fragment {
  private FragmentListener mListener;

  public interface FragmentListener {
    onRecyclerViewItemClicked(int position);
  }

  @Override
  public void onAttach(Context context) {
    super.onAttach(context);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = (FragmentListener) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString()
                + " must implement FragmentListener");
    }
  }

}
</code>```

Fourth, execute the fragment listener to tell the activity about the recyclerView item click. Add the code in the previous Adapter listener:

```<code>public class YourFragment extends Fragment {
  ...
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    ...
    // This is an example, you can register the listener in any method

    YourAdapter adapter = new YourAdapter(...);

    YourAdapter.AdapterListener listener = new YourAdapter.AdapterListener {
       @Override
       public void onItemClicked(int position) {
         mListener.onRecyclerViewItemClicked(position);
       }
    }
  }
}
</code>```

Fifth, register the activity as the listener receiver. Hence you do the actual logic:

```<code>public class YourActivity extends Activity
        implements YourFragment.FragmentListener {

  ...

  @Ovveride
  public void onRecyclerViewItemClicked(int position) {
    // Handle the RecyclerView item click here
    switch(position) {
      case 0:
        showInterstitial();
        break;
     default:
       intent = new Intent(this, AllBlock.class);
       startActivity(intent);
    }
  }
}
</code>```

Note:

I tend to use Event Bus mechanism with EventBus because it simplify all the listener code. You could try EventBus after you've mastering the Listener/Callback pattern. Horas!

Body:
How to call a method from my activity in to my fragment adapter? I use a RecyclerView on my fragment and there is intent inside this fragment adapter. I already make a method in my Main Activity but I'm unable to call it from my Fragment Adapter.

Method in Main Activity

public void showInterstitial() {
  if(interstitialAd != null && interstitialAd.isLoaded()) {
     interstitialAd.show();
     loadingIklan=true;
  }
}

and I want put that method inside intent switch case on fragment adapter

    public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private TextView homeTitle;

        private Context context;

        public ViewHolder(View itemView) {
            super(itemView);
            context = itemView.getContext();
            homeTitle = (TextView)itemView.findViewById(R.id.homeTitle);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final Intent intent;
                    switch (getAdapterPosition()) {
                        case 0:
                            ((MainActivity) getActivity()).showInterstitial();
                            intent = new Intent(context, AllBlock.class);
                            break;
                        case 1:
                            intent = new Intent(context, BasicBlock.class);
                            break;

                        default:
                            intent = new Intent(context, AllBlock.class);
                            break;
                    }
                    context.startActivity(intent);
                }
            });
        }
    }

    public List<HomeData> homeList;

    public HomeAdapter(List<HomeData> homeList) {

        this.homeList = homeList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.homeTitle.setText(homeList.get(position).getHomeTitle());
    }

    @Override
    public int getItemCount() {
        return homeList.size();
    }
}

my main fragment

public class Home extends Fragment {

    public Home() {
        // Required empty public constructor
    }

    private RecyclerView recyclerView;
    private HomeAdapter homeAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.home, container, false);

        recyclerView = (RecyclerView)view.findViewById(R.id.recyclerview);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        homeAdapter = new HomeAdapter(homeDataList());
        recyclerView.setAdapter(homeAdapter);

        return view;
    }
}

anyone can help me with a right code? Thank you.

Body:
You should not call activity from RecyclerView adapter. Adapter should only handling the data presentation. Hence, you need to you a Listener/Callback pattern. Because your adapter is called from fragment where the fragment is attached to the activity, then you need to create a nested Listener/Callback.

First, create the listener interface in RecyclerView adapter. The purpose of the interface is to tell the listener (which is Fragment) to do something.

public class YourAdapter extends RecyclerView.Adapter<YourAdapter.ViewHolder> {

  ...
  private AdapterListener listener;

  // define the listener
  public interface AdapterListener {
    void onItemClicked(int position);
  }

  // register the listener with this method
  public setListener(AdapterListener listener) {
    this.listener = listener;
  }

  ...

  public ViewHolder(View itemView) {
    itemView.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {

         // tell the listener about the click
         if(listener != null) {
           listener.onItemClicked(getAdapterPosition());
         }

       }
  }

}

Second, register the Fragment as the listener:

public class YourFragment extends Fragment {
  ...
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    ...
    // This is an example, you can register the listener in any method

    // sample
    YourAdapter adapter = new YourAdapter(...);

    YourAdapter.AdapterListener listener = new YourAdapter.AdapterListener {
       @Override
       public void onItemClicked(int position) {

         // handle the item click here.
       }
    }
  }
}

Third, create listener to communicate between Fragment and Activity (Read more at Communicating with Other Fragments:

public class YourFragment extends Fragment {
  private FragmentListener mListener;

  public interface FragmentListener {
    onRecyclerViewItemClicked(int position);
  }

  @Override
  public void onAttach(Context context) {
    super.onAttach(context);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = (FragmentListener) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString()
                + " must implement FragmentListener");
    }
  }

}

Fourth, execute the fragment listener to tell the activity about the recyclerView item click. Add the code in the previous Adapter listener:

public class YourFragment extends Fragment {
  ...
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    ...
    // This is an example, you can register the listener in any method

    YourAdapter adapter = new YourAdapter(...);

    YourAdapter.AdapterListener listener = new YourAdapter.AdapterListener {
       @Override
       public void onItemClicked(int position) {
         mListener.onRecyclerViewItemClicked(position);
       }
    }
  }
}

Fifth, register the activity as the listener receiver. Hence you do the actual logic:

public class YourActivity extends Activity
        implements YourFragment.FragmentListener {

  ...

  @Ovveride
  public void onRecyclerViewItemClicked(int position) {
    // Handle the RecyclerView item click here
    switch(position) {
      case 0:
        showInterstitial();
        break;
     default:
       intent = new Intent(this, AllBlock.class);
       startActivity(intent);
    }
  }
}

Note:

I tend to use Event Bus mechanism with EventBus because it simplify all the listener code. You could try EventBus after you've mastering the Listener/Callback pattern. Horas!


问:
Can I interact with Phriction via Git?
Some wikis and wiki subsystems use Git as a backend (ikiwiki, Gogs...)

Is it possible to interact with Phriction (wiki subsystem of Phabricator) via Git? In other words, changes via the Phriction web interface appear in origin/master, and changes merged into origin/master appear in the web interface.

答: Phriction is a database backed wiki, not a file based wiki with git managing the history. So this method of interaction is not possible.</p>

Title: Can I interact with Phriction via Git?