问:
How can I define a macro using other preprocessor directives?
I am trying to define the following macro to disable a specific warning:

```<code>#define HUGE_VAL_DISABLE_WRN #pragma warning( disable : 4005 )

HUGE_VAL_DISABLE_WRN    // <-- errors here
#include "header.h"
</code>```

and I get the following errors (all on the same line):

```<code>error C2121: '#' : invalid character : possibly the result of a macro expansion
error C2146: syntax error : missing ';' before identifier 'warning'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2065: 'disable' : undeclared identifier
error C2143: syntax error : missing ')' before ':'
error C2448: 'warning' : function-style initializer appears to be a function definition
error C2059: syntax error : 'constant'
error C2059: syntax error : ')'
</code>```

What I am trying to do is to define a macro containing some preprocessor directives, which can be empty in certain conditions, but I am clearly missing something.

The complete definition is:

```<code>#if (_MSC_VER < REC_VISUAL_CPP_VERS && INTEL_MKL_VERSION < REC_INTEL_MKL_VERS)
#define HUGE_VAL_DISABLE_WRN_BEGIN \
    _Pragma("warning( push )") \
    _Pragma("warning( disable : 4005 )") // macro redefinition
#define HUGE_VAL_DISABLE_WRN_END #pragma warning( pop )
#else
    #define HUGE_VAL_DISABLE_WRN_BEGIN
    #define HUGE_VAL_DISABLE_WRN_END
#endif
</code>```

From this I get:

```<code>error : this declaration has no storage class or type specifier
error : a value of type "const char *" cannot be used to initialize an entity of type "int"
error : expected a ";"
warning : parsing restarts here after previous syntax error
</code>```

答:
I just found out that Microsoft Visual C++ (at least up to version 2019) does not provide the _Pragma keyword (part of Standard C++11).

They have their own, slightly different, __pragma keyword:

```<code>#define HUGE_VAL_DISABLE_WRN_BEGIN \
    __pragma(warning( push )) \
    __pragma(warning( disable : 4005 )) // macro redefinition
</code>```

Body:
I am trying to define the following macro to disable a specific warning:

#define HUGE_VAL_DISABLE_WRN #pragma warning( disable : 4005 )

HUGE_VAL_DISABLE_WRN    // <-- errors here
#include "header.h"

and I get the following errors (all on the same line):

error C2121: '#' : invalid character : possibly the result of a macro expansion
error C2146: syntax error : missing ';' before identifier 'warning'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2065: 'disable' : undeclared identifier
error C2143: syntax error : missing ')' before ':'
error C2448: 'warning' : function-style initializer appears to be a function definition
error C2059: syntax error : 'constant'
error C2059: syntax error : ')'

What I am trying to do is to define a macro containing some preprocessor directives, which can be empty in certain conditions, but I am clearly missing something.

The complete definition is:

#if (_MSC_VER < REC_VISUAL_CPP_VERS && INTEL_MKL_VERSION < REC_INTEL_MKL_VERS)
#define HUGE_VAL_DISABLE_WRN_BEGIN \
    _Pragma("warning( push )") \
    _Pragma("warning( disable : 4005 )") // macro redefinition
#define HUGE_VAL_DISABLE_WRN_END #pragma warning( pop )
#else
    #define HUGE_VAL_DISABLE_WRN_BEGIN
    #define HUGE_VAL_DISABLE_WRN_END
#endif

From this I get:

error : this declaration has no storage class or type specifier
error : a value of type "const char *" cannot be used to initialize an entity of type "int"
error : expected a ";"
warning : parsing restarts here after previous syntax error

Body:
I just found out that Microsoft Visual C++ (at least up to version 2019) does not provide the _Pragma keyword (part of Standard C++11).

They have their own, slightly different, __pragma keyword:

#define HUGE_VAL_DISABLE_WRN_BEGIN \
    __pragma(warning( push )) \
    __pragma(warning( disable : 4005 )) // macro redefinition


来源: stackexchange

问:
How does the ViewModel constructor get the required interfaces?
My question based on InventorySampleApp by Microsoft.

The ServiceLocator contains method Configure() that register Services and ViewModels. With method GetService<T>() we can get it. For example, ProductView.cs:

```<code>ViewModel = ServiceLocator.Current.GetService<ProductDetailsViewModel>();
</code>```

Each *ViewModel contains constructor with interface, for example:

```<code>public ProductDetailsViewModel(IProductService productService, IFilePickerService filePickerService, ICommonServices commonServices)
</code>```

I can't understand the magiс that ViewModel uses to get such interfaces into its constructor. So there are no lines like this:

```<code>... = new ProductDetailsViewModel(productService, filePickerService, commonServices)
</code>```

How does the ViewModel constructor get the required interfaces?

ServiceLocator

```<code>public class ServiceLocator : IDisposable
{
    static private readonly ConcurrentDictionary<int, ServiceLocator> _serviceLocators = new ConcurrentDictionary<int, ServiceLocator>();

    static private ServiceProvider _rootServiceProvider = null;

    static public void Configure(IServiceCollection serviceCollection)
    {
        serviceCollection.AddSingleton<ISettingsService, SettingsService>();
        serviceCollection.AddSingleton<IDataServiceFactory, DataServiceFactory>();
        serviceCollection.AddSingleton<ILookupTables, LookupTables>();
        serviceCollection.AddSingleton<ICustomerService, CustomerService>();
        serviceCollection.AddSingleton<IOrderService, OrderService>();
        serviceCollection.AddSingleton<IOrderItemService, OrderItemService>();
        serviceCollection.AddSingleton<IProductService, ProductService>();

        serviceCollection.AddSingleton<IMessageService, MessageService>();
        serviceCollection.AddSingleton<ILogService, LogService>();
        serviceCollection.AddSingleton<IDialogService, DialogService>();
        serviceCollection.AddSingleton<IFilePickerService, FilePickerService>();
        serviceCollection.AddSingleton<ILoginService, LoginService>();

        serviceCollection.AddScoped<IContextService, ContextService>();
        serviceCollection.AddScoped<INavigationService, NavigationService>();
        serviceCollection.AddScoped<ICommonServices, CommonServices>();

        serviceCollection.AddTransient<LoginViewModel>();

        serviceCollection.AddTransient<ShellViewModel>();
        serviceCollection.AddTransient<MainShellViewModel>();

        serviceCollection.AddTransient<DashboardViewModel>();

        serviceCollection.AddTransient<CustomersViewModel>();
        serviceCollection.AddTransient<CustomerDetailsViewModel>();

        serviceCollection.AddTransient<OrdersViewModel>();
        serviceCollection.AddTransient<OrderDetailsViewModel>();
        serviceCollection.AddTransient<OrderDetailsWithItemsViewModel>();

        serviceCollection.AddTransient<OrderItemsViewModel>();
        serviceCollection.AddTransient<OrderItemDetailsViewModel>();

        serviceCollection.AddTransient<ProductsViewModel>();
        serviceCollection.AddTransient<ProductDetailsViewModel>();

        serviceCollection.AddTransient<AppLogsViewModel>();

        serviceCollection.AddTransient<SettingsViewModel>();
        serviceCollection.AddTransient<ValidateConnectionViewModel>();
        serviceCollection.AddTransient<CreateDatabaseViewModel>();

        _rootServiceProvider = serviceCollection.BuildServiceProvider();
    }

    static public ServiceLocator Current
    {
        get
        {
            int currentViewId = ApplicationView.GetForCurrentView().Id;
            return _serviceLocators.GetOrAdd(currentViewId, key => new ServiceLocator());
        }
    }

    static public void DisposeCurrent()
    {
        int currentViewId = ApplicationView.GetForCurrentView().Id;
        if (_serviceLocators.TryRemove(currentViewId, out ServiceLocator current))
        {
            current.Dispose();
        }
    }

    private IServiceScope _serviceScope = null;

    private ServiceLocator()
    {
        _serviceScope = _rootServiceProvider.CreateScope();
    }

    public T GetService<T>()
    {
        return GetService<T>(true);
    }

    public T GetService<T>(bool isRequired)
    {
        if (isRequired)
        {
            return _serviceScope.ServiceProvider.GetRequiredService<T>();
        }
        return _serviceScope.ServiceProvider.GetService<T>();
    }

    #region Dispose
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_serviceScope != null)
            {
                _serviceScope.Dispose();
            }
        }
    }
    #endregion
</code>```

答:
Notice that the GetService method calls into ServiceProvider.GetService. This is a library method that takes care of things for you. Underneath the covers, it uses reflection to examine the constructor of the type you request.

For example, when you request a ProductDetailsViewModel, the ServiceLocator can see that it needs object of the types IProductService, IFilePickerService, ICommonServices.

It then looks into its registry of services. For example, the line

```<code>serviceCollection.AddSingleton<IProductService, ProductService>();
</code>```

registers the concrete type ProductService against the interface IProductService, so whenever the ServiceLocator needs to create an IProductService object, it'll use a ProductService object.

This process is called auto-wiring and is described in more details in chapter 12 of Steven van Deursen's and my book about Dependency Injection.

I can't understand the magiс that ViewModel uses to get such interfaces into its constructor.

Indeed, do yourself the favour and learn Pure DI instead of relying on opaque libraries that you don't feel comfortable with.

I've never seen that example code base before, but from the examples posted here, it looks like it's filled with code smells and anti-patterns.

ContentLicense: CC BY-SA 4.0

Body:
My question based on InventorySampleApp by Microsoft.

The ServiceLocator contains method Configure() that register Services and ViewModels. With method GetService<T>() we can get it. For example, ProductView.cs:

ViewModel = ServiceLocator.Current.GetService<ProductDetailsViewModel>();

Each *ViewModel contains constructor with interface, for example:

public ProductDetailsViewModel(IProductService productService, IFilePickerService filePickerService, ICommonServices commonServices)

I can't understand the magiс that ViewModel uses to get such interfaces into its constructor. So there are no lines like this:

... = new ProductDetailsViewModel(productService, filePickerService, commonServices)

How does the ViewModel constructor get the required interfaces?

ServiceLocator

public class ServiceLocator : IDisposable
{
    static private readonly ConcurrentDictionary<int, ServiceLocator> _serviceLocators = new ConcurrentDictionary<int, ServiceLocator>();

    static private ServiceProvider _rootServiceProvider = null;

    static public void Configure(IServiceCollection serviceCollection)
    {
        serviceCollection.AddSingleton<ISettingsService, SettingsService>();
        serviceCollection.AddSingleton<IDataServiceFactory, DataServiceFactory>();
        serviceCollection.AddSingleton<ILookupTables, LookupTables>();
        serviceCollection.AddSingleton<ICustomerService, CustomerService>();
        serviceCollection.AddSingleton<IOrderService, OrderService>();
        serviceCollection.AddSingleton<IOrderItemService, OrderItemService>();
        serviceCollection.AddSingleton<IProductService, ProductService>();

        serviceCollection.AddSingleton<IMessageService, MessageService>();
        serviceCollection.AddSingleton<ILogService, LogService>();
        serviceCollection.AddSingleton<IDialogService, DialogService>();
        serviceCollection.AddSingleton<IFilePickerService, FilePickerService>();
        serviceCollection.AddSingleton<ILoginService, LoginService>();

        serviceCollection.AddScoped<IContextService, ContextService>();
        serviceCollection.AddScoped<INavigationService, NavigationService>();
        serviceCollection.AddScoped<ICommonServices, CommonServices>();

        serviceCollection.AddTransient<LoginViewModel>();

        serviceCollection.AddTransient<ShellViewModel>();
        serviceCollection.AddTransient<MainShellViewModel>();

        serviceCollection.AddTransient<DashboardViewModel>();

        serviceCollection.AddTransient<CustomersViewModel>();
        serviceCollection.AddTransient<CustomerDetailsViewModel>();

        serviceCollection.AddTransient<OrdersViewModel>();
        serviceCollection.AddTransient<OrderDetailsViewModel>();
        serviceCollection.AddTransient<OrderDetailsWithItemsViewModel>();

        serviceCollection.AddTransient<OrderItemsViewModel>();
        serviceCollection.AddTransient<OrderItemDetailsViewModel>();

        serviceCollection.AddTransient<ProductsViewModel>();
        serviceCollection.AddTransient<ProductDetailsViewModel>();

        serviceCollection.AddTransient<AppLogsViewModel>();

        serviceCollection.AddTransient<SettingsViewModel>();
        serviceCollection.AddTransient<ValidateConnectionViewModel>();
        serviceCollection.AddTransient<CreateDatabaseViewModel>();

        _rootServiceProvider = serviceCollection.BuildServiceProvider();
    }

    static public ServiceLocator Current
    {
        get
        {
            int currentViewId = ApplicationView.GetForCurrentView().Id;
            return _serviceLocators.GetOrAdd(currentViewId, key => new ServiceLocator());
        }
    }

    static public void DisposeCurrent()
    {
        int currentViewId = ApplicationView.GetForCurrentView().Id;
        if (_serviceLocators.TryRemove(currentViewId, out ServiceLocator current))
        {
            current.Dispose();
        }
    }

    private IServiceScope _serviceScope = null;

    private ServiceLocator()
    {
        _serviceScope = _rootServiceProvider.CreateScope();
    }

    public T GetService<T>()
    {
        return GetService<T>(true);
    }

    public T GetService<T>(bool isRequired)
    {
        if (isRequired)
        {
            return _serviceScope.ServiceProvider.GetRequiredService<T>();
        }
        return _serviceScope.ServiceProvider.GetService<T>();
    }

    #region Dispose
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_serviceScope != null)
            {
                _serviceScope.Dispose();
            }
        }
    }
    #endregion

Body:
Notice that the GetService method calls into ServiceProvider.GetService. This is a library method that takes care of things for you. Underneath the covers, it uses reflection to examine the constructor of the type you request.

For example, when you request a ProductDetailsViewModel, the ServiceLocator can see that it needs object of the types IProductService, IFilePickerService, ICommonServices.

It then looks into its registry of services. For example, the line

serviceCollection.AddSingleton<IProductService, ProductService>();

registers the concrete type ProductService against the interface IProductService, so whenever the ServiceLocator needs to create an IProductService object, it'll use a ProductService object.

This process is called auto-wiring and is described in more details in chapter 12 of Steven van Deursen's and my book about Dependency Injection.

I can't understand the magiс that ViewModel uses to get such interfaces into its constructor.

Indeed, do yourself the favour and learn Pure DI instead of relying on opaque libraries that you don't feel comfortable with.

I've never seen that example code base before, but from the examples posted here, it looks like it's filled with code smells and anti-patterns.


问:
Room - SELECT doesn't return any data
Can't get where is my mistake - it seems data is inserted (I checked the database file through Device File Explorer) but it doesn't returns.
I wonder whether it's in Adapter or ViewHolder or anywhere else.
Any help is granted!

This the activity where I perform my queries

```<code>public class ShowDatabaseActivity extends AppCompatActivity {
    private List <Contact> contactsList = new ArrayList<>()

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_database);
        setupToolbar();
        initRecyclerView();
        Intent intent = getIntent();
        unpack(intent);
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            toolbar.setNavigationOnClickListener(v -> onBackPressed());
        }
    }

    private void initRecyclerView() {
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        final ContactsListAdapter adapter = new ContactsListAdapter(contactsList);
        adapter.notifyDataSetChanged();
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
    }

    private void unpack(Intent intent) {
        final Handler handler = new Handler();
        Thread backgroundThread = new Thread(() -> {
            Bundle extras = intent.getExtras();
            String lastName = extras.getString(Constants.LAST_NAME_KEY);
            String firstName = extras.getString(Constants.FIRST_NAME_KEY);
            String middleName = extras.getString(Constants.MIDDLE_NAME_KEY);
            int age = extras.getInt(Constants.AGE_KEY);
            Contact contact = new Contact(lastName, firstName, middleName, age);
            AppDatabase.getINSTANCE(ShowDatabaseActivity.this).contactDao().insert(contact);
            AppDatabase.getINSTANCE(ShowDatabaseActivity.this).contactDao().getAll();
            handler.post(() -> {

            });
        });
        backgroundThread.start();
    }
}
</code>```

If I debug this line shows data sucessfully -

```<code>(ShowDatabaseActivity.this).contactDao().insert(contact);
</code>```

My adapter

```<code>public class ContactsListAdapter extends RecyclerView.Adapter<ContactsListAdapter.ContactViewHolder> {
    private Context context;
    private List<Contact> contacts;

    public ContactsListAdapter(@NonNull List<Contact> contacts) {
        this.contacts = contacts;
    }

    @Override
    public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final LayoutInflater inflater = LayoutInflater.from(context);
        View itemView = inflater.inflate(R.layout.recycler_view, parent, false);
        return new ContactViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
            Contact currentContact = contacts.get(position);
            if (currentContact!=null) {
                holder.contactLastNameView.setText(currentContact.getLastName());
                holder.contactFirstNameView.setText(currentContact.getFirstName());
                holder.contactMiddleNameView.setText(currentContact.getMiddleName());
                holder.contactAgeView.setText(Integer.toString(currentContact.getAge()));
            }
            else {
                holder.contactLastNameView.setText("No information");
                holder.contactFirstNameView.setText("No information");
                holder.contactMiddleNameView.setText("No information");
                holder.contactAgeView.setText("No information");
            }
    }

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

    class ContactViewHolder extends RecyclerView.ViewHolder {
        private final TextView contactLastNameView;
        private final TextView contactFirstNameView;
        private final TextView contactMiddleNameView;
        private final TextView contactAgeView;

        private ContactViewHolder(View itemView) {
            super(itemView);
            contactLastNameView = itemView.findViewById(R.id.last_name_text_view);
            contactFirstNameView = itemView.findViewById(R.id.first_name_text_view);
            contactMiddleNameView = itemView.findViewById(R.id.middle_name_text_view);
            contactAgeView = itemView.findViewById(R.id.age_text_view);
        }
    }

    @Override
    public int getItemViewType(final int position) {
        return R.layout.recycler_view;
    }
}
</code>```

My DataBase

```<code>@Database(entities = {Contact.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    public abstract ContactDao contactDao();

    private List<Contact> allContacts;

    List<Contact> getAllContacts() {
        return allContacts;
    }

    private static AppDatabase INSTANCE;

    public synchronized static AppDatabase getINSTANCE(Context context) {
            INSTANCE = getDatabase(context);
        return INSTANCE;
    }

    private static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            AppDatabase.class, "table_contacts")
                            .build();
                Log.d("LOG", "Getting the database instance");
            }
        }
        return INSTANCE;
    }
}
</code>```

There is no doubt in my Entity and Dao classes as it worked perfectly with other variant of database so I don't attach them.
Will be very grateful for any help!

答:
```<code> AppDatabase.getINSTANCE(ShowDatabaseActivity.this).contactDao().getAll();
</code>```

This code does not assign data to anything/ variable to hold your data. Assign data to a reference variable  and pass that variable to the adapter so it can show data from it.

Title: Room - SELECT doesn't return any data

Body:
Can't get where is my mistake - it seems data is inserted (I checked the database file through Device File Explorer) but it doesn't returns.
I wonder whether it's in Adapter or ViewHolder or anywhere else.
Any help is granted!

This the activity where I perform my queries

public class ShowDatabaseActivity extends AppCompatActivity {
    private List <Contact> contactsList = new ArrayList<>()

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_database);
        setupToolbar();
        initRecyclerView();
        Intent intent = getIntent();
        unpack(intent);
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            toolbar.setNavigationOnClickListener(v -> onBackPressed());
        }
    }

    private void initRecyclerView() {
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        final ContactsListAdapter adapter = new ContactsListAdapter(contactsList);
        adapter.notifyDataSetChanged();
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
    }

    private void unpack(Intent intent) {
        final Handler handler = new Handler();
        Thread backgroundThread = new Thread(() -> {
            Bundle extras = intent.getExtras();
            String lastName = extras.getString(Constants.LAST_NAME_KEY);
            String firstName = extras.getString(Constants.FIRST_NAME_KEY);
            String middleName = extras.getString(Constants.MIDDLE_NAME_KEY);
            int age = extras.getInt(Constants.AGE_KEY);
            Contact contact = new Contact(lastName, firstName, middleName, age);
            AppDatabase.getINSTANCE(ShowDatabaseActivity.this).contactDao().insert(contact);
            AppDatabase.getINSTANCE(ShowDatabaseActivity.this).contactDao().getAll();
            handler.post(() -> {

            });
        });
        backgroundThread.start();
    }
}

If I debug this line shows data sucessfully -

(ShowDatabaseActivity.this).contactDao().insert(contact);

My adapter

public class ContactsListAdapter extends RecyclerView.Adapter<ContactsListAdapter.ContactViewHolder> {
    private Context context;
    private List<Contact> contacts;

    public ContactsListAdapter(@NonNull List<Contact> contacts) {
        this.contacts = contacts;
    }

    @Override
    public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final LayoutInflater inflater = LayoutInflater.from(context);
        View itemView = inflater.inflate(R.layout.recycler_view, parent, false);
        return new ContactViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
            Contact currentContact = contacts.get(position);
            if (currentContact!=null) {
                holder.contactLastNameView.setText(currentContact.getLastName());
                holder.contactFirstNameView.setText(currentContact.getFirstName());
                holder.contactMiddleNameView.setText(currentContact.getMiddleName());
                holder.contactAgeView.setText(Integer.toString(currentContact.getAge()));
            }
            else {
                holder.contactLastNameView.setText("No information");
                holder.contactFirstNameView.setText("No information");
                holder.contactMiddleNameView.setText("No information");
                holder.contactAgeView.setText("No information");
            }
    }

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

    class ContactViewHolder extends RecyclerView.ViewHolder {
        private final TextView contactLastNameView;
        private final TextView contactFirstNameView;
        private final TextView contactMiddleNameView;
        private final TextView contactAgeView;

        private ContactViewHolder(View itemView) {
            super(itemView);
            contactLastNameView = itemView.findViewById(R.id.last_name_text_view);
            contactFirstNameView = itemView.findViewById(R.id.first_name_text_view);
            contactMiddleNameView = itemView.findViewById(R.id.middle_name_text_view);
            contactAgeView = itemView.findViewById(R.id.age_text_view);
        }
    }

    @Override
    public int getItemViewType(final int position) {
        return R.layout.recycler_view;
    }
}

My DataBase

@Database(entities = {Contact.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    public abstract ContactDao contactDao();

    private List<Contact> allContacts;

    List<Contact> getAllContacts() {
        return allContacts;
    }

    private static AppDatabase INSTANCE;

    public synchronized static AppDatabase getINSTANCE(Context context) {
            INSTANCE = getDatabase(context);
        return INSTANCE;
    }

    private static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            AppDatabase.class, "table_contacts")
                            .build();
                Log.d("LOG", "Getting the database instance");
            }
        }
        return INSTANCE;
    }
}

There is no doubt in my Entity and Dao classes as it worked perfectly with other variant of database so I don't attach them.
Will be very grateful for any help!

Body:
 AppDatabase.getINSTANCE(ShowDatabaseActivity.this).contactDao().getAll();

This code does not assign data to anything/ variable to hold your data. Assign data to a reference variable  and pass that variable to the adapter so it can show data from it.


问:
gke-security-groups for subdomain
We have some troubles getting the RBAC properly working with the gke-security-groups approach.

We have a verified subdomain in our Gsuite which we want to use for our gke security groups, i.e. security.example.com. The users reside in example.com and are members of the specific groups, e.g. security-gke-developers-team1@security.example.com. The gke-security-groups@security.example.com is used in the cluster creation. However, GKE does not seem to properly lookup the group memberships of the users and no helpful log or error message can be found anywhere.

Does anyone know if this approach can even work or if the gke-security-groups do have to be on the same domain as the users, i.e. gke-security-groups@example.com instead of gke-security-groups@security.example.com?

Any help is highly appreciated.

答: gke-security-groups work fine like outlined above. The issue was the visibility of the groups from the G-Suite as the groups have been defined as internal so that only members and owners can see the members of the group. Changing the view permissions to organization solved the issue.</p>

Title: gke-security-groups for subdomain


问:
Calculating daily averages in pd.Series
I have a Dataframe series with 30s frequency.

```<code>df.head()
</code>```

I want to calculate the daily averages for all signals in that series but it doesnt seem to work. I tried both

```<code>df_average = df.to_period('D')
df.resample('D')
</code>```

And i get:

I want to have only 1 line per day. Why do i get more?
Thank you

答:
If there is DatetimeIndex only add an aggregate function, here mean, to resample:

```<code>df1 = df.resample('D').mean()
</code>```

Title: Calculating daily averages in pd.Series

Body:
I have a Dataframe series with 30s frequency.

df.head()

I want to calculate the daily averages for all signals in that series but it doesnt seem to work. I tried both

df_average = df.to_period('D')
df.resample('D')

And i get:

I want to have only 1 line per day. Why do i get more?
Thank you

Body:
If there is DatetimeIndex only add an aggregate function, here mean, to resample:

df1 = df.resample('D').mean()


问:
Java: overriding equals method doesn't do the trick when looking for a key of hashtable?
I have a hashtable looking like this:

```<code>Hashtable<Mapping, Integer> mappingCount = new Hashtable<Mapping, Integer>();
</code>```

I want to use this code:

```<code>if (mappingCount.get(currentMapping) != null)
    mappingCount.put(currentMapping, mappingCount.get(currentMapping) + 1);
else
    mappingCount.put(currentMapping, 1);
</code>```

In order to be able to get the value from the hashtable, for the class Mapping I did the following:

```<code>@Override
public boolean equals(Object obj) {
    return ((Mapping)obj).mappingXML.equals(this.mappingXML);
}
</code>```

However, this doesn't do the trick since mappingCount.get(currentMapping) always results in null. To be sure that something's not wrong, I did the following:

```<code>if (aaa.contains(currentMapping.getMappingXML()))
    System.out.println("found it!");
else
    aaa.add(currentMapping.getMappingXML());
</code>```

where aaa is List<String> aaa = new ArrayList<String>(). Of course, found it is printed many times. What am I doing wrong?

答:
You also need to override the hashCode() method.

From the JavaDocs:

To successfully store and retrieve
  objects from a hashtable, the objects
  used as keys must implement the
  hashCode method and the equals method.

The reason for this is that Hashtable uses hashCode as a preliminary test to see if two objects are equals. If the hashCode matches, then it uses equals to check for collissions.

The default implementation of hashCode() returns the memory address of the object, and for two objects that are equal, their hashcodes must also be equal.

Also look at the general contract for hashCode().

ContentLicense: CC BY-SA 3.0

Body:
I have a hashtable looking like this:

Hashtable<Mapping, Integer> mappingCount = new Hashtable<Mapping, Integer>();

I want to use this code:

if (mappingCount.get(currentMapping) != null)
    mappingCount.put(currentMapping, mappingCount.get(currentMapping) + 1);
else
    mappingCount.put(currentMapping, 1);

In order to be able to get the value from the hashtable, for the class Mapping I did the following:

@Override
public boolean equals(Object obj) {
    return ((Mapping)obj).mappingXML.equals(this.mappingXML);
}

However, this doesn't do the trick since mappingCount.get(currentMapping) always results in null. To be sure that something's not wrong, I did the following:

if (aaa.contains(currentMapping.getMappingXML()))
    System.out.println("found it!");
else
    aaa.add(currentMapping.getMappingXML());

where aaa is List<String> aaa = new ArrayList<String>(). Of course, found it is printed many times. What am I doing wrong?


问:
Kubernetes Network Policy stops all traffic to Pod
Scenario:

I have Four(4) Pods, Payroll,internal,external,mysql.

I want internal pod to only access:

a. Internal > Payroll on port 8080

b. Internal > mysql on port 3306

Kindly suggest what is missing part? I made the below network policy. But my pod is unable to communicate with 'any' pod.
Hence it has achieved the given target, but practically unable to access other pods. Below are my network policy details.

```<code>master $ k describe netpol/internal-policy
Name:         internal-policy
Namespace:    default
Created on:   2020-02-20 02:15:06 +0000 UTC
Labels:       <none>
Annotations:  <none>
Spec:
  PodSelector:     name=internal
  Allowing ingress traffic:
    <none> (Selected pods are isolated for ingress connectivity)
  Allowing egress traffic:
    To Port: 8080/TCP
    To:
      PodSelector: name=payroll
    ----------
    To Port: 3306/TCP
    To:
      PodSelector: name=mysql
  Policy Types: Egress
</code>```

Policy YAML

```<code>apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: internal-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      name: internal
  policyTypes:
  - Egress
  egress:
  - to:
    - podSelector:
        matchLabels:
          name: payroll
    ports:
      - protocol: TCP
        port: 8080
  - to:
    - podSelector:
        matchLabels:
          name: mysql
    ports:
      - protocol: TCP
        port: 3306 (edited)
</code>```

答:
Hence it has achieved the given target, but practically unable to
  access other pods.

If I understand you correctly you achieved the goal defined in your network policy and all your Pods wearing label name: internal are currently able to communicate both with payroll (on port 8080) and mysql (on port 3306) Pods, right ?

Please correct me if I'm wrong but I see some contradiction in your statement. On the one hand you want your internal Pods to be able to communicate only with very specific set of Pods and connect with them using specified ports:

I want internal pod to only access:

a. Internal > Payroll on port 8080

b. Internal > mysql on port 3306

and on the other, you seem surprised that they can't access any other Pods:

Hence it has achieved the given target, but practically unable to
  access other pods.

Keep in mind that when you apply some NetworkPolicy rule on specific set of Pods, at the same time the dafault deny all rule is implicitly applied on selected Pods (unless you decide to reconfigure the default policy to make it work the way you want).

As you can read here:

Pods become isolated by having a NetworkPolicy that selects them. Once
  there is any NetworkPolicy in a namespace selecting a particular pod,
  that pod will reject any connections that are not allowed by any
  NetworkPolicy. (Other pods in the namespace that are not selected by
  any NetworkPolicy will continue to accept all traffic.)

The above applies also to egress rules.

If currently your internal Pods have access only to payroll and mysql Pod on specified ports, everything works as it is supposed to work.

If you are interested in denying all other traffic to your payroll and mysql Pods, you should apply an ingress rule on those Pods rather than defining egress on Pods which are supposed to communicate with them, but at the same time they should not be deprived of the ability to communicate with other Pods.

Please let me know if it helped. If something is not clear or my assumption was wrong, also please let me know and don't hesitate to ask additional questions.

Body:
Scenario:

I have Four(4) Pods, Payroll,internal,external,mysql.

I want internal pod to only access:

a. Internal > Payroll on port 8080

b. Internal > mysql on port 3306

Kindly suggest what is missing part? I made the below network policy. But my pod is unable to communicate with 'any' pod.
Hence it has achieved the given target, but practically unable to access other pods. Below are my network policy details.

master $ k describe netpol/internal-policy
Name:         internal-policy
Namespace:    default
Created on:   2020-02-20 02:15:06 +0000 UTC
Labels:       <none>
Annotations:  <none>
Spec:
  PodSelector:     name=internal
  Allowing ingress traffic:
    <none> (Selected pods are isolated for ingress connectivity)
  Allowing egress traffic:
    To Port: 8080/TCP
    To:
      PodSelector: name=payroll
    ----------
    To Port: 3306/TCP
    To:
      PodSelector: name=mysql
  Policy Types: Egress

Policy YAML

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: internal-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      name: internal
  policyTypes:
  - Egress
  egress:
  - to:
    - podSelector:
        matchLabels:
          name: payroll
    ports:
      - protocol: TCP
        port: 8080
  - to:
    - podSelector:
        matchLabels:
          name: mysql
    ports:
      - protocol: TCP
        port: 3306 (edited)


问:
How to get access_token from fyers API?
I'm looking to get access_token from fyers API
I'm able to get authorization_code and build authorization_url to open it in browser to enter user credentials. access_token is displayed in browser's address when user enters credentials but my program is unable to retrieve the access_code.
Your help is much appreciable.

My code is as follows:

```<code>from fyers_api import accessToken

from fyers_api import fyersModel
import requests

import webbrowser

import urllib.request as ur

app_id = "XXXXXXXXX"

app_secret = "XXXXXXXXX"

app_session = accessToken.SessionModel(app_id, app_secret)

response = app_session.auth()

if response['code'] != 200:
    print('CODE=' + str(response['code']))
    print('MESSAGE=' + str(response['message']))
    print('Exiting program...')
    exit(0)

authorization_code = response['data']['authorization_code']

app_session.set_token(authorization_code)

authorization_url=app_session.generate_token('XXXXXX')

token = webbrowser.open(authorization_url)
#Following authorization url is opened in browser:
#https://api.fyers.in/api/v1/genrateToken?authorization_code=xxxxxxxxxxxxx&appId=xxxxxxxxx&user_id=xxxxxx

#User is redirected to following url after successful log-in:
#https://trade.fyers.in/?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=&user_id=xxxxxx

print(token)

#token=”your_access_token”

#is_async = False #(By default False, Change to True for asnyc API calls.)

#fyers = fyersModel.FyersModel(is_async)

#fyers. get_profile(token = token)
</code>```

答:
```<code>         from fyers_api import accessToken
         from fyers_api import fyersModel

               app_id = "xxxxxxxxxx"
               app_secret = "xxxxxxxxxx"
               app_session = accessToken.SessionModel(app_id, app_secret)
               response = app_session.auth()
               print(app_session)
               print(response)
               authorization_code = response['data']['authorization_code']

               app_session.set_token(authorization_code)
               gen_token = app_session.generate_token()
               print("token url is copy paste this url in browser and copy access
               token excluding your id at Last  ")
               print(gen_token)
               print("tokent printed thanks")

   token="gAAAAABeTWk7AnufuuQQx0D0NkgABinWk7AnufuuQQx0DQ3ctAFWk7AnufuuQQx0DMQQwacJ-
   _xUVnrTu2Pk5K5QCLF0SZmw7nlpaWk7AnufuuQQx0DG4_3EGCYw92-iAh8="
  is_async = False
  fyers = fyersModel.FyersModel(is_async)
  print(fyers. get_profile(token = token))
  fyers.funds(token = token)
  print(fyers.funds(token = token))
</code>```

Title: How to get access_token from fyers API?

Body:
I'm looking to get access_token from fyers API
I'm able to get authorization_code and build authorization_url to open it in browser to enter user credentials. access_token is displayed in browser's address when user enters credentials but my program is unable to retrieve the access_code.
Your help is much appreciable.

My code is as follows:

from fyers_api import accessToken

from fyers_api import fyersModel
import requests

import webbrowser

import urllib.request as ur

app_id = "XXXXXXXXX"

app_secret = "XXXXXXXXX"

app_session = accessToken.SessionModel(app_id, app_secret)

response = app_session.auth()

if response['code'] != 200:
    print('CODE=' + str(response['code']))
    print('MESSAGE=' + str(response['message']))
    print('Exiting program...')
    exit(0)

authorization_code = response['data']['authorization_code']

app_session.set_token(authorization_code)

authorization_url=app_session.generate_token('XXXXXX')

token = webbrowser.open(authorization_url)
#Following authorization url is opened in browser:
#https://api.fyers.in/api/v1/genrateToken?authorization_code=xxxxxxxxxxxxx&appId=xxxxxxxxx&user_id=xxxxxx

#User is redirected to following url after successful log-in:
#https://trade.fyers.in/?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=&user_id=xxxxxx

print(token)

#token=”your_access_token”

#is_async = False #(By default False, Change to True for asnyc API calls.)

#fyers = fyersModel.FyersModel(is_async)

#fyers. get_profile(token = token)


答:
Here is a solution using pandas library:

```<code>import pandas as pd

new_tablica = []
column_names = ['col1', 'col2', 'col3']

for matrix in tablica:
    df = pd.DataFrame(matrix, columns=column_names)

    df = df[df['col2'] > 0]
    new_tablica.append(df.values.tolist())
</code>```

I haven't tested timings, but this way the solution is easily scalable to large matrices. I recommend you to use the pandas library for managing table-like data, as it has lots of methods more efficient than pure Python.

Title: Delete list from the list matrix - Python

Body:
I created sorted matrix with ID/ Odometers/ Date. I really need to delete all list where 0 value is on the second position.
I prepared a function and loop but unfortunately I have still below error. I doubt that del [] method is used correctly ?

in zero_clear, if tablica[i][1] == 0: ****

tablica = [
            [
            [21091705,  0,'30.06.2019'],
            [21091705,  0,'29.06.2019'],
            [21091705,  653842,'29.06.2019'],
            [21091705,  641701,'28.06.2019'],
            [21091705,  642000,'27.06.2019'],
            [21091705,  0,'25.06.2019'],
            [21091705,  642030,'25.06.2019'],
            [21091705,  642030,'25.06.2019'],
            [21091705,  637030,'25.06.2019'],
            [21091705,  0,'25.06.2019'],
            [21091705,  0,'17.05.2019'],
            [21091705,  641256,'25.06.2019']
            ],
            [
            [21091703,  487000,'30.06.2019'],
            [21091703,  461524,'29.06.2019'],
            [21091703,  0,'29.06.2019'],
            [21091703,  0,'28.06.2019'],
            [21091703,  427701,'28.06.2019'],
            [21091703,  429000,'27.06.2019']
            ],
            [
            [21091701,  421077,'30.06.2019'],
            [21091701,  453777,'29.06.2019'],
            [21091701,  0,'29.06.2019'],
            [21091701,  427701,'28.06.2019'],
            [21091701,  433123,'27.06.2019']
            ],
            [
            [21091704,  491000,'30.06.2019'],
            [21091704,  0,'29.06.2019'],
            [21091704,  474542,'29.06.2019'],
            [21091704,  427701,'28.06.2019'],
            [21091704,  427701,'28.06.2019'],
            [21091704,  0,'27.06.2019']
            ]
            ]

def zero_clear(tablica):

    for i in range(len(tablica)):

        if tablica[i][1] == 0:
            del tablica[i]

    return tablica

for item in tablica:
    zero_clear(item)

Body:
Here is a solution using pandas library:

import pandas as pd

new_tablica = []
column_names = ['col1', 'col2', 'col3']

for matrix in tablica:
    df = pd.DataFrame(matrix, columns=column_names)

    df = df[df['col2'] > 0]
    new_tablica.append(df.values.tolist())

I haven't tested timings, but this way the solution is easily scalable to large matrices. I recommend you to use the pandas library for managing table-like data, as it has lots of methods more efficient than pure Python.


问:
Optimize a nested for loop in Python
I have data stored as key value pairs in a leveldb database. The values are the laser vector embedding of sentences and keys are intents of those sentences. When a new sentence is inputted, I compare the vector embedding of that sentence against the values in the leveldb database in order to identify the intent. Here, I have used a nested for loop and this takes more than 5 seconds to execute. Can someone suggest a way to optimize this loop/ code segment?

expose.py

```<code>import plyvel
from flask import Flask
from flask_restful import Api
from laserembeddings import Laser
from getters.getIntents import *
from getters.getEntities import *

app = Flask(__name__)
api = Api(app)

si_data_vec = plyvel.DB('levelDB/si_data_vec', create_if_missing=False)

path_to_bpe_codes = 'data/laser_models/93langs.fcodes'
path_to_bpe_vocab = 'data/laser_models/93langs.fvocab'
path_to_encoder = 'data/laser_models/bilstm.93langs.2018-12-26.pt'

laser = Laser(path_to_bpe_codes, path_to_bpe_vocab, path_to_encoder)

@app.route('/lang/si/<keylist>', methods=['GET'])
def get_si(keylist):

    intent = get_intents(keylist, si_data_vec, laser)

    return intent

# Initialize and start the web application
if __name__ == "__main__":
    app.run()
</code>```

getIntents.py

This contains the loop to be optimized

```<code>import io
from itertools import combinations
import numpy as np

def get_intents(key_list, si_data_vec, laser):

    avg = laser.embed_sentences([key_list], lang='si')[0]

    minimum_dist = 1
    intent = ''

    ### LOOP TO BE OPTIMIZED
    for key, value in si_data_vec:
        bio = io.BytesIO(value)
        vec = np.load(bio)

        for pair in combinations([avg, vec], 2):
            dist = distance(list(pair[0]), list(pair[1]))
            if dist < minimum_dist:
                minimum_dist = dist
                intent = key.decode()
    return intent

def distance(list1, list2):
    """Distance between two vectors."""
    squares = [(p-q) ** 2 for p, q in zip(list1, list2)]
    return sum(squares) ** .5
</code>```

Updated getIntents.py as per the comment

```<code>import io
import numpy as np

def get_intents(key_list, si_data_vec, laser):

    avg = laser.embed_sentences([key_list], lang='si')[0]

    minimum_dist = 1
    intent = ''
    for key, value in si_data_vec:
        bio = io.BytesIO(value)
        vec = np.load(bio)

        dist = distance(avg, vec)

        if dist < minimum_dist:
            minimum_dist = dist
            intent = key.decode()

    return intent

def distance(list1, list2):
    """Distance between two vectors."""
    squares = [(p-q) ** 2 for p, q in zip(list1, list2)]
    return sum(squares) ** .5
</code>```

答:
The only thing I can think of is using numpy for distance calculation (as you already import numpy anyway); I am not sure if this will give you much speedup though.

```<code>avg = np.array(laser.embed_sentences([key_list], lang='si')[0])
for key, value in si_data_vec:
    bio = io.BytesIO(value)
    vec = np.load(bio)
    dist = np.linalg.norm(avg-vec)
</code>```

See also How can the Euclidean distance be calculated with NumPy?

Title: Optimize a nested for loop in Python

Body:
I have data stored as key value pairs in a leveldb database. The values are the laser vector embedding of sentences and keys are intents of those sentences. When a new sentence is inputted, I compare the vector embedding of that sentence against the values in the leveldb database in order to identify the intent. Here, I have used a nested for loop and this takes more than 5 seconds to execute. Can someone suggest a way to optimize this loop/ code segment?

expose.py

import plyvel
from flask import Flask
from flask_restful import Api
from laserembeddings import Laser
from getters.getIntents import *
from getters.getEntities import *

app = Flask(__name__)
api = Api(app)

si_data_vec = plyvel.DB('levelDB/si_data_vec', create_if_missing=False)

path_to_bpe_codes = 'data/laser_models/93langs.fcodes'
path_to_bpe_vocab = 'data/laser_models/93langs.fvocab'
path_to_encoder = 'data/laser_models/bilstm.93langs.2018-12-26.pt'

laser = Laser(path_to_bpe_codes, path_to_bpe_vocab, path_to_encoder)

@app.route('/lang/si/<keylist>', methods=['GET'])
def get_si(keylist):

    intent = get_intents(keylist, si_data_vec, laser)

    return intent

# Initialize and start the web application
if __name__ == "__main__":
    app.run()

getIntents.py

This contains the loop to be optimized

import io
from itertools import combinations
import numpy as np

def get_intents(key_list, si_data_vec, laser):

    avg = laser.embed_sentences([key_list], lang='si')[0]

    minimum_dist = 1
    intent = ''

    ### LOOP TO BE OPTIMIZED
    for key, value in si_data_vec:
        bio = io.BytesIO(value)
        vec = np.load(bio)

        for pair in combinations([avg, vec], 2):
            dist = distance(list(pair[0]), list(pair[1]))
            if dist < minimum_dist:
                minimum_dist = dist
                intent = key.decode()
    return intent

def distance(list1, list2):
    """Distance between two vectors."""
    squares = [(p-q) ** 2 for p, q in zip(list1, list2)]
    return sum(squares) ** .5

Updated getIntents.py as per the comment

import io
import numpy as np

def get_intents(key_list, si_data_vec, laser):

    avg = laser.embed_sentences([key_list], lang='si')[0]

    minimum_dist = 1
    intent = ''
    for key, value in si_data_vec:
        bio = io.BytesIO(value)
        vec = np.load(bio)

        dist = distance(avg, vec)

        if dist < minimum_dist:
            minimum_dist = dist
            intent = key.decode()

    return intent

def distance(list1, list2):
    """Distance between two vectors."""
    squares = [(p-q) ** 2 for p, q in zip(list1, list2)]
    return sum(squares) ** .5

Body:
The only thing I can think of is using numpy for distance calculation (as you already import numpy anyway); I am not sure if this will give you much speedup though.

avg = np.array(laser.embed_sentences([key_list], lang='si')[0])
for key, value in si_data_vec:
    bio = io.BytesIO(value)
    vec = np.load(bio)
    dist = np.linalg.norm(avg-vec)

See also How can the Euclidean distance be calculated with NumPy?


问:
Decode RTP iLBC payload
I want to decode iLBC audio data from RTP payload using c++? I can extract payload data but I don't know how to decode an iLBC frame. How to do that? Is there any reliable library?</p>

答:
you can also explore pjmedia ilbc codec.

https://www.pjsip.org/pjmedia/docs/html/group__PJMED__ILBC.htm#details

https://github.com/jfigus/PJSIP/blob/master/pjproject-2.1.0/pjmedia/src/pjmedia-codec/ilbc.c

Title: Decode RTP iLBC payload


问:
What does [0, 1) mean in Python?
I sometimes see this [0, 1) arrangement of square and round parentheses, but haven't been able to find anywhere that tells what it means. It isn't easily Googlable!

There is an example on this page https://www.tensorflow.org/api_docs/python/tf/random/uniform :

For floats, the default range is [0, 1)

Is it a programming construct? Something else?

Thanks.

答:
You'll find the answer right above where you found the source of your question:

The lower bound minval is included in the range, while the upper bound maxval is excluded.

Title: What does [0, 1) mean in Python?


答: Whenever you override equals, you must override hashCode as well.

Title: Java: overriding equals method doesn't do the trick when looking for a key of hashtable?


问:
Why does nothing changed to open a program in windows while using the assoc command to alter the specific extension to another different?
I use the windows 10 pro version and open the command prompt as the administrator to run the windows commands in my laptop. Using the assoc command to change the file extension file to another different (e.g. assoc .jpg=txtfile), I find nothing changed after running it and still that jpeg file opens with the regular program instead of notepad. In addition I can see the only change in by typing just the assoc and running it when a list of extensions belonging to different programs appears. Fo instance I have changed the .jpg file to txt file that it shows only as '.jpg=txtfile" in the list but tyat is still opened in jpeg program not notpad? Is anyone here to help me with clearly. Thanks</p>

答:
You need to use ftype as well. I have a link saved to MS docs that says it is up-to-date till Win8: https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/cc771394(v=ws.11).

Maybe nothing has changed in Win10, but you get the idea from the above and can Google it for Win10.


问:
DataTables - Reduce column a little?
I use DataTables and would like to reduce the columns a bit.

I use the following code for this.

```<code>$('#example').dataTable( {
  "columnDefs": [
    { "width": "29px", "targets": 0 }
  ]
});
</code>```

When I then check the number of pixels in the developer tools in Chrome, significantly more pixels appear and I still have too much space between the last letter of the column name and the arrow for sorting. See screenshot.

I just want to reduce the space between the last letter of the label and the arrow for sorting the records a bit. Example

答:
I have not tried this solution but maybe it's working. We need to define width of table with this option.
Datatable configutation :

```<code>$('#example').dataTable( {
    "autoWidth": false
} );
</code>```

Css :

```<code>table {
  margin: 0 auto;
  width: 100%;
  clear: both;
  border-collapse: collapse;
  table-layout: fixed; // ***********add this
  word-wrap:break-word; // ***********and this
}
</code>```

OR

You can try from this link: https://datatables.net/extensions/fixedcolumns/examples/initialisation/size_fixed.html

Title: DataTables - Reduce column a little?

Body:
I use DataTables and would like to reduce the columns a bit.

I use the following code for this.

$('#example').dataTable( {
  "columnDefs": [
    { "width": "29px", "targets": 0 }
  ]
});

When I then check the number of pixels in the developer tools in Chrome, significantly more pixels appear and I still have too much space between the last letter of the column name and the arrow for sorting. See screenshot.

I just want to reduce the space between the last letter of the label and the arrow for sorting the records a bit. Example

Body:
I have not tried this solution but maybe it's working. We need to define width of table with this option.
Datatable configutation :

$('#example').dataTable( {
    "autoWidth": false
} );

Css :

table {
  margin: 0 auto;
  width: 100%;
  clear: both;
  border-collapse: collapse;
  table-layout: fixed; // ***********add this
  word-wrap:break-word; // ***********and this
}

OR

You can try from this link: https://datatables.net/extensions/fixedcolumns/examples/initialisation/size_fixed.html


问:
PWA Service worker notification click
i'm trying do show a notification and do something when it's clicked.

```<code>    try {
    navigator.serviceWorker.getRegistration()
        .then(reg => {
            reg.showNotification("Guarda il videoclip!", {
                body: "clicca qua!",
                icon: "images/she_is_fire.png",
                vibrate: [100, 50, 100],
                tag: 'sample',
                actions: [{ action: 'explore', title: 'Guarda', icon: 'images/she_is_fire.png' }],
            });
            self.addEventListener('notificationclick', function(event) {
                event.notification.close();
                window.open("https://youtu.be/PAvHeRGZ_lA");
            }, false);
        })
        .catch(err => alert('Service Worker registration error: ' + err));

} catch (err) {
    alert('Notification API error: ' + err);
}
</code>```

I added the eventlistener but it never gets fired.

What am i doing wrong?

答: Always remember, after adding code (refer answer ) in service-worker.js , restart your browser to reflect the changes. I was making change and not restarting browser window , got me frustrated !</p>

Title: PWA Service worker notification click

Body:
i'm trying do show a notification and do something when it's clicked.

    try {
    navigator.serviceWorker.getRegistration()
        .then(reg => {
            reg.showNotification("Guarda il videoclip!", {
                body: "clicca qua!",
                icon: "images/she_is_fire.png",
                vibrate: [100, 50, 100],
                tag: 'sample',
                actions: [{ action: 'explore', title: 'Guarda', icon: 'images/she_is_fire.png' }],
            });
            self.addEventListener('notificationclick', function(event) {
                event.notification.close();
                window.open("https://youtu.be/PAvHeRGZ_lA");
            }, false);
        })
        .catch(err => alert('Service Worker registration error: ' + err));

} catch (err) {
    alert('Notification API error: ' + err);
}

I added the eventlistener but it never gets fired.

What am i doing wrong?


Body:
I thing that something went wrong because after your change of the matrix, when I use simple for loops, to see the output it should be like this ( without lists with 0 on second position) :

    for ele in tablica:
        for item in ele:
            print(item)

[21091705, 653842, '29.06.2019']
[21091705, 641701, '28.06.2019']
[21091705, 642000, '27.06.2019']
[21091705, 642030, '25.06.2019']
[21091705, 642030, '25.06.2019']
[21091705, 637030, '25.06.2019']
[21091705, 641256, '25.06.2019']
[21091703, 487000, '30.06.2019']
[21091703, 461524, '29.06.2019']
[21091703, 427701, '28.06.2019']
[21091703, 429000, '27.06.2019']
[21091701, 421077, '30.06.2019']
[21091701, 453777, '29.06.2019']
[21091701, 427701, '28.06.2019']
[21091701, 433123, '27.06.2019']
[21091704, 491000, '30.06.2019']
[21091704, 474542, '29.06.2019']
[21091704, 427701, '28.06.2019']
[21091704, 427701, '28.06.2019']

When I use this loops to see the output after your change of the matrix the output is much more complicated:

tablica = [[[row for i in range(len(item))] for row in item if row[1] != 0] for item in tablica]

Output of:

for ele in tablica:
      for item in ele:
                print(item)

[[21091705, 653842, '29.06.2019'], [21091705, 653842, '29.06.2019'], [21091705, 653842, '29.06.2019'], [21091705, 653842, '29.06.2019'], [21091705, 653842, '29.06.2019'], [21091705, 653842, '29.06.2019'], [21091705, 653842, '29.06.2019'], [21091705, 653842, '29.06.2019'], [21091705, 653842, '29.06.2019'], [21091705, 653842, '29.06.2019'], [21091705, 653842, '29.06.2019'], [21091705, 653842, '29.06.2019']]
[[21091705, 641701, '28.06.2019'], [21091705, 641701, '28.06.2019'], [21091705, 641701, '28.06.2019'], [21091705, 641701, '28.06.2019'], [21091705, 641701, '28.06.2019'], [21091705, 641701, '28.06.2019'], [21091705, 641701, '28.06.2019'], [21091705, 641701, '28.06.2019'], [21091705, 641701, '28.06.2019'], [21091705, 641701, '28.06.2019'], [21091705, 641701, '28.06.2019'], [21091705, 641701, '28.06.2019']]
[[21091705, 642000, '27.06.2019'], [21091705, 642000, '27.06.2019'], [21091705, 642000, '27.06.2019'], [21091705, 642000, '27.06.2019'], [21091705, 642000, '27.06.2019'], [21091705, 642000, '27.06.2019'], [21091705, 642000, '27.06.2019'], [21091705, 642000, '27.06.2019'], [21091705, 642000, '27.06.2019'], [21091705, 642000, '27.06.2019'], [21091705, 642000, '27.06.2019'], [21091705, 642000, '27.06.2019']]


答:
Looks to me that you're more looking for the vas_pricing than the vas. So I'd recommend you make the query on vas_pricing instead:

```<code>let options = {
  where: {
    tenant: 'brand_1',
    vas_id: 'promo_summer_2019_10GB'
  },
  include: [
    {
      model: vas,
      required: false
    }
  ]
};

vas_pricing.findAll(options)
.then(function(data) {
    console.log(JSON.stringify(data, null, 2))
})
.catch(function(error) {
    console.error(error);
});
</code>```

Title: Problems with "includes" using Sequelize when a composite foreign key is used

Body:
Here is a sample of my main table:

+-------------+------------------------+--------------------+
| tenant      | vas_id                 | friendly_name      |
+-------------+------------------------+--------------------+
| brand_1     | 1gb_data_zone1         | 1GB Data in Zone 1 |
| brand_1     | promo_summer_2019_10GB | 10GB for Summer    |
| brand_1     | roaming_prepaid        | Roaming            |
| brand_1     | voicemail_prepaid      | Voicemail          |
| brand_2     | test_vas               | Test               |
| brand_2     | roaming_prepaid        | Roaming            |
| brand_2     | voicemail_prepaid      | Voicemail          |
+-------------+------------------------+--------------------+

tenant and vas_id are the two primary keys (a.k.a. composite primary keys) in this table, and they are used together as constain to another table, 1:N relationship:

+---------+------------------------+-----------------+-------------------+-------------------+
| tenant  | vas_id                 | activation_cost | deactivation_cost | modification_cost |
+---------+------------------------+-----------------+-------------------+-------------------+
| brand_1 | 1gb_data_zone1         |            2000 |                 0 |                 0 |
| brand_1 | promo_summer_2019_10GB |               0 |                 0 |                 0 |
| brand_1 | roaming_prepaid        |               0 |                 0 |                 0 |
| brand_1 | voicemail_prepaid      |               0 |                 0 |                 0 |
| brand_2 | test_vas               |               0 |                 0 |                 0 |
| brand_2 | roaming_prepaid        |               0 |                 0 |                 0 |
| brand_2 | voicemail_prepaid      |               0 |                 0 |                 0 |
+---------+------------------------+-----------------+-------------------+-------------------

Would you say that this structure can get along with Sequelize?

Here is the code that I use to mark the two primary keys:

const vas = serviceLayerDB.define('vas',
    { // Database columns:
        tenant: {
            type: Sequelize.STRING(45),
            primaryKey: true
        },
        vas_id: {
            type: Sequelize.STRING(100),
            primaryKey: true
        }
        friendly_name: {
            type: Sequelize.STRING(100)
        }
    }

const vas_pricing = serviceLayerDB.define('vas_pricing',
    { // Database columns:
        tenant: {
            type: Sequelize.STRING(45),
            primaryKey: true
        },
        vas_id: {
            type: Sequelize.STRING(100),
            primaryKey: true
        },
        activation_cost: {
            type: Sequelize.NUMBER
        },
        deactivation_cost: {
            type: Sequelize.NUMBER
        },
        modification_cost: {
            type: Sequelize.NUMBER
        }
    });

...and this is the code that I use to relate the table above with another table (vas_pricing):

vas.hasOne(vas_pricing, { foreignKey: 'vas_id' });
vas.hasOne(vas_pricing, { foreignKey: 'tenant' });

Strange things happen, for example, while executing the following code that finds on the main table AND also in the child table:

let options = {
    where: {
        tenant: 'brand_1',
        vas_id: 'promo_summer_2019_10GB'
    },
    include: [
        {
            model: vas_pricing,
            required: false
        }
    ]
};
vas.findAll(options)
    .then(function(data) {
        console.log(JSON.stringify(data, null, 2))
    })
    .catch(function(error) {
        console.error(error);
    });

Result:

[
    {
        "tenant": "brand_1",
        "vas_id": "promo_summer_2019_10GB",
        "friendly_name": "10GB During Summer",
        "vas_pricing": {
            "tenant": "brand_1",
            "vas_id": "1gb_data_zone1",
            "activation_cost": 20,
            "deactivation_cost": 0,
            "modification_cost": 0
        }
    },
    {
        "tenant": "brand_1",
        "vas_id": "promo_summer_2019_10GB",
        "friendly_name": "10GB During Summer",
        "vas_pricing": {
            "tenant": "brand_1",
            "vas_id": "promo_summer_2019_10GB",
            "activation_cost": 0,
            "deactivation_cost": 0,
            "modification_cost": 0
        }
    },
    {
        "tenant": "brand_1",
        "vas_id": "promo_summer_2019_10GB",
        "friendly_name": "10GB During Summer",
        "vas_pricing": {
            "tenant": "brand_1",
            "vas_id": "roaming_prepaid",
            "activation_cost": 0,
            "deactivation_cost": 0,
            "modification_cost": 0
        }
    },
    {
        "tenant": "brand_1",
        "vas_id": "promo_summer_2019_10GB",
        "friendly_name": "10GB During Summer",
        "vas_pricing": {
            "tenant": "brand_1",
            "vas_id": "voicemail_prepaid",
            "activation_cost": 0,
            "deactivation_cost": 0,
            "modification_cost": 0
        }
    }
]

Expected result:

[
    {
        "tenant": "brand_1",
        "vas_id": "promo_summer_2019_10GB",
        "friendly_name": "10GB During Summer",
        "vas_pricing": {
            "tenant": "brand_1",
            "vas_id": "promo_summer_2019_10GB",
            "activation_cost": 0,
            "deactivation_cost": 0,
            "modification_cost": 0
        }
    }
]

I have been banging my head for days looking for a solution without success. Any ideas?

Body:
Looks to me that you're more looking for the vas_pricing than the vas. So I'd recommend you make the query on vas_pricing instead:

let options = {
  where: {
    tenant: 'brand_1',
    vas_id: 'promo_summer_2019_10GB'
  },
  include: [
    {
      model: vas,
      required: false
    }
  ]
};

vas_pricing.findAll(options)
.then(function(data) {
    console.log(JSON.stringify(data, null, 2))
})
.catch(function(error) {
    console.error(error);
});


问:
Absolute/outer and inner namespace confusion in C#
```<code>using Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = Foo.Uber.Bar();
        }
    }
}
</code>```

How could I solve this? Just moving the using statement inside my namespace doesn't help.

答:
You can actually specify the full path via the root namespace

```<code>var x = global::Foo.Uber.Bar();
</code>```

Namespaces Overview

A namespace has the following
  properties:

They organize large code projects.

They are delimited with the . operator.

The using directive means you do not need to specify the name of the
  namespace for every class.

The global namespace is the "root" namespace: global::system
  will always refer to the .NET
  Framework namespace System.

I prefer this over aliases because when you read it, you know exactly what is going on. Aliases can be easy to misunderstand if you skip over the definition.

Body:
using Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = Foo.Uber.Bar();
        }
    }
}

How could I solve this? Just moving the using statement inside my namespace doesn't help.

Body:
You can actually specify the full path via the root namespace

var x = global::Foo.Uber.Bar();

Namespaces Overview

A namespace has the following
  properties:

They organize large code projects.

They are delimited with the . operator.

The using directive means you do not need to specify the name of the
  namespace for every class.

The global namespace is the "root" namespace: global::system
  will always refer to the .NET
  Framework namespace System.

I prefer this over aliases because when you read it, you know exactly what is going on. Aliases can be easy to misunderstand if you skip over the definition.


问:
swift: auto logout after certain time
I am developing an app which is connected to a server through .net api.

What user logs in it generate an access token which is used to make network calls.

Requirement: After 20 mins of the generation of that access token, the
  token gets expired and the user have to log in again to continue using
  the app.

How can I achieve this feature that after 20 min the user will get logout from app and redirected to the home page.

If the user is using app even after 20 min from login? how to save the access token in app and remove it once user logout.

I have seen a couple of answers in Objective c but I want the answer in swift.

答:
Welcome to stack overflow

Short Answer

Create a timer in app delegate to track the token expiry. And reset timer when needed.

Long Answer TLDR;

To implement the feature as you have explained we need to

Keep track of access token expiry in app delegate only.

Start a timer for 20 mins when user logs in from AppDelegate.

Before making any API Calls access the token from app delegate (Internally you can save in any secure method for example KeyChain),

While accessing token from app Delegate check if timer is expired. If so present your login screen in the window.

If not present then make API Call and let the user do the tasks.

Advantage of this method

If you are sure that access token will expire in 20mins then without making any API calls we can logout the user from app.

Title: swift: auto logout after certain time


问:
Executing command using SSH.NET on digi 6030dx modem - what are this character sequences starting with left square bracket?
I have some large project that connect to many devices over SSH.NET

Now I have to add support for new modem witch is digi 6030dx.

I added it and I am able to connect with no issues

But when I send some/any command like show config the output is:

[16C[0K
[16C[0Ks
[17C[0Kh
[18C[0Ko
[19C[0Kw
[20C[0K
[20C[0Kc
[21C[0Ko
[22C[0Kn
[23C[0Kf
[24C[0Ki
[25C[0Kg

Commands
-------------------------------------------------------------------------------
config      View and modify the configuration
exit        Exit the CLI
analyzer    Analyzer commands.
cli-legacy  Enter the legacy Admin CLI.
cp          Copy a file or directory.
help        Show CLI editing and navigation commands.
ls          List a directory.
mkdir       Create a directory.
modem       Modem commands.
more        View a file.
mv          Move a file or directory.
ping        Ping a host.
reboot      Reboot the system.
rm          Remove a file or directory.
scp         Copy a file or directory over SSH.
show        Show instance statistics.
system      System commands.
traceroute  Print the route packets trace to network host.
update      Update firmware.

dra.wk.0001> ashowconfigdra.wk.0001> ashowconfig
[16C[0K
```

Does anyone known what are this strange signs / why my command is splited by this and newlines?
It is first device that have this issue and the app support over 200 other with no issues.

I guess some coding issue or something ? putty does not show this signs so probably 'understand' them somehow?

答:
Those are ANSI escape codes.

In general, with SSH, you get these only if your client (library) declares support for terminal emulation.

SSH.NET library does that always, when you use the "shell" channel (SshClient.CreateShell or SshClient.CreateShellStream).

In general (were you connecting to well behaving SSH server), to avoid getting the codes:

Use "exec" channel (use SshClient.RunCommand). SSH.NET does not use terminal emulation on "exec" channel. Though SSH servers on "devices" (contrary to full servers) usually do not implement the "exec" channel. See also What is the difference between exec_command and send with invoke_shell() on Paramiko?

Modify SSH.NET code not to request terminal emulation for the "shell" channel. – Remove SendPseudoTerminalRequest request from Shell.Start implementation.

Though as you are connecting to some "device" and telneting further to another device and the codes probably come from the far device, the question is whether this will in fact have any effect on that device at all. Possibly you won't be able to avoid getting the codes. Lack of terminal emulation on the first SSH connection possibly won't have any effect on the second telnet connection.

In the end, you may have to deal with the codes.

See also How to strip ANSI escape codes from AIX topas command result in C#.

Body:
I have some large project that connect to many devices over SSH.NET

Now I have to add support for new modem witch is digi 6030dx.

I added it and I am able to connect with no issues

But when I send some/any command like show config the output is:

[16C[0K
[16C[0Ks
[17C[0Kh
[18C[0Ko
[19C[0Kw
[20C[0K
[20C[0Kc
[21C[0Ko
[22C[0Kn
[23C[0Kf
[24C[0Ki
[25C[0Kg

Commands
-------------------------------------------------------------------------------
config      View and modify the configuration
exit        Exit the CLI
analyzer    Analyzer commands.
cli-legacy  Enter the legacy Admin CLI.
cp          Copy a file or directory.
help        Show CLI editing and navigation commands.
ls          List a directory.
mkdir       Create a directory.
modem       Modem commands.
more        View a file.
mv          Move a file or directory.
ping        Ping a host.
reboot      Reboot the system.
rm          Remove a file or directory.
scp         Copy a file or directory over SSH.
show        Show instance statistics.
system      System commands.
traceroute  Print the route packets trace to network host.
update      Update firmware.

dra.wk.0001> ashowconfigdra.wk.0001> ashowconfig
[16C[0K

Does anyone known what are this strange signs / why my command is splited by this and newlines?
It is first device that have this issue and the app support over 200 other with no issues.

I guess some coding issue or something ? putty does not show this signs so probably 'understand' them somehow?


答: It is a mathematical notation for an "open range" or "half closed interval". The notation has no use in common programming languages, including Python. In this case, it means "all the representable numbers between 0 and 1, excluding 1".</p>

Title: What does [0, 1) mean in Python?

Body:
I sometimes see this [0, 1) arrangement of square and round parentheses, but haven't been able to find anywhere that tells what it means. It isn't easily Googlable!

There is an example on this page https://www.tensorflow.org/api_docs/python/tf/random/uniform :

For floats, the default range is [0, 1)

Is it a programming construct? Something else?

Thanks.


问:
My Android HTML application is losing values stored in localStorage when it shuts down. Anyone else see this issue?
I have a native Android 2.1 application that hosts a web view.  I load up a site that contains javascript that uses the LocalStorage feature.  When the application is running localStorage works fine.  When some users exit the application and restart it, all the values are gone.  I'm not seeing this problem in my Motrola Droid or Sprint EVO, but there is a report of users in the field with this issue.

Does anyone know what I am missing?  I'm setting the following flag to true.

```<code>settings.setDomStorageEnabled(true);
</code>```

答:
To make the local storage work for your own WebView in Android, you need to make sure the WebView is using the correct file, and the local storage is enabled like this:

```<code>String packageName = "com.dongshengcn.android";
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDatabaseEnabled(true);
settings.setDatabasePath("/data/data/"+packageName+"/databases");
settings.setDomStorageEnabled(true);
</code>```

Where "com.dongshengcn.android" should be replaced with your own android app pacakge name.

ContentLicense: CC BY-SA 2.5

Body:
I have a native Android 2.1 application that hosts a web view.  I load up a site that contains javascript that uses the LocalStorage feature.  When the application is running localStorage works fine.  When some users exit the application and restart it, all the values are gone.  I'm not seeing this problem in my Motrola Droid or Sprint EVO, but there is a report of users in the field with this issue.

Does anyone know what I am missing?  I'm setting the following flag to true.

settings.setDomStorageEnabled(true);

Body:
To make the local storage work for your own WebView in Android, you need to make sure the WebView is using the correct file, and the local storage is enabled like this:

String packageName = "com.dongshengcn.android";
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDatabaseEnabled(true);
settings.setDatabasePath("/data/data/"+packageName+"/databases");
settings.setDomStorageEnabled(true);

Where "com.dongshengcn.android" should be replaced with your own android app pacakge name.


问:
what is the significance of 'retry' and 'every' config parameters in Dancer2::Plugin::Redis
I am using Dancer2::Plugin::Redis plugin to handle the Redis connections.

In order to provide the required configuration parameters, the documentation gives the following sample.

```<code>plugins:
  Redis:
    # if you use TCP/IP:
    server: "localhost:6379"
    # if you use UNIX/Linux sockets:
    sock: "/path/to/sock"
    # (optional) Redis password used with auth:
    password: "Very secure password 123!"
    # (optional) Reconnect up to 60 seconds (reconnect) every 5000 milliseconds (every):
    reconnect: 60
    every: 5000
    # (optional) Redis connection name (NOT the Redis database ID):
    name: "my_connection_name"
    # (optional) Function called on Redis connect:
    on_connect: "MyDancer2App::redis_on_connect"
    # (optional) Use serialization for storing values other than simple scalars with Redis:
</code>```

How does the reconnect and every parameters work together?

Is it like connection will be alive for 60 seconds and it refreshes every 5 sec? If so, it does not make any sense.

答:
From https://metacpan.org/pod/Redis#reconnect,-every

The reconnect option enables auto-reconnection mode. If we cannot
  connect to the Redis server, or if a network write fails, we enter
  retry mode. We will try a new connection every every microseconds (1
  ms by default), up-to reconnect seconds.

Be aware that read errors will always thrown an exception, and will
  not trigger a retry until the new command is sent.

If we cannot re-establish a connection after reconnect seconds, an
  exception will be thrown.

Body:
I am using Dancer2::Plugin::Redis plugin to handle the Redis connections.

In order to provide the required configuration parameters, the documentation gives the following sample.

plugins:
  Redis:
    # if you use TCP/IP:
    server: "localhost:6379"
    # if you use UNIX/Linux sockets:
    sock: "/path/to/sock"
    # (optional) Redis password used with auth:
    password: "Very secure password 123!"
    # (optional) Reconnect up to 60 seconds (reconnect) every 5000 milliseconds (every):
    reconnect: 60
    every: 5000
    # (optional) Redis connection name (NOT the Redis database ID):
    name: "my_connection_name"
    # (optional) Function called on Redis connect:
    on_connect: "MyDancer2App::redis_on_connect"
    # (optional) Use serialization for storing values other than simple scalars with Redis:

How does the reconnect and every parameters work together?

Is it like connection will be alive for 60 seconds and it refreshes every 5 sec? If so, it does not make any sense.


问:
Console.log of function returning object
So I have a function which is returning an object which has an object as value. I need to console.log the result of the function, however what I get is this:

```<code> testedDatalayer: {
    event: 'mkt_pageInformation',
    eventDetails: { page: [Object], pagePath: '/' }
  }
</code>```

I need to display the value as normal instead of [Object]. I know I can stringify it, however I really want to keep it as an object rather then string and make it look like this:

```<code> expectedDataLayer: {
    event: 'mkt_pageInformation',
    page: { type: 'xxx', category: 'xxxx' },
    pagePath: 'xxxxx'
  },
</code>```

Is there any way of keeping that structure and console logging the function without the need of strinfigy?

EDIT: doing it on node.js and logging to cmd

答:
If you're using Node, you could try using util.inspect:

```<code>const inspect = require('util').inspect;
console.log(inspect(yourObject,{depth: Infinity}));
</code>```

For more info you could check the nodejs docs for it at:

https://nodejs.org/api/util.html#util_util_inspect_object_options

Body:
So I have a function which is returning an object which has an object as value. I need to console.log the result of the function, however what I get is this:

 testedDatalayer: {
    event: 'mkt_pageInformation',
    eventDetails: { page: [Object], pagePath: '/' }
  }

I need to display the value as normal instead of [Object]. I know I can stringify it, however I really want to keep it as an object rather then string and make it look like this:

 expectedDataLayer: {
    event: 'mkt_pageInformation',
    page: { type: 'xxx', category: 'xxxx' },
    pagePath: 'xxxxx'
  },

Is there any way of keeping that structure and console logging the function without the need of strinfigy?

EDIT: doing it on node.js and logging to cmd

Body:
If you're using Node, you could try using util.inspect:

const inspect = require('util').inspect;
console.log(inspect(yourObject,{depth: Infinity}));

For more info you could check the nodejs docs for it at:

https://nodejs.org/api/util.html#util_util_inspect_object_options


问:
Flutter - ListView inside on a TabBarView loses its scroll position
I have a very simple Flutter app with a TabBarView with two views (Tab 1 and Tab 2), one of them (Tab 1) has a ListView with many simple Text Widgets, the problem with this is that after I scroll down the ListView elements of Tab 1, if I swipe from Tab 1 to Tab 2 and finally I swipe from
Tab 2 to Tab 1, the previous scroll position in the ListView of Tab 1 get lost.

Here is the code:

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  late TabController controller;

  @override
  void initState() {
    super.initState();
    controller = TabController(
      length: 2,
      vsync: this,
    );
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var tabs = const <Tab>[
      Tab(icon: Icon(Icons.home), text: 'Tab 1'),
      Tab(icon: Icon(Icons.account_box), text: 'Tab 2')
    ];

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: TabBarView(controller: controller, children: <Widget>[
        ListView(children: <Widget>[
          Column(children: <Widget>[
            for (int i = 0; i < 48; i++) Text('Data $i'),
          ])
        ]),
        const Center(child: Text('Tab 2'))
      ]),
      bottomNavigationBar: Material(
        color: Colors.deepOrange,
        child: TabBar(controller: controller, tabs: tabs),
      ),
    );
  }
}
</code>```

I have even separated the TabBarView childrens (Tab 1 and Tab 2) in another classes and I have noticed that the

```<code>@override
  Widget build(BuildContext context) {
  ...
}
</code>```

method of each child (Tab 1 and Tab 2) is executed every time I swipe to its container tab.

My questions are:

1.- How can I keep the scroll of the ListView even if I move from tab to tab?

2.- Is there a way to execute the

```<code>@override
Widget build(BuildContext context) {

}
</code>```

method only once if I separate the TabBarView childrens (Tab 1 and Tab 2) to another classes?
I mean, if I have to retrieve data when the Tab 1 and Tab 2 are created I don't want to do this every time its Tab is swiped in. That would be expensive.

3.- In general, Is there a way to prevent that a tab view (including its variables, data, etc.) be rebuilt every time I swipe to that tab?

Thank you in advance.

答:
Can't add a comment, so left it as answer.

If you using PageStorageKey, have a lot of items in the ListView, scroll down plenty items and have lag on tab switch, the solution is to provide itemExtent to ListView.

As I understand, without itemExtent ListView don't know which items immediately show, because using PageStorageKey cashed only position in pixels, and ListView need calculate height of all items scrolled from top. In another hand, with itemExtent ListView can easily calculate item to show, for example: index = cashedPositionInPixels / itemExtent.

Body:
I have a very simple Flutter app with a TabBarView with two views (Tab 1 and Tab 2), one of them (Tab 1) has a ListView with many simple Text Widgets, the problem with this is that after I scroll down the ListView elements of Tab 1, if I swipe from Tab 1 to Tab 2 and finally I swipe from
Tab 2 to Tab 1, the previous scroll position in the ListView of Tab 1 get lost.

Here is the code:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  late TabController controller;

  @override
  void initState() {
    super.initState();
    controller = TabController(
      length: 2,
      vsync: this,
    );
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var tabs = const <Tab>[
      Tab(icon: Icon(Icons.home), text: 'Tab 1'),
      Tab(icon: Icon(Icons.account_box), text: 'Tab 2')
    ];

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: TabBarView(controller: controller, children: <Widget>[
        ListView(children: <Widget>[
          Column(children: <Widget>[
            for (int i = 0; i < 48; i++) Text('Data $i'),
          ])
        ]),
        const Center(child: Text('Tab 2'))
      ]),
      bottomNavigationBar: Material(
        color: Colors.deepOrange,
        child: TabBar(controller: controller, tabs: tabs),
      ),
    );
  }
}

I have even separated the TabBarView childrens (Tab 1 and Tab 2) in another classes and I have noticed that the

@override
  Widget build(BuildContext context) {
  ...
}

method of each child (Tab 1 and Tab 2) is executed every time I swipe to its container tab.

My questions are:

1.- How can I keep the scroll of the ListView even if I move from tab to tab?

2.- Is there a way to execute the

@override
Widget build(BuildContext context) {

}

method only once if I separate the TabBarView childrens (Tab 1 and Tab 2) to another classes?
I mean, if I have to retrieve data when the Tab 1 and Tab 2 are created I don't want to do this every time its Tab is swiped in. That would be expensive.

3.- In general, Is there a way to prevent that a tab view (including its variables, data, etc.) be rebuilt every time I swipe to that tab?

Thank you in advance.


问:
What can I use as a XACML PDP?
I have an API REST made in node js, and now I'd like to implement some XACML policy. I have been searching and I found that I can use ALFA to make the XACML rules. But I need a PDP for applying the rules. What can I use / how can I implement it?

I have read about WSO2 Identity Server (which I think I can use as a PDP? I'm not sure). It is probably too much for a little project. Any other suggestions? Or is WSO2 IS adecuate?

答:
Yes, you can use Wso2 Identity Server as your PDP. Once I had a requirement to secure a Spring Boot rest API through XACML[1]. Anyway, It would be much easier for you to use the Identity Server PDP than implementing one. You have easy beginner samples that you can try out for your use case.[2] There are tools in the identity server that you can use to create the XACML rules.

[1].https://medium.com/@buddhimau/role-based-authorization-for-spring-boot-using-wso2-identity-server-3d74ab307fb9

[2].https://medium.com/@gdrdabarera/how-entitlement-management-works-with-rest-api-via-xacml-in-wso2-identity-server-5-3-0-7a60940d040c

Title: What can I use as a XACML PDP?


问:
How can i get non repeated date values grails with <g:select >tag
I have an option for selecting a date from a drop-down with <g:select>.  How can I get non-repeated date values through this?  This is the code to get date in the specified format from the domain class.

dob is of type Date.

```<code><g:set var="dateFormat" value="MM/dd/yyyy"/>
<g:select id="dob" name="dob" from="${Person.list().dob*.format(dateFormat)}"
    value="${personInstance?.dob?.format(dateFormat)}" />
</code>```

答:
If "Colony" is a grails domain class, then you can alter your query to retrieve distinct values. You didn't provide details, but let's say your domain class is called "Colony" and it has a property called "name", which for some reason you haven't made a unique constraint. Then you can do the following:

```<code>//add this method to Colony.groovy
public static List listUnique() {
    Colony.withCriteria {
        projections {
            distinct "name"
        }
    }.sort()
}

//in xxx.gsp
<g:select name="colony" from="${Colony.listUnique()}" />
</code>```

I agree with tim_yates's answer above, but thought you might appreciate a grails/hibernate approach, as well.

Body:
I have an option for selecting a date from a drop-down with <g:select>.  How can I get non-repeated date values through this?  This is the code to get date in the specified format from the domain class.

dob is of type Date.

<g:set var="dateFormat" value="MM/dd/yyyy"/>
<g:select id="dob" name="dob" from="${Person.list().dob*.format(dateFormat)}"
    value="${personInstance?.dob?.format(dateFormat)}" />

Body:
If "Colony" is a grails domain class, then you can alter your query to retrieve distinct values. You didn't provide details, but let's say your domain class is called "Colony" and it has a property called "name", which for some reason you haven't made a unique constraint. Then you can do the following:

//add this method to Colony.groovy
public static List listUnique() {
    Colony.withCriteria {
        projections {
            distinct "name"
        }
    }.sort()
}

//in xxx.gsp
<g:select name="colony" from="${Colony.listUnique()}" />

I agree with tim_yates's answer above, but thought you might appreciate a grails/hibernate approach, as well.


问:
Chrome allows ajax going to http foreign origin where firefox does not - why?
I have a JSP with javascript code, running on a server with HTTPS. In this JavaScript I trigger a request to another (local) webserver like this:

```<code>let url = 'http:/localhost:3111/doSomePost';
      $.ajax({
        type: 'POST',
        url: url,
        contentType: 'application/octet-stream',
        processData: false,
        data: uint8array
    })
</code>```

This requires CrossOrigin to be enabled on the local webserver in order to work - I configured that part and it works.

But it only works in Chrome. Not in Firefox.

Firefox will give me this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
  the remote resource at
  http://localhost:3111/doSomePost. (Reason: CORS
  request did not succeed).

I can see in the network tab of firefox devtools, that firefox does not even bother to send the preflight request (the OPTIONS request). So Firefox just decides it won't send that request (and I suspect it to be because that local webserver protocol is HTTP).

I have now changed my local webserver to use HTTPS using a self-signed certificate as described here: https://www.baeldung.com/spring-boot-https-self-signed-certificate

Now, it works in Firefox and Chrome (after I manually add the certificate which is not valid).

I just wonder why chrome has no problem but firefox does.

UPDATE: corrected minor typo in error message

答:
I've managed to find a better solution. Instead of switching the local webserver to HTTPS in order to get firefox working, I changed the above request to:

```<code>let url = 'http:/localhost:3111/doSomePost';
      $.ajax({
        type: 'POST',
        url: url,
        data: jsonWithBase64encodedData
    })
</code>```

This now qualifies as so called "Simple request" (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) again, and is being treated in a similar, and most importantly, working way in all browsers.

Body:
I have a JSP with javascript code, running on a server with HTTPS. In this JavaScript I trigger a request to another (local) webserver like this:

let url = 'http:/localhost:3111/doSomePost';
      $.ajax({
        type: 'POST',
        url: url,
        contentType: 'application/octet-stream',
        processData: false,
        data: uint8array
    })

This requires CrossOrigin to be enabled on the local webserver in order to work - I configured that part and it works.

But it only works in Chrome. Not in Firefox.

Firefox will give me this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
  the remote resource at
  http://localhost:3111/doSomePost. (Reason: CORS
  request did not succeed).

I can see in the network tab of firefox devtools, that firefox does not even bother to send the preflight request (the OPTIONS request). So Firefox just decides it won't send that request (and I suspect it to be because that local webserver protocol is HTTP).

I have now changed my local webserver to use HTTPS using a self-signed certificate as described here: https://www.baeldung.com/spring-boot-https-self-signed-certificate

Now, it works in Firefox and Chrome (after I manually add the certificate which is not valid).

I just wonder why chrome has no problem but firefox does.

UPDATE: corrected minor typo in error message

Body:
I've managed to find a better solution. Instead of switching the local webserver to HTTPS in order to get firefox working, I changed the above request to:

let url = 'http:/localhost:3111/doSomePost';
      $.ajax({
        type: 'POST',
        url: url,
        data: jsonWithBase64encodedData
    })

This now qualifies as so called "Simple request" (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) again, and is being treated in a similar, and most importantly, working way in all browsers.