问:
Xamarin Android Drawable Navbar Item Clickable
I'm new to Xamarin, I'm trying to figure out that when I click on one of the item on the navbar it would proceed to another activity or another layout but I've tried to used the switch but it doesn't make changes. Here is my code

MainActivity.cs

```<code> public class MainDashboard : AppCompatActivity
    {
        Android.Support.V7.Widget.Toolbar mainToolbar;
        Android.Support.V4.Widget.DrawerLayout drawerLayout;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(PediburRatingApp.Resource.Layout.MainDashboard);
            // Create your application here
            ConnectControl();
        }
        void ConnectControl()
        {
            drawerLayout = (Android.Support.V4.Widget.DrawerLayout)FindViewById(Resource.Id.drawerLayout);
            mainToolbar = (Android.Support.V7.Widget.Toolbar)FindViewById(Resource.Id.mainToolbar);
            SetSupportActionBar(mainToolbar);
            SupportActionBar.Title = "";
            Android.Support.V7.App.ActionBar actionBar = SupportActionBar;
            actionBar.SetHomeAsUpIndicator(Resource.Mipmap.ic_menu_action);
            actionBar.SetDisplayHomeAsUpEnabled(true);
        }
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            switch (item.ItemId)
            {

                case Android.Resource.Id.Home:
                    drawerLayout.OpenDrawer((int)GravityFlags.Left);
                    return true;

                case Resource.Id.navProfile:

                    return true;
                default:
                    return base.OnOptionsItemSelected(item);
            }
            return base.OnOptionsItemSelected(item);
        }
    }
</code>```

Main Activity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fitsSystemWindows="true"
    android:id="@+id/drawerLayout">

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

        <include
            layout="@layout/include_main"
 />

    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navView"
        android:layout_width="300dp"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:layout_gravity="start"
        app:headerLayout="@layout/headerLayout"
        app:menu="@menu/navmenu"
    />
</android.support.v4.widget.DrawerLayout>
</code>```

If I've done wrong please correct me

Here is the Navmenu.xml

```<code><?xml version="1.0" encoding="utf-8" ?>
<!--For all properties see: https://aka.ms/android-menu-resource-->
<menu xmlns:android="http://schemas.android.com/apk/res/android">

  <group>
    <item
      android:id="@+id/navProfile"
      android:title="Profile"
      android:icon="@mipmap/ic_person_action"
      />
    <item
  android:id="@+id/navRating"
  android:title="Rate a Driver"
  android:icon="@mipmap/ic_person_action"
      />
    <item
  android:id="@+id/navTopDriver"
  android:title="Weekly Driver"
  android:icon="@mipmap/ic_person_action"
      />
    <item
  android:id="@+id/navBalance"
  android:title="View Balance"
  android:icon="@mipmap/ic_person_action"
      />
    <item
  android:id="@+id/navAbout"
  android:title="About"
  android:icon="@mipmap/ic_person_action"
      />

  </group>

</menu>

</code>```

答:
Do you want to achieve the result like following GIF?

If so, you can achieve it by Fragment

Here is code. when switch Fragments.

```<code>      public bool OnNavigationItemSelected(IMenuItem item)
    {
        int id = item.ItemId;

        FragmentTransaction transaction = this.FragmentManager.BeginTransaction();

        if (id == Resource.Id.nav_camera)
        {
            // Handle the camera action

        }
        else if (id == Resource.Id.nav_gallery)
        {
            fragment = new Fragment1();

        }
        else if (id == Resource.Id.nav_slideshow)
        {
            fragment = new Fragment2();

        }
        else if (id == Resource.Id.nav_manage)
        {

        }
        else if (id == Resource.Id.nav_share)
        {

        }
        else if (id == Resource.Id.nav_send)
        {

        }

        DrawerLayout drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
        drawer.CloseDrawer(GravityCompat.Start);
        transaction.Replace(Resource.Id.FramePage, fragment);
        transaction.Commit();
        return true;
    }
</code>```

Here is my demo(For testing, I just create two Fragments(Gallery and slidehow tab)), you can refer to it.

https://github.com/851265601/XAndroidFragmentAndNavigationVIew

Body:
I'm new to Xamarin, I'm trying to figure out that when I click on one of the item on the navbar it would proceed to another activity or another layout but I've tried to used the switch but it doesn't make changes. Here is my code

MainActivity.cs

 public class MainDashboard : AppCompatActivity
    {
        Android.Support.V7.Widget.Toolbar mainToolbar;
        Android.Support.V4.Widget.DrawerLayout drawerLayout;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(PediburRatingApp.Resource.Layout.MainDashboard);
            // Create your application here
            ConnectControl();
        }
        void ConnectControl()
        {
            drawerLayout = (Android.Support.V4.Widget.DrawerLayout)FindViewById(Resource.Id.drawerLayout);
            mainToolbar = (Android.Support.V7.Widget.Toolbar)FindViewById(Resource.Id.mainToolbar);
            SetSupportActionBar(mainToolbar);
            SupportActionBar.Title = "";
            Android.Support.V7.App.ActionBar actionBar = SupportActionBar;
            actionBar.SetHomeAsUpIndicator(Resource.Mipmap.ic_menu_action);
            actionBar.SetDisplayHomeAsUpEnabled(true);
        }
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            switch (item.ItemId)
            {

                case Android.Resource.Id.Home:
                    drawerLayout.OpenDrawer((int)GravityFlags.Left);
                    return true;

                case Resource.Id.navProfile:

                    return true;
                default:
                    return base.OnOptionsItemSelected(item);
            }
            return base.OnOptionsItemSelected(item);
        }
    }

Main Activity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fitsSystemWindows="true"
    android:id="@+id/drawerLayout">

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

        <include
            layout="@layout/include_main"
 />

    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navView"
        android:layout_width="300dp"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:layout_gravity="start"
        app:headerLayout="@layout/headerLayout"
        app:menu="@menu/navmenu"
    />
</android.support.v4.widget.DrawerLayout>

If I've done wrong please correct me

Here is the Navmenu.xml

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

<menu xmlns:android="http://schemas.android.com/apk/res/android">

  <group>
    <item
      android:id="@+id/navProfile"
      android:title="Profile"
      android:icon="@mipmap/ic_person_action"
      />
    <item
  android:id="@+id/navRating"
  android:title="Rate a Driver"
  android:icon="@mipmap/ic_person_action"
      />
    <item
  android:id="@+id/navTopDriver"
  android:title="Weekly Driver"
  android:icon="@mipmap/ic_person_action"
      />
    <item
  android:id="@+id/navBalance"
  android:title="View Balance"
  android:icon="@mipmap/ic_person_action"
      />
    <item
  android:id="@+id/navAbout"
  android:title="About"
  android:icon="@mipmap/ic_person_action"
      />

  </group>

</menu>

Body:
Do you want to achieve the result like following GIF?

If so, you can achieve it by Fragment

Here is code. when switch Fragments.

      public bool OnNavigationItemSelected(IMenuItem item)
    {
        int id = item.ItemId;

        FragmentTransaction transaction = this.FragmentManager.BeginTransaction();

        if (id == Resource.Id.nav_camera)
        {
            // Handle the camera action

        }
        else if (id == Resource.Id.nav_gallery)
        {
            fragment = new Fragment1();

        }
        else if (id == Resource.Id.nav_slideshow)
        {
            fragment = new Fragment2();

        }
        else if (id == Resource.Id.nav_manage)
        {

        }
        else if (id == Resource.Id.nav_share)
        {

        }
        else if (id == Resource.Id.nav_send)
        {

        }

        DrawerLayout drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
        drawer.CloseDrawer(GravityCompat.Start);
        transaction.Replace(Resource.Id.FramePage, fragment);
        transaction.Commit();
        return true;
    }

Here is my demo(For testing, I just create two Fragments(Gallery and slidehow tab)), you can refer to it.

https://github.com/851265601/XAndroidFragmentAndNavigationVIew


来源: stackexchange

问:
How to get data from wildcard in firebase cloud functions
Assuming that I trigger events on the following ref('/users/{userId}/items/{newItem}')
I want to get a value from inside the  wildcard userId

I have tried var token = event.params.userId.token but it return to be undefined

Any suggestions?

答:
In firestore you can use this.</p>

```<code>exports.getUser = functions.firestore
    .document('users/{userId}').onWrite((change, context) => {
        let userId = context.params.userId;
        //...
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In firestore you can use this.

exports.getUser = functions.firestore
    .document('users/{userId}').onWrite((change, context) => {
        let userId = context.params.userId;
        //...
    });

ContentLicense: CC BY-SA 4.0


问:
Redshift querying data on dates
I am trying to query data from redshift table.

I have a users table with columns such as name, age, gender and created_at for example:

```<code>|----|-----|------|----------|
|name|age  |gender|created_at|
------------------------------
|X   | 24  | F    | some_date|
______________________________
</code>```

I need to query above table, in such a way that I have additional columns such as created_this_week, created_last_week, created_last_4_week, current_month, last_month etc
Additional flag columns should be 'Y' for conditions such as data is from last week, current week, current month, last month, last 4 weeks (excluding this week) so last 4 weeks starting last week etc, something like below.

```<code>|----|-----|------|-----------|------------|---------|-----------|------------|---------|
|name|age  |gender|created_at |current_week|last_week|last_4_week|current_mnth|last_mnth|
_________________________________________________________________________________________
| X  | 24  |  F   |CURRENTDATE|      Y     |   N     |     N     |    Y       |   N     |
_________________________________________________________________________________________
| F  | 21  |  M   | lst_wk_dt |      N     |   Y     |     Y     | Depends    | depends |
_________________________________________________________________________________________
</code>```

I am new to PostgresSQL and Redshift, and still in my learning phase, I spent past few hrs trying to do this myself but was unsuccessful. I'd really appreciate if someone can help me out with this one.

答:
You would use a case expressions:

```<code>select t.*,
       (case when created_at >= now() - interval '1 week' then 'Y' else 'N' end) as week1,
       (case when created_at >= now() - interval '4 week' then 'Y' else 'N' end) as week4,
       . . .
from t;
</code>```

Title: Redshift querying data on dates

Body:
I am trying to query data from redshift table.

I have a users table with columns such as name, age, gender and created_at for example:

|----|-----|------|----------|
|name|age  |gender|created_at|
------------------------------
|X   | 24  | F    | some_date|
______________________________

I need to query above table, in such a way that I have additional columns such as created_this_week, created_last_week, created_last_4_week, current_month, last_month etc
Additional flag columns should be 'Y' for conditions such as data is from last week, current week, current month, last month, last 4 weeks (excluding this week) so last 4 weeks starting last week etc, something like below.

|----|-----|------|-----------|------------|---------|-----------|------------|---------|
|name|age  |gender|created_at |current_week|last_week|last_4_week|current_mnth|last_mnth|
_________________________________________________________________________________________
| X  | 24  |  F   |CURRENTDATE|      Y     |   N     |     N     |    Y       |   N     |
_________________________________________________________________________________________
| F  | 21  |  M   | lst_wk_dt |      N     |   Y     |     Y     | Depends    | depends |
_________________________________________________________________________________________

I am new to PostgresSQL and Redshift, and still in my learning phase, I spent past few hrs trying to do this myself but was unsuccessful. I'd really appreciate if someone can help me out with this one.

Body:
You would use a case expressions:

select t.*,
       (case when created_at >= now() - interval '1 week' then 'Y' else 'N' end) as week1,
       (case when created_at >= now() - interval '4 week' then 'Y' else 'N' end) as week4,
       . . .
from t;


问:
Updatea dataframe with another one on matching rows like SQL update with a join statement
Is there any simple way to update a subset of dataframe rows using another one?

Practically, I want to use R to do UPDATE x INNER JOIN y ON x.col1 = y.col1 SET x.col2 = y.col2

Inputs:

```<code>x <- data.frame(col1=c('a','c','b','d'), col2=c(11,34,13,25))
</code>```

```<code>y <- data.frame(col1=c('a','b'), col2=c(3,5))
</code>```

```<code>z <- match(x$col1,y$col1)
</code>```

1  1 NA  2 NA

Outputs:

Method 1

```<code>x$col2 <- y$col2[z]
</code>```

Method 2

```<code>x$col2[z] <- y$col2[z]
</code>```

Error in x$col2[z] <- y$col2[z] :    NAs are not allowed in
  subscripted assignments

Method 3

```<code>x$col2[z[!is.na(z)]] <- y$col2[z[!is.na(z)]]
</code>```

Desired Output:

in x update only the values that match in col1 of y

答:
You can use match in base R:

```<code>x$col2[match(y$col1, x$col1)] <- y$col2
x

#  col1 col2
#1    a    3
#2    c   34
#3    b    5
#4    d   25
</code>```

Or left_join and coalesce in dplyr

```<code>library(dplyr)

left_join(x, y, by = 'col1') %>%
  mutate(col2 = coalesce(col2.y, col2.x)) %>%
  select(names(x))
</code>```

Most efficient would be an update join in data.table

```<code>library(data.table)

setDT(x)
setDT(y)
x[y, on=.(col1), col2:=i.col2]
</code>```

Body:
Is there any simple way to update a subset of dataframe rows using another one?

Practically, I want to use R to do UPDATE x INNER JOIN y ON x.col1 = y.col1 SET x.col2 = y.col2

Inputs:

x <- data.frame(col1=c('a','c','b','d'), col2=c(11,34,13,25))

y <- data.frame(col1=c('a','b'), col2=c(3,5))

z <- match(x$col1,y$col1)

1  1 NA  2 NA

Outputs:

Method 1

x$col2 <- y$col2[z]

Method 2

x$col2[z] <- y$col2[z]

Error in x$col2[z] <- y$col2[z] :    NAs are not allowed in
  subscripted assignments

Method 3

x$col2[z[!is.na(z)]] <- y$col2[z[!is.na(z)]]

Desired Output:

in x update only the values that match in col1 of y

Body:
You can use match in base R:

x$col2[match(y$col1, x$col1)] <- y$col2
x

#  col1 col2
#1    a    3
#2    c   34
#3    b    5
#4    d   25

Or left_join and coalesce in dplyr

library(dplyr)

left_join(x, y, by = 'col1') %>%
  mutate(col2 = coalesce(col2.y, col2.x)) %>%
  select(names(x))

Most efficient would be an update join in data.table

library(data.table)

setDT(x)
setDT(y)
x[y, on=.(col1), col2:=i.col2]


问:
Rails :confirm modifier callback?
I want to call a javascript function that will be conditional upon a user's response to the confirm box.

For example, I have the following anchor:

```<code><%= link_to 'Sign Out', destroy_session_path, confirm: 'Are you sure that you would like to sign out?', method: :delete %>
</code>```

Should I just abandon the unobtrusive javascript and bind my own jQuery callback to my anchor?

Or is there some magical way to pass a callback function to the Rails url helper? I did not see any discussion of callbacks in the documentation.

答:
In 2020, the accepted answer didn't work for me. I ended up doing something like this instead:

$(document).on('confirm:complete', function (e) {
  if (e.originalEvent.detail[0]) {
    // user confirmed!
    myCallbackFunction();
  } else {
    // user canceled!
  }
});
```

Title: Rails :confirm modifier callback?

Body:
I want to call a javascript function that will be conditional upon a user's response to the confirm box.

For example, I have the following anchor:

<%= link_to 'Sign Out', destroy_session_path, confirm: 'Are you sure that you would like to sign out?', method: :delete %>

Should I just abandon the unobtrusive javascript and bind my own jQuery callback to my anchor?

Or is there some magical way to pass a callback function to the Rails url helper? I did not see any discussion of callbacks in the documentation.


问:
ORACLE, CONNECT BY ROWNUM FROM DUAL, MULTIPLE COLUMN
I need 2 columns, the first column contains int numbers 1 -100 and the second column contains 001-100.

I have tried this query,
but the result is the second column is not 001 to 100

```<code>SELECT ROWNUM AS Nomor, to_char (ROWNUM) AS No_Row
FROM DUAL
CONNECT BY ROWNUM >= '001' AND ROWNUM <= 100;
</code>```

How can I do that?
Can somebody help me

答:
You seem to want:

```<code>SELECT ROWNUM AS Nomor, to_char(ROWNUM, '000') AS No_Row
</code>```

That is, you want a format for to_char().

Body:
I need 2 columns, the first column contains int numbers 1 -100 and the second column contains 001-100.

I have tried this query,
but the result is the second column is not 001 to 100

SELECT ROWNUM AS Nomor, to_char (ROWNUM) AS No_Row
FROM DUAL
CONNECT BY ROWNUM >= '001' AND ROWNUM <= 100;

How can I do that?
Can somebody help me

Body:
You seem to want:

SELECT ROWNUM AS Nomor, to_char(ROWNUM, '000') AS No_Row

That is, you want a format for to_char().


答:
Since the exact operation you want here is a SQL style join, the sqldf package comes in handy:

```<code>library(sqldf)

sql <- "SELECT x.col1, COALESCE(y.col2, x.col2) AS col2
        FROM x LEFT JOIN y ON x.col1 = y.col1"
x <- sqldf(sql)
</code>```

Data:

```<code>x <- data.frame(col1=c('a','c','b','d'), col2=c(11,34,13,25))
y <- data.frame(col1=c('a','b'), col2=c(3,5))
</code>```

Title: Updatea dataframe with another one on matching rows like SQL update with a join statement

Body:
Since the exact operation you want here is a SQL style join, the sqldf package comes in handy:

library(sqldf)

sql <- "SELECT x.col1, COALESCE(y.col2, x.col2) AS col2
        FROM x LEFT JOIN y ON x.col1 = y.col1"
x <- sqldf(sql)

Data:

x <- data.frame(col1=c('a','c','b','d'), col2=c(11,34,13,25))
y <- data.frame(col1=c('a','b'), col2=c(3,5))


问:
Why am I getting a "no matching function" error?
Pretty new to C++, I was given an assignment that is basically about utilizing two different classes, however when creating my header files and c++ files and attempting to compile I get an error that reads no matching function for call to 'Owner::Owner()'. Since I am not super familiar with C++ yet I am assuming that this issue has something to do with my constructors and the way I am trying to call them, my assignment details what I think my issue is about but I am having trouble understanding exactly what needs to be done. I will provide the assignment details on the issue, as well as the code and compilation error below. Sorry for all the information I've just been stuck with this issue for a while and I can't seem to figure out a solution.

Transcribed Error
In constructor 'Dog::Dog(std::__cxx11::string, int)':
Dog.cpp:23:46: error: no matching function for call to 'Owner::Owner()' Dog::Dog(std::string unsetBreed, int unsetAge){

Assignment Details

Now you will write a program that consists of two classes, a Dog class and an Owner class. Their specification is shown in the UML diagram below. Notice that in our design, every Dog has an Owner class member. Class Owner is immutable, as mentioned above. An immutable class is just a class whose members cannot be changed(mutated) after an object was instantiated. Therefore, the Owner class does not have any setter methods. The Owner’s class attributes must be set at the time of creation(in the Owner’s constructor). You will call Owner’s constructor from inside Dog’s constructor. Do not forget to do it inside each constructor in class Dog.

Dog.h File

```<code>#ifndef DOG_H_INCLUDED
#define DOG_H_INCLUDED

#include <iostream>
#include "Owner.h"

class Dog {
//-----------------------//
  private:
    std::string breed;
    int age;
    Owner owner;
    static int dogCount;
//-----------------------//
  public:
    Dog();
    Dog(std::string, int);
    std::string getBreed();
    int getAge();
    void setBreed(std::string);
    void setAge(int);
    void printDogInfo();
    int getDogCount();
};
#endif // DOG_H_INCLUDED
</code>```

Owner.h File

```<code>#ifndef OWNER_H_INCLUDED
#define OWNER_H_INCLUDED
#include <iostream>

class Owner {
//-----------------------//
  private:
    std::string name;
    int age;
//-----------------------//
  public:
    Owner(std::string, int);
    std::string getName();
    int getAge();
//-----------------------//
};

#endif // OWNER_H_INCLUDED
</code>```

Dog.cpp File

```<code>#include <iostream>
#include "Owner.cpp"
#include "Owner.h"
#include "Dog.h"

//---------------SETTERS------------------//
void Dog::setBreed(std::string dogBreed){dogBreed = breed;}
void Dog::setAge(int dogAge){dogAge = age;}

//--------------GETTERS------------------//
std::string Dog::getBreed(){return breed;}
int Dog::getAge(){return age;}
int Dog::getDogCount(){return dogCount;}

//--------------OTHERS-------------------//
Dog::Dog(std::string unsetBreed, int unsetAge){
  Owner::Owner(std::string unsetName, int unsetOwnerAge);
  Dog::setBreed(unsetBreed);
  Dog::setAge(unsetAge);
}

void Dog::printDogInfo(){
  Dog::getBreed();
  Dog::getAge();
}
</code>```

Owner.cpp File

```<code>#include <iostream>
#include "Owner.h"
#include "Dog.h"

//--------------GETTERS------------------//
int Owner::getAge(){return age;}
std::string Owner::getName(){return name;}

//--------------OTHERS-------------------//
Owner::Owner(std::string unsetName, int unsetOwnerAge){
  Owner::getName();
  Owner::getAge();
}
</code>```

答: Looks like your Owner class dosen't have a default constructor try including Owner::Owner() constructor.

Body:
Pretty new to C++, I was given an assignment that is basically about utilizing two different classes, however when creating my header files and c++ files and attempting to compile I get an error that reads no matching function for call to 'Owner::Owner()'. Since I am not super familiar with C++ yet I am assuming that this issue has something to do with my constructors and the way I am trying to call them, my assignment details what I think my issue is about but I am having trouble understanding exactly what needs to be done. I will provide the assignment details on the issue, as well as the code and compilation error below. Sorry for all the information I've just been stuck with this issue for a while and I can't seem to figure out a solution.

Transcribed Error
In constructor 'Dog::Dog(std::__cxx11::string, int)':
Dog.cpp:23:46: error: no matching function for call to 'Owner::Owner()' Dog::Dog(std::string unsetBreed, int unsetAge){

Assignment Details

Now you will write a program that consists of two classes, a Dog class and an Owner class. Their specification is shown in the UML diagram below. Notice that in our design, every Dog has an Owner class member. Class Owner is immutable, as mentioned above. An immutable class is just a class whose members cannot be changed(mutated) after an object was instantiated. Therefore, the Owner class does not have any setter methods. The Owner’s class attributes must be set at the time of creation(in the Owner’s constructor). You will call Owner’s constructor from inside Dog’s constructor. Do not forget to do it inside each constructor in class Dog.

Dog.h File

#ifndef DOG_H_INCLUDED
#define DOG_H_INCLUDED

#include <iostream>
#include "Owner.h"

class Dog {
//-----------------------//
  private:
    std::string breed;
    int age;
    Owner owner;
    static int dogCount;
//-----------------------//
  public:
    Dog();
    Dog(std::string, int);
    std::string getBreed();
    int getAge();
    void setBreed(std::string);
    void setAge(int);
    void printDogInfo();
    int getDogCount();
};
#endif // DOG_H_INCLUDED

Owner.h File

#ifndef OWNER_H_INCLUDED
#define OWNER_H_INCLUDED
#include <iostream>

class Owner {
//-----------------------//
  private:
    std::string name;
    int age;
//-----------------------//
  public:
    Owner(std::string, int);
    std::string getName();
    int getAge();
//-----------------------//
};

#endif // OWNER_H_INCLUDED

Dog.cpp File

#include <iostream>
#include "Owner.cpp"
#include "Owner.h"
#include "Dog.h"

//---------------SETTERS------------------//
void Dog::setBreed(std::string dogBreed){dogBreed = breed;}
void Dog::setAge(int dogAge){dogAge = age;}

//--------------GETTERS------------------//
std::string Dog::getBreed(){return breed;}
int Dog::getAge(){return age;}
int Dog::getDogCount(){return dogCount;}

//--------------OTHERS-------------------//
Dog::Dog(std::string unsetBreed, int unsetAge){
  Owner::Owner(std::string unsetName, int unsetOwnerAge);
  Dog::setBreed(unsetBreed);
  Dog::setAge(unsetAge);
}

void Dog::printDogInfo(){
  Dog::getBreed();
  Dog::getAge();
}

Owner.cpp File

#include <iostream>
#include "Owner.h"
#include "Dog.h"

//--------------GETTERS------------------//
int Owner::getAge(){return age;}
std::string Owner::getName(){return name;}

//--------------OTHERS-------------------//
Owner::Owner(std::string unsetName, int unsetOwnerAge){
  Owner::getName();
  Owner::getAge();
}


问:
If Date equals Date Else
This should work! It's simple... yet here I am. Is my syntax wrong somewhere?

for row in dbOps(sqlQuery, "", "SELECT"):
    rowDate = row['d_date']
    currDate = datetime.datetime.today().strftime('%Y-%m-%d')
    print(rowDate, currDate)
    if rowDate == currDate:
        print("yes")
    else:
        print("no")

#### Output
2020-02-19 2020-02-19
no
```

<p>Edit:
When I run this as string literals, it works...?</p>

<pre class="lang-py prettyprint-override"><code>rowDate = "2020-02-19"
currDate = "2020-02-19"
print(rowDate, currDate)
if rowDate == currDate:
  print("yes")
else:
    print("no")
</code>```

答:
First you should check type of data

```<code>print( type(rowDate), type(currDate) )
</code>```

Maybe you don't have two strings.

if you have dateiem then you can use

```<code>rowDate = rowDate.strftime('%Y-%m-%d')
</code>```

or you can check what will happen if keep

```<code>currDate = datetime.datetime.today()
</code>```

If rowDate is datetime.date then try

```<code>currDate = datetime.datetime.today().date()
</code>```

or

```<code>currDate = datetime.date.today()
</code>```

Title: If Date equals Date Else

Body:
This should work! It's simple... yet here I am. Is my syntax wrong somewhere?

for row in dbOps(sqlQuery, "", "SELECT"):
    rowDate = row['d_date']
    currDate = datetime.datetime.today().strftime('%Y-%m-%d')
    print(rowDate, currDate)
    if rowDate == currDate:
        print("yes")
    else:
        print("no")

#### Output
2020-02-19 2020-02-19
no

Edit:
When I run this as string literals, it works...?

rowDate = "2020-02-19"
currDate = "2020-02-19"
print(rowDate, currDate)
if rowDate == currDate:
  print("yes")
else:
    print("no")

Body:
First you should check type of data

print( type(rowDate), type(currDate) )

Maybe you don't have two strings.

if you have dateiem then you can use

rowDate = rowDate.strftime('%Y-%m-%d')

or you can check what will happen if keep

currDate = datetime.datetime.today()

If rowDate is datetime.date then try

currDate = datetime.datetime.today().date()

or

currDate = datetime.date.today()


问:
marker icon isn't showing in Leaflet
I 've put together a very simple React / Leaflet demo but the marker icon is not showing at all.
Full running code is here.

Here's what I have in my componentDidMount method:

```<code>componentDidMount() {
this.map = L.map("map-id", {
  center: [37.98, 23.72],
  zoom: 12,
  zoomControl: true
});

const mapboxAccessToken =
  "pk.eyJ1IjoibXBlcmRpa2VhcyIsImEiOiJjazZpMjZjMW4wOXJzM2ttc2hrcTJrNG9nIn0.naHhlYnc4czWUjX0-icY7Q";
L.tileLayer(
  "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}",
  {
    attribution:
      'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    maxZoom: 25,
    id: "mapbox/streets-v11",
    accessToken: mapboxAccessToken
  }
).addTo(this.map);

L.marker([37.98, 23.72])
  .addTo(this.map)
  .bindPopup("a marker")
  .openPopup();
}
</code>```

Basically, the popup is visible, but not the marker icon itself. I.e., here's what I see:

答:
Just for reference, this is due to webpack trying to include the Marker Icon image file specified in Leaflet CSS as a static asset in  different folder and possibly file renaming (e.g. for finger printing); all this interferes with Leaflet algorithm which uses that image only as a pointer to its actual CSS images folder, which therefore can be completely missing after webpack build step.

See details in https://github.com/Leaflet/Leaflet/issues/4968

I specifically made a Leaflet plugin to cover this issue: https://github.com/ghybs/leaflet-defaulticon-compatibility

Retrieve all Leaflet Default Icon options from CSS, in particular all icon images URL's, to improve compatibility with bundlers and frameworks that modify URL's in CSS.

Unfortunately, it would still not work in CodeSandbox (or even in StackBlitz), because the latter does not handle these static assets. It is visible by just trying to use Leaflet Layers Control, which uses a very simple CSS background image, which is also missing in CodeSandbox.

But everything should be fine in your own environment.

demo in CodeSandbox: https://codesandbox.io/s/elegant-swirles-yzsql

and in StackBlitz (same static assets issue): https://stackblitz.com/edit/react-vqgtxd?file=index.js

Title: marker icon isn't showing in Leaflet

Body:
I 've put together a very simple React / Leaflet demo but the marker icon is not showing at all.
Full running code is here.

Here's what I have in my componentDidMount method:

componentDidMount() {
this.map = L.map("map-id", {
  center: [37.98, 23.72],
  zoom: 12,
  zoomControl: true
});

const mapboxAccessToken =
  "pk.eyJ1IjoibXBlcmRpa2VhcyIsImEiOiJjazZpMjZjMW4wOXJzM2ttc2hrcTJrNG9nIn0.naHhlYnc4czWUjX0-icY7Q";
L.tileLayer(
  "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}",
  {
    attribution:
      'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
    maxZoom: 25,
    id: "mapbox/streets-v11",
    accessToken: mapboxAccessToken
  }
).addTo(this.map);

L.marker([37.98, 23.72])
  .addTo(this.map)
  .bindPopup("a marker")
  .openPopup();
}

Basically, the popup is visible, but not the marker icon itself. I.e., here's what I see:


问:
Angular ng2-file-upload Input File Filter not working for PNG in Internet Explorer
I am using the file uploader from ng2-file-upload with filetype restriction.
However everytime i choose a png file with the Internet Explorer 11, it is not added into the queue. All the other allowed filetypes are working.
Here is the code with the file Options:

let uploadOptions: FileUploaderOptions;
if (navigator.userAgent.match(/Trident.*rv\:11\./)) {
  uploadOptions = {
    url: uploadUrl,
    allowedFileType: ['xls', 'xlsx', 'doc', 'docx', 'pdf', 'gif', 'jpg', 'jpeg', 'png', 'odt', 'txt', 'ods'],
    maxFileSize: 10 * 1024 * 1024
  };
} else {
  uploadOptions = {
    url: uploadUrl,
    allowedMimeType: ['application/pdf',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.oasis.opendocument.text',
      'application/vnd.oasis.opendocument.spreadsheet',
      'image/gif',
      'image/jpeg',
      'image/png'
    ],
    maxFileSize: 10 * 1024 * 1024
  };

}

this.uploader = new FileUploader(uploadOptions);
this.uploader.onCompleteAll = () => {
  this.editStateService.documentAdded('player', 'document');
  this.documentListUpdated.emit();
  this.uploader.clearQueue();
};```

Anybody know how to get this working?

答:
Please check this thread, the allowedFileTypes are actually not file extensions, it supports the following file type:

application

image

video

audio

pdf

compress

doc

xls

ppt

Try to add image to the allowedFileTypes list.

Body:
I am using the file uploader from ng2-file-upload with filetype restriction.
However everytime i choose a png file with the Internet Explorer 11, it is not added into the queue. All the other allowed filetypes are working.
Here is the code with the file Options:

let uploadOptions: FileUploaderOptions;
if (navigator.userAgent.match(/Trident.*rv\:11\./)) {
  uploadOptions = {
    url: uploadUrl,
    allowedFileType: ['xls', 'xlsx', 'doc', 'docx', 'pdf', 'gif', 'jpg', 'jpeg', 'png', 'odt', 'txt', 'ods'],
    maxFileSize: 10 * 1024 * 1024
  };
} else {
  uploadOptions = {
    url: uploadUrl,
    allowedMimeType: ['application/pdf',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.oasis.opendocument.text',
      'application/vnd.oasis.opendocument.spreadsheet',
      'image/gif',
      'image/jpeg',
      'image/png'
    ],
    maxFileSize: 10 * 1024 * 1024
  };

}

this.uploader = new FileUploader(uploadOptions);
this.uploader.onCompleteAll = () => {
  this.editStateService.documentAdded('player', 'document');
  this.documentListUpdated.emit();
  this.uploader.clearQueue();
};

Anybody know how to get this working?


问:
converting mongodb values in query to a string in python
How can I convert the values in the multiple responses from mongodb in python to a string with the values separated by a comma?

I don't know if my question is understandable, basically, this is what I want to do.

I am using this code to get data from mongodb:

```<code>    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["mydatabase"]
    driversdb = mydb["orders"]

    ordersQuery = { "city": city }
    mydoc = ordersdb.find(ordersQuery)
    for x in mydoc:
</code>```

The response is:

```<code>{ <more values>, 'orderid': 'IHZXMZQ3SX', <more values> }
{ <more values>, 'orderid': 'eu8j35tvoO', <more values> }
<more data>
</code>```

how can I convert that to:

```<code>orderslist = "IHZXMZQ3SX, eu8j35tvoO, <more orderids>"
</code>```

答:
it can be extracted in one line</p>

```<code>orderids = [x['orderid'] for x in mydoc]
</code>```

Body:
How can I convert the values in the multiple responses from mongodb in python to a string with the values separated by a comma?

I don't know if my question is understandable, basically, this is what I want to do.

I am using this code to get data from mongodb:

    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["mydatabase"]
    driversdb = mydb["orders"]

    ordersQuery = { "city": city }
    mydoc = ordersdb.find(ordersQuery)
    for x in mydoc:

The response is:

{ <more values>, 'orderid': 'IHZXMZQ3SX', <more values> }
{ <more values>, 'orderid': 'eu8j35tvoO', <more values> }
<more data>

how can I convert that to:

orderslist = "IHZXMZQ3SX, eu8j35tvoO, <more orderids>"

Body:
it can be extracted in one line

orderids = [x['orderid'] for x in mydoc]


问:
Insert queryset results into ManytoManyfield
I have a models.py file that looks like this:

```<code>from django.db import models
from common.models import Record
from tinymce import models as tinymce_models

# Create your models here.
class Address(Record):
    def __unicode__(self):
        return unicode(self.ip)

    ip = models.IPAddressField(unique=True)
    notes = models.TextField(blank=True)

    class Meta:
        verbose_name_plural = "Addresses"

class Servers(models.Model):
    def __unicode__(self):
        return unicode(self.server_name)

    server_name = models.CharField(max_length=100)
    ip_address = models.ForeignKey(Address)
    secondary_ips = models.ManyToManyField(Address, verbose_name = 'Secondary IPs', blank=True, related_name='secondary_ips')

    class Meta:
        verbose_name_plural = "Servers"
</code>```

I have a list of IP's and Servers in the system.  I am trying to have the ManytoManyField only display the list of IP's that are not currently associated with a server.

I have the following queryset:

```<code>inner_qs = Servers.objects.values_list('ip_address_id', flat=True)
entries = Address.objects.exclude(id__in=inner_qs)
</code>```

It returns only the IP addresses that are not in the Server table.  I do not know how to incorporate those results into my ManytoManyField and where I am supposed to place my queryset.  I currently only get the results when I enter the django Shell

Any ideas,

Thanks

答:
I got here because I had a model with a manytomanyfield pointing to this model "CampaignsProducts" which its str property was generating many queries :

Before :

```<code>class CampaignsProducts(mdlcom.CommonStructure):
 product = models.ForeignKey(
    'products.Product',
    verbose_name=u'Producto',
    null=False, on_delete=models.CASCADE,
    related_name="%(app_label)s_%(class)s_product_set",
 )
 campaign = models.ForeignKey(
    'prices.Campaigns',
    verbose_name=u'Campaña',
    null=False, on_delete=models.CASCADE,
    related_name="%(app_label)s_%(class)s_campaign_set",
 )
 def __str__(self):
    return '{} - {}'.format(self.product.name, self.campaign.name)
</code>```

In order to fix it, I changed the following "str" property

```<code>def __str__(self):
   return str(self.id)
</code>```

and the solution that was provided by Mikko, saved my life :

```<code>class CouponForm(forms.ModelForm):
NO_REQUIRED = [
    'sellers', 'platforms', 'campaigns_product',
]

class Meta:
    model = mdlpri.Coupon
    fields = '__all__'

def get_campaigns_choices(self):
    qscampaigns = (
        mdlpri.CampaignsProducts.objects.all()
        .select_related("product")
        .select_related("campaign")
        .order_by("id")
    )
    choices = []
    for item in qscampaigns:
        wdescription = '{} - {}'.format(
            item.product.name, item.campaign.name
        )
        choices.append((item.id, wdescription))

    return choices

def __init__(self, *args, **kwargs):
    super(CouponForm, self).__init__(*args, **kwargs)
    for wfield in self.NO_REQUIRED:
        self.fields[wfield].required = False
</code>```

personalize choices

```<code>    w = self.fields["campaigns_product"].widget
    w.choices = self.get_campaigns_choices()
</code>```

Query Before the change (by product):

```<code>SELECT "products_product"."id", "products_product"."name", "products_product"."custom", "products_product"."created_at", "products_product"."updated_at", "products_product"."active", "products_product"."position", "products_product"."url", "products_product"."for_bonus_platform", "products_product"."for_cms_platform", "products_product"."for_store_platform", "products_product"."for_call_center_platform", "products_product"."for_ibk_platform", "products_product"."for_scotiabank_platform", "products_product"."for_bbva_platform", "products_product"."for_refurbished_platform" FROM "products_product" WHERE "products_product"."id" = 1
</code>```

Query after the change :

```<code>SELECT "prices_campaignsproducts"."id", "prices_campaignsproducts"."date_created_at", "prices_campaignsproducts"."created_at", "prices_campaignsproducts"."updated_at", "prices_campaignsproducts"."user_id", "prices_campaignsproducts"."last_user_modified_id", "prices_campaignsproducts"."product_id", "prices_campaignsproducts"."campaign_id", "prices_campaignsproducts"."price", "prices_campaignsproducts"."is_active", "prices_campaignsproducts"."expiration_from", "prices_campaignsproducts"."expiration_to", "products_product"."id", "products_product"."name", "products_product"."custom", "products_product"."created_at", "products_product"."updated_at", "products_product"."active", "products_product"."position", "products_product"."url", "products_product"."for_bonus_platform", "products_product"."for_cms_platform", "products_product"."for_store_platform", "products_product"."for_call_center_platform", "products_product"."for_ibk_platform", "products_product"."for_scotiabank_platform", "products_product"."for_bbva_platform", "products_product"."for_refurbished_platform", "prices_campaigns"."id", "prices_campaigns"."date_created_at", "prices_campaigns"."created_at", "prices_campaigns"."updated_at", "prices_campaigns"."user_id", "prices_campaigns"."last_user_modified_id", "prices_campaigns"."name", "prices_campaigns"."is_active" FROM "prices_campaignsproducts" INNER JOIN "products_product" ON ("prices_campaignsproducts"."product_id" = "products_product"."id") INNER JOIN "prices_campaigns" ON ("prices_campaignsproducts"."campaign_id" = "prices_campaigns"."id") ORDER BY "prices_campaignsproducts"."id" ASC
</code>```

Just wanted to share my experience.

Best regards,

Body:
I have a models.py file that looks like this:

from django.db import models
from common.models import Record
from tinymce import models as tinymce_models

# Create your models here.
class Address(Record):
    def __unicode__(self):
        return unicode(self.ip)

    ip = models.IPAddressField(unique=True)
    notes = models.TextField(blank=True)

    class Meta:
        verbose_name_plural = "Addresses"

class Servers(models.Model):
    def __unicode__(self):
        return unicode(self.server_name)

    server_name = models.CharField(max_length=100)
    ip_address = models.ForeignKey(Address)
    secondary_ips = models.ManyToManyField(Address, verbose_name = 'Secondary IPs', blank=True, related_name='secondary_ips')

    class Meta:
        verbose_name_plural = "Servers"

I have a list of IP's and Servers in the system.  I am trying to have the ManytoManyField only display the list of IP's that are not currently associated with a server.

I have the following queryset:

inner_qs = Servers.objects.values_list('ip_address_id', flat=True)
entries = Address.objects.exclude(id__in=inner_qs)

It returns only the IP addresses that are not in the Server table.  I do not know how to incorporate those results into my ManytoManyField and where I am supposed to place my queryset.  I currently only get the results when I enter the django Shell

Any ideas,

Thanks

Body:
I got here because I had a model with a manytomanyfield pointing to this model "CampaignsProducts" which its str property was generating many queries :

Before :

class CampaignsProducts(mdlcom.CommonStructure):
 product = models.ForeignKey(
    'products.Product',
    verbose_name=u'Producto',
    null=False, on_delete=models.CASCADE,
    related_name="%(app_label)s_%(class)s_product_set",
 )
 campaign = models.ForeignKey(
    'prices.Campaigns',
    verbose_name=u'Campaña',
    null=False, on_delete=models.CASCADE,
    related_name="%(app_label)s_%(class)s_campaign_set",
 )
 def __str__(self):
    return '{} - {}'.format(self.product.name, self.campaign.name)

In order to fix it, I changed the following "str" property

def __str__(self):
   return str(self.id)

and the solution that was provided by Mikko, saved my life :

class CouponForm(forms.ModelForm):
NO_REQUIRED = [
    'sellers', 'platforms', 'campaigns_product',
]

class Meta:
    model = mdlpri.Coupon
    fields = '__all__'

def get_campaigns_choices(self):
    qscampaigns = (
        mdlpri.CampaignsProducts.objects.all()
        .select_related("product")
        .select_related("campaign")
        .order_by("id")
    )
    choices = []
    for item in qscampaigns:
        wdescription = '{} - {}'.format(
            item.product.name, item.campaign.name
        )
        choices.append((item.id, wdescription))

    return choices

def __init__(self, *args, **kwargs):
    super(CouponForm, self).__init__(*args, **kwargs)
    for wfield in self.NO_REQUIRED:
        self.fields[wfield].required = False

personalize choices

    w = self.fields["campaigns_product"].widget
    w.choices = self.get_campaigns_choices()

Query Before the change (by product):

SELECT "products_product"."id", "products_product"."name", "products_product"."custom", "products_product"."created_at", "products_product"."updated_at", "products_product"."active", "products_product"."position", "products_product"."url", "products_product"."for_bonus_platform", "products_product"."for_cms_platform", "products_product"."for_store_platform", "products_product"."for_call_center_platform", "products_product"."for_ibk_platform", "products_product"."for_scotiabank_platform", "products_product"."for_bbva_platform", "products_product"."for_refurbished_platform" FROM "products_product" WHERE "products_product"."id" = 1

Query after the change :

SELECT "prices_campaignsproducts"."id", "prices_campaignsproducts"."date_created_at", "prices_campaignsproducts"."created_at", "prices_campaignsproducts"."updated_at", "prices_campaignsproducts"."user_id", "prices_campaignsproducts"."last_user_modified_id", "prices_campaignsproducts"."product_id", "prices_campaignsproducts"."campaign_id", "prices_campaignsproducts"."price", "prices_campaignsproducts"."is_active", "prices_campaignsproducts"."expiration_from", "prices_campaignsproducts"."expiration_to", "products_product"."id", "products_product"."name", "products_product"."custom", "products_product"."created_at", "products_product"."updated_at", "products_product"."active", "products_product"."position", "products_product"."url", "products_product"."for_bonus_platform", "products_product"."for_cms_platform", "products_product"."for_store_platform", "products_product"."for_call_center_platform", "products_product"."for_ibk_platform", "products_product"."for_scotiabank_platform", "products_product"."for_bbva_platform", "products_product"."for_refurbished_platform", "prices_campaigns"."id", "prices_campaigns"."date_created_at", "prices_campaigns"."created_at", "prices_campaigns"."updated_at", "prices_campaigns"."user_id", "prices_campaigns"."last_user_modified_id", "prices_campaigns"."name", "prices_campaigns"."is_active" FROM "prices_campaignsproducts" INNER JOIN "products_product" ON ("prices_campaignsproducts"."product_id" = "products_product"."id") INNER JOIN "prices_campaigns" ON ("prices_campaignsproducts"."campaign_id" = "prices_campaigns"."id") ORDER BY "prices_campaignsproducts"."id" ASC

Just wanted to share my experience.

Best regards,


问:
undefined error converting an address into coordinates with Mapbox geocoder
I'm working with Mapbox geocoder services for the first time, and I was trying to get the coordinates (latitude and longitude) as result of address search and I did it, but when I try to insert this result into two inputs, the input search change the address selected to "Undefined" and I don't now Why.
I want the coordinates into two input but also keep the selected address into the input search.
This is an image that shows the error:

This is the code I have Now:

mapboxgl.accessToken = 'pk.eyJ1IjoiY2FybWVuOTIiLCJhIjoiY2s2cGljM3ZzMW1udjNlbnkxZmMzdXJ3ZCJ9.HJQPFlX5VUh6wlS18R3bFw';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v11',
center: [-74.5, 40], // starting position
zoom: 9 // starting zoom
});
  var geocoder = new MapboxGeocoder({ // Initialize the geocoder
  accessToken: mapboxgl.accessToken, // Set the access token
  marker: {
    color: 'orange'
    },
  mapboxgl: mapboxgl // Set the mapbox-gl instance
  getItemValue: e => {
  document.getElementById('LocationLongitude_listingAdd').value = e['center'][0]; //long
  document.getElementById('LocationLatitude_listingAdd').value = e['center'][1]; //lat
  document.getElementsByClassName('mapboxgl-ctrl-geocoder--input').value = e['place_name']; //lat
    }

  });
document.getElementById('geocode_container').appendChild(geocoder.onAdd(map));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    #container_map{ position: relative; width: 100%; height: 400px;}
#map { position: absolute; top: 0; bottom: 0; width: 100%; height: 100%; }
.mapboxgl-ctrl-geocoder--input{min-width: 100%; width: 100%; border: 1px solid #DFE3E7 !important; border-radius: 0.267rem !important; transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out !important;}
 #map .mapboxgl-canvas-container canvas
    {
        width: 100% !important;
        height: 400px !important;
    }
.mapboxgl-ctrl-geocoder--input:focus{
    border-color: #5A8DEE !important;
    outline: 0 !important;
    box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.1) !important;
    }

.coordinates-result input { display: inline-block; }

    @media screen and (min-width: 640px)
    {
            .mapboxgl-ctrl-geocoder
            {
                width: 100% !important;
                font-size: 12px;
                line-height: 20px;

            }
    }
    .mapboxgl-ctrl-geocoder, .mapboxgl-ctrl-geocoder .suggestions {
        box-shadow: none !important;
    }</code>```

<!DOCTYPE html>

<link href="https://api.mapbox.com/mapbox-gl-js/v1.7.0/mapbox-gl.css" rel="stylesheet" />

    <link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.4.2/mapbox-gl-geocoder.css" type="text/css" />

    ```

How Can I do to get the result coordinates of searching an address on Mapbox and keep the address and the coordinates into their inputs, because I'll save that data on a database.

答:
According to the API docs https://github.com/mapbox/mapbox-gl-geocoder/blob/master/API.md#mapboxgeocoder

options.getItemValue Function? A function that specifies how the
  selected result should be rendered in the search bar. This function
  should accept a single Carmen GeoJSON object as input and return a
  string. HTML tags in the output string will not be rendered. Defaults
  to (item) => item.place_name.

In your example you've failed to return something from getItemValue hence it's showing undefined.

However, it looks like you actually just want to listen to the result event https://github.com/mapbox/mapbox-gl-geocoder/blob/master/API.md#on

```<code>geocoder.on('result', (e) => {
})
</code>```

and not actually change the formatting of suggestions which is what getItemValue does.

Body:
I'm working with Mapbox geocoder services for the first time, and I was trying to get the coordinates (latitude and longitude) as result of address search and I did it, but when I try to insert this result into two inputs, the input search change the address selected to "Undefined" and I don't now Why.
I want the coordinates into two input but also keep the selected address into the input search.
This is an image that shows the error:

This is the code I have Now:

mapboxgl.accessToken = 'pk.eyJ1IjoiY2FybWVuOTIiLCJhIjoiY2s2cGljM3ZzMW1udjNlbnkxZmMzdXJ3ZCJ9.HJQPFlX5VUh6wlS18R3bFw';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v11',
center: [-74.5, 40], // starting position
zoom: 9 // starting zoom
});
  var geocoder = new MapboxGeocoder({ // Initialize the geocoder
  accessToken: mapboxgl.accessToken, // Set the access token
  marker: {
    color: 'orange'
    },
  mapboxgl: mapboxgl // Set the mapbox-gl instance
  getItemValue: e => {
  document.getElementById('LocationLongitude_listingAdd').value = e['center'][0]; //long
  document.getElementById('LocationLatitude_listingAdd').value = e['center'][1]; //lat
  document.getElementsByClassName('mapboxgl-ctrl-geocoder--input').value = e['place_name']; //lat
    }

  });
document.getElementById('geocode_container').appendChild(geocoder.onAdd(map));

    #container_map{ position: relative; width: 100%; height: 400px;}
#map { position: absolute; top: 0; bottom: 0; width: 100%; height: 100%; }
.mapboxgl-ctrl-geocoder--input{min-width: 100%; width: 100%; border: 1px solid #DFE3E7 !important; border-radius: 0.267rem !important; transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out !important;}
 #map .mapboxgl-canvas-container canvas
    {
        width: 100% !important;
        height: 400px !important;
    }
.mapboxgl-ctrl-geocoder--input:focus{
    border-color: #5A8DEE !important;
    outline: 0 !important;
    box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.1) !important;
    }

.coordinates-result input { display: inline-block; }

    @media screen and (min-width: 640px)
    {
            .mapboxgl-ctrl-geocoder
            {
                width: 100% !important;
                font-size: 12px;
                line-height: 20px;

            }
    }
    .mapboxgl-ctrl-geocoder, .mapboxgl-ctrl-geocoder .suggestions {
        box-shadow: none !important;
    }

<!DOCTYPE html>

<link href="https://api.mapbox.com/mapbox-gl-js/v1.7.0/mapbox-gl.css" rel="stylesheet" />

    <link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.4.2/mapbox-gl-geocoder.css" type="text/css" />

How Can I do to get the result coordinates of searching an address on Mapbox and keep the address and the coordinates into their inputs, because I'll save that data on a database.

Body:
According to the API docs https://github.com/mapbox/mapbox-gl-geocoder/blob/master/API.md#mapboxgeocoder

options.getItemValue Function? A function that specifies how the
  selected result should be rendered in the search bar. This function
  should accept a single Carmen GeoJSON object as input and return a
  string. HTML tags in the output string will not be rendered. Defaults
  to (item) => item.place_name.

In your example you've failed to return something from getItemValue hence it's showing undefined.

However, it looks like you actually just want to listen to the result event https://github.com/mapbox/mapbox-gl-geocoder/blob/master/API.md#on

geocoder.on('result', (e) => {
})

and not actually change the formatting of suggestions which is what getItemValue does.


问:
Vector capacity and reserve
Consider the following code snippet:

```<code>std::vector<int> v;
v.reserve(100);
v.insert(v.end(), 100, 5);

v.erase(v.begin(), v.end());

std::cout << v.capacity << std::endl;
</code>```

This prints out 100. Does it mean that vector still holds the 100 memory locations? Is it required to call reserve(0) after calling erase(begin,end) on a vector, to relinquish all space held by the vector?

答: Just as a reminder, C++0x/11 added the shrink_to_fit convenience function to the STL container, which is already available in VS2010, so you're lucky if you're coding on Windows (with VS). :)

Title: Vector capacity and reserve

Body:
Consider the following code snippet:

std::vector<int> v;
v.reserve(100);
v.insert(v.end(), 100, 5);

v.erase(v.begin(), v.end());

std::cout << v.capacity << std::endl;

This prints out 100. Does it mean that vector still holds the 100 memory locations? Is it required to call reserve(0) after calling erase(begin,end) on a vector, to relinquish all space held by the vector?


问:
Is there a way to dynamic update variables in subclass?
I have two config classes, base class Config and subclass ProdConfig, code shows below:

class Config:
    URL = "http://127.0.0.1"
    ANOTHER_URL = URL + "/home"

class ProdConfig(Config):
    URL = "http://test.abc.com"
    # ANOTHER_URL = URL + "/home"

print(Config.URL) # "http://127.0.0.1"
print(Config.ANOTHER_URL) # "http://127.0.0.1/home"
print(ProdConfig.URL) # "http://test.abc.com"
print(ProdConfig.ANOTHER_URL) # http://127.0.0.1/home
```

If I do not override the variable ANOTHER_URL in ProdConfig or declare it as @property, the value is same with base class, I got it cus value is assigned when base class imported, but can I get it with new value align to new URL? Is there a way to use Metaclass or setattr or getattr tricks to solve this problem??

Thank you very much!

答:
As noted in the question and the following discussion attached to it, the usage of property does not work on the class definition directly, and that forcing subclasses to also define the property to maintain the definition "protocol" for every attribute may become cumbersome.  A usage of format string was also suggested, but we will still have the same issue with the assignment done at class definition for the standard type metaclass is that it will not be recalculated.  Consider the alternative approach:

```<code>class Config:
    URL = "http://127.0.0.1"
    ANOTHER_URL = f"{URL}/home"

class ProdConfig(Config):
    URL = "http://test.abc.com"
</code>```

Running the following will fail to produce the desired result:

```<code>>>> conf = ProdConfig()
>>> print(conf.URL)
http://test.abc.com
>>> print(conf.ANOTHER_URL)
http://127.0.0.1/home
</code>```

Simply due to the fact that ANOTHER_URL was not reassigned in the scope of ProdConfig.  However, this problem can be solved using the following metaclass:

```<code>class ConfigFormatMeta(type):

    def __init__(cls, name, bases, attrs):
        # create and store a "private" mapping of original definitions,
        # for reuse by subclasses
        cls._config_map = config_map = {}
        # merge all config_maps of base classes.
        for base_cls in bases:
            if hasattr(base_cls, '_config_map'):
                config_map.update(base_cls._config_map)

        # update the config_map with original definitions in the newly
        # constructed class, filter out all values beginning with '_'
        config_map.update({
            k: v for k, v in vars(cls).items() if not k.startswith('_')})

        # Now assign the formatted attributes to the class
        for k in config_map:
            # Only apply to str attributes; other types of attributes
            # on the class will need additional work.
            if isinstance(config_map[k], str):
                setattr(cls, k, config_map[k].format(**config_map))

        super().__init__(name, bases, attrs)
</code>```

With that, try basing the Config class using the new metaclass:

```<code>class Config(metaclass=ConfigFormatMeta):
    URL = 'http://example.com'
    ANOTHER_URL = '{URL}/home'

class ProdConfig(Config):
    URL = 'http://abc.example.com'
</code>```

Now try this again:

```<code>>>> conf = ProdConfig()
>>> print(conf.URL)
http://abc.example.com
>>> print(conf.ANOTHER_URL)
http://abc.example.com/home
</code>```

Note that ANOTHER_URL was not redefined in the scope of ProdConfig, yet the desired behavior of having only the URL be redefined to have the expected value of 'http://abc.example.com/home' was achieved.

Also it is worth noting that using metaclasses will interfere with multiple inheritance with other classes that have a different base metaclass, and that there is a bit of duplication with the original mapping that is slightly hidden via the _config_map attribute on the class itself, so please treat this mostly as a proof of concept.

Body:
I have two config classes, base class Config and subclass ProdConfig, code shows below:

class Config:
    URL = "http://127.0.0.1"
    ANOTHER_URL = URL + "/home"

class ProdConfig(Config):
    URL = "http://test.abc.com"
    # ANOTHER_URL = URL + "/home"

print(Config.URL) # "http://127.0.0.1"
print(Config.ANOTHER_URL) # "http://127.0.0.1/home"
print(ProdConfig.URL) # "http://test.abc.com"
print(ProdConfig.ANOTHER_URL) # http://127.0.0.1/home

If I do not override the variable ANOTHER_URL in ProdConfig or declare it as @property, the value is same with base class, I got it cus value is assigned when base class imported, but can I get it with new value align to new URL? Is there a way to use Metaclass or setattr or getattr tricks to solve this problem??

Thank you very much!

Body:
As noted in the question and the following discussion attached to it, the usage of property does not work on the class definition directly, and that forcing subclasses to also define the property to maintain the definition "protocol" for every attribute may become cumbersome.  A usage of format string was also suggested, but we will still have the same issue with the assignment done at class definition for the standard type metaclass is that it will not be recalculated.  Consider the alternative approach:

class Config:
    URL = "http://127.0.0.1"
    ANOTHER_URL = f"{URL}/home"

class ProdConfig(Config):
    URL = "http://test.abc.com"

Running the following will fail to produce the desired result:

>>> conf = ProdConfig()
>>> print(conf.URL)
http://test.abc.com
>>> print(conf.ANOTHER_URL)
http://127.0.0.1/home

Simply due to the fact that ANOTHER_URL was not reassigned in the scope of ProdConfig.  However, this problem can be solved using the following metaclass:

class ConfigFormatMeta(type):

    def __init__(cls, name, bases, attrs):
        # create and store a "private" mapping of original definitions,
        # for reuse by subclasses
        cls._config_map = config_map = {}
        # merge all config_maps of base classes.
        for base_cls in bases:
            if hasattr(base_cls, '_config_map'):
                config_map.update(base_cls._config_map)

        # update the config_map with original definitions in the newly
        # constructed class, filter out all values beginning with '_'
        config_map.update({
            k: v for k, v in vars(cls).items() if not k.startswith('_')})

        # Now assign the formatted attributes to the class
        for k in config_map:
            # Only apply to str attributes; other types of attributes
            # on the class will need additional work.
            if isinstance(config_map[k], str):
                setattr(cls, k, config_map[k].format(**config_map))

        super().__init__(name, bases, attrs)

With that, try basing the Config class using the new metaclass:

class Config(metaclass=ConfigFormatMeta):
    URL = 'http://example.com'
    ANOTHER_URL = '{URL}/home'

class ProdConfig(Config):
    URL = 'http://abc.example.com'

Now try this again:

>>> conf = ProdConfig()
>>> print(conf.URL)
http://abc.example.com
>>> print(conf.ANOTHER_URL)
http://abc.example.com/home

Note that ANOTHER_URL was not redefined in the scope of ProdConfig, yet the desired behavior of having only the URL be redefined to have the expected value of 'http://abc.example.com/home' was achieved.

Also it is worth noting that using metaclasses will interfere with multiple inheritance with other classes that have a different base metaclass, and that there is a bit of duplication with the original mapping that is slightly hidden via the _config_map attribute on the class itself, so please treat this mostly as a proof of concept.


问:
How do i print all the numbers in value num1, num2, num3, and the long hex in rax?
```<code>Console         equ     -11

extern  GetStdHandle:   PROTO
extern  WriteFile:      PROTO
extern  ReadFile:       PROTO
extern  ExitProcess:    PROTO

.data
num1        byte    ?
num2        word    ?
num3        dword   ?
num4        qword   ?
stdin       qword   ?
stdout      qword   ?
numWrite    qword   ?

.code
mainCRTStartup      PROC
    sub rsp, 40     ;reserve shadow space

    mov rcx, CONSOLE
    call GetStdHandle
    mov stdin, rax

    ;Storing information into memory
    mov num1, 6dh
    mov num2, 7361h
    mov num3, 7369206dh
    mov rax, 216e754620h

    mov rcx, stdout         ;parm1 = console
    lea rdx, num2           ;parm2 = ASCII
    ;parm3 = total #bytes to display
    mov r8, 15
    lea r9, numWrite
    mov qword ptr [rsp+32], 0
    call ReadFile

    add rsp, 40
    mov rcx, 0
    call ExitProcess
mainCRTStartup      ENDP
END
</code>```

答:
As comment, you can use printf with "%x" format or "%lx" for long type.

Or you can use the api itoa/ltoa


问:
Unable to verify Forge callback payload signature
I am currently using Forge Webhooks API to handle different events that might occur on a project. Everything works fine, except the payload signature check.

The reason why I want to check the payload is because the callback will end up on my API and I want to reject all requests that do not come from Forge's webhook service.

Steps I followed:

Add (register) secret key (token) on Forge. API Reference

Trigger an event that will eventually call my API for handling it.

Validating signature header. Followed this tutorial.

PROBLEM!!! My computedSignature is different from the signature received from Forge.

My C# code looks like this:

private const string SHA_HASH = "sha1hash";

```<code>var secretKeyBytes = Encoding.UTF8.GetBytes(ForgeAuthConfiguration.AntiForgeryToken);

using var hmac = new HMACSHA1(secretKeyBytes);

var computedHash = hmac.ComputeHash(request.Body.ReadAsBytes());

var computedSignature = $"{SHA_HASH}={computedHash.Aggregate("", (s, e) => s + $"{e:x2}", s => s)}";
</code>```

For one example, Forge's request has this signature header: sha1hash=303c4e7d2a94ccfa559560dc2421cee8496d2d83

My C# code computes this signature: sha1hash=3bb8d41c3c1cb6c9652745f5996b4e7f832ca8d5

The same AntiForgeryToken was sent to Forge at step 1

Ok, I thought my C# code is broken, then I tried this online HMAC generator and for the given input, result is: 3bb8d41c3c1cb6c9652745f5996b4e7f832ca8d5 (same as C#)

Ok, maybe the online generator is broken, I tried their own code in node js and this is the result:

I have 3 ways of encrypting the SAME body using the SAME key and I get the SAME result every time. BUT those results are DIFFERENT from the signature provided by Forge, resulting in failing the check and rejecting a valid request...

Does anyone know what is happening with that signature?

Why is it different from my result if I follow their tutorial?

How are you validating your requests?

答:
The code below is working at my side. Could you give it a try if it helps?

```<code>    [HttpPost]
    [Route("api/forge/callback/webhookbysig")]
    public async Task<IActionResult> WebhookCallbackBySig()
    {
        try
        {
            var encoding = Encoding.UTF8;
            byte[] rawBody = null;
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                rawBody = encoding.GetBytes(reader.ReadToEnd());
            }
            var requestSignature = Request.Headers["x-adsk-signature"];
            string myPrivateToken = Credentials.GetAppSetting("FORGE_WEBHOOK_PRIVATE_TOKEN");
            var tokenBytes = encoding.GetBytes(myPrivateToken);
            var hmacSha1 = new HMACSHA1(tokenBytes);
            byte[] hashmessage = hmacSha1.ComputeHash(rawBody);
            var calculatedSignature = "sha1hash=" + BitConverter.ToString(hashmessage).ToLower().Replace("-", "");
            if (requestSignature.Equals(calculatedSignature))
            {
                System.Diagnostics.Debug.Write("Same!");
            }
            else
            {
                System.Diagnostics.Debug.Write("diff!");
            }

        }
        catch(Exception ex)
        {

        }

        // ALWAYS return ok (200)

        return Ok();
 }
</code>```

If this does not help, please share with your webhook ID (better send email at forge.help@autodesk.com). We will ask engineer team to check it.

Body:
I am currently using Forge Webhooks API to handle different events that might occur on a project. Everything works fine, except the payload signature check.

The reason why I want to check the payload is because the callback will end up on my API and I want to reject all requests that do not come from Forge's webhook service.

Steps I followed:

Add (register) secret key (token) on Forge. API Reference

Trigger an event that will eventually call my API for handling it.

Validating signature header. Followed this tutorial.

PROBLEM!!! My computedSignature is different from the signature received from Forge.

My C# code looks like this:

private const string SHA_HASH = "sha1hash";

var secretKeyBytes = Encoding.UTF8.GetBytes(ForgeAuthConfiguration.AntiForgeryToken);

using var hmac = new HMACSHA1(secretKeyBytes);

var computedHash = hmac.ComputeHash(request.Body.ReadAsBytes());

var computedSignature = $"{SHA_HASH}={computedHash.Aggregate("", (s, e) => s + $"{e:x2}", s => s)}";

For one example, Forge's request has this signature header: sha1hash=303c4e7d2a94ccfa559560dc2421cee8496d2d83

My C# code computes this signature: sha1hash=3bb8d41c3c1cb6c9652745f5996b4e7f832ca8d5

The same AntiForgeryToken was sent to Forge at step 1

Ok, I thought my C# code is broken, then I tried this online HMAC generator and for the given input, result is: 3bb8d41c3c1cb6c9652745f5996b4e7f832ca8d5 (same as C#)

Ok, maybe the online generator is broken, I tried their own code in node js and this is the result:

I have 3 ways of encrypting the SAME body using the SAME key and I get the SAME result every time. BUT those results are DIFFERENT from the signature provided by Forge, resulting in failing the check and rejecting a valid request...

Does anyone know what is happening with that signature?

Why is it different from my result if I follow their tutorial?

How are you validating your requests?

Body:
The code below is working at my side. Could you give it a try if it helps?

    [HttpPost]
    [Route("api/forge/callback/webhookbysig")]
    public async Task<IActionResult> WebhookCallbackBySig()
    {
        try
        {
            var encoding = Encoding.UTF8;
            byte[] rawBody = null;
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                rawBody = encoding.GetBytes(reader.ReadToEnd());
            }
            var requestSignature = Request.Headers["x-adsk-signature"];
            string myPrivateToken = Credentials.GetAppSetting("FORGE_WEBHOOK_PRIVATE_TOKEN");
            var tokenBytes = encoding.GetBytes(myPrivateToken);
            var hmacSha1 = new HMACSHA1(tokenBytes);
            byte[] hashmessage = hmacSha1.ComputeHash(rawBody);
            var calculatedSignature = "sha1hash=" + BitConverter.ToString(hashmessage).ToLower().Replace("-", "");
            if (requestSignature.Equals(calculatedSignature))
            {
                System.Diagnostics.Debug.Write("Same!");
            }
            else
            {
                System.Diagnostics.Debug.Write("diff!");
            }

        }
        catch(Exception ex)
        {

        }

        // ALWAYS return ok (200)

        return Ok();
 }

If this does not help, please share with your webhook ID (better send email at forge.help@autodesk.com). We will ask engineer team to check it.


问:
How to Serialize xml and get just deepest nodes
I have the following xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<root>
    <file_1>
        <file_name Value="" />
        <date Value="" />
        <information>
            <page1>
                <percentage Value="90%" />
                <profit Value="50%" />
                <total Value="$1500" />
            </page1>
        </information>
    </file_1>
</root>
</code>```

and I want to serialize that xml but I want that all subnodes in page1 node could be handle like properties, for example:

```<code>var xmlInfo = new List<xmlClass>();
var FieldName = xmlInfo[0].FieldName; // the value of FieldName should be percentage
var data = xmlInfo[0].Value; // the value of data should be 90%
</code>```

In other words, I'm only interested in the deepest nodes to serialize them into an object.

I have a serialization method, but I don't know how to build the class.

```<code>public static T Deserialize<T>(XDocument doc)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (var reader = doc.Root.CreateReader())
            {
                return (T)xmlSerializer.Deserialize(reader);
            }
        }
</code>```

答:
Use xml linq with a dictionary :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, string> dict = doc.Descendants("page1")
                .First()
                .Elements()
                .GroupBy(x => x.Name.LocalName, y => (string)y.Attribute("Value"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}
</code>```

Body:
I have the following xml file

<?xml version="1.0" encoding="utf-8"?>
<root>
    <file_1>
        <file_name Value="" />
        <date Value="" />
        <information>
            <page1>
                <percentage Value="90%" />
                <profit Value="50%" />
                <total Value="$1500" />
            </page1>
        </information>
    </file_1>
</root>

and I want to serialize that xml but I want that all subnodes in page1 node could be handle like properties, for example:

var xmlInfo = new List<xmlClass>();
var FieldName = xmlInfo[0].FieldName; // the value of FieldName should be percentage
var data = xmlInfo[0].Value; // the value of data should be 90%

In other words, I'm only interested in the deepest nodes to serialize them into an object.

I have a serialization method, but I don't know how to build the class.

public static T Deserialize<T>(XDocument doc)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (var reader = doc.Root.CreateReader())
            {
                return (T)xmlSerializer.Deserialize(reader);
            }
        }

Body:
Use xml linq with a dictionary :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, string> dict = doc.Descendants("page1")
                .First()
                .Elements()
                .GroupBy(x => x.Name.LocalName, y => (string)y.Attribute("Value"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}


问:
Get eye, target and up vectors from view matrix
In Direct3D, I'm using the Matrix.LookAtLH function to compute the view matrix.

I am using this for the camera, which I orbit around a target by moving the origin to the target position, rotating, and then moving the origin back to (0,0,0).

This is multiplied to the matrix that was originally computed from LookAtLH.

Is there a way I can, after a few of these operations, decompose the matrix to get the eye position, target position, and up vector?

答:
View matricies are very easy to extract data from. Check out the documentation for the function you used (I've used the documentation for D3DXMatrixLookAtLH):

http://msdn.microsoft.com/en-us/library/bb205342%28v=vs.85%29.aspx

As you can see towards the bottom of the page, the matrix is internally generated like so:

```<code>zaxis = normal(At - Eye)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)

 xaxis.x           yaxis.x           zaxis.x          0
 xaxis.y           yaxis.y           zaxis.y          0
 xaxis.z           yaxis.z           zaxis.z          0
-dot(xaxis, eye)  -dot(yaxis, eye)  -dot(zaxis, eye)  1
</code>```

Bear in mind, this is only valid for DirectX; transpose the above matrix when porting the same calculations to OpenGL because the coordinate system in DirectX is backwards to the norm.

Body:
View matricies are very easy to extract data from. Check out the documentation for the function you used (I've used the documentation for D3DXMatrixLookAtLH):

http://msdn.microsoft.com/en-us/library/bb205342%28v=vs.85%29.aspx

As you can see towards the bottom of the page, the matrix is internally generated like so:

zaxis = normal(At - Eye)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)

 xaxis.x           yaxis.x           zaxis.x          0
 xaxis.y           yaxis.y           zaxis.y          0
 xaxis.z           yaxis.z           zaxis.z          0
-dot(xaxis, eye)  -dot(yaxis, eye)  -dot(zaxis, eye)  1

Bear in mind, this is only valid for DirectX; transpose the above matrix when porting the same calculations to OpenGL because the coordinate system in DirectX is backwards to the norm.


问:
Getting element content with JSOUP node's attributes
I'm having troubles with JSoup.

I have this html code:

```<code> <div title = "test" data-x="test1">I am the content</div>
</code>```

I'm using Jsoup to parse the html file.

When I'm traversing it like this:

```<code>html.traverse(new NodeVisitor() {
        public void head(Node node, int depth) {
            System.out.println(node.attributes());

        }

        public void tail(Node node, int depth) {
            ...
        }
   });
</code>```

I can see with the print that Jsoup assumes Element content is an attribute. Is that right?
I was expecting to get only "title" and "data-x" in this example.

Thanks

答:
Try this</p>

```<code>String html = "<div title = 'test' data-x='test1'>I am the content</div>";

Document doc = Jsoup.parse(html);

Element div = doc.select("div").first();

String divTitle = div.attr("title"); // "test"
String divDataX = div.attr("data-x"); // "test1"
</code>```

Body:
I'm having troubles with JSoup.

I have this html code:

I am the content

I'm using Jsoup to parse the html file.

When I'm traversing it like this:

html.traverse(new NodeVisitor() {
        public void head(Node node, int depth) {
            System.out.println(node.attributes());

        }

        public void tail(Node node, int depth) {
            ...
        }
   });

I can see with the print that Jsoup assumes Element content is an attribute. Is that right?
I was expecting to get only "title" and "data-x" in this example.

Thanks

Body:
Try this

String html = "<div title = 'test' data-x='test1'>I am the content</div>";

Document doc = Jsoup.parse(html);

Element div = doc.select("div").first();

String divTitle = div.attr("title"); // "test"
String divDataX = div.attr("data-x"); // "test1"


问:
Creating a Stream User in React Native with a Rails Backend
I am trying to create a stream user for my react native front end.  I used Ruby on Rails for the authentication backend, received a jwt token, and now I want to use that token to create my stream user.  How do I go about doing this?  In creating the token server-side, would I need to include this line of code in my login/signup function?

```<code>user_token = client.create_user_session_token('the-user-id')
</code>```

Any help would be great! Thanks!

答:
If you are generating and passing a token from your Ruby back end to your react-native front end, you need to instantiate the Stream client in your front end. You don't need to create another token on the front end with the code you have linked. Instantiate client with the following code: </p>

```<code>const client = stream.connect(api_key, token, app_id);
</code>```

Body:
I am trying to create a stream user for my react native front end.  I used Ruby on Rails for the authentication backend, received a jwt token, and now I want to use that token to create my stream user.  How do I go about doing this?  In creating the token server-side, would I need to include this line of code in my login/signup function?

user_token = client.create_user_session_token('the-user-id')

Any help would be great! Thanks!

Body:
If you are generating and passing a token from your Ruby back end to your react-native front end, you need to instantiate the Stream client in your front end. You don't need to create another token on the front end with the code you have linked. Instantiate client with the following code:

const client = stream.connect(api_key, token, app_id);


问:
Creating an R function that can accept both datasets and object names as well as those names as a string object
I can make a function that takes object names as arguments (this is just a normal function).

I can also now make a function that get's its data and column arguments via a named vector (utilising dataset <- eval(sym(dataset)) and date_col <- sym(date_col)).

However I would like a function that can handle both types of inputs.

Step one is to detect the class of the input.

For the dataset argument, this (below) works fine for both the named vector and the actual object name.

```<code> if (is.character(dataset)) {
    dataset <- eval(sym(dataset)) }
</code>```

I am not able to figure out the appropriate way to handle the column arguments, however.

When I use the named-vector elements for them, the process (below) works fine.

```<code>  if (is.character(date_col)) {
    date_col <- sym(date_col) }
</code>```

But I am unsure how to handle the actual column name (ie by adding in an else component, above).
Essentially I want to turn it into a sym so I can still use the {{}} (or !!) in the function's steps.

Here is a minimum reproducible example for what I am after.
As you will see the named vector version works but not the actual dataset and column names.

Is what I'm after even possible? Can a function be dynamic in this way or do I need to make two separate functions?

[edited: made a simpler example, as per comment]

```<code>library(dplyr)
library(rlang)

new_table <- tibble(
  Date = seq.Date(as.Date("2016-01-01"), as.Date("2019-12-31"), 1)) %>%
  mutate(total_sales = rnorm(n()))

f_arguments <- c("dataset" = "new_table",
                        "date_col" = "Date",
                        "sales_col" = "total_sales")

f <- function(data, x, envir = parent.frame()) {

  if (is.character(data)) {
    data <- get(data, envir)}

  if (is.character(x)) {
    x <- sym(x) }

  data %>%
    mutate(year_month = lubridate::floor_date(!!ensym(x), "months"),
           year = lubridate::year(!!ensym(x)))

}

# this (below) works per the above code, but not if I comment out
# the if (is.character(x)) line

f(f_arguments[["dataset"]],
  f_arguments[["date_col"]])

# this (below) does not work with the above code, but it will work if I comment out
# the if (is.character(x)) line

f(new_table, Date)

</code>```

答:
Have revised the example in line with the revised question.

```<code>library(dplr)
library(lubridate)

f <- function(data, x, envir = parent.frame()) {
  if (is.character(data)) data <- get(data, envir)
  x <- eval(substitute(x), data, envir)
  if (is.character(x)) x <- data[[x]]
  data %>% mutate(year = year(x)) %>% slice(1:2)
}
</code>```

giving

```<code>f(f_arguments[["dataset"]], f_arguments[["date_col"]])  # test 1
## # A tibble: 2 x 3
##   Date       total_sales  year
##   <date>           <dbl> <dbl>
## 1 2016-01-01      -0.975  2016
## 2 2016-01-02       0.120  2016

f("new_table", "Date") # test 2
## # A tibble: 2 x 3
##   Date       total_sales  year
##   <date>           <dbl> <dbl>
## 1 2016-01-01      -0.975  2016
## 2 2016-01-02       0.120  2016

f(new_table, Date)  # test 3
## # A tibble: 2 x 3
##   Date       total_sales  year
##   <date>           <dbl> <dbl>
## 1 2016-01-01      -0.975  2016
## 2 2016-01-02       0.120  2016

f(new_table, f_arguments[["date_col"]]) # test 4
## # A tibble: 2 x 3
##   Date       total_sales  year
##   <date>           <dbl> <dbl>
## 1 2016-01-01      -0.975  2016
## 2 2016-01-02       0.120  2016

# test 5
g <- function(...) { new_tab <- new_table; f(...) }
g("new_tab", "Date")
## # A tibble: 2 x 3
##   Date       total_sales  year
##   <date>           <dbl> <dbl>
## 1 2016-01-01      -0.975  2016
## 2 2016-01-02       0.120  2016
</code>```

Note

Personally I would not do the above and would avoid unevaluated arguments and would pass the first argument as an object and the second as a character string.  The two examples shown below would still work.

```<code>f2 <- function(data, x) {
  data %>% mutate(year = year(.[[x]])) %>% slice(1:2)
}

f2(new_table, "Date")
f2(get(f_arguments[["dataset"]]), f_arguments[["date_col"]])
</code>```

Alternately allow data to be passed as a character string using S3:

```<code>f3 <- function(data, x, ...) UseMethod("f3")
f3.default <- function(data, x, ...)  {
  data %>% mutate(year = year(.[[x]])) %>% slice(1:2)
}
f3.character <- function(data, x, envir = parent.frame(), ...) {
   data <- get(data, envir)
   NextMethod()
}

f3(new_table, "Date")
f3(f_arguments[["dataset"]], f_arguments[["date_col"]])
</code>```

Body:
I can make a function that takes object names as arguments (this is just a normal function).

I can also now make a function that get's its data and column arguments via a named vector (utilising dataset <- eval(sym(dataset)) and date_col <- sym(date_col)).

However I would like a function that can handle both types of inputs.

Step one is to detect the class of the input.

For the dataset argument, this (below) works fine for both the named vector and the actual object name.

 if (is.character(dataset)) {
    dataset <- eval(sym(dataset)) }

I am not able to figure out the appropriate way to handle the column arguments, however.

When I use the named-vector elements for them, the process (below) works fine.

  if (is.character(date_col)) {
    date_col <- sym(date_col) }

But I am unsure how to handle the actual column name (ie by adding in an else component, above).
Essentially I want to turn it into a sym so I can still use the {{}} (or !!) in the function's steps.

Here is a minimum reproducible example for what I am after.
As you will see the named vector version works but not the actual dataset and column names.

Is what I'm after even possible? Can a function be dynamic in this way or do I need to make two separate functions?

[edited: made a simpler example, as per comment]

library(dplyr)
library(rlang)

new_table <- tibble(
  Date = seq.Date(as.Date("2016-01-01"), as.Date("2019-12-31"), 1)) %>%
  mutate(total_sales = rnorm(n()))

f_arguments <- c("dataset" = "new_table",
                        "date_col" = "Date",
                        "sales_col" = "total_sales")

f <- function(data, x, envir = parent.frame()) {

  if (is.character(data)) {
    data <- get(data, envir)}

  if (is.character(x)) {
    x <- sym(x) }

  data %>%
    mutate(year_month = lubridate::floor_date(!!ensym(x), "months"),
           year = lubridate::year(!!ensym(x)))

}

# this (below) works per the above code, but not if I comment out
# the if (is.character(x)) line

f(f_arguments[["dataset"]],
  f_arguments[["date_col"]])

# this (below) does not work with the above code, but it will work if I comment out
# the if (is.character(x)) line

f(new_table, Date)

Body:
Have revised the example in line with the revised question.

library(dplr)
library(lubridate)

f <- function(data, x, envir = parent.frame()) {
  if (is.character(data)) data <- get(data, envir)
  x <- eval(substitute(x), data, envir)
  if (is.character(x)) x <- data[[x]]
  data %>% mutate(year = year(x)) %>% slice(1:2)
}

giving

f(f_arguments[["dataset"]], f_arguments[["date_col"]])  # test 1
## # A tibble: 2 x 3
##   Date       total_sales  year
##   <date>           <dbl> <dbl>
## 1 2016-01-01      -0.975  2016
## 2 2016-01-02       0.120  2016

f("new_table", "Date") # test 2
## # A tibble: 2 x 3
##   Date       total_sales  year
##   <date>           <dbl> <dbl>
## 1 2016-01-01      -0.975  2016
## 2 2016-01-02       0.120  2016

f(new_table, Date)  # test 3
## # A tibble: 2 x 3
##   Date       total_sales  year
##   <date>           <dbl> <dbl>
## 1 2016-01-01      -0.975  2016
## 2 2016-01-02       0.120  2016

f(new_table, f_arguments[["date_col"]]) # test 4
## # A tibble: 2 x 3
##   Date       total_sales  year
##   <date>           <dbl> <dbl>
## 1 2016-01-01      -0.975  2016
## 2 2016-01-02       0.120  2016

# test 5
g <- function(...) { new_tab <- new_table; f(...) }
g("new_tab", "Date")
## # A tibble: 2 x 3
##   Date       total_sales  year
##   <date>           <dbl> <dbl>
## 1 2016-01-01      -0.975  2016
## 2 2016-01-02       0.120  2016

Note

Personally I would not do the above and would avoid unevaluated arguments and would pass the first argument as an object and the second as a character string.  The two examples shown below would still work.

f2 <- function(data, x) {
  data %>% mutate(year = year(.[[x]])) %>% slice(1:2)
}

f2(new_table, "Date")
f2(get(f_arguments[["dataset"]]), f_arguments[["date_col"]])

Alternately allow data to be passed as a character string using S3:

f3 <- function(data, x, ...) UseMethod("f3")
f3.default <- function(data, x, ...)  {
  data %>% mutate(year = year(.[[x]])) %>% slice(1:2)
}
f3.character <- function(data, x, envir = parent.frame(), ...) {
   data <- get(data, envir)
   NextMethod()
}

f3(new_table, "Date")
f3(f_arguments[["dataset"]], f_arguments[["date_col"]])