问:
No SQL stats on JavaMelody - JBoss EAP 7
I have a maven application running on JBoss EAP 7.2 . Below details:

Build: Maven 3.6

Server: JBoss EAP 7.2

Java: OpenJDK 11

JavaMelody Core: 1.83.0

Package: EAR

Application: Struts 2.5.22

DB: Oracle 18c

OJDBC Driver: 18.3

Although I managed to configure JavaMelody and see the main statistics, I can't seem to find a way to configure the SQL monitoring.

Currently, for my JDBC configuration I use the <jta-data-source>java:jboss/datasources/myDS</jta-data-source>  in my persistence.xml file, which reads the datasource from the standalone.xml of the JBoss server.

I have tried several changes in my persistence.xml file like adding:

<property name="net.bull.javamelody.jpa.provider" value="org.hibernate.jpa.HibernatePersistenceProvider" />
```
<p>or</p>
<pre class="lang-xml prettyprint-override"><code><property name="hibernate.connection.driver_class" value="net.bull.javamelody.JdbcDriver"/>
</code>```

My struts.xml configuration:

<package name="myApp" extends="struts-default">
    <interceptors>
        <interceptor name="monitoring" class="net.bull.javamelody.StrutsInterceptor"/>
        <interceptor-stack name="myAppStack">
            <interceptor-ref name="monitoring"/>
            <interceptor-ref name="prepare"/>
            ...
            <interceptor-ref name="json"/>
            <interceptor-ref name="debugging"/>
            <interceptor-ref name="defaultStack"/>
        </interceptor-stack>
    </interceptors>
    <default-interceptor-ref name="myAppStack"/>
</package>
```

or even configuring my datasource entirely in the persistence file using the hibernate.connection.url/username/password properties, but with no luck.

I tried to following the instructions found here, but I can't seem to find what is wrong:

https://github.com/javamelody/javamelody/wiki/UserGuide#7-jdbc

https://github.com/javamelody/javamelody/wiki/UserGuideAdvanced#jpa-monitoring

Note: In my persistence.xml I was using also <property name="hibernate.connection.driver" value="oracle.jdbc.OracleDriver" /> . I am not sure if this is somehow conflicting.

答:
JPA monitoring is completely different than SQL monitoring: do not try net.bull.javamelody.jpa.provider to monitor SQL. And it is useless to try hibernate.connection.driver_class if you use a datasource from JNDI.

For SQL monitoring, you can try to monitor SQL from the datasource in JNDI:

either add a javamelody parameter datasource, for example with a system property: -Djavamelody.datasources=java:jboss/datasources/myDS

or rename your datasource to java:jdbc/myDS

Then check the "Debugging logs" at the bottom of the javamelody reports.

And because you are using an EAR, see https://github.com/javamelody/javamelody/wiki/UserGuideAdvanced#setup-javamelody-in-an-ear-file

Body:
I have a maven application running on JBoss EAP 7.2 . Below details:

Build: Maven 3.6

Server: JBoss EAP 7.2

Java: OpenJDK 11

JavaMelody Core: 1.83.0

Package: EAR

Application: Struts 2.5.22

DB: Oracle 18c

OJDBC Driver: 18.3

Although I managed to configure JavaMelody and see the main statistics, I can't seem to find a way to configure the SQL monitoring.

Currently, for my JDBC configuration I use the <jta-data-source>java:jboss/datasources/myDS</jta-data-source>  in my persistence.xml file, which reads the datasource from the standalone.xml of the JBoss server.

I have tried several changes in my persistence.xml file like adding:

<property name="net.bull.javamelody.jpa.provider" value="org.hibernate.jpa.HibernatePersistenceProvider" />

or

<property name="hibernate.connection.driver_class" value="net.bull.javamelody.JdbcDriver"/>

My struts.xml configuration:

<package name="myApp" extends="struts-default">
    <interceptors>
        <interceptor name="monitoring" class="net.bull.javamelody.StrutsInterceptor"/>
        <interceptor-stack name="myAppStack">
            <interceptor-ref name="monitoring"/>
            <interceptor-ref name="prepare"/>
            ...
            <interceptor-ref name="json"/>
            <interceptor-ref name="debugging"/>
            <interceptor-ref name="defaultStack"/>
        </interceptor-stack>
    </interceptors>
    <default-interceptor-ref name="myAppStack"/>
</package>

or even configuring my datasource entirely in the persistence file using the hibernate.connection.url/username/password properties, but with no luck.

I tried to following the instructions found here, but I can't seem to find what is wrong:

https://github.com/javamelody/javamelody/wiki/UserGuide#7-jdbc

https://github.com/javamelody/javamelody/wiki/UserGuideAdvanced#jpa-monitoring

Note: In my persistence.xml I was using also <property name="hibernate.connection.driver" value="oracle.jdbc.OracleDriver" /> . I am not sure if this is somehow conflicting.


来源: stackexchange

问:
NullPointerException when using FirebaseUI and RecyclerView
I followed this guide How to display data from Firestore in a RecyclerView with Android?, but am facing a NullPointerException in the setter in the ViewHolder. I'm also actually very unsure of what to do in the setter in the ViewHolder...

![database]https://imgur.com/a/wquZ08f

Model:

```<code>public class FoodModel {
    private String foodName;
    private String foodType;
    private String foodQty;
    private String foodExpDate;

    public FoodModel() {}

    public FoodModel(String name, String type, String qty, String expDate) {
        this.foodName = name;
        this.foodType = type;
        this.foodQty = qty;
        this.foodExpDate = expDate;
    }

    public String getFoodName() {return foodName;}
    public void setFoodName(String name) {foodName = name;}

    public String getFoodType() {return foodType;}
    public void setFoodType(String type) {foodType = type;}

    public String getFoodQty() {return foodQty;}
    public void setFoodQty(String qty) {foodQty = qty;}

    public String getFoodExpDate() {return foodExpDate;}
    public void setFoodExpDate(String expDate) {foodExpDate = expDate;}
}
</code>```

Activity code:

```<code>recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        Query foodQuery = db.collection("Food")
                .orderBy("food_name", Query.Direction.ASCENDING);

        FirestoreRecyclerOptions<FoodModel> options = new FirestoreRecyclerOptions.Builder<FoodModel>()
                .setQuery(foodQuery, FoodModel.class)
                .build();

        adapter = new FirestoreRecyclerAdapter<FoodModel, FoodViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull FoodViewHolder holder, int position, @NonNull FoodModel model) {
                holder.setFoodName(model.getFoodName());
            }
            @NonNull
            @Override
            public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup group, int viewType) {
                View view = LayoutInflater.from(group.getContext()).inflate(R.layout.recycler_view_row, group, false);
                return new FoodViewHolder(view);
            }
        };
        recyclerView.setAdapter(adapter);
    }
    private class FoodViewHolder extends RecyclerView.ViewHolder {
        private View view;

        FoodViewHolder(View itemView) {
            super(itemView);
            view = itemView;
        }

        void setFoodName(String foodName) {
            TextView textView = view.findViewById(R.id.editName);
            textView.setText(foodName);
        }
    }
</code>```

xml of recycler_view_row:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/foodListRow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

errors:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.qremind, PID: 17735
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.qremind.FoodList$FoodViewHolder.setFoodName(FoodList.java:91)
        at com.example.qremind.FoodList$1.onBindViewHolder(FoodList.java:70)
        at com.example.qremind.FoodList$1.onBindViewHolder(FoodList.java:67)
        at com.firebase.ui.firestore.FirestoreRecyclerAdapter.onBindViewHolder(FirestoreRecyclerAdapter.java:158)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1897)
        at androidx.recyclerview.widget.RecyclerView$1.run(RecyclerView.java:414)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:878)
        at android.view.Choreographer.doCallbacks(Choreographer.java:690)
        at android.view.Choreographer.doFrame(Choreographer.java:622)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:864)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:185)
        at android.app.ActivityThread.main(ActivityThread.java:6473)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:916)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:806)
</code>```

答:
Change this:

```<code>TextView textView = view.findViewById(R.id.editName);
</code>```

into this:

```<code>TextView textView = view.findViewById(R.id.foodListRow);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I followed this guide How to display data from Firestore in a RecyclerView with Android?, but am facing a NullPointerException in the setter in the ViewHolder. I'm also actually very unsure of what to do in the setter in the ViewHolder...

![database]https://imgur.com/a/wquZ08f

Model:

public class FoodModel {
    private String foodName;
    private String foodType;
    private String foodQty;
    private String foodExpDate;

    public FoodModel() {}

    public FoodModel(String name, String type, String qty, String expDate) {
        this.foodName = name;
        this.foodType = type;
        this.foodQty = qty;
        this.foodExpDate = expDate;
    }

    public String getFoodName() {return foodName;}
    public void setFoodName(String name) {foodName = name;}

    public String getFoodType() {return foodType;}
    public void setFoodType(String type) {foodType = type;}

    public String getFoodQty() {return foodQty;}
    public void setFoodQty(String qty) {foodQty = qty;}

    public String getFoodExpDate() {return foodExpDate;}
    public void setFoodExpDate(String expDate) {foodExpDate = expDate;}
}

Activity code:

recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        Query foodQuery = db.collection("Food")
                .orderBy("food_name", Query.Direction.ASCENDING);

        FirestoreRecyclerOptions<FoodModel> options = new FirestoreRecyclerOptions.Builder<FoodModel>()
                .setQuery(foodQuery, FoodModel.class)
                .build();

        adapter = new FirestoreRecyclerAdapter<FoodModel, FoodViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull FoodViewHolder holder, int position, @NonNull FoodModel model) {
                holder.setFoodName(model.getFoodName());
            }
            @NonNull
            @Override
            public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup group, int viewType) {
                View view = LayoutInflater.from(group.getContext()).inflate(R.layout.recycler_view_row, group, false);
                return new FoodViewHolder(view);
            }
        };
        recyclerView.setAdapter(adapter);
    }
    private class FoodViewHolder extends RecyclerView.ViewHolder {
        private View view;

        FoodViewHolder(View itemView) {
            super(itemView);
            view = itemView;
        }

        void setFoodName(String foodName) {
            TextView textView = view.findViewById(R.id.editName);
            textView.setText(foodName);
        }
    }

xml of recycler_view_row:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/foodListRow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

errors:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.qremind, PID: 17735
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.qremind.FoodList$FoodViewHolder.setFoodName(FoodList.java:91)
        at com.example.qremind.FoodList$1.onBindViewHolder(FoodList.java:70)
        at com.example.qremind.FoodList$1.onBindViewHolder(FoodList.java:67)
        at com.firebase.ui.firestore.FirestoreRecyclerAdapter.onBindViewHolder(FirestoreRecyclerAdapter.java:158)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1897)
        at androidx.recyclerview.widget.RecyclerView$1.run(RecyclerView.java:414)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:878)
        at android.view.Choreographer.doCallbacks(Choreographer.java:690)
        at android.view.Choreographer.doFrame(Choreographer.java:622)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:864)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:185)
        at android.app.ActivityThread.main(ActivityThread.java:6473)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:916)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:806)

Body:
Change this:

TextView textView = view.findViewById(R.id.editName);

into this:

TextView textView = view.findViewById(R.id.foodListRow);


问:
Checking if all value of X array is in Y or not
I have two arrays

```<code>var A = [1,2,3,4,5];
var B = [1,2,3,4,5,6,7,8,9];
</code>```

Now I want to check if all elements of A are exist in B or not like this

```<code>var A = [1,2,3,4,5];
var B = [1,2,3,4,5,6,7,8,9];
// true

var A = [1,2,3,4,5];
var B = [1,2,3,4,5];
// True

var A = [1,2,3,4,5];
var B = [1,2,3,5,6,7,8,9];
// False
</code>```

I have tried using some like this

```<code>if(A.some(item => B.includes(item)) {
     return true;
}
</code>```

But it filters the array and returns true if one of the value is true

Body:
I have two arrays

var A = [1,2,3,4,5];
var B = [1,2,3,4,5,6,7,8,9];

Now I want to check if all elements of A are exist in B or not like this

var A = [1,2,3,4,5];
var B = [1,2,3,4,5,6,7,8,9];
// true

var A = [1,2,3,4,5];
var B = [1,2,3,4,5];
// True

var A = [1,2,3,4,5];
var B = [1,2,3,5,6,7,8,9];
// False

I have tried using some like this

if(A.some(item => B.includes(item)) {
     return true;
}

But it filters the array and returns true if one of the value is true

Body:
Use every()

var A1 = [1,2,3,4,5];
var B1 = [1,2,3,4,5,6,7,8,9];
var A2 = [1,2,3,4,5];
var B2 = [1,2,3,4,5];
var A3 = [1,2,3,4,5];
var B3 = [1,2,3,5,6,7,8,9];

console.log(A1.every(item => B1.includes(item)));
console.log(A2.every(item => B2.includes(item)));
console.log(A3.every(item => B3.includes(item)));


问:
how can I figure out the output of a c# project file (.csproj)
I have a very large .NET solution with hundreds of projects (all c#) how can I figure out which of the projects is the application project to set as the start up project.

I was thinking of grepping the csproj files for some keyword that indicates it's an executable.

Thank you

答:
ok Found the answer

```<code>  <OutputType>WinExe</OutputType>
</code>```

in the csproj file.

ContentLicense: CC BY-SA 3.0

Body:
ok Found the answer

  <OutputType>WinExe</OutputType>

in the csproj file.


问:
Unittest Flask Context Errors when executing sqlite queries
I am trying to populate my sqlite database in a flask unit test and I am getting the following errors on the line that executes the query:

```<code>Exception: <class 'RuntimeError'>, Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.
</code>```

This is my unittest setup:

The setup method:

```<code>def setUp(self) -> None:
    # creates a test client
    self.app = app.test_client()
    app.app_context().push()
    app.config["WTF_CSRF_ENABLED"] = False
    app.config["DEBUG"] = False
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + join(_cwd, 'test_app.db')
    app.config["SQLALCHEMY_DATABASE_BINDS"] = {"test": "sqlite:///test_app.db"}
    app.config["TESTING"] = True
    app.config["SERVER_NAME"] = 'localhost.localdomain'

    db.init_app(app)
    db.drop_all()
    db.create_all()

    with app.app_context():
        db_file = join(_cwd, 'app.db.sql')
        rs = init_db_from_script(db_file)
        print(f"Result: {rs}")

    # Disable mail sending
    mail = Mail()
    mail.init_app(app)
    self.assertEqual(app.debug, False)

def tearDown(self) -> None:
    """
    Ensures that the database is emptied for next unit test
    """
    with app.app_context():
        # db.drop_all()
        pass
</code>```

then test itself:

```<code>def test_graph_data_url(self):
    graph_data = [OrderedDict([('name', 'contact'), ('visits', 55)])]
    g_info = get_info_for_graph()
    app.app_context().push()
    with app.test_client() as c:
        rc = c.get('/api/get-graph-info')
    print(f"Database Path: {join(_cwd, 'app.db.sql')}")
    print(f"g_info: {g_info}")
    self.assertEqual(g_info, [])
    self.assertEqual(200, rc.status_code)
</code>```

and the function that does the execution:

```<code>def init_db_from_script(script: str) -> bool:
    """Function to load data into sqlite
    database
    Parameters:
        script (str): path to sql file
    Returns:
        bool: True if successful and False otherwise
    """
    # Create an empty command string
    sql_command = ''
    with open(script, 'r') as sql_file:
        # Iterate over all lines in the sql file
        for line in sql_file:
            # Ignore commented lines
            if not line.startswith('--') and line.strip('\n'):
                # Append line to the command string
                sql_command += line.strip('\n')

                # If the command string ends with ';', it is a full statement
                if sql_command.endswith(';'):
                    # Try to execute statement and commit it
                    try:
                        with app.test_client():
                            with app.app_context():
                                session.execute(text(sql_command))
                                session.commit()

                    # Assert in case of error
                    except TypeError as t_err:
                        print("TypeError: {}".format(t_err))
                        return False
                    except ValueError as v_err:
                        print("ValueError: {}".format(v_err))
                        return False
                    except Exception as e_err:
                        print("Exception: {}, {}".format(type(e_err), e_err))
                        return False

                    # Finally, clear command string
                    finally:
                        sql_command = ''
</code>```

From my debugging session the error is thrown at the line session.execute(text(sql_command)), so I am really lost as how I am to apply the "application context" in this case.

答:
Ok I was able figure why I was getting this error. From my:

```<code>init_db_from_script(script: str) -> bool
</code>```

function I was using the session object and that was going outside the "context" of the current flask test when I should have been using:

```<code>db.session.execute
</code>```

Which was setup in the def setUp method, so I updated my function header to:

```<code>def init_db_from_script(script: str, db: SQLAlchemy) -> bool
</code>```

and the def setUp method body to:

```<code>db.init_app(app)
    db.drop_all()
    db.create_all()

    with app.app_context():
        db_file = join(_cwd, 'app.db.sql')
        init_db_from_script(db_file, db)
</code>```

and in the body of the def init_db_from_script(script: str, db: SQLAlchemy) -> bool function I used the db SQLAlchemy to execute the queries like so:

```<code>try:
   db.engine.execute(text(sql_command))
   db.session.commit()
</code>```

Body:
I am trying to populate my sqlite database in a flask unit test and I am getting the following errors on the line that executes the query:

Exception: <class 'RuntimeError'>, Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

This is my unittest setup:

The setup method:

def setUp(self) -> None:
    # creates a test client
    self.app = app.test_client()
    app.app_context().push()
    app.config["WTF_CSRF_ENABLED"] = False
    app.config["DEBUG"] = False
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + join(_cwd, 'test_app.db')
    app.config["SQLALCHEMY_DATABASE_BINDS"] = {"test": "sqlite:///test_app.db"}
    app.config["TESTING"] = True
    app.config["SERVER_NAME"] = 'localhost.localdomain'

    db.init_app(app)
    db.drop_all()
    db.create_all()

    with app.app_context():
        db_file = join(_cwd, 'app.db.sql')
        rs = init_db_from_script(db_file)
        print(f"Result: {rs}")

    # Disable mail sending
    mail = Mail()
    mail.init_app(app)
    self.assertEqual(app.debug, False)

def tearDown(self) -> None:
    """
    Ensures that the database is emptied for next unit test
    """
    with app.app_context():
        # db.drop_all()
        pass

then test itself:

def test_graph_data_url(self):
    graph_data = [OrderedDict([('name', 'contact'), ('visits', 55)])]
    g_info = get_info_for_graph()
    app.app_context().push()
    with app.test_client() as c:
        rc = c.get('/api/get-graph-info')
    print(f"Database Path: {join(_cwd, 'app.db.sql')}")
    print(f"g_info: {g_info}")
    self.assertEqual(g_info, [])
    self.assertEqual(200, rc.status_code)

and the function that does the execution:

def init_db_from_script(script: str) -> bool:
    """Function to load data into sqlite
    database
    Parameters:
        script (str): path to sql file
    Returns:
        bool: True if successful and False otherwise
    """
    # Create an empty command string
    sql_command = ''
    with open(script, 'r') as sql_file:
        # Iterate over all lines in the sql file
        for line in sql_file:
            # Ignore commented lines
            if not line.startswith('--') and line.strip('\n'):
                # Append line to the command string
                sql_command += line.strip('\n')

                # If the command string ends with ';', it is a full statement
                if sql_command.endswith(';'):
                    # Try to execute statement and commit it
                    try:
                        with app.test_client():
                            with app.app_context():
                                session.execute(text(sql_command))
                                session.commit()

                    # Assert in case of error
                    except TypeError as t_err:
                        print("TypeError: {}".format(t_err))
                        return False
                    except ValueError as v_err:
                        print("ValueError: {}".format(v_err))
                        return False
                    except Exception as e_err:
                        print("Exception: {}, {}".format(type(e_err), e_err))
                        return False

                    # Finally, clear command string
                    finally:
                        sql_command = ''

From my debugging session the error is thrown at the line session.execute(text(sql_command)), so I am really lost as how I am to apply the "application context" in this case.

Body:
Ok I was able figure why I was getting this error. From my:

init_db_from_script(script: str) -> bool

function I was using the session object and that was going outside the "context" of the current flask test when I should have been using:

db.session.execute

Which was setup in the def setUp method, so I updated my function header to:

def init_db_from_script(script: str, db: SQLAlchemy) -> bool

and the def setUp method body to:

db.init_app(app)
    db.drop_all()
    db.create_all()

    with app.app_context():
        db_file = join(_cwd, 'app.db.sql')
        init_db_from_script(db_file, db)

and in the body of the def init_db_from_script(script: str, db: SQLAlchemy) -> bool function I used the db SQLAlchemy to execute the queries like so:

try:
   db.engine.execute(text(sql_command))
   db.session.commit()


问:
rename command for replacing text in filename from a certain point (character), but only up to, and maintaining the file extension
I've got a ton of files as follows

```<code>audiofile_drums_1-ktpcwybsh5c.wav
soundsample_drums_2-fghlkjy57sa.wav
noise_snippet_guitar_5-mxjtgqta3o1.wav
louder_flute_9-mdlsiqpfj6c.wav
</code>```

I want to remove everything between and including the "-" and the .wav file extension, to be left with

```<code>audiofile_drums_1.wav
soundsample_drums_2.wav
noise_snippet_guitar_5.wav
louder_flute_9.wav
</code>```

I've tried to do delete everything following and including the character "-" using

```<code>rename 's/-.*//' *
</code>```

Which gives me

```<code>audiofile_drums_1
soundsample_drums_2
noise_snippet_guitar_5
louder_flute_9
</code>```

And for lack of finding an easy way to rename all the files again, adding .wav the extension, I am hoping there is a slicker way to do this in one nifty command in one stage instead of 2.

Any suggestions?

Thanks

答:
This works in my specific case, but should work for any file extension.

```<code>rename -n 's/-.*(?=\.wav$)//' *
</code>```

The command looks for all characters after and inclusive of the - symbol in the filename, then, using a positive lookahead** (?=\.wav$) to search for the characters (the file extension in this case) at the end of the filename (denoted by $, and replaces them with no characters (removing them).

** NOTE: A positive look ahead is a zero width assertion.
It will affect the match but it will not be included
in the replacement. (The '.wav' part will not be
erased)

In this example (?=\.wav$) is the positive lookahead.  The dollar sign $, as in regex, denotes at the end of the line, so perfect for a file extension.

Body:
I've got a ton of files as follows

audiofile_drums_1-ktpcwybsh5c.wav
soundsample_drums_2-fghlkjy57sa.wav
noise_snippet_guitar_5-mxjtgqta3o1.wav
louder_flute_9-mdlsiqpfj6c.wav

I want to remove everything between and including the "-" and the .wav file extension, to be left with

audiofile_drums_1.wav
soundsample_drums_2.wav
noise_snippet_guitar_5.wav
louder_flute_9.wav

I've tried to do delete everything following and including the character "-" using

rename 's/-.*//' *

Which gives me

audiofile_drums_1
soundsample_drums_2
noise_snippet_guitar_5
louder_flute_9

And for lack of finding an easy way to rename all the files again, adding .wav the extension, I am hoping there is a slicker way to do this in one nifty command in one stage instead of 2.

Any suggestions?

Thanks

Body:
This works in my specific case, but should work for any file extension.

rename -n 's/-.*(?=\.wav$)//' *

The command looks for all characters after and inclusive of the - symbol in the filename, then, using a positive lookahead** (?=\.wav$) to search for the characters (the file extension in this case) at the end of the filename (denoted by $, and replaces them with no characters (removing them).

** NOTE: A positive look ahead is a zero width assertion.
It will affect the match but it will not be included
in the replacement. (The '.wav' part will not be
erased)

In this example (?=\.wav$) is the positive lookahead.  The dollar sign $, as in regex, denotes at the end of the line, so perfect for a file extension.


问:
How do you get FULL SCREEN in Safari?
Mainly for artistic reasons I want to have run my slideshow (plain javascript) in fullscreen. For browsers like Internet Explorer, Chrome, Firefox and some others this seems to be no problem when they are run on windows machines: the user just has to press key F11 to enter the fullscreen mode (and press it again to leave it), as he/she is instructed to do by a preceding page introducing the slideshow. [BTW. this is the only 'physical' interaction between the viewer and the slideshow: pressing the key also means 'being ready' to view the slideshow, sitting comfortable at a certain distance from the screen, not too close, etc.] For this and other reasons I do not want to have run the slideshow  automatically [or by click] in fullscreen mode.

As I said, this works perfectly on a windows machine. Howver this does not work for Safari on mac: pressing ^+cmd+F does not give you fullscreen, as I understand it, for the url of my webpage is still visible on top of the screen, including the title bar. For example:

```<code><A HREF="javascript:slideshow();
self.moveTo(0,0);self.resizeTo(screen.availWidth,screen.availHeight);"></A>
</code>```

which gives the same result: address bar and title bar are still visible.

In case you want to watch my slideshow in fullscreen for a couple of minutes, go to:

http://www.atelierfransvandestaak.nl/slideshow.html

I have searched for an answer on several fora for a couple of month's but in vain. Now I begin to think this is not a matter of code but of definition. Since what Apple designers call fullscreen is not really fullscreen in my opinion. Definitions are a matter of standard: meaning, you can't change it, as the rest of the world follows its rule. Or can you?
So my main question then is, can we agree on a fullscreen view [e.g. of an image]. If not, you cannot encode it either. Perhaps, this takes us too far from Stackoverflow's directives for asking questions [about code], but I appreciate any suggestion or answer.

Thanks in advance,
wimsch

PS. The cause of our fullscreen problem [=safari doesn't go to native fullscreen, not by javascript code, even when it is  explicitly instructed to by the user <<^ cmd F>>] is perhaps, that the address bar can take an url but also a search string. So, I guess the (quick) search engine [Spotlight] is interconnected with the address bar and this could easily explain why the address bar remains visible, preventing safari from going to Native fullscreen. What do you think of this?

答:
I solved all my problems using this great package https://www.npmjs.com/package/screenfull

From the readme:

Simple wrapper for cross-browser usage of the JavaScript Fullscreen API, which lets you bring the page or any element into fullscreen. Smoothens out the browser implementation differences, so you don't have to.

It just works and the docs are great.

Title: How do you get FULL SCREEN in Safari?

Body:
Mainly for artistic reasons I want to have run my slideshow (plain javascript) in fullscreen. For browsers like Internet Explorer, Chrome, Firefox and some others this seems to be no problem when they are run on windows machines: the user just has to press key F11 to enter the fullscreen mode (and press it again to leave it), as he/she is instructed to do by a preceding page introducing the slideshow. [BTW. this is the only 'physical' interaction between the viewer and the slideshow: pressing the key also means 'being ready' to view the slideshow, sitting comfortable at a certain distance from the screen, not too close, etc.] For this and other reasons I do not want to have run the slideshow  automatically [or by click] in fullscreen mode.

As I said, this works perfectly on a windows machine. Howver this does not work for Safari on mac: pressing ^+cmd+F does not give you fullscreen, as I understand it, for the url of my webpage is still visible on top of the screen, including the title bar. For example:

which gives the same result: address bar and title bar are still visible.

In case you want to watch my slideshow in fullscreen for a couple of minutes, go to:

http://www.atelierfransvandestaak.nl/slideshow.html

I have searched for an answer on several fora for a couple of month's but in vain. Now I begin to think this is not a matter of code but of definition. Since what Apple designers call fullscreen is not really fullscreen in my opinion. Definitions are a matter of standard: meaning, you can't change it, as the rest of the world follows its rule. Or can you?
So my main question then is, can we agree on a fullscreen view [e.g. of an image]. If not, you cannot encode it either. Perhaps, this takes us too far from Stackoverflow's directives for asking questions [about code], but I appreciate any suggestion or answer.

Thanks in advance,
wimsch

PS. The cause of our fullscreen problem [=safari doesn't go to native fullscreen, not by javascript code, even when it is  explicitly instructed to by the user <<^ cmd F>>] is perhaps, that the address bar can take an url but also a search string. So, I guess the (quick) search engine [Spotlight] is interconnected with the address bar and this could easily explain why the address bar remains visible, preventing safari from going to Native fullscreen. What do you think of this?


问:
string manipulation: partly convert to lowercase
As the title says: What's best way of converting a string from any-case to lowercase keeping a portion unchanged? e.g. a string like: FormatDate(%M)==2 or stArTDate(%Y/%m)==11/3 and I want to convert it to formatdate(%M)==2 or startdate(%Y/%m)==11/3 i.e. change it to lowercase except the part in between the braces (). For the first example, I came up something like this:

```<code>>>> import re
>>> fdt = re.compile('(F|f)(O|o)(R|r)(M|m)(A|a)(T|t)(D|d)(A|a)(T|t)(E|e)\(')
>>> ss = "forMatDate(%M)==2"
>>> if fdt.match(ss):
...   SS = ss.split('(')
...   SS[0] = SS[0].lower()
...   ss = "(".join(SS)
...
>>> print ss
formatdate(%M)==2
</code>```

Whilst it works just fine, I didn't quite like it doing this way. The regular expression is ugly and it makes thing pretty much restricted to a particular string. Is there any better (hence, dynamic) way of doing that? Thanks in advance. Cheers!!

Update:

I probably didn't say it very clearly: it's not always formatdate(), sometimes it's startdate() or enddate() along with UserName==JohnDee and so on.. (it's part of the user-input) but the format is always the same and I wanted something reusable. So, this is the updated version based on Krumelur's script.

```<code>>>> fdt = re.compile('\(%[dmwyMW].*\)')
>>> ss = "formatDate(%M)==4"
>>> st = "UserName==JohnDee"
>>>
>>> def dt_lower(sX):
...   if fdt.search(sX):
...     p1,p2 = sX.split('(',1)
...     sX = "%s(%s" % (p1.lower(), p2)
...   else: sX = sX.lower()
...   return sX
...
>>> print dt_lower(ss)
formatdate(%M)==4
>>>
>>> print dt_lower(st)
username==johndee
</code>```

This is exactly what I wanted. Thanks everyone for helping. Cheers!!

答:
Do your strings always look exactly like this? If so, maybe this is enough:</p>

```<code>p1,p2 = instr.split('(',1)
lc = '%s(%s' % (p1.lower(), p2)
</code>```

Body:
As the title says: What's best way of converting a string from any-case to lowercase keeping a portion unchanged? e.g. a string like: FormatDate(%M)==2 or stArTDate(%Y/%m)==11/3 and I want to convert it to formatdate(%M)==2 or startdate(%Y/%m)==11/3 i.e. change it to lowercase except the part in between the braces (). For the first example, I came up something like this:

>>> import re
>>> fdt = re.compile('(F|f)(O|o)(R|r)(M|m)(A|a)(T|t)(D|d)(A|a)(T|t)(E|e)\(')
>>> ss = "forMatDate(%M)==2"
>>> if fdt.match(ss):
...   SS = ss.split('(')
...   SS[0] = SS[0].lower()
...   ss = "(".join(SS)
...
>>> print ss
formatdate(%M)==2

Whilst it works just fine, I didn't quite like it doing this way. The regular expression is ugly and it makes thing pretty much restricted to a particular string. Is there any better (hence, dynamic) way of doing that? Thanks in advance. Cheers!!

Update:

I probably didn't say it very clearly: it's not always formatdate(), sometimes it's startdate() or enddate() along with UserName==JohnDee and so on.. (it's part of the user-input) but the format is always the same and I wanted something reusable. So, this is the updated version based on Krumelur's script.

>>> fdt = re.compile('\(%[dmwyMW].*\)')
>>> ss = "formatDate(%M)==4"
>>> st = "UserName==JohnDee"
>>>
>>> def dt_lower(sX):
...   if fdt.search(sX):
...     p1,p2 = sX.split('(',1)
...     sX = "%s(%s" % (p1.lower(), p2)
...   else: sX = sX.lower()
...   return sX
...
>>> print dt_lower(ss)
formatdate(%M)==4
>>>
>>> print dt_lower(st)
username==johndee

This is exactly what I wanted. Thanks everyone for helping. Cheers!!

Body:
Do your strings always look exactly like this? If so, maybe this is enough:

p1,p2 = instr.split('(',1)
lc = '%s(%s' % (p1.lower(), p2)


问:
what is the alternate for depreciation for XMLHttpRequest for file-saver?
I am using File Saver for my react application to download files.

```<code>var FileSaver = require('file-saver');
..
..
..
FileSaver.saveAs(files['file_path'], files['file_title']);
</code>```

It was working fine but few days back it showing an error now.

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

答:
You can get rid of the warning by invoking saveAs from a Promise:

```<code>const FileSaver = require('file-saver');
..
..
..
new Promise(resolve => {
  resolve(FileSaver.saveAs(files['file_path'], files['file_title']));
})
.then(result => console.log("Done downloading") )
.catch(err => console.log("Error downloading: " + err));
</code>```

Body:
I am using File Saver for my react application to download files.

var FileSaver = require('file-saver');
..
..
..
FileSaver.saveAs(files['file_path'], files['file_title']);

It was working fine but few days back it showing an error now.

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Body:
You can get rid of the warning by invoking saveAs from a Promise:

const FileSaver = require('file-saver');
..
..
..
new Promise(resolve => {
  resolve(FileSaver.saveAs(files['file_path'], files['file_title']));
})
.then(result => console.log("Done downloading") )
.catch(err => console.log("Error downloading: " + err));


问:
Can't install snips-nlu-en in using pip3?
I am trying to install snips-nlu-en but keep getting the following error:

```<code>sudo -H pip3 install snips-nlu-en

Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 353, in run
    wb.build(autobuilding=True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/lib/python3/dist-packages/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 795, in get_page
    resp.raise_for_status()
  File "/usr/share/python-wheels/requests-2.18.4-py2.py3-none-any.whl/requests/models.py", line 935, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://pypi.org/simple/snips-nlu-en/
</code>```

Please advise how can I fix it?

答:
There is no such package: https://pypi.org/project/snips-nlu-en/ returns error 404. What are you trying to install?

There is snips-nlu, is it what you want?

```<code>pip install snips-nlu
</code>```

Body:
I am trying to install snips-nlu-en but keep getting the following error:

sudo -H pip3 install snips-nlu-en

Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 353, in run
    wb.build(autobuilding=True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/lib/python3/dist-packages/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 795, in get_page
    resp.raise_for_status()
  File "/usr/share/python-wheels/requests-2.18.4-py2.py3-none-any.whl/requests/models.py", line 935, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://pypi.org/simple/snips-nlu-en/

Please advise how can I fix it?

Body:
There is no such package: https://pypi.org/project/snips-nlu-en/ returns error 404. What are you trying to install?

There is snips-nlu, is it what you want?

pip install snips-nlu


问:
Getting Country name By Ip Address in android
My requirement is to get country name by device Ip. Without any WEB/API calls. I googled well but I cannot conclude anything. We have good free service MaxMind but it provides CSV format as well its very huge in file size. Do we have any suggested way.? We should not use location based service like GPS/Network Provider..?

please helps me to fix this out..

答:
Check this service. it is completely free:

https://iplist.cc/api


问:
How to merge elements of a collection in one array using Eloquent
I'm trying the following:

I'm getting all clinic_tests related to my patients using the following function:

```<code>public function getPatientsClinicTests(Specialist $id)
  {
        $patientClinicTests = $id->patients()
            ->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
            ->get()
            ->pluck('PatientClinicTests')
            ->filter(function ($value) { return !empty($value); });

        $result = [];
        foreach ($patientClinicTests as $array) {
            $result = array_merge($result, $array->toArray());
        }

        return $result;
    }
</code>```

First group of code:

```<code>$patientClinicTests = $id->patients()
                ->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
                ->get()
                ->pluck('PatientClinicTests')
                ->filter(function ($value) { return !empty($value); });
</code>```

Brings me a collection of arrays as follows:

```<code>[
  [
    {
      "id": 16,
      "patient_id": 7,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 7,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Austen Wiegand",
        }
      }
    },
    .....
  ],
  [
    {
      "id": 22,
      "patient_id": 1,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 1,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Gregor Wiegand",
        }
      }
    },
    .......
  ]
]
</code>```

As I need to return one array of elements I combine the arrays I got as follows:

```<code>$result = [];
    foreach ($patientClinicTests as $array) {
        $result = array_merge($result, $array->toArray());
    }

    return $result;
</code>```

This returns one array as follows:

```<code>[
    {
      "id": 16,
      "patient_id": 7,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 7,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Austen Wiegand",
        }
      }
    },
    {
      "id": 22,
      "patient_id": 1,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 1,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Gregor Wiegand",
        }
      }
    },
    .......
]
</code>```

I would like to know if there is a smarter option to return as one array of elements using Eloquent instead a foreach statement.

Thanks a lot for your help!

答:
you could use all() method to convert your collection to an array:

```<code>$patientClinicTests = $id->patients()
            ->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
            ->get()
            ->pluck('PatientClinicTests')
            ->filter(function ($value) { return !empty($value); })->all();
</code>```

please note that if you want to iterate over your array you should rebuild the array indexes after filtering ... you can do that using 'values' method:

```<code>$patientClinicTests = $id->patients()
            ->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
            ->get()
            ->pluck('PatientClinicTests')
            ->filter(function ($value) { return !empty($value); })->values()->all();
</code>```

more details in:

https://laravel.com/docs/7.x/collections#introduction

Body:
I'm trying the following:

I'm getting all clinic_tests related to my patients using the following function:

public function getPatientsClinicTests(Specialist $id)
  {
        $patientClinicTests = $id->patients()
            ->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
            ->get()
            ->pluck('PatientClinicTests')
            ->filter(function ($value) { return !empty($value); });

        $result = [];
        foreach ($patientClinicTests as $array) {
            $result = array_merge($result, $array->toArray());
        }

        return $result;
    }

First group of code:

$patientClinicTests = $id->patients()
                ->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
                ->get()
                ->pluck('PatientClinicTests')
                ->filter(function ($value) { return !empty($value); });

Brings me a collection of arrays as follows:

[
  [
    {
      "id": 16,
      "patient_id": 7,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 7,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Austen Wiegand",
        }
      }
    },
    .....
  ],
  [
    {
      "id": 22,
      "patient_id": 1,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 1,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Gregor Wiegand",
        }
      }
    },
    .......
  ]
]

As I need to return one array of elements I combine the arrays I got as follows:

$result = [];
    foreach ($patientClinicTests as $array) {
        $result = array_merge($result, $array->toArray());
    }

    return $result;

This returns one array as follows:

[
    {
      "id": 16,
      "patient_id": 7,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 7,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Austen Wiegand",
        }
      }
    },
    {
      "id": 22,
      "patient_id": 1,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 1,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Gregor Wiegand",
        }
      }
    },
    .......
]

I would like to know if there is a smarter option to return as one array of elements using Eloquent instead a foreach statement.

Thanks a lot for your help!

Body:
you could use all() method to convert your collection to an array:

$patientClinicTests = $id->patients()
            ->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
            ->get()
            ->pluck('PatientClinicTests')
            ->filter(function ($value) { return !empty($value); })->all();

please note that if you want to iterate over your array you should rebuild the array indexes after filtering ... you can do that using 'values' method:

$patientClinicTests = $id->patients()
            ->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
            ->get()
            ->pluck('PatientClinicTests')
            ->filter(function ($value) { return !empty($value); })->values()->all();

more details in:

https://laravel.com/docs/7.x/collections#introduction


问:
Using another variable to store context inside a different variable
I want to add value inside a textbox.text variable only I don't want to use another variable for that issue:

```<code>$temp = '$textbox'

$textbox.text = "this will store this string exactly as I want"

# I want to use temp for that issue but this code of course won't work:

$temp.text = "this will not work"
</code>```

How can I use this $temp variable to call the $textbox variable?

EDIT:

I have a gui with 8 Textboxes, 2 on each row.
the left row are named textbox2 textbox4 textbox6 and so on
the right row are named textbox3 textbox5 textbox7 and so on.
the idea is this:
i have an array with 8 items.
if i have text inside a textbox to the left, i put an array item inside the corresponsing textbox to the right. E.g:

```<code>if (textbox2.textlength -gt 0) #meaning its not empty textbox
 {textbox3.text = $array[0]} #corresponding textbox to the right will get value from array
</code>```

so i have to check textbox2,4,6,8 and so on, and each time i see a value i need to take the next array item and put it inside the right textbox
im gonna add a picture:

i hope its clear.
i want to create a loop for this issue but i cannot do something like:

```<code>for ($i=2; $i -lt 17; $i=$i+2){
    if (textbox$i.textlength -gt 0 ) #of cours this wont work..
</code>```

MORE EDIT:
this is the code that i want to put inside a loop:

```<code> Function FillBoxes ($passarray) {

     if ($textbox2.textlength -gt 0) {
      $textbox3.text = $passarray[0]}

      if ($textbox4.textlength -gt 0) {
      $textbox5.text = $passarray[1]}

     if ($textbox6.textlength -gt 0) {
      $textbox7.text = $passarray[2]}

     if ($textbox8.textlength -gt 0) {
      $textbox9.text = $passarray[3]}

     if ($textbox10.textlength -gt 0) {
      $textbox11.text = $passarray[4]}

     if ($textbox12.textlength -gt 0) {
      $textbox13.text = $passarray[5]}

     if ($textbox14.textlength -gt 0) {
      $textbox15.text = $passarray[6]}

     if ($textbox16.textlength -gt 0) {
      $textbox17.text = $passarray[7]}
     }
</code>```

答:
Perhaps you can make it easier by using the .Name property when you create the TextBoxes:

```<code>for ($i = 2; $i -lt 17; $i++) {
    $textBox = New-Object System.Windows.Forms.TextBox
    $textBox.Name = "TextBox$i"
    # add the rest of the textbox properties and add to the forms Controls array
    $form.Controls.Add($textBox)
}
</code>```

Then, in your FillBoxes function you can select the boxes by their name

```<code>for ($i = 2; $i -lt 17; $i += 2) {
    $tb = $form.Controls.Item("TextBox$i")
    if (!([string]::IsNullOrWhiteSpace($tb.Text))) {
        $form.Controls.Item("TextBox$($i + 1)").Text = $passarray[$i - 2]
    }
}
</code>```

Body:
I want to add value inside a textbox.text variable only I don't want to use another variable for that issue:

$temp = '$textbox'

$textbox.text = "this will store this string exactly as I want"

# I want to use temp for that issue but this code of course won't work:

$temp.text = "this will not work"

How can I use this $temp variable to call the $textbox variable?

EDIT:

I have a gui with 8 Textboxes, 2 on each row.
the left row are named textbox2 textbox4 textbox6 and so on
the right row are named textbox3 textbox5 textbox7 and so on.
the idea is this:
i have an array with 8 items.
if i have text inside a textbox to the left, i put an array item inside the corresponsing textbox to the right. E.g:

if (textbox2.textlength -gt 0) #meaning its not empty textbox
 {textbox3.text = $array[0]} #corresponding textbox to the right will get value from array

so i have to check textbox2,4,6,8 and so on, and each time i see a value i need to take the next array item and put it inside the right textbox
im gonna add a picture:

i hope its clear.
i want to create a loop for this issue but i cannot do something like:

for ($i=2; $i -lt 17; $i=$i+2){
    if (textbox$i.textlength -gt 0 ) #of cours this wont work..

MORE EDIT:
this is the code that i want to put inside a loop:

 Function FillBoxes ($passarray) {

     if ($textbox2.textlength -gt 0) {
      $textbox3.text = $passarray[0]}

      if ($textbox4.textlength -gt 0) {
      $textbox5.text = $passarray[1]}

     if ($textbox6.textlength -gt 0) {
      $textbox7.text = $passarray[2]}

     if ($textbox8.textlength -gt 0) {
      $textbox9.text = $passarray[3]}

     if ($textbox10.textlength -gt 0) {
      $textbox11.text = $passarray[4]}

     if ($textbox12.textlength -gt 0) {
      $textbox13.text = $passarray[5]}

     if ($textbox14.textlength -gt 0) {
      $textbox15.text = $passarray[6]}

     if ($textbox16.textlength -gt 0) {
      $textbox17.text = $passarray[7]}
     }

Body:
Perhaps you can make it easier by using the .Name property when you create the TextBoxes:

for ($i = 2; $i -lt 17; $i++) {
    $textBox = New-Object System.Windows.Forms.TextBox
    $textBox.Name = "TextBox$i"
    # add the rest of the textbox properties and add to the forms Controls array
    $form.Controls.Add($textBox)
}

Then, in your FillBoxes function you can select the boxes by their name

for ($i = 2; $i -lt 17; $i += 2) {
    $tb = $form.Controls.Item("TextBox$i")
    if (!([string]::IsNullOrWhiteSpace($tb.Text))) {
        $form.Controls.Item("TextBox$($i + 1)").Text = $passarray[$i - 2]
    }
}


问:
Permanently change color of selected text and revert in HTML with JavaScript
I want to be able to select text click on a button and have the text color change e. The text color change should persist after the text is no longer selected.

I know that there are many solutions that do this already with CSS. However; I want to be able to have access to the nodes so that on another button click, I can revert the color change. I have tried looking into window.getSelection() and Ranges and DocumentFragment, but I am having trouble understanding how to select the nodes in a DocumentFragment, modify each node, insert it in the right position in the document and also create a reference so that I can, in a later click, change the color again back to black.

I also found this thread which essentially does what I"m trying to do, but it uses execCommand which is obsolete.

I don't want a CSS solution and I don't want a solution that uses jQuery.

Below is the js code and codepen with a similar html structure that I am working with.

I have 2 buttons, one that changes the selections color and one that will revert the color of the selection even after the text is no longer selected.

I am using window.getSelection() to get a Selection of the selected text. I check that the Selection is valid and then get a Range with getRangeAt(0) followed by a call to extractContents().

This is where the hard part comes in because:

It extracts the DocumentFragment from the document so how can I re-insert the DocumentFragment in the same position it was extracted from?

I am having trouble figuring out how to modify the nodes in the DocumentFragment styles

```<code>var changeColorButton = document.getElementById('xyz');
var revertColor = document.getElementById('zyx');

const changeSelectionColor = () => {
  let selection = window.getSelection()
  if (selection) {
    let range = selection.getRangeAt(0)
    if (range) {
      let frag = range.extractContents();
    }
    /*
      2 problems:
      1. accessing each node in the DocumentFragment and modifying the style then re-inserting into the correct spot
      2. Creating a reference to this fragment for revertColorChange() to use to change the color back to black
    */
  }
}

const revertColorChange = () => {
  // revert color
}

changeColorButton.addEventListener('click', changeSelectionColor);
</code>```

Minimal Reproducible Example - https://codepen.io/NoobCodePenner/pen/GRoKNRd

答:
```<code><!DOCTYPE html>
<html>
<body>

<button onClick="changeColor()">Change color</button><br/>
<button onClick="changeColorBack()">Change to previous color</button>
<p id="demo">Javascript</p>

<script>
changeColor=()=>{
document.getElementById("demo").style.color ="red"
}

changeColorBack=()=>{
document.getElementById("demo").style.color ="black"
}

</script>

</body>
</html>

</code>```

Is this what you are looking for?

Body:
I want to be able to select text click on a button and have the text color change e. The text color change should persist after the text is no longer selected.

I know that there are many solutions that do this already with CSS. However; I want to be able to have access to the nodes so that on another button click, I can revert the color change. I have tried looking into window.getSelection() and Ranges and DocumentFragment, but I am having trouble understanding how to select the nodes in a DocumentFragment, modify each node, insert it in the right position in the document and also create a reference so that I can, in a later click, change the color again back to black.

I also found this thread which essentially does what I"m trying to do, but it uses execCommand which is obsolete.

I don't want a CSS solution and I don't want a solution that uses jQuery.

Below is the js code and codepen with a similar html structure that I am working with.

I have 2 buttons, one that changes the selections color and one that will revert the color of the selection even after the text is no longer selected.

I am using window.getSelection() to get a Selection of the selected text. I check that the Selection is valid and then get a Range with getRangeAt(0) followed by a call to extractContents().

This is where the hard part comes in because:

It extracts the DocumentFragment from the document so how can I re-insert the DocumentFragment in the same position it was extracted from?

I am having trouble figuring out how to modify the nodes in the DocumentFragment styles

var changeColorButton = document.getElementById('xyz');
var revertColor = document.getElementById('zyx');

const changeSelectionColor = () => {
  let selection = window.getSelection()
  if (selection) {
    let range = selection.getRangeAt(0)
    if (range) {
      let frag = range.extractContents();
    }
    /*
      2 problems:
      1. accessing each node in the DocumentFragment and modifying the style then re-inserting into the correct spot
      2. Creating a reference to this fragment for revertColorChange() to use to change the color back to black
    */
  }
}

const revertColorChange = () => {
  // revert color
}

changeColorButton.addEventListener('click', changeSelectionColor);

Minimal Reproducible Example - https://codepen.io/NoobCodePenner/pen/GRoKNRd

Body:
<!DOCTYPE html>
<html>
<body>

<button onClick="changeColor()">Change color</button><br/>
<button onClick="changeColorBack()">Change to previous color</button>
<p id="demo">Javascript</p>

<script>
changeColor=()=>{
document.getElementById("demo").style.color ="red"
}

changeColorBack=()=>{
document.getElementById("demo").style.color ="black"
}

</script>

</body>
</html>

Is this what you are looking for?


问:
HTTP3 Client for flutter
Is There a HTTP3 client for dart? There is Flupke in Java, Aioqic in python but  I didn't find one for dart as well as flutter

答:
If you need a persistent connection you can use the Client class provided by the http Library:
https://pub.dev/documentation/http/latest/http/Client-class.html

Try out this package, to make the consumption of HTTP resources easier: https://pub.dev/packages/http

Title: HTTP3 Client for flutter


问:
How to replace specific values that starts with some pattern in config.yml using sed
I have a file named config.yml, I want to replace all the values in YAML file which start with keyword config only

```<code>key1: "config/some_text"
key2: "some_text/config/"
</code>```

I want it like

```<code>key1: "my_new_text/some_text"
key2: "some_text/config/"
</code>```

I'm using the following command, this might be wrong as I'm not familiar with regex

```<code>sed -i 's:config/*$.:new_text:g' file_name
</code>```

and the output is

```<code>key1: "my_new_text"
key2: "some_text/my_new_text"
</code>```

答:
This should work:

```<code>sed -i -E 's/config[^"]+/my_new_text/' config.yml
</code>```

Input:

```<code>key1: "config/some_text"
key2: "some_text/config"
</code>```

Output:

```<code>key1: "my_new_text"
key2: "some_text/config"
</code>```

Explanation:

-E will use extended regex

config[^"]+ means "substitute config and the chars that follow if they are not " and they are at least one", so the second config will not be substituted because it doesn't have a char that is not " after it.

Body:
I have a file named config.yml, I want to replace all the values in YAML file which start with keyword config only

key1: "config/some_text"
key2: "some_text/config/"

I want it like

key1: "my_new_text/some_text"
key2: "some_text/config/"

I'm using the following command, this might be wrong as I'm not familiar with regex

sed -i 's:config/*$.:new_text:g' file_name

and the output is

key1: "my_new_text"
key2: "some_text/my_new_text"

Body:
This should work:

sed -i -E 's/config[^"]+/my_new_text/' config.yml

Input:

key1: "config/some_text"
key2: "some_text/config"

Output:

key1: "my_new_text"
key2: "some_text/config"

Explanation:

-E will use extended regex

config[^"]+ means "substitute config and the chars that follow if they are not " and they are at least one", so the second config will not be substituted because it doesn't have a char that is not " after it.


问:
My javascript function for clearing a form text input field is not working
Even though a lot of work is left, the basic calculator is done, everything is working just fine except the clear function. I can not get it to clear the viewer. need immediate help please.

(i put everything in one file so it is easy for everyone to understand the full thing)

Please avoid the styling tho.

So basically i made this extremely simple calculator with the function clear()
Any ideas on how i can make this function in order to clear the viewer?

```<code><!DOCTYPE html>
<html>

<head>

<script>
  function insert(num) {
    document.view.viewer.value = document.view.viewer.value+num
  }
  function equal() {
    document.view.viewer.value = eval(document.view.viewer.value);
  }
  function clear() {
    document.view.viewer.value = "";
  }
</script>

<style>
body {
  background-image: url("peepee.png");
}
*{
  margin: 0px;
  padding: 0px;
}
.button {
  height:100px;
  width:100px;
  background-color:grey;
  text-align:center;
  margin:2px;
  font-size: 50px;
  cursor: pointer;
  border: 0px;
}
.clear {
  height:100px;
  width:400px;
  background-color: red;
  text-align:center;
  margin:2px;
  font-size: 50px;
  cursor: pointer;
  border: 0px;
}
.viewer {
  height: 100px;
  width: 430px;
  font-size: 50px;
  margin: 2px
}
</style>

</head>

<body>
  <div class= "main">
    <form name= "view">
      <input class="viewer" name= "viewer">
    </form>
    <table>
      <tr>
        <td><input class="button" value="7" onclick= "insert(7)"></td>
        <td><input class="button" value="8" onclick= "insert(8)"></td>
        <td><input class="button" value="9" onclick= "insert(9)"></td>
        <td><input class="button" value="-" onclick= "insert('/')"></td>
      </tr>
      <tr>
        <td><input class="button" value="4" onclick= "insert(4)"></td>
        <td><input class="button" value="5" onclick= "insert(5)"></td>
        <td><input class="button" value="6" onclick= "insert(6)"></td>
        <td><input class="button" value="x" onclick= "insert('*')"></td>
      </tr>
      <tr>
        <td><input class="button" value="1" onclick= "insert(1)"></td>
        <td><input class="button" value="2" onclick= "insert(2)"></td>
        <td><input class="button" value="3" onclick= "insert(3)"></td>
        <td><input class="button" value="-" onclick= "insert('-')"></td>
      </tr>
      <tr>
        <td><input class="button" value="0" onclick= "insert(0)"></td>
        <td><input class="button" value="." onclick= "insert('.')"></td>
        <td><input class="button" value="=" onclick= "equal()"></td>
        <td><input class="button" value="+" onclick= "insert('+')"></td>
      </tr>
    </table>
    <table>
      <tr>
        <td><input class= "clear" value="Clear" onclick= "clear()"></td>
      </tr>
    </table>
  </div>
</body>

</html>
</code>```

答:
so I figured out solution you are not giving a type of your input
  and change your clear function to something else clearText. It
  seems that clear function is some kind of inbuilt function
  and put defer attribute in your script tag so that it will load after the body

function clearText() {
    console.log("Clear Button clicked!");
    document.view.viewer.value = "";
};

<input type="button" class="clear" value="Clear" onclick="clearText()" />

Body:
Even though a lot of work is left, the basic calculator is done, everything is working just fine except the clear function. I can not get it to clear the viewer. need immediate help please.

(i put everything in one file so it is easy for everyone to understand the full thing)

Please avoid the styling tho.

So basically i made this extremely simple calculator with the function clear()
Any ideas on how i can make this function in order to clear the viewer?

<!DOCTYPE html>

    <form name= "view">
      <input class="viewer" name= "viewer">
    </form>

        <input class="button" value="7" onclick= "insert(7)">
        <input class="button" value="8" onclick= "insert(8)">
        <input class="button" value="9" onclick= "insert(9)">
        <input class="button" value="-" onclick= "insert('/')">

        <input class="button" value="4" onclick= "insert(4)">
        <input class="button" value="5" onclick= "insert(5)">
        <input class="button" value="6" onclick= "insert(6)">
        <input class="button" value="x" onclick= "insert('*')">

        <input class="button" value="1" onclick= "insert(1)">
        <input class="button" value="2" onclick= "insert(2)">
        <input class="button" value="3" onclick= "insert(3)">
        <input class="button" value="-" onclick= "insert('-')">

        <input class="button" value="0" onclick= "insert(0)">
        <input class="button" value="." onclick= "insert('.')">
        <input class="button" value="=" onclick= "equal()">
        <input class="button" value="+" onclick= "insert('+')">

        <input class= "clear" value="Clear" onclick= "clear()">

Body:
so I figured out solution you are not giving a type of your input
  and change your clear function to something else clearText. It
  seems that clear function is some kind of inbuilt function
  and put defer attribute in your script tag so that it will load after the body

function clearText() {
    console.log("Clear Button clicked!");
    document.view.viewer.value = "";
};

<td><input type="button" class="clear" value="Clear" onclick="clearText()" /></td>


问:
Mongo bulk fetch record based on multiple conditions
I have multiple records stored in mongo collections and I have multiple conditions.
I want to batch or bulk read the records based on different conditions and I also want to know the records which are fetched are outcome of which condition.

I am using spring boot and mongotemplate to perform this operation.

I have tried of following approaches

1.Combining the conditions with OR(But I will not be aware the record is the outcome of which condition.

2.Bulkoperations,But I didnt find bulk read.

答:
We can combine conditions using $switch or $cond with projection in mongo.Following the is mongo query for the same

```<code>db.action.aggregate(
  {
    $project:
      {
        "name":"$name",
        "condNAme" :
        {
          $switch:
            {
              branches: [
              {  case: {$eq: ["$clientId", 1000]}, then:"cond1"},
              {  case: {$eq: ["$clientId", 1001]}, then:"cond2"},
              ],
              default:0
            }
         }
      }
   }
)
</code>```

if first condition is satisfied then it will append cond1,if second condition is satisfied then it will append cond2.So in this way we can identify which condition is executed to true

Body:
We can combine conditions using $switch or $cond with projection in mongo.Following the is mongo query for the same

db.action.aggregate(
  {
    $project:
      {
        "name":"$name",
        "condNAme" :
        {
          $switch:
            {
              branches: [
              {  case: {$eq: ["$clientId", 1000]}, then:"cond1"},
              {  case: {$eq: ["$clientId", 1001]}, then:"cond2"},
              ],
              default:0
            }
         }
      }
   }
)

if first condition is satisfied then it will append cond1,if second condition is satisfied then it will append cond2.So in this way we can identify which condition is executed to true


问:
How to remove button from Highcharts
I'm creating charts with the Highcharts library and I wonder how to remove the 2 little buttons on the right corner which one you can print and download graphs and I'd like to add a new one.

Maybe someone could help me?

答:
The best way to do this is to update the exporting.buttons.contextButton.menuItems array to only include the menu items you want. Below is an example that excludes the "Print Chart" and "View Full Screen" options.

```<code>exporting: {
    buttons: {
        contextButton: {
            menuItems: ["downloadPNG", "downloadJPEG", "downloadPDF", "downloadSVG"]
        }
    }
}
</code>```

Highcharts Example

Title: How to remove button from Highcharts

Body:
The best way to do this is to update the exporting.buttons.contextButton.menuItems array to only include the menu items you want. Below is an example that excludes the "Print Chart" and "View Full Screen" options.

exporting: {
    buttons: {
        contextButton: {
            menuItems: ["downloadPNG", "downloadJPEG", "downloadPDF", "downloadSVG"]
        }
    }
}

Highcharts Example


问:
A p5/.js custom rotation behavior problem
I am trying to make a custom rotation/magnetic behavior that makes a bunch of box() rotating normally and will stop rotating and magnetically attract towards the cursor if within a certain distance.

I am not sure how to fix it as now the cubes can only spin randomly.

please help/give some clues thanks!

let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(243, 243, 243);
  //background(backCol);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));

    }
  }

}

function draw() {
  background(backCol);
  noFill();

  for (let a = 0; a < cubes.length; a++) {
    cubes[a].update();
  }
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 30;
    this.stroke = 70;
    this.shift1 = color(96);
    this.shift2 = color(244);
    this.a = atan2(mouseY-this.y, mouseX-this.x);
  }

  update() {
    this.shape();
    this.magnetic();
  }

  shape() {
    push();
    stroke(this.stroke);
    translate(this.x - width / 2, this.y - height / 2, 0);
    rotateX(millis()/1000);
    rotateY(millis()/1000);
    box(this.size);
    pop();
  }

  shift_Color() {
    let distance = dist(mouseX, mouseY, this.x, this.y);
    let shiftX = map(mouseX,0,this.a,0,1.0);
    let change = lerpColor(this.shift1,this.shift2,shiftX);

    if (distance < this.a) {
      fill(change);
    } else {
      noFill();
    }
  }

  magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.size * 2) {
      rotateX(this.a);
      rotateY(this.a);
    } else {
      rotateX(millis()/1000);
      rotateY(millis()/1000);
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script></code>```

答:
You have to invoke the method magnetic() in the method shape, in between push() and pop(), instead of rotateX()/rotateY() rather than after drawing the boxes:

shape() {
    push();
    stroke(this.stroke);
    translate(this.x - width / 2, this.y - height / 2, 0);
    //rotateX(millis()/1000);
    //rotateY(millis()/1000);
    this.magnetic()
    box(this.size);
    pop();
}
```

<p>Further more the angle <code>a</code> depends on the current mouse position rather than on the position of mouse, when the object is constructed.<br>
Compute the angle <code>a</code> in the method <code>magnetic</code> rather than in the constructor:</p>

<pre class="lang-js prettyprint-override"><code>magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.size * 2) {
      this.a = atan2(mouseY-this.y, mouseX-this.x);
      rotateX(this.a);
      rotateY(this.a);
    } else {
      rotateX(millis()/1000);
      rotateY(millis()/1000);
    }
}
</code>```

See the example:

let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(243, 243, 243);
  //background(backCol);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));

    }
  }

}

function draw() {
  background(backCol);
  noFill();

  for (let a = 0; a < cubes.length; a++) {
    cubes[a].update();
  }
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 30;
    this.stroke = 70;
    this.shift1 = color(96);
    this.shift2 = color(244);
    this.a = atan2(mouseY-this.y, mouseX-this.x);
  }

  update() {
    this.shape();
    //this.magnetic();
  }

  shape() {
    push();
    stroke(this.stroke);
    translate(this.x - width / 2, this.y - height / 2, 0);
    //rotateX(millis()/1000);
    //rotateY(millis()/1000);
    this.magnetic()
    box(this.size);
    pop();
  }

  shift_Color() {
    let distance = dist(mouseX, mouseY, this.x, this.y);
    let shiftX = map(mouseX,0,this.a,0,1.0);
    let change = lerpColor(this.shift1,this.shift2,shiftX);

    if (distance < this.a) {
      fill(change);
    } else {
      noFill();
    }
  }

  magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.size * 2) {
      this.a = atan2(mouseY-this.y, mouseX-this.x);
      rotateX(this.a);
      rotateY(this.a);
    } else {
      rotateX(millis()/1000);
      rotateY(millis()/1000);
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script></code>```

Body:
You have to invoke the method magnetic() in the method shape, in between push() and pop(), instead of rotateX()/rotateY() rather than after drawing the boxes:

shape() {
    push();
    stroke(this.stroke);
    translate(this.x - width / 2, this.y - height / 2, 0);
    //rotateX(millis()/1000);
    //rotateY(millis()/1000);
    this.magnetic()
    box(this.size);
    pop();
}

Further more the angle a depends on the current mouse position rather than on the position of mouse, when the object is constructed.

Compute the angle a in the method magnetic rather than in the constructor:

magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.size * 2) {
      this.a = atan2(mouseY-this.y, mouseX-this.x);
      rotateX(this.a);
      rotateY(this.a);
    } else {
      rotateX(millis()/1000);
      rotateY(millis()/1000);
    }
}

See the example:

let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(243, 243, 243);
  //background(backCol);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));

    }
  }

}

function draw() {
  background(backCol);
  noFill();

  for (let a = 0; a < cubes.length; a++) {
    cubes[a].update();
  }
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 30;
    this.stroke = 70;
    this.shift1 = color(96);
    this.shift2 = color(244);
    this.a = atan2(mouseY-this.y, mouseX-this.x);
  }

  update() {
    this.shape();
    //this.magnetic();
  }

  shape() {
    push();
    stroke(this.stroke);
    translate(this.x - width / 2, this.y - height / 2, 0);
    //rotateX(millis()/1000);
    //rotateY(millis()/1000);
    this.magnetic()
    box(this.size);
    pop();
  }

  shift_Color() {
    let distance = dist(mouseX, mouseY, this.x, this.y);
    let shiftX = map(mouseX,0,this.a,0,1.0);
    let change = lerpColor(this.shift1,this.shift2,shiftX);

    if (distance < this.a) {
      fill(change);
    } else {
      noFill();
    }
  }

  magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.size * 2) {
      this.a = atan2(mouseY-this.y, mouseX-this.x);
      rotateX(this.a);
      rotateY(this.a);
    } else {
      rotateX(millis()/1000);
      rotateY(millis()/1000);
    }
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>


问:
The free Delphi 2006 compiler
On Wikipedia I read:

Borland Delphi 2006 [...] Each version is available in two editions:
  Explorer—a free downloadable
  version—and Professional

Is this edition still available? Or are people who grabbed it in 2006 lucky and the others not that much?

答: Unfortunately there are no free Delphi versions now. You can use free Turbo Delphi only if you already have the product keyfile, but you can't obtain new free Turbo Delphi keyfile anymore.</p>

Title: The free Delphi 2006 compiler


问:
Flutter - Convert minutes to TimeOfDay
Currently I get a number from the BE that states like 750 minutes (int) and should represent the time of day.

750 minutes = 12.5 hours and so the UI should display 12:30

1080 minutes = 18 hours and so the UI should display 18:00

But I can't seem to find a way to get a clean convertion from minutes to a proper Object with hours and minutes.

In the end I want to have a TimeOfDay object

I will continue to struggle and will also post if I find the answer myself :)

答:
With the help of the comments above I resolved it by splitting the sting. I don't see this as the best way to convert since I'm dependened that the Duration Class will never change but never the less I got what I wanted by doing the following

```<code>  TimeOfDay minutesToTimeOfDay(int minutes) {
      Duration duration = Duration(minutes: minutes);
      List<String> parts = duration.toString().split(':');
      return TimeOfDay(hour: int.parse(parts[0]), minute: int.parse(parts[1]));
  }
</code>```

Create Duration with the amount of minutes, then toString() that instance this will outpout 00:00 and then split this string on the colon ":"

Title: Flutter - Convert minutes to TimeOfDay

Body:
With the help of the comments above I resolved it by splitting the sting. I don't see this as the best way to convert since I'm dependened that the Duration Class will never change but never the less I got what I wanted by doing the following

  TimeOfDay minutesToTimeOfDay(int minutes) {
      Duration duration = Duration(minutes: minutes);
      List<String> parts = duration.toString().split(':');
      return TimeOfDay(hour: int.parse(parts[0]), minute: int.parse(parts[1]));
  }

Create Duration with the amount of minutes, then toString() that instance this will outpout 00:00 and then split this string on the colon ":"


问:
AJAX data not displayed in page
To sum up what I'm trying to achieve here:

Inside of index.php, when selecting an option in a dropdown list, a function is called with the onchange="displayData(this) event inside of <select>

This function performs an AJAX POST request to a PHP page (target.php) with the value of the selected option inside of data

The PHP page is displayed inside a div on the page

Here is the function, using jQuery:

```<code>function displayData(str){
  $.ajax({
    url: "target.php",
    type: "POST",
    data: {"value": str.value},
    success: function(data){
      console.log(data);
    }
  });

  $('#my-div').load('target.php');
}
</code>```

To make things easier, here is what the PHP page looks like: <?php echo $_POST['value']; ?>

When logging data on success, everything seems to work fine, the value of $_POST['value'] is displayed in the console correctly. In the page itself though, I get an error:

Notice: Undefined index: value

Sorry if it seems kind of dumb, but I can't figure out what I'm doing wrong... So I thought of asking the community. Thank you for your help guys! Cheers.

答: hey the problem is quite simple, if you are posting the data value getting from ajax to target.php then the  $('#my-div').load('target.php') should be inside the ajax success function and you have to put the data using html function like this $("#my-div").html(data). it will directly load the data in html format inside the div.

Title: AJAX data not displayed in page

Body:
To sum up what I'm trying to achieve here:

Inside of index.php, when selecting an option in a dropdown list, a function is called with the onchange="displayData(this) event inside of <select>

This function performs an AJAX POST request to a PHP page (target.php) with the value of the selected option inside of data

The PHP page is displayed inside a div on the page

Here is the function, using jQuery:

function displayData(str){
  $.ajax({
    url: "target.php",
    type: "POST",
    data: {"value": str.value},
    success: function(data){
      console.log(data);
    }
  });

  $('#my-div').load('target.php');
}

To make things easier, here is what the PHP page looks like: <?php echo $_POST['value']; ?>

When logging data on success, everything seems to work fine, the value of $_POST['value'] is displayed in the console correctly. In the page itself though, I get an error:

Notice: Undefined index: value

Sorry if it seems kind of dumb, but I can't figure out what I'm doing wrong... So I thought of asking the community. Thank you for your help guys! Cheers.


问:
Removing .h extension in user defined c++ header file
Can we remove .h extensions while we define our own header file in c++? like in case of standard header files in c++.

I have created a header file and named it add.h and tried including it using #include "add" but it didn't work.

after following up the comments and answers:
using codeblocks ide
i have created a "add" of type File and tried it including in my source file and it worked. attaching the snapshot below.
the aim of my question is to ask if userdefined header files can also omit .h extensions and how?
i am really trying to explore this fact and don't have a good understanding of how compilers stores standard header files.
A easy to understood conclusion is really appreciated
Thankyou.

答:
Can we remove .h extensions while we define our own header file in c++?

Sure, as long as that matches the filename of the file. As far as the language is concerned, the name of the file is largely irrelevant.

However, .h or similar such as .hpp is conventional, and helps the reader of the source to understand what the file is used for. This is an important consideration.

Another consideration is that some tools use the filename as a heuristic to determine the purpose of the file. For example, your IDE might not assume that the file contains C++ code, and thus not enable C++ features such as source analysis unless you follow a common naming convention.

I have created a header file and named it add.h and tried it including in source file using #include "add" but it didn't work.i know i am missing some important concepts here.

What you're missing is that the include directive must match the name of the file. If you include "add", then you must name the file add, not add.h. If you name a file add.h, then you must include "add.h", not "add".


问:
MySQL query filtering results
I have a table named pt_products with the fields:

```<code>  `id` int(6) unsigned NOT NULL,
  `ean` bigint(13) unsigned NOT NULL,
  `merchant` varchar(64) NOT NULL,
  `price` decimal(10,2)NOT NULL,
  PRIMARY KEY (`id`)
</code>```

Example of entries on the table:

```<code>INSERT INTO `pt_products` (`id`, `ean`, `merchant`, `price`) VALUES
 ('1', '884116311874', 'Amazon', '10000.00'),
  ('2', '884116311874', 'BestBuy', '10999.00'),
('3','884116321378', 'CyberPuerta', '14789.00'),
 ('4', '884116311875', 'Amazon', '10999.00'),
  ('5', '884116311875', 'BestBuy', '10000.00');
</code>```

What I need to do is:

-Group the entries on the table that have the same ean.

-Discard the grouped entries in case none of them have "Amazon" on the merchant field.

-Discard the grouped entries that have "Amazon" on the merchant field if the price field of the one containing "Amazon" as merchant has not the lowest price field.

-At least one different merchant with the same 'ean' besides 'Amazon'

What I have achieved is to group the entries of the table by ean, but this displays all the entries ordered by ean:

```<code>SELECT ean, merchant, price FROM pt_products ORDER BY ean;
</code>```

I wonter what is the best way to get the desired results. If by using the apprpiate query of by filtering the results from the query using a php loop.

You can test using the example I given above here
Thank you

答:
You can group by ean and set the condition in the having clause:

```<code>SELECT ean
FROM pt_products
GROUP BY ean
HAVING MIN(price) = MIN(CASE WHEN merchant = 'Amazon' THEN price END)
   AND SUM(merchant <> 'Amazon') > 0
</code>```

If you want all the rows for the results of the above query, then use also the operator IN:

```<code>SELECT *
FROM pt_products
WHERE ean IN (
    SELECT ean
    FROM pt_products
    GROUP BY ean
    HAVING MIN(price) = MIN(CASE WHEN merchant = 'Amazon' THEN price END)
       AND SUM(merchant <> 'Amazon') > 0
)
</code>```

See the demo.

Results:

```<code>>    id |          ean | merchant    |    price
> ----: | -----------: | :---------- | -------:
>     1 | 884116311874 | Amazon      | 10000.00
>     2 | 884116311874 | BestBuy     | 10999.00
> 87448 |  10343943704 | Amazon      |  3259.00
> 93885 |  10343943704 | Linio       |  3999.00
> 94913 |  10343943704 | XtremeTecPc |  3834.00
</code>```

Title: MySQL query filtering results

Body:
I have a table named pt_products with the fields:

  `id` int(6) unsigned NOT NULL,
  `ean` bigint(13) unsigned NOT NULL,
  `merchant` varchar(64) NOT NULL,
  `price` decimal(10,2)NOT NULL,
  PRIMARY KEY (`id`)

Example of entries on the table:

INSERT INTO `pt_products` (`id`, `ean`, `merchant`, `price`) VALUES
 ('1', '884116311874', 'Amazon', '10000.00'),
  ('2', '884116311874', 'BestBuy', '10999.00'),
('3','884116321378', 'CyberPuerta', '14789.00'),
 ('4', '884116311875', 'Amazon', '10999.00'),
  ('5', '884116311875', 'BestBuy', '10000.00');

What I need to do is:

-Group the entries on the table that have the same ean.

-Discard the grouped entries in case none of them have "Amazon" on the merchant field.

-Discard the grouped entries that have "Amazon" on the merchant field if the price field of the one containing "Amazon" as merchant has not the lowest price field.

-At least one different merchant with the same 'ean' besides 'Amazon'

What I have achieved is to group the entries of the table by ean, but this displays all the entries ordered by ean:

SELECT ean, merchant, price FROM pt_products ORDER BY ean;

I wonter what is the best way to get the desired results. If by using the apprpiate query of by filtering the results from the query using a php loop.

You can test using the example I given above here
Thank you

Body:
You can group by ean and set the condition in the having clause:

SELECT ean
FROM pt_products
GROUP BY ean
HAVING MIN(price) = MIN(CASE WHEN merchant = 'Amazon' THEN price END)
   AND SUM(merchant <> 'Amazon') > 0

If you want all the rows for the results of the above query, then use also the operator IN:

SELECT *
FROM pt_products
WHERE ean IN (
    SELECT ean
    FROM pt_products
    GROUP BY ean
    HAVING MIN(price) = MIN(CASE WHEN merchant = 'Amazon' THEN price END)
       AND SUM(merchant <> 'Amazon') > 0
)

See the demo.

Results:

>    id |          ean | merchant    |    price
> ----: | -----------: | :---------- | -------:
>     1 | 884116311874 | Amazon      | 10000.00
>     2 | 884116311874 | BestBuy     | 10999.00
> 87448 |  10343943704 | Amazon      |  3259.00
> 93885 |  10343943704 | Linio       |  3999.00
> 94913 |  10343943704 | XtremeTecPc |  3834.00


问:
How can I move an object randomly in small area from his current position?
```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetMove : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        transform.transform.position = RandomVector(0.1f, 0.5f);
    }

    private Vector3 RandomVector(float min, float max)
    {
        var x = Random.Range(min, max);
        var y = Random.Range(min, max);
        var z = Random.Range(min, max);

        return new Vector3(transform.position.x + x, transform.position.y + y, transform.position.z);
    }
}
</code>```

I want it to move in small area randomly between 0.1 and 0.5 but since I did + x and + y it keep changing position and move far far nonstop.

```<code>return new Vector3(transform.position.x + x, transform.position.y + y, transform.position.z);
</code>```

What should I do instead transform.position.x + x and transform.position.x + y ?

答:
This is what I wanted :
The script is attached to a cube.
Another script is attached to the sci-fi drone I have that all is do is making the drone LookAt the cube.

That's it this create a lost control effect of the sci-fi drone shooting out of control.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetMove : MonoBehaviour
{
    [SerializeField] private List<Vector3> waypoints = new List<Vector3>();  // Hom many items you want, will show in Inspector
    public float speed;

    private int current = 0;
    private float WPradius = 1;

    private void Start()
    {
        GetRandom();
    }

    private void Update()
    {
        MoveBetweenWaypoints();
    }

    private void GetRandom()
    {
        for (int i = 0; i < 30; i++)
        {
            waypoints.Add(new Vector3(Random.Range(transform.position.x, transform.position.x + 3f),
                Random.Range(transform.position.y, transform.position.y + 3f),
                transform.position.z));
        }
    }

    private void MoveBetweenWaypoints()
    {
        if(Vector3.Distance(waypoints[current], transform.position) < WPradius)
        {
            current = Random.Range(0, waypoints.Count);
            if(current >= waypoints.Count)
            {
                current = 0;
            }
        }

        transform.position = Vector3.MoveTowards(transform.position, waypoints[current], Time.deltaTime * speed);
    }
}
</code>```

Body:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetMove : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        transform.transform.position = RandomVector(0.1f, 0.5f);
    }

    private Vector3 RandomVector(float min, float max)
    {
        var x = Random.Range(min, max);
        var y = Random.Range(min, max);
        var z = Random.Range(min, max);

        return new Vector3(transform.position.x + x, transform.position.y + y, transform.position.z);
    }
}

I want it to move in small area randomly between 0.1 and 0.5 but since I did + x and + y it keep changing position and move far far nonstop.

return new Vector3(transform.position.x + x, transform.position.y + y, transform.position.z);

What should I do instead transform.position.x + x and transform.position.x + y ?

Body:
This is what I wanted :
The script is attached to a cube.
Another script is attached to the sci-fi drone I have that all is do is making the drone LookAt the cube.

That's it this create a lost control effect of the sci-fi drone shooting out of control.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetMove : MonoBehaviour
{
    [SerializeField] private List<Vector3> waypoints = new List<Vector3>();  // Hom many items you want, will show in Inspector
    public float speed;

    private int current = 0;
    private float WPradius = 1;

    private void Start()
    {
        GetRandom();
    }

    private void Update()
    {
        MoveBetweenWaypoints();
    }

    private void GetRandom()
    {
        for (int i = 0; i < 30; i++)
        {
            waypoints.Add(new Vector3(Random.Range(transform.position.x, transform.position.x + 3f),
                Random.Range(transform.position.y, transform.position.y + 3f),
                transform.position.z));
        }
    }

    private void MoveBetweenWaypoints()
    {
        if(Vector3.Distance(waypoints[current], transform.position) < WPradius)
        {
            current = Random.Range(0, waypoints.Count);
            if(current >= waypoints.Count)
            {
                current = 0;
            }
        }

        transform.position = Vector3.MoveTowards(transform.position, waypoints[current], Time.deltaTime * speed);
    }
}