问:
How can I make my visual studio 2017 project NOT a test project while still referencing NUnit
I have a library with unittest helper classes. I reference NUnit in this project but now Visual Studio thinks this project is a test project and complains that there are no tests discovered. This project is not meant to be a test project, just a regular .net standard library that references NUnit.

I want to "convince" visual studio that this is NOT a test project.
Any idea's?

Technical details: the project is a .Net Standard 2.0 project and I reference the following NuGet packages:

Moq 4.10.0

Moq.AutoMock 1.2.0.111

NUnit 3.10.1

I use Visual Studio 2017 Enterprise version 15.8.4

An example of what this library is for:

```<code>  public abstract class AutoMockerTestBase
  {
     protected AutoMocker AutoMocker { get; private set; }

     [SetUp]
     public virtual void SetUp()
     {
        AutoMocker = new AutoMocker(MockBehavior.Strict);
     }

     [TearDown]
     public virtual void TearDown()
     {
        AutoMocker.VerifyAll();
     }
  }
</code>```

To reproduce the problem:

Add a .net standard2.0 class library project to a solution.

Reference NUnit

Now notice the visual studio changes the project icon to a test project.

Help me find a way to have visual studio NOT think this project is a test project, and make sure that vs does not try to discover tests in this project.

EDIT: Looking through the "Tests" output I found this:

```<code>[16/09/2018 10:12:55 Warning] Exception NUnit.Engine.NUnitEngineException, Exception thrown discovering tests in C:\Users\me\Source\Repos\Shared\src\UnitTestHelpers\bin\Debug\netstandard2.0\Shared.UnitTestHelpers.dll
[16/09/2018 10:12:55 Warning] An exception occurred in the driver while loading tests.
[16/09/2018 10:12:55 Warning]    at NUnit.Engine.Runners.DirectTestRunner.LoadDriver(IFrameworkDriver driver, String testFile, TestPackage subPackage)
   at NUnit.Engine.Runners.DirectTestRunner.LoadPackage()
   at NUnit.Engine.Runners.TestDomainRunner.LoadPackage()
   at NUnit.Engine.Runners.DirectTestRunner.EnsurePackageIsLoaded()
   at NUnit.Engine.Runners.DirectTestRunner.Explore(TestFilter filter)
   at NUnit.Engine.Runners.MasterTestRunner.Explore(TestFilter filter)
   at NUnit.VisualStudio.TestAdapter.NUnit3TestDiscoverer.DiscoverTests(IEnumerable`1 sources, IDiscoveryContext discoveryContext, IMessageLogger messageLogger, ITestCaseDiscoverySink discoverySink) in D:\repos\nunit\nunit3-vs-adapter\src\NUnitTestAdapter\NUnit3TestDiscoverer.cs:line 90
[16/09/2018 10:12:55 Warning] Innerexception: System.IO.FileNotFoundException: Could not load file or assembly 'nunit.framework' or one of its dependencies. The system cannot find the file specified.
File name: 'nunit.framework'
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Activator.CreateInstance(String assemblyString, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo)
   at System.AppDomain.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   at NUnit.Engine.Drivers.NUnit3FrameworkDriver.CreateObject(String typeName, Object[] args)
   at NUnit.Engine.Drivers.NUnit3FrameworkDriver.Load(String testAssemblyPath, IDictionary`2 settings)
   at NUnit.Engine.Runners.DirectTestRunner.LoadDriver(IFrameworkDriver driver, String testFile, TestPackage subPackage)
</code>```

答:
Inside the .csproj file you should be able to add the following:

```<code><PropertyGroup>
  <IsTestProject>false<IsTestProject>
</PropertyGroup>
</code>```

This has worked for me with libraries referencing XUnit that aren't test libraries and it should work for NUnit as well.

Body:
I have a library with unittest helper classes. I reference NUnit in this project but now Visual Studio thinks this project is a test project and complains that there are no tests discovered. This project is not meant to be a test project, just a regular .net standard library that references NUnit.

I want to "convince" visual studio that this is NOT a test project.
Any idea's?

Technical details: the project is a .Net Standard 2.0 project and I reference the following NuGet packages:

Moq 4.10.0

Moq.AutoMock 1.2.0.111

NUnit 3.10.1

I use Visual Studio 2017 Enterprise version 15.8.4

An example of what this library is for:

  public abstract class AutoMockerTestBase
  {
     protected AutoMocker AutoMocker { get; private set; }

     [SetUp]
     public virtual void SetUp()
     {
        AutoMocker = new AutoMocker(MockBehavior.Strict);
     }

     [TearDown]
     public virtual void TearDown()
     {
        AutoMocker.VerifyAll();
     }
  }

To reproduce the problem:

Add a .net standard2.0 class library project to a solution.

Reference NUnit

Now notice the visual studio changes the project icon to a test project.

Help me find a way to have visual studio NOT think this project is a test project, and make sure that vs does not try to discover tests in this project.

EDIT: Looking through the "Tests" output I found this:

[16/09/2018 10:12:55 Warning] Exception NUnit.Engine.NUnitEngineException, Exception thrown discovering tests in C:\Users\me\Source\Repos\Shared\src\UnitTestHelpers\bin\Debug\netstandard2.0\Shared.UnitTestHelpers.dll
[16/09/2018 10:12:55 Warning] An exception occurred in the driver while loading tests.
[16/09/2018 10:12:55 Warning]    at NUnit.Engine.Runners.DirectTestRunner.LoadDriver(IFrameworkDriver driver, String testFile, TestPackage subPackage)
   at NUnit.Engine.Runners.DirectTestRunner.LoadPackage()
   at NUnit.Engine.Runners.TestDomainRunner.LoadPackage()
   at NUnit.Engine.Runners.DirectTestRunner.EnsurePackageIsLoaded()
   at NUnit.Engine.Runners.DirectTestRunner.Explore(TestFilter filter)
   at NUnit.Engine.Runners.MasterTestRunner.Explore(TestFilter filter)
   at NUnit.VisualStudio.TestAdapter.NUnit3TestDiscoverer.DiscoverTests(IEnumerable`1 sources, IDiscoveryContext discoveryContext, IMessageLogger messageLogger, ITestCaseDiscoverySink discoverySink) in D:\repos\nunit\nunit3-vs-adapter\src\NUnitTestAdapter\NUnit3TestDiscoverer.cs:line 90
[16/09/2018 10:12:55 Warning] Innerexception: System.IO.FileNotFoundException: Could not load file or assembly 'nunit.framework' or one of its dependencies. The system cannot find the file specified.
File name: 'nunit.framework'
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Activator.CreateInstance(String assemblyString, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo)
   at System.AppDomain.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   at NUnit.Engine.Drivers.NUnit3FrameworkDriver.CreateObject(String typeName, Object[] args)
   at NUnit.Engine.Drivers.NUnit3FrameworkDriver.Load(String testAssemblyPath, IDictionary`2 settings)
   at NUnit.Engine.Runners.DirectTestRunner.LoadDriver(IFrameworkDriver driver, String testFile, TestPackage subPackage)

Body:
Inside the .csproj file you should be able to add the following:

<PropertyGroup>
  <IsTestProject>false<IsTestProject>
</PropertyGroup>

This has worked for me with libraries referencing XUnit that aren't test libraries and it should work for NUnit as well.


来源: stackexchange

问:
Resolving Web Site Project References
I have an ASP.NET web site (not web project). It somehow stores references to the other projects in the solution. At build time it needs to copy them over.

I'm trying to reproduce this in an MSBuild script. I know normal references are handled by refresh files and that's good and working.

How can I get the DLL files for the project references (and their dependencies)?

答:
For website projects, the easiest way is to add a Web Deployment project to your solution.
This is a special project type (available from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0AA30AE8-C73B-4BDD-BB1B-FE697256C459) that mimics the "Publish" action in Visual Studio.

Once you've added it to your solution, you can then call MSBUILD.EXE to compile your web site and all of its dependencies:

```<code>C:\Windows\Microsoft.NET\Framework\v2.0.50727\MSBUILD C:\MyWebSite\MyWebSiteDeployProj\MyWebSiteDeployProj.wdproj /target:Clean;Rebuild
</code>```

ContentLicense: CC BY-SA 3.0

Title: Resolving Web Site Project References

Body:
For website projects, the easiest way is to add a Web Deployment project to your solution.
This is a special project type (available from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0AA30AE8-C73B-4BDD-BB1B-FE697256C459) that mimics the "Publish" action in Visual Studio.

Once you've added it to your solution, you can then call MSBUILD.EXE to compile your web site and all of its dependencies:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\MSBUILD C:\MyWebSite\MyWebSiteDeployProj\MyWebSiteDeployProj.wdproj /target:Clean;Rebuild


问:
How can I install libgfortran3 in Ubuntu/Lubuntu 20.04?
I'm using jBlas and it require libgfortran3 and tell me to install it from:

```<code>sudo apt-get install libgfortran3
</code>```

But I'm using Lubuntu 20.04, which use the same packages as Ubuntu 20.04. I can't find the package here
https://packages.ubuntu.com/search?keywords=libgfortran3

So what should I do?

答:
In short, libgfortran3 is no longer supported in Ubuntu 20.04. It depends on an older version of gcc which is no longer maintained in this version of the distribution.

As an alternative, you might want to try installing its successor package with:

```<code>sudo apt-get install libgfortran5
</code>```

It will provide these files for your Ubuntu installation:

```<code>/usr/lib/x86_64-linux-gnu/libgfortran.so.5
/usr/lib/x86_64-linux-gnu/libgfortran.so.5.0.0
/usr/share/doc/libgfortran5
</code>```

This way, you have an option of dynamically loading/linking against libgfortran at runtime.

Hope it helps.

ContentLicense: CC BY-SA 4.0

Body:
I'm using jBlas and it require libgfortran3 and tell me to install it from:

sudo apt-get install libgfortran3

But I'm using Lubuntu 20.04, which use the same packages as Ubuntu 20.04. I can't find the package here
https://packages.ubuntu.com/search?keywords=libgfortran3

So what should I do?

Body:
In short, libgfortran3 is no longer supported in Ubuntu 20.04. It depends on an older version of gcc which is no longer maintained in this version of the distribution.

As an alternative, you might want to try installing its successor package with:

sudo apt-get install libgfortran5

It will provide these files for your Ubuntu installation:

/usr/lib/x86_64-linux-gnu/libgfortran.so.5
/usr/lib/x86_64-linux-gnu/libgfortran.so.5.0.0
/usr/share/doc/libgfortran5

This way, you have an option of dynamically loading/linking against libgfortran at runtime.

Hope it helps.


问:
accessing state inside calculatestate from componentdidmount
I am new to flux and react and I would like to know how can I access state inside calculatestate() from
componentdidmount()?

how can I access events state inside componentdidmount()? I would like loop through events and then run a query per event, which in turn updates another store.

```<code>static getStores() {
  return [SomeStore];
}
static calculateState(prevState, props) {
  const somestore = SomeStore.getState();

  return {
    events: SomeStore.getState(),
  };
}

componentdidmount(){

  //this.state.events;
  //need to do some query based on the events
  //this query will update another store.
}
</code>```

答:
You need to use the lifecycle methods to understand the componentDidMount method which are outlined here

To initialise the localstate, you should use the constructor method (static can also be used as an alternative, but jsfiddle throws an error.

To show the initial state, you can log within componentDidMount with this.state.

const someStore = ["event"];

class TodoApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = { events: someStore };
  }

  // if you want to change state based on props
  shouldComponentUpdate(nextProps, nextState) {
    // change state if you want here
    if (this.state.events.length !== nextState.events.length) {
      console.log(this.state, nextState)
      return true // update
    }

    return false
  }

  // get initial state
  componentDidMount() {
    console.log(this.state.events);
  }

  render() {
    return (

        example
        <button onClick = {() => {
          this.setState(state => {
            return {
              events: [...state.events, "new event"]
            }
          })
        }}>Add Event</button>

          events: { JSON.stringify(this.state.events) }

    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}</code>```

```

Body:
I am new to flux and react and I would like to know how can I access state inside calculatestate() from
componentdidmount()?

how can I access events state inside componentdidmount()? I would like loop through events and then run a query per event, which in turn updates another store.

static getStores() {
  return [SomeStore];
}
static calculateState(prevState, props) {
  const somestore = SomeStore.getState();

  return {
    events: SomeStore.getState(),
  };
}

componentdidmount(){

  //this.state.events;
  //need to do some query based on the events
  //this query will update another store.
}

Body:
You need to use the lifecycle methods to understand the componentDidMount method which are outlined here

To initialise the localstate, you should use the constructor method (static can also be used as an alternative, but jsfiddle throws an error.

To show the initial state, you can log within componentDidMount with this.state.

const someStore = ["event"];

class TodoApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = { events: someStore };
  }

  // if you want to change state based on props
  shouldComponentUpdate(nextProps, nextState) {
    // change state if you want here
    if (this.state.events.length !== nextState.events.length) {
      console.log(this.state, nextState)
      return true // update
    }

    return false
  }

  // get initial state
  componentDidMount() {
    console.log(this.state.events);
  }

  render() {
    return (
      <div>
        <span>example</span>
        <button onClick = {() => {
          this.setState(state => {
            return {
              events: [...state.events, "new event"]
            }
          })
        }}>Add Event</button>

        <div>
          events: { JSON.stringify(this.state.events) }
        </div>
      </div>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"));

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>


问:
Can a java class object be a state variable in another class?
Let's say I have a Car class in Java and then I make another class called ElectricCar. Can a Car object be a state variable in my ElectricCar class?</p>

答:
Yes; and it's quite common:</p>

```<code>class Car {
}

class ElectricCar {
    private final Car car;

    ElectricCar(Car car) {
        this.car = car;
    }

}
</code>```

Body:
Yes; and it's quite common:

class Car {
}

class ElectricCar {
    private final Car car;

    ElectricCar(Car car) {
        this.car = car;
    }

}


问:
Visual Studio does not show errors in the code anymore
I've been using Visual Studio (2017) for quite a long time now, to program mostly in C#, for Unity games. Recently though, I noticed that it was not displaying any errors in the code anymore, or at least most of them. I initially started making some small tests, for example removing variables that were being used multiple times in the scripts. Visual Studio was not showing any errors, while when going back to Unity, it was showing all the correct errors in the console (as always). Instead, if I tried to remove a parenthese, it was, after a bit, showing errors all over the place. Again, it was really strange.

After one day, I was still testing, and I noticed that if I first opened Visual Studio, and then in "recent" I clicked on the the .sln file, that opened all the scripts for one Unity project, it was immediately showing all the right errors, like it had always done and how (I think) it should always do. I started looking for some differences between what I was seeing there, and what I was seeing when opening the .cs files (in the way that wasn't working):

At the top, I wasn't seeing "Debug" and "Any CPU" how I was when it was working:

Another thing was that, between the "Project" and the "Debug" buttons (at the top, that open the drop-down lists), I didn't have the "Compile" button.

Also, under the the "Debug" drop-down many options like "start debug" were not available / disabled.

At the top left, under the left-most script name, I have "External files" instead of "Assembly-CSharp"

At the right of where there should be "Debug" and "Any CPU", I have "Connect" instead of "Start" (Or something similar, my system's language is not english, these are translations)

Another (maybe less relevant) thing that has changed from before, when it was working:

I have installed Visual Studio 2019, and uninstalled after a few minutes (I've always preferred Visual Studio 2017!).

Programming without seeing the errors realtime takes much more time, so I'd really like to fix this problem, if it is possible to do so. Is there anything that I have to activate? Did I accidentally press a combination of keys?

Thanks in advance! :)

答:
You need to turn on the underline errors in the editor options in Visual Studio.

These options can be found here:

Tools > Options > Text Editor > C# > Advanced > Editor Help


问:
Can I end an activity and start a new one from a fragment switch case?
I am working in android studio.I have a  bottom-navigation fragment. For the last switch case, I need a button to navigate to the HomeActivity (home screen). I tried:

...

```<code>  case SUMMARY:
             navNextText.setText(R.string.end);
             navNextImageView.setOnClickListener(v -> navigateHome());
             navNextText.setOnClickListener(v -> navigateHome());
             break;

        default:
            Log.w(TAG, "Executing a default case in navigateNext(). CTX: " + contextState.toString());
    }

 private void navigateHome() {
    Objects.requireNonNull(getActivity()).finish();
    Intent in = new Intent(getActivity(), HomeActivity.class);
    startActivity(in);
}
</code>```

This works to an extent. I can navigate home, but when I click back into the activity that the navigation fragment resides, the navigation bar resumes where it was previous to changing activity.
I have also tried adding onStop() and onDestroy to private void navigateHome, but that seemed to do nothing.
I am just wondering what is the cleaner way to close an activity from a fragment and start a new one.

答:
just add finish() if you want to remove the current activity from the backstack
As you're in a fragment, use requireActivity().finish()

Also to make sure you have no activities in back stack, you can remove all using below intent flag

```<code> private void navigateHome() {
    Objects.requireNonNull(getActivity()).finish();
    Intent in = new Intent(getActivity(), HomeActivity.class);
    in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // <<<<< flag
    startActivity(in);
    requireActivity().finish(); // <<< finish the current activity
}

</code>```

Body:
I am working in android studio.I have a  bottom-navigation fragment. For the last switch case, I need a button to navigate to the HomeActivity (home screen). I tried:

...

  case SUMMARY:
             navNextText.setText(R.string.end);
             navNextImageView.setOnClickListener(v -> navigateHome());
             navNextText.setOnClickListener(v -> navigateHome());
             break;

        default:
            Log.w(TAG, "Executing a default case in navigateNext(). CTX: " + contextState.toString());
    }

 private void navigateHome() {
    Objects.requireNonNull(getActivity()).finish();
    Intent in = new Intent(getActivity(), HomeActivity.class);
    startActivity(in);
}

This works to an extent. I can navigate home, but when I click back into the activity that the navigation fragment resides, the navigation bar resumes where it was previous to changing activity.
I have also tried adding onStop() and onDestroy to private void navigateHome, but that seemed to do nothing.
I am just wondering what is the cleaner way to close an activity from a fragment and start a new one.

Body:
just add finish() if you want to remove the current activity from the backstack
As you're in a fragment, use requireActivity().finish()

Also to make sure you have no activities in back stack, you can remove all using below intent flag

 private void navigateHome() {
    Objects.requireNonNull(getActivity()).finish();
    Intent in = new Intent(getActivity(), HomeActivity.class);
    in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // <<<<< flag
    startActivity(in);
    requireActivity().finish(); // <<< finish the current activity
}


问:
kivy dropdown menu in FloatLayout and GridLayout doesnt show up
Hey guys trying to create an app with a dropdown button but it seems to not work (the full app has GridLayout with 7 rows and this FloatLayout in the example is one of the rows) I've tried with GridLayout, BoxLayout, and FloatLayout and still doesn't appear on the app. Any ideas what's wrong here?

.py file

```<code>class WindowManager(ScreenManager, Screen):
    TestMe = ObjectProperty(None)

text_lists = ['hi', 'nice one', 'another one']

class TestMe(Screen, FloatLayout):
    global text_lists
    main_button = ObjectProperty(None)
    selected_list = 'SELECTED'
    top_layout = ObjectProperty(None)
    top_layout = GridLayout(cols=4)

    def __init__(self, **kwargs):
        super(TestMe, self).__init__(**kwargs)
        self.dropdown = DropDown()
        self.create_drop_down()
        self.create_go_button()

    def create_drop_down(self):
        for list_name in text_lists:
            # When adding widgets, we need to specify the height manually
            # (disabling the size_hint_y) so the dropdown can calculate
            # the area it needs.

            btn = Button(text= list_name, size_hint_y=None, height=88, width=400, background_color=(41/255, 21/255, 228/255, 1))

            # for each button, attach a callback that will call the select() method
            # on the dropdown. We'll pass the text of the button as the data of the
            # selection.
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text),
                     on_press=lambda btn: self.select_list(btn.text))

            # then add the button inside the dropdown
            self.dropdown.add_widget(btn)

        # create a big main button
        self.main_button = Button(text='Choose A List', size_hint=(None, None), height=88, width=400, background_color=(41/255, 21/255, 228/255, 1))

        # show the dropdown menu when the main button is released
        # note: all the bind() calls pass the instance of the caller (here, the
        # mainbutton instance) as the first argument of the callback (here,
        # dropdown.open.).
        self.main_button.bind(on_release=self.dropdown.open)

        # one last thing, listen for the selection in the dropdown list and
        # assign the data to the button text.
        self.dropdown.bind(on_select=lambda instance, x: setattr(self.main_button, 'text', x))
        self.top_layout.add_widget(self.main_button)

    def create_go_button(self):
        go_btn = Button(text="Go!", size_hint=(None, None), height=88, width=400, background_color=(41/255, 21/255, 228/255, 1))
        self.top_layout.add_widget(go_btn)

    def select_list(self, selected):
        self.selected_list = selected

class MyTest(App):
    def build(self):
        return kv

if __name__ == '__main__':
    kv = Builder.load_file('test_kv.kv')

    MyTest().run()
</code>```

test_kv.kv file

```<code>WindowManager:
    TestMe:

<TestMe>:
name: "testy"
id: testy
top_layout: top_layout
FloatLayout:
    Label:
        text: 'Test Screen'
        font: 'Aharoni'
        font_size: 24
        pos_hint: {"left": 0.45, "y": 0.45}
    GridLayout:
        pos_hint: {"top": 0.9}
        size_hint: 1, 0.8
        rows: 2
        spacing: 10
        padding: 10
        GridLayout:
            id: top_layout
            cols: 4
            Button:
                text: "Fun!"
            Label:
                text: "This is a test"
        Button:
            text: "Run!"
</code>```

答:
The problem is that you are calling create_drop_down() and create_go_button() in the __init__() method of the TestMe class. Since you also define a <TestMe>: rule in your kv, there is a conflict. According to the somewhat unclear documentation, the kv rule is applied after the __init__() is run. That means that any Widgets added to TestMe in its __init__() will be overwritten by the Widegets specified in the kv rule. The possible solutions are to add all the children of TestMe in either the __init__() method or in the kv, or to move the adding of Widgets out of the __init__() method. Here is a modified version of your code that does the latter approach:

```<code>class WindowManager(ScreenManager, Screen):
    TestMe = ObjectProperty(None)

text_lists = ['hi', 'nice one', 'another one']

class TestMe(Screen, FloatLayout):
    global text_lists
    main_button = ObjectProperty(None)
    selected_list = 'SELECTED'
    top_layout = ObjectProperty(None)
    #top_layout = GridLayout(cols=4)

    def __init__(self, **kwargs):
        super(TestMe, self).__init__(**kwargs)
        self.dropdown = DropDown()
        Clock.schedule_once(self.create_drop_down)
        Clock.schedule_once(self.create_go_button)
        # self.create_drop_down()
        # self.create_go_button()

    def create_drop_down(self, *args):
        for list_name in text_lists:
            # When adding widgets, we need to specify the height manually
            # (disabling the size_hint_y) so the dropdown can calculate
            # the area it needs.

            btn = Button(text= list_name, size_hint_y=None, height=88, width=400, background_color=(41/255, 21/255, 228/255, 1))

            # for each button, attach a callback that will call the select() method
            # on the dropdown. We'll pass the text of the button as the data of the
            # selection.
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text),
                     on_press=lambda btn: self.select_list(btn.text))

            # then add the button inside the dropdown
            self.dropdown.add_widget(btn)

        # create a big main button
        # self.main_button = Button(text='Choose A List', size_hint=(None, None), height=88, width=400, background_color=(41/255, 21/255, 228/255, 1))
        self.main_button = Button(text='Choose A List', background_color=(41/255, 21/255, 228/255, 1))

        # show the dropdown menu when the main button is released
        # note: all the bind() calls pass the instance of the caller (here, the
        # mainbutton instance) as the first argument of the callback (here,
        # dropdown.open.).
        self.main_button.bind(on_release=self.dropdown.open)

        # one last thing, listen for the selection in the dropdown list and
        # assign the data to the button text.
        self.dropdown.bind(on_select=lambda instance, x: setattr(self.main_button, 'text', x))
        self.top_layout.add_widget(self.main_button)

    def create_go_button(self, *args):
        # go_btn = Button(text="Go!", size_hint=(None, None), height=88, width=400, background_color=(41/255, 21/255, 228/255, 1))
        go_btn = Button(text="Go!", background_color=(41/255, 21/255, 228/255, 1))
        self.top_layout.add_widget(go_btn)

    def select_list(self, selected):
        self.selected_list = selected

class MyTest(App):
    def build(self):
        return kv
</code>```

I have modified the code to call the create methods using Clock.schedule_once(), so that it happens after the kv rule is applied.
I have also removed the size_hint and size  arguments to the Buttons created to allow the GridLayout to size them. I have also commented out some unnecessary code.

Body:
Hey guys trying to create an app with a dropdown button but it seems to not work (the full app has GridLayout with 7 rows and this FloatLayout in the example is one of the rows) I've tried with GridLayout, BoxLayout, and FloatLayout and still doesn't appear on the app. Any ideas what's wrong here?

.py file

class WindowManager(ScreenManager, Screen):
    TestMe = ObjectProperty(None)

text_lists = ['hi', 'nice one', 'another one']

class TestMe(Screen, FloatLayout):
    global text_lists
    main_button = ObjectProperty(None)
    selected_list = 'SELECTED'
    top_layout = ObjectProperty(None)
    top_layout = GridLayout(cols=4)

    def __init__(self, **kwargs):
        super(TestMe, self).__init__(**kwargs)
        self.dropdown = DropDown()
        self.create_drop_down()
        self.create_go_button()

    def create_drop_down(self):
        for list_name in text_lists:
            # When adding widgets, we need to specify the height manually
            # (disabling the size_hint_y) so the dropdown can calculate
            # the area it needs.

            btn = Button(text= list_name, size_hint_y=None, height=88, width=400, background_color=(41/255, 21/255, 228/255, 1))

            # for each button, attach a callback that will call the select() method
            # on the dropdown. We'll pass the text of the button as the data of the
            # selection.
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text),
                     on_press=lambda btn: self.select_list(btn.text))

            # then add the button inside the dropdown
            self.dropdown.add_widget(btn)

        # create a big main button
        self.main_button = Button(text='Choose A List', size_hint=(None, None), height=88, width=400, background_color=(41/255, 21/255, 228/255, 1))

        # show the dropdown menu when the main button is released
        # note: all the bind() calls pass the instance of the caller (here, the
        # mainbutton instance) as the first argument of the callback (here,
        # dropdown.open.).
        self.main_button.bind(on_release=self.dropdown.open)

        # one last thing, listen for the selection in the dropdown list and
        # assign the data to the button text.
        self.dropdown.bind(on_select=lambda instance, x: setattr(self.main_button, 'text', x))
        self.top_layout.add_widget(self.main_button)

    def create_go_button(self):
        go_btn = Button(text="Go!", size_hint=(None, None), height=88, width=400, background_color=(41/255, 21/255, 228/255, 1))
        self.top_layout.add_widget(go_btn)

    def select_list(self, selected):
        self.selected_list = selected

class MyTest(App):
    def build(self):
        return kv

if __name__ == '__main__':
    kv = Builder.load_file('test_kv.kv')

    MyTest().run()

test_kv.kv file

WindowManager:
    TestMe:

<TestMe>:
name: "testy"
id: testy
top_layout: top_layout
FloatLayout:
    Label:
        text: 'Test Screen'
        font: 'Aharoni'
        font_size: 24
        pos_hint: {"left": 0.45, "y": 0.45}
    GridLayout:
        pos_hint: {"top": 0.9}
        size_hint: 1, 0.8
        rows: 2
        spacing: 10
        padding: 10
        GridLayout:
            id: top_layout
            cols: 4
            Button:
                text: "Fun!"
            Label:
                text: "This is a test"
        Button:
            text: "Run!"

Body:
The problem is that you are calling create_drop_down() and create_go_button() in the __init__() method of the TestMe class. Since you also define a <TestMe>: rule in your kv, there is a conflict. According to the somewhat unclear documentation, the kv rule is applied after the __init__() is run. That means that any Widgets added to TestMe in its __init__() will be overwritten by the Widegets specified in the kv rule. The possible solutions are to add all the children of TestMe in either the __init__() method or in the kv, or to move the adding of Widgets out of the __init__() method. Here is a modified version of your code that does the latter approach:

class WindowManager(ScreenManager, Screen):
    TestMe = ObjectProperty(None)

text_lists = ['hi', 'nice one', 'another one']

class TestMe(Screen, FloatLayout):
    global text_lists
    main_button = ObjectProperty(None)
    selected_list = 'SELECTED'
    top_layout = ObjectProperty(None)
    #top_layout = GridLayout(cols=4)

    def __init__(self, **kwargs):
        super(TestMe, self).__init__(**kwargs)
        self.dropdown = DropDown()
        Clock.schedule_once(self.create_drop_down)
        Clock.schedule_once(self.create_go_button)
        # self.create_drop_down()
        # self.create_go_button()

    def create_drop_down(self, *args):
        for list_name in text_lists:
            # When adding widgets, we need to specify the height manually
            # (disabling the size_hint_y) so the dropdown can calculate
            # the area it needs.

            btn = Button(text= list_name, size_hint_y=None, height=88, width=400, background_color=(41/255, 21/255, 228/255, 1))

            # for each button, attach a callback that will call the select() method
            # on the dropdown. We'll pass the text of the button as the data of the
            # selection.
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text),
                     on_press=lambda btn: self.select_list(btn.text))

            # then add the button inside the dropdown
            self.dropdown.add_widget(btn)

        # create a big main button
        # self.main_button = Button(text='Choose A List', size_hint=(None, None), height=88, width=400, background_color=(41/255, 21/255, 228/255, 1))
        self.main_button = Button(text='Choose A List', background_color=(41/255, 21/255, 228/255, 1))

        # show the dropdown menu when the main button is released
        # note: all the bind() calls pass the instance of the caller (here, the
        # mainbutton instance) as the first argument of the callback (here,
        # dropdown.open.).
        self.main_button.bind(on_release=self.dropdown.open)

        # one last thing, listen for the selection in the dropdown list and
        # assign the data to the button text.
        self.dropdown.bind(on_select=lambda instance, x: setattr(self.main_button, 'text', x))
        self.top_layout.add_widget(self.main_button)

    def create_go_button(self, *args):
        # go_btn = Button(text="Go!", size_hint=(None, None), height=88, width=400, background_color=(41/255, 21/255, 228/255, 1))
        go_btn = Button(text="Go!", background_color=(41/255, 21/255, 228/255, 1))
        self.top_layout.add_widget(go_btn)

    def select_list(self, selected):
        self.selected_list = selected

class MyTest(App):
    def build(self):
        return kv

I have modified the code to call the create methods using Clock.schedule_once(), so that it happens after the kv rule is applied.
I have also removed the size_hint and size  arguments to the Buttons created to allow the GridLayout to size them. I have also commented out some unnecessary code.


问:
PX Transform Routine compile issues
I have a transformer routine written in C++ that is set to clear all whitespace and map to a value if the input string is either null or empty. The c++ code compiles and has tested properly, but I am having trouble getting the routine to work in Datastage.

As per instructions, I have copied the exact compiler options that I have in my DS Environment as below.

```<code>g++ -c -O -fPIC -Wno-deprecated -m64 -mtune=generic -mcmodel=small BlankToValue.cpp
g++ -shared -m64 BlankToValue.so BlankToValue.o
</code>```

When testing the routine in a job however I get the following error.

Sequential_File_36,0: Internal Error: (shbuf): iomgr/iomgr.C: 2649

Is there a different set of options I should be using for compilation?

For reference, the c++ code.

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

char * BlankToValue(char *InStr, char *RepStr)
{
    if (InStr[0] == '\0')                           // Check for null pointer at first character of input string.
    {
        return RepStr;                              // Return replacement string if true. This is to prevent unnecessary processing.
    } else
    {
        const char* checkstr = InStr;               // Establish copy of inputstring stored in checkstring.
        do {                                        // Start outer loop.
            while (isspace(*checkstr)) {            // Inner loop while current checkstring byte is whitespace.
                ++checkstr;                         // Increment to next checkstring byte.
            }
        } while ((*InStr++ = *checkstr++));         // Set inputstring byte to current checkstring and iterate both. Breaks when either string evaluates to null.
        *InStr = '\0';                              // Set null terminator for input string at current byte location.
        if (InStr[0] == '\0')                       // Checks first character of cleaned input string for null pointer.
        {
            return RepStr;                          // Return replacement string if true.
        } else
        {
            return InStr;                           // Return new input string if false.
        }
    }
}
</code>```

答:
After a day or two of multiple attempts to try different compile and code approaches I found the solution to my problem. The below code was throwing a segmentation fault when passed a null column. Which makes sense in retrospect.

```<code>if (InStr[0] == '\0')
</code>```

It has been corrected to the below and now everything works properly.

```<code>if ((InStr == NULL) || (InStr[0] == '\0'))
</code>```

Title: PX Transform Routine compile issues

Body:
I have a transformer routine written in C++ that is set to clear all whitespace and map to a value if the input string is either null or empty. The c++ code compiles and has tested properly, but I am having trouble getting the routine to work in Datastage.

As per instructions, I have copied the exact compiler options that I have in my DS Environment as below.

g++ -c -O -fPIC -Wno-deprecated -m64 -mtune=generic -mcmodel=small BlankToValue.cpp
g++ -shared -m64 BlankToValue.so BlankToValue.o

When testing the routine in a job however I get the following error.

Sequential_File_36,0: Internal Error: (shbuf): iomgr/iomgr.C: 2649

Is there a different set of options I should be using for compilation?

For reference, the c++ code.

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

char * BlankToValue(char *InStr, char *RepStr)
{
    if (InStr[0] == '\0')                           // Check for null pointer at first character of input string.
    {
        return RepStr;                              // Return replacement string if true. This is to prevent unnecessary processing.
    } else
    {
        const char* checkstr = InStr;               // Establish copy of inputstring stored in checkstring.
        do {                                        // Start outer loop.
            while (isspace(*checkstr)) {            // Inner loop while current checkstring byte is whitespace.
                ++checkstr;                         // Increment to next checkstring byte.
            }
        } while ((*InStr++ = *checkstr++));         // Set inputstring byte to current checkstring and iterate both. Breaks when either string evaluates to null.
        *InStr = '\0';                              // Set null terminator for input string at current byte location.
        if (InStr[0] == '\0')                       // Checks first character of cleaned input string for null pointer.
        {
            return RepStr;                          // Return replacement string if true.
        } else
        {
            return InStr;                           // Return new input string if false.
        }
    }
}

Body:
After a day or two of multiple attempts to try different compile and code approaches I found the solution to my problem. The below code was throwing a segmentation fault when passed a null column. Which makes sense in retrospect.

if (InStr[0] == '\0')

It has been corrected to the below and now everything works properly.

if ((InStr == NULL) || (InStr[0] == '\0'))


问:
Connect NestJS to a websocket server
How can NestJS be use as a websocket client? I want to connect to a remote websocket server as a client using NestJS, but I didn't find any information about this implementation in the framework.</p>

答:
I try it by another way. I write an adapter with socket.io-client. Then use this adapter in boostrap by method useWebSocketAdapter. After that i can write handle websocket event in gateway like the way working with socket server (use decorator @SubscribeMessage)

My Adapter file

```<code>import { WebSocketAdapter, INestApplicationContext } from '@nestjs/common';
import { MessageMappingProperties } from '@nestjs/websockets'

import * as SocketIoClient from 'socket.io-client';
import { isFunction, isNil } from '@nestjs/common/utils/shared.utils';
import { fromEvent, Observable } from 'rxjs';
import { filter, first, map, mergeMap, share, takeUntil } from 'rxjs/operators';

export class IoClientAdapter implements WebSocketAdapter {
    private io;
    constructor(private app: INestApplicationContext) {

    }

    create(port: number, options?: SocketIOClient.ConnectOpts) {
        const client = SocketIoClient("http://localhost:3000" , options || {})
        this.io = client;
        return client;
    }

    bindClientConnect(server: SocketIOClient.Socket, callback: Function) {
        this.io.on('connect', callback);
    }

    bindClientDisconnect(client: SocketIOClient.Socket, callback: Function) {
        console.log("it disconnect")
        //client.on('disconnect', callback);
    }

    public bindMessageHandlers(
        client: any,
        handlers: MessageMappingProperties[],
        transform: (data: any) => Observable<any>,
    ) {
        const disconnect$ = fromEvent(this.io, 'disconnect').pipe(
            share(),
            first(),
        );

        handlers.forEach(({ message, callback }) => {
            const source$ = fromEvent(this.io, message).pipe(
                mergeMap((payload: any) => {
                    const { data, ack } = this.mapPayload(payload);
                    return transform(callback(data, ack)).pipe(
                        filter((response: any) => !isNil(response)),
                        map((response: any) => [response, ack]),
                    );
                }),
                takeUntil(disconnect$),
            );
            source$.subscribe(([response, ack]) => {
                if (response.event) {
                    return client.emit(response.event, response.data);
                }
                isFunction(ack) && ack(response);
            });
        });
    }

    public mapPayload(payload: any): { data: any; ack?: Function } {
        if (!Array.isArray(payload)) {
            return { data: payload };
        }
        const lastElement = payload[payload.length - 1];
        const isAck = isFunction(lastElement);
        if (isAck) {
            const size = payload.length - 1;
            return {
                data: size === 1 ? payload[0] : payload.slice(0, size),
                ack: lastElement,
            };
        }
        return { data: payload };
    }

    close(server: SocketIOClient.Socket) {
        this.io.close()
    }
}

</code>```

main.js

```<code>import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {IoClientAdapter} from './adapters/ioclient.adapter'

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useWebSocketAdapter(new IoClientAdapter(app))
  await app.listen(3006);
  console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
</code>```

then Gateway

```<code>import {
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  WsResponse,
} from '@nestjs/websockets';
import { from, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Server } from 'socket.io';

@WebSocketGateway()
export class EventsGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('hello')
  async identity(@MessageBody() data: number): Promise<number> {
      console.log(data)
    return data;
  }
}
</code>```

It a trick, but look so cool. Message handler can write more like nestjs style.

Title: Connect NestJS to a websocket server

Body:
I try it by another way. I write an adapter with socket.io-client. Then use this adapter in boostrap by method useWebSocketAdapter. After that i can write handle websocket event in gateway like the way working with socket server (use decorator @SubscribeMessage)

My Adapter file

import { WebSocketAdapter, INestApplicationContext } from '@nestjs/common';
import { MessageMappingProperties } from '@nestjs/websockets'

import * as SocketIoClient from 'socket.io-client';
import { isFunction, isNil } from '@nestjs/common/utils/shared.utils';
import { fromEvent, Observable } from 'rxjs';
import { filter, first, map, mergeMap, share, takeUntil } from 'rxjs/operators';

export class IoClientAdapter implements WebSocketAdapter {
    private io;
    constructor(private app: INestApplicationContext) {

    }

    create(port: number, options?: SocketIOClient.ConnectOpts) {
        const client = SocketIoClient("http://localhost:3000" , options || {})
        this.io = client;
        return client;
    }

    bindClientConnect(server: SocketIOClient.Socket, callback: Function) {
        this.io.on('connect', callback);
    }

    bindClientDisconnect(client: SocketIOClient.Socket, callback: Function) {
        console.log("it disconnect")
        //client.on('disconnect', callback);
    }

    public bindMessageHandlers(
        client: any,
        handlers: MessageMappingProperties[],
        transform: (data: any) => Observable<any>,
    ) {
        const disconnect$ = fromEvent(this.io, 'disconnect').pipe(
            share(),
            first(),
        );

        handlers.forEach(({ message, callback }) => {
            const source$ = fromEvent(this.io, message).pipe(
                mergeMap((payload: any) => {
                    const { data, ack } = this.mapPayload(payload);
                    return transform(callback(data, ack)).pipe(
                        filter((response: any) => !isNil(response)),
                        map((response: any) => [response, ack]),
                    );
                }),
                takeUntil(disconnect$),
            );
            source$.subscribe(([response, ack]) => {
                if (response.event) {
                    return client.emit(response.event, response.data);
                }
                isFunction(ack) && ack(response);
            });
        });
    }

    public mapPayload(payload: any): { data: any; ack?: Function } {
        if (!Array.isArray(payload)) {
            return { data: payload };
        }
        const lastElement = payload[payload.length - 1];
        const isAck = isFunction(lastElement);
        if (isAck) {
            const size = payload.length - 1;
            return {
                data: size === 1 ? payload[0] : payload.slice(0, size),
                ack: lastElement,
            };
        }
        return { data: payload };
    }

    close(server: SocketIOClient.Socket) {
        this.io.close()
    }
}

main.js

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {IoClientAdapter} from './adapters/ioclient.adapter'

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useWebSocketAdapter(new IoClientAdapter(app))
  await app.listen(3006);
  console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();

then Gateway

import {
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  WsResponse,
} from '@nestjs/websockets';
import { from, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Server } from 'socket.io';

@WebSocketGateway()
export class EventsGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('hello')
  async identity(@MessageBody() data: number): Promise<number> {
      console.log(data)
    return data;
  }
}

It a trick, but look so cool. Message handler can write more like nestjs style.


问:
Call to undefined method App\Product::link()
Help me, i am trying put some pagination in my page, but keep showing this error Call to undefined method App\Product::link()

my Code

Blade:

```<code>@extends('layouts.index')
@section('content')

<!-- TOP Navbar -->
<div class="w-100 shadow d-flex position-relative position-fixed" style="z-index: 2; background-color: white; ">

    <div class="d-flex justify-content-center py-3 mr-auto" style="width: 200px">
        <img src="/images/logo.svg" alt="logo icon">
    </div>

    <div class="pt-4 bd-highlight"><a href="/">
            <a href="/create">
                <button type="button" class="btn font p-auto rounded-pill text-white font-weight-bold "
                        style="background-color: #28AD47; width: 178px; height: 40px">New Product
                </button>
            </a>
        </a>
    </div>

    <div class=" bd-highlight">
        <div class="dropdown px-5" style="padding-top: 24px">
            <a class=" align-middle font dropdown-toggle" href="#" role="button" id="dropdownMenuLink"
               data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
               style="color: #2c3539">                    {{ Auth::user()->name }}

            </a>

            <div class="dropdown-menu mt-4" aria-labelledby="dropdownMenuLink" x-placement="bottom-start"
                 style="position: absolute; transform: translate3d(-20px, 38px, 0px); top: 0px; left: 0px; will-change: transform;">
                <a class="dropdown-item" href="{{ url('/profile') }}"><i class="fa fa-btn fa-user"></i>Profile</a>
                <a class="dropdown-item" href="{{ route('logout') }}"
                   onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
                    Logout
                </a>

                <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                    {{ csrf_field() }}
                </form>
            </div>
        </div>
    </div>
</div>

<!-------------------------->

<div style="background-color: #F8F8F8; z-index: 0;" class="d-flex justify-content-start ">
    <div style="width: 200px; height: calc(100vh - 70px);margin-top: 73px;z-index: 1"
         class="bg-white shadow position-fixed ">
        <div class="d-flex justify-content-center">
            <a href="/create">
                <p class="font my-5" style="color: #525252"><img src="/images/plus.svg" class="mr-3" alt="plus icon"
                                                                 width="16px" height="16px">
                    New Product
                </p>
            </a>
        </div>

        <div class="d-flex justify-content-center">
            <p class="font my-5" style="color: #525252"><img src="/images/edit.svg" class="mr-3" alt="edit icon"
                                                             width="16px" height="16px">
                Edit Product
            </p>

        </div>
    </div>

    <div class="w-100 " style="margin-top: 73px;margin-left: 200px">
        <div class="d-flex justify-content-center">
            <h1 class="font p-5">All products</h1>
        </div>
        <!-- <div style="height: calc(100vh -  202px);background-color: #676767">-->
        <div class=" d-flex justify-content-center flex-wrap">
            @foreach($products as $product)
                <div class="product shadow m-4">
                    <div class="d-flex justify-content-center mt-3">
                        <img src="/images/car-example.png" alt="car photo" width="190px" height="140px">
                    </div>

                    <div>
                        <p class="font text-white pt-4 pl-5" style="font-size: 16px">
                            {{$product->name}} <img src="/images/info.svg" alt="info icon" width="20px"
                                                     height="15px" class="pl-2 mb-1 red-tooltip"
                                                     data-toggle="tooltip"
                                                     data-placement="right" title="{{$product->description}} ">
                        </p>
                    </div>

                    <div class="d-flex  bd-highlight" style="margin-top: 40px">
                        <div class="pl-5 mt-auto bd-highlight">
                            <h3 class="font text-white">${{$product->price}}</h3>
                        </div>

                        <div class="bd-highlight ml-auto mt-3 pr-5">

                            <a href="/">
                                <button type="button"
                                        class="btn font rounded-pill text-white font-weight-light "
                                        style="font-size: 18px;background-color: #28AD47; width: 99px; height: 41px">
                                    Buy
                                </button>
                            </a>
                        </div>
                    </div>
                </div>

            @endforeach

        </div>

        <div class="w-100" style="background-color: white; z-index: 0;">
            <div class=" d-flex justify-content-center pt-2">
                    {{ $product->link() }}
            </div>
        </div>

    </div>
</div>

<!-- Bootstrap Link -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script>
    $(function () {
        $('[data-toggle="tooltip"]').tooltip()

        })
    </script>

    <!-- Hover -->

 @endsection
</code>```

Controller:

```<code><?php
</code>```

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()

```<code>{
    $products = Product::orderBy('name')->paginate(10);
    return view('show')->with('products', $products);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    return view('create');
}

/**
 * Store a newly created resource in storage.
 *
 * @param \Illuminate\Http\Request $request
 * @return \Illuminate\Http\Response
 */

public function store(Request $request)
{

    $this->validate($request, [
        'name' =>'required | unique:product|max:64',
        'description' => 'required',
        'price' => 'required',
    ]);

    print_r($request->input());
    $product = new Product;
    $product->name = $request->name;
    $product->description = $request->description;
    $product->price = $request->price;
    echo $product->save();

    return redirect('/home');
}

/**
 * Display the specified resource.
 *
 * @param int $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{

}

/**
 * Show the form for editing the specified resource.
 *
 * @param int $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    //
}

/**
 * Update the specified resource in storage.
 *
 * @param \Illuminate\Http\Request $request
 * @param int $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    //
}

/**
 * Remove the specified resource from storage.
 *
 * @param int $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    //
}
</code>```

}

web.php:

```<code>Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::resource('home', 'ProductController');

Route::get('profile', 'UserController@profile')->middleware('auth');

Route::post('profile', 'UserController@update_avatar')->name('profile');

Route::view('create', 'create')->middleware('auth');

Route::post('submit', 'ProductController@store');
</code>```

答:
You need use products and links in plural</p>

```<code><div class="w-100" style="background-color: white; z-index: 0;">
        <div class=" d-flex justify-content-center pt-2">
                {{ $products->links() }}
        </div>
    </div>
</code>```

Body:
Help me, i am trying put some pagination in my page, but keep showing this error Call to undefined method App\Product::link()

my Code

Blade:

@extends('layouts.index')
@section('content')

                <button type="button" class="btn font p-auto rounded-pill text-white font-weight-bold "
                        style="background-color: #28AD47; width: 178px; height: 40px">New Product
                </button>

                                {{ Auth::user()->name }}

                Profile

                    Logout

                <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                    {{ csrf_field() }}
                </form>

                    New Product

                Edit Product

All products

            @foreach($products as $product)

                            {{$product->name}} description}} ">

${{$product->price}}

                                <button type="button"
                                        class="btn font rounded-pill text-white font-weight-light "
                                        style="font-size: 18px;background-color: #28AD47; width: 99px; height: 41px">
                                    Buy
                                </button>

            @endforeach

                    {{ $product->link() }}

<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

 @endsection

Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()

{
    $products = Product::orderBy('name')->paginate(10);
    return view('show')->with('products', $products);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    return view('create');
}

/**
 * Store a newly created resource in storage.
 *
 * @param \Illuminate\Http\Request $request
 * @return \Illuminate\Http\Response
 */

public function store(Request $request)
{

    $this->validate($request, [
        'name' =>'required | unique:product|max:64',
        'description' => 'required',
        'price' => 'required',
    ]);

    print_r($request->input());
    $product = new Product;
    $product->name = $request->name;
    $product->description = $request->description;
    $product->price = $request->price;
    echo $product->save();

    return redirect('/home');
}

/**
 * Display the specified resource.
 *
 * @param int $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{

}

/**
 * Show the form for editing the specified resource.
 *
 * @param int $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    //
}

/**
 * Update the specified resource in storage.
 *
 * @param \Illuminate\Http\Request $request
 * @param int $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    //
}

/**
 * Remove the specified resource from storage.
 *
 * @param int $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    //
}

}

web.php:

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::resource('home', 'ProductController');

Route::get('profile', 'UserController@profile')->middleware('auth');

Route::post('profile', 'UserController@update_avatar')->name('profile');

Route::view('create', 'create')->middleware('auth');

Route::post('submit', 'ProductController@store');

Body:
You need use products and links in plural

<div class="w-100" style="background-color: white; z-index: 0;">
        <div class=" d-flex justify-content-center pt-2">
                {{ $products->links() }}
        </div>
    </div>


问:
Implementing events in C++
After some research on internet for an efficient way to implement events in C++, I found the following methods

Interface class - Applications can override the virtual functions in the derived class

Normal Callback mechanism using function pointers

Delegates using Boost.function

Signals and slots (as used in Qt)

I am confused on advantages and disadvantages of each of these and when to use anyone of this.
Which is the best method and why?
Is there any other solutions which are better than the ones listed?

答:
First two options are part of the basic C++ standard, with the function callbacks being compatible with C code as well.

The other two options require using boost and Qt respectively.

Advantages/disadvantages is kindof too broad a question, and the answer depends greatly on what you're doing, in what environment and for what purpose.

Title: Implementing events in C++


问:
Sequelize table name change
Have renamed a table from users to user in MySQL database. In Express I'm running Sequelize and created a schema for the old users table. With the table renamed and everything in the code changed from users to user, Sequelize is still looking for a table named specifically users even though the table name is updated in the schema.

```<code>User = db.sequelize.define('user', {
  first_name: Sequelize.STRING,
  last_name: Sequelize.STRING,
  email: Sequelize.STRING,
  password: Sequelize.STRING,
  role: Sequelize.STRING,
  created_at: Sequelize.DATE,
  updated_at: Sequelize.DATE
});
</code>```

Tried running this to overwrite the table with one produced by Sequelize and it still created a table named users

```<code>User.sync({force: true}).then(() => {
  // Table created
  return User.create({
    firstName: 'test',
    lastName: 'test',
    email: 'test@example.com',
    password: 'password'
  });
});
</code>```

Has anyone else experienced the same? Is there some other configuration I am missing? This is all I did in the first place when creating the first table.

答:
recent sequelize version allows you to do this</p>

```<code>up: async (queryInterface, Sequelize) => queryInterface.showAllTables().then(async (tables) => {any function})
</code>```

Title: Sequelize table name change

Body:
Have renamed a table from users to user in MySQL database. In Express I'm running Sequelize and created a schema for the old users table. With the table renamed and everything in the code changed from users to user, Sequelize is still looking for a table named specifically users even though the table name is updated in the schema.

User = db.sequelize.define('user', {
  first_name: Sequelize.STRING,
  last_name: Sequelize.STRING,
  email: Sequelize.STRING,
  password: Sequelize.STRING,
  role: Sequelize.STRING,
  created_at: Sequelize.DATE,
  updated_at: Sequelize.DATE
});

Tried running this to overwrite the table with one produced by Sequelize and it still created a table named users

User.sync({force: true}).then(() => {
  // Table created
  return User.create({
    firstName: 'test',
    lastName: 'test',
    email: 'test@example.com',
    password: 'password'
  });
});

Has anyone else experienced the same? Is there some other configuration I am missing? This is all I did in the first place when creating the first table.

Body:
recent sequelize version allows you to do this

up: async (queryInterface, Sequelize) => queryInterface.showAllTables().then(async (tables) => {any function})


问:
Why is CLion not showing exceptions?
CLion appears to be not showing me any exceptions when running my code. To test this, I've created a new project with only the following code:

```<code>#include <iostream>

int main() {
    std::cout << "--- One" << std::endl;
    throw 6;
    std::cout << "--- Two" << std::endl;
    return 0;
}
</code>```

Which leads to the following output:

```<code>C:\Users\david\CLionProjects\untitled\cmake-build-debug\untitled.exe
--- One

Process finished with exit code 0
</code>```

As you can see, code before the exception is executed and code following it is not executed (as you would expect). But instead of a message about the exception, it says "Process finished with exit code 0", as if no exception had occurred.

The same code compiled and executed on Ubuntu (via terminal) displayed an error message. So I assume the problem is with CLion.

How can I resolve this problem so that I can see messages for exceptions in my code?

Is there any setting that could lead to such behaviour?

I'm using CLion on Windows 10 with Cygwin. Here's a screenshot of the problem:

答:
Throw requires also try and catch

From:
http://www.cplusplus.com/doc/tutorial/exceptions/

```<code>// exceptions
#include <iostream>
using namespace std;

int main () {
  try
  {
    throw 20;
  }
  catch (int e)
  {
    cout << "An exception occurred. Exception Nr. " << e << '\n';
  }
  return 0;
}
</code>```

that compiled and run under cygwin shows:

```<code>$ g++ prova1.cc -o prova1

$ ./prova1
An exception occurred. Exception Nr. 2
</code>```

Title: Why is CLion not showing exceptions?

Body:
CLion appears to be not showing me any exceptions when running my code. To test this, I've created a new project with only the following code:

#include <iostream>

int main() {
    std::cout << "--- One" << std::endl;
    throw 6;
    std::cout << "--- Two" << std::endl;
    return 0;
}

Which leads to the following output:

C:\Users\david\CLionProjects\untitled\cmake-build-debug\untitled.exe
--- One

Process finished with exit code 0

As you can see, code before the exception is executed and code following it is not executed (as you would expect). But instead of a message about the exception, it says "Process finished with exit code 0", as if no exception had occurred.

The same code compiled and executed on Ubuntu (via terminal) displayed an error message. So I assume the problem is with CLion.

How can I resolve this problem so that I can see messages for exceptions in my code?

Is there any setting that could lead to such behaviour?

I'm using CLion on Windows 10 with Cygwin. Here's a screenshot of the problem:

Body:
Throw requires also try and catch

From:
http://www.cplusplus.com/doc/tutorial/exceptions/

// exceptions
#include <iostream>
using namespace std;

int main () {
  try
  {
    throw 20;
  }
  catch (int e)
  {
    cout << "An exception occurred. Exception Nr. " << e << '\n';
  }
  return 0;
}

that compiled and run under cygwin shows:

$ g++ prova1.cc -o prova1

$ ./prova1
An exception occurred. Exception Nr. 2


问:
bash loop error : Get JSON Object by property with jq / bash
I would like to get the values from Json file. Which is working.

JsonFileToTest:

```<code>{
  "permissions": [
    {
      "emailid": "test1@test.com",
      "rights": "read"
    },
    {
      "emailid": "test2@test.com",
      "rights": "read"
    }
  ]
}
</code>```

```<code>readPermissions=($(jq -r '.permissions' JsonFileToTest))

# The command below works perfectly, But when I Put it in a loop, It does not.
#echo ${readPermissions[@]} | jq 'values[].emailid'

for vals in ${readPermissions[@]}
do
   # I would like o extract the email id of the user. The loop is not working atm.
    echo ${vals[@]} | jq 'values[].emailid'
done
</code>```

what am I missing here?
thanks

答:
If you really want to do it this way, that might look like:

```<code>readarray -t permissions < <(jq -c '.permissions[]' JsonFileToTest)
for permissionSet in "${permissions[@]}"; do
  jq -r '.emailid' <<<"$permissionSet"
done
</code>```

Note that we're telling jq to print one line per item (with -c), and using readarray -t to read each line into an array element (unlike the array=( $(...command...) ) antipattern, which splits not just on newlines but on other whitespace as well, and expands globs in the process).

But there's no reason whatsoever to do any of that. You'll get the exact same result simply running:

```<code>jq -r '.permissions[].emailid' JsonFileToTest
</code>```

Body:
I would like to get the values from Json file. Which is working.

JsonFileToTest:

{
  "permissions": [
    {
      "emailid": "test1@test.com",
      "rights": "read"
    },
    {
      "emailid": "test2@test.com",
      "rights": "read"
    }
  ]
}

readPermissions=($(jq -r '.permissions' JsonFileToTest))

# The command below works perfectly, But when I Put it in a loop, It does not.
#echo ${readPermissions[@]} | jq 'values[].emailid'

for vals in ${readPermissions[@]}
do
   # I would like o extract the email id of the user. The loop is not working atm.
    echo ${vals[@]} | jq 'values[].emailid'
done

what am I missing here?
thanks

Body:
If you really want to do it this way, that might look like:

readarray -t permissions < <(jq -c '.permissions[]' JsonFileToTest)
for permissionSet in "${permissions[@]}"; do
  jq -r '.emailid' <<<"$permissionSet"
done

Note that we're telling jq to print one line per item (with -c), and using readarray -t to read each line into an array element (unlike the array=( $(...command...) ) antipattern, which splits not just on newlines but on other whitespace as well, and expands globs in the process).

But there's no reason whatsoever to do any of that. You'll get the exact same result simply running:

jq -r '.permissions[].emailid' JsonFileToTest


问:
React. TypeError: Cannot read property 'id' of undefined
this is my first question, i'm a newbie dev and i've been working on my first web app for a week. I'm stuck because i'm trying to make a simple mobile e commerce, i've made 8 cards and i've put a plus icon that needs to add the item in the cart when it is clicked, also it has to flip and become a cart icon.

I guess i can't access what it is inside the map method?! and i get the error: TypeError: Cannot read property 'id' of undefined. The problem is inside the some method, I can't come up with any different solution. Any suggestion? Can you help me please? Thanks.

```<code>function Mobile() {
const [hovered, setHovered] = useState(false)
const [cartItems, setCartItems] = useState([])

const mobiles = data.map(mobile => (
    <div className='card' key={mobile.id}
         onMouseEnter = {() => setHovered(true)}
         onMouseLeave = {() => setHovered(false)}

    >
            {cartIcon()}
            <img src= {mobile.img}  alt='Mobile phones' className='mobile-img' />
            <h3 className='mobile-title'>{mobile.title}</h3>
            <p className='mobile-info'>{mobile.info}</p>
            <p className='mobile-price'>€ {mobile.price}</p>
    </div>

))

function addToCart(newItem) {
setCartItems(prevItems => [...prevItems, newItem])
</code>```

}

```<code>function cartIcon() {
const alreadyInCart = cartItems.some(item => item ===  item.id)
if(alreadyInCart) {
    return <i className="ri-shopping-cart-fill cart"></i>
} else if(hovered) {
    return <i className="ri-add-circle-line cart" onClick = {() => addToCart()}></i>
}
</code>```

}

答:
You need to pass item to the cartIcon function. The error is because your function does not have access to whatever item is. I'm assuming it's mobile?
Inside your map pass mobile

```<code>{cartIcon(mobile)}
</code>```

In the cart icon function create an arg called item

```<code>function cartIcon(item) {
const alreadyInCart = cartItems.some(item => item ===  item.id)
if(alreadyInCart) {
    return <i className="ri-shopping-cart-fill cart"></i>
} else if(hovered) {
    return <i className="ri-add-circle-line cart" onClick = {() => addToCart()}></i>
}

</code>```

I can't see all the code but this should fix your error.

Body:
this is my first question, i'm a newbie dev and i've been working on my first web app for a week. I'm stuck because i'm trying to make a simple mobile e commerce, i've made 8 cards and i've put a plus icon that needs to add the item in the cart when it is clicked, also it has to flip and become a cart icon.

I guess i can't access what it is inside the map method?! and i get the error: TypeError: Cannot read property 'id' of undefined. The problem is inside the some method, I can't come up with any different solution. Any suggestion? Can you help me please? Thanks.

function Mobile() {
const [hovered, setHovered] = useState(false)
const [cartItems, setCartItems] = useState([])

const mobiles = data.map(mobile => (

 setHovered(true)}
         onMouseLeave = {() => setHovered(false)}

    >
            {cartIcon()}

{mobile.title}

{mobile.info}

€ {mobile.price}

))

function addToCart(newItem) {
setCartItems(prevItems => [...prevItems, newItem])

}

function cartIcon() {
const alreadyInCart = cartItems.some(item => item ===  item.id)
if(alreadyInCart) {
    return
} else if(hovered) {
    return  addToCart()}>
}

}

Body:
You need to pass item to the cartIcon function. The error is because your function does not have access to whatever item is. I'm assuming it's mobile?
Inside your map pass mobile

{cartIcon(mobile)}

In the cart icon function create an arg called item

function cartIcon(item) {
const alreadyInCart = cartItems.some(item => item ===  item.id)
if(alreadyInCart) {
    return <i className="ri-shopping-cart-fill cart"></i>
} else if(hovered) {
    return <i className="ri-add-circle-line cart" onClick = {() => addToCart()}></i>
}

I can't see all the code but this should fix your error.


问:
Convert keras model to quantized tflite lost precision
I'm trying to convert my keras model into tflite quantized model so that I can run my model on coral TPU, but the output of my keras model and tflite model are significantly different.

The red points are quantized tflite model output, and blue points are original keras model output.

Here is my code to convert keras model to quantized tflite model :

```<code>quant = True
gc.collect()
import tensorflow as tf
import numpy as np
import pathlib
print(tf.__version__)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
if quant:
    print("Converting quant....")
    sample_size = 200
    rdm_idx = np.random.choice(range(len(X_test)),sample_size)
    rep_data = tf.cast(X_train[rdm_idx], tf.float32) / 255.0
    dataset = tf.data.Dataset.from_tensor_slices(rep_data).batch(1)

    def representative_data_gen():
        for input_value in dataset.take(sample_size):
            yield [input_value]

    converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
    converter.representative_dataset = representative_data_gen
    converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
    converter.inference_input_type = tf.uint8
    converter.inference_output_type = tf.uint8
    tflite_model_quant = converter.convert()
    open("MaskedLandMarkDetction_MobileNetV2_quant_fromKeras_v5.tflite", "wb").write(tflite_model_quant)

    print("Write quantization tflite done.")
else:
    print("Converting normal....")
    tflite_model = converter.convert()
    open("MaskedLandMarkDetction_MobileNetV2_fromKeras.tflite", "wb").write(tflite_model)
    print("Write tflite done.")
</code>```

X_train is my training data, and I will scale input images value from 0 to 1 by divided 255., so I do the same in representative_data_gen functions.

Any assistance you can provide would be greatly appreciated.

The tensorflow version I used is gpu 2.2.0

答:
It looks like the usage of the api is correct. Not all models are guaranteed to get good accuracy with post training quantization. For example, tasks that require more precision or small models may suffer more loss.

For these more difficult tasks we recommend using quantization aware training, which is available for keras models: https://www.tensorflow.org/model_optimization/guide/quantization/training.

Body:
I'm trying to convert my keras model into tflite quantized model so that I can run my model on coral TPU, but the output of my keras model and tflite model are significantly different.

The red points are quantized tflite model output, and blue points are original keras model output.

Here is my code to convert keras model to quantized tflite model :

quant = True
gc.collect()
import tensorflow as tf
import numpy as np
import pathlib
print(tf.__version__)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
if quant:
    print("Converting quant....")
    sample_size = 200
    rdm_idx = np.random.choice(range(len(X_test)),sample_size)
    rep_data = tf.cast(X_train[rdm_idx], tf.float32) / 255.0
    dataset = tf.data.Dataset.from_tensor_slices(rep_data).batch(1)

    def representative_data_gen():
        for input_value in dataset.take(sample_size):
            yield [input_value]

    converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
    converter.representative_dataset = representative_data_gen
    converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
    converter.inference_input_type = tf.uint8
    converter.inference_output_type = tf.uint8
    tflite_model_quant = converter.convert()
    open("MaskedLandMarkDetction_MobileNetV2_quant_fromKeras_v5.tflite", "wb").write(tflite_model_quant)

    print("Write quantization tflite done.")
else:
    print("Converting normal....")
    tflite_model = converter.convert()
    open("MaskedLandMarkDetction_MobileNetV2_fromKeras.tflite", "wb").write(tflite_model)
    print("Write tflite done.")

X_train is my training data, and I will scale input images value from 0 to 1 by divided 255., so I do the same in representative_data_gen functions.

Any assistance you can provide would be greatly appreciated.

The tensorflow version I used is gpu 2.2.0


问:
.NET Core 3.1 Console App as a Windows Service
I currently have a pretty big console app running with ASP.NET Core 3.1. I have been tasked with now making this work on one of our servers as a Window Service. I have everything ready to make it run as a service on the server itself, however, the one thing I am stuck on at the moment is how to actually change it in code to make it run as a service without breaking it.

I have found a couple of tutorials like this that do explain how to run a console app as a service, however, all of them that I have found start from a fresh project. My issue is that my current project has already been written. The main problem that I am asking for help with is how would I go about making my project work as a windows service while also keeping the functionality that is currently in a startup.cs. For context, here is my current startup.cs and program.cs:

Startup.cs

```<code>public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSignalR();
        services.AddTransient<SharePointUploader>();
        services.AddTransient<FileUploadService>();
        services.AddSingleton<UploaderHub>();
        //services.AddAuthentication(IISDefaults.AuthenticationScheme);
        services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
        services.AddAuthorization();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHttpsRedirection();
        }

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<UploaderHub>("/uploadHub");
        });
    }
}
</code>```

Program.cs

```<code>public class Program
{
    public static void Main(string[] args)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Debug("init main");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception exception)
        {
            //NLog: catch setup errors
            logger.Error(exception, "Stopped program because of exception");
            throw;
        }
        finally
        {
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(LogLevel.Trace);
            })
            .UseNLog();
}
</code>```

I don't really understand how this is supposed to work when run as a windows service (based on tutorials like linked above). Any help would be greatly appreciated.

答:
Use IWebHostBuilder instead of IHostBuilder:

```<code>public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, config) =>
        {
            // Configure the app here.
        })
        .UseNLog()
        .UseUrls("http://localhost:5001/;" +
                    "https://localhost:5002/;")
        .UseStartup<Startup>();
</code>```

You also need the following packages:

```<code>Microsoft.AspNetCore.Hosting;
Microsoft.AspNetCore.Hosting.WindowsServices;
</code>```

Modify your main function:

```<code>bool isService = !(Debugger.IsAttached || args.Contains("--console"));
var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray());
var host = builder.Build();

if (isService)
{
    host.RunAsService();
}
else
{
    host.Run();
}
</code>```

For installation of the service use the tool sc.exe. You can run the app as console app by passing --console as argument to the app. For debugging you need to pass --console as well.

Body:
I currently have a pretty big console app running with ASP.NET Core 3.1. I have been tasked with now making this work on one of our servers as a Window Service. I have everything ready to make it run as a service on the server itself, however, the one thing I am stuck on at the moment is how to actually change it in code to make it run as a service without breaking it.

I have found a couple of tutorials like this that do explain how to run a console app as a service, however, all of them that I have found start from a fresh project. My issue is that my current project has already been written. The main problem that I am asking for help with is how would I go about making my project work as a windows service while also keeping the functionality that is currently in a startup.cs. For context, here is my current startup.cs and program.cs:

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSignalR();
        services.AddTransient<SharePointUploader>();
        services.AddTransient<FileUploadService>();
        services.AddSingleton<UploaderHub>();
        //services.AddAuthentication(IISDefaults.AuthenticationScheme);
        services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
        services.AddAuthorization();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHttpsRedirection();
        }

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<UploaderHub>("/uploadHub");
        });
    }
}

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Debug("init main");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception exception)
        {
            //NLog: catch setup errors
            logger.Error(exception, "Stopped program because of exception");
            throw;
        }
        finally
        {
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(LogLevel.Trace);
            })
            .UseNLog();
}

I don't really understand how this is supposed to work when run as a windows service (based on tutorials like linked above). Any help would be greatly appreciated.

Body:
Use IWebHostBuilder instead of IHostBuilder:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, config) =>
        {
            // Configure the app here.
        })
        .UseNLog()
        .UseUrls("http://localhost:5001/;" +
                    "https://localhost:5002/;")
        .UseStartup<Startup>();

You also need the following packages:

Microsoft.AspNetCore.Hosting;
Microsoft.AspNetCore.Hosting.WindowsServices;

Modify your main function:

bool isService = !(Debugger.IsAttached || args.Contains("--console"));
var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray());
var host = builder.Build();

if (isService)
{
    host.RunAsService();
}
else
{
    host.Run();
}

For installation of the service use the tool sc.exe. You can run the app as console app by passing --console as argument to the app. For debugging you need to pass --console as well.


问:
How do I use AppleScript to get e-mail addresses, account information from Lotus Notes?
We have a mailbox containing roughly 60,000 e-mails, and I've been challenged to pull the names, account numbers and e-mail addresses out of the body of each and export it into a spreadsheet-friendly format.

I was thinking of using AppleScript and Notes 8.5, but I can't find any documentation on how to interact with individual messages in Notes.

Can anyone help?

答:
If you're familiar with scripting languages, I suggest going with LotusScript instead.  It gives you direct access to the Notes objects rather than Applescript and the Notes C API.

You can create a Notes Agent within the mailbox using the Notes Designer application.  The code would roughly be this:

```<code>Dim s as New NotesSession
Dim db as NotesDatabase
Dim dc as NotesDocumentCollection
Dim doc as NotesDocument

Set db = s.CurrentDatabase
Set dc = db.Search(|Form="Memo"|, Nothing, 0)
Set doc = dc.GetFirstDocument

While Not (doc Is Nothing)

    'Process each document here...

    Set doc = dc.GetNextDocument(doc)
End While
</code>```

The question is how are the email addresses, account numbers, and names stored in the body of each email?

You could pull all the text out of the body of the emails into a large text file, perhaps, and then process that with Applescript, if you're more comfortable with that.

```<code>fileNum = Freefile()
pathname = "C:\path\to\file"
Open pathname For Output As fileNum
While Not (doc Is Nothing)

    Set rtitem = doc.GetFirstItem( "Body" )
    Write #fileNum, rtitem.GetFormattedText(False, 0)

    Set doc = dc.GetNextDocument(doc)
End While
Close fileNum
</code>```

Or you could use the NotesRichTextItem methods to navigate and extract specific data from the body.  This could be useful, perhaps, if the data is stored in tables within the body of the email, as the NotesRichTextItem methods allow you to find a table element and navigate cells (although this is rather difficult, and might be worth posting a second question on StackOverflow to get help with this).

If you're looking to get the email address and names from the To: or From: fields of the email, you can do that more easily by accessing properties of the NotesDocument for each email.  The fields could be extracted like so:

```<code>Dim ToEmail as String
Dim FromEmail as String

ToEmail = doc.SendTo(0)   'a document's item properties are zero-based arrays
FromEmail = doc.From(0)
</code>```

Body:
If you're familiar with scripting languages, I suggest going with LotusScript instead.  It gives you direct access to the Notes objects rather than Applescript and the Notes C API.

You can create a Notes Agent within the mailbox using the Notes Designer application.  The code would roughly be this:

Dim s as New NotesSession
Dim db as NotesDatabase
Dim dc as NotesDocumentCollection
Dim doc as NotesDocument

Set db = s.CurrentDatabase
Set dc = db.Search(|Form="Memo"|, Nothing, 0)
Set doc = dc.GetFirstDocument

While Not (doc Is Nothing)

    'Process each document here...

    Set doc = dc.GetNextDocument(doc)
End While

The question is how are the email addresses, account numbers, and names stored in the body of each email?

You could pull all the text out of the body of the emails into a large text file, perhaps, and then process that with Applescript, if you're more comfortable with that.

fileNum = Freefile()
pathname = "C:\path\to\file"
Open pathname For Output As fileNum
While Not (doc Is Nothing)

    Set rtitem = doc.GetFirstItem( "Body" )
    Write #fileNum, rtitem.GetFormattedText(False, 0)

    Set doc = dc.GetNextDocument(doc)
End While
Close fileNum

Or you could use the NotesRichTextItem methods to navigate and extract specific data from the body.  This could be useful, perhaps, if the data is stored in tables within the body of the email, as the NotesRichTextItem methods allow you to find a table element and navigate cells (although this is rather difficult, and might be worth posting a second question on StackOverflow to get help with this).

If you're looking to get the email address and names from the To: or From: fields of the email, you can do that more easily by accessing properties of the NotesDocument for each email.  The fields could be extracted like so:

Dim ToEmail as String
Dim FromEmail as String

ToEmail = doc.SendTo(0)   'a document's item properties are zero-based arrays
FromEmail = doc.From(0)