问:
Lazy-loading is not supported for detached entities EF
I need help to my new project for learning. i am using linq and EF and getting data from db. but it's show subjected error my code are below

Class Have Many subjects : Class 1 have these Subjects list  English, Science , Mathematics
ERROR:

InvalidOperationException: Error generated for warning
  'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning':
  An attempt was made to lazy-load navigation property 'ClassSubject' on
  detached entity of type 'SubjectProxy'. Lazy-loading is not supported
  for detached entities or entities that are loaded with
  'AsNoTracking()'. This exception can be suppressed or logged by
  passing event ID 'CoreEventId.DetachedLazyLoadingWarning' to the
  'ConfigureWarnings' method in 'DbContext.OnConfiguring' or
  'AddDbContext'.
  pri

```<code>vate readonly IGenericRepository<Subject> _subject;
        private readonly IGenericRepository<ClassSubject> _classSubject;
        public SubjectService(IGenericRepository<Subject> subject, IGenericRepository<ClassSubject> classSubject)
        {
            _subject = subject;
            _classSubject = classSubject;

        }
   public async Task<IEnumerable<ClassSubjectLib>> GetClassSubject()
    {
        var _dbs = await _classSubject.AllAsync().ConfigureAwait(false);
        return _dbs.Select(x => new ClassSubjectLib
        {
            ClassDetailsId = Convert.ToString(x.ClassDetailsId),
            SubjectId = Convert.ToString(x.SubjectId),
            SubjectInfo = _subject.FindBy(s => s.SubjectId == x.SubjectId)

        });
    }
    public class ClassSubjectLib
    {
        public int ClassSubjectId { get; set; }
        public string ClassDetailsId{ get; set; }
        public string SubjectId { get; set; }
        public IEnumerable<Subject> SubjectInfo { get; set; }
    }

 public  class Subject
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int SubjectId { get; set; }
        [Column(TypeName = "VARCHAR(100)")]
        public string SubjectName { get; set; }
        public bool IsShow { get; set; }

        public DateTime Created { get; set; }
        public DateTime Updated { get; set; }
        public virtual ICollection<ClassSubject> ClassSubject { get; set; }
    }

public class ClassSubject
    {
        [Key]
        public int ClassSubjectId { get; set; }
        public int ClassDetailsId { get; set; }
        public int SubjectId { get; set; }

        public DateTime Created { get; set; }
        public DateTime Updated { get; set; }
        public virtual Subject Subject { get; set; }
        public virtual ClassDetails ClassDetails { get; set; }

    }
</code>```

I need data Like

```<code>{
    "ClassSubjectId": 1,
    "ClassDetailsId": 1,
    "SubjectInfo": [{
        "SubjectName": "Abc",
        "SubjectId": 1
    }, {
        "SubjectName": "cfd",
        "SubjectId": 2
    }]
}
</code>```

 Data of database

答:
Get rid of your useless extra repository layer and just do something like:</p>

```<code>public async Task<IEnumerable<ClassSubjectLib>> GetClassSubject()
{
    return dbContext.Set<ClassSubject>()
                    .Select(x => new ClassSubjectLib
                         {
                            ClassDetailsId = Convert.ToString(x.ClassDetailsId),
                            SubjectId = Convert.ToString(x.SubjectId),
                            SubjectInfo = x.Subjects.ToList()

                         })
                    .ToListAsync();
}
</code>```

Body:
I need help to my new project for learning. i am using linq and EF and getting data from db. but it's show subjected error my code are below

Class Have Many subjects : Class 1 have these Subjects list  English, Science , Mathematics
ERROR:

InvalidOperationException: Error generated for warning
  'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning':
  An attempt was made to lazy-load navigation property 'ClassSubject' on
  detached entity of type 'SubjectProxy'. Lazy-loading is not supported
  for detached entities or entities that are loaded with
  'AsNoTracking()'. This exception can be suppressed or logged by
  passing event ID 'CoreEventId.DetachedLazyLoadingWarning' to the
  'ConfigureWarnings' method in 'DbContext.OnConfiguring' or
  'AddDbContext'.
  pri

vate readonly IGenericRepository<Subject> _subject;
        private readonly IGenericRepository<ClassSubject> _classSubject;
        public SubjectService(IGenericRepository<Subject> subject, IGenericRepository<ClassSubject> classSubject)
        {
            _subject = subject;
            _classSubject = classSubject;

        }
   public async Task<IEnumerable<ClassSubjectLib>> GetClassSubject()
    {
        var _dbs = await _classSubject.AllAsync().ConfigureAwait(false);
        return _dbs.Select(x => new ClassSubjectLib
        {
            ClassDetailsId = Convert.ToString(x.ClassDetailsId),
            SubjectId = Convert.ToString(x.SubjectId),
            SubjectInfo = _subject.FindBy(s => s.SubjectId == x.SubjectId)

        });
    }
    public class ClassSubjectLib
    {
        public int ClassSubjectId { get; set; }
        public string ClassDetailsId{ get; set; }
        public string SubjectId { get; set; }
        public IEnumerable<Subject> SubjectInfo { get; set; }
    }

 public  class Subject
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int SubjectId { get; set; }
        [Column(TypeName = "VARCHAR(100)")]
        public string SubjectName { get; set; }
        public bool IsShow { get; set; }

        public DateTime Created { get; set; }
        public DateTime Updated { get; set; }
        public virtual ICollection<ClassSubject> ClassSubject { get; set; }
    }

public class ClassSubject
    {
        [Key]
        public int ClassSubjectId { get; set; }
        public int ClassDetailsId { get; set; }
        public int SubjectId { get; set; }

        public DateTime Created { get; set; }
        public DateTime Updated { get; set; }
        public virtual Subject Subject { get; set; }
        public virtual ClassDetails ClassDetails { get; set; }

    }

I need data Like

{
    "ClassSubjectId": 1,
    "ClassDetailsId": 1,
    "SubjectInfo": [{
        "SubjectName": "Abc",
        "SubjectId": 1
    }, {
        "SubjectName": "cfd",
        "SubjectId": 2
    }]
}

 Data of database

Body:
Get rid of your useless extra repository layer and just do something like:

public async Task<IEnumerable<ClassSubjectLib>> GetClassSubject()
{
    return dbContext.Set<ClassSubject>()
                    .Select(x => new ClassSubjectLib
                         {
                            ClassDetailsId = Convert.ToString(x.ClassDetailsId),
                            SubjectId = Convert.ToString(x.SubjectId),
                            SubjectInfo = x.Subjects.ToList()

                         })
                    .ToListAsync();
}


来源: stackexchange

问:
Fragment$InstantiationException on inflating androidx fragment from android.app.Activity
I'm getting the following exception:

```<code>android.app.Fragment$InstantiationException: Trying to instantiate a class com.example.android.btVspTest.StageCollectionFragment that is not a Fragment
</code>```

The exception triggers within the following call to android.app.Activity.setContentView from onCreate() of my VspTestActivity class, which extends android.app.Activity:
setContentView(R.layout.activity_vsp_test);

My com.example.android.btVspTest.StageCollectionFragment extends androidx.fragment.app.Fragment. I am guessing the issue has to do with incompatibility beween android.app.Activity and androidx.fragment.app.Fragment. Is there a fix or work-around?

Application level build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29

    defaultConfig {
        minSdkVersion 26
        targetSdkVersion 29
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'
    /*implementation 'com.google.android.material:material:1.1.0-alpha08'*/
    implementation 'androidx.viewpager2:viewpager2:1.0.0'
}
</code>```

activity_vsp_test.xml:

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/margin_huge"
        android:orientation="horizontal">

        <Button
            android:id="@+id/test_connect_button"
            android:layout_width="126dp"
            android:layout_height="match_parent"
            android:text="@string/connect" />

        <Button
            android:id="@+id/test_disconnect_button"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="@string/disconnect" />

        <Button
            android:id="@+id/test_bluetooth_button"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="startBluetoothActivity"
            android:text="Bluetooth" />

    </LinearLayout>

    <TextView
        android:id="@+id/vsp_test_connection_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/disconnected" />

    <TextView
        android:id="@+id/test_result_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- 2 irrelevant linear layouts with buttons in them removed -->

    <fragment class="com.example.android.btVspTest.StageCollectionFragment"
        android:id="@+id/test_stage_collection_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</LinearLayout>
</code>```

StageCollectionFragment.java:

```<code>package com.example.android.btVspTest;

import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.android.bluetoothvsp.R;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.android.material.tabs.TabLayoutMediator.TabConfigurationStrategy;

public class StageCollectionFragment extends Fragment implements TabConfigurationStrategy {
    // When requested, this adapter returns a StageFragment,
    // representing an object in the collection.
    StageCollectionAdapter demoCollectionAdapter;
    ViewPager2 viewPager;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.test_stage_layout, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        demoCollectionAdapter = new StageCollectionAdapter(this);
        viewPager = view.findViewById(R.id.test_stage_pager);
        viewPager.setAdapter(demoCollectionAdapter);

        TabLayout tabLayout = view.findViewById(R.id.test_stage_tab_layout);
        new TabLayoutMediator(tabLayout, viewPager, this).attach();

    }

    @Override
    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
        tab.setText("OBJECT " + (position + 1));
    }
}
</code>```

VspTestActivity.java:

```<code>package com.example.android.btVspTest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.bluetoothvsp.ActivityMessageDataKey;
import com.example.android.bluetoothvsp.BluetoothActivity;
import com.example.android.bluetoothvsp.DeviceListActivity;
import com.example.android.bluetoothvsp.R;
import com.example.android.bluetoothvsp.enums.ConnectionState;
import com.example.android.bluetoothvsp.enums.TestState;
import com.example.android.common.logger.Log;
import com.example.android.common.logger.LogWrapper;
import com.example.android.common.logger.MessageOnlyLogFilter;

public class VspTestActivity extends Activity
{
    /**
     * Debugging.
     */
    private static final String TAG = "VspTestActivity";

    /**
     * UI elements.
     */
    private TextView mConnectionTextView;
    private TextView mTestResultTextView;
    private Button mConnectButton;
    private Button mDisconnectButton;
    private Button mSynchronousTestButton;
    private Button mHostSpamButton;
    private Button mReaderSpamButton;
    private Button mBothSpamButton;

    /**
     * Objects provided by Android to facilitate Bluetooth operations.
     */
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice mDevice;

    /**
     * Manger used to start and handle the communication tests.
     */
    private BluetoothVspTestManager mVspTestManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vsp_test);

        if (savedInstanceState != null) {
            return;
        }

    // Irrelevant code removed
    }

    // Irrelevant code removed

    @Override
    protected  void onStart() {
        super.onStart();
        // Irrelevant code removed
    }

    // Irrelevant code removed
}
</code>```

Some of the code is copy->paste->edit of example at https://developer.android.com/guide/navigation/navigation-swipe-view-2, with following mapping:

My StageCollectionFragment is their CollectionDemoFragment

My StageFragment is their DemoObjectFragment

That developer.android.com example unfortunately isn't complete as the layout resources are missing. I haven't been able to find a full example on the internet, of combining TabLayout & ViewPager2.

I'm trying to do something like the draft screen at https://imgur.com/a/k8Tr52y?. I would eventually have 4 to 5 tabs with actual meaningful tab titles, with the tabs being added dynamically, and specific fragments in each of the tabs.

答:
Your activity must extend androidx.fragment.app.FragmentActivity.

From the documentation,

Base class for activities that want to use the support-based
  Fragments.

Also from Fragment's documentation,

Your activity must extend FragmentActivity

You must call FragmentActivity.getSupportFragmentManager() to get the    FragmentManager

ContentLicense: CC BY-SA 4.0

Body:
I'm getting the following exception:

android.app.Fragment$InstantiationException: Trying to instantiate a class com.example.android.btVspTest.StageCollectionFragment that is not a Fragment

The exception triggers within the following call to android.app.Activity.setContentView from onCreate() of my VspTestActivity class, which extends android.app.Activity:
setContentView(R.layout.activity_vsp_test);

My com.example.android.btVspTest.StageCollectionFragment extends androidx.fragment.app.Fragment. I am guessing the issue has to do with incompatibility beween android.app.Activity and androidx.fragment.app.Fragment. Is there a fix or work-around?

Application level build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29

    defaultConfig {
        minSdkVersion 26
        targetSdkVersion 29
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'
    /*implementation 'com.google.android.material:material:1.1.0-alpha08'*/
    implementation 'androidx.viewpager2:viewpager2:1.0.0'
}

activity_vsp_test.xml:

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/margin_huge"
        android:orientation="horizontal">

        <Button
            android:id="@+id/test_connect_button"
            android:layout_width="126dp"
            android:layout_height="match_parent"
            android:text="@string/connect" />

        <Button
            android:id="@+id/test_disconnect_button"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="@string/disconnect" />

        <Button
            android:id="@+id/test_bluetooth_button"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="startBluetoothActivity"
            android:text="Bluetooth" />

    </LinearLayout>

    <TextView
        android:id="@+id/vsp_test_connection_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/disconnected" />

    <TextView
        android:id="@+id/test_result_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <fragment class="com.example.android.btVspTest.StageCollectionFragment"
        android:id="@+id/test_stage_collection_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</LinearLayout>

StageCollectionFragment.java:

package com.example.android.btVspTest;

import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.android.bluetoothvsp.R;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.android.material.tabs.TabLayoutMediator.TabConfigurationStrategy;

public class StageCollectionFragment extends Fragment implements TabConfigurationStrategy {
    // When requested, this adapter returns a StageFragment,
    // representing an object in the collection.
    StageCollectionAdapter demoCollectionAdapter;
    ViewPager2 viewPager;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.test_stage_layout, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        demoCollectionAdapter = new StageCollectionAdapter(this);
        viewPager = view.findViewById(R.id.test_stage_pager);
        viewPager.setAdapter(demoCollectionAdapter);

        TabLayout tabLayout = view.findViewById(R.id.test_stage_tab_layout);
        new TabLayoutMediator(tabLayout, viewPager, this).attach();

    }

    @Override
    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
        tab.setText("OBJECT " + (position + 1));
    }
}

VspTestActivity.java:

package com.example.android.btVspTest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.bluetoothvsp.ActivityMessageDataKey;
import com.example.android.bluetoothvsp.BluetoothActivity;
import com.example.android.bluetoothvsp.DeviceListActivity;
import com.example.android.bluetoothvsp.R;
import com.example.android.bluetoothvsp.enums.ConnectionState;
import com.example.android.bluetoothvsp.enums.TestState;
import com.example.android.common.logger.Log;
import com.example.android.common.logger.LogWrapper;
import com.example.android.common.logger.MessageOnlyLogFilter;

public class VspTestActivity extends Activity
{
    /**
     * Debugging.
     */
    private static final String TAG = "VspTestActivity";

    /**
     * UI elements.
     */
    private TextView mConnectionTextView;
    private TextView mTestResultTextView;
    private Button mConnectButton;
    private Button mDisconnectButton;
    private Button mSynchronousTestButton;
    private Button mHostSpamButton;
    private Button mReaderSpamButton;
    private Button mBothSpamButton;

    /**
     * Objects provided by Android to facilitate Bluetooth operations.
     */
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice mDevice;

    /**
     * Manger used to start and handle the communication tests.
     */
    private BluetoothVspTestManager mVspTestManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vsp_test);

        if (savedInstanceState != null) {
            return;
        }

    // Irrelevant code removed
    }

    // Irrelevant code removed

    @Override
    protected  void onStart() {
        super.onStart();
        // Irrelevant code removed
    }

    // Irrelevant code removed
}

Some of the code is copy->paste->edit of example at https://developer.android.com/guide/navigation/navigation-swipe-view-2, with following mapping:

My StageCollectionFragment is their CollectionDemoFragment

My StageFragment is their DemoObjectFragment

That developer.android.com example unfortunately isn't complete as the layout resources are missing. I haven't been able to find a full example on the internet, of combining TabLayout & ViewPager2.

I'm trying to do something like the draft screen at https://imgur.com/a/k8Tr52y?. I would eventually have 4 to 5 tabs with actual meaningful tab titles, with the tabs being added dynamically, and specific fragments in each of the tabs.


问:
flutter websockets autoreconnect - how to implement
I am struggling how to implement websockets autoreconnect in flutter. I use web_socket_channel, however, the plugin just wraps dart.io WebSocket, hence any solution based on WebSocket class will work for me as well.

I already figured out, how to catch the socket disconnection, see the code snippet below:

```<code>    try {
      _channel = IOWebSocketChannel.connect(
        wsUrl,
      );

      ///
      /// Start listening to new notifications / messages
      ///
      _channel.stream.listen(
        _onMessageFromServer,
        onDone: () {
          debugPrint('ws channel closed');
        },
        onError: (error) {
          debugPrint('ws error $error');
        },
      );
    } catch (e) {
      ///
      /// General error handling
      /// TODO handle connection failure
      ///
      debugPrint('Connection exception $e');
    }
</code>```

I was thinking to call IOWebSocketChannel.connect from within onDone, however, this leads to a kind of infinite loop - since I have to close the _channel prior calling connect again, this on its turn calls onDone again and so on.

Any help would be greatly appreciated!

答:
With the package:web_socket_channel (IOWebSocketChannel) there is not any way in order to implement reconnection for the socket connections. But you can use WebSocket class in order to implement a reconnectable connection.

You can implement the WebSocket channel and then broadcast messages with StreamController class. Working example:

import 'dart:async';
import 'dart:io';

class NotificationController {

  static final NotificationController _singleton = new NotificationController._internal();

  StreamController<String> streamController = new StreamController.broadcast(sync: true);

  String wsUrl = 'ws://YOUR_WEBSERVICE_URL';

  WebSocket channel;

  factory NotificationController() {
    return _singleton;
  }

  NotificationController._internal() {
    initWebSocketConnection();
  }

  initWebSocketConnection() async {
    print("conecting...");
    this.channel = await connectWs();
    print("socket connection initializied");
    this.channel.done.then((dynamic _) => _onDisconnected());
    broadcastNotifications();
  }

  broadcastNotifications() {
    this.channel.listen((streamData) {
      streamController.add(streamData);
    }, onDone: () {
      print("conecting aborted");
      initWebSocketConnection();
    }, onError: (e) {
      print('Server error: $e');
      initWebSocketConnection();
    });
  }

  connectWs() async{
    try {
      return await WebSocket.connect(wsUrl);
    } catch  (e) {
      print("Error! can not connect WS connectWs " + e.toString());
      await Future.delayed(Duration(milliseconds: 10000));
      return await connectWs();
    }

  }

  void _onDisconnected() {
    initWebSocketConnection();
  }
}
```
<p>Because the notification controller returns a singleton instance, then there will be always one Socket connection between the server and device. And with the broadcast method of StreamController, we can share the data sent by Websocket between multiple consumers</p>
<pre class="lang-dart prettyprint-override"><code>var _streamController = new NotificationController().streamController;

_streamController.stream.listen(pushNotifications);
</code>```

Body:
I am struggling how to implement websockets autoreconnect in flutter. I use web_socket_channel, however, the plugin just wraps dart.io WebSocket, hence any solution based on WebSocket class will work for me as well.

I already figured out, how to catch the socket disconnection, see the code snippet below:

    try {
      _channel = IOWebSocketChannel.connect(
        wsUrl,
      );

      ///
      /// Start listening to new notifications / messages
      ///
      _channel.stream.listen(
        _onMessageFromServer,
        onDone: () {
          debugPrint('ws channel closed');
        },
        onError: (error) {
          debugPrint('ws error $error');
        },
      );
    } catch (e) {
      ///
      /// General error handling
      /// TODO handle connection failure
      ///
      debugPrint('Connection exception $e');
    }

I was thinking to call IOWebSocketChannel.connect from within onDone, however, this leads to a kind of infinite loop - since I have to close the _channel prior calling connect again, this on its turn calls onDone again and so on.

Any help would be greatly appreciated!

Body:
With the package:web_socket_channel (IOWebSocketChannel) there is not any way in order to implement reconnection for the socket connections. But you can use WebSocket class in order to implement a reconnectable connection.

You can implement the WebSocket channel and then broadcast messages with StreamController class. Working example:

import 'dart:async';
import 'dart:io';

class NotificationController {

  static final NotificationController _singleton = new NotificationController._internal();

  StreamController<String> streamController = new StreamController.broadcast(sync: true);

  String wsUrl = 'ws://YOUR_WEBSERVICE_URL';

  WebSocket channel;

  factory NotificationController() {
    return _singleton;
  }

  NotificationController._internal() {
    initWebSocketConnection();
  }

  initWebSocketConnection() async {
    print("conecting...");
    this.channel = await connectWs();
    print("socket connection initializied");
    this.channel.done.then((dynamic _) => _onDisconnected());
    broadcastNotifications();
  }

  broadcastNotifications() {
    this.channel.listen((streamData) {
      streamController.add(streamData);
    }, onDone: () {
      print("conecting aborted");
      initWebSocketConnection();
    }, onError: (e) {
      print('Server error: $e');
      initWebSocketConnection();
    });
  }

  connectWs() async{
    try {
      return await WebSocket.connect(wsUrl);
    } catch  (e) {
      print("Error! can not connect WS connectWs " + e.toString());
      await Future.delayed(Duration(milliseconds: 10000));
      return await connectWs();
    }

  }

  void _onDisconnected() {
    initWebSocketConnection();
  }
}

Because the notification controller returns a singleton instance, then there will be always one Socket connection between the server and device. And with the broadcast method of StreamController, we can share the data sent by Websocket between multiple consumers

var _streamController = new NotificationController().streamController;

_streamController.stream.listen(pushNotifications);


问:
What value should I pass into TimeZoneInfo.FindSystemTimeZoneById(String)?
I want to use the TimeZoneInfo.FindSystemTimeZoneById(String) method, but I don't know what values to use as the input?

Where can I get a list of values for id required for FindSystemTimeZoneById?

答:
To get the most current list of time zones, use tzutil from Windows:

tzutil /l

Here you can find the official Time Zone Ids list from Microsoft in MSDN:
https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/default-time-zones

```<code>  ID      |   Time zone name
----------|------------------------
  0       |   Dateline Standard Time
  110     |   UTC-11
  200     |   Hawaiian Standard Time
  300     |   Alaskan Standard Time
  400     |   Pacific Standard Time
  410     |   Pacific Standard Time (Mexico)
  500     |   Mountain Standard Time
  510     |   Mountain Standard Time (Mexico)
  520     |   US Mountain Standard Time
  600     |   Canada Central Standard Time
  610     |   Central America Standard Time
  620     |   Central Standard Time
  630     |   Central Standard Time (Mexico)
  700     |   Eastern Standard Time
  710     |   SA Pacific Standard Time
  720     |   US Eastern Standard Time
  840     |   Venezuela Standard Time
  800     |   Atlantic Standard Time
  810     |   Central Brazilian Standard Time
  820     |   Pacific SA Standard Time
  830     |   SA Western Standard Time
  850     |   Paraguay Standard Time
  900     |   Newfoundland Standard Time
  910     |   E. South America Standard Time
  920     |   Greenland Standard Time
  930     |   Montevideo Standard Time
  940     |   SA Eastern Standard Time
  950     |   Argentina Standard Time
  1000    |   Mid-Atlantic Standard Time
  1010    |   UTC-2
  1100    |   Azores Standard Time
  1110    |   Cabo Verde Standard Time
  1200    |   GMT Standard Time
  1210    |   Greenwich Standard Time
  1220    |   Morocco Standard Time
  1230    |   UTC
  1300    |   Central Europe Standard Time
  1310    |   Central European Standard Time
  1320    |   Romance Standard Time
  1330    |   W. Central Africa Standard Time
  1340    |   W. Europe Standard Time
  1350    |   Namibia Standard Time
  1400    |   E. Europe Standard Time
  1410    |   Egypt Standard Time
  1420    |   FLE Standard Time
  1430    |   GTB Standard Time
  1440    |   Israel Standard Time
  1450    |   Jordan Standard Time
  1460    |   Middle East Standard Time
  1470    |   South Africa Standard Time
  1480    |   Syria Standard Time
  1490    |   Turkey Standard Time
  1500    |   Arab Standard Time
  1510    |   Arabic Standard Time
  1520    |   E. Africa Standard Time
  1530    |   Kaliningrad Standard Time
  1550    |   Iran Standard Time
  1540    |   Russian Standard Time
  1600    |   Arabian Standard Time
  1610    |   Azerbaijan Standard Time
  1620    |   Caucasus Standard Time
  1640    |   Georgian Standard Time
  1650    |   Mauritius Standard Time
  1630    |   Afghanistan Standard Time
  1710    |   West Asia Standard Time
  1750    |   Pakistan Standard Time
  1720    |   India Standard Time
  1730    |   Sri Lanka Standard Time
  1740    |   Nepal Standard Time
  1700    |   Ekaterinburg Standard Time
  1800    |   Central Asia Standard Time
  1830    |   Bangladesh Standard Time
  1820    |   Myanmar Standard Time
  1810    |   N. Central Asia Standard Time
  1910    |   SE Asia Standard Time
  1900    |   North Asia Standard Time
  2000    |   China Standard Time
  2020    |   Singapore Standard Time
  2030    |   Taipei Standard Time
  2040    |   W. Australia Standard Time
  2050    |   Ulaanbaatar Standard Time
  2010    |   North Asia East Standard Time
  2100    |   Korea Standard Time
  2110    |   Tokyo Standard Time
  2130    |   AUS Central Standard Time
  2140    |   Cen. Australia Standard Time
  2120    |   Yakutsk Standard Time
  2200    |   AUS Eastern Standard Time
  2210    |   E. Australia Standard Time
  2220    |   Tasmania Standard Time
  2240    |   West Pacific Standard Time
  2230    |   Vladivostok Standard Time
  2300    |   Central Pacific Standard Time
  2310    |   Magadan Standard Time
  2400    |   Fiji Standard Time
  2410    |   New Zealand Standard Time
  2430    |   UTC+12
  2500    |   Tonga Standard Time
  2510    |   Samoa Standard Time
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To get the most current list of time zones, use tzutil from Windows:

tzutil /l

Here you can find the official Time Zone Ids list from Microsoft in MSDN:
https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/default-time-zones

  ID      |   Time zone name
----------|------------------------
  0       |   Dateline Standard Time
  110     |   UTC-11
  200     |   Hawaiian Standard Time
  300     |   Alaskan Standard Time
  400     |   Pacific Standard Time
  410     |   Pacific Standard Time (Mexico)
  500     |   Mountain Standard Time
  510     |   Mountain Standard Time (Mexico)
  520     |   US Mountain Standard Time
  600     |   Canada Central Standard Time
  610     |   Central America Standard Time
  620     |   Central Standard Time
  630     |   Central Standard Time (Mexico)
  700     |   Eastern Standard Time
  710     |   SA Pacific Standard Time
  720     |   US Eastern Standard Time
  840     |   Venezuela Standard Time
  800     |   Atlantic Standard Time
  810     |   Central Brazilian Standard Time
  820     |   Pacific SA Standard Time
  830     |   SA Western Standard Time
  850     |   Paraguay Standard Time
  900     |   Newfoundland Standard Time
  910     |   E. South America Standard Time
  920     |   Greenland Standard Time
  930     |   Montevideo Standard Time
  940     |   SA Eastern Standard Time
  950     |   Argentina Standard Time
  1000    |   Mid-Atlantic Standard Time
  1010    |   UTC-2
  1100    |   Azores Standard Time
  1110    |   Cabo Verde Standard Time
  1200    |   GMT Standard Time
  1210    |   Greenwich Standard Time
  1220    |   Morocco Standard Time
  1230    |   UTC
  1300    |   Central Europe Standard Time
  1310    |   Central European Standard Time
  1320    |   Romance Standard Time
  1330    |   W. Central Africa Standard Time
  1340    |   W. Europe Standard Time
  1350    |   Namibia Standard Time
  1400    |   E. Europe Standard Time
  1410    |   Egypt Standard Time
  1420    |   FLE Standard Time
  1430    |   GTB Standard Time
  1440    |   Israel Standard Time
  1450    |   Jordan Standard Time
  1460    |   Middle East Standard Time
  1470    |   South Africa Standard Time
  1480    |   Syria Standard Time
  1490    |   Turkey Standard Time
  1500    |   Arab Standard Time
  1510    |   Arabic Standard Time
  1520    |   E. Africa Standard Time
  1530    |   Kaliningrad Standard Time
  1550    |   Iran Standard Time
  1540    |   Russian Standard Time
  1600    |   Arabian Standard Time
  1610    |   Azerbaijan Standard Time
  1620    |   Caucasus Standard Time
  1640    |   Georgian Standard Time
  1650    |   Mauritius Standard Time
  1630    |   Afghanistan Standard Time
  1710    |   West Asia Standard Time
  1750    |   Pakistan Standard Time
  1720    |   India Standard Time
  1730    |   Sri Lanka Standard Time
  1740    |   Nepal Standard Time
  1700    |   Ekaterinburg Standard Time
  1800    |   Central Asia Standard Time
  1830    |   Bangladesh Standard Time
  1820    |   Myanmar Standard Time
  1810    |   N. Central Asia Standard Time
  1910    |   SE Asia Standard Time
  1900    |   North Asia Standard Time
  2000    |   China Standard Time
  2020    |   Singapore Standard Time
  2030    |   Taipei Standard Time
  2040    |   W. Australia Standard Time
  2050    |   Ulaanbaatar Standard Time
  2010    |   North Asia East Standard Time
  2100    |   Korea Standard Time
  2110    |   Tokyo Standard Time
  2130    |   AUS Central Standard Time
  2140    |   Cen. Australia Standard Time
  2120    |   Yakutsk Standard Time
  2200    |   AUS Eastern Standard Time
  2210    |   E. Australia Standard Time
  2220    |   Tasmania Standard Time
  2240    |   West Pacific Standard Time
  2230    |   Vladivostok Standard Time
  2300    |   Central Pacific Standard Time
  2310    |   Magadan Standard Time
  2400    |   Fiji Standard Time
  2410    |   New Zealand Standard Time
  2430    |   UTC+12
  2500    |   Tonga Standard Time
  2510    |   Samoa Standard Time


问:
setting cross origin variable in iframe
i am embedding a form on a checkout page with an iframe and i am trying to take the price of the cart and have it automatically inputted into the amount field. the value of the cart variable seems to be $("span[data-test='cart-price-value']").innerText;
when i check it in the console, but i am confused on whether i should set the variable in the script that embeds the iframe or in my iframe html itself or whether or not i have to do both and add a jquery listener to the iframe html

and also i need to trim off the '$' from the variable, cause
$("span[data-test='cart-price-value']").innerText; returns a value with a dollar sign in front of it for example "$435.66" and i need it to be just "435.66" any help would be appreciated

答:
There are a few things here -

Browsers have some pretty stringent restrictions about cross-origin iframes. You won't be able to communicate between the BigCommerce Checkout on one URL to an iframe hosted on a different URL - if their origins are different.

If you try to use JavaScript from the BC checkout page to set the value of a form input embedded in the iframe, you'll get a security warning in the console and the browser will dissallow it.

However, there is an API which allows for this communication - you can read more here:

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

You're going to be sending and listening for custom "message" events and running code accordingly.

I'm not 100% on this, but from what it sounds like, you'll want to use Window.postMessage() to the iframe/origin hosting the external form, and send along the price you need to input.

On the page which serves the iframe/form code, you'll need an event listener to wait for this message to come in, and that's when you can have an event handler which will take the value passed along in the cross-origin message and modify the form input value.

Now, in terms of actually implementing this - it will also become more complicated depending on what type of Checkout Page you're hosting. Are you on Optimized One Page Checkout (The new one?) If so, you'll probably need Mutation Listeners, as the OPC is an external React Application, and you can't really hook into the internal state, you need to use mutation listeners to wait until each section (Customer Details, Shipping Details, Billing Details, payment Step) loads - as these are refreshed using internal React State which you can't access from the BC/stencil/cornerstone/blueprint scripts.

More details on that here:
https://medium.com/bigcommerce-developer-blog/the-complete-guide-to-checkout-customization-on-bigcommerce-6b566bc36fa9

If you're using an older version of checkout where you can manually modify the JS and HTML structure of the checkout that BC serves, you might not need this.

Title: setting cross origin variable in iframe


问:
How can I export dataframes to each Excel sheet?
I used for loop to make a dataframe and I want to export these data frames for each Excel sheet, and has each sheet name.

For example, first, save the created dataframe with the name "a" in the first Excel worksheet, and the next dataframe with the name "b" in the second Excel worksheet.
these dataframes are made by for loop.

How could I do that?

答:
Code:

```<code>dfs=[]
for loop:
    dfs.append(dfx)

    names = ["a", "b", "c", "d", "e"]
    for name, df in zip(names, dfs):
       df.to_csv(f'~/Desktop/df{name}.tsv', index=False, header=False, sep='\t')
</code>```

Code Explanation:

dfs is array to keep data frames which are created inside outer loop, names is for keeping alphabetic or unique names. zip() function creates an iterator that will aggregate elements from two or more iterables, so name and df iterate through.

Body:
Code:

dfs=[]
for loop:
    dfs.append(dfx)

    names = ["a", "b", "c", "d", "e"]
    for name, df in zip(names, dfs):
       df.to_csv(f'~/Desktop/df{name}.tsv', index=False, header=False, sep='\t')

Code Explanation:

dfs is array to keep data frames which are created inside outer loop, names is for keeping alphabetic or unique names. zip() function creates an iterator that will aggregate elements from two or more iterables, so name and df iterate through.


问:
Using R expss and data.table is it possible to load data.table labels from a csv file instead of typing the code in by hand?
Applying labels is an important part of making survey data comprehensible when reported

So the best example I can find uses expss::apply_labels()
e.g the famous mtcars example https://cran.r-project.org/web/packages/expss/vignettes/tables-with-labels.html

as input this requires a data.table and a list of comma separated assignment pairs e.g

```<code>apply_labels(dt, col1 = "label1", col2 = "label2", col3 = "label3")
</code>```

This is fine if you have one data file and a few columns and you can be bothered typing them in for each time, but its not very helpful if you have lots of data files. So how could one load a csv metadata file
in format:

Col1    Col2    Col3

Label1  Label2  Label3

where the Col names match the same names in the data table

this means effectively translating the metadata csv file so that it generates

coln = "labeln"

for each column.

So far I have found the biggest problem is that the apply labels column names are objects not strings and it is very difficult to translate a string to the object in the right scope.

This is where I've got to

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

    readcsvdata <- function(dfile)
     {
        rdata <- fread(file = dfile, sep = "," , quote = "\"" , header = TRUE,
        stringsAsFactors = FALSE, na.strings = getOption("datatable.na.strings","NA"))
        return(rdata)
        }

    rawdatafilename <- "testdata.csv"
    rawmetadata <- "metadata.csv"

    mdt <- readcsvdata(rawmetadata)
    rdt <-readcsvdata(rawdatafilename)
    commonnames <- intersect(names(mdt),names(rdt))  # find common
    qlabels <- as.character(mdt[1, commonnames, with = FALSE])

    comslist <- list()
    for (i in 1:length(commonnames)) # loop through commonnames and qlabels
          {
          if (i == length(commonnames))
              {x <- glue('{commonnames[i]} = "{qlabels[i]}"')} # no comma for final item
              else
              {x <- glue('{commonnames[i]} = "{qlabels[i]}",')} # comma for next item

          comslist[[i]] <- x
    }

comstring <- paste(unlist(comslist), collapse = '')

tdt = apply_labels(tdt, eval(parse(text = comstring)))
</code>```

which yields

Error in parse(text = comstring) : :1:24: unexpected ',' 1: varone = "Label1", ^

oh and print(comstring) produces:

[1] "varone = \"Question one\",vartwo = \"Question two\",varthree =
  \"Question three\",varfour = \"Question four\",varfive = \"Question
  five\",varsix = \"Question six\",varseven = \"Question
  seven\",vareight = \"Question eight\",varnine = \"Question
  nine\",varten = \"Question ten\""

答:
apply_labels is not very convenient for assignment labels from external dictionary. You can use var_lab instead:

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

readcsvdata <- function(dfile)
{
    rdata <- fread(file = dfile, sep = "," , quote = "\"" , header = TRUE,
                   stringsAsFactors = FALSE, na.strings = getOption("datatable.na.strings","NA"))
    return(rdata)
}

rawdatafilename <- "testdata.csv"
rawmetadata <- "metadata.csv"

mdt <- readcsvdata(rawmetadata)
rdt <-readcsvdata(rawdatafilename)
commonnames <- intersect(names(mdt),names(rdt))  # find common
qlabels <- as.list(mdt[1, commonnames, with = FALSE])

for (each_name in commonnames) # loop through commonnames and qlabels
{
    var_lab(rdt[[each_name]]) <- qlabels[[each_name]]
}
</code>```

There is a similar val_lab function for value labels. Additionally you may be interested in apply_dictionary and create_dictionary functions. To get help about them type ?apply_dictionary in the console.

Body:
Applying labels is an important part of making survey data comprehensible when reported

So the best example I can find uses expss::apply_labels()
e.g the famous mtcars example https://cran.r-project.org/web/packages/expss/vignettes/tables-with-labels.html

as input this requires a data.table and a list of comma separated assignment pairs e.g

apply_labels(dt, col1 = "label1", col2 = "label2", col3 = "label3")

This is fine if you have one data file and a few columns and you can be bothered typing them in for each time, but its not very helpful if you have lots of data files. So how could one load a csv metadata file
in format:

Col1    Col2    Col3

Label1  Label2  Label3

where the Col names match the same names in the data table

this means effectively translating the metadata csv file so that it generates

coln = "labeln"

for each column.

So far I have found the biggest problem is that the apply labels column names are objects not strings and it is very difficult to translate a string to the object in the right scope.

This is where I've got to

    library(expss)
    library(data.table)
    library(glue)

    readcsvdata <- function(dfile)
     {
        rdata <- fread(file = dfile, sep = "," , quote = "\"" , header = TRUE,
        stringsAsFactors = FALSE, na.strings = getOption("datatable.na.strings","NA"))
        return(rdata)
        }

    rawdatafilename <- "testdata.csv"
    rawmetadata <- "metadata.csv"

    mdt <- readcsvdata(rawmetadata)
    rdt <-readcsvdata(rawdatafilename)
    commonnames <- intersect(names(mdt),names(rdt))  # find common
    qlabels <- as.character(mdt[1, commonnames, with = FALSE])

    comslist <- list()
    for (i in 1:length(commonnames)) # loop through commonnames and qlabels
          {
          if (i == length(commonnames))
              {x <- glue('{commonnames[i]} = "{qlabels[i]}"')} # no comma for final item
              else
              {x <- glue('{commonnames[i]} = "{qlabels[i]}",')} # comma for next item

          comslist[[i]] <- x
    }

comstring <- paste(unlist(comslist), collapse = '')

tdt = apply_labels(tdt, eval(parse(text = comstring)))

which yields

Error in parse(text = comstring) : :1:24: unexpected ',' 1: varone = "Label1", ^

oh and print(comstring) produces:

[1] "varone = \"Question one\",vartwo = \"Question two\",varthree =
  \"Question three\",varfour = \"Question four\",varfive = \"Question
  five\",varsix = \"Question six\",varseven = \"Question
  seven\",vareight = \"Question eight\",varnine = \"Question
  nine\",varten = \"Question ten\""

Body:
apply_labels is not very convenient for assignment labels from external dictionary. You can use var_lab instead:

library(expss)
library(data.table)

readcsvdata <- function(dfile)
{
    rdata <- fread(file = dfile, sep = "," , quote = "\"" , header = TRUE,
                   stringsAsFactors = FALSE, na.strings = getOption("datatable.na.strings","NA"))
    return(rdata)
}

rawdatafilename <- "testdata.csv"
rawmetadata <- "metadata.csv"

mdt <- readcsvdata(rawmetadata)
rdt <-readcsvdata(rawdatafilename)
commonnames <- intersect(names(mdt),names(rdt))  # find common
qlabels <- as.list(mdt[1, commonnames, with = FALSE])

for (each_name in commonnames) # loop through commonnames and qlabels
{
    var_lab(rdt[[each_name]]) <- qlabels[[each_name]]
}

There is a similar val_lab function for value labels. Additionally you may be interested in apply_dictionary and create_dictionary functions. To get help about them type ?apply_dictionary in the console.


问:
Flutter - show android homescreen widget in the app
Is it possible somehow to display Android homescreen widget as a Flutter widget?

I've read about PlatformView widget that can embed any Android view inside Flutter app. How is it possible to do the same with homescreen widgets?

答: There is no official support from flutter but you can take a look at this video explaining how to create a home widget using flutter unfortunately the speak he didn't post the code. It looks like the only solution to add the app widget android code in the generated code which means you should know android development in kotlin/java.</p>


问:
how remove last special character from this string with preg_replace?
I want to remove this >

from

```<code>com.gau.go.launcherex.gowidget.weatherwidget>
</code>```

答:
To remove > you can use preg_replace() as

```<code>preg_replace('/[>$]/s', '', $str);
</code>```

Output

```<code>com.gau.go.launcherex.gowidget.weatherwidget
</code>```

Body:
I want to remove this >

from

com.gau.go.launcherex.gowidget.weatherwidget>

Body:
To remove > you can use preg_replace() as

preg_replace('/[>$]/s', '', $str);

Output

com.gau.go.launcherex.gowidget.weatherwidget


问:
How do I persist a list of objects using jupyter
I'm working on Jupyter and trying to make my list persistent but pickling just gives me this error:

```<code>PicklingError                             Traceback (most recent call last)
<ipython-input-34-3ba985598f1e> in <module>
      1 with open("book_data/books.pkl", "wb") as cf:
----> 2    pickle.dump(book_list, cf)

PicklingError: Can't pickle <class '__main__.book'>: it's not the same object as __main__.book
</code>```

I tried using dill to save the session instead and it gave me this error:

```<code>RecursionError                            Traceback (most recent call last)
<ipython-input-33-5011bc09ef45> in <module>
      1 import dill
----> 2 dill.dump_session('Data_Gathering.db')
</code>```

答:
I'm the dill author.  If you are only looking to pickle a list of objects, you might just try

```<code>with open("book_data/books.pkl", "wb") as cf:
    dill.dump(book_list, cf)
</code>```

dill can pickle the entire session, but from within a jupiter notebook it has some difficulty, so it's generally just easier to pickle the objects you are interested in.

Body:
I'm working on Jupyter and trying to make my list persistent but pickling just gives me this error:

PicklingError                             Traceback (most recent call last)
<ipython-input-34-3ba985598f1e> in <module>
      1 with open("book_data/books.pkl", "wb") as cf:
----> 2    pickle.dump(book_list, cf)

PicklingError: Can't pickle <class '__main__.book'>: it's not the same object as __main__.book

I tried using dill to save the session instead and it gave me this error:

RecursionError                            Traceback (most recent call last)
<ipython-input-33-5011bc09ef45> in <module>
      1 import dill
----> 2 dill.dump_session('Data_Gathering.db')

Body:
I'm the dill author.  If you are only looking to pickle a list of objects, you might just try

with open("book_data/books.pkl", "wb") as cf:
    dill.dump(book_list, cf)

dill can pickle the entire session, but from within a jupiter notebook it has some difficulty, so it's generally just easier to pickle the objects you are interested in.


问:
Injecting Correct ISessionFactory Into IRepository Using Castle Windsor and NHibernate Facility
I have three SQL Server databases that a single application retrieves data from.  I am using NHibernate to retrieve data from the different databases.  I have things set up so that each database has its own repository and class mappings in its own assembly.  In my castle.config file I have the database connections setup using the Castle NHibernate Facility:

```<code><?xml version="1.0" encoding="utf-8" ?>
<castle>
  <facilities>
    <facility id="factorysupport" type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Windsor" />
    <facility id="nhibernate" isWeb="false" type="Castle.Facilities.NHibernateIntegration.NHibernateFacility, Castle.Facilities.NHibernateIntegration">
      <factory id="databaseone.factory" alias="databaseone">
        <settings>
            <!--Settings Here -->
        </settings>
        <assemblies>
           <assembly>DAL.DatabaseOne</assembly>
        </assemblies>
      </factory>
      <factory id="databasetwo.factory" alias="databasetwo">
        <settings>
          <!--Settings Here -->
        </settings>
        <assemblies>
          <assembly>DAL.DatabaseTwo</assembly>
        </assemblies>
      </factory>
      <factory id="databasethree.factory" alias="databasethree">
        <settings>
            <!--Settings Here -->
        </settings>
        <assemblies>
             <assembly>DAL.DatabaseThree</assembly>
        </assemblies>
      </factory>
    </facility>
  </facilities>
</castle>
</code>```

All of my repositories have a constructor that take an ISessionFactory as the parameter:

```<code>public MyRepository<T> : IRepository<T>
{
   public MyRepository(ISessionFactory factory)
   {
        //Do stuff here
   }
 }
</code>```

I have an installer class where I would like to define the various repositories:

```<code>//In install method of IWindsorInstaller
container.register(Component.For(typeof(IRepository<>)).ImplementedBy(typeof(MyRepository<>));
</code>```

Using one database things work fine.  When I add the second database to the mix, the same ISessionFactory is injected into all of the repositories.  My question is what is the best way to handle this?  I could manually specify which ISessionFactory should be injected into which Repository<> but I cannot seem to find documentation on this.  The best way would be if I could say something like: For all class mappings in assembly DAL.DatabaseOne, always inject the ISessionFactory corresponding to databaseone.factory; and for all class mappings in assembly DAL.DatabaseTwo, always inject the ISessionFactory corresponding to databasetwo.factory.

Thoughts or suggestions?

答:
This is explained in this post by Fabio Maulo toward the end under the heading 'Configuring your DAOs/Repository for multiple DB'.

He maps the factory individually for each domain class but you could also use reflection on each of the domain assemblies in your case to register the appropriate factory.

Body:
I have three SQL Server databases that a single application retrieves data from.  I am using NHibernate to retrieve data from the different databases.  I have things set up so that each database has its own repository and class mappings in its own assembly.  In my castle.config file I have the database connections setup using the Castle NHibernate Facility:

<?xml version="1.0" encoding="utf-8" ?>
<castle>
  <facilities>
    <facility id="factorysupport" type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Windsor" />
    <facility id="nhibernate" isWeb="false" type="Castle.Facilities.NHibernateIntegration.NHibernateFacility, Castle.Facilities.NHibernateIntegration">
      <factory id="databaseone.factory" alias="databaseone">
        <settings>

        </settings>
        <assemblies>
           <assembly>DAL.DatabaseOne</assembly>
        </assemblies>
      </factory>
      <factory id="databasetwo.factory" alias="databasetwo">
        <settings>

        </settings>
        <assemblies>
          <assembly>DAL.DatabaseTwo</assembly>
        </assemblies>
      </factory>
      <factory id="databasethree.factory" alias="databasethree">
        <settings>

        </settings>
        <assemblies>
             <assembly>DAL.DatabaseThree</assembly>
        </assemblies>
      </factory>
    </facility>
  </facilities>
</castle>

All of my repositories have a constructor that take an ISessionFactory as the parameter:

public MyRepository<T> : IRepository<T>
{
   public MyRepository(ISessionFactory factory)
   {
        //Do stuff here
   }
 }

I have an installer class where I would like to define the various repositories:

//In install method of IWindsorInstaller
container.register(Component.For(typeof(IRepository<>)).ImplementedBy(typeof(MyRepository<>));

Using one database things work fine.  When I add the second database to the mix, the same ISessionFactory is injected into all of the repositories.  My question is what is the best way to handle this?  I could manually specify which ISessionFactory should be injected into which Repository<> but I cannot seem to find documentation on this.  The best way would be if I could say something like: For all class mappings in assembly DAL.DatabaseOne, always inject the ISessionFactory corresponding to databaseone.factory; and for all class mappings in assembly DAL.DatabaseTwo, always inject the ISessionFactory corresponding to databasetwo.factory.

Thoughts or suggestions?


答:
Put the character before $ to match it at the end of the string.

```<code>$string = preg_replace('/>$/', '', $string);
</code>```

Title: how remove last special character from this string with preg_replace?

Body:
Put the character before $ to match it at the end of the string.

$string = preg_replace('/>$/', '', $string);


问:
Firebase JS API auth - account-exists-with-different-credential
We're having real problems trying to resolve this and so hoping for some Firebase assistance / those that have solved the same problem.

The app is React Native (0.43.2) and using Firebase JS API (latest)

We provide Facebook and Google auth. Works fine.

BUT, if a user:

signs in with Facebook (is ok)

later, signs in with Google  (is also fine)

later, tries to sign in with Facebook - BOOM! not so fine and Firebase returns this error:

auth/account-exists-with-different-credential

From reading docs and a few posts on SO, we thought the following was correct but clearly not as we're getting the same auth error back.

```<code>...error returned by Firebase auth after trying Facebook login...

const email = error.email;
const pendingCred = error.credential;

firebase.auth().fetchProvidersForEmail(email)
.then(providers => {
   //providers returns this array -> ["google.com"]
   firebase.auth().signInWithCredential(pendingCred)
   .then(result => {
       result.user.link(pendingCred)
   })
   .catch(error => log(error))
</code>```

The call to signInWithCredential is throwing the same error auth/account-exists-with-different-credential.

Can anyone help point out what we are doing wrong with this implementation? Greatly appreciated.

答:
I've written about how to do this without needing to sign in for a second time here:

https://blog.wedport.co.uk/2020/05/29/react-native-firebase-auth-with-linking/

You need to store the original credential and retrieve to login silently before linking the accounts. Full code in link:

```<code>signInOrLink: async function (provider, credential, email) {
  this.saveCredential(provider, credential)
  await auth().signInWithCredential(credential).catch(
    async (error) => {
      try {
        if (error.code != "auth/account-exists-with-different-credential") {
          throw error;
        }
        let methods = await auth().fetchSignInMethodsForEmail(email);
        let oldCred = await this.getCredential(methods[0]);
        let prevUser = await auth().signInWithCredential(oldCred);
        auth().currentUser.linkWithCredential(credential);
      }
      catch (error) {
        throw error;
      }
    }
  );
</code>```

}

Body:
We're having real problems trying to resolve this and so hoping for some Firebase assistance / those that have solved the same problem.

The app is React Native (0.43.2) and using Firebase JS API (latest)

We provide Facebook and Google auth. Works fine.

BUT, if a user:

signs in with Facebook (is ok)

later, signs in with Google  (is also fine)

later, tries to sign in with Facebook - BOOM! not so fine and Firebase returns this error:

auth/account-exists-with-different-credential

From reading docs and a few posts on SO, we thought the following was correct but clearly not as we're getting the same auth error back.

...error returned by Firebase auth after trying Facebook login...

const email = error.email;
const pendingCred = error.credential;

firebase.auth().fetchProvidersForEmail(email)
.then(providers => {
   //providers returns this array -> ["google.com"]
   firebase.auth().signInWithCredential(pendingCred)
   .then(result => {
       result.user.link(pendingCred)
   })
   .catch(error => log(error))

The call to signInWithCredential is throwing the same error auth/account-exists-with-different-credential.

Can anyone help point out what we are doing wrong with this implementation? Greatly appreciated.

Body:
I've written about how to do this without needing to sign in for a second time here:

https://blog.wedport.co.uk/2020/05/29/react-native-firebase-auth-with-linking/

You need to store the original credential and retrieve to login silently before linking the accounts. Full code in link:

signInOrLink: async function (provider, credential, email) {
  this.saveCredential(provider, credential)
  await auth().signInWithCredential(credential).catch(
    async (error) => {
      try {
        if (error.code != "auth/account-exists-with-different-credential") {
          throw error;
        }
        let methods = await auth().fetchSignInMethodsForEmail(email);
        let oldCred = await this.getCredential(methods[0]);
        let prevUser = await auth().signInWithCredential(oldCred);
        auth().currentUser.linkWithCredential(credential);
      }
      catch (error) {
        throw error;
      }
    }
  );

}


问:
List assignment/creation in Python showing unexpected behaviour
I was playing around with a block of code during which I stumbled upon some unexpected behaviour of Python.

I defined a list as follows:

```<code>a = [1, 2, 3]
</code>```

Made another list with a loop:

```<code>res = (item for item in a if a.count(item) > 0)
print(list(res)) # [1, 2, 3] -- as expected -- Consider this is line 1
</code>```

Then later I changed the initial value of first list:

```<code>a = [7, 2, 9]
</code>```

I was expecting no change in res as the changes I made to a were after res was created, but to my surprise, the value of res was changed.

```<code>print(list(res)) # prints [] -- Consider this as line 2
</code>```

What's more shocking is that the result of print depends on print statement on line 1, if I comment out print statement at line1 then line 2 prints [2]

Can someone please explain me what's going on here?

答:
Okay, I think I get it, I was not creating another list with that loop and I was creating something called generator.

Which can be converted to list only once, that is why it prints [] if I give print statement at line 1.

And it modifies itself according to value of a until it is exhausted.

Body:
I was playing around with a block of code during which I stumbled upon some unexpected behaviour of Python.

I defined a list as follows:

a = [1, 2, 3]

Made another list with a loop:

res = (item for item in a if a.count(item) > 0)
print(list(res)) # [1, 2, 3] -- as expected -- Consider this is line 1

Then later I changed the initial value of first list:

a = [7, 2, 9]

I was expecting no change in res as the changes I made to a were after res was created, but to my surprise, the value of res was changed.

print(list(res)) # prints [] -- Consider this as line 2

What's more shocking is that the result of print depends on print statement on line 1, if I comment out print statement at line1 then line 2 prints [2]

Can someone please explain me what's going on here?


问:
XSLT to remove an element but not its children?
Input:

```<code><req>
  <element>
   <field1>abcd</field1>
   <field2>05/05/2020</field2>
  </element>
</req>
</code>```

Expected Output:

```<code><req>
  <field1>abcd</field1>
  <field2>05/05/2020</field2>
</req>
</code>```

So my requirement is to remove element from the input XML.

答:
Or just:</p>

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/req">
    <xsl:copy>
        <xsl:copy-of select="element/*"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Body:
Input:

<req>
  <element>
   <field1>abcd</field1>
   <field2>05/05/2020</field2>
  </element>
</req>

Expected Output:

<req>
  <field1>abcd</field1>
  <field2>05/05/2020</field2>
</req>

So my requirement is to remove element from the input XML.

Body:
Or just:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/req">
    <xsl:copy>
        <xsl:copy-of select="element/*"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>


问:
Count number of lines in a text file PS Im not allowed to use streamreader
it always outputs the number 2 i dont know if the problem is from the code or from my program :</p>

```<code>        DIM COUNT_LINE AS INTEGER =0
        If Not EOF(1) Then
            FileGet(1, True, RecordNumber:=1)
            COUNT_LINE += 1
        End If
        last_record = COUNT_LINE+1
        TxtItemNumber.Text = last_record
        End If'''
</code>```

答:
```<code>Imports System.IO
</code>```

The above is required for the following

```<code>Private Sub OPCode()
    Dim lines = File.ReadLines("answers.txt")
    Dim count = lines.Count
    MessageBox.Show(count.ToString)
End Sub
</code>```

.ReadLines returns an IEnumerable(Of String) of the lines in the text file. The .Count of the enumerable will give you the count of how many lines are in the array. Can also be the one-liner given by @jmcilhinney in comments.

```<code>Dim count = File.ReadLines("answers.txt").Count
</code>```

Body:
it always outputs the number 2 i dont know if the problem is from the code or from my program :

        DIM COUNT_LINE AS INTEGER =0
        If Not EOF(1) Then
            FileGet(1, True, RecordNumber:=1)
            COUNT_LINE += 1
        End If
        last_record = COUNT_LINE+1
        TxtItemNumber.Text = last_record
        End If'''

Body:
Imports System.IO

The above is required for the following

Private Sub OPCode()
    Dim lines = File.ReadLines("answers.txt")
    Dim count = lines.Count
    MessageBox.Show(count.ToString)
End Sub

.ReadLines returns an IEnumerable(Of String) of the lines in the text file. The .Count of the enumerable will give you the count of how many lines are in the array. Can also be the one-liner given by @jmcilhinney in comments.

Dim count = File.ReadLines("answers.txt").Count


问:
SSRS report subscription not working sometime
We have created 10 to 12 SSRS reports and created subscription for the reports. Sometimes the status of the subscription is showing mail sent but actually we have not received any email. What may be the issue here.</p>

答: Have you ever received mail from that SSRS server? If not, the issue I've had is that Exchange hasn't had "relay for this host" enabled. You will find the error in the SSRS logs.</p>


问:
How to use NavigationLink to detect name of click NavigationView item
How can the destination of a NavigationLink can modified to detect which item within a list was clicked? An if statement of some sort would be very helpful but all items currently do the same thing.

```<code>import SwiftUI

let textTitle = NSLocalizedString("PageTitle", comment: "")
let textItemA = NSLocalizedString("ItemA", comment: "")
let textItemB = NSLocalizedString("ItemB", comment: "")
let textItemC = NSLocalizedString("ItemC", comment: "")

struct ItemMain: Identifiable {
    var id = UUID()
    var name: String
}

let myItems: [MyItem] = [
    MyItem(name: textItemA),
    MyItem(name: textItemB),
    MyItem(name: textItemC)]

struct ContentView: View {
    @State private var showingAlert = false

    var body: some View {
        NavigationView{
            List(myItems) { myItem in
                NavigationLink(destination: MyDetailView(myItem: myItem)) {
                    Text(myItem.name)
                }
            }

            .navigationBarTitle(textTitle)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct MyDetailView: View {
    var myItem: MyItem

    var body: some View {
        Text(myIem.name)
    }
}
</code>```

答:
I customized your MyItem model as it is not provided by you

```<code>enum MyItemType {
    case navigation
    case alert
}

struct MyItem: Identifiable {
    let id = UUID()
    let name: String
    var type: MyItemType = .alert
}
</code>```

And made changed to your ContentView

```<code>struct ContentView: View {
    @State private var showingAlert = false

    var body: some View {
        NavigationView{
            listView
                .navigationBarTitle(textTitle)
        }
        .alert(isPresented: $showingAlert) {
            //Customise your alert according to your need
            Alert(title: Text("Alert"))
        }
    }

    private var listView: some View {
        List(myItems) { myItem in
            if myItem.type == .navigation {
                NavigationLink(destination: MyDetailView(myItem: myItem)) {
                    Text(myItem.name)
                }
            } else {
                Button(action: {
                    self.showingAlert = true
                }) {
                    Text(myItem.name)
                }
            }
        }
    }
}
</code>```

And lastly your myItems array:

```<code>let myItems: [MyItem] = [
    MyItem(name: textItemA, type: MyItemType.navigation),
    MyItem(name: textItemB),
    MyItem(name: textItemC)
]
</code>```

Body:
How can the destination of a NavigationLink can modified to detect which item within a list was clicked? An if statement of some sort would be very helpful but all items currently do the same thing.

import SwiftUI

let textTitle = NSLocalizedString("PageTitle", comment: "")
let textItemA = NSLocalizedString("ItemA", comment: "")
let textItemB = NSLocalizedString("ItemB", comment: "")
let textItemC = NSLocalizedString("ItemC", comment: "")

struct ItemMain: Identifiable {
    var id = UUID()
    var name: String
}

let myItems: [MyItem] = [
    MyItem(name: textItemA),
    MyItem(name: textItemB),
    MyItem(name: textItemC)]

struct ContentView: View {
    @State private var showingAlert = false

    var body: some View {
        NavigationView{
            List(myItems) { myItem in
                NavigationLink(destination: MyDetailView(myItem: myItem)) {
                    Text(myItem.name)
                }
            }

            .navigationBarTitle(textTitle)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct MyDetailView: View {
    var myItem: MyItem

    var body: some View {
        Text(myIem.name)
    }
}

Body:
I customized your MyItem model as it is not provided by you

enum MyItemType {
    case navigation
    case alert
}

struct MyItem: Identifiable {
    let id = UUID()
    let name: String
    var type: MyItemType = .alert
}

And made changed to your ContentView

struct ContentView: View {
    @State private var showingAlert = false

    var body: some View {
        NavigationView{
            listView
                .navigationBarTitle(textTitle)
        }
        .alert(isPresented: $showingAlert) {
            //Customise your alert according to your need
            Alert(title: Text("Alert"))
        }
    }

    private var listView: some View {
        List(myItems) { myItem in
            if myItem.type == .navigation {
                NavigationLink(destination: MyDetailView(myItem: myItem)) {
                    Text(myItem.name)
                }
            } else {
                Button(action: {
                    self.showingAlert = true
                }) {
                    Text(myItem.name)
                }
            }
        }
    }
}

And lastly your myItems array:

let myItems: [MyItem] = [
    MyItem(name: textItemA, type: MyItemType.navigation),
    MyItem(name: textItemB),
    MyItem(name: textItemC)
]


问:
Print table from array in php
I have an array with following format:

```<code>Array
(
    [0] => Array
        (
            [Push to Web] => Yes
            [attribute_set] => laminate_flooring
            [category] => Accessories/Underlay
            [name] => Under Pad Feather Light Foam
            [sku] => 123-1028
            [description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
            [short_description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
            [image] => 123-1028.jpg
            [gallery_Image] => 9095307460638-424-424.jpg
            [price] => 0.24
            [qty_ca] => 16
            [weight] => 3
            [meta_description] => 51-1001
            [meta_title] => Under Pad Feather Light Foam
            [status] => 1
            [flooring_coverage] => 200
            [is_flooring_product] => 1
            [web_price_comparative] => 0.31
        )

    [1] => Array
        (
            [Push to Web] => Yes
            [category] => Accessories
            [name] => Vent Maple Flush 4x10
            [sku] => 089-1000
            [description] => Vent Flush Mount Maple 4 x 10
            [short_description] => Vent Flush Mount Maple 4 x 10
            [image] => 089-1000.jpg
            [price] => 17.05
            [qty_ca] => 63
            [qty_us] => 41
            [meta_description] => 10-1023
            [meta_title] => Vent Maple Flush 4x10
            [status] => 1
            [flooring_coverage] => 1
            [min_order_qty] => 400
            [web_price_comparative] => 22.16
        )
)
</code>```

I have to print the data in the table so that each key of array is printed as column header and the value as column data. That means Push to Web, attribute_set etc will be header and Yes, laminate_flooring will be data respectively.

I wrote the following but its not working.

```<code>$table  = '<table border="1" id="datatable">
<tr>';
foreach($data as $key=>$value){
    $table .= '<td>'.$key.'</td>';
}
$table .= '</tr>';
foreach($data as $value){
    $table .=   '<tr>';
    foreach($value as $innerkey=>$innervalue){
                $table .=   '<td>'.$innervalue.'</td>';
             }
             $table .= '</tr>';
        }
    }
 }
 $table .= '</table>';

 print_r($table);
</code>```

Please help me to sort out the problem. Thanks in advance

答:
You say you get 0,1,2 in the header keys.. etc....

```<code>foreach($data as $key=>$value){
    $table .= '<td>'.$key.'</td>';
}
</code>```

This is because your top level keys are:

```<code>0
1
2
3..
</code>```

In the next level you have these keys:

```<code>Push to Web
Category
Name
etc..
</code>```

In this code snippet you add the innervalue-data (push to web-value, category-value, name-value etc...)...

```<code>foreach($data as $value){
    $table .=   '<tr>';
    foreach($value as $innerkey=>$innervalue){
        $table .= '<td>'.$innervalue.'</td>';
    }
    $table .= '</tr>';
}
</code>```

...these values are on the same level as the key you want. Therefore $innerkey is the key you want to add in the header:

```<code>foreach($data as $value){
    $table .= '<tr>';
    foreach($value as $innerkey=>$innervalue){
        $table .= '<td>'.$innerkey.'</td>';
    }
    $table .= '</tr>';
}
</code>```

So the logic is basically something like this:

```<code>$table  = '<table border="1" id="datatable">';
foreach($data as $key=>$value){
    $table .= '<tr>';
    foreach($value as $innerkey=>$innervalue){
        $table .= '<td>'.$innerkey.'</td>';
    }
    $table .= '</tr>';
}
foreach($data as $value){
    $table .= '<tr>';
    foreach($value as $innerkey=>$innervalue){
        $table .= '<td>'.$innervalue.'</td>';
    }
    $table .= '</tr>';
}
$table .= '</table>';
</code>```

Based on above logic - you can do like this to achieve what you want:

UPDATE

Now that I understand that all keys does not exists in all items. You could do like this:

```<code>//Because you have different keys in different item
//you could recreate each item in the array
//Based on the the $use_keys array here
//(add all keys you want to use and $use_keys set the order of the keys in
//each item!)
$use_keys = ['pushweb', 'attribute set', 'category', 'name'];

//Go through the whole array and recreate it with keys given
//in $use_keys
foreach($data as $key=>$value){

    //Create a new array with key values from array $use_keys
    $new_arr = [];
    foreach($use_keys as $apk_item) {
        //Add key/value to the new array. If value already exist
        //in the $data[key] then use that value, else just empty string
        $new_value = '';
        if (isset($data[$key][$apk_item])) {
            $new_value = $data[$key][$apk_item];
        }
        $new_arr[$apk_item] = $new_value;
    }
    //Recreate the data[key] part of the original data array
    $data[$key] = $new_arr;
}

//Then same code as before
$row = 0;
$table  = '<table border="1" id="datatable">';
foreach($data as $value){
    $table .= '<tr>';
    if ($row == 0) {
        foreach($value as $innerkey=>$innervalue){
            $table .= '<td>'.$innerkey.'</td>';
        }
    }
    $table .= '</tr><tr>';
    foreach($value as $innerkey=>$innervalue){
        $table .= '<td>'.$innervalue.'</td>';
    }
    $table .= '</tr>';
    $row++;
}
$table .= '</table>';
</code>```

Title: Print table from array in php

Body:
I have an array with following format:

Array
(
    [0] => Array
        (
            [Push to Web] => Yes
            [attribute_set] => laminate_flooring
            [category] => Accessories/Underlay
            [name] => Under Pad Feather Light Foam
            [sku] => 123-1028
            [description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
            [short_description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
            [image] => 123-1028.jpg
            [gallery_Image] => 9095307460638-424-424.jpg
            [price] => 0.24
            [qty_ca] => 16
            [weight] => 3
            [meta_description] => 51-1001
            [meta_title] => Under Pad Feather Light Foam
            [status] => 1
            [flooring_coverage] => 200
            [is_flooring_product] => 1
            [web_price_comparative] => 0.31
        )

    [1] => Array
        (
            [Push to Web] => Yes
            [category] => Accessories
            [name] => Vent Maple Flush 4x10
            [sku] => 089-1000
            [description] => Vent Flush Mount Maple 4 x 10
            [short_description] => Vent Flush Mount Maple 4 x 10
            [image] => 089-1000.jpg
            [price] => 17.05
            [qty_ca] => 63
            [qty_us] => 41
            [meta_description] => 10-1023
            [meta_title] => Vent Maple Flush 4x10
            [status] => 1
            [flooring_coverage] => 1
            [min_order_qty] => 400
            [web_price_comparative] => 22.16
        )
)

I have to print the data in the table so that each key of array is printed as column header and the value as column data. That means Push to Web, attribute_set etc will be header and Yes, laminate_flooring will be data respectively.

I wrote the following but its not working.

$table  = '

';
foreach($data as $key=>$value){
    $table .= ''.$key.'	';
}
$table .= '
';
foreach($data as $value){
    $table .=   '
';
    foreach($value as $innerkey=>$innervalue){
                $table .=   ''.$innervalue.'	';
             }
             $table .= '
';
        }
    }
 }
 $table .= '
';

 print_r($table);

Please help me to sort out the problem. Thanks in advance

Body:
You say you get 0,1,2 in the header keys.. etc....

foreach($data as $key=>$value){
    $table .= '<td>'.$key.'</td>';
}

This is because your top level keys are:

0
1
2
3..

In the next level you have these keys:

Push to Web
Category
Name
etc..

In this code snippet you add the innervalue-data (push to web-value, category-value, name-value etc...)...

foreach($data as $value){
    $table .=   '<tr>';
    foreach($value as $innerkey=>$innervalue){
        $table .= '<td>'.$innervalue.'</td>';
    }
    $table .= '</tr>';
}

...these values are on the same level as the key you want. Therefore $innerkey is the key you want to add in the header:

foreach($data as $value){
    $table .= '<tr>';
    foreach($value as $innerkey=>$innervalue){
        $table .= '<td>'.$innerkey.'</td>';
    }
    $table .= '</tr>';
}

So the logic is basically something like this:

$table  = '<table border="1" id="datatable">';
foreach($data as $key=>$value){
    $table .= '<tr>';
    foreach($value as $innerkey=>$innervalue){
        $table .= '<td>'.$innerkey.'</td>';
    }
    $table .= '</tr>';
}
foreach($data as $value){
    $table .= '<tr>';
    foreach($value as $innerkey=>$innervalue){
        $table .= '<td>'.$innervalue.'</td>';
    }
    $table .= '</tr>';
}
$table .= '</table>';

Based on above logic - you can do like this to achieve what you want:

UPDATE

Now that I understand that all keys does not exists in all items. You could do like this:

//Because you have different keys in different item
//you could recreate each item in the array
//Based on the the $use_keys array here
//(add all keys you want to use and $use_keys set the order of the keys in
//each item!)
$use_keys = ['pushweb', 'attribute set', 'category', 'name'];

//Go through the whole array and recreate it with keys given
//in $use_keys
foreach($data as $key=>$value){

    //Create a new array with key values from array $use_keys
    $new_arr = [];
    foreach($use_keys as $apk_item) {
        //Add key/value to the new array. If value already exist
        //in the $data[key] then use that value, else just empty string
        $new_value = '';
        if (isset($data[$key][$apk_item])) {
            $new_value = $data[$key][$apk_item];
        }
        $new_arr[$apk_item] = $new_value;
    }
    //Recreate the data[key] part of the original data array
    $data[$key] = $new_arr;
}

//Then same code as before
$row = 0;
$table  = '<table border="1" id="datatable">';
foreach($data as $value){
    $table .= '<tr>';
    if ($row == 0) {
        foreach($value as $innerkey=>$innervalue){
            $table .= '<td>'.$innerkey.'</td>';
        }
    }
    $table .= '</tr><tr>';
    foreach($value as $innerkey=>$innervalue){
        $table .= '<td>'.$innervalue.'</td>';
    }
    $table .= '</tr>';
    $row++;
}
$table .= '</table>';


问:
pass attribute on click link instead hash
I have a link in my menu. It has an attributte like title=.roc.
When I click on this link, I want to save this attribute and click on element with the same attribute on the destination page.

Page example.com. I click in the next link.

```<code><li class="menu-item"><a title=".roc" href="https://example.com/port/#flash">Roc</a></li>
</code>```

So now, in example.com/port/, it should click the element with title=".roc":

```<code><a id="flash" href="#" title=".roc">ROC2</a>
</code>```

I have this code, but I dont know how pass the attribute instead the hash:

```<code>jQuery(function ($) {
  var activeTab = document.querySelector(location.hash);
  history.replaceState(null, null, ' ');
  window.addEventListener('load', function () {
    if (activeTab) {
      setTimeout(function(){ activeTab.click(); }, 100);
    }
  })
});
</code>```

答:
on the pages you want to hook transfer 'title' from:

```<code>jQuery(function ($) {
  $(document.body).on('click','a[title]', function(event) {
    sessionStorage.setItem('title', event.target.getAttribute('title'));
  });
});
</code>```

then on the other page:

```<code>jQuery(function ($) {
  var activeTab = document.querySelector(`[title="${sessionStorage.getItem('title')}"]`);
  window.addEventListener('load', function (event) {
    if (activeTab) {
      setTimeout(function(){ activeTab.click(); }, 100);
    }
  })
});
</code>```

Body:
I have a link in my menu. It has an attributte like title=.roc.
When I click on this link, I want to save this attribute and click on element with the same attribute on the destination page.

Page example.com. I click in the next link.

Roc

So now, in example.com/port/, it should click the element with title=".roc":

ROC2

I have this code, but I dont know how pass the attribute instead the hash:

jQuery(function ($) {
  var activeTab = document.querySelector(location.hash);
  history.replaceState(null, null, ' ');
  window.addEventListener('load', function () {
    if (activeTab) {
      setTimeout(function(){ activeTab.click(); }, 100);
    }
  })
});

Body:
on the pages you want to hook transfer 'title' from:

jQuery(function ($) {
  $(document.body).on('click','a[title]', function(event) {
    sessionStorage.setItem('title', event.target.getAttribute('title'));
  });
});

then on the other page:

jQuery(function ($) {
  var activeTab = document.querySelector(`[title="${sessionStorage.getItem('title')}"]`);
  window.addEventListener('load', function (event) {
    if (activeTab) {
      setTimeout(function(){ activeTab.click(); }, 100);
    }
  })
});


问:
transfer of pointer from function to function
I have a problem, because while loading data from the console, a bug is popping up I think it's a tricky thing to pass the indicator through the function, but I don't know how to fix it.

```<code>#include<stdio.h>
#include<stdlib.h>

typedef struct rn{
    int n;   /**numerator**/
    unsigned d;    /**denomirator**/
} rationalNumber;

typedef struct dot{
    rationalNumber x;
    rationalNumber y;
} point;

int gcd(int a, int b)
{
  if(b!=0)
    return gcd(b,a%b);

       return a;
}

void input(rationalNumber *a)
{
    int nwd;
    if (scanf("%d/%u",&(a->n), &(a->d)) == 1) a->d=1;
    else
    {
        nwd = abs(gcd(a->n, a->d));
        a->n = a->n/nwd;
        a->d = a->d/nwd;
    }

}

void load_point(point *a, void(*function)(rationalNumber *))
{
    function(&a->x);
    function(&a->y);

}

int main(void)
{

    rationalNumber *z;
    point *a;

    load_point(a, input);

return 0;
}

</code>```

I've got this message : Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

in this place : if (scanf("%d/%u",&(a->n), &(a->d)) == 1) a->d=1;

答:
You're creating pointers that point to nothing in particular and then pass these on to the function which never initializes them, allocates memory for them, and trusts that they're valid, but they're not.

Remember that point* a is a pointer, not an allocation.

An easy solution is to use local variables instead of pointers:

```<code>int main(void)
{
    rationalNumber z;
    point a;

    load_point(&a, input);

    return 0;
}
</code>```

Body:
I have a problem, because while loading data from the console, a bug is popping up I think it's a tricky thing to pass the indicator through the function, but I don't know how to fix it.

#include<stdio.h>
#include<stdlib.h>

typedef struct rn{
    int n;   /**numerator**/
    unsigned d;    /**denomirator**/
} rationalNumber;

typedef struct dot{
    rationalNumber x;
    rationalNumber y;
} point;

int gcd(int a, int b)
{
  if(b!=0)
    return gcd(b,a%b);

       return a;
}

void input(rationalNumber *a)
{
    int nwd;
    if (scanf("%d/%u",&(a->n), &(a->d)) == 1) a->d=1;
    else
    {
        nwd = abs(gcd(a->n, a->d));
        a->n = a->n/nwd;
        a->d = a->d/nwd;
    }

}

void load_point(point *a, void(*function)(rationalNumber *))
{
    function(&a->x);
    function(&a->y);

}

int main(void)
{

    rationalNumber *z;
    point *a;

    load_point(a, input);

return 0;
}

I've got this message : Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

in this place : if (scanf("%d/%u",&(a->n), &(a->d)) == 1) a->d=1;

Body:
You're creating pointers that point to nothing in particular and then pass these on to the function which never initializes them, allocates memory for them, and trusts that they're valid, but they're not.

Remember that point* a is a pointer, not an allocation.

An easy solution is to use local variables instead of pointers:

int main(void)
{
    rationalNumber z;
    point a;

    load_point(&a, input);

    return 0;
}


问:
node-superagent responseType('blob') vs. buffer(true)
Due to the deprecation of request, we're currently rewriting the request-service in our node app with superagent. So far all looks fine, however we're not quite sure how to request binary data/octet-stream and to process the actual response body as a Buffer. According to the docs (on the client side) one should use

```<code>superAgentRequest.responseType('blob');
</code>```

which seems to work fine on NodeJS, but I've also found this github issue where they use

```<code>superAgentRequest.buffer(true);
</code>```

which works just as well. So I'm wondering what the preferred method to request binary data in NodeJS is?

答:
As per documentation https://visionmedia.github.io/superagent/

SuperAgent will parse known response-body data for you, currently supporting application/x-www-form-urlencoded, application/json, and multipart/form-data. You can setup automatic parsing for other response-body data as well:

You can set a custom parser (that takes precedence over built-in parsers) with the .buffer(true).parse(fn) method. If response buffering is not enabled (.buffer(false)) then the response event will be emitted without waiting for the body parser to finish, so response.body won't be available.

So to parse other response types, you will need to set .buffer(true).parse(fn). But if you do not want to parse response then no need to set buffer(true).

Body:
Due to the deprecation of request, we're currently rewriting the request-service in our node app with superagent. So far all looks fine, however we're not quite sure how to request binary data/octet-stream and to process the actual response body as a Buffer. According to the docs (on the client side) one should use

superAgentRequest.responseType('blob');

which seems to work fine on NodeJS, but I've also found this github issue where they use

superAgentRequest.buffer(true);

which works just as well. So I'm wondering what the preferred method to request binary data in NodeJS is?


问:
Python Networkx: edges not taking proper color, while specifying node positions
I am pretty novice in Python and started learning networkx to plot a graph, or road network.
I have to specify, the node positions. The edge color should be dependent on the values of the edges. I tried using pandas dataframe to generate edges. The edge colors work fine when position is not specified.
An example is attached.

When not specifying positions

```<code># Build a dataframe with your connections
df = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C'], 'value':[1, 10, 5, 5]})
df

# Build your graph
G=nx.from_pandas_edgelist(df, 'from', 'to', create_using=nx.Graph() )

# Custom the nodes:
nx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color=df['value'], width=10.0, edge_cmap=plt.cm.Blues)

</code>```

Here the edge colors are perfect

When specifying positions

```<code>pos = {'A': (0,1), 'D': (1,2) , 'B': (2,3) , 'C': (6,5), 'E': (0,0)}

nx.draw(G, pos, with_labels=True, node_color='skyblue', node_size=1500, edge_color=df['value'], width=10.0, edge_cmap=plt.cm.Blues)
</code>```

Here node positions are perfect, but edge colors according to value are wrong:

I also tried putting position like the following -

```<code>df2 = pd.DataFrame({ "Nodes": ['A','D','B','C','E'], "x": [0,1,2,6,0], "y": [1,2,3,5,0]})
for i in df2.index:
    G.add_node(df2.loc[i, "Nodes"], df2=(nodes.loc[i, "x"], df2.loc[i, "y"]))
</code>```

But, the problem in output remains they same.

答:
Indeed as you mention the edge color is determined by the values of the edges, as the edge_color numeric values are mapped to colors through the specified edge_cmap. What is causing confusion here is the specific arrangement of the coordinates, since the edge connecting (A,D) is overlapped by the one connecting (A,B):

```<code>pos = {'A': (0,1), 'D': (1,2) , 'B': (2,3) , 'C': (6,5), 'E': (0,0)}
</code>```

If we slightly change the coordinates of D, you'll see that the edge has the expected color:

```<code>pos = {'A': (0,1), 'D': (4,1) , 'B': (2,3) , 'C': (6,5), 'E': (0,0)}

nx.draw(G, pos,
        with_labels=True,
        node_color='skyblue',
        node_size=1500,
        edge_color=df['value'],
        width=10.0,
        edge_cmap=plt.cm.Blues)
</code>```

Body:
I am pretty novice in Python and started learning networkx to plot a graph, or road network.
I have to specify, the node positions. The edge color should be dependent on the values of the edges. I tried using pandas dataframe to generate edges. The edge colors work fine when position is not specified.
An example is attached.

When not specifying positions

# Build a dataframe with your connections
df = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C'], 'value':[1, 10, 5, 5]})
df

# Build your graph
G=nx.from_pandas_edgelist(df, 'from', 'to', create_using=nx.Graph() )

# Custom the nodes:
nx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color=df['value'], width=10.0, edge_cmap=plt.cm.Blues)

Here the edge colors are perfect

When specifying positions

pos = {'A': (0,1), 'D': (1,2) , 'B': (2,3) , 'C': (6,5), 'E': (0,0)}

nx.draw(G, pos, with_labels=True, node_color='skyblue', node_size=1500, edge_color=df['value'], width=10.0, edge_cmap=plt.cm.Blues)

Here node positions are perfect, but edge colors according to value are wrong:

I also tried putting position like the following -

df2 = pd.DataFrame({ "Nodes": ['A','D','B','C','E'], "x": [0,1,2,6,0], "y": [1,2,3,5,0]})
for i in df2.index:
    G.add_node(df2.loc[i, "Nodes"], df2=(nodes.loc[i, "x"], df2.loc[i, "y"]))

But, the problem in output remains they same.

Body:
Indeed as you mention the edge color is determined by the values of the edges, as the edge_color numeric values are mapped to colors through the specified edge_cmap. What is causing confusion here is the specific arrangement of the coordinates, since the edge connecting (A,D) is overlapped by the one connecting (A,B):

pos = {'A': (0,1), 'D': (1,2) , 'B': (2,3) , 'C': (6,5), 'E': (0,0)}

If we slightly change the coordinates of D, you'll see that the edge has the expected color:

pos = {'A': (0,1), 'D': (4,1) , 'B': (2,3) , 'C': (6,5), 'E': (0,0)}

nx.draw(G, pos,
        with_labels=True,
        node_color='skyblue',
        node_size=1500,
        edge_color=df['value'],
        width=10.0,
        edge_cmap=plt.cm.Blues)


问:
Rectangular Prism Collision
I want to make a game where the character is a rectangular prism that can be rotated, and the rest of the map are axis-aligned rectangular prisms.  Everything other than the character will be static, so I was wondering what would be the best algorithm for finding if the character is colliding with any parts in the map.  Any tutorials/code/advice would be much appreciated :)

Also, the character will only be rotated on the Y axis, if that helps.

答:
In the special case that the character only rotates around its axis parallel to the Y-axis, the collision detection with another axis-aligned rectangular prism reduces to:

Check if the character's Y-interval intersects the other prism's Y-interval.

Check if the corresponding XZ-cross-sections of the two prisms intersect, which amounts to a problem of collision detection between two rotated rectangles.

If the answer to both the above is yes, then and only then do the prisms overlap.

Having reduced the particular problem to that of overlapping intervals and intersecting (rotated) rectangles, there are a number of good code resources for each of these tasks.  The first task is pretty trivial:

Overlapping intervals

Two closed intervals [a,b] and [c,d] intersect if and only c ≤ b and a ≤ d.  Here we also assume the intervals' notation is consistent, i.e. that a ≤ b and c ≤ d (otherwise swap the endpoints as necessary to make it so).

Intersecting rotated rectangles

A highly rated SO answer to this specific question is here.  A Lua implementation I wrote for a slightly more general problem, Shortest distance between two rectangles, includes "early exit" optimizations (bounding circle and vertex in rectangle) that I mentioned on this thread.  My Lua code returns "false" if the rotated rectangles intersect, otherwise the distance between them.  For Java purposes the return value of zero in the collision cases would serve.

Title: Rectangular Prism Collision