问:
Get reverse model foreign key object for inherited object
I have the following model with a reference an object and an object it inherits from:

```<code>class Employee(models.Model):
    user = models.OneToOneField(User, blank=True, null=True)
    entity = models.ForeignKey('companies.Entity', blank=True, null=True)
    brand = models.OneToOneField('companies.Brand', related_name='brand', blank=True, null=True)

class Entity(models.Model):
    name = models.CharField('Name', max_length=255, db_index=True)

class Brand(Entity):
    company_name = models.CharField(max_length=128, blank=True, null=True)
</code>```

The problem is when I try to reference the inverse relationship, I can't access the Brand only the Entity.  I want to get the employee associated with a brand.  I tried this:

```<code>brands = Brand.objects.filter(pk=2)

for b in brands:
    print b.employee_set.all().query
</code>```

It outputs:

```<code>SELECT * FROM `employee` WHERE `employee`.`entity_id` = 2
</code>```

I want it to output:

```<code>SELECT * FROM `employee` WHERE `employee`.`brand_id` = 2
</code>```

答: Inside your model file, the way you define Entity and Brand is called Multi-table inheritance, django will  automatically create OneToOneField relationship between entity and brand, but in your employee model, entity is your foreignkey but brand has onetoonefield with you employee model, that's not going to work. You can override the field by declaring your own OneToOneField with parent_link=True on Entity so there aren't oneToOneField relationship between entity and brand, check this for detail: https://docs.djangoproject.com/en/1.11/topics/db/models/#multi-table-inheritance. Hope this help you.</p>

Body:
I have the following model with a reference an object and an object it inherits from:

class Employee(models.Model):
    user = models.OneToOneField(User, blank=True, null=True)
    entity = models.ForeignKey('companies.Entity', blank=True, null=True)
    brand = models.OneToOneField('companies.Brand', related_name='brand', blank=True, null=True)

class Entity(models.Model):
    name = models.CharField('Name', max_length=255, db_index=True)

class Brand(Entity):
    company_name = models.CharField(max_length=128, blank=True, null=True)

The problem is when I try to reference the inverse relationship, I can't access the Brand only the Entity.  I want to get the employee associated with a brand.  I tried this:

brands = Brand.objects.filter(pk=2)

for b in brands:
    print b.employee_set.all().query

It outputs:

SELECT * FROM `employee` WHERE `employee`.`entity_id` = 2

I want it to output:

SELECT * FROM `employee` WHERE `employee`.`brand_id` = 2


来源: stackexchange

问:
PostgreSQL - Avoid listing the same IN() values twice
I have a query on a customer referrals table in which each row contains the customer id of a referring customer, and a referred customer. So if Bob with custID 100 refers John with custID 200 to our product, we enter a row in the referrals table where referring_user_id is 100 and referred_user_id is 200.

Given a list of user_ids, I want to search both the referring_user_id column and the referred_user_id column for any matches. The only way I figured out how to do this is to do an OR on both columns, and copy the list of user_ids twice like so:

```<code>SELECT
    ---columns---
FROM tbl_referrals REF
LEFT JOIN tbl_profile PRF1 ON REF.referring_user_id = PRF1.user_id
LEFT JOIN tbl_profile PRF2 ON REF.referred_user_id = PRF2.user_id
WHERE
    PRF1.user_id IN (
        'id100',
        'id200',
        'id300',
        'id400'
    )
    OR PRF2.user_id IN (
        'id100',
        'id200',
        'id300',
        'id400'
    )
ORDER BY REF.referred_user_id
limit 100;
</code>```

Is there a way to write this query without writing the whole list of ids twice? This is post-gres btw, but I think it applies to all SQL.

答:
```<code>WITH ids(id) AS (VALUES('{id100,id200,id300,id400}'::text[]))
SELECT
    ---columns---
FROM tbl_referrals REF
  JOIN ids ON (REF.referring_user_id = ANY(ids.id) OR REF.referred_user_id = ANY(ids.id))
  LEFT JOIN tbl_profile PRF1 ON REF.referring_user_id = PRF1.user_id
  LEFT JOIN tbl_profile PRF2 ON REF.referred_user_id = PRF2.user_id
ORDER BY REF.referred_user_id
limit 100;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a query on a customer referrals table in which each row contains the customer id of a referring customer, and a referred customer. So if Bob with custID 100 refers John with custID 200 to our product, we enter a row in the referrals table where referring_user_id is 100 and referred_user_id is 200.

Given a list of user_ids, I want to search both the referring_user_id column and the referred_user_id column for any matches. The only way I figured out how to do this is to do an OR on both columns, and copy the list of user_ids twice like so:

SELECT
    ---columns---
FROM tbl_referrals REF
LEFT JOIN tbl_profile PRF1 ON REF.referring_user_id = PRF1.user_id
LEFT JOIN tbl_profile PRF2 ON REF.referred_user_id = PRF2.user_id
WHERE
    PRF1.user_id IN (
        'id100',
        'id200',
        'id300',
        'id400'
    )
    OR PRF2.user_id IN (
        'id100',
        'id200',
        'id300',
        'id400'
    )
ORDER BY REF.referred_user_id
limit 100;

Is there a way to write this query without writing the whole list of ids twice? This is post-gres btw, but I think it applies to all SQL.


问:
Can we make an element of block modifier in BEM?
I just wanted to know whether the following code follows BEM methodology best practices? Creating an element for the block modifier i.e. in this case "block--mod" is a modifier for the "block" block. Is it allowed to create a nested element with this pattern: "block--mod__elm". </p>

```<code><div class="block block--mod">
   <div class="block__elm block--mod__elm">
</div>
</code>```

答:
I could not find an example of a the .block--mod__elem pattern in Yandex's BEM documentation (Yandex devised the BEM methodology), but an early article about BEM on CSS Wizardry does show an example of a modifier with a sub-element, .person--female__hand:

```<code>.person {}
.person__hand {}
.person--female {}
.person--female__hand {}
.person__hand--left {}
</code>```

Source: MindBEMding – getting your head ’round BEM syntax

Modifiers with sub-elements can be a little hard to follow, but I do not shy away using from them if it seems like the logical approach.

Edit: @NikolayMihaylov's answer gives an alternative approach that I wholeheartedly support. It is more readable and more maintainable.

Body:
I could not find an example of a the .block--mod__elem pattern in Yandex's BEM documentation (Yandex devised the BEM methodology), but an early article about BEM on CSS Wizardry does show an example of a modifier with a sub-element, .person--female__hand:

.person {}
.person__hand {}
.person--female {}
.person--female__hand {}
.person__hand--left {}

Source: MindBEMding – getting your head ’round BEM syntax

Modifiers with sub-elements can be a little hard to follow, but I do not shy away using from them if it seems like the logical approach.

Edit: @NikolayMihaylov's answer gives an alternative approach that I wholeheartedly support. It is more readable and more maintainable.


问:
Inflate fragment from activity
Here is my activity class. I am trying to inflate fragment to this activity.

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.fg1, new ButtonsFragment());
        ft.commit();
    }
</code>```

activity_main.xml

```<code><LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/a_layout"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_margin="10dp"
        android:id="@+id/fg1"
        />
</LinearLayout>
</code>```

ButtonsFragment.java

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

    Button b1,b2,b3;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
    {
        super.onCreateView(inflater,container,savedInstanceState);

       View v = inflater.inflate(R.layout.fragment_buttons,container,false);

        b2 = (Button)v.findViewById(R.id.b2);
        b1 = (Button)v.findViewById(R.id.b1);
        b3 = (Button)v.findViewById(R.id.b3);
        return v;
    }
}
</code>```

fragment_buttons.xml

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.iiitb.patientdoctormanagementsystem.ButtonsFragment">

 <LinearLayout
        android:id="@+id/ll"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:textAllCaps="false"
            android:text="Past Appointments"
            android:id="@+id/b1"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Button
            android:textAllCaps="false"
            android:text="Todays Appointments"
            android:id="@+id/b2"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Button
            android:textAllCaps="false"
            android:text="Upcoming Appointments"
            android:id="@+id/b3"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />
    </LinearLayout>
</FrameLayout>
</code>```

But I am getting this exception:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.iiitb.patientdoctormanagementsystem/com.example.iiitb.patientdoctormanagementsystem.MainActivity}: android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class fragment
</code>```

PLEASE HELP!!

答:
There are two ways you can add a fragment to the activity layout:

Declare the fragment inside the activity's layout file

Programmatically add the fragment to a ViewGroup

In your example you followed both approached at the same time. You should select one of them. When you added a fragment in activity layout:

```<code><fragment
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:layout_margin="10dp"
    android:id="@+id/fg1"
    />
</code>```

You missed android:name attribute. This attribute specifies the Fragment class to instantiate in the layout. So, you should declare it like this:

```<code> <fragment
    android:name="your.package.ButtonsFragment"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:layout_margin="10dp"
    android:id="@+id/fg1"
    />
</code>```

When the system creates this activity layout, it instantiates each fragment specified in the layout and calls the onCreateView() method for each one, to retrieve each fragment's layout. The system inserts the View returned by the fragment directly in place of the  element. (from developer.android.com)

By following this approach you don't need these lines of code (remove it):

```<code>FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fg1, new ButtonsFragment());
ft.commit();
</code>```

If you want to follow the second approach, add a fragment to an existing ViewGroup programmatically, you should change activity layout as follow:

```<code><FrameLayout
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:layout_margin="10dp"
    android:id="@+id/fg1" />
</code>```

and leave other parts of your code as it is. For more information about fragments you can refer to android documentation

Title: Inflate fragment from activity

Body:
Here is my activity class. I am trying to inflate fragment to this activity.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.fg1, new ButtonsFragment());
        ft.commit();
    }

activity_main.xml

<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/a_layout"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_margin="10dp"
        android:id="@+id/fg1"
        />
</LinearLayout>

ButtonsFragment.java

public class ButtonsFragment extends Fragment {

    Button b1,b2,b3;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
    {
        super.onCreateView(inflater,container,savedInstanceState);

       View v = inflater.inflate(R.layout.fragment_buttons,container,false);

        b2 = (Button)v.findViewById(R.id.b2);
        b1 = (Button)v.findViewById(R.id.b1);
        b3 = (Button)v.findViewById(R.id.b3);
        return v;
    }
}

fragment_buttons.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.iiitb.patientdoctormanagementsystem.ButtonsFragment">

 <LinearLayout
        android:id="@+id/ll"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:textAllCaps="false"
            android:text="Past Appointments"
            android:id="@+id/b1"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Button
            android:textAllCaps="false"
            android:text="Todays Appointments"
            android:id="@+id/b2"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Button
            android:textAllCaps="false"
            android:text="Upcoming Appointments"
            android:id="@+id/b3"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />
    </LinearLayout>
</FrameLayout>

But I am getting this exception:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.iiitb.patientdoctormanagementsystem/com.example.iiitb.patientdoctormanagementsystem.MainActivity}: android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class fragment

PLEASE HELP!!

Body:
There are two ways you can add a fragment to the activity layout:

Declare the fragment inside the activity's layout file

Programmatically add the fragment to a ViewGroup

In your example you followed both approached at the same time. You should select one of them. When you added a fragment in activity layout:

<fragment
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:layout_margin="10dp"
    android:id="@+id/fg1"
    />

You missed android:name attribute. This attribute specifies the Fragment class to instantiate in the layout. So, you should declare it like this:

 <fragment
    android:name="your.package.ButtonsFragment"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:layout_margin="10dp"
    android:id="@+id/fg1"
    />

When the system creates this activity layout, it instantiates each fragment specified in the layout and calls the onCreateView() method for each one, to retrieve each fragment's layout. The system inserts the View returned by the fragment directly in place of the  element. (from developer.android.com)

By following this approach you don't need these lines of code (remove it):

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fg1, new ButtonsFragment());
ft.commit();

If you want to follow the second approach, add a fragment to an existing ViewGroup programmatically, you should change activity layout as follow:

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:layout_margin="10dp"
    android:id="@+id/fg1" />

and leave other parts of your code as it is. For more information about fragments you can refer to android documentation


问:
Is it bad practice to have an output parameter in a method in a WCF service?
I'm looking for reasons beyond the usual "out parameters are confusing and indicate the method is doing more than one thing"-style arguments and more about what is specifically bad about output parameters in WCF services.  Where I work now, we have a rule against them in WCF services, and I'm trying to work out why!</p>

答:
Personally, I use out parameters in specific places (such as methods named TryParse()).  So, I have some of the bias you talked about where I only use it in specific, limited places.  In addition, you can't assume that a .Net application is going to be consuming this on the other end.  Because WCF provides an interface consumable as a SOAP or REST web service (among other communication types), I can't guarantee that WCF would even support out params for compatibility with non-.Net consumers.

Beyond that, a WCF service is providing an API to a consumer, and API's should provide an interface that should be consumed with limited knowledge of how the server methods were coded.  (Don't presume the guy writing the WCF server is the same guy writing the client on the other end).  Attempting to use an out param on an API seems like a code smell.  Presumably, one would use an out param to return another value(s) to the consumer.  Consider instead using a message object.  A message object is specifically composed of all the pieces of data that need to be sent from the WCF server to its consumer.  For example, let's say you have a method exposed in a WCF server called TryCreateUser:

```<code>bool TryCreateUser(string name, string email, out User user){}
</code>```

where you intend to return a bool indicating where user creation occurred successfully and a User object containing the user if it succeeded.  I would create a new class, UserCreationMessage:

```<code>class UserCreationMessage {
    bool IsSuccessful;
    User user;
}
</code>```

Return this message object back to the consumer, and you can still get the multiple returned values.  However, you now have a coherent object being returned that's more explanatory to the end user of the API.

In the end, I'd reason that it's bad practice to have an out parameter in an API, such as a WCF server because programmers creating the consumer for this service have to be able to easily look at the API and consume it without jumping through the hoops that an out param present.  Since a better design for this exists, use it.  API's require higher coding standards, especially in the interface exposed to the end consumer.

ContentLicense: CC BY-SA 2.5

Body:
Personally, I use out parameters in specific places (such as methods named TryParse()).  So, I have some of the bias you talked about where I only use it in specific, limited places.  In addition, you can't assume that a .Net application is going to be consuming this on the other end.  Because WCF provides an interface consumable as a SOAP or REST web service (among other communication types), I can't guarantee that WCF would even support out params for compatibility with non-.Net consumers.

Beyond that, a WCF service is providing an API to a consumer, and API's should provide an interface that should be consumed with limited knowledge of how the server methods were coded.  (Don't presume the guy writing the WCF server is the same guy writing the client on the other end).  Attempting to use an out param on an API seems like a code smell.  Presumably, one would use an out param to return another value(s) to the consumer.  Consider instead using a message object.  A message object is specifically composed of all the pieces of data that need to be sent from the WCF server to its consumer.  For example, let's say you have a method exposed in a WCF server called TryCreateUser:

bool TryCreateUser(string name, string email, out User user){}

where you intend to return a bool indicating where user creation occurred successfully and a User object containing the user if it succeeded.  I would create a new class, UserCreationMessage:

class UserCreationMessage {
    bool IsSuccessful;
    User user;
}

Return this message object back to the consumer, and you can still get the multiple returned values.  However, you now have a coherent object being returned that's more explanatory to the end user of the API.

In the end, I'd reason that it's bad practice to have an out parameter in an API, such as a WCF server because programmers creating the consumer for this service have to be able to easily look at the API and consume it without jumping through the hoops that an out param present.  Since a better design for this exists, use it.  API's require higher coding standards, especially in the interface exposed to the end consumer.


问:
Using decode with to_date
If anyone could help me with the following, I'd be grateful:
I'm trying to write a code (create an alert in PowerSchool) that will indicate if a student is younger or older than average for their current grade level. (For example, as student born before 6/30/2002 is older than average for 9th grade) I can't seem to make DECODE work in conjunction with >= TO_DATE. Here's my statement:</p>

```<code>select lastfirst, decode  (dob >=  to_date ('2002-06-30', 'yyyy-mm-dd'), 'old') DOB
from students
where grade_level = 9
order by lastfirst
</code>```

答:
You probably could get away with using a PowerSchool decode in your sql, but I find code easier to write when fewer languages/systems are included, so I would leave it out.  I would also let SQL do the average age calculation so you don't have to supply or calculate average dates yourself (see Averaging dates in oracle sql for an explanation of the TO_DATE line).

```<code>SELECT
    LastFirst AS "Student Name"
    ,CASE WHEN dob >= (
        SELECT
            TO_DATE(ROUND(AVG(TO_NUMBER(TO_CHAR(dob, 'J')))),'J')
        FROM Students
        WHERE Grade_Level = 9
        AND Enroll_Status = 0
    ) THEN 'Younger' ELSE 'Older' END AS "Older or Younger?"
FROM Students
WHERE Grade_Level = 9
ORDER BY LastFirst
</code>```

The subquery calculates the average birthday, and the CASE statement compares each of your records against that, reporting if it's older or younger.

In the subquery that calculates the average, I've taken the liberty of assuming you only want to compare against currently enrolled students, since withdrawn students retain the same grade level.  You don't really want those students who left 10 years ago and are still listed as a 9th grader to mess with your average numbers.

Title: Using decode with to_date

Body:
If anyone could help me with the following, I'd be grateful:
I'm trying to write a code (create an alert in PowerSchool) that will indicate if a student is younger or older than average for their current grade level. (For example, as student born before 6/30/2002 is older than average for 9th grade) I can't seem to make DECODE work in conjunction with >= TO_DATE. Here's my statement:

select lastfirst, decode  (dob >=  to_date ('2002-06-30', 'yyyy-mm-dd'), 'old') DOB
from students
where grade_level = 9
order by lastfirst

Body:
You probably could get away with using a PowerSchool decode in your sql, but I find code easier to write when fewer languages/systems are included, so I would leave it out.  I would also let SQL do the average age calculation so you don't have to supply or calculate average dates yourself (see Averaging dates in oracle sql for an explanation of the TO_DATE line).

SELECT
    LastFirst AS "Student Name"
    ,CASE WHEN dob >= (
        SELECT
            TO_DATE(ROUND(AVG(TO_NUMBER(TO_CHAR(dob, 'J')))),'J')
        FROM Students
        WHERE Grade_Level = 9
        AND Enroll_Status = 0
    ) THEN 'Younger' ELSE 'Older' END AS "Older or Younger?"
FROM Students
WHERE Grade_Level = 9
ORDER BY LastFirst

The subquery calculates the average birthday, and the CASE statement compares each of your records against that, reporting if it's older or younger.

In the subquery that calculates the average, I've taken the liberty of assuming you only want to compare against currently enrolled students, since withdrawn students retain the same grade level.  You don't really want those students who left 10 years ago and are still listed as a 9th grader to mess with your average numbers.


问:
Error adding Data to my SQLite Database on Android Studio
New to Android Studio and SQLite so some help would be appreciated.

Creating an app where someone enters in their friend details and it adds them to a Database.

I've created my Database Class and my Activity to add friends but whenever I attempt to add them to the database, I get an error in the logcat stating:

```<code>11-16 20:40:20.083 2641-2641/com.example.kod45.myapplication E/SQLiteDatabase: Error inserting EMAIL=pm@gmail.com NAME=paul ID=1 SURNAME=pail
                                                                           android.database.sqlite.SQLiteException: table friends_table has no column named EMAIL (code 1): , while compiling: INSERT INTO friends_table(EMAIL,NAME,ID,SURNAME) VALUES (?,?,?,?)
                                                                           #################################################################
                                                                           Error Code : 1 (SQLITE_ERROR)
                                                                           Caused By : SQL(query) error or missing database.
                                                                            (table friends_table has no column named EMAIL (code 1): , while compiling: INSERT INTO friends_table(EMAIL,NAME,ID,SURNAME) VALUES (?,?,?,?))
</code>```

Here is my Database Handler:

```<code>public class DBHandler extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "Friends.db";
    public static final String TABLE_NAME = "friends_table";
    public static final String ID_COL = "ID";
    public static final String EMAIL = "EMAIL";
    public static final String FIRST_NAME = "NAME";
    public static final String SURNAME = "SURNAME";

public DBHandler(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

public void onCreate(SQLiteDatabase db)
{
    String CREATE_FRIENDS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + ID_COL + " INTEGER PRIMARY KEY,"
            + EMAIL + "TEXT,"
            + FIRST_NAME + "TEXT,"
            + SURNAME + "TEXT" + ")";

    db.execSQL(CREATE_FRIENDS_TABLE);
}

public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
    // example of drop old tables and Re-
    //create tables.
    //you can alter tables such as add
    //columns, etc. but not drop tables
    db.execSQL("drop table if exists "
            + TABLE_NAME);
    onCreate(db);
}

public void addNewFriend(Friend newFriend)
{
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(ID_COL, newFriend.getFriendID());
    values.put(EMAIL, newFriend.getEmailAddress());
    values.put(FIRST_NAME, newFriend.getFirstName());
    values.put(SURNAME, newFriend.getSurname());

    db.insert(TABLE_NAME, null, values);
    db.close();
}

public ArrayList<Friend> getAllFriends()
{
    ArrayList<Friend> friendList = new ArrayList<Friend>();

    String selectQuery = "SELECT * FROM " + TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if(cursor.moveToFirst()) {
        do
            {
                Friend friend = new Friend();
                friend.setFriendID(Integer.parseInt(cursor.getString(0)));
                friend.setEmailAddress(cursor.getString(1));
                friend.setFirstName(cursor.getString(2));
                friend.setSurname(cursor.getString(3));

                //Adding to list
                friendList.add(friend);
            }
            while (cursor.moveToNext()) ;

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

}

And also how I am adding:

```<code>    public class AddFriends extends AppCompatActivity {
        DBHandler myDB;
        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friends);
        myDB = new DBHandler(this);
    }

    public void addFriend(View v) {
        EditText email = (EditText) findViewById(R.id.emailText);
        EditText firstName = (EditText) findViewById(R.id.firstnameText);
        EditText surname = (EditText) findViewById(R.id.surnameText);
        EditText id = (EditText) findViewById (R.id.idText);
        Button addData = (Button)findViewById(R.id.addFriendButton);

        //Passing them as strings
        String emailString = email.getText().toString();
        String firstNameString = firstName.getText().toString();
        String surnameString = surname.getText().toString();
        int idNum = Integer.parseInt(id.getText().toString());

        String emailPattern = "[a-zA-Z0-9._-]+@[a-z0-9]+\\.+[a-z0-9]+";

        if(emailString.matches(emailPattern))
        {
            Friend friend = new Friend(idNum, emailString, firstNameString, surnameString);

            myDB.addNewFriend(friend);
    //            startActivity(new Intent(this, ViewAllFriends.class));

        }
        else
        {
            Toast.makeText(this, "Email not valid", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_home) {
            startActivity(new Intent(this, MainActivity.class));
        }
        else if(id == R.id.action_search)
        {
//            startActivity(new Intent(this, SearchFriends.class));
            Toast.makeText(this, "Already on Add Friend Page", Toast.LENGTH_SHORT).show();
        }
        else if(id == R.id.action_view)
        {
//            startActivity(new Intent(this, ViewAllFriends.class));
            Toast.makeText(this, "Already on Add Friend Page", Toast.LENGTH_SHORT).show();
        }
        else if(id == R.id.action_add){
            Toast.makeText(this, "Already on# Add Friend Page", Toast.LENGTH_SHORT).show();
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

答:
this is a really easy error to fix,
you should basically read the error message, is part of your career
you have an inserting error because...

table friends_table has no column named EMAIL (code 1):

So what do you think could be?
Of course you have to create a column EMAIL.
You will think of course that you created the email but what you miss are the spaces.  Basically when you create a Table you have to take care that the SQL query is perfectly formed.

so instead to write "TEXT" you should write " TEXT" leaving a space on both the fields EMAIL and SURNAME because they are wrong written in this way.

Also you should consider that if you run you app with an emulator or device that you have to uninstall your app before, so that when you will relaunch with Run will be installed from scratch a new "correct" database.

Body:
New to Android Studio and SQLite so some help would be appreciated.

Creating an app where someone enters in their friend details and it adds them to a Database.

I've created my Database Class and my Activity to add friends but whenever I attempt to add them to the database, I get an error in the logcat stating:

11-16 20:40:20.083 2641-2641/com.example.kod45.myapplication E/SQLiteDatabase: Error inserting EMAIL=pm@gmail.com NAME=paul ID=1 SURNAME=pail
                                                                           android.database.sqlite.SQLiteException: table friends_table has no column named EMAIL (code 1): , while compiling: INSERT INTO friends_table(EMAIL,NAME,ID,SURNAME) VALUES (?,?,?,?)
                                                                           #################################################################
                                                                           Error Code : 1 (SQLITE_ERROR)
                                                                           Caused By : SQL(query) error or missing database.
                                                                            (table friends_table has no column named EMAIL (code 1): , while compiling: INSERT INTO friends_table(EMAIL,NAME,ID,SURNAME) VALUES (?,?,?,?))

Here is my Database Handler:

public class DBHandler extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "Friends.db";
    public static final String TABLE_NAME = "friends_table";
    public static final String ID_COL = "ID";
    public static final String EMAIL = "EMAIL";
    public static final String FIRST_NAME = "NAME";
    public static final String SURNAME = "SURNAME";

public DBHandler(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

public void onCreate(SQLiteDatabase db)
{
    String CREATE_FRIENDS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + ID_COL + " INTEGER PRIMARY KEY,"
            + EMAIL + "TEXT,"
            + FIRST_NAME + "TEXT,"
            + SURNAME + "TEXT" + ")";

    db.execSQL(CREATE_FRIENDS_TABLE);
}

public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
    // example of drop old tables and Re-
    //create tables.
    //you can alter tables such as add
    //columns, etc. but not drop tables
    db.execSQL("drop table if exists "
            + TABLE_NAME);
    onCreate(db);
}

public void addNewFriend(Friend newFriend)
{
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(ID_COL, newFriend.getFriendID());
    values.put(EMAIL, newFriend.getEmailAddress());
    values.put(FIRST_NAME, newFriend.getFirstName());
    values.put(SURNAME, newFriend.getSurname());

    db.insert(TABLE_NAME, null, values);
    db.close();
}

public ArrayList<Friend> getAllFriends()
{
    ArrayList<Friend> friendList = new ArrayList<Friend>();

    String selectQuery = "SELECT * FROM " + TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if(cursor.moveToFirst()) {
        do
            {
                Friend friend = new Friend();
                friend.setFriendID(Integer.parseInt(cursor.getString(0)));
                friend.setEmailAddress(cursor.getString(1));
                friend.setFirstName(cursor.getString(2));
                friend.setSurname(cursor.getString(3));

                //Adding to list
                friendList.add(friend);
            }
            while (cursor.moveToNext()) ;

        }
    return friendList;
    }

}

And also how I am adding:

    public class AddFriends extends AppCompatActivity {
        DBHandler myDB;
        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friends);
        myDB = new DBHandler(this);
    }

    public void addFriend(View v) {
        EditText email = (EditText) findViewById(R.id.emailText);
        EditText firstName = (EditText) findViewById(R.id.firstnameText);
        EditText surname = (EditText) findViewById(R.id.surnameText);
        EditText id = (EditText) findViewById (R.id.idText);
        Button addData = (Button)findViewById(R.id.addFriendButton);

        //Passing them as strings
        String emailString = email.getText().toString();
        String firstNameString = firstName.getText().toString();
        String surnameString = surname.getText().toString();
        int idNum = Integer.parseInt(id.getText().toString());

        String emailPattern = "[a-zA-Z0-9._-]+@[a-z0-9]+\\.+[a-z0-9]+";

        if(emailString.matches(emailPattern))
        {
            Friend friend = new Friend(idNum, emailString, firstNameString, surnameString);

            myDB.addNewFriend(friend);
    //            startActivity(new Intent(this, ViewAllFriends.class));

        }
        else
        {
            Toast.makeText(this, "Email not valid", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_home) {
            startActivity(new Intent(this, MainActivity.class));
        }
        else if(id == R.id.action_search)
        {
//            startActivity(new Intent(this, SearchFriends.class));
            Toast.makeText(this, "Already on Add Friend Page", Toast.LENGTH_SHORT).show();
        }
        else if(id == R.id.action_view)
        {
//            startActivity(new Intent(this, ViewAllFriends.class));
            Toast.makeText(this, "Already on Add Friend Page", Toast.LENGTH_SHORT).show();
        }
        else if(id == R.id.action_add){
            Toast.makeText(this, "Already on# Add Friend Page", Toast.LENGTH_SHORT).show();
        }

        return super.onOptionsItemSelected(item);
    }
}


答:
Your table create SQL does not have spaces between column names and column types for the last 3 columns.

Change

```<code>    String CREATE_FRIENDS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
        + ID_COL + " INTEGER PRIMARY KEY,"
        + EMAIL + "TEXT,"
        + FIRST_NAME + "TEXT,"
        + SURNAME + "TEXT" + ")";
</code>```

to :-

```<code>    String CREATE_FRIENDS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
        + ID_COL + " INTEGER PRIMARY KEY,"
        + EMAIL + " TEXT,"
        + FIRST_NAME + " TEXT,"
        + SURNAME + " TEXT" + ")";
</code>```

then do one of the following

delete the App's data and rerun

uninstall the App and rerun

change public static final int DATABASE_VERSION = 1; to public static final int DATABASE_VERSION = 2; and rerun the App.

You may also wish to consider the following:

1) You can simplify looping through the cursor by using:-

```<code>    while(cursor.moveToNext) {
        ....
    }
</code>```

2) You may reduce issues with determining/calculating column offsets by taking advantage of the Cursor's getColumnIndex(columnname) method rather than hard coding the offsets.

With both 1 and 2 you code could be:-

```<code>while(cursor.moveToNext()) {
    Friend friend = new Friend();
    friend.setFriendID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID_COL))));
    friend.setEmailAddress(cursor.getString(cursor.getColumnIndex(EMAIL)));
    friend.setFirstName(cursor.getString(cursor.getColumnIndex(FIRST_NAME)));
    friend.setSurname(cursor.getString(cursor.getColumnIndex(SURNAME)));

    //Adding to list
    friendList.add(friend);
}
</code>```

Title: Error adding Data to my SQLite Database on Android Studio

Body:
Your table create SQL does not have spaces between column names and column types for the last 3 columns.

Change

    String CREATE_FRIENDS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
        + ID_COL + " INTEGER PRIMARY KEY,"
        + EMAIL + "TEXT,"
        + FIRST_NAME + "TEXT,"
        + SURNAME + "TEXT" + ")";

to :-

    String CREATE_FRIENDS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
        + ID_COL + " INTEGER PRIMARY KEY,"
        + EMAIL + " TEXT,"
        + FIRST_NAME + " TEXT,"
        + SURNAME + " TEXT" + ")";

then do one of the following

delete the App's data and rerun

uninstall the App and rerun

change public static final int DATABASE_VERSION = 1; to public static final int DATABASE_VERSION = 2; and rerun the App.

You may also wish to consider the following:

1) You can simplify looping through the cursor by using:-

    while(cursor.moveToNext) {
        ....
    }

2) You may reduce issues with determining/calculating column offsets by taking advantage of the Cursor's getColumnIndex(columnname) method rather than hard coding the offsets.

With both 1 and 2 you code could be:-

while(cursor.moveToNext()) {
    Friend friend = new Friend();
    friend.setFriendID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID_COL))));
    friend.setEmailAddress(cursor.getString(cursor.getColumnIndex(EMAIL)));
    friend.setFirstName(cursor.getString(cursor.getColumnIndex(FIRST_NAME)));
    friend.setSurname(cursor.getString(cursor.getColumnIndex(SURNAME)));

    //Adding to list
    friendList.add(friend);
}


问:
Vim Regex: Two regexes conflicting
In trying to write a syntax file for an in-house language, I'm trying to capture the first word of every line preceded by a / and assign it to one hi def link, and the second word of every line (enclosed by / and /) and assign it to a second hi def link.

For the syntax:

```<code>cmo/create/mo1///tri
createpts/brick/xyz/2,2,2/0.,0.,0./1.,1.,1./1,1,1
</code>```

I am trying to capture cmo and createpts as argOne, and create and brick as argTwo:

```<code>syn match argOne '^\zs[^\/]\+\ze\/'
syn match argTwo '^[^\/]\+\/\zs[^\/]\+\ze\/'

hi def link argOne         Type
hi def link argTwo         Statement
</code>```

The issue is that they conflict: when both sys match statements are present, ViM only captures those found by argOne. But in isolation, when one of the two syn match is commented out, either argOne or argTwo will work perfectly.

How can I get these two statements to play nice with each other?

答:
One solution is to create contained matches, define an argOneTwo which matches the first two arguments, and then provide matches for the first and the second match:

```<code>syn match argOne '^\zs[^\/]\+\ze' contained
syn match argTwo '\/\zs[^\/]\+\ze\/' contained
syn match argOneTwo '^\zs[^\/]\+\/[^\/]\+\ze\/' contains=argOne,argTwo

hi def link argTwo         Statement
hi def link argOne         Type
</code>```

Title: Vim Regex: Two regexes conflicting

Body:
In trying to write a syntax file for an in-house language, I'm trying to capture the first word of every line preceded by a / and assign it to one hi def link, and the second word of every line (enclosed by / and /) and assign it to a second hi def link.

For the syntax:

cmo/create/mo1///tri
createpts/brick/xyz/2,2,2/0.,0.,0./1.,1.,1./1,1,1

I am trying to capture cmo and createpts as argOne, and create and brick as argTwo:

syn match argOne '^\zs[^\/]\+\ze\/'
syn match argTwo '^[^\/]\+\/\zs[^\/]\+\ze\/'

hi def link argOne         Type
hi def link argTwo         Statement

The issue is that they conflict: when both sys match statements are present, ViM only captures those found by argOne. But in isolation, when one of the two syn match is commented out, either argOne or argTwo will work perfectly.

How can I get these two statements to play nice with each other?

Body:
One solution is to create contained matches, define an argOneTwo which matches the first two arguments, and then provide matches for the first and the second match:

syn match argOne '^\zs[^\/]\+\ze' contained
syn match argTwo '\/\zs[^\/]\+\ze\/' contained
syn match argOneTwo '^\zs[^\/]\+\/[^\/]\+\ze\/' contains=argOne,argTwo

hi def link argTwo         Statement
hi def link argOne         Type


问:
Difference between `PowerShellVersion` and `PowerShellHostVersion`
Summary

What's the difference between the PowerShell Module Manifest values PowerShellVersion and PowerShellHostVersion?

Long Version

When creating a new module manifest there are settings for both the minimum version of PowerShell required by this module, and also the minimum version of the PowerShell Host required.  i.e.

New-ModuleManifest -Path '.\MyModule.psd1' -PowerShellVersion '5.0' -PowerShellHostVersion '2.0'

PowerShellVersion relates to $PSVersionTable.PSVersion.Major (NB: Relates to the major version since valid values all have 0 set for their minor version / no build or revision numbers).

PowerShellHostVersion is the one I'm not clear on.  My belief is that this relates to $Host.Version (i.e. with PowerShellHostName relating to $Host.Name).  However, in my experience both ISE (Windows PowerShell ISE Host) and ConsoleHost have their version numbers inline with the PS version; so it seems odd to require that these be out of sync with the PS version as implied in the example.  My hope is these are rarely used parameters for rare use cases; but I want to ensure I've understood correctly what these are for, and if there is a common scenario where they're applicable.

The example values in MSDN's documentation differ (i.e. PowershellVersion is given 5.0, whilst PowershellHostVersion gets 2.0)

The Official Documentation just gives a circular description (i.e. adds no more information than the parameter name itself implies).

答:
My belief is that this relates to $Host.Version

Your belief is correct. Tested this by amending the manifest produced to set the value of PowerShellHostVersion to 6.0. When importing, get the error:

```<code>Import-Module : The current Windows PowerShell host is: 'ConsoleHost' (version
5.1.15063.674). The module 'C:\MyModule.psd1' requires a minimum Windows PowerShell
host version of '6.0' to run.
At line:1 char:1
+ Import-Module .\MyModule.psd1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (C:\MyModule.psd1:String) [Import-M
   odule], InvalidOperationException
    + FullyQualifiedErrorId : Modules_InsufficientPowerShellHostVersion,Microsoft.PowerShel
   l.Commands.ImportModuleCommand
</code>```

Version related to $Host.Version, and name relates to $Host.Name

```<code>PS C:\> $Host.Version

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      15063  674
</code>```

This Shavy Levy blog post and the linked PowerShell Team follow up from 2010 give an interesting history. On my machine I get the same output for $Host.Version from Console and ISE hosts.

No clue what version Power GUI and other mentioned hosts use.

Body:
My belief is that this relates to $Host.Version

Your belief is correct. Tested this by amending the manifest produced to set the value of PowerShellHostVersion to 6.0. When importing, get the error:

Import-Module : The current Windows PowerShell host is: 'ConsoleHost' (version
5.1.15063.674). The module 'C:\MyModule.psd1' requires a minimum Windows PowerShell
host version of '6.0' to run.
At line:1 char:1
+ Import-Module .\MyModule.psd1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (C:\MyModule.psd1:String) [Import-M
   odule], InvalidOperationException
    + FullyQualifiedErrorId : Modules_InsufficientPowerShellHostVersion,Microsoft.PowerShel
   l.Commands.ImportModuleCommand

Version related to $Host.Version, and name relates to $Host.Name

PS C:\> $Host.Version

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      15063  674

This Shavy Levy blog post and the linked PowerShell Team follow up from 2010 give an interesting history. On my machine I get the same output for $Host.Version from Console and ISE hosts.

No clue what version Power GUI and other mentioned hosts use.


问:
Can't use protobuf in cmakelists.txt
I am trying to run the example given in protobuf repo here, the c++ version. I have successfully installed the library and am able to run the Makefile. But on running the CMakeLists.txt, I get this error:

```<code>CMake Error at CMakeLists.txt:9 (find_package):
  Could not find a package configuration file provided by "protobuf" with any
  of the following names:

    protobufConfig.cmake
    protobuf-config.cmake

  Add the installation prefix of "protobuf" to CMAKE_PREFIX_PATH or set
  "protobuf_DIR" to a directory containing one of the above files.  If
  "protobuf" provides a separate development package or SDK, be sure it has
  been installed.

-- Configuring incomplete, errors occurred!
See also "/home/cortana/Projects/CppProjects/proto/build/CMakeFiles/CMakeOutput.log".
See also "/home/cortana/Projects/CppProjects/proto/build/CMakeFiles/CMakeError.log".
</code>```

I have updated my LD_LIBRARY_PATH but this error is still there. How do I remove this error?

EDIT:

CMakeLists.txt:

```<code># Minimum CMake required
cmake_minimum_required(VERSION 2.8.12)

# Project
project(protobuf-examples)

include(FindProtobuf)
# Find required protobuf package
find_package(protobuf CONFIG REQUIRED)

if(protobuf_VERBOSE)
  message(STATUS "Using Protocol Buffers ${Protobuf_VERSION}")
endif()

set(CMAKE_INCLUDE_CURRENT_DIR TRUE)

set(CMAKE_PREFIX_PATH
    ${CMAKE_PREFIX_PATH}
    ${THIRDPARTY_DIR}/protobuf-3.1.0
)

include_directories(${ProtobufIncludePath})

# http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_build_my_MSVC_application_with_a_static_runtime.3F
if(MSVC AND protobuf_MSVC_STATIC_RUNTIME)
  foreach(flag_var
      CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
      CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
    if(${flag_var} MATCHES "/MD")
      string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
    endif(${flag_var} MATCHES "/MD")
  endforeach()
endif()

foreach(example add_person list_people)
  set(${example}_SRCS ${example}.cc)
  set(${example}_PROTOS addressbook.proto)

  #Code Generation
  if(protobuf_MODULE_COMPATIBLE) #Legacy Support
    protobuf_generate_cpp(${example}_PROTO_SRCS ${example}_PROTO_HDRS ${${example}_PROTOS})
    list(APPEND ${example}_SRCS ${${example}_PROTO_SRCS} ${${example}_PROTO_HDRS})
  else()

    foreach(proto_file ${${example}_PROTOS})
      get_filename_component(proto_file_abs ${proto_file} ABSOLUTE)
      get_filename_component(basename ${proto_file} NAME_WE)
      set(generated_files ${basename}.pb.cc ${basename}.pb.h)
      list(APPEND ${example}_SRCS ${generated_files})

      add_custom_command(
        OUTPUT ${generated_files}
        COMMAND protobuf::protoc
        ARGS --cpp_out ${CMAKE_CURRENT_BINARY_DIR} -I ${CMAKE_CURRENT_SOURCE_DIR} ${proto_file_abs}
        COMMENT "Generating ${generated_files} from ${proto_file}"
        VERBATIM
      )
    endforeach()
  endif()

  #Executable setup
  set(executable_name ${example}_cpp)
  add_executable(${executable_name} ${${example}_SRCS} ${${example}_PROTOS})
  if(protobuf_MODULE_COMPATIBLE) #Legacy mode
    target_include_directories(${executable_name} PUBLIC ${PROTOBUF_INCLUDE_DIRS})
    target_link_libraries(${executable_name} ${PROTOBUF_LIBRARIES})
  else()
    target_link_libraries(${executable_name} protobuf::libprotobuf)
  endif()

endforeach()
</code>```

EDIT 2:

After trying for 2 hours, I couldn't fix the CMakeLists.txt provided by google examples. I wrote this basic one and it works for me:

```<code>PROJECT(protopuff)
CMAKE_MINIMUM_REQUIRED (VERSION 3.5)
SET(CMAKE_CXX_FLAGS "-g -Wall -Werror -std=c++11")

INCLUDE(FindProtobuf)
FIND_PACKAGE(Protobuf REQUIRED)
INCLUDE_DIRECTORIES(${PROTOBUF_INCLUDE_DIR})
PROTOBUF_GENERATE_CPP(PROTO_SRC PROTO_HEADER addressbook.proto)
ADD_LIBRARY(proto ${PROTO_HEADER} ${PROTO_SRC})

INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
ADD_EXECUTABLE(${CMAKE_PROJECT_NAME}_add add_person.cc)
ADD_EXECUTABLE(${CMAKE_PROJECT_NAME}_list list_people.cc)
TARGET_LINK_LIBRARIES(${CMAKE_PROJECT_NAME}_add proto ${PROTOBUF_LIBRARY})
TARGET_LINK_LIBRARIES(${CMAKE_PROJECT_NAME}_list proto ${PROTOBUF_LIBRARY})
</code>```

答:
Your problem is here:

```<code>find_package(protobuf CONFIG REQUIRED)
</code>```

The name should start with uppercase: Protobuf. And that is the reason why your version is working; because in there, you have used correct case (last code snippet line 6):

```<code>find_package(Protobuf REQUIRED)
</code>```

Here cmake documentation for find_package

The command searches for a file called <name>Config.cmake or <lower-case-name>-config.cmake for each name specified.

Title: Can't use protobuf in cmakelists.txt

Body:
I am trying to run the example given in protobuf repo here, the c++ version. I have successfully installed the library and am able to run the Makefile. But on running the CMakeLists.txt, I get this error:

CMake Error at CMakeLists.txt:9 (find_package):
  Could not find a package configuration file provided by "protobuf" with any
  of the following names:

    protobufConfig.cmake
    protobuf-config.cmake

  Add the installation prefix of "protobuf" to CMAKE_PREFIX_PATH or set
  "protobuf_DIR" to a directory containing one of the above files.  If
  "protobuf" provides a separate development package or SDK, be sure it has
  been installed.

-- Configuring incomplete, errors occurred!
See also "/home/cortana/Projects/CppProjects/proto/build/CMakeFiles/CMakeOutput.log".
See also "/home/cortana/Projects/CppProjects/proto/build/CMakeFiles/CMakeError.log".

I have updated my LD_LIBRARY_PATH but this error is still there. How do I remove this error?

EDIT:

CMakeLists.txt:

# Minimum CMake required
cmake_minimum_required(VERSION 2.8.12)

# Project
project(protobuf-examples)

include(FindProtobuf)
# Find required protobuf package
find_package(protobuf CONFIG REQUIRED)

if(protobuf_VERBOSE)
  message(STATUS "Using Protocol Buffers ${Protobuf_VERSION}")
endif()

set(CMAKE_INCLUDE_CURRENT_DIR TRUE)

set(CMAKE_PREFIX_PATH
    ${CMAKE_PREFIX_PATH}
    ${THIRDPARTY_DIR}/protobuf-3.1.0
)

include_directories(${ProtobufIncludePath})

# http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_build_my_MSVC_application_with_a_static_runtime.3F
if(MSVC AND protobuf_MSVC_STATIC_RUNTIME)
  foreach(flag_var
      CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
      CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
    if(${flag_var} MATCHES "/MD")
      string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
    endif(${flag_var} MATCHES "/MD")
  endforeach()
endif()

foreach(example add_person list_people)
  set(${example}_SRCS ${example}.cc)
  set(${example}_PROTOS addressbook.proto)

  #Code Generation
  if(protobuf_MODULE_COMPATIBLE) #Legacy Support
    protobuf_generate_cpp(${example}_PROTO_SRCS ${example}_PROTO_HDRS ${${example}_PROTOS})
    list(APPEND ${example}_SRCS ${${example}_PROTO_SRCS} ${${example}_PROTO_HDRS})
  else()

    foreach(proto_file ${${example}_PROTOS})
      get_filename_component(proto_file_abs ${proto_file} ABSOLUTE)
      get_filename_component(basename ${proto_file} NAME_WE)
      set(generated_files ${basename}.pb.cc ${basename}.pb.h)
      list(APPEND ${example}_SRCS ${generated_files})

      add_custom_command(
        OUTPUT ${generated_files}
        COMMAND protobuf::protoc
        ARGS --cpp_out ${CMAKE_CURRENT_BINARY_DIR} -I ${CMAKE_CURRENT_SOURCE_DIR} ${proto_file_abs}
        COMMENT "Generating ${generated_files} from ${proto_file}"
        VERBATIM
      )
    endforeach()
  endif()

  #Executable setup
  set(executable_name ${example}_cpp)
  add_executable(${executable_name} ${${example}_SRCS} ${${example}_PROTOS})
  if(protobuf_MODULE_COMPATIBLE) #Legacy mode
    target_include_directories(${executable_name} PUBLIC ${PROTOBUF_INCLUDE_DIRS})
    target_link_libraries(${executable_name} ${PROTOBUF_LIBRARIES})
  else()
    target_link_libraries(${executable_name} protobuf::libprotobuf)
  endif()

endforeach()

EDIT 2:

After trying for 2 hours, I couldn't fix the CMakeLists.txt provided by google examples. I wrote this basic one and it works for me:

PROJECT(protopuff)
CMAKE_MINIMUM_REQUIRED (VERSION 3.5)
SET(CMAKE_CXX_FLAGS "-g -Wall -Werror -std=c++11")

INCLUDE(FindProtobuf)
FIND_PACKAGE(Protobuf REQUIRED)
INCLUDE_DIRECTORIES(${PROTOBUF_INCLUDE_DIR})
PROTOBUF_GENERATE_CPP(PROTO_SRC PROTO_HEADER addressbook.proto)
ADD_LIBRARY(proto ${PROTO_HEADER} ${PROTO_SRC})

INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
ADD_EXECUTABLE(${CMAKE_PROJECT_NAME}_add add_person.cc)
ADD_EXECUTABLE(${CMAKE_PROJECT_NAME}_list list_people.cc)
TARGET_LINK_LIBRARIES(${CMAKE_PROJECT_NAME}_add proto ${PROTOBUF_LIBRARY})
TARGET_LINK_LIBRARIES(${CMAKE_PROJECT_NAME}_list proto ${PROTOBUF_LIBRARY})

Body:
Your problem is here:

find_package(protobuf CONFIG REQUIRED)

The name should start with uppercase: Protobuf. And that is the reason why your version is working; because in there, you have used correct case (last code snippet line 6):

find_package(Protobuf REQUIRED)

Here cmake documentation for find_package

The command searches for a file called <name>Config.cmake or <lower-case-name>-config.cmake for each name specified.

ContentLicense: CC BY-SA 4.0


问:
Getting rid of ANSI escape characters when viewing ri in (Mac)Vim
I'm having trouble viewing ri documentation within gvim and MacVim (tried it on both) Some of the ri documentation includes text decorations that look fine when viewed in a terminal window, but include ANSI escape characters when viewing in gvim/MacVim. For example, the following ri snippet from $ri class looks like this in the terminal:

Returns the class of obj, now
  preferred over Object#type

And this in gvim:

Returns the class of [4mobj[m, now preferred over [7mObject#type[m,

It'd be great to be able to reference legible ri docs within gvim. Any ideas on where to begin looking to fix this?

答:
Try running ri like this:

```<code>ri --format=rdoc
</code>```

AFAIK, the rdoc format is plain text so you won't have to filter out the ANSI escape sequences.

You can probably get "real" plain text by making a shell script like this:

```<code>ri --format=bs $@ | sed 's:.^H::g'
</code>```

Where ^H is a raw Ctrl-H (or whatever backspace is for you), then call that shell script instead of ri.

Body:
Try running ri like this:

ri --format=rdoc

AFAIK, the rdoc format is plain text so you won't have to filter out the ANSI escape sequences.

You can probably get "real" plain text by making a shell script like this:

ri --format=bs $@ | sed 's:.^H::g'

Where ^H is a raw Ctrl-H (or whatever backspace is for you), then call that shell script instead of ri.


问:
Insert Data from old SQL table, to new one with columns changed to rows
I currently have a table that looks similar to this:

Old Table(example only)

I need to import the data to a new table, but making the column headers into rows and value for each one. Similar to this.

New Table(example only)

Would I use a Pivot or an Unpivot to do this? I have a lot of columns with about 700 rows that need to be converted this way.

答:
if you don't have lot of columns you can always try something like :</p>

```<code>SELECT SN, 'Property1' as Property, Property1 as Value from <TABLE>
UNION ALL
SELECT SN, 'Property2' as Property, Property2 as Value from <TABLE>
UNION ALL
SELECT SN, 'Property3' as Property, Property3 as Value from <TABLE>
</code>```

Body:
if you don't have lot of columns you can always try something like :

SELECT SN, 'Property1' as Property, Property1 as Value from <TABLE>
UNION ALL
SELECT SN, 'Property2' as Property, Property2 as Value from <TABLE>
UNION ALL
SELECT SN, 'Property3' as Property, Property3 as Value from <TABLE>


问:
Python requests fails when tryign to connect to .onion site
I'm trying to get a webpage which is hosted in the tor network. I'm using the following code:

```<code>import requests

def get_tor_session():
    session = requests.session()
    session.proxies = {'http':  'socks5://127.0.0.1:9150',
                       'https': 'socks5://127.0.0.1:9150'}
    return session

session = get_tor_session()
</code>```

When I try to get a normal website it works fine, for example: print(session.get("http://httpbin.org/ip").text) prints {"origin": "80.67.172.162"}

But when I try it on a .onion site, it fails with this error:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/socks.py", line 813, in connect
    negotiate(self, dest_addr, dest_port)
  File "/usr/local/lib/python3.6/site-packages/socks.py", line 477, in _negotiate_SOCKS5
    CONNECT, dest_addr)
  File "/usr/local/lib/python3.6/site-packages/socks.py", line 540, in _SOCKS5_request
    resolved = self._write_SOCKS5_address(dst, writer)
  File "/usr/local/lib/python3.6/site-packages/socks.py", line 592, in _write_SOCKS5_address
    addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG)
  File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 745, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known

During handling of the above exception, another exception occurred:
</code>```

...

```<code>Traceback (most recent call last):
  File "spider.py", line 13, in <module>
    print(session.get("http://zqktlwi4fecvo6ri.onion/").text)
  File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 521, in get
    return self.request('GET', url, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/requests/adapters.py", line 508, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: SOCKSHTTPConnectionPool(host='zqktlwi4fecvo6ri.onion', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.contri
b.socks.SOCKSConnection object at 0x106fd62e8>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))
</code>```

答:
When using the socks5 scheme, domains are resolved locally by the client's DNS server. But 'normal' DNS servers can't resolve .onion domains and so your request fails.

From docs.python-requests.org:

Using the scheme socks5 causes the DNS resolution to happen on the client, rather than on the proxy server. This is in line with curl, which uses the scheme to decide whether to do the DNS resolution on the client or proxy. If you want to resolve the domains on the proxy server, use socks5h as the scheme.

So, in order to connect to .onion sites you should let TOR resolve the domain. This is possible if you use the socks5h sheme in the proxies dictionary.

```<code>import requests

session = requests.session()
session.proxies = {'http': 'socks5h://127.0.0.1:9150', 'https': 'socks5h://127.0.0.1:9150'}
response = session.get("https://3g2upl4pq6kufc4m.onion/")
print(response)
#<Response [200]>
</code>```

Note that you may have to install extra dependencies.

```<code>pip install requests[socks]
</code>```

Body:
I'm trying to get a webpage which is hosted in the tor network. I'm using the following code:

import requests

def get_tor_session():
    session = requests.session()
    session.proxies = {'http':  'socks5://127.0.0.1:9150',
                       'https': 'socks5://127.0.0.1:9150'}
    return session

session = get_tor_session()

When I try to get a normal website it works fine, for example: print(session.get("http://httpbin.org/ip").text) prints {"origin": "80.67.172.162"}

But when I try it on a .onion site, it fails with this error:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/socks.py", line 813, in connect
    negotiate(self, dest_addr, dest_port)
  File "/usr/local/lib/python3.6/site-packages/socks.py", line 477, in _negotiate_SOCKS5
    CONNECT, dest_addr)
  File "/usr/local/lib/python3.6/site-packages/socks.py", line 540, in _SOCKS5_request
    resolved = self._write_SOCKS5_address(dst, writer)
  File "/usr/local/lib/python3.6/site-packages/socks.py", line 592, in _write_SOCKS5_address
    addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG)
  File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 745, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known

During handling of the above exception, another exception occurred:

...

Traceback (most recent call last):
  File "spider.py", line 13, in <module>
    print(session.get("http://zqktlwi4fecvo6ri.onion/").text)
  File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 521, in get
    return self.request('GET', url, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/requests/adapters.py", line 508, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: SOCKSHTTPConnectionPool(host='zqktlwi4fecvo6ri.onion', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.contri
b.socks.SOCKSConnection object at 0x106fd62e8>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))

Body:
When using the socks5 scheme, domains are resolved locally by the client's DNS server. But 'normal' DNS servers can't resolve .onion domains and so your request fails.

From docs.python-requests.org:

Using the scheme socks5 causes the DNS resolution to happen on the client, rather than on the proxy server. This is in line with curl, which uses the scheme to decide whether to do the DNS resolution on the client or proxy. If you want to resolve the domains on the proxy server, use socks5h as the scheme.

So, in order to connect to .onion sites you should let TOR resolve the domain. This is possible if you use the socks5h sheme in the proxies dictionary.

import requests

session = requests.session()
session.proxies = {'http': 'socks5h://127.0.0.1:9150', 'https': 'socks5h://127.0.0.1:9150'}
response = session.get("https://3g2upl4pq6kufc4m.onion/")
print(response)
#<Response [200]>

Note that you may have to install extra dependencies.

pip install requests[socks]


问:
PHP - How can I Create Dynamic Bootstrap Rows & Columns in WordPress based on how many sub arrays an array has?
I am using the Advanced Custom Fields plugin in WordPress to display rows of different employees. Basically, a User can input data in the Admin section, and it creates an array that can be used to display the data.

Currently, The array is storing 5 values(subarrays):

```<code>array (
    0 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/jaime.jpg',
            'profile_name' => 'Jaime Daignault',
            'profile_job' => 'Executive Director',
            'profile_email' => 'Jaimie.Daignault@ocdd.org',
        ),
    1 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/beth.jpg',
            'profile_name' => 'Beth Kessler',
            'profile_job' => 'Family Engagement Coordinator',
            'profile_email' => 'Beth.Kessler@ocdd.org',
        ),
    2 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/carrie.jpg',
            'profile_name' => 'Carrie Salehiamin',
            'profile_job' => 'Operations Manager',
            'profile_email' => 'CarrieS@ocdd.org',
        ),
    3 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/leslie.jpg',
            'profile_name' => 'Leslie Sutton',
            'profile_job' => 'Policy Director',
            'profile_email' => 'Leslie.Sutton@ocdd.org',
        ),
    4 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/ryley.jpg',
            'profile_name' => 'Ryley Newport',
            'profile_job' => 'Communications Director',
            'profile_email' => 'Ryley.newport@ocdd.org',
        ),
)
</code>```

I want to be able to create one Bootstrap row with 3 columns, if it has 3 subarrays. Otherwise, I want to create 2 rows, with 3 columns each, if there is more than 3 subarrays. So far this is what I created:

```<code>// Store Name of custom field(array) from Admin Section
<?php $repeater = get_field('staff'); ?>

<?php if(count($repeater) <= 3): ?>
    <?php while(have_rows('staff')) : the_row(); ?>
        <div class="row">
            <div class="col-md-4 col-sm-6 col-xs-12 staffBlock">
                <img src="<?php the_sub_field('profile_pic'); ?>" alt="Profile Pic">
                <h4 class="staffTitle"><?php the_sub_field('profile_name'); ?></h4>
                <p class="staffSubTitle"><?php the_sub_field('profile_job'); ?></p>
                <a class="staffEmail" href="mailto:<?php the_sub_field('profile_email'); ?>"><?php the_sub_field('profile_email'); ?></a>
            </div>
        </div>
    <?php endwhile; ?>

<?php elseif(count($repeater) > 3 && count(repeater) <= 6): ?>
    <?php while(have_rows('staff')) : the_row(); ?>
        // Display first row and 3 columns
        // Display second row and remaining columns
    <?php endwhile; ?>
<?php endif; ?>
</code>```

It works great if the Array has 3 subarrays, but I can't seem to wrap my head around how to create two different rows if it has more subarrays.

答:
A
 creates a new row, while a
 creates a column with the specified widths for each breakpoint. In your example then you will only get three columns per row on medium size screens and above.

I'm not familiar with ACF, but my basic concept code to insert a new row after every 3 columns would be something along the lines of:

```<code><?php $i=0; ?>
<div class="row">
    <?php while(have_rows('staff')) : the_row();
if (($i > 0) && ($i % 3 === 0)) { ?>
</div>
<div class="row">
    <?php }
$i++; ?>
    <div class="col-md-4 col-sm-6 col-xs-12 staffBlock">
        <img src="<?php the_sub_field('profile_pic'); ?>" alt="Profile Pic">
        <h4 class="staffTitle">
            <?php the_sub_field('profile_name'); ?></h4>
        <p class="staffSubTitle">
            <?php the_sub_field('profile_job'); ?></p>
        <a class="staffEmail" href="mailto:<?php the_sub_field('profile_email'); ?>"><?php the_sub_field('profile_email'); ?></a>
    </div>
    <?php endwhile; ?>
</div>
</code>```

Body:
I am using the Advanced Custom Fields plugin in WordPress to display rows of different employees. Basically, a User can input data in the Admin section, and it creates an array that can be used to display the data.

Currently, The array is storing 5 values(subarrays):

array (
    0 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/jaime.jpg',
            'profile_name' => 'Jaime Daignault',
            'profile_job' => 'Executive Director',
            'profile_email' => 'Jaimie.Daignault@ocdd.org',
        ),
    1 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/beth.jpg',
            'profile_name' => 'Beth Kessler',
            'profile_job' => 'Family Engagement Coordinator',
            'profile_email' => 'Beth.Kessler@ocdd.org',
        ),
    2 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/carrie.jpg',
            'profile_name' => 'Carrie Salehiamin',
            'profile_job' => 'Operations Manager',
            'profile_email' => 'CarrieS@ocdd.org',
        ),
    3 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/leslie.jpg',
            'profile_name' => 'Leslie Sutton',
            'profile_job' => 'Policy Director',
            'profile_email' => 'Leslie.Sutton@ocdd.org',
        ),
    4 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/ryley.jpg',
            'profile_name' => 'Ryley Newport',
            'profile_job' => 'Communications Director',
            'profile_email' => 'Ryley.newport@ocdd.org',
        ),
)

I want to be able to create one Bootstrap row with 3 columns, if it has 3 subarrays. Otherwise, I want to create 2 rows, with 3 columns each, if there is more than 3 subarrays. So far this is what I created:

// Store Name of custom field(array) from Admin Section
<?php $repeater = get_field('staff'); ?>

<?php if(count($repeater) <= 3): ?>
    <?php while(have_rows('staff')) : the_row(); ?>

                <img src="<?php the_sub_field('profile_pic'); ?>" alt="Profile Pic">

<?php the_sub_field('profile_name'); ?>

<?php the_sub_field('profile_job'); ?>

                <a class="staffEmail" href="mailto:<?php the_sub_field('profile_email'); ?>"><?php the_sub_field('profile_email'); ?>

    <?php endwhile; ?>

<?php elseif(count($repeater) > 3 && count(repeater) <= 6): ?>
    <?php while(have_rows('staff')) : the_row(); ?>
        // Display first row and 3 columns
        // Display second row and remaining columns
    <?php endwhile; ?>
<?php endif; ?>

It works great if the Array has 3 subarrays, but I can't seem to wrap my head around how to create two different rows if it has more subarrays.

Body:
A <div class="row"> creates a new row, while a <div class="col-md-4 col-sm-6 col-xs-12"> creates a column with the specified widths for each breakpoint. In your example then you will only get three columns per row on medium size screens and above.

I'm not familiar with ACF, but my basic concept code to insert a new row after every 3 columns would be something along the lines of:

<?php $i=0; ?>
<div class="row">
    <?php while(have_rows('staff')) : the_row();
if (($i > 0) && ($i % 3 === 0)) { ?>
</div>
<div class="row">
    <?php }
$i++; ?>
    <div class="col-md-4 col-sm-6 col-xs-12 staffBlock">
        <img src="<?php the_sub_field('profile_pic'); ?>" alt="Profile Pic">
        <h4 class="staffTitle">
            <?php the_sub_field('profile_name'); ?></h4>
        <p class="staffSubTitle">
            <?php the_sub_field('profile_job'); ?></p>
        <a class="staffEmail" href="mailto:<?php the_sub_field('profile_email'); ?>"><?php the_sub_field('profile_email'); ?></a>
    </div>
    <?php endwhile; ?>
</div>


问:
HTTP REDIRECT(3xx) TO A DIFFERENT HOST
I'm building a HTTP client(for embedded devices) and I was wondering,
If I receive a HTTP 3xx response, and in the location header I get a hostname different from the one I had in the request. Should I disconnect the TCP connection and reconnect to the new host, or I just need to send a new request with a new host header and keep the old TCP connection alive.
Thank you</p>

答:
It doesn't make sense to reuse the original TCP connection if you're being redirected elsewhere. If my webserver only hosts example.com and I redirect you to elsewhere.net, my webserver will probably not respond to a request for elsewhere.net.

Worse, this also potentially sets you up for a great man-in-the-middle attack if my server redirects you to http://bank.com and you reuse the same TCP connection when sending a request to bank.com. My server can maliciously respond to requests with Host: bank.com, which isn't something you want to happen.

You can't assume the original connection can be reused unless the redirect is to the same same host with the same protocol.

Persistent HTTP connections are a little tricky with the number of client/server combinations. You can avoid the complexity by just wasting time closing and re-establishing each connection:

If you're implementing a HTTP/1.0 client, Connection: keep-alive isn't something you have to implement. Compliant servers should just close the connection after every request if you don't negotiate that you support persistent connections.

If you're implementing a HTTP/1.1 client and don't want to persist the connection, just send Connection: close with your request and a HTTP/1.1 server should close the connection.

Title: HTTP REDIRECT(3xx) TO A DIFFERENT HOST


问:
Comparing a Sympy expression with variable exponent to zero
I am wondering if there is a way to have SymPy recognize that expressions such as Pow(positive, variable) will always be greater than zero (assuming real numbers).

```<code>from sympy import *
init_session()

StictLessThan(0, 1)      # returns desired output
>>> False

StrictLessThan(0, x)     # returns desired output
>>> 0 < x

StrictLessThan(0, 2**x)  # returns undesired output, but not surprising
>>> 0 < 2**x

(2**x).is_comparable     # From this I assume that I would have to define my own function
>>> False

some_function(0, 2**x)   # does this exist built into the SymPy package?
>>> True
</code>```

I am aware that I can make my own function to do this, but I am curious as to the built-in capabilities and limitations of SymPy.

```<code>def is_positive_exponential(exponential):
    base, exponent = exponential.as_base_exp()
    return True if base > 0 else False
</code>```

答:
Consider that when x = pi*I/log(2) (a complex number),  the expression 2**x evaluates to -1 which is not positive.

If you tell SymPy that x is a real number, it will know that 2**x is positive.

```<code>x = Symbol('x', real=True)
StrictLessThan(0, 2**x)    # returns True
</code>```

See the list of possible assumptions. By default, Symbol('x') is assumed "commutative" but nothing else is assumed about it.

Body:
I am wondering if there is a way to have SymPy recognize that expressions such as Pow(positive, variable) will always be greater than zero (assuming real numbers).

from sympy import *
init_session()

StictLessThan(0, 1)      # returns desired output
>>> False

StrictLessThan(0, x)     # returns desired output
>>> 0 < x

StrictLessThan(0, 2**x)  # returns undesired output, but not surprising
>>> 0 < 2**x

(2**x).is_comparable     # From this I assume that I would have to define my own function
>>> False

some_function(0, 2**x)   # does this exist built into the SymPy package?
>>> True

I am aware that I can make my own function to do this, but I am curious as to the built-in capabilities and limitations of SymPy.

def is_positive_exponential(exponential):
    base, exponent = exponential.as_base_exp()
    return True if base > 0 else False

Body:
Consider that when x = pi*I/log(2) (a complex number),  the expression 2**x evaluates to -1 which is not positive.

If you tell SymPy that x is a real number, it will know that 2**x is positive.

x = Symbol('x', real=True)
StrictLessThan(0, 2**x)    # returns True

See the list of possible assumptions. By default, Symbol('x') is assumed "commutative" but nothing else is assumed about it.


问:
How do I prevent JAXB from binding superclass methods of the @XmlRootElement when marshalling?
I have a class that is annotated as the @XmlRootElement with @XmlAccessorType(XmlAccessType.NONE).  The problem that I am having is that the superclass's methods are being bound, when I do not want them to be bound, and cannot update the class.  I am hoping there is an annotation that I can put on the root element class to prevent this from happening.

Example:

```<code>@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Person extends NamedObject {

    @XmlElement
    public String getId() { ... }

}
</code>```

I would expect that only the methods annotated @XmlElement on Person would be bound and marshalled, but the superclass's methods are all being bound, as well.  The resulting XML then has too much information.

How do I prevent the superclass's methods from being bound without having to annotate the superclass, itself?

答:
I know this question is quite old, but there is a kind of solution which works if your superclass is in the same package as its child.

Create a package-info.java in your package and insert

```<code>@XmlAccessorType(XmlAccessType.NONE)
package my.package.with.classes;
</code>```

Obviously, it sets XmlAccessType.NONE upon all classes in the package. Myself, I use it in every package in our domain model. Therefore, I'm pretty safe. However, if your class is 'out of reach', f.e. it's in the JDK, use the solution from the accepted answer in [JAX-B] How can I ignore a superclass?.

I hope it's helpful for anynone who stumbles upon this question as I did.

OwnerDisplayName: Matt Fisher

Body:
I have a class that is annotated as the @XmlRootElement with @XmlAccessorType(XmlAccessType.NONE).  The problem that I am having is that the superclass's methods are being bound, when I do not want them to be bound, and cannot update the class.  I am hoping there is an annotation that I can put on the root element class to prevent this from happening.

Example:

@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Person extends NamedObject {

    @XmlElement
    public String getId() { ... }

}

I would expect that only the methods annotated @XmlElement on Person would be bound and marshalled, but the superclass's methods are all being bound, as well.  The resulting XML then has too much information.

How do I prevent the superclass's methods from being bound without having to annotate the superclass, itself?

LastEditorDisplayName: Matt Fisher

Body:
I know this question is quite old, but there is a kind of solution which works if your superclass is in the same package as its child.

Create a package-info.java in your package and insert

@XmlAccessorType(XmlAccessType.NONE)
package my.package.with.classes;

Obviously, it sets XmlAccessType.NONE upon all classes in the package. Myself, I use it in every package in our domain model. Therefore, I'm pretty safe. However, if your class is 'out of reach', f.e. it's in the JDK, use the solution from the accepted answer in [JAX-B] How can I ignore a superclass?.

I hope it's helpful for anynone who stumbles upon this question as I did.


问:
beeline cannot connect to hive2server
Enter username for jdbc:hive2://localhost:10001/default:
Enter password for jdbc:hive2://localhost:10001/default:
17/08/19 09:25:14 [main]: WARN jdbc.HiveConnection: Failed to connect to localhost:10001
Could not open connection to the HS2 server. Please check the server URI and if the URI is correct, then ask the administrator to check the server status.
Error: Could not open client transport with JDBC Uri: jdbc:hive2://localhost:10001/default: java.net.ConnectException: Connection refused (Connection refused) (state=08S01,code=0)
Beeline version 2.3.0 by Apache Hive
beeline> show tables;
No current connection
beeline>

I tried to changing the xml properties also but struck in same place

答:
Looks like you are connecting to the wrong port number:

```<code> jdbc:hive2://localhost:10001
</code>```

If you did not change the hive-site.xml, thrift port is 10000. If you still want to connect to 10001 which is used by thrift on Http, you need to add "transportMode=http" in your beeline connection string.

Title: beeline cannot connect to hive2server

Body:
Looks like you are connecting to the wrong port number:

 jdbc:hive2://localhost:10001

If you did not change the hive-site.xml, thrift port is 10000. If you still want to connect to 10001 which is used by thrift on Http, you need to add "transportMode=http" in your beeline connection string.


问:
Android Studio is slow (how to speed up)?
I recently upgraded from Eclipse to Android Studio and I'm not really liking the experience. I'm comparing them both on a Windows 7 64 bit ultimate with 16GB of ram and Intel i7 4770 running NVidia Geforce 780 with the latest NVidia drivers if it matters and I'm running the latest JDK and the latest Android Studio.

The Android Studio is very slow in building the project which I can live with but it's also extremely resource intensive and sometimes slows down the PC to a crawl.

Whenever I'm building or running anything in AS, my PC seems to become extremely sluggish. It also causes flickering of screen and occasionally blanking my second monitor if I click on "Gradle build running" spinner which I find very odd. The RAM usage also shoots up to ~3GB which I find excessive for doing nothing (this is when it's idle after a few builds).

In addition, the panels at the bottom of AS keep jumping around which is a horrible user experience (moves from Android to Messages to Version Control or anything else on an ad-hoc basis depending on what's happening which is very, very annoying).

What I would like to know is basically:

1) How do I make Android Studio run better? I may be doing something wrong or missing some updates that I'm not aware of and I'm sure others have also noticed these behaviors and have found some solutions to it.

2) How do I "pin" the bottom panels so that they don't jump around and instead, let me, the user, navigate to them when I wish to instead of automatically switching them?

Many thanks and my apologies again if it's not the correct place for these questions.

Edit 1
Some more comments:

I'm using the latest stable build as of today. The build is Android Studio 1.2.2 Build # AI-141.1980579, Build on June 3, 2015

The behavior happens when using either Java 7 or 8. It doesn't appear to be related to the version of Java.

I am not using Presentation Mode. Just the vanilla view.

Doing the changes to the build configuration (thanks to @Blackbelt and his answer) appears to have helped with the build but the other problems with sluggishness and general user experience remain.

答:
This might sound stupid and off topic but in my case I was using an external 4k Monitor with my MacBook Pro 13' (MacOS High Sierra, 2016) and I had the resolution set to the wrong scaled resolution. Switching to another scaled resolution where there was no "using a scaled resolution may affect performance" warning resolved my overall performance issues. In my case I had to increase the resolution to max.

So for me it was an overall performance problem which first surfaced with Android Studio, it was not an Android Studio specific problem.

EDIT 25.11.2017

As a result I had to increase font sizes in Android Studio:

and on my Mac in General. I followed some of these tips to get that done.


问:
Does it matter where I initialize my integer?
I'm trying to understand something. I'm still a beginner to c++ and I just created this little program where you input a value and it tells you whether it's even or odd. To do this, I made an integer called "result" which takes value, and then does % 2 operation.

However, my first mistake was that I put int result above "cin >> value" so for some reason that messed up the program and the number would always be even no matter what. Then when I put int result below "cin >> value" the program worked like it should. Why is it doing this?

Any help would be appreciated thank you. I apologize if this is a duplicate but I don't know what to search for.

```<code>#include <iostream>
#include <string>
#include "Human.h"
#include <ctime>
using namespace std;

int main() {

    int value = 0; // where I input
    cin >> value;
    // if you put int result above cin program changes.
    int result = value % 2;

    if (result == 0) {
        cout << "Even number." << endl;
    }
    else {
        cout << "Odd number." << endl;
    }

    return 0;
}
</code>```

答:
When you put int result = value % 2; before cin >> value;, your program will calculate the result before you put a value inside int value via your input.
So your program does calculate int result = 0 % 2;

Body:
I'm trying to understand something. I'm still a beginner to c++ and I just created this little program where you input a value and it tells you whether it's even or odd. To do this, I made an integer called "result" which takes value, and then does % 2 operation.

However, my first mistake was that I put int result above "cin >> value" so for some reason that messed up the program and the number would always be even no matter what. Then when I put int result below "cin >> value" the program worked like it should. Why is it doing this?

Any help would be appreciated thank you. I apologize if this is a duplicate but I don't know what to search for.

#include <iostream>
#include <string>
#include "Human.h"
#include <ctime>
using namespace std;

int main() {

    int value = 0; // where I input
    cin >> value;
    // if you put int result above cin program changes.
    int result = value % 2;

    if (result == 0) {
        cout << "Even number." << endl;
    }
    else {
        cout << "Odd number." << endl;
    }

    return 0;
}


问:
How to capitalize the first character of every sentence
Create an application with a method that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized.

This is what I have to far and I can't seem to get it right:

```<code>    //Create method to process string.
    private string Sentences(string input)
    {
        //Capitalize first letter of input.
        char firstLetter = char.ToUpper(input[0]);

        //Combine the capitalize letter with the rest of the input.
        input = firstLetter.ToString() + input.Substring(1);

        //Create a char array to hold all characters in input.
        char[] letters = new char[input.Length];

        //Read the characters from input into the array.
        for (int i = 0; i < input.Length; i++)
        {
            letters[i] = input[i];
        }

        //Loop through array to test for punctuation and capitalize a character 2 index away.
        for (int index = 0; index < letters.Length; index++)
        {
            if(char.IsPunctuation(letters[index]))
            {
                if (!((index + 2) >= letters.Length))
                {
                    char.ToUpper(letters[index+ 2]);
                }
            }
        }

        for(int ind = 0; ind < letters.Length; ind++)
        {
            input += letters[ind].ToString();
        }

        return input;
    }
</code>```

答:
You have two tasks:

1) Split text into sentences
2) Capitalize the first char in the sentences

Task one can be very complex, e.g. because there a lot of crazy languages out there. Put since this is homework I assume you can go ahead and simply split by well know separators.

Task two is just about basic string operations. You select the first char, make it uppercase and add the missing part of the sentence via a substring operation.

Here is a code example:

```<code>char[] separators = new char[] { '!', '.', '?' };
string[] sentencesArray = "First sentence. second sentence!lastone.".Split(separators, StringSplitOptions.RemoveEmptyEntries);
var i = 0;
Array.ForEach(sentencesArray, e =>
{
 sentencesArray[i] = e.Trim().First().ToString().ToUpper() +
 e.Trim().Substring(1);
 i++;
 });
</code>```

Body:
Create an application with a method that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized.

This is what I have to far and I can't seem to get it right:

    //Create method to process string.
    private string Sentences(string input)
    {
        //Capitalize first letter of input.
        char firstLetter = char.ToUpper(input[0]);

        //Combine the capitalize letter with the rest of the input.
        input = firstLetter.ToString() + input.Substring(1);

        //Create a char array to hold all characters in input.
        char[] letters = new char[input.Length];

        //Read the characters from input into the array.
        for (int i = 0; i < input.Length; i++)
        {
            letters[i] = input[i];
        }

        //Loop through array to test for punctuation and capitalize a character 2 index away.
        for (int index = 0; index < letters.Length; index++)
        {
            if(char.IsPunctuation(letters[index]))
            {
                if (!((index + 2) >= letters.Length))
                {
                    char.ToUpper(letters[index+ 2]);
                }
            }
        }

        for(int ind = 0; ind < letters.Length; ind++)
        {
            input += letters[ind].ToString();
        }

        return input;
    }

Body:
You have two tasks:

1) Split text into sentences
2) Capitalize the first char in the sentences

Task one can be very complex, e.g. because there a lot of crazy languages out there. Put since this is homework I assume you can go ahead and simply split by well know separators.

Task two is just about basic string operations. You select the first char, make it uppercase and add the missing part of the sentence via a substring operation.

Here is a code example:

char[] separators = new char[] { '!', '.', '?' };
string[] sentencesArray = "First sentence. second sentence!lastone.".Split(separators, StringSplitOptions.RemoveEmptyEntries);
var i = 0;
Array.ForEach(sentencesArray, e =>
{
 sentencesArray[i] = e.Trim().First().ToString().ToUpper() +
 e.Trim().Substring(1);
 i++;
 });


问:
Pass Drawable from Fragment to Dialogfragment using Bundle
I need to pass a drawable (mDLlist.get(position).getImageId()) from a Fragment to a DialogFragment.

I can`t seem to find a way how to do this, any input would be great.

Thank you upfront.

```<code>...
FragmentManager ft = ((FragmentActivity)context1).getSupportFragmentManager();
DialogFragment newFragment = MyNotification.newInstance();

Bundle args = new Bundle();
// How to pass this value ?
args.put?("appdraw", mDLlist.get(position).getImageId());
//--//
args.putString("appname", (String)mDLlist.get(position).getLabelnameText());
args.putString("appversion", mDLlist.get(position).getVersionName());
args.putString("appinstalltime", "Downloaded");
newFragment.setArguments(args);

newFragment.show(ft, "mydialog");
...
</code>```

答:
If anyone has the same problem, I used a "workaround" by passing the position of the adapter:

```<code>args.putInt("appdrawpos", position);
</code>```

and compared it with a counter(i) which I use in a method I wrote:

```<code>int appDrawPos = 0;
Drawable drawIcon;
int i = 0;
...
//Get the adapter position
appDrawPos = getArguments().getInt("appdrawpos");
//Get apk icon
getAPKicon(folder.getAbsolutePath());
...
public void getAPKicon(String directoryName) {
        File directory = new File(directoryName);
        final PackageManager pm = getActivity().getPackageManager();
        File[] fList = directory.listFiles();

        for (File file : fList) {
            if (file.isFile()) {
                //If counter is the same as adapter position
                //Grab the icon from the apk
                if (i == appDrawPos)
                    if (file.getName().endsWith(".apk")) {
                        PackageInfo info = pm.getPackageArchiveInfo(file.getAbsolutePath(), 0);
                        info.applicationInfo.sourceDir = file.getAbsolutePath();
                        info.applicationInfo.publicSourceDir = file.getAbsolutePath();
                        drawIcon = (info.applicationInfo.loadIcon(pm));
                        appDrawPos = 0;
                        i = 0;
                    }
                    i++;
            } else if (file.isDirectory()) {
                getAPKicon(file.getAbsolutePath());
            }
        }
    }
</code>```

Body:
I need to pass a drawable (mDLlist.get(position).getImageId()) from a Fragment to a DialogFragment.

I can`t seem to find a way how to do this, any input would be great.

Thank you upfront.

...
FragmentManager ft = ((FragmentActivity)context1).getSupportFragmentManager();
DialogFragment newFragment = MyNotification.newInstance();

Bundle args = new Bundle();
// How to pass this value ?
args.put?("appdraw", mDLlist.get(position).getImageId());
//--//
args.putString("appname", (String)mDLlist.get(position).getLabelnameText());
args.putString("appversion", mDLlist.get(position).getVersionName());
args.putString("appinstalltime", "Downloaded");
newFragment.setArguments(args);

newFragment.show(ft, "mydialog");
...

Body:
If anyone has the same problem, I used a "workaround" by passing the position of the adapter:

args.putInt("appdrawpos", position);

and compared it with a counter(i) which I use in a method I wrote:

int appDrawPos = 0;
Drawable drawIcon;
int i = 0;
...
//Get the adapter position
appDrawPos = getArguments().getInt("appdrawpos");
//Get apk icon
getAPKicon(folder.getAbsolutePath());
...
public void getAPKicon(String directoryName) {
        File directory = new File(directoryName);
        final PackageManager pm = getActivity().getPackageManager();
        File[] fList = directory.listFiles();

        for (File file : fList) {
            if (file.isFile()) {
                //If counter is the same as adapter position
                //Grab the icon from the apk
                if (i == appDrawPos)
                    if (file.getName().endsWith(".apk")) {
                        PackageInfo info = pm.getPackageArchiveInfo(file.getAbsolutePath(), 0);
                        info.applicationInfo.sourceDir = file.getAbsolutePath();
                        info.applicationInfo.publicSourceDir = file.getAbsolutePath();
                        drawIcon = (info.applicationInfo.loadIcon(pm));
                        appDrawPos = 0;
                        i = 0;
                    }
                    i++;
            } else if (file.isDirectory()) {
                getAPKicon(file.getAbsolutePath());
            }
        }
    }