问:
Flutter setState to another class?
I have a root class RootPage which is a StatefulWidget which is always in view. I would like to change the body in RootPage which is controlled by RootPage's currentPage Widget from different classes such as my FeedPage class and any other class that I make?

Example code

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

class RootPage extends StatefulWidget {
  @override
  _RootPageState createState() => new _RootPageState();
}
class _RootPageState extends State<RootPage> {
  FeedPage feedPage;

  Widget currentPage;

  @override
  void initState() {
    super.initState();
    feedPage = FeedPage();

    currentPage = feedPage;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      //Current page to be changed from other classes too?
      body: currentPage
    );
  }
}

class FeedPage extends StatefulWidget {
  @override
  _feedPageState createState() => new _feedPageState();
}
class _feedPageState extends State<FeedPage> {

  @override
  Widget build(BuildContext context) {
    return new FlatButton(
      onPressed: () {
        setState(() {
          //change the currentPage in RootPage so it switches FeedPage away and gets a new class that I'll make
        });
      },
      child: new Text('Go to a new page but keep root, just replace this feed part'),
    );
  }
}
</code>```

I'm sure there's an obvious answer but I can't seem to figure out how to do it efficiently so it'll be easy to integrate future classes and keep my Root always in view.

答:
This was a tricky question but I got a solution for this question I to faced this problem so many times. So let's first solve your problem. And this is the solution for your code

Lets first save this file with a name feedPage.dart

```<code>`import 'package:flutter/material.dart';
class FeedPage extends StatefulWidget {
  @override
  _feedPageState createState() => new _feedPageState();
}
class _feedPageState extends State<FeedPage> {

  @override
  Widget build(BuildContext context) {
    return new FlatButton(
      onPressed: () {
        setState(() {
          //change the currentPage in RootPage so it switches FeedPage away and gets a new class that I'll make
        });
      },
      child: new Text('Go to a new page but keep root, just replace this feed part'),
    );
  }
}`
</code>```

And then import that file into your main file

```<code>`
 import 'package:flutter/material.dart';
 import 'feedPage.dart'
class RootPage extends StatefulWidget {
  @override
  _RootPageState createState() => new _RootPageState();
}
class _RootPageState extends State<RootPage> {
  FeedPage feedPage;

  Widget currentPage;

  @override
  void initState() {
    super.initState();
    feedPage = FeedPage();

    currentPage = feedPage;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      //Current page to be changed from other classes too?
      body: currentPage
    );
  }
}`
</code>```

In flutter you cant write multiple Stateful widgets in one dart file you have to create that as a widget and use it in your code as setState is an attribute of a Stateful widget we have write this code in an diffrent file

Problem Solved......:)

Title: Flutter setState to another class?

Body:
I have a root class RootPage which is a StatefulWidget which is always in view. I would like to change the body in RootPage which is controlled by RootPage's currentPage Widget from different classes such as my FeedPage class and any other class that I make?

Example code

import 'package:flutter/material.dart';

class RootPage extends StatefulWidget {
  @override
  _RootPageState createState() => new _RootPageState();
}
class _RootPageState extends State<RootPage> {
  FeedPage feedPage;

  Widget currentPage;

  @override
  void initState() {
    super.initState();
    feedPage = FeedPage();

    currentPage = feedPage;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      //Current page to be changed from other classes too?
      body: currentPage
    );
  }
}

class FeedPage extends StatefulWidget {
  @override
  _feedPageState createState() => new _feedPageState();
}
class _feedPageState extends State<FeedPage> {

  @override
  Widget build(BuildContext context) {
    return new FlatButton(
      onPressed: () {
        setState(() {
          //change the currentPage in RootPage so it switches FeedPage away and gets a new class that I'll make
        });
      },
      child: new Text('Go to a new page but keep root, just replace this feed part'),
    );
  }
}

I'm sure there's an obvious answer but I can't seem to figure out how to do it efficiently so it'll be easy to integrate future classes and keep my Root always in view.

Body:
This was a tricky question but I got a solution for this question I to faced this problem so many times. So let's first solve your problem. And this is the solution for your code

Lets first save this file with a name feedPage.dart

`import 'package:flutter/material.dart';
class FeedPage extends StatefulWidget {
  @override
  _feedPageState createState() => new _feedPageState();
}
class _feedPageState extends State<FeedPage> {

  @override
  Widget build(BuildContext context) {
    return new FlatButton(
      onPressed: () {
        setState(() {
          //change the currentPage in RootPage so it switches FeedPage away and gets a new class that I'll make
        });
      },
      child: new Text('Go to a new page but keep root, just replace this feed part'),
    );
  }
}`

And then import that file into your main file

`
 import 'package:flutter/material.dart';
 import 'feedPage.dart'
class RootPage extends StatefulWidget {
  @override
  _RootPageState createState() => new _RootPageState();
}
class _RootPageState extends State<RootPage> {
  FeedPage feedPage;

  Widget currentPage;

  @override
  void initState() {
    super.initState();
    feedPage = FeedPage();

    currentPage = feedPage;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      //Current page to be changed from other classes too?
      body: currentPage
    );
  }
}`

In flutter you cant write multiple Stateful widgets in one dart file you have to create that as a widget and use it in your code as setState is an attribute of a Stateful widget we have write this code in an diffrent file

Problem Solved......:)


来源: stackexchange

问:
How to cleanly exit QEMU after executing bare metal program without user intervention?
I am assembling a cross compiling unit testing rig for an ARM system and running the tests on a host machine with qemu-system-arm. Specifically, I'm using qemu to emulate the Stellaris LM3S6965 eval board as it contains a Cortex M3 processor like my target environment. The binary run in qemu is built with GNU Tools for ARM.

There is no OS involved. The test suite is run as a bare metal application with qemu in -nographic mode. The toolchain and the test rig itself are working fine. And the tests successfully run to completion and produce test results within qemu just fine as well.

The problem is in wrapping up qemu in an automated build tool (Rake in this case). Other than keyboard commands I have not yet found a good way to cause qemu to exit after the test suite runs and spits out its results. This causes the build environment to hang / rely on user intervention.

I have looked high and low and have found no good sources on how to accomplish a simple exit after program termination. I did find a couple suggestions of running qemu with the -no-reboot option and then triggering a system reset from the program running in the emulator. I have tried this. It works… kinda. I write the appropriate values to the emulated processor's reset vector after main() executes, and this does trigger a reset. After running the test suite qemu reports catching a system reset. However, it reports this as a hardware error, dumps register contents, and then exits angry (error message below). While this does accomplish exiting after the test suite runs, it then breaks the automated build script due to qemu exiting with an error condition.

```<code>qemu: hardware error: System reset
</code>```

I'd like to avoid hacking the insertion of keyboard commands into the build to simulate user intervention. I'd also like to avoid relying on qemu exiting in an error state.

It seems I'm close to a clean exit but not quite there. Searching for the qemu error message (above) has produced no relevant documentation other than tangentially related bug reports.

Is there a mechanism for causing qemu to exit after main() returns in a bare metal program that I'm missing? Will this -no-reboot + system reset strategy work? If so, what else is necessary to allow qemu to exit cleanly?

答:
Following J. Havran answer ,it worked using different assembly, and i was working with zephyr qemu cortex m3 :

```<code>static inline void _exit_qemu() {
  register u32_t r0 __asm__("r0");
  r0 = 0x18;
  register u32_t r1 __asm__("r1");
  r1 = 0x20026;
  __asm__ volatile("bkpt #0xAB");
}
</code>```

and

```<code>qemu-system-arm -cpu cortex-m3 -machine lm3s6965evb -nographic -vga none -net none -pidfile qemu.pid -serial mon:stdio -semihosting -kernel build/zephyr/zephyr.elf
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am assembling a cross compiling unit testing rig for an ARM system and running the tests on a host machine with qemu-system-arm. Specifically, I'm using qemu to emulate the Stellaris LM3S6965 eval board as it contains a Cortex M3 processor like my target environment. The binary run in qemu is built with GNU Tools for ARM.

There is no OS involved. The test suite is run as a bare metal application with qemu in -nographic mode. The toolchain and the test rig itself are working fine. And the tests successfully run to completion and produce test results within qemu just fine as well.

The problem is in wrapping up qemu in an automated build tool (Rake in this case). Other than keyboard commands I have not yet found a good way to cause qemu to exit after the test suite runs and spits out its results. This causes the build environment to hang / rely on user intervention.

I have looked high and low and have found no good sources on how to accomplish a simple exit after program termination. I did find a couple suggestions of running qemu with the -no-reboot option and then triggering a system reset from the program running in the emulator. I have tried this. It works… kinda. I write the appropriate values to the emulated processor's reset vector after main() executes, and this does trigger a reset. After running the test suite qemu reports catching a system reset. However, it reports this as a hardware error, dumps register contents, and then exits angry (error message below). While this does accomplish exiting after the test suite runs, it then breaks the automated build script due to qemu exiting with an error condition.

qemu: hardware error: System reset

I'd like to avoid hacking the insertion of keyboard commands into the build to simulate user intervention. I'd also like to avoid relying on qemu exiting in an error state.

It seems I'm close to a clean exit but not quite there. Searching for the qemu error message (above) has produced no relevant documentation other than tangentially related bug reports.

Is there a mechanism for causing qemu to exit after main() returns in a bare metal program that I'm missing? Will this -no-reboot + system reset strategy work? If so, what else is necessary to allow qemu to exit cleanly?

Body:
Following J. Havran answer ,it worked using different assembly, and i was working with zephyr qemu cortex m3 :

static inline void _exit_qemu() {
  register u32_t r0 __asm__("r0");
  r0 = 0x18;
  register u32_t r1 __asm__("r1");
  r1 = 0x20026;
  __asm__ volatile("bkpt #0xAB");
}

and

qemu-system-arm -cpu cortex-m3 -machine lm3s6965evb -nographic -vga none -net none -pidfile qemu.pid -serial mon:stdio -semihosting -kernel build/zephyr/zephyr.elf

ContentLicense: CC BY-SA 4.0


问:
Is there an equivalent to `line-mode` and `char-mode` (ansi-term) for multi-term?
Any time I try to move around in the buffer (besides moving up and down lines with C-p and C-n), my cursor is brought back to the command line so I cannot select and copy arbitrary text in the multi-term buffer. I can use my mouse to move to and highlight text, and all goes well from there, but is there a set of key bindings that will allow me to set the mark in other parts of the buffer? I looked in multi-term.el` but was not able to find anything that addressed this.

答: Try 'term-line-mode' and 'term-char-mode'</p>


问:
java.lang.NumberFormatException: null i
Here i come up with problem while performing some operation like update,delete and insert  but its return some null value with exception kindly some one could look at the code if its wrong:

Error:

```<code>HTTP Status 500 - null

type Exception report

message null

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.NumberFormatException: null
    java.lang.Integer.parseInt(Integer.java:454)
    java.lang.Integer.parseInt(Integer.java:527)
    Controller.ControllerTest.doGet(ControllerTest.java:48)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.37 logs.

Apache Tomcat/6.0.37
</code>```

user.jsp:

```<code><form method="POST" action='ControllerTest' name="frmAddUser">

  <jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
        <% for(int i = 0; i < users.size(); i+=1)
        {
            UseBean user = (UseBean)users.get(i);
        %>

        id:<input type="text" name="ID" value="<%=user.getID() %>"><br/>
        Name:<input type="text" name="Name" value="<%= user.getName() %>"><br/>
        Password:<input type="text" name="password" value="<%= user.getPassword() %>"><br/>
        phoneno:<input type="text" name="Phoneo" value="<%= user.getPhoneo() %>"><br/>
        Emailid:<input type="text" name="Emailid" value="<%= user.getEmailID() %>">  <br/>

        <%} %>
         <input type="submit" value="Submit" />
    </form>
</code>```

listuser.jsp

```<code>  <body>
<table border=1>
<thead>
    <tr>
    <th>Id</th>
    <th>Name</th>
    <th>password</th>
    <th>phoneno</th>
    <th>emailid</th>
    <th colspan=2>Action</th>
    </tr>
</thead>
<tbody>
    <jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
    <% for(int i = 0; i < users.size(); i+=1)
    {
        UseBean user = (UseBean)users.get(i);
    %>
        <tr>
        <td><%= user.getID() %></td>
        <td><%= user.getName() %></td>
        <td><%= user.getPassword() %></td>
        <td><%= user.getEmailID() %></td>
        <td><%= user.getPhoneo() %></td>
        <td><a href="ControllerTest?action=edit&userId=<%= user.getID() %>" >Update</a></td>
        <td><a href="ControllerTest?action=delete&userId=<%= user.getID() %>">Delete</a></td>
        </tr>
    <% } %>
</tbody>
</table>
<p>
<a href="ControllerTest?action=insert">Add User</a>
</p>
</code>```

Controllertest.java:

```<code>package Controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;
import dbBean.UseBean;

public class ControllerTest extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private static String INSERT_OR_EDIT = "/user.jsp";
    private static String LIST_USER = "/listUser.jsp";

    private UserDao dao;

    public ControllerTest()
    {
        super();
        dao = new UserDao();

    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {

        String forward = "";
        String action = request.getParameter("action");
        if (action.equalsIgnoreCase("delete"))
        {
            try
            {
                int userId = Integer.parseInt(request.getParameter("userId"));
                dao.deleteUser(userId);
                forward = LIST_USER;
                request.setAttribute("users", dao.getAllUsers());
            }
            catch (NumberFormatException ex)
            {

                System.out.println("Error occured with during conversion delete");
            }
        }
        else if (action.equalsIgnoreCase("edit"))
        {
            forward = INSERT_OR_EDIT;
            try
            {

                int userId = Integer.parseInt(request.getParameter("userId"));
                UseBean bean = dao.getUserById(userId);
                request.setAttribute("user", bean);

            } catch (NumberFormatException ex)
            {

                System.out.println("Error occured with during conversion edit");
            }
        }
        else if (action.equalsIgnoreCase("listUser"))
        {
            forward = LIST_USER;
            request.setAttribute("users", dao.getAllUsers());
        } else
        {
            forward = INSERT_OR_EDIT;
        }
        RequestDispatcher view = request.getRequestDispatcher(forward);
        view.forward(request, response);

    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {

        try
        {
            UseBean bean = new UseBean();
            bean.setName(request.getParameter("Name"));
            bean.setPassword(request.getParameter("password"));
            bean.setPhoneo(request.getParameter("Phoneo"));
            bean.setEmailID(request.getParameter("Emailid"));
            String userid = request.getParameter("ID");
            if (userid == null || userid.isEmpty())
            {
                dao.addUser(bean);
            } else
            {
                bean.setID(Integer.parseInt(userid));
                dao.updateUser(bean);
            }
            RequestDispatcher view = request.getRequestDispatcher(LIST_USER);
            request.setAttribute("users", dao.getAllUsers());
            view.forward(request, response);

        }

        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("erro occuring in update code");
        }

    }
}
</code>```

答:
In file user.jsp and listuser.jsp. you used space for URL Rewriting.

you should use

```<code>    <tr>
    <td><%=user.getID()%></td>
    <td><%=user.getName()%></td>
    <td><%=user.getPassword()%></td>
    <td><%=user.getEmailID()%></td>
    <td><%=user.getPhoneo()%></td>
    <td><a href="ControllerTest?action=edit&userId=<%=user.getID()%>" >Update</a></td>
    <td><a href="ControllerTest?action=delete&userId=<%=user.getID()%>">Delete</a></td>
    </tr>
</code>```

Title: java.lang.NumberFormatException: null i

Body:
Here i come up with problem while performing some operation like update,delete and insert  but its return some null value with exception kindly some one could look at the code if its wrong:

Error:

HTTP Status 500 - null

type Exception report

message null

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.NumberFormatException: null
    java.lang.Integer.parseInt(Integer.java:454)
    java.lang.Integer.parseInt(Integer.java:527)
    Controller.ControllerTest.doGet(ControllerTest.java:48)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.37 logs.

Apache Tomcat/6.0.37

user.jsp:

<form method="POST" action='ControllerTest' name="frmAddUser">

  <jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
        <% for(int i = 0; i < users.size(); i+=1)
        {
            UseBean user = (UseBean)users.get(i);
        %>

        id:<input type="text" name="ID" value="<%=user.getID() %>">

        Name:<input type="text" name="Name" value="<%= user.getName() %>">

        Password:<input type="text" name="password" value="<%= user.getPassword() %>">

        phoneno:<input type="text" name="Phoneo" value="<%= user.getPhoneo() %>">

        Emailid:<input type="text" name="Emailid" value="<%= user.getEmailID() %>">

        <%} %>
         <input type="submit" value="Submit" />
    </form>

listuser.jsp

    Id
    Name
    password
    phoneno
    emailid
    Action

    <jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
    <% for(int i = 0; i < users.size(); i+=1)
    {
        UseBean user = (UseBean)users.get(i);
    %>

        <%= user.getID() %>
        <%= user.getName() %>
        <%= user.getPassword() %>
        <%= user.getEmailID() %>
        <%= user.getPhoneo() %>
        <a href="ControllerTest?action=edit&userId=<%= user.getID() %>" >Update
        <a href="ControllerTest?action=delete&userId=<%= user.getID() %>">Delete

    <% } %>

Add User

Controllertest.java:

package Controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;
import dbBean.UseBean;

public class ControllerTest extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private static String INSERT_OR_EDIT = "/user.jsp";
    private static String LIST_USER = "/listUser.jsp";

    private UserDao dao;

    public ControllerTest()
    {
        super();
        dao = new UserDao();

    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {

        String forward = "";
        String action = request.getParameter("action");
        if (action.equalsIgnoreCase("delete"))
        {
            try
            {
                int userId = Integer.parseInt(request.getParameter("userId"));
                dao.deleteUser(userId);
                forward = LIST_USER;
                request.setAttribute("users", dao.getAllUsers());
            }
            catch (NumberFormatException ex)
            {

                System.out.println("Error occured with during conversion delete");
            }
        }
        else if (action.equalsIgnoreCase("edit"))
        {
            forward = INSERT_OR_EDIT;
            try
            {

                int userId = Integer.parseInt(request.getParameter("userId"));
                UseBean bean = dao.getUserById(userId);
                request.setAttribute("user", bean);

            } catch (NumberFormatException ex)
            {

                System.out.println("Error occured with during conversion edit");
            }
        }
        else if (action.equalsIgnoreCase("listUser"))
        {
            forward = LIST_USER;
            request.setAttribute("users", dao.getAllUsers());
        } else
        {
            forward = INSERT_OR_EDIT;
        }
        RequestDispatcher view = request.getRequestDispatcher(forward);
        view.forward(request, response);

    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {

        try
        {
            UseBean bean = new UseBean();
            bean.setName(request.getParameter("Name"));
            bean.setPassword(request.getParameter("password"));
            bean.setPhoneo(request.getParameter("Phoneo"));
            bean.setEmailID(request.getParameter("Emailid"));
            String userid = request.getParameter("ID");
            if (userid == null || userid.isEmpty())
            {
                dao.addUser(bean);
            } else
            {
                bean.setID(Integer.parseInt(userid));
                dao.updateUser(bean);
            }
            RequestDispatcher view = request.getRequestDispatcher(LIST_USER);
            request.setAttribute("users", dao.getAllUsers());
            view.forward(request, response);

        }

        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("erro occuring in update code");
        }

    }
}

Body:
In file user.jsp and listuser.jsp. you used space for URL Rewriting.

you should use

    <tr>
    <td><%=user.getID()%></td>
    <td><%=user.getName()%></td>
    <td><%=user.getPassword()%></td>
    <td><%=user.getEmailID()%></td>
    <td><%=user.getPhoneo()%></td>
    <td><a href="ControllerTest?action=edit&userId=<%=user.getID()%>" >Update</a></td>
    <td><a href="ControllerTest?action=delete&userId=<%=user.getID()%>">Delete</a></td>
    </tr>


问:
Tips to get started with webdevelopment
I am very curious about what you think is the best approach for people that want to start webdevelopment. I'm now talking about people that finished their education and so want to start from scratch.
I still have questions like:

Where do you start?
What software gets involved in webdevelopment?
What tools / setup would you recommend?

Offcourse i'm interested to hear alot more then only the answers to those three questions.
I am not writing this to get a load of people react on my post, i am trully interested in knowing how much work and money it will cost a webdeveloper when starting from scratch.
I hope to get a clear view on how to approach and to maybe hear some best practices.

答:
you need:

a google chrome . This provide you some advantage like inspect option. A webdeveloper toolbar might also be useful.
2. Html, Css, JavaScript are the basic language that you should be know
a programming environment, eg. Php or ASP.NET is needed for storing data and making login type page
a Visual Code Studio is needed for coding. This provide you emmet facilities that suggest you while you are coding

ContentLicense: CC BY-SA 2.5

Title: Tips to get started with webdevelopment


问:
Android ViewModel responsibility is only hold data or hold data + controller for view?
From official we know

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way

But i think lot of developers use ViewModel as both data store and controller(like calling repository, network client for data). I also use as for both data store and controller for view.

Android official sample code has also some controller logic. From official :

```<code>class MyViewModel : ViewModel() {
  private val users: MutableLiveData<List<User>> by lazy {
     MutableLiveData().also {
        loadUsers()
     }
  }

  fun getUsers(): LiveData<List<User>> {
    return users
  }

  private fun loadUsers() {
    // Do an asynchronous operation to fetch users.
  }
}
</code>```

Here loadUsers may calling some Repository or NetworkClient . So here it acting like controller.

I am sure many developer do this way, but as from definition ViewModel should store and manage UI related data, should ViewModel act as a Controller ?

I found some stackoverflow thread this and this about this.

First one accepted answer suggested not to use use ViewModel as Controller and to use a Controller for other task.

In comment section of Second one @commonsware also suggested not to use complicated things other than data.

So my question is

What will be the actual responsibility of ViewModel from architectural concept?

If i have to do some method calls related to View [like data query, network call and other business login related stuff ] where should i do it?

and if i have to use a Controller then how i connect View and Controller for device rotation and sharing controller between Fragment ?

Hope my question is clear to all

Thanks in advance.

答:
Here loadUsers() may calling some Repository or NetworkClient . So here it acting like controller.

I am sure many developer do this way, but as from definition ViewModel should store and manage UI related data, should ViewModel act as a Controller ?

Theoretically, the retrieval of data should be internal to the LiveData, triggered by having active observers and based on that, deciding what to do (in onActive()). If the LiveData is actually a MediatorLiveData, then this also applies to any block bound with addSource, as the block added with addSource of a MediatorLiveData is only called when the MediatorLiveData is observed by an active observer

You can see this technique used to its fullest in the NetworkBoundResource. The ViewModel only stores data, and knows nothing of data loading.

What will be the actual responsibility of ViewModel from architectural concept?

If you see the comments by Yigit Boyar (creator of ViewModel):

I'm the guy (or part of the team) that added it and it had nothing to do w/ MVVM. It is all about trying to give a class to people where they should put the data.

AAC is not an MVVM implementation, nor VM concept only lives as part of MVVM.

In fact, the main motivation for this was; we've been telling devs not to manage data in the UI controller and the answers was also, so where? And ViewModel became that answer.

We want it to be the model for your view layer (fragment, activity whatever). On the hindsight, it could be better to pick a name that is new but naming is really hard.

In conclusion: ViewModel is the Model in an MVC scenario, where C is the Activity or Fragment, V is the inflated view, and M is the ViewModel.

If i have to do some method calls related to View [like data query, network call and other business login related stuff ] where should i do it?

ViewModel gets the data in the form of a LiveData, and the LiveData is "activated" by observing it from the View with a given lifecycle.

Network calls are supposed to be also triggered in the same manner (if you follow the approach as per LiveData was designed).

In theory, if you have a login call, you could as well do it in the controller instead of the model, so you could do it in the Fragment, even though there are tricks like Jetpack Databinding that would let you call methods from the View on the Model directly from the XML.

and if i have to use a Controller then how i connect View and Controller for device rotation and sharing controller between Fragment ?

ViewModel exposes LiveData and can potentially also expose LiveEvent if you write the necessary code for that (unfortunately that is not provided by the Jetpack team, and neither are Command bindings), and either the View or the Controller can call methods directly on it if necessary. ViewModel is stored across config changes (not across process death, ofc) so it should not hold a direct view reference.

Body:
From official we know

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way

But i think lot of developers use ViewModel as both data store and controller(like calling repository, network client for data). I also use as for both data store and controller for view.

Android official sample code has also some controller logic. From official :

class MyViewModel : ViewModel() {
  private val users: MutableLiveData<List<User>> by lazy {
     MutableLiveData().also {
        loadUsers()
     }
  }

  fun getUsers(): LiveData<List<User>> {
    return users
  }

  private fun loadUsers() {
    // Do an asynchronous operation to fetch users.
  }
}

Here loadUsers may calling some Repository or NetworkClient . So here it acting like controller.

I am sure many developer do this way, but as from definition ViewModel should store and manage UI related data, should ViewModel act as a Controller ?

I found some stackoverflow thread this and this about this.

First one accepted answer suggested not to use use ViewModel as Controller and to use a Controller for other task.

In comment section of Second one @commonsware also suggested not to use complicated things other than data.

So my question is

What will be the actual responsibility of ViewModel from architectural concept?

If i have to do some method calls related to View [like data query, network call and other business login related stuff ] where should i do it?

and if i have to use a Controller then how i connect View and Controller for device rotation and sharing controller between Fragment ?

Hope my question is clear to all

Thanks in advance.


问:
Using Hindi Font in HTML Websites
I want to create a website in hindi font. for this i have tried @font-family: "Kruti Dev" etc. but I feel that this website will require hindi font on every user's pc.

What's the best way to use hindi font on a website ?

答:
use meta tag

    <meta charset="UTF-8" />
    <title>Hindi Font का उपयोग</title>

We Can Use Hindi Font

इस Page में हम हिन्दी भाषा का उपयोग करेंगे

We Can also use Hindi Hex Code

इस Page में हम हिन्दी भाषा उपयोग करेंगे

Hindi Code Entity

```

Title: Using Hindi Font in HTML Websites

Body:
use meta tag

<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hindi Font का उपयोग</title>
  </head>
  <body>
    <h1>We Can Use Hindi Font</h1>
    <p>इस Page में हम हिन्दी भाषा का उपयोग करेंगे</p>
    <h1>We Can also use Hindi Hex Code</h1>
    <p>&#x0907;&#x0938;&nbsp;Page&nbsp;&#x092E;&#x0947;&#x0902;&nbsp;&#x0939;&#x092E;&nbsp;&#x0939;&#x093F;&#x0928;&#x094D;&#x0926;&#x0940;&nbsp;&#x092D;&#x093E;&#x0937;&#x093E;&nbsp;&#x0909;&#x092A;&#x092F;&#x094B;&#x0917;&nbsp;&#x0915;&#x0930;&#x0947;&#x0902;&#x0917;&#x0947;</p>

    <a href="https://www.anirdesh.com/gujarati/hindi-unicode.php"><h1>Hindi Code Entity</h1></a>
  </body>
</html>


问:
iOS: How to get Audio Sample Rate from AVAsset or AVAssetTrack
After loading an AVAsset like this:

```<code>AVAsset *asset = [AVAsset assetWithURL:url];
</code>```

I want to know what the Sampling Rate is of the Audio track. Currently, I am getting the Audio Track like this:

```<code>AVAssetTrack *audioTrack = [[asset tracksWithMediaCharacteristic:AVMediaCharacteristicAudible] objectAtIndex:0];
</code>```

Which works. But I can't seem to find any kind of property, not even after using Google ;-) , that gives me the sampling rate. How does this work normally ? Is it even possible ? (I start doubting more and more, because Googling is not giving me a lot of information ...)

答:
Using Swift and AVFoundation :

```<code>let url = Bundle.main.url(forResource: "audio", withExtension: "m4a")!
let asset = AVAsset(url: url)
if let firstTrack = asset.tracks.first {
    print("bitrate: \(firstTrack.estimatedDataRate)")
}
</code>```

To find more information in your metadata, you can also consult:
https://developer.apple.com/documentation/avfoundation/avassettrack
https://developer.apple.com/documentation/avfoundation/media_assets_playback_and_editing/finding_metadata_values

Body:
After loading an AVAsset like this:

AVAsset *asset = [AVAsset assetWithURL:url];

I want to know what the Sampling Rate is of the Audio track. Currently, I am getting the Audio Track like this:

AVAssetTrack *audioTrack = [[asset tracksWithMediaCharacteristic:AVMediaCharacteristicAudible] objectAtIndex:0];

Which works. But I can't seem to find any kind of property, not even after using Google ;-) , that gives me the sampling rate. How does this work normally ? Is it even possible ? (I start doubting more and more, because Googling is not giving me a lot of information ...)

Body:
Using Swift and AVFoundation :

let url = Bundle.main.url(forResource: "audio", withExtension: "m4a")!
let asset = AVAsset(url: url)
if let firstTrack = asset.tracks.first {
    print("bitrate: \(firstTrack.estimatedDataRate)")
}

To find more information in your metadata, you can also consult:
https://developer.apple.com/documentation/avfoundation/avassettrack
https://developer.apple.com/documentation/avfoundation/media_assets_playback_and_editing/finding_metadata_values


问:
how to get the sum of values in 2 textboxes that gets updated C#
I have 2 textboxes that get updated regularly, via serial port each of them displays data on 1 line, I want to get the sum of these values from these textboxes and put the sum into another text box.

Code:

```<code>value 1 and 2 are type string
textbox1.text = value1;
textbox2.text = value2;

double value3 = convert.ToDouble(value1) + convert.ToDouble(value2);
textbox3.text = value3.ToString();
</code>```

Output textbox1:

```<code>100, after sometime updates to 200, then 300
</code>```

Output textbox2:

```<code>50, after sometime updates to 100, then 150
</code>```

What I'm getting, output in textbox3:

```<code>150, after some time updates to 300, then 450
</code>```

The value I should get is

```<code>100+200+300+50+100+150
</code>```

答:
When you are getting input from text field in C# you will get string data as input. For integer operations, you need to convert your string input from text using Parse method.

Try

```<code>Int16.Parse()
Int32.Parse()
Int64.Parse()
</code>```

Body:
I have 2 textboxes that get updated regularly, via serial port each of them displays data on 1 line, I want to get the sum of these values from these textboxes and put the sum into another text box.

Code:

value 1 and 2 are type string
textbox1.text = value1;
textbox2.text = value2;

double value3 = convert.ToDouble(value1) + convert.ToDouble(value2);
textbox3.text = value3.ToString();

Output textbox1:

100, after sometime updates to 200, then 300

Output textbox2:

50, after sometime updates to 100, then 150

What I'm getting, output in textbox3:

150, after some time updates to 300, then 450

The value I should get is

100+200+300+50+100+150

Body:
When you are getting input from text field in C# you will get string data as input. For integer operations, you need to convert your string input from text using Parse method.

Try

Int16.Parse()
Int32.Parse()
Int64.Parse()


问:
CKEditor 5 image resize in Angular
I install CKEditor5 in Angular project, it works fine but i have a problem with resize image.
I see the documentation in this link: https://ckeditor.com/docs/ckeditor5/latest/features/image.html#installation but i'm not able to implement it correctly. ImageResize is the only plugin that not active by default, how can i activate? where?

I tried to add it as plugin but i have a error that said there are duplicate declaration of CKEditor5
Here is component code about CKEditor

```<code>import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import '@ckeditor/ckeditor5-build-classic/build/translations/it';

  public Editor = ClassicEditor;

  public config = {
    language: 'it',
    placeholder: 'Descrivi il tuo procedimento scrivendo e inserendo immagini',
    ckfinder: {

      uploadUrl: environment.laravel_api+'/upload-image-step?command=QuickUpload&type=Images&responseType=json',

      options: {
        resourceType: 'Images'
      }
    },
    image: {
      resizeUnit:'%',
      toolbar: [ 'imageTextAlternative', '|', 'imageStyle:alignLeft', 'imageStyle:full', 'imageStyle:alignRight' ],

      styles: [

        'full',

        'alignLeft',

        'alignRight'
      ],

    },

  };
</code>```

In view i have this

```<code><ckeditor id="editor" style="width: 100%;" [editor]="Editor" [config]="config" data="" formControlName="editor"></ckeditor>
</code>```

答:
I was having the same issue but was eventually able to figure it out.

Essentially, I followed the steps outlined here:
https://ckeditor.com/docs/ckeditor5/latest/builds/guides/development/custom-builds.html

The gist is that if you need plugins, you simply have to use a custom built module.

The following is roughly what I did (using Angular 9)...

First, create the custom build

1. Clone the base repo.
I ended up cloning it into the /assets directory within my Angular app

git clone https://github.com/ckeditor/ckeditor5-build-classic.git
```

<p><strong>2. Within the newly cloned repo, install the <code>@ckeditor/ckeditor5-image</code> package</strong></p>

<pre class="lang-sh prettyprint-override"><code>cd ckeditor5
npm install --save @ckeditor/ckeditor5-image
</code>```

3. Open and edit the src/ckeditor.js file, and import ImageResize

import ImageResize from '@ckeditor/ckeditor5-image/src/imageresize';
...
```

<p><strong>4. Within the same <code>src/ckeditor.js</code> file, add <code>ImageResize</code> to the plugins list</strong></p>

<pre class="lang-js prettyprint-override"><code>// Plugins to include in the build.
ClassicEditor.builtinPlugins = [
    Essentials,
    Alignment,
    ImageResize, // <----
    ...
];
</code>```

5. Save the file and build

npm run build
```

<h1>Then, use the build in your Angular app</h1>

<p><strong>1. First, ensure that you have the CKEditor Angular component, which still needs to be defined in your app module</strong></p>

<pre class="lang-js prettyprint-override"><code>import { CKEditorModule } from '@ckeditor/ckeditor5-angular';
...
imports: [
    CKEditorModule
    ...
]
</code>```

2. Finally, use your new custom CKEditor build inside of your component instead of the base one that you were using before:

// Your existing code, which is using a pre-built build
import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
```

<p>Should be changed to point to the new custom one in the /assets directory</p>

<pre class="lang-js prettyprint-override"><code>// Obviously, change to suit your directory structure
import * as ClassicEditor from '../../assets/ckeditor5';
</code>```

3. That's it! the plugins should now work as described. Just note that you will need to re-build anytime you want to add additional plugins.

Title: CKEditor 5 image resize in Angular

Body:
I install CKEditor5 in Angular project, it works fine but i have a problem with resize image.
I see the documentation in this link: https://ckeditor.com/docs/ckeditor5/latest/features/image.html#installation but i'm not able to implement it correctly. ImageResize is the only plugin that not active by default, how can i activate? where?

I tried to add it as plugin but i have a error that said there are duplicate declaration of CKEditor5
Here is component code about CKEditor

import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import '@ckeditor/ckeditor5-build-classic/build/translations/it';

  public Editor = ClassicEditor;

  public config = {
    language: 'it',
    placeholder: 'Descrivi il tuo procedimento scrivendo e inserendo immagini',
    ckfinder: {

      uploadUrl: environment.laravel_api+'/upload-image-step?command=QuickUpload&type=Images&responseType=json',

      options: {
        resourceType: 'Images'
      }
    },
    image: {
      resizeUnit:'%',
      toolbar: [ 'imageTextAlternative', '|', 'imageStyle:alignLeft', 'imageStyle:full', 'imageStyle:alignRight' ],

      styles: [

        'full',

        'alignLeft',

        'alignRight'
      ],

    },

  };

In view i have this

<ckeditor id="editor" style="width: 100%;" [editor]="Editor" [config]="config" data="" formControlName="editor"></ckeditor>

Body:
I was having the same issue but was eventually able to figure it out.

Essentially, I followed the steps outlined here:
https://ckeditor.com/docs/ckeditor5/latest/builds/guides/development/custom-builds.html

The gist is that if you need plugins, you simply have to use a custom built module.

The following is roughly what I did (using Angular 9)...

First, create the custom build

1. Clone the base repo.
I ended up cloning it into the /assets directory within my Angular app

git clone https://github.com/ckeditor/ckeditor5-build-classic.git

2. Within the newly cloned repo, install the @ckeditor/ckeditor5-image package

cd ckeditor5
npm install --save @ckeditor/ckeditor5-image

3. Open and edit the src/ckeditor.js file, and import ImageResize

import ImageResize from '@ckeditor/ckeditor5-image/src/imageresize';
...

4. Within the same src/ckeditor.js file, add ImageResize to the plugins list

// Plugins to include in the build.
ClassicEditor.builtinPlugins = [
    Essentials,
    Alignment,
    ImageResize, // <----
    ...
];

5. Save the file and build

npm run build

Then, use the build in your Angular app

1. First, ensure that you have the CKEditor Angular component, which still needs to be defined in your app module

import { CKEditorModule } from '@ckeditor/ckeditor5-angular';
...
imports: [
    CKEditorModule
    ...
]

2. Finally, use your new custom CKEditor build inside of your component instead of the base one that you were using before:

// Your existing code, which is using a pre-built build
import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';

Should be changed to point to the new custom one in the /assets directory

// Obviously, change to suit your directory structure
import * as ClassicEditor from '../../assets/ckeditor5';

3. That's it! the plugins should now work as described. Just note that you will need to re-build anytime you want to add additional plugins.


问:
PHP additional parameters to usort
The following code lays within a function which itself lays within a class. Its purpose is to avoid having one sorting function per $filter value :

```<code>$GLOBAL['filter'] = $filter;
usort($this->data, function($arr1, $arr2) {
    return ($arr1[$GLOBALS['filter']] > $arr2[$GLOBALS['filter']]) ? 1 : -1;
});
</code>```

My solution works perfectly fine, but I find it rather inelegant. Would somebody have an idea to acheive the same goal without resorting to the $GLOBALS variable ?

Thanks for your propositions

答:
```<code>   public function sortList($params, $listToSort)
    {
        if (!isset($listToSort) || !isset($params) || count($params) == 0) {
            return $listToSort;
        }
        foreach ($params as $col => $value) {
            $orderFlag = $value == 'asc' ? 1 : -1;
            usort($listToSort, function ($a, $b) use ($orderFlag, $col) {
                return strcmp($a[$col], $b[$col]) * $orderFlag;
            });
        }
    return $listToSort;
}
</code>```

Above $params is json eg: {name : 'asc', age : 'desc'} and $listToSort is array of array eg: array(array('name': 'Himanshu', age: 22), array('name': 'Steve', age: 35))

Place this code in Utils.php of your project as it is a general solution.

Title: PHP additional parameters to usort

Body:
The following code lays within a function which itself lays within a class. Its purpose is to avoid having one sorting function per $filter value :

$GLOBAL['filter'] = $filter;
usort($this->data, function($arr1, $arr2) {
    return ($arr1[$GLOBALS['filter']] > $arr2[$GLOBALS['filter']]) ? 1 : -1;
});

My solution works perfectly fine, but I find it rather inelegant. Would somebody have an idea to acheive the same goal without resorting to the $GLOBALS variable ?

Thanks for your propositions

Body:
   public function sortList($params, $listToSort)
    {
        if (!isset($listToSort) || !isset($params) || count($params) == 0) {
            return $listToSort;
        }
        foreach ($params as $col => $value) {
            $orderFlag = $value == 'asc' ? 1 : -1;
            usort($listToSort, function ($a, $b) use ($orderFlag, $col) {
                return strcmp($a[$col], $b[$col]) * $orderFlag;
            });
        }
    return $listToSort;
}

Above $params is json eg: {name : 'asc', age : 'desc'} and $listToSort is array of array eg: array(array('name': 'Himanshu', age: 22), array('name': 'Steve', age: 35))

Place this code in Utils.php of your project as it is a general solution.


问:
CefSharp get a part from a Source Code of a selected/active element

Hello everyone  and already thanks in advance!

I need to somehow get only a part of a loaded Website Source Code (Picture point 2) by hovering (if not possible I would also be happy with a mouse click) over an element (Picture point 1).
I know it sounds maybe weird because the DevTool does it already really nice with just a click (Picture point 3).
But if possible I would like to only read out the inner- and outer-HTML (whichever I need in the moment) the part which is active/selected.

What I have reached is:

```<code>int counter = 0;

private async void timer1_Tick(object sender, EventArgs e)
{
        string returnValue = "";

        string script = "(function() { return document.activeElement.outerHTML; })();";

        var task = browser.GetMainFrame().EvaluateScriptAsync(script);

        await task.ContinueWith(t =>
        {
            if (!t.IsFaulted)
            {
                var response = t.Result;

                if (response.Success && response.Result != null)
                {
                    returnValue = response.Result.ToString();
                }
            }
        });

        if (returnValue != "")
        {
            richTextBox1.Invoke(new Action(() => richTextBox1.Text = returnValue));
        }
        else // Just to check if there still happens something:
        {
            counter += 1;
            richTextBox1.Invoke(new Action(() => richTextBox1.Text = counter.ToString() ));
        }
}
</code>```

With this code the problem seems solved . But I wonder if there is an "better" way without an timer.

答:
The answer or lets say the better solution is (thanks to @amaitland) to throw that timer away and use instead (in Form_Load or whereever you setup everything):

```<code>browser.JavascriptMessageReceived += OnBrowserJavascriptMessageReceived;
browser.FrameLoadEnd += Browser_FrameLoadEnd;
</code>```

and put my code in:

```<code>private void OnBrowserJavascriptMessageReceived(object sender, JavascriptMessageReceivedEventArgs e)
{
    // the code
}
</code>```

And also you need:

```<code>async void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{ // Does wait till the Website is fully loaded.
    if (e.Frame.IsMain)
    {
        //In the main frame we inject some javascript that's run on mouseUp
        //You can hook any javascript event you like.
        browser.ExecuteScriptAsync(@"
              document.body.onmouseup = function()
              {
                //CefSharp.PostMessage can be used to communicate between the browser
                //and .Net, in this case we pass a simple string,
                //complex objects are supported, passing a reference to Javascript methods
                //is also supported.
                //See https://github.com/cefsharp/CefSharp/issues/2775#issuecomment-498454221 for details
                CefSharp.PostMessage(window.getSelection().toString());
              }
        ");
    }
}
</code>```

Body:
Hello everyone  and already thanks in advance!

I need to somehow get only a part of a loaded Website Source Code (Picture point 2) by hovering (if not possible I would also be happy with a mouse click) over an element (Picture point 1).
I know it sounds maybe weird because the DevTool does it already really nice with just a click (Picture point 3).
But if possible I would like to only read out the inner- and outer-HTML (whichever I need in the moment) the part which is active/selected.

What I have reached is:

int counter = 0;

private async void timer1_Tick(object sender, EventArgs e)
{
        string returnValue = "";

        string script = "(function() { return document.activeElement.outerHTML; })();";

        var task = browser.GetMainFrame().EvaluateScriptAsync(script);

        await task.ContinueWith(t =>
        {
            if (!t.IsFaulted)
            {
                var response = t.Result;

                if (response.Success && response.Result != null)
                {
                    returnValue = response.Result.ToString();
                }
            }
        });

        if (returnValue != "")
        {
            richTextBox1.Invoke(new Action(() => richTextBox1.Text = returnValue));
        }
        else // Just to check if there still happens something:
        {
            counter += 1;
            richTextBox1.Invoke(new Action(() => richTextBox1.Text = counter.ToString() ));
        }
}

With this code the problem seems solved . But I wonder if there is an "better" way without an timer.

Body:
The answer or lets say the better solution is (thanks to @amaitland) to throw that timer away and use instead (in Form_Load or whereever you setup everything):

browser.JavascriptMessageReceived += OnBrowserJavascriptMessageReceived;
browser.FrameLoadEnd += Browser_FrameLoadEnd;

and put my code in:

private void OnBrowserJavascriptMessageReceived(object sender, JavascriptMessageReceivedEventArgs e)
{
    // the code
}

And also you need:

async void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{ // Does wait till the Website is fully loaded.
    if (e.Frame.IsMain)
    {
        //In the main frame we inject some javascript that's run on mouseUp
        //You can hook any javascript event you like.
        browser.ExecuteScriptAsync(@"
              document.body.onmouseup = function()
              {
                //CefSharp.PostMessage can be used to communicate between the browser
                //and .Net, in this case we pass a simple string,
                //complex objects are supported, passing a reference to Javascript methods
                //is also supported.
                //See https://github.com/cefsharp/CefSharp/issues/2775#issuecomment-498454221 for details
                CefSharp.PostMessage(window.getSelection().toString());
              }
        ");
    }
}


问:
jQuery Ajax Request without loading results
Hey all, i'm really new to ajax and all i want to do is call an ajax function that doesn't return anything. I've used

$('#myDiv').load('/ajaxScript.asp');

and that loads the results to myDiv just fine. I just want to run the ajax without returning anything at all. Just run my code. How do i do this? Also, how do i detect when it is done doing it's thing? Thanks all!

答:
Use the simple functions:

```<code>jQuery.post("{url}", {parameters}, function(data, status){}, "text");
</code>```

or

```<code>jQuery.get("{url}", {parameters}, function(data, status){}, "text");
</code>```

See http://api.jquery.com/jQuery.post/ or http://api.jquery.com/jQuery.get/. The function will get called when the request returns.

Body:
Use the simple functions:

jQuery.post("{url}", {parameters}, function(data, status){}, "text");

or

jQuery.get("{url}", {parameters}, function(data, status){}, "text");

See http://api.jquery.com/jQuery.post/ or http://api.jquery.com/jQuery.get/. The function will get called when the request returns.


问:
Index of vector of strings in c++
I have a vector of string including :- chemistry physics maths.
I want to access first character of each word ie c of chemistry p of physics and m of maths. How to do that? </p>

答:
You can treat it like a 2D matrix of characters.

Given the vector of strings:

```<code>std::vector<std::string> vec = {"chemestry", "physics", "math"};
</code>```

You can use a normal loop to access all first characters:

```<code>for (int i = 0; i < vec.size(); i++)
    std::cout << vec[i][0] << " ";
</code>```

Or a range based loop:

```<code>for (auto &str : vec)
    std::cout << str[0] << " ";
</code>```

Output:

```<code>c p m
</code>```

Title: Index of vector of strings in c++

Body:
You can treat it like a 2D matrix of characters.

Given the vector of strings:

std::vector<std::string> vec = {"chemestry", "physics", "math"};

You can use a normal loop to access all first characters:

for (int i = 0; i < vec.size(); i++)
    std::cout << vec[i][0] << " ";

Or a range based loop:

for (auto &str : vec)
    std::cout << str[0] << " ";

Output:

c p m


问:
How to align images of a known object with a 3D model of that object using opencv?
I have a CAD model of an object in Blender software. And I had printed it out and took some photos of it.

I need to use the Blender software to render some synthetic images of the object. My task is to create rendered images as similar as possible to the photos which I took for the printed model. In the Blender software, there is a camera view to capture images to render. What I have are:

CAD model of the object

photos of the object

background photo

What I get now is:

But obviously, the perspective and orientation of the 3D model in the synthetic image are not as same as the real photo's. How can I do to match them?

答: Normally, this is a problem of different interpretation of the camera coordinate systems. For example, opencv interprets the z-axis or the camera to be aligned with the optical axis of the camera and going from outside to inside. You can check how the blender interprets the camera coordinate system and transform it to match opencv.</p>


问:
try/except issue in Python
I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below:

Following is the code:

```<code>sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)
</code>```

答:
Ideally, you put as less code as possible into a try-block and try to not repeat code, this makes it easier to debug/find errors in programs.

A more pythonic version of the 'questioning' would look like this:

```<code># define a dictionary to save the user input
userInput = {
    'hours': None,
    'rate': None
}

# The input lines are identical so you can just 'exchange' the question.
# Dynamically ask for user input and quit immedialy in case of non-float
for question in userInput.keys():
    try:
        userInput[question] = float(input(f"Enter {question}:"))
    except:
        print('Error, please enter numeric input')
        quit()

# continue with the original code
fh, fr = userInput['hours'], userInput['rate']
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:", xp)
</code>```

Title: try/except issue in Python

Body:
I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below:

Following is the code:

sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

Body:
Ideally, you put as less code as possible into a try-block and try to not repeat code, this makes it easier to debug/find errors in programs.

A more pythonic version of the 'questioning' would look like this:

# define a dictionary to save the user input
userInput = {
    'hours': None,
    'rate': None
}

# The input lines are identical so you can just 'exchange' the question.
# Dynamically ask for user input and quit immedialy in case of non-float
for question in userInput.keys():
    try:
        userInput[question] = float(input(f"Enter {question}:"))
    except:
        print('Error, please enter numeric input')
        quit()

# continue with the original code
fh, fr = userInput['hours'], userInput['rate']
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:", xp)


问:
chown: invalid user: ‘+x’
some_file.py:

```<code>#! /usr/bin/python
print("Hello World!")
</code>```

On terminal:

```<code>sudo chown +x some_file.py
chown: invalid user: ‘+x’
</code>```

I want to make the file executable.

答:
The chown command stands for change ownership. That's why you get invalid user: ‘+x’, because it was expecting a user as input.

If you want to change permissions of a file you must use the chmod command. To make a file executable for the user owner of that file you could try

```<code>chmod u+x some_file.py
</code>```

Title: chown: invalid user: ‘+x’

Body:
some_file.py:

#! /usr/bin/python
print("Hello World!")

On terminal:

sudo chown +x some_file.py
chown: invalid user: ‘+x’

I want to make the file executable.

Body:
The chown command stands for change ownership. That's why you get invalid user: ‘+x’, because it was expecting a user as input.

If you want to change permissions of a file you must use the chmod command. To make a file executable for the user owner of that file you could try

chmod u+x some_file.py


问:
How can I make TypeScript deconstruct function parameter, assign default value, and optional whole object type at same time?
Please see this minimum function

```<code>function addX({ num = 1 }) {
  return num + 1;
}
</code>```

The above function has done two things

Deconstruct function parameter

Assign default value

Now, I can use the function like this:

```<code>add({ num: 2 }); // valid
add({}); // valid
</code>```

However, I can't use it like this

```<code>add(); // Expected 1 arguments, but got 0
</code>```

I can't find a way to tell TypeScript the whole object is optional

```<code>// Invalid
function add({ num = 1 }?) {
  return num + 1;
}

// Invalid
function add({ num = 1 }?: { num: number }) {
  return num + 1;
}
</code>```

How can I achieve it?

答:
How about this</p>

```<code>function addX({ num = 1 } = {num: 1}) {
  return num + 1;
}

addX() // returns 2

addX({}) // returns 2

addX({num: 2}) // returns 3
</code>```

Body:
Please see this minimum function

function addX({ num = 1 }) {
  return num + 1;
}

The above function has done two things

Deconstruct function parameter

Assign default value

Now, I can use the function like this:

add({ num: 2 }); // valid
add({}); // valid

However, I can't use it like this

add(); // Expected 1 arguments, but got 0

I can't find a way to tell TypeScript the whole object is optional

// Invalid
function add({ num = 1 }?) {
  return num + 1;
}

// Invalid
function add({ num = 1 }?: { num: number }) {
  return num + 1;
}

How can I achieve it?

Body:
How about this

function addX({ num = 1 } = {num: 1}) {
  return num + 1;
}

addX() // returns 2

addX({}) // returns 2

addX({num: 2}) // returns 3


问:
Determining binary/text file type in Java?
Namely, how would you tell an archive (jar/rar/etc.) file from a textual (xml/txt, encoding-independent) one?</p>

答:
There's no guaranteed way, but here are a couple of possibilities:

Look for a header on the file.  Unfortunately, headers are file-specific, so while you might be able to find out that it's a RAR file, you won't get the more generic answer of whether it's text or binary.

Count the number of character vs. non-character types.  Text files will be mostly alphabetical characters while binary files - especially compressed ones like rar, zip, and such - will tend to have bytes more evenly represented.

Look for a regularly repeating pattern of newlines.

OwnerDisplayName: gsmd

OwnerDisplayName: Aric TenEyck


问:
How to save images in camera roll in iphone programmatically?
I am developing one application. In that I want to save my pictures in camera roll. So how to save my pictures in camera roll through code?</p>

答:
The most basic way (and the only way if you're targeting iOS before 4.0) is to use UIImageWriteToSavedPhotosAlbum. This lets you specify a selector to be called on a target object when the save is complete.

In 4.0, you can use ALAssetsLibrary's writeImageToSavedPhotosAlbum:orientation:completionBlock: to write the image; in this case, you provide a block to be called when the save is complete.

In 4.1, you can also use ALAssetsLibrary's writeImageDataToSavedPhotosAlbum:metadata:completionBlock: or writeImageToSavedPhotosAlbum:metadata:completionBlock: to write an image along with metadata (e.g. geotagging information). The former is also the only way to write an image from an NSData object without first loading it as a UIImage or CGImageRef.


问:
Import Error when using pandas_datareader.data using Spyder in Anaconda
When importing pandas_datareader.data as web, I am getting the following error:

ImportError: cannot import name 'assert_raises_regex' from 'pandas.util.testing'

I am using Spyder from the Anaconda Navigator and I have tried updating Spyder, Anaconda and made sure I had the latest version of pandas

I am new to python so I might be missing something...

答: You should install the latest version of pandas-datareader from anaconda as the warning sayspandas.util.testing is being deprecated in favor of pandas.testing. A look at the source https://github.com/pydata/pandas-datareader/blob/master/pandas_datareader/compat/init.py shows the pandas_datareader.compat module using pandas.testing instead.


问:
Can't access docker application from localhost using docker-compose
before I start: I have searched this question already and implemented what the "Solutions" were and it did not help (setting host to 0.0.0.0). So, with that out of the way,

Directory structure

```<code>|-- osr
|    |-- __init__.py
|-- requirements.txt
|-- Dockerfile
|-- docker-compose.yml
</code>```

Dockerfile:

```<code>FROM python:3.7.5-buster

EXPOSE 5000 # i have tried with and without this

ENV INSTALL_PATH /osr
ENV FLASK_APP osr
ENV FLASK_ENV development
RUN mkdir -p $INSTALL_PATH

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . .

CMD [ "flask", "run", "--host=0.0.0.0"]
</code>```

docker-compose.yml:

```<code>version: '3.8'
services:
    web:
        build: .
        ports:
            - '5000:5000'
        expose:
            - '5000'
        volumes:
            - .:/osr
</code>```

__ init __.py

```<code>import os
from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev'
    )

    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    return app
</code>```

docker-compose build web
docker-compose run web

```<code> * Serving Flask app "osr" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 225-441-434
</code>```

all of the below return "hmm can't reach this page"

```<code>http://localhost
http://localhost:5000/hello
http://127.0.0.1:5000/hello
</code>```

I've even tried going to the containers IP with

docker exec -it 49e677 bash
ip add | grep global
    inet 172.21.0.2/16 brd 172.21.255.255 scope global eth0

```<code>http://127.21.0.2:5000/hello # nothing
</code>```

Nothing.

I'm sure the app itself works fine as I can simply run the app directly.

```<code>$env:FLASK_APP="osr"
$env:FLASK_ENV="development"
flask run --host=0.0.0.0
</code>```

And it runs fine

EDIT: UPDATE

I am actually able to get to the container when I run it through simply the Dockerfile... using

docker run -it -p 5000:5000 osr_web # the container built by docker-compose build

With this, I am able to access the endpoint through localhost:5000/hello

So the issue appears to lie in spinning it up through docker-compose run

Does this help at all?

UPDATE 2

I have discovered that when I run docker ps -a I can see that Docker run actually exposes the port, but docker-compose run does not:

答:
Are you sure app works fine itself? I tried to run your python __init__.py file and ended up with an error.

```<code>python osr/__init__.py
  File "osr/__init__.py", line 11
    def hello():
    ^
IndentationError: unexpected indent
</code>```

It works after fixing the indentation error.

```<code>@app.route('/hello')
def hello():
    return 'Hello, World!'

$ docker run -d -p 5000:5000 harik8/osr:latest
76628f86fecb61c0be4a969d3c91c5c575702ad8063b594a6c1c90b498ea25f1

$ curl http://127.0.0.1:5000/hello
Hello, World!
</code>```

You can't run both docker and docker-compose in port 5000 at the same time. Either run one at a time or change the docker-compose/dockerfile host port.

```<code>$ docker ps -a | grep osr
8b885c4a9654        harik8/osr:latest                                     "flask run --host=0.…"   12 seconds ago       Up 11 seconds               0.0.0.0:5000->5000/tcp
$ docker ps -a | grep q5
70f38bf11e26        q5_web                                                "flask run --host=0.…"   About a minute ago   Up 10 seconds               0.0.0.0:5001->5000/tcp
</code>```

```<code>$ docker ps -a | grep q5
f9f6ba999109        q5_web                                                "flask run --host=0.…"   5 minutes ago       Up 5 minutes                0.0.0.0:5000->5000/tcp                                                                                q5_web_1
$ docker ps -a | grep osr
93fb421333e4        harik8/osr:latest                                     "flask run --host=0.…"   18 seconds ago      Up 18 seconds               5000/tcp
</code>```

Body:
before I start: I have searched this question already and implemented what the "Solutions" were and it did not help (setting host to 0.0.0.0). So, with that out of the way,

Directory structure

|-- osr
|    |-- __init__.py
|-- requirements.txt
|-- Dockerfile
|-- docker-compose.yml

Dockerfile:

FROM python:3.7.5-buster

EXPOSE 5000 # i have tried with and without this

ENV INSTALL_PATH /osr
ENV FLASK_APP osr
ENV FLASK_ENV development
RUN mkdir -p $INSTALL_PATH

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . .

CMD [ "flask", "run", "--host=0.0.0.0"]

docker-compose.yml:

version: '3.8'
services:
    web:
        build: .
        ports:
            - '5000:5000'
        expose:
            - '5000'
        volumes:
            - .:/osr

__ init __.py

import os
from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev'
    )

    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    return app

docker-compose build web
docker-compose run web

 * Serving Flask app "osr" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 225-441-434

all of the below return "hmm can't reach this page"

http://localhost
http://localhost:5000/hello
http://127.0.0.1:5000/hello

I've even tried going to the containers IP with

docker exec -it 49e677 bash
ip add | grep global
    inet 172.21.0.2/16 brd 172.21.255.255 scope global eth0

http://127.21.0.2:5000/hello # nothing

Nothing.

I'm sure the app itself works fine as I can simply run the app directly.

$env:FLASK_APP="osr"
$env:FLASK_ENV="development"
flask run --host=0.0.0.0

And it runs fine

EDIT: UPDATE

I am actually able to get to the container when I run it through simply the Dockerfile... using

docker run -it -p 5000:5000 osr_web # the container built by docker-compose build

With this, I am able to access the endpoint through localhost:5000/hello

So the issue appears to lie in spinning it up through docker-compose run

Does this help at all?

UPDATE 2

I have discovered that when I run docker ps -a I can see that Docker run actually exposes the port, but docker-compose run does not:

Body:
Are you sure app works fine itself? I tried to run your python __init__.py file and ended up with an error.

python osr/__init__.py
  File "osr/__init__.py", line 11
    def hello():
    ^
IndentationError: unexpected indent

It works after fixing the indentation error.

@app.route('/hello')
def hello():
    return 'Hello, World!'

$ docker run -d -p 5000:5000 harik8/osr:latest
76628f86fecb61c0be4a969d3c91c5c575702ad8063b594a6c1c90b498ea25f1

$ curl http://127.0.0.1:5000/hello
Hello, World!

You can't run both docker and docker-compose in port 5000 at the same time. Either run one at a time or change the docker-compose/dockerfile host port.

$ docker ps -a | grep osr
8b885c4a9654        harik8/osr:latest                                     "flask run --host=0.…"   12 seconds ago       Up 11 seconds               0.0.0.0:5000->5000/tcp
$ docker ps -a | grep q5
70f38bf11e26        q5_web                                                "flask run --host=0.…"   About a minute ago   Up 10 seconds               0.0.0.0:5001->5000/tcp

$ docker ps -a | grep q5
f9f6ba999109        q5_web                                                "flask run --host=0.…"   5 minutes ago       Up 5 minutes                0.0.0.0:5000->5000/tcp                                                                                q5_web_1
$ docker ps -a | grep osr
93fb421333e4        harik8/osr:latest                                     "flask run --host=0.…"   18 seconds ago      Up 18 seconds               5000/tcp


问:
Make an already existing Graph fully connected
I have a Graph of this structure:

```<code>G = {
    '1':['100', '134', '1435'],
    '145':['4', '2345', '253'],
    '3773':['12'], '773':['1211', '629']}
</code>```

The graph is actually so large, with 6378 nodes and 39932 edges.
My problem is that the graph is disconnected, and i want the graph to be fully connected with no disconnected component.

Can someone help me with the python code please? I have been cracking my head since sunday.Thank you

```<code>def add_disconnected_nodes(Graph, begin):
    gkey = []
    cap_vertices = []
    for vertex in Graph.keys():
        gkey.append(vertex)
    if begin in gkey:
        begin = gkey[0]
    for vertices in Graph.keys():
        if vertices != begin and vertices not in Graph[begin]:
            cap_vertices.append(vertices)
            #Graph[begin] = [Graph[begin], cap_vertices]
            Graph[begin] + cap_vertices
            Graph.update()
    return Graph
</code>```

I wrote this code, but it ran without an error. Still, it would not get the job done. I know i am not doing something right

EDITED: So i rewrote the code this way, now it is taking forever to execute.  I chose a start vertex as key, and every other node node in the value of this key, i tried to add to the value. Maybe i am doing something wrong; Someone please help me!

```<code>def add_disconnected_nodes(Graph, begin):
if begin not in Graph:
    return False

beg = {}
bbg = []
for vet in Graph.keys():
    bbg.append(vet)
bba = []
while len(bbg) != 0:
    for ls in bbg:
        if ls != begin and ls not in Graph[begin]:
            bba.append(ls)
            bbg.remove(ls)
            if len(bbg) == 0:
                break
            beg[begin] = Graph[begin] + bba
            Graph.update(beg)
return Graph
</code>```

答:
if you want to do it in optimized way, use Strongly Connected Components(kosaraju's algorithem) and find out the most strongly connected components and add your weakly connected nodes to make a fully connected graph.

code sample to demonstrate :

```<code>#Function to findout the closely connected components:

class Graph:

def __init__(self,vertices):
    self.V= vertices #No. of vertices
    self.graph = defaultdict(list) # default dictionary to store graph

# function to add an edge to graph
def addEdge(self,u,v):
    self.graph[u].append(v)

# A function used by DFS
def DFSUtil(self,v,visited):
    # Mark the current node as visited and print it
    visited[v]= True
    print(v)
    #Recur for all the vertices adjacent to this vertex
    for i in self.graph[v]:
        if visited[i]==False:
            self.DFSUtil(i,visited)

def fillOrder(self,v,visited, stack):
    # Mark the current node as visited
    visited[v]= True
    #Recur for all the vertices adjacent to this vertex
    for i in self.graph[v]:
        if visited[i]==False:
            self.fillOrder(i, visited, stack)
    stack = stack.append(v)

# Function that returns reverse (or transpose) of this graph
def getTranspose(self):
    g = Graph(self.V)

    # Recur for all the vertices adjacent to this vertex
    for i in self.graph:
        for j in self.graph[i]:
            g.addEdge(j,i)
    return g

def printSCCs(self):

    stack = []
    # Mark all the vertices as not visited (For first DFS)
    visited =[False]*(self.V)
    # Fill vertices in stack according to their finishing
    # times
    for i in range(self.V):
        if visited[i]==False:
            self.fillOrder(i, visited, stack)

    # Create a reversed graph
    gr = self.getTranspose()

     # Mark all the vertices as not visited (For second DFS)
    visited =[False]*(self.V)

     # Now process all vertices in order defined by Stack
    while stack:
        i = stack.pop()
        if visited[i]==False:
            gr.DFSUtil(i, visited)
            print("*****")
</code>```

Let us say i have total of 18 nodes and some initial connections:

```<code>g = Graph(18)
g.addEdge(0, 10)
g.addEdge(1, 15)
g.addEdge(1, 17)
g.addEdge(2, 1)
g.addEdge(2, 3)
g.addEdge(4, 12)
g.addEdge(5, 7)
g.addEdge(6, 11)
g.addEdge(7, 8)
g.addEdge(7, 9)
g.addEdge(8, 9)
g.addEdge(9, 10)
g.addEdge(11, 14)
g.addEdge(12, 0)
g.addEdge(13, 6)
g.addEdge(14, 13)
g.addEdge(14, 4)
g.addEdge(15, 1)
g.addEdge(16, 2)
</code>```

my initial input have connections like:

```<code> {0: [10],
 1: [15, 17],
 2: [3, 1],
 3: [],
 4: [12],
 5: [7],
 6: [11],
 7: [8, 9],
 8: [9],
 9: [10],
 10: [],
 11: [14],
 12: [0],
 13: [6],
 14: [13, 4],
 15: [1],
 16: [2],
 17: []}
</code>```

after running the above algorithm the strongly connected component i got are as follows:

```<code>Following are strongly connected components in given graph
16
*****
6
13
14
11
*****
5
*****
7
*****
8
*****
9
*****
4
*****
12
*****
2
*****
3
*****
1
15
*****
17
*****
0
*****
10
*****
</code>```

By Hit and trial if I add below connections. my graph becomes fully connected:

```<code>##### New Additions ############
g.addEdge(9, 5)
g.addEdge(5, 11)
g.addEdge(12, 7)
g.addEdge(10, 13)
g.addEdge(3, 4)
g.addEdge(17, 16)
g.addEdge(14, 15)
</code>```

Again running the above Strongly Connected Components algo the final output is:

```<code>Following are strongly connected components in given graph
0
12
4
14
11
5
9
7
8
6
13
10
3
2
16
17
1
15
*****
</code>```

The reference of the code is at the following link:
Strongly Connected Components

Note: I have tried this based on your question, There must be a better way and better method rather than Hit and Trail. Please feel free to improve the answer if better method is found. The purpose of this answer is to introduce an approach for analyzing your problem.

Body:
I have a Graph of this structure:

G = {
    '1':['100', '134', '1435'],
    '145':['4', '2345', '253'],
    '3773':['12'], '773':['1211', '629']}

The graph is actually so large, with 6378 nodes and 39932 edges.
My problem is that the graph is disconnected, and i want the graph to be fully connected with no disconnected component.

Can someone help me with the python code please? I have been cracking my head since sunday.Thank you

def add_disconnected_nodes(Graph, begin):
    gkey = []
    cap_vertices = []
    for vertex in Graph.keys():
        gkey.append(vertex)
    if begin in gkey:
        begin = gkey[0]
    for vertices in Graph.keys():
        if vertices != begin and vertices not in Graph[begin]:
            cap_vertices.append(vertices)
            #Graph[begin] = [Graph[begin], cap_vertices]
            Graph[begin] + cap_vertices
            Graph.update()
    return Graph

I wrote this code, but it ran without an error. Still, it would not get the job done. I know i am not doing something right

EDITED: So i rewrote the code this way, now it is taking forever to execute.  I chose a start vertex as key, and every other node node in the value of this key, i tried to add to the value. Maybe i am doing something wrong; Someone please help me!

def add_disconnected_nodes(Graph, begin):
if begin not in Graph:
    return False

beg = {}
bbg = []
for vet in Graph.keys():
    bbg.append(vet)
bba = []
while len(bbg) != 0:
    for ls in bbg:
        if ls != begin and ls not in Graph[begin]:
            bba.append(ls)
            bbg.remove(ls)
            if len(bbg) == 0:
                break
            beg[begin] = Graph[begin] + bba
            Graph.update(beg)
return Graph

Body:
if you want to do it in optimized way, use Strongly Connected Components(kosaraju's algorithem) and find out the most strongly connected components and add your weakly connected nodes to make a fully connected graph.

code sample to demonstrate :

#Function to findout the closely connected components:

class Graph:

def __init__(self,vertices):
    self.V= vertices #No. of vertices
    self.graph = defaultdict(list) # default dictionary to store graph

# function to add an edge to graph
def addEdge(self,u,v):
    self.graph[u].append(v)

# A function used by DFS
def DFSUtil(self,v,visited):
    # Mark the current node as visited and print it
    visited[v]= True
    print(v)
    #Recur for all the vertices adjacent to this vertex
    for i in self.graph[v]:
        if visited[i]==False:
            self.DFSUtil(i,visited)

def fillOrder(self,v,visited, stack):
    # Mark the current node as visited
    visited[v]= True
    #Recur for all the vertices adjacent to this vertex
    for i in self.graph[v]:
        if visited[i]==False:
            self.fillOrder(i, visited, stack)
    stack = stack.append(v)

# Function that returns reverse (or transpose) of this graph
def getTranspose(self):
    g = Graph(self.V)

    # Recur for all the vertices adjacent to this vertex
    for i in self.graph:
        for j in self.graph[i]:
            g.addEdge(j,i)
    return g

def printSCCs(self):

    stack = []
    # Mark all the vertices as not visited (For first DFS)
    visited =[False]*(self.V)
    # Fill vertices in stack according to their finishing
    # times
    for i in range(self.V):
        if visited[i]==False:
            self.fillOrder(i, visited, stack)

    # Create a reversed graph
    gr = self.getTranspose()

     # Mark all the vertices as not visited (For second DFS)
    visited =[False]*(self.V)

     # Now process all vertices in order defined by Stack
    while stack:
        i = stack.pop()
        if visited[i]==False:
            gr.DFSUtil(i, visited)
            print("*****")

Let us say i have total of 18 nodes and some initial connections:

g = Graph(18)
g.addEdge(0, 10)
g.addEdge(1, 15)
g.addEdge(1, 17)
g.addEdge(2, 1)
g.addEdge(2, 3)
g.addEdge(4, 12)
g.addEdge(5, 7)
g.addEdge(6, 11)
g.addEdge(7, 8)
g.addEdge(7, 9)
g.addEdge(8, 9)
g.addEdge(9, 10)
g.addEdge(11, 14)
g.addEdge(12, 0)
g.addEdge(13, 6)
g.addEdge(14, 13)
g.addEdge(14, 4)
g.addEdge(15, 1)
g.addEdge(16, 2)

my initial input have connections like:

 {0: [10],
 1: [15, 17],
 2: [3, 1],
 3: [],
 4: [12],
 5: [7],
 6: [11],
 7: [8, 9],
 8: [9],
 9: [10],
 10: [],
 11: [14],
 12: [0],
 13: [6],
 14: [13, 4],
 15: [1],
 16: [2],
 17: []}

after running the above algorithm the strongly connected component i got are as follows:

Following are strongly connected components in given graph
16
*****
6
13
14
11
*****
5
*****
7
*****
8
*****
9
*****
4
*****
12
*****
2
*****
3
*****
1
15
*****
17
*****
0
*****
10
*****

By Hit and trial if I add below connections. my graph becomes fully connected:

##### New Additions ############
g.addEdge(9, 5)
g.addEdge(5, 11)
g.addEdge(12, 7)
g.addEdge(10, 13)
g.addEdge(3, 4)
g.addEdge(17, 16)
g.addEdge(14, 15)

Again running the above Strongly Connected Components algo the final output is:

Following are strongly connected components in given graph
0
12
4
14
11
5
9
7
8
6
13
10
3
2
16
17
1
15
*****

The reference of the code is at the following link:
Strongly Connected Components

Note: I have tried this based on your question, There must be a better way and better method rather than Hit and Trail. Please feel free to improve the answer if better method is found. The purpose of this answer is to introduce an approach for analyzing your problem.


问:
Homework-C Programming- Recursive Program
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

```<code>f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise
</code>```

My program:

```<code>#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}
</code>```

答:
You are asked to implement f(x) defined as:

```<code>f(x) = 0              if x <= 0
       f(x-1) + 2     otherwise
</code>```

So, first of all, forget about the factorial, I'm guessing you grabbed it as the example or a recursive function, but this isn't what you're asked to do here.

You need to implement the function f, and an implementation would look like this:

```<code>int f( int x ) {
    if( x <= 0 ){
        return /*something*/;
    }else{
        return /*something else*/;
    }
}
</code>```

From reading the definition of f(x) that you're given, you can figure out what /*something*/ and /*something else*/ should be.

Then, you're asked to "test" your implementation. You do that by seeing what values f returns from your main function which would look like:

```<code>int main(void){

    printf("f(1) is %d\n", f(1));
    printf("f(13) is %d\n", f(13));
    /* .. more tests here if you want .. */

    return 0;
}
</code>```

Body:
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise

My program:

#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}

Body:
You are asked to implement f(x) defined as:

f(x) = 0              if x <= 0
       f(x-1) + 2     otherwise

So, first of all, forget about the factorial, I'm guessing you grabbed it as the example or a recursive function, but this isn't what you're asked to do here.

You need to implement the function f, and an implementation would look like this:

int f( int x ) {
    if( x <= 0 ){
        return /*something*/;
    }else{
        return /*something else*/;
    }
}

From reading the definition of f(x) that you're given, you can figure out what /*something*/ and /*something else*/ should be.

Then, you're asked to "test" your implementation. You do that by seeing what values f returns from your main function which would look like:

int main(void){

    printf("f(1) is %d\n", f(1));
    printf("f(13) is %d\n", f(13));
    /* .. more tests here if you want .. */

    return 0;
}


问:
Reading from flash that's not part of the application
I'm programming bare-metal embedded, so no OS etc. on a STM32L4 (ARM Cortex M4). I have a separate page in flash, which is written by a bootloader (it is not and should not be part of my application binary, this is a must). In this page, I store configuration parameters that will be used in my application. This configuration page may change, but not during runtime, after a change I reset the processor.

How can I access this data in flash most nicely?

My definition of nice is (in this order of priority):
- support for (u)int32_t, (u)int8_t, bool, char[fixed-size]
- little overhead when compared to #define PARAM (1) or constexpr
- typesafe usage (i.e. uint8_t var = CONFIG_CHAR_ARRAY shall issue atleast a warning)
- no RAM copy
- readability of the configuration parameters while debugging (using STM32CubeIDE)

The solution shall scale for all possible 2048 bytes of the flashpage. Code generation is anyhow part of the process.

So far, I have tested two variants (I am coming from plain C but am using (potentially modern) C++ in this project). My current testcase is

```<code>    if (param) function_call();
</code>```

but it should also work for other cases such as

```<code>    for(int i = 0; i < param2; i++)
</code>```

define with pointer cast

```<code>#define CONF_PARAM1 (*(bool*)(CONFIG_ADDRESS + 0x0083))
</code>```

Which leads to (using -Os):

```<code>8008872:    4b1b        ldr r3, [pc, #108]  ; (80088e0 <_Z16main_applicationv+0xac>)
8008874:    781b        ldrb    r3, [r3, #0]
8008876:    b10b        cbz r3, 800887c <_Z16main_applicationv+0x48>
8008878:    f7ff ff56   bl  8008728 <_Z10function_callv>

80088e0:    0801f883    .word   0x0801f883
</code>```

const variable

```<code>const bool CONF_PARAM1 = *(bool*)(CONFIG_ADDRESS + 0x0083);
</code>```

leading to

```<code>800887c:    4b19        ldr r3, [pc, #100]  ; (80088e4 <_Z16main_applicationv+0xb0>)
800887e:    781b        ldrb    r3, [r3, #0]
8008880:    b10b        cbz r3, 8008886 <_Z16main_applicationv+0x52>
8008882:    f000 f899   bl  8008728 <_Z10function_callv>

80088e4:    200000c0    .word   0x200000c0
</code>```

I dislike option 2, as it adds a RAM copy (would not scale well for 2048 bytes of config), option 1 looks like very old c style and does not help while debugging. I struggle to find another option using the linker script, as I do not find a way to not end up with the variable being in the application's binary.

Is there any better way of doing this?

答:
If you make your constant a reference the compiler wont copy it into a variable, it will probably just load the address into a variable. You can then wrap the generation of the references into a templated function to make your code cleaner:

```<code>#include <cstdint>
#include <iostream>

template <typename T>
const T& configOption(uintptr_t offset)
{
    const uintptr_t CONFIG_ADDRESS = 0x1000;
    return *reinterpret_cast<T*>(CONFIG_ADDRESS + offset);
}

auto& CONF_PARAM1 = configOption< bool >(0x0083);
auto& CONF_PARAM2 = configOption< int >(0x0087);

int main()
{
    std::cout << CONF_PARAM1 << ", " << CONF_PARAM2 << "\n";
}
</code>```

GCC optimises this fairly well: https://godbolt.org/z/r27o5Q

Body:
I'm programming bare-metal embedded, so no OS etc. on a STM32L4 (ARM Cortex M4). I have a separate page in flash, which is written by a bootloader (it is not and should not be part of my application binary, this is a must). In this page, I store configuration parameters that will be used in my application. This configuration page may change, but not during runtime, after a change I reset the processor.

How can I access this data in flash most nicely?

My definition of nice is (in this order of priority):
- support for (u)int32_t, (u)int8_t, bool, char[fixed-size]
- little overhead when compared to #define PARAM (1) or constexpr
- typesafe usage (i.e. uint8_t var = CONFIG_CHAR_ARRAY shall issue atleast a warning)
- no RAM copy
- readability of the configuration parameters while debugging (using STM32CubeIDE)

The solution shall scale for all possible 2048 bytes of the flashpage. Code generation is anyhow part of the process.

So far, I have tested two variants (I am coming from plain C but am using (potentially modern) C++ in this project). My current testcase is

    if (param) function_call();

but it should also work for other cases such as

    for(int i = 0; i < param2; i++)

define with pointer cast

#define CONF_PARAM1 (*(bool*)(CONFIG_ADDRESS + 0x0083))

Which leads to (using -Os):

8008872:    4b1b        ldr r3, [pc, #108]  ; (80088e0 <_Z16main_applicationv+0xac>)
8008874:    781b        ldrb    r3, [r3, #0]
8008876:    b10b        cbz r3, 800887c <_Z16main_applicationv+0x48>
8008878:    f7ff ff56   bl  8008728 <_Z10function_callv>

80088e0:    0801f883    .word   0x0801f883

const variable

const bool CONF_PARAM1 = *(bool*)(CONFIG_ADDRESS + 0x0083);

leading to

800887c:    4b19        ldr r3, [pc, #100]  ; (80088e4 <_Z16main_applicationv+0xb0>)
800887e:    781b        ldrb    r3, [r3, #0]
8008880:    b10b        cbz r3, 8008886 <_Z16main_applicationv+0x52>
8008882:    f000 f899   bl  8008728 <_Z10function_callv>

80088e4:    200000c0    .word   0x200000c0

I dislike option 2, as it adds a RAM copy (would not scale well for 2048 bytes of config), option 1 looks like very old c style and does not help while debugging. I struggle to find another option using the linker script, as I do not find a way to not end up with the variable being in the application's binary.

Is there any better way of doing this?

Body:
If you make your constant a reference the compiler wont copy it into a variable, it will probably just load the address into a variable. You can then wrap the generation of the references into a templated function to make your code cleaner:

#include <cstdint>
#include <iostream>

template <typename T>
const T& configOption(uintptr_t offset)
{
    const uintptr_t CONFIG_ADDRESS = 0x1000;
    return *reinterpret_cast<T*>(CONFIG_ADDRESS + offset);
}

auto& CONF_PARAM1 = configOption< bool >(0x0083);
auto& CONF_PARAM2 = configOption< int >(0x0087);

int main()
{
    std::cout << CONF_PARAM1 << ", " << CONF_PARAM2 << "\n";
}

GCC optimises this fairly well: https://godbolt.org/z/r27o5Q


问:
Download .pdf file from Vue CLI project folder
I am trying to simply download a .pdf file out of a Vue component.
It works with for example .jpg or .png files, but not with .pdf files.

This is my vue.config.js

```<code>module.exports = {
  chainWebpack: config => {
    config.module
      .rule("vue")
      .use("vue-loader")
      .loader("vue-loader")
      .tap(options => {
        // modify the options...
        return options;
      });

    config.module
      .rule("pdf")
      .test(/\.pdf$/)
      .use("file-loader")
      .loader("file-loader");
  }
}
</code>```

In my simplified Vue component, I try to download the file like this(works with .jpg)

```<code>   <template>
     <div>
       <a :href="pdfLink" download="myPdf.pdf">Download</a>
     </div>
   </template>

 <script>
    name: "PdfFileComponent",
    data: () => ({
    pdfLink: require("../assets/myPdf.pdf")
  })
 </script>
</code>```

Any help is appreciated!

答:
I got it working with some changes to my rules in the vue.config.js

```<code>module.exports = {
  configureWebpack: {
    rules: [
      {
        test: /\.(pdf)(\?.*)?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              name: 'files/[name].[hash:8].[ext]'
            }
          }
        ]
      }
    ]
  }
}
</code>```

Hope this helps someone with the same problem.

Body:
I am trying to simply download a .pdf file out of a Vue component.
It works with for example .jpg or .png files, but not with .pdf files.

This is my vue.config.js

module.exports = {
  chainWebpack: config => {
    config.module
      .rule("vue")
      .use("vue-loader")
      .loader("vue-loader")
      .tap(options => {
        // modify the options...
        return options;
      });

    config.module
      .rule("pdf")
      .test(/\.pdf$/)
      .use("file-loader")
      .loader("file-loader");
  }
}

In my simplified Vue component, I try to download the file like this(works with .jpg)

   <template>

       Download

   </template>

Any help is appreciated!

Body:
I got it working with some changes to my rules in the vue.config.js

module.exports = {
  configureWebpack: {
    rules: [
      {
        test: /\.(pdf)(\?.*)?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              name: 'files/[name].[hash:8].[ext]'
            }
          }
        ]
      }
    ]
  }
}

Hope this helps someone with the same problem.