问:
Why is my Trigger not triggering (Unity, C#)
I work at the moment on my enemies but in the script they don't want to activate the trigger in the script :/

I'm using the same script and trigger for every enemy (they only have different weapons)

The transition doesn't have exit time

Normally it should after Facetargetting me, starting to play animation because of trigger

This is the script:

```<code>public class Gegnerscript : MonoBehaviour
{
    public float lookRadius = 10f;

    Transform target;
    NavMeshAgent agent;

    Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        target = GegnerManager.instance.Player.transform;
        agent = GetComponent<NavMeshAgent>();
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        float distance = Vector3.Distance(target.position, transform.position);

        if (distance <= lookRadius)
        {
            agent.SetDestination(target.position);

            if (distance <= agent.stoppingDistance)
            {
                FaceTarget(); //is working
                // animator.SetTrigger("AngriffGegner");  // is not working/doesn't trigger
            }
        }
    }

    void FaceTarget ()
    {
        Vector3 direction = (target.position - transform.position).normalized;
        Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.black;
        Gizmos.DrawWireSphere(transform.position, lookRadius);
    }
}
</code>```

答:
Make sure that you typed the name of the trigger exactly
because if there is any difference the trigger won't work

so check the trigger name in the unity editor and make sure it matches the name you typed in code (also check for capital and small letters they really matter)

Body:
I work at the moment on my enemies but in the script they don't want to activate the trigger in the script :/

I'm using the same script and trigger for every enemy (they only have different weapons)

The transition doesn't have exit time

Normally it should after Facetargetting me, starting to play animation because of trigger

This is the script:

public class Gegnerscript : MonoBehaviour
{
    public float lookRadius = 10f;

    Transform target;
    NavMeshAgent agent;

    Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        target = GegnerManager.instance.Player.transform;
        agent = GetComponent<NavMeshAgent>();
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        float distance = Vector3.Distance(target.position, transform.position);

        if (distance <= lookRadius)
        {
            agent.SetDestination(target.position);

            if (distance <= agent.stoppingDistance)
            {
                FaceTarget(); //is working
                // animator.SetTrigger("AngriffGegner");  // is not working/doesn't trigger
            }
        }
    }

    void FaceTarget ()
    {
        Vector3 direction = (target.position - transform.position).normalized;
        Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.black;
        Gizmos.DrawWireSphere(transform.position, lookRadius);
    }
}


来源: stackexchange

问:
Firebase Firestore not repsonding to EventListener
I have a RecyclerView.Adapter in my code which is used to set elements in my layout file, but due to an UNKNOWN error, I am not able to display those elements. I am able to retrieve the data from Firebase, able to reach the onBindViewHolder but, there are no end results.

Logcat

```<code>D/HomeViewModel: Data was added to the LiveData List.[secondQuestion, question]
D/HomeAdapter: onCreateViewHolder
    onBindViewHolder
</code>```

HomeAdapter.java

```<code>@Override
    public void onBindViewHolder(@NonNull HomeAdapter.ViewHolder holder, final int position) {
         if (mQuestions.isEmpty()) {
              String question = mQuestions.get(position);
              holder.question.setText(question);
          }
}
</code>```

HomeFragment.java

```<code>homeViewModel.getmQuestionsData().observe(getViewLifecycleOwner(), new Observer<List<String>>() {
            @Override
            public void onChanged(List<String> mQuestionList) {
                mQuestion.addAll(mQuestionList);

                // TODO: The FUCKING Bug is around here
                adapter.notifyDataSetChanged();
            }
        });
</code>```

HomeViewModel.java

```<code>MutableLiveData<List<String>> getmQuestionsData() {
        repository.getPredictiousCol()
                //.whereEqualTo("exists","true")
//
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                        if (e != null) {
                            Log.d(TAG, "Question could not be retrieved " + e);
                            mQuestionsData = null;
                            return;
                        }
                        List<String> questionList = new ArrayList<>();
                        assert queryDocumentSnapshots != null;
                        for (QueryDocumentSnapshot doc : queryDocumentSnapshots) {
                            if (doc.get("question") != null) {
                                questionList.add((String) doc.get("question"));
                            }
                        }
                        mQuestionsData.postValue(questionList);
                        Log.d(TAG, "Data was added to the LiveData List." + questionList);
                    }
                });
        return mQuestionsData;
    }
</code>```

Comment down below if you want more of my code or any other related queries.

THANK YOU!

答:
I think your error is here:

```<code>@Override
    public void onBindViewHolder(@NonNull HomeAdapter.ViewHolder holder, final int position) {
         if (mQuestions.isEmpty()) {
              String question = mQuestions.get(position);
              holder.question.setText(question);
          }
}
</code>```

You're in essence saying if you have nothing in your list then set the questions to your list.... It should say:

```<code>@Override
    public void onBindViewHolder(@NonNull HomeAdapter.ViewHolder holder, final int position) {
         if (!mQuestions.isEmpty()) {
              String question = mQuestions.get(position);
              holder.question.setText(question);
          }
}
</code>```

note the ! before mQuestions.isEmpty() meaning if the mQuestion is not empty...

ContentLicense: CC BY-SA 4.0

Body:
I have a RecyclerView.Adapter in my code which is used to set elements in my layout file, but due to an UNKNOWN error, I am not able to display those elements. I am able to retrieve the data from Firebase, able to reach the onBindViewHolder but, there are no end results.

Logcat

D/HomeViewModel: Data was added to the LiveData List.[secondQuestion, question]
D/HomeAdapter: onCreateViewHolder
    onBindViewHolder

HomeAdapter.java

@Override
    public void onBindViewHolder(@NonNull HomeAdapter.ViewHolder holder, final int position) {
         if (mQuestions.isEmpty()) {
              String question = mQuestions.get(position);
              holder.question.setText(question);
          }
}

HomeFragment.java

homeViewModel.getmQuestionsData().observe(getViewLifecycleOwner(), new Observer<List<String>>() {
            @Override
            public void onChanged(List<String> mQuestionList) {
                mQuestion.addAll(mQuestionList);

                // TODO: The FUCKING Bug is around here
                adapter.notifyDataSetChanged();
            }
        });

HomeViewModel.java

MutableLiveData<List<String>> getmQuestionsData() {
        repository.getPredictiousCol()
                //.whereEqualTo("exists","true")
//
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                        if (e != null) {
                            Log.d(TAG, "Question could not be retrieved " + e);
                            mQuestionsData = null;
                            return;
                        }
                        List<String> questionList = new ArrayList<>();
                        assert queryDocumentSnapshots != null;
                        for (QueryDocumentSnapshot doc : queryDocumentSnapshots) {
                            if (doc.get("question") != null) {
                                questionList.add((String) doc.get("question"));
                            }
                        }
                        mQuestionsData.postValue(questionList);
                        Log.d(TAG, "Data was added to the LiveData List." + questionList);
                    }
                });
        return mQuestionsData;
    }

Comment down below if you want more of my code or any other related queries.

THANK YOU!

Body:
I think your error is here:

@Override
    public void onBindViewHolder(@NonNull HomeAdapter.ViewHolder holder, final int position) {
         if (mQuestions.isEmpty()) {
              String question = mQuestions.get(position);
              holder.question.setText(question);
          }
}

You're in essence saying if you have nothing in your list then set the questions to your list.... It should say:

@Override
    public void onBindViewHolder(@NonNull HomeAdapter.ViewHolder holder, final int position) {
         if (!mQuestions.isEmpty()) {
              String question = mQuestions.get(position);
              holder.question.setText(question);
          }
}

note the ! before mQuestions.isEmpty() meaning if the mQuestion is not empty...


问:
XCode 4 / iOS 4.3 Build Errors on ASI HTTP Library
My development machine died and I've had to rebuild it from scratch.  I reinstalled the latest XCode which came with iOS SDK 4.3.  I reopened my project and have had to readd all my frameworks to get the code to mostly compile.  I'm down to two errors, both basically this:

error: expected specifier-qualifier-list before 'UIBackgroundTaskIdentifier'

This is on the file: ASIHTTPRequest.h on these lines:

```<code>#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
BOOL shouldContinueWhenAppEntersBackground;
UIBackgroundTaskIdentifier backgroundTask;
#endif
</code>```

which is part of the ASI HTTP library.

I'm targeting iOS 3.2.2 and building on the latest iOS 4.3.  This did not happen in my old environment which was XCode 4 using iOS 4.2.   I have tried using a bunch of different build settings but none have fixed the issue.  Commenting out the lines causes a number of other issues, and that is not a good solution anyways.  Any ideas?

Thanks in advance!

答:
OK, my "fix" for this problem was to create a new project in the new XCode version and copy my classes and resources over. It took about a half an hour to do so as I had about 100 files to move, but it worked on the first attempt.

I can only guess that there was some subtle difference between XCode versions I wasn't aware of.  XCode certainly didn't provide any kind of meaningful error message to guide me to it in any event.

ContentLicense: CC BY-SA 3.0

Body:
My development machine died and I've had to rebuild it from scratch.  I reinstalled the latest XCode which came with iOS SDK 4.3.  I reopened my project and have had to readd all my frameworks to get the code to mostly compile.  I'm down to two errors, both basically this:

error: expected specifier-qualifier-list before 'UIBackgroundTaskIdentifier'

This is on the file: ASIHTTPRequest.h on these lines:

#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
BOOL shouldContinueWhenAppEntersBackground;
UIBackgroundTaskIdentifier backgroundTask;
#endif

which is part of the ASI HTTP library.

I'm targeting iOS 3.2.2 and building on the latest iOS 4.3.  This did not happen in my old environment which was XCode 4 using iOS 4.2.   I have tried using a bunch of different build settings but none have fixed the issue.  Commenting out the lines causes a number of other issues, and that is not a good solution anyways.  Any ideas?

Thanks in advance!


问:
How can i convert a string to a list?
I have a string such as thislist = "[3, 2, 1]" or "[1]"

I need to convert it to a list with float (or int) elements, but i don't know how to do it?

What i tried is this:

```<code>thislist = list(thislist)
</code>```

But, when i try this solution, it gives me:

```<code> ['[', '3', ',', ' ', '2', ',', ' ', '1', ']']
</code>```

which is not what i need. Of course, i can do some more process to obtain my favorite result which is
[3,2,1]. But, i am looking for the most efficient approach!

答:
```<code>import json
thislist = "[3, 2, 1]"
goodList = json.loads(thislist) # this will give you [3, 2, 1]
</code>```

Title: How can i convert a string to a list?

Body:
I have a string such as thislist = "[3, 2, 1]" or "[1]"

I need to convert it to a list with float (or int) elements, but i don't know how to do it?

What i tried is this:

thislist = list(thislist)

But, when i try this solution, it gives me:

 ['[', '3', ',', ' ', '2', ',', ' ', '1', ']']

which is not what i need. Of course, i can do some more process to obtain my favorite result which is
[3,2,1]. But, i am looking for the most efficient approach!


问:
Gulp autoprefixer is not prefixing
I am not sure why but Autoprefixer is not adding any prefixes to the compiled CSS. Does anyone know?

Here is my gulpfile.js

```<code>const gulp = require('gulp');
const autoprefixer = require('gulp-autoprefixer');

exports.default = () => (
    gulp.src('css/styles.css')
        .pipe(autoprefixer({
            cascade: false
        }))
        .pipe(gulp.dest('dist'))
);
</code>```

gulp- v
CLI version: 2.2.1
Local version: 4.0.2

Thanks!

答:
It does!

```<code>input::placeholder { color: red; }
</code>```

results in

```<code>input::-moz-placeholder {
        color: red;
}
input:-ms-input-placeholder {
        color: red;
}
input::-ms-input-placeholder {
        color: red;
}
input::placeholder {
        color: red;
}
</code>```

You've probably used css rules that don't need prefixes with your current configuration. Check browserslist for custom prefixing rules

Title: Gulp autoprefixer is not prefixing

Body:
I am not sure why but Autoprefixer is not adding any prefixes to the compiled CSS. Does anyone know?

Here is my gulpfile.js

const gulp = require('gulp');
const autoprefixer = require('gulp-autoprefixer');

exports.default = () => (
    gulp.src('css/styles.css')
        .pipe(autoprefixer({
            cascade: false
        }))
        .pipe(gulp.dest('dist'))
);

gulp- v
CLI version: 2.2.1
Local version: 4.0.2

Thanks!

Body:
It does!

input::placeholder { color: red; }

results in

input::-moz-placeholder {
        color: red;
}
input:-ms-input-placeholder {
        color: red;
}
input::-ms-input-placeholder {
        color: red;
}
input::placeholder {
        color: red;
}

You've probably used css rules that don't need prefixes with your current configuration. Check browserslist for custom prefixing rules


问:
How to share data between fragments and activities in android
I am new to android.

Can anyone please tell me if it is possible to share data between activities and fragments using java interfaces. I have studied OOP but I am still stuck in interfaces and abstracts classes. I think if I implement a class on many activities, I will be able to share data like passing data from one activity and getting it from another.

Am I right about it? Please help me

答:
use intents and them use the putExtra() and getExtra() to pass and recieve information, alternatively you can pass them as NavArgs() when using the jetpack navigation library.

intents in java

navigation


问:
JBoss Wildfly 9.0 ArrayIndexOutOfBoundException [asm 3.1]
While deploying war in JBoss getting below exception: Using asm3.1 jar

I've verified this on google. But I didn't get much info. It said that check asm jar dependency with java8 version and I've tried updating asm latest builds also after updating latest builds (asm 5.0.3 or later) I got another error as incompatibleclasschangeerror

```<code>    java.lang.ArrayIndexOutOfBoundsException: 9578
        at   org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:85)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
        at org.jboss.threads.JBossThread.run(JBossThread.java:320) Caused by: java.lang.ArrayIndexOutOfBoundsException: 9578
        at org.objectweb.asm.ClassReader.readClass(Unknown Source)
        at org.objectweb.asm.ClassReader.accept(Unknown Source)
        at org.objectweb.asm.ClassReader.accept(Unknown Source)
        at com.sun.jersey.spi.scanning.AnnotationScannerListener.onProcess(AnnotationScannerListener.java:133)
        at com.sun.jersey.core.spi.scanning.JarFileScanner.scan(JarFileScanner.java:97)
        at com.sun.jersey.spi.scanning.WebAppResourcesScanner$1.f(WebAppResourcesScanner.java:94)
</code>```

答: I've removed the lambda dependency from my application and verified it. It is working fine. (asm 3.1, JBoss wildfly 9.0, Java 1.8).</p>

Body:
While deploying war in JBoss getting below exception: Using asm3.1 jar

I've verified this on google. But I didn't get much info. It said that check asm jar dependency with java8 version and I've tried updating asm latest builds also after updating latest builds (asm 5.0.3 or later) I got another error as incompatibleclasschangeerror

    java.lang.ArrayIndexOutOfBoundsException: 9578
        at   org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:85)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
        at org.jboss.threads.JBossThread.run(JBossThread.java:320) Caused by: java.lang.ArrayIndexOutOfBoundsException: 9578
        at org.objectweb.asm.ClassReader.readClass(Unknown Source)
        at org.objectweb.asm.ClassReader.accept(Unknown Source)
        at org.objectweb.asm.ClassReader.accept(Unknown Source)
        at com.sun.jersey.spi.scanning.AnnotationScannerListener.onProcess(AnnotationScannerListener.java:133)
        at com.sun.jersey.core.spi.scanning.JarFileScanner.scan(JarFileScanner.java:97)
        at com.sun.jersey.spi.scanning.WebAppResourcesScanner$1.f(WebAppResourcesScanner.java:94)


问:
Set a global variable in an arrow function node
I want to get the message before the current message as a variable.
Here is my code:

```<code>message.channel.messages.fetch({ limit: 2 }).then(messages => {
          prevMsg = messages.last()
      }).catch(err => {
          console.error(err)
      })
        console.log("prevMsg is " + prevMsg)
</code>```

But I get a ReferenceError: prevMsg is not defined at the line where my console.log is.
My question is how can I set the variable in that arrow function so that the variable is accessible elsewhere or if there is a better way of doing this?

答:
The function call you have there is asynchronous that is why it is undefined...

```<code>const prevMsg;

message.channel.messages.fetch({ limit: 2 })
  .then(messages => {
      prevMsg = messages.last()
  }).catch(err => {
      console.error(err)
  });

// the call above runs asynchronously that is why loggin here comes out undefined
// it has not been assigned yet...
console.log(prevMsg);
</code>```

You need to implement a way to wait for the call to finish, you cant use a global await but you can wrap this in a function that is asynchronous also...

```<code>async function myfunction() {

  const prevMsg = await message.channel.messages.fetch({ limit: 2 })
    .then(messages => messages.last())
    .catch(err => {
      console.error(err)
    });

  // this should work
  console.log(prevMsg);

}

</code>```

Body:
I want to get the message before the current message as a variable.
Here is my code:

message.channel.messages.fetch({ limit: 2 }).then(messages => {
          prevMsg = messages.last()
      }).catch(err => {
          console.error(err)
      })
        console.log("prevMsg is " + prevMsg)

But I get a ReferenceError: prevMsg is not defined at the line where my console.log is.
My question is how can I set the variable in that arrow function so that the variable is accessible elsewhere or if there is a better way of doing this?

Body:
The function call you have there is asynchronous that is why it is undefined...

const prevMsg;

message.channel.messages.fetch({ limit: 2 })
  .then(messages => {
      prevMsg = messages.last()
  }).catch(err => {
      console.error(err)
  });

// the call above runs asynchronously that is why loggin here comes out undefined
// it has not been assigned yet...
console.log(prevMsg);

You need to implement a way to wait for the call to finish, you cant use a global await but you can wrap this in a function that is asynchronous also...

async function myfunction() {

  const prevMsg = await message.channel.messages.fetch({ limit: 2 })
    .then(messages => messages.last())
    .catch(err => {
      console.error(err)
    });

  // this should work
  console.log(prevMsg);

}


问:
Computing the gradient orientations using only the gradient magnitudes image
How can I compute the gradient orientations image using the gradient magnitudes image — is there a technique to inverse the convolutional step of the input image with a Sobel filter to compute the two gradients directions images (Ix and Iy)?</p>

答:
This problem corresponds to a so-called Eikonal differential equation, which can be solved numerically: https://en.wikipedia.org/wiki/Eikonal_equation#2D_approximation_on_a_Cartesian_grid.

Don't do that.


问:
Why or when to use Laravel resources/collections
I do not understand why or when to use the resources in Laravel https://laravel.com/docs/7.x/eloquent-resources .

See this controller :

```<code>public function show(School $school)
{
    // return response()->json($school, 200);
    return new SchoolResource($school);
}
</code>```

The both return solutions returned this kind of response :

```<code>    {
    "data": {
        "id": "4f390a7b-3c3f-4c23-9e6a-dd4429cf835d",
        "name": "school name",
.......,
</code>```

The data are the results of a query automatically injected (here : $school).

And same question for a collection of resources. Imagine this controller :

```<code>public function index(Request $request)
{
    try {
        $schools = $this->schoolRepository->all($request->all());
    } catch (\Exception $e) {
        return response()->json(['message' => 'Bad request'], 400);
    }

    return SchoolResource::collection($schools);
    // return response()->json($schools, 200);
}
</code>```

If I need to add some fields , I can do that either in the model or in the repository.

I often read that this resource notion is important to understand and to use. But for the moment  I do not see when or why I should use it. I certainly must not understand something!

答:
There are a couple of primary reasons to use resources to manage your return values even if your resources don't do anything than pass data through today, you may want it to do something different in the future.

A small list of reasons why resources are really useful

1. Data manipulation, specific to clients (i.e. js applications consuming your api)

If you start manipulating data in your models using mutators (getters / setters). Your internal application now has to work with these constraints. Many times its easier to work with the raw data internally and then just allow your resources to manipulate the data for the client.

2. Conforming to an API specification, such as JSON API v1.0

Whilst you will likely need logic in your application to handle schemas like this, your models and controllers should not. The resource has a critical role here to organise the data for your consumer applications in a compliant fashion.

3. The age old mantra, separation of concerns

This goes hand in hand with point 1, it is not a model or a controllers responsibility to map data to what you expect your consumer applications to receive.

Building on your example

You currently have the following in the show route of your resource controller.

```<code>public function show(School $school)
{
    // return response()->json($school, 200);
    return new SchoolResource($school);
}
</code>```

This need not change, even if your API specification does (reason 1 and 3).

Adding fields, yes, you'll need to add them to your model but lets use this to actually do something meaningful with your resource.

We've created a migration for a new JSON field ratings. Ratings has a data structure like this:

```<code>[
    {
        name: string,
        value: float,
    }
]
</code>```

For reasons such as media scrutiny, we never want to expose all the rating data to our publically available front end consumer apps. Instead we want to provide an average score of all ratings.

Now we could do this in the model, but is it the models responsibility to do this? Not really, the model should be handling and dealing in raw / discreetly modified data only. So is it the controllers responsibility? No, the controller coordinates what should be done and is not interested in specific details or the data.

So where do we do this? Enter your resource that was handily already set up.

```<code>class School extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'rating' => $this->getRating(),
        ];
    }

    /**
     * Mean rating rounded to one decimal place
     * @return float
     */
    protected function getRating()
    {
        return (round(array_reduce($this->ratings, function($acc, $curr) {
            $acc += $curr['value'];
            return $acc;
        }, 0) / count($this->ratings), 1);
    }
}
</code>```

The resource is where we have manipulated data specifically for our responses and left our internal data modelling un-touched and clean without pollution from specific nuances of our consuming applications.

More importantly, if you just returned return response()->json($school, 200); from your controller, your data structures will not match and you would be exposing some sensitive data to your front end applications.

Additional (24/12/21)

It's worth noting that if, for example, the data that you are manipulating is required by many different views / resources then we have a number of options.

Traits, create a trait that adds the getRating method. Downside, every class that needs this must import and declare the trait. Upside, your code is dry.

Model scopes, add a scope to your model that does the data processing via SQL (or your DB QL of choice). Downside, slight pollution of the model. Upside, super quick.

Append the data to the model (https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json) using an accessor that runs the getRating code to set the data on the model. Upside, clean and usable throughout the application. Downsides pollutes the model a little and data only available in the JSON representation of the model.

Decorate the resource. This allows you to intercept and modify/add to the result of the toArray method in the decorated resource. Upsides not many. Downsides, obfuscated and confusing implementation detail. I wouldn't recommend this approach.

Helper function. Rather than have the method on the resource, create a helper that takes the ratings array and returns the result. Upside, simple implementation. Downsides, none that I can thing of.

So after thinking about this alot I think that I would likely do what I originally wrote in this answer. If I need to re-use I would likely create a helper. If I was concerned about performance I would use a model scope to do the calculations in SQL (if possible, remember it's a JSON field). Taking a step further, if many models require this logic, a trait for those models would be my next step (this only applies if you go down the SQL calculation route).

Body:
I do not understand why or when to use the resources in Laravel https://laravel.com/docs/7.x/eloquent-resources .

See this controller :

public function show(School $school)
{
    // return response()->json($school, 200);
    return new SchoolResource($school);
}

The both return solutions returned this kind of response :

    {
    "data": {
        "id": "4f390a7b-3c3f-4c23-9e6a-dd4429cf835d",
        "name": "school name",
.......,

The data are the results of a query automatically injected (here : $school).

And same question for a collection of resources. Imagine this controller :

public function index(Request $request)
{
    try {
        $schools = $this->schoolRepository->all($request->all());
    } catch (\Exception $e) {
        return response()->json(['message' => 'Bad request'], 400);
    }

    return SchoolResource::collection($schools);
    // return response()->json($schools, 200);
}

If I need to add some fields , I can do that either in the model or in the repository.

I often read that this resource notion is important to understand and to use. But for the moment  I do not see when or why I should use it. I certainly must not understand something!

Body:
There are a couple of primary reasons to use resources to manage your return values even if your resources don't do anything than pass data through today, you may want it to do something different in the future.

A small list of reasons why resources are really useful

1. Data manipulation, specific to clients (i.e. js applications consuming your api)

If you start manipulating data in your models using mutators (getters / setters). Your internal application now has to work with these constraints. Many times its easier to work with the raw data internally and then just allow your resources to manipulate the data for the client.

2. Conforming to an API specification, such as JSON API v1.0

Whilst you will likely need logic in your application to handle schemas like this, your models and controllers should not. The resource has a critical role here to organise the data for your consumer applications in a compliant fashion.

3. The age old mantra, separation of concerns

This goes hand in hand with point 1, it is not a model or a controllers responsibility to map data to what you expect your consumer applications to receive.

Building on your example

You currently have the following in the show route of your resource controller.

public function show(School $school)
{
    // return response()->json($school, 200);
    return new SchoolResource($school);
}

This need not change, even if your API specification does (reason 1 and 3).

Adding fields, yes, you'll need to add them to your model but lets use this to actually do something meaningful with your resource.

We've created a migration for a new JSON field ratings. Ratings has a data structure like this:

[
    {
        name: string,
        value: float,
    }
]

For reasons such as media scrutiny, we never want to expose all the rating data to our publically available front end consumer apps. Instead we want to provide an average score of all ratings.

Now we could do this in the model, but is it the models responsibility to do this? Not really, the model should be handling and dealing in raw / discreetly modified data only. So is it the controllers responsibility? No, the controller coordinates what should be done and is not interested in specific details or the data.

So where do we do this? Enter your resource that was handily already set up.

class School extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'rating' => $this->getRating(),
        ];
    }

    /**
     * Mean rating rounded to one decimal place
     * @return float
     */
    protected function getRating()
    {
        return (round(array_reduce($this->ratings, function($acc, $curr) {
            $acc += $curr['value'];
            return $acc;
        }, 0) / count($this->ratings), 1);
    }
}

The resource is where we have manipulated data specifically for our responses and left our internal data modelling un-touched and clean without pollution from specific nuances of our consuming applications.

More importantly, if you just returned return response()->json($school, 200); from your controller, your data structures will not match and you would be exposing some sensitive data to your front end applications.

Additional (24/12/21)

It's worth noting that if, for example, the data that you are manipulating is required by many different views / resources then we have a number of options.

Traits, create a trait that adds the getRating method. Downside, every class that needs this must import and declare the trait. Upside, your code is dry.

Model scopes, add a scope to your model that does the data processing via SQL (or your DB QL of choice). Downside, slight pollution of the model. Upside, super quick.

Append the data to the model (https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json) using an accessor that runs the getRating code to set the data on the model. Upside, clean and usable throughout the application. Downsides pollutes the model a little and data only available in the JSON representation of the model.

Decorate the resource. This allows you to intercept and modify/add to the result of the toArray method in the decorated resource. Upsides not many. Downsides, obfuscated and confusing implementation detail. I wouldn't recommend this approach.

Helper function. Rather than have the method on the resource, create a helper that takes the ratings array and returns the result. Upside, simple implementation. Downsides, none that I can thing of.

So after thinking about this alot I think that I would likely do what I originally wrote in this answer. If I need to re-use I would likely create a helper. If I was concerned about performance I would use a model scope to do the calculations in SQL (if possible, remember it's a JSON field). Taking a step further, if many models require this logic, a trait for those models would be my next step (this only applies if you go down the SQL calculation route).


问:
Electron issue after updating electron and typescript
I have a small electron project which I've just updated (Electron, typescript etc)...

This is the code that's breaking:

```<code>dialog.showOpenDialog({}, (files) => {
    if(files && files.length > 0) {
      fs.readFile(files[0], 'utf8', (err, res) => {
        if (!err) {
          editor.setModel(monaco.editor.createModel(res, 'javascript'));
        }
      })
    }
  })
</code>```

It doesn't like the {} after dialog.showOpenDialog(

The error I'm getting is:

```<code>Argument of type '{}' is not assignable to parameter of type 'BrowserWindow'.
</code>```

How can I fix this?

答:
The showOpenDialog is used differently, probably you updated from a quite old electron version and they changed it. Now it takes an optional browserWindow and an options object and returns a promise (shown with the async/await syntax):

```<code>  const {canceled, files, bookmarks} = await dialog.showOpenDialog({});
</code>```

Reference: https://www.electronjs.org/docs/api/dialog#dialogshowopendialogbrowserwindow-options

Body:
I have a small electron project which I've just updated (Electron, typescript etc)...

This is the code that's breaking:

dialog.showOpenDialog({}, (files) => {
    if(files && files.length > 0) {
      fs.readFile(files[0], 'utf8', (err, res) => {
        if (!err) {
          editor.setModel(monaco.editor.createModel(res, 'javascript'));
        }
      })
    }
  })

It doesn't like the {} after dialog.showOpenDialog(

The error I'm getting is:

Argument of type '{}' is not assignable to parameter of type 'BrowserWindow'.

How can I fix this?

Body:
The showOpenDialog is used differently, probably you updated from a quite old electron version and they changed it. Now it takes an optional browserWindow and an options object and returns a promise (shown with the async/await syntax):

  const {canceled, files, bookmarks} = await dialog.showOpenDialog({});

Reference: https://www.electronjs.org/docs/api/dialog#dialogshowopendialogbrowserwindow-options


问:
generate resource URL within controller endpoint
I want to minimize my API response bodies by replacing information about subresource with a resource URL. So let's say you would fetch a vendor and don't want to list all the products he is selling but you want to provide a URL that leads to those information.

For example I tried this in my controller endpoint

```<code>string resourceUrl = Url.Link(nameof(GetVendorById), new { id = 1 });
</code>```

and was expecting to get the following string

```<code>https://localhost:5001/vendors/1
</code>```

Unfortunately the string returns null. So how do you generate such resource urls?

The following dummy code is just an example of what I want to achieve, I know I shouldn't return the vendor products when fetching a vendor.

```<code>[HttpGet("{id:int}")]
public async Task<ActionResult<VendorResponseModel>> GetVendorById([FromRoute] int id)
{
    VendorResponseModel vendor = new VendorResponseModel()
    {
        Id = id,
        Name = "Vendor " + id,
        Products = new List<VendorProductResponseModel>()
        {
            new VendorProductResponseModel()
            {
                Id = 1,
                ResourceUrl = Url.Link(nameof(ProductsController.GetProductById), new { id = 1 })
            }
        }
    };

    return Ok(vendor);
}
</code>```

答:
```<code>//Generates a relative URL to your current request
//E.g you are on a page in a folder named vendors that contains index.cshtml,
//create.cshtml, details.cshtml And the current request is on create.cshtml,
// the preceding code will generate a URL relative to your current url
//{"baseurl/vendors/details/556"}
var resourceUrl = Url.Page("/details", pageHandler:null,
        values: new { productId = 123, otherId = 556 }, protocol: Request.Scheme);

//Used normally for MVC controllers
Url.Action("yourAction", "yourController", new { myId =455}, Request.Scheme);

//Gets the URL of the current request
Url.ActionContext()

//Generates a URL with your base URL appended to it
Url.Content("~/tyuu/you/557")

//Generates an absolute URL
Url.Link("routeName", new { myId = 456 }

//Then you can encode it this way
var encoded = HtmlEncoder.Default.Encode(resourceUrl)
</code>```

Will give you the URL with all the parameters you want insides of it.

Edit

If you think the problem is the package itself, clean solution, remove all packages and dotnet restore

Body:
I want to minimize my API response bodies by replacing information about subresource with a resource URL. So let's say you would fetch a vendor and don't want to list all the products he is selling but you want to provide a URL that leads to those information.

For example I tried this in my controller endpoint

string resourceUrl = Url.Link(nameof(GetVendorById), new { id = 1 });

and was expecting to get the following string

https://localhost:5001/vendors/1

Unfortunately the string returns null. So how do you generate such resource urls?

The following dummy code is just an example of what I want to achieve, I know I shouldn't return the vendor products when fetching a vendor.

[HttpGet("{id:int}")]
public async Task<ActionResult<VendorResponseModel>> GetVendorById([FromRoute] int id)
{
    VendorResponseModel vendor = new VendorResponseModel()
    {
        Id = id,
        Name = "Vendor " + id,
        Products = new List<VendorProductResponseModel>()
        {
            new VendorProductResponseModel()
            {
                Id = 1,
                ResourceUrl = Url.Link(nameof(ProductsController.GetProductById), new { id = 1 })
            }
        }
    };

    return Ok(vendor);
}

Body:
//Generates a relative URL to your current request
//E.g you are on a page in a folder named vendors that contains index.cshtml,
//create.cshtml, details.cshtml And the current request is on create.cshtml,
// the preceding code will generate a URL relative to your current url
//{"baseurl/vendors/details/556"}
var resourceUrl = Url.Page("/details", pageHandler:null,
        values: new { productId = 123, otherId = 556 }, protocol: Request.Scheme);

//Used normally for MVC controllers
Url.Action("yourAction", "yourController", new { myId =455}, Request.Scheme);

//Gets the URL of the current request
Url.ActionContext()

//Generates a URL with your base URL appended to it
Url.Content("~/tyuu/you/557")

//Generates an absolute URL
Url.Link("routeName", new { myId = 456 }

//Then you can encode it this way
var encoded = HtmlEncoder.Default.Encode(resourceUrl)

Will give you the URL with all the parameters you want insides of it.

Edit

If you think the problem is the package itself, clean solution, remove all packages and dotnet restore


问:
How can I get the name of the team instead of its ID
I have 2 tables

teams

TeamID as PK, int

TeamName

matches (bridge table)

MatchID as PK, int

TeamID_1 as PK, FK, int

TeamID_2 as PK, FK, int

MatchWinner

How could I manage to get TeamName instead of TeamID in the final table?

Already tried using, inner and outer joins etc.

Here is my query:

```<code>SELECT CONCAT(m.MatchID, m.TeamID_1, m.TeamID_2) AS MatchID, m.TeamID_1 AS 'Team 1', m.TeamID_2 AS 'Team 2', m.MatchWinner AS 'Winner'
    FROM teams t
    JOIN matches m
    ON t.TeamID IN (m.TeamID_1, m.TeamID_2)
    WHERE t.TeamName = 'Fnatic';
</code>```

The final table should look like

MatchID - Team 1 - Team 2 - Winner

18582 - Fnatic - Astralis - Fnatic

答:
You must join matches with 2 copies of teams:

```<code>select m.matchid, t1.teamname team1, t2.teamname team2, m.Winner
from matches m
inner join teams t1 on t1.teamid = m.teamid_1
inner join teams t2 on t2.teamid = m.teamid_2
where 'Fnatic' in (t1.teamname, t2.teamname)
</code>```

Body:
I have 2 tables

teams

TeamID as PK, int

TeamName

matches (bridge table)

MatchID as PK, int

TeamID_1 as PK, FK, int

TeamID_2 as PK, FK, int

MatchWinner

How could I manage to get TeamName instead of TeamID in the final table?

Already tried using, inner and outer joins etc.

Here is my query:

SELECT CONCAT(m.MatchID, m.TeamID_1, m.TeamID_2) AS MatchID, m.TeamID_1 AS 'Team 1', m.TeamID_2 AS 'Team 2', m.MatchWinner AS 'Winner'
    FROM teams t
    JOIN matches m
    ON t.TeamID IN (m.TeamID_1, m.TeamID_2)
    WHERE t.TeamName = 'Fnatic';

The final table should look like

MatchID - Team 1 - Team 2 - Winner

18582 - Fnatic - Astralis - Fnatic

Body:
You must join matches with 2 copies of teams:

select m.matchid, t1.teamname team1, t2.teamname team2, m.Winner
from matches m
inner join teams t1 on t1.teamid = m.teamid_1
inner join teams t2 on t2.teamid = m.teamid_2
where 'Fnatic' in (t1.teamname, t2.teamname)


问:
Hosting an .apk file on over own site
I got requirement to host my .apk file on one public site other than android market or any other app stores. In android market, after registred in to the market the downloded .apk will automatically installed on mobile without any manual action. So I am willing to create one URL and host my .apk file in to that and want to download that .apk in to the android mobile and it has to install automatically.

How can I do that....plz share if any code or links are there regrading this.

答:
If Android device has Settings->Applications->Unknown Sources checked, Android will allow .apk installation. If its not checked - you will not succeed.

Assuming that check bar is checked and you have downloaded .apk file. You can run next code to trigger installation:

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(apkFileName));
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);
</code>```

Title: Hosting an .apk file on over own site

Body:
If Android device has Settings->Applications->Unknown Sources checked, Android will allow .apk installation. If its not checked - you will not succeed.

Assuming that check bar is checked and you have downloaded .apk file. You can run next code to trigger installation:

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(apkFileName));
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);


问:
pl/sql function to find those customers who are eligible for LOAN and the amount of loan
Note:
the question has 2 table: customer(id,name,dept,designation,salary) and account(id,ACCOUNT_NUMBER,FIXED
DEPOSIT) .
i wrote the pl/sql function for that:

```<code>CREATE OR REPLACE FUNCTION loan_func (sal IN NUMBER,fd in NUMBER)
RETURN NUMBER
IS
loan NUMBER(6);
BEGIN
IF (sal>60000 AND fd>100000) THEN
loan := (sal*0.4)+100000;
ELSIF (sal>50000 AND sal<59999 AND fd>50000) THEN
loan := (sal*0.3)+90000;
END IF;
RETURN loan;
END;
</code>```

the function  in entered correctly but the cursor doesnot work! can you help me fix the problem to get the ans?

below is the cursor:

```<code>DECLARE
CURSOR CR IS
SELECT
    C_ID,
    A_ID,
    NAME,
    FIXED_DEPOSIT,
    SALARY
FROM
    CUSTOMER
join ACCOUNT
on     C_ID = A_ID;
I CUSTOMER.C_ID%TYPE;
N CUSTOMER.NAME%TYPE;
fd ACCOUNT.FIXED_DEPOSIT%TYPE;
sal CUSTOMER.SALARY%TYPE;
Loan NUMBER(6);
BEGIN
OPEN CR;
LOOP
EXIT WHEN CR%NOTFOUND;
FETCH CR INTO I,N,fd,sal;
DBMS_OUTPUT.PUTLINE(I || N);
Loan:=loan_func(sal,fd);
DBMS_OUTPUT.PUTLINE(loan);
END LOOP;
END;
</code>```

it shows the following error:

ORA-06550: line 22, column 2:
PLS-00394: wrong number of values in the INTO list of a FETCH statement

答:
```<code>DECLARE
CURSOR CR IS
SELECT
    ID,NAME,FIXED_DEPOSIT,SALARY
FROM
    CUSTOMER C,
    ACCOUNT A
WHERE
    C.ID=A.ID;  <============================ missing ';'

I C.ID%TYPE;
N C.NAME%TYPE;
fd A.FIXED_DEPOSIT%TYPE;
sal C.SALARY%TYPE;
Loan NUMBER(6);
BEGIN
    OPEN CR;
LOOP
EXIT WHEN CR%NOTFOUND
FETCH CR INTO I,N,fd,sal;
DBMS_OUTPUT.PUTLINE(‘ID = ||I||’ ‘NAME = ||N||’);
Loan:=loan_func(sal,fd);
DBMS_OUTPUT.PUTLINE(‘LOAN AMOUNT IS =’|| loan);
END LOOP
END;
</code>```

Body:
Note:
the question has 2 table: customer(id,name,dept,designation,salary) and account(id,ACCOUNT_NUMBER,FIXED
DEPOSIT) .
i wrote the pl/sql function for that:

CREATE OR REPLACE FUNCTION loan_func (sal IN NUMBER,fd in NUMBER)
RETURN NUMBER
IS
loan NUMBER(6);
BEGIN
IF (sal>60000 AND fd>100000) THEN
loan := (sal*0.4)+100000;
ELSIF (sal>50000 AND sal<59999 AND fd>50000) THEN
loan := (sal*0.3)+90000;
END IF;
RETURN loan;
END;

the function  in entered correctly but the cursor doesnot work! can you help me fix the problem to get the ans?

below is the cursor:

DECLARE
CURSOR CR IS
SELECT
    C_ID,
    A_ID,
    NAME,
    FIXED_DEPOSIT,
    SALARY
FROM
    CUSTOMER
join ACCOUNT
on     C_ID = A_ID;
I CUSTOMER.C_ID%TYPE;
N CUSTOMER.NAME%TYPE;
fd ACCOUNT.FIXED_DEPOSIT%TYPE;
sal CUSTOMER.SALARY%TYPE;
Loan NUMBER(6);
BEGIN
OPEN CR;
LOOP
EXIT WHEN CR%NOTFOUND;
FETCH CR INTO I,N,fd,sal;
DBMS_OUTPUT.PUTLINE(I || N);
Loan:=loan_func(sal,fd);
DBMS_OUTPUT.PUTLINE(loan);
END LOOP;
END;

it shows the following error:

ORA-06550: line 22, column 2:
PLS-00394: wrong number of values in the INTO list of a FETCH statement


问:
[Vue warn]: Unknown custom element: <router-view> - did you register the component correctly?
I use Vue 2 in CLI mode with webpack-simple. I have following files:

main.js:

import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';
import Routes from './routes';

Vue.use('VueRouter');

const router = new VueRouter({
  routes: Routes,
});

new Vue({
  el: '#app',
  render: h => h(App),
  router: router,
});
```
<p>App.vue:</p>
<pre class="lang-html prettyprint-override"><code><template>
  <div>
    <router-view></router-view>
  </div>
</template>

<script>
import Loader from './Loader.vue';

export default {
  name: 'app',
}
</script>

<style lang="scss">
</style>
</code>```

routes.js:

import Game from './components/Game.vue';
import Login from './components/Login.vue';

export default [
  { path: '/', component: Game, name: "Game" },
  { path: '/login', component: Login, name: "Login" },
]
```
<p>Game.vue and Login.vue looks the same:</p>
<pre class="lang-html prettyprint-override"><code><template>
  <div>
    Game
  </div>
</template>

<script>
export default {
  name: 'game',
}
</script>

<style lang="scss">
div {
  border: 1px solid red;
  width: 100px;
  height: 100px;
}
</style>
</code>```

unfortunately starting a file gives me an error:

[Vue warn]: Unknown custom element:  - did you register
the component correctly? For recursive components, make sure to
provide the "name" option.

Also router-view tag is not changed to proper html. I use vue router for the first time. It' been installed via npm in version 3.0.1

Any advice?

答:
I had a similar issue, running the commands below fixed it for me.</p>

```<code>npm install
npm install vue-router
npm run dev
</code>```

Body:
I use Vue 2 in CLI mode with webpack-simple. I have following files:

main.js:

import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';
import Routes from './routes';

Vue.use('VueRouter');

const router = new VueRouter({
  routes: Routes,
});

new Vue({
  el: '#app',
  render: h => h(App),
  router: router,
});

App.vue:

<template>

    <router-view></router-view>

</template>

routes.js:

import Game from './components/Game.vue';
import Login from './components/Login.vue';

export default [
  { path: '/', component: Game, name: "Game" },
  { path: '/login', component: Login, name: "Login" },
]

Game.vue and Login.vue looks the same:

<template>

    Game

</template>

unfortunately starting a file gives me an error:

[Vue warn]: Unknown custom element:  - did you register
the component correctly? For recursive components, make sure to
provide the "name" option.

Also router-view tag is not changed to proper html. I use vue router for the first time. It' been installed via npm in version 3.0.1

Any advice?

Body:
I had a similar issue, running the commands below fixed it for me.

npm install
npm install vue-router
npm run dev


问:
How to get the day of the week from the day number in JavaScript?
Given dayNumber is from 0 - 6 representing Monday - Sunday respectively.

Can the Date / String objects be used to get the day of the week from dayNumber?

答:
let weekday = ['Sunday',
               'Monday',
               'Tuesday',
               'Wednesday',
               'Thursday',
               'Friday',
               'Saturday'][new Date().getDay()];

console.log(weekday)```


问:
Call overloaded generic method from generic method
My question is: Why is AddData(string data) never called? When I call ds.Add("Some text") then the type of data parameter is known at compilation time thus the overloaded implementation of Add should call AddData(string) method (or this is what I was hoped for)

The output is

```<code>Ignore data of type System.String
Ignore data of type System.Double
</code>```

using System;

namespace GenericCall
{
    interface IDataStore
    {
        void Add<T>(T data);
    }

    class MyDataStore : IDataStore
    {
        public void Add<T>(T data)
        {
            AddData(data);
        }

        private void AddData<T>(T data)
        {
            Console.WriteLine($"Ignore data of type {data.GetType()}");
        }

        private void AddData(string data)
        {
            Console.WriteLine("Accept string data");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyDataStore ds = new MyDataStore();
            ds.Add("Some text");
            ds.Add(3.14);
        }
    }
}
```

答:
Overload resolution happens at compile time for your code.

At compile time, the compiler has no knowledge of what T actually is, so this call:

```<code>public void Add<T>(T data)
{
    AddData(data); <------
}
</code>```

can only be resolved to the generic AddData, according to the rules of overload resolution.

One way to make overload resolution happen at runtime is to make the public Add accept a dynamic parameter:

```<code>// you should change the interface declaration also!
public void Add(dynamic data)
{
    AddData(data);
}
</code>```

This will produce the output:

```<code>Accept string data
Ignore data of type System.Double
</code>```

Body:
My question is: Why is AddData(string data) never called? When I call ds.Add("Some text") then the type of data parameter is known at compilation time thus the overloaded implementation of Add should call AddData(string) method (or this is what I was hoped for)

The output is

Ignore data of type System.String
Ignore data of type System.Double

using System;

namespace GenericCall
{
    interface IDataStore
    {
        void Add<T>(T data);
    }

    class MyDataStore : IDataStore
    {
        public void Add<T>(T data)
        {
            AddData(data);
        }

        private void AddData<T>(T data)
        {
            Console.WriteLine($"Ignore data of type {data.GetType()}");
        }

        private void AddData(string data)
        {
            Console.WriteLine("Accept string data");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyDataStore ds = new MyDataStore();
            ds.Add("Some text");
            ds.Add(3.14);
        }
    }
}

Body:
Overload resolution happens at compile time for your code.

At compile time, the compiler has no knowledge of what T actually is, so this call:

public void Add<T>(T data)
{
    AddData(data); <------
}

can only be resolved to the generic AddData, according to the rules of overload resolution.

One way to make overload resolution happen at runtime is to make the public Add accept a dynamic parameter:

// you should change the interface declaration also!
public void Add(dynamic data)
{
    AddData(data);
}

This will produce the output:

Accept string data
Ignore data of type System.Double


问:
JDA Voice Activity Tracking
I want to track voice activity of my bot with JDA. I am using lavaplayer to stream audio to the voice channel, and I want bot to leave the channel after some time when it is inactive or there is no one except bot. I am new to the coding community and trying different things. Can you help me about this issue?</p>

答: You could check if there is anyone in the channel except the bot every time someone leaves the voice channel and start a timer or smth if this is the case.</p>

Title: JDA Voice Activity Tracking


问:
How to solve the problem of each CSV element calculation error?
I have a CSV file that must count and output the results.

The CSV file has millions of rows. The following is my CSV file screenshot.

The following is my code:

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
pd.set_option("display.max_rows",1000000000)
pd.set_option("display.max_columns",1000000000)
df = pd.read_csv("Ax_Seg_output_no_comma.csv")
cnted = df.groupby(['Content'],as_index=False)['Content'].agg({'cnt':'count'})
cnted.to_csv('01.csv',index=0)
</code>```

I used pandas to count it, but I got some problems.

It has not to count properly.

I need to get the result such as A,5 B,2 C,1......

However, I got some wrong results is A,5 B C,1

It has not counted some elements.

A part of the lines has not to count.

If I count only 25000 rows of the element, it can output the correct result.

The following is the wrong result:

And then, the normal result should be the following:

I doubt if it exceeds the pandas limit. I think it has no more errors.

Can anyone help me? Thanks

(It is the original CSV file: https://drive.google.com/file/d/18_Y3Wu8OFFpAzgRXRsNh8C_nyh8wPPEu/view?usp=sharing)

答:
Your code is fine, but the results are confusing as some of the items (the value of 'Content') is multi-line. That's why you're seeing things such as: </p>

```<code>a

b:2
</code>```

<p>The reason that some items contain multi-lines / newline characters is that you have quote signs in your CSV. To ignore them, read the csv as follows: </p>

```<code>import csv
df = pd.read_csv("Ax_Seg_output_no_comma.csv", quoting=csv.QUOTE_NONE)
</code>```

Body:
I have a CSV file that must count and output the results.

The CSV file has millions of rows. The following is my CSV file screenshot.

The following is my code:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
pd.set_option("display.max_rows",1000000000)
pd.set_option("display.max_columns",1000000000)
df = pd.read_csv("Ax_Seg_output_no_comma.csv")
cnted = df.groupby(['Content'],as_index=False)['Content'].agg({'cnt':'count'})
cnted.to_csv('01.csv',index=0)

I used pandas to count it, but I got some problems.

It has not to count properly.

I need to get the result such as A,5 B,2 C,1......

However, I got some wrong results is A,5 B C,1

It has not counted some elements.

A part of the lines has not to count.

If I count only 25000 rows of the element, it can output the correct result.

The following is the wrong result:

And then, the normal result should be the following:

I doubt if it exceeds the pandas limit. I think it has no more errors.

Can anyone help me? Thanks

(It is the original CSV file: https://drive.google.com/file/d/18_Y3Wu8OFFpAzgRXRsNh8C_nyh8wPPEu/view?usp=sharing)

Body:
Your code is fine, but the results are confusing as some of the items (the value of 'Content') is multi-line. That's why you're seeing things such as:

a

b:2

The reason that some items contain multi-lines / newline characters is that you have quote signs in your CSV. To ignore them, read the csv as follows:

import csv
df = pd.read_csv("Ax_Seg_output_no_comma.csv", quoting=csv.QUOTE_NONE)


问:
Reflection api - find subclass type
Hi I am trying to find out the subclass, form an superclass object.

```<code>if Class Super is the super class.
and Class Sub1 and Class Sub2 extends Class Super.(all classes are public)

Lets say I have a object of Super type as
Super superObject = new Sub1();
</code>```

now for the superObject, is it possible to find which subclass the superObject extends in Java?

Since "SuperClass will not be aware of any SubClasses it has", can you please tell me is my above question valid in the first place, or am I missing any basic concept?

Thanks in advance.

答:
The getClass() method will return the concrete type of the object at runtime, not the reference type.  So simply doing:

```<code>Super superObject = new Sub1();
Class<? extends Super> klass = superObject.getClass();
</code>```

Will give you Sub1.class  It's not clear from your question what you then want to do with it.  You can simply call getName() on it, check if some other reference you have is of the same type, etc etc.

Title: Reflection api - find subclass type

Body:
Hi I am trying to find out the subclass, form an superclass object.

if Class Super is the super class.
and Class Sub1 and Class Sub2 extends Class Super.(all classes are public)

Lets say I have a object of Super type as
Super superObject = new Sub1();

now for the superObject, is it possible to find which subclass the superObject extends in Java?

Since "SuperClass will not be aware of any SubClasses it has", can you please tell me is my above question valid in the first place, or am I missing any basic concept?

Thanks in advance.

Body:
The getClass() method will return the concrete type of the object at runtime, not the reference type.  So simply doing:

Super superObject = new Sub1();
Class<? extends Super> klass = superObject.getClass();

Will give you Sub1.class  It's not clear from your question what you then want to do with it.  You can simply call getName() on it, check if some other reference you have is of the same type, etc etc.


问:
Phalcon Component using a Custom View (Volt) - how to create Phalcon UI Widgets
On my website i have to write a number of custom UI components and stays independently to the Controllers and Models, to generate views (In common some people call them UI-widgets).

i.e Creating re-usable "site-search" widget.

Currently, my approach is, I create an extended Component under the "Phalcon\Mvc\User\Component"

```<code>use Phalcon\Mvc\User\Component as Component;
class SiteSearch extends Component
{
   function doSomething (){
     //how to call a custom view for this component?
   }
}
</code>```

However, I am confused about how we can integrate a view for this extended "Component"? Any idea or different approach we can use?

答:
You can use partials, and reuse it in places where needed.

https://docs.phalcon.io/4.0/en/views#partials

Body:
On my website i have to write a number of custom UI components and stays independently to the Controllers and Models, to generate views (In common some people call them UI-widgets).

i.e Creating re-usable "site-search" widget.

Currently, my approach is, I create an extended Component under the "Phalcon\Mvc\User\Component"

use Phalcon\Mvc\User\Component as Component;
class SiteSearch extends Component
{
   function doSomething (){
     //how to call a custom view for this component?
   }
}

However, I am confused about how we can integrate a view for this extended "Component"? Any idea or different approach we can use?


问:
np.linalg.norm does not work for CSR matrix
I have a 220,000 x 34 matrix represented as a Numpy CSR matrix.  When I try to take the row-wise norm of the matrix, I get an exception:

```<code>>>> np.linalg.norm(csr)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\IBM_ADMIN\AppData\Local\Programs\Python\Python37\lib\site-packa
ges\numpy\linalg\linalg.py", line 2450, in norm
    sqnorm = dot(x, x)
  File "C:\Users\IBM_ADMIN\AppData\Local\Programs\Python\Python37\lib\site-packa
ges\scipy\sparse\base.py", line 480, in __mul__
    raise ValueError('dimension mismatch')
ValueError: dimension mismatch
>>> csr
<3x2 sparse matrix of type '<class 'numpy.int32'>'
        with 6 stored elements in Compressed Sparse Row format>
</code>```

Is there a restriction on which Numpy methods/functions work with CSR matrixes?

In desperation, I tried to code around this by doing an element-wise multiplication of the matrix with itself and then summing along the rows, but I got an exception with that, too.

答:
Here's a function snorm that works on both;
snorm( sparsematrix, axis=1 ) gets you row norms --

```<code>import numpy as np
from scipy import sparse
from scipy.sparse import linalg as sslin

def snorm( A, ord=None, axis=None ):
    """ norm of either scipy sparse matrix or numpy dense ndarray
        ord=None: sqrt( sum Aij^2 ), Frobenius norm
        ord=np.inf: max |Aij|
        axis=None: all,  axis=0: columns,  axis=1: rows
    """
    if sparse.issparse( A ):
        return sslin.norm( A, ord=ord, axis=axis )
        # https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.norm.html
    else:
        return np.linalg.norm( A, ord=ord, axis=axis )

#...............................................................................
# test snorm --
for A in [np.array([[ 1, 2 ], [3, 4] ]),
        np.eye( 0 )]:
    print( "\nA: \n", A )
    S = sparse.csr_matrix( A )
    for axis in [None, 0, 1]:
        npnorm = snorm( A, axis=axis )
        sparsenorm = snorm( S, axis=axis )
        print( "snorm axis %s: %s  %s " % (axis, npnorm, sparsenorm ))
</code>```

Body:
I have a 220,000 x 34 matrix represented as a Numpy CSR matrix.  When I try to take the row-wise norm of the matrix, I get an exception:

>>> np.linalg.norm(csr)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\IBM_ADMIN\AppData\Local\Programs\Python\Python37\lib\site-packa
ges\numpy\linalg\linalg.py", line 2450, in norm
    sqnorm = dot(x, x)
  File "C:\Users\IBM_ADMIN\AppData\Local\Programs\Python\Python37\lib\site-packa
ges\scipy\sparse\base.py", line 480, in __mul__
    raise ValueError('dimension mismatch')
ValueError: dimension mismatch
>>> csr
<3x2 sparse matrix of type '<class 'numpy.int32'>'
        with 6 stored elements in Compressed Sparse Row format>

Is there a restriction on which Numpy methods/functions work with CSR matrixes?

In desperation, I tried to code around this by doing an element-wise multiplication of the matrix with itself and then summing along the rows, but I got an exception with that, too.

Body:
Here's a function snorm that works on both;
snorm( sparsematrix, axis=1 ) gets you row norms --

import numpy as np
from scipy import sparse
from scipy.sparse import linalg as sslin

def snorm( A, ord=None, axis=None ):
    """ norm of either scipy sparse matrix or numpy dense ndarray
        ord=None: sqrt( sum Aij^2 ), Frobenius norm
        ord=np.inf: max |Aij|
        axis=None: all,  axis=0: columns,  axis=1: rows
    """
    if sparse.issparse( A ):
        return sslin.norm( A, ord=ord, axis=axis )
        # https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.norm.html
    else:
        return np.linalg.norm( A, ord=ord, axis=axis )

#...............................................................................
# test snorm --
for A in [np.array([[ 1, 2 ], [3, 4] ]),
        np.eye( 0 )]:
    print( "\nA: \n", A )
    S = sparse.csr_matrix( A )
    for axis in [None, 0, 1]:
        npnorm = snorm( A, axis=axis )
        sparsenorm = snorm( S, axis=axis )
        print( "snorm axis %s: %s  %s " % (axis, npnorm, sparsenorm ))


问:
ListView list icon show
I have an android project which has an activity downloads file and I want the file showing in the listview as well as an icon to be shown according to the extension of that file or if file is mp3 then mp3 Cover Picture

Please Someone Help Me How To Do it:-

This is my download.java file

```<code>package com.musicwala.djaman;
import android.app.Activity;
import android.os.Bundle;
import java.util.ArrayList;
import android.os.Environment;
import java.io.File;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.Arrays;
import org.json.JSONArray;
import java.util.List;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.Color;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.view.animation.OvershootInterpolator;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import android.media.MediaPlayer;
import java.io.IOException;

public class download extends ListActivity
{
    ListView listView;
    private File file;
    private List<String> myList;
   // String [] items = {"Bitcoin", "Ethereum", "LiteCoin", "Dash", "Neo", "Nano", "Bitcoin Cash", "Verge", "Ripple", "Bitcoin Diamond", "Iconomi", "Stellar Lumens"};
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO: Implement this method
        //getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setTitle("Downloads");
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.GREEN));
        getActionBar().setSubtitle("MusicWala");
        super.onCreate(savedInstanceState);
        myList = new ArrayList<String>();

        String root_sd = Environment.getExternalStorageDirectory().toString();
        file = new File( root_sd + "/MusicWala" ) ;
        File list[] = file.listFiles();

        for( int i=0; i< list.length; i++)
        {
            myList.add( list[i].getName() );
        }

        setListAdapter(new ArrayAdapter<String>(this,
                                                android.R.layout.simple_list_item_1, myList ));

    }

    protected void onListItemClick(ListView l, View v, int position, long id)
    {
        super.onListItemClick(l, v, position, id);

        File temp_file = new File( file, myList.get( position ) );

        if( !temp_file.isFile())
        {
            file = new File( file, myList.get( position ));
            File list[] = file.listFiles();

            myList.clear();

            for( int i=0; i< list.length; i++)
            {
                myList.add( list[i].getName() );
            }
            Toast.makeText(getApplicationContext(), file.toString(), Toast.LENGTH_LONG).show();
            setListAdapter(new ArrayAdapter<String>(this,
                                                    android.R.layout.simple_list_item_1, myList ));

        }
        Toast.makeText(getApplicationContext(), temp_file.getPath(), Toast.LENGTH_LONG).show();
        /*String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
        */
        String path = temp_file.getPath();
        String name = temp_file.getName();

        Intent intent = new Intent(download.this, play_ui.class);
        intent.putExtra("file", name).putExtra("path",path);
          startActivity(intent);

    }}
</code>```

this is my download.xml of list view

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="21dp">

    </RelativeLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>
</code>```

my listview of download file

I Want

答:
First, You need to create a custom ListView Adapter, After that you can specify the icon easily using an If statement in your Adapter class

Check this link to know more how to do that ..

Create a custom ListView Adapter

Title: ListView list icon show

Body:
I have an android project which has an activity downloads file and I want the file showing in the listview as well as an icon to be shown according to the extension of that file or if file is mp3 then mp3 Cover Picture

Please Someone Help Me How To Do it:-

This is my download.java file

package com.musicwala.djaman;
import android.app.Activity;
import android.os.Bundle;
import java.util.ArrayList;
import android.os.Environment;
import java.io.File;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.Arrays;
import org.json.JSONArray;
import java.util.List;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.Color;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.view.animation.OvershootInterpolator;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import android.media.MediaPlayer;
import java.io.IOException;

public class download extends ListActivity
{
    ListView listView;
    private File file;
    private List<String> myList;
   // String [] items = {"Bitcoin", "Ethereum", "LiteCoin", "Dash", "Neo", "Nano", "Bitcoin Cash", "Verge", "Ripple", "Bitcoin Diamond", "Iconomi", "Stellar Lumens"};
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO: Implement this method
        //getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setTitle("Downloads");
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.GREEN));
        getActionBar().setSubtitle("MusicWala");
        super.onCreate(savedInstanceState);
        myList = new ArrayList<String>();

        String root_sd = Environment.getExternalStorageDirectory().toString();
        file = new File( root_sd + "/MusicWala" ) ;
        File list[] = file.listFiles();

        for( int i=0; i< list.length; i++)
        {
            myList.add( list[i].getName() );
        }

        setListAdapter(new ArrayAdapter<String>(this,
                                                android.R.layout.simple_list_item_1, myList ));

    }

    protected void onListItemClick(ListView l, View v, int position, long id)
    {
        super.onListItemClick(l, v, position, id);

        File temp_file = new File( file, myList.get( position ) );

        if( !temp_file.isFile())
        {
            file = new File( file, myList.get( position ));
            File list[] = file.listFiles();

            myList.clear();

            for( int i=0; i< list.length; i++)
            {
                myList.add( list[i].getName() );
            }
            Toast.makeText(getApplicationContext(), file.toString(), Toast.LENGTH_LONG).show();
            setListAdapter(new ArrayAdapter<String>(this,
                                                    android.R.layout.simple_list_item_1, myList ));

        }
        Toast.makeText(getApplicationContext(), temp_file.getPath(), Toast.LENGTH_LONG).show();
        /*String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
        */
        String path = temp_file.getPath();
        String name = temp_file.getName();

        Intent intent = new Intent(download.this, play_ui.class);
        intent.putExtra("file", name).putExtra("path",path);
          startActivity(intent);

    }}

this is my download.xml of list view

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="21dp">

    </RelativeLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

my listview of download file

I Want


问:
Clicking on app link is not opening instant app directly
When I click on app link, it's showing me this screen

I was expecting the instant app to be opened directly. Any help would be appreciated

答:
Create App Links for Instant Apps:

If you've already followed the guides to Create Deep Links to App Content and Verify Android App Links, then you've already done most of the work necessary to make app links work with your instant app. There are just a couple extra rules when using app links for instant apps:

All intent filters used as app links in your instant app must support
both HTTP and HTTPS. For example:

```<code><intent-filter>
     <action android:name="android.intent.action.VIEW" />
     <category android:name="android.intent.category.DEFAULT" />
     <category android:name="android.intent.category.BROWSABLE" />
     <data android:scheme="http" android:host="www.example.com" />
     <data android:scheme="https" />
</intent-filter>
</code>```

For more: Follow this link.

After that, Change how you open instant apps from links.

Body:
Create App Links for Instant Apps:

If you've already followed the guides to Create Deep Links to App Content and Verify Android App Links, then you've already done most of the work necessary to make app links work with your instant app. There are just a couple extra rules when using app links for instant apps:

All intent filters used as app links in your instant app must support
both HTTP and HTTPS. For example:

<intent-filter>
     <action android:name="android.intent.action.VIEW" />
     <category android:name="android.intent.category.DEFAULT" />
     <category android:name="android.intent.category.BROWSABLE" />
     <data android:scheme="http" android:host="www.example.com" />
     <data android:scheme="https" />
</intent-filter>

For more: Follow this link.

After that, Change how you open instant apps from links.


问:
Github Pages returns 404 Error when trying to grab paper.js resource
I saw some other posts but it seems like I still can't get it to work, I made sure that the path exists inside the project but it doesn't seem to be able to grab it despite others working.

Specifically, as seen in the console in the page
Failed to load resource: the server responded with a status of 404 ()
for paper-full.js:1

The offending github page:
https://eriejar.github.io/SoundOfLife/gameoflife.js

The repo: https://github.com/Eriejar/SoundOfLife

Any help would be appreciated

I have tried the following URLs:

src="~/node_modules/paper/dist/paper-full.js"

src="./node_modules/paper/dist/paper-full.js"

src="/node_modules/paper/dist/paper-full.js"

src="node_modules/paper/dist/paper-full.js"

答: GitHub pages ignores the node_modules folder by default. Copy paper-full.js out of the folder or try the solution provided here: Github Pages 404 on node_modules folder</p>


问:
Android Studio music background
I want to play music in the background. I would like to change the song (there will be 2 songs) in my app. I successfully played a single song but I don't know how to add the second song.

I did it with Music Service:

```<code>public class MusicService extends Service implements MediaPlayer.OnErrorListener {

private final IBinder mBinder = new ServiceBinder();

MediaPlayer mPlayer;
private int length = 0;

public MusicService() {
}

public class ServiceBinder extends Binder {
    MusicService getService() {
        return MusicService.this;
    }
}

@Override
public IBinder onBind(Intent arg0) {
    return mBinder;
}

@Override
public void onCreate() {
    super.onCreate();

    mPlayer = MediaPlayer.create(this, R.raw.classic);
    mPlayer.setOnErrorListener(this);

    if (mPlayer != null) {
        mPlayer.setLooping(true);
        mPlayer.setVolume(50, 50);
    }

    mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

        public boolean onError(MediaPlayer mp, int what, int
                extra) {

            onError(mPlayer, what, extra);
            return true;
        }
    });
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (mPlayer != null) {
        mPlayer.start();
    }
    return START_NOT_STICKY;
}

public void pauseMusic() {
    if (mPlayer != null) {
        if (mPlayer.isPlaying()) {
            mPlayer.pause();
            length = mPlayer.getCurrentPosition();
        }
    }
}

public void resumeMusic() {
    if (mPlayer != null) {
        if (!mPlayer.isPlaying()) {
            mPlayer.seekTo(length);
            mPlayer.start();
        }
    }
}

public void startMusicClassic() {
    mPlayer = MediaPlayer.create(this, R.raw.classic);
    mPlayer.setOnErrorListener(this);

    if (mPlayer != null) {
        mPlayer.setLooping(true);
        mPlayer.setVolume(50, 50);
        mPlayer.start();
    }

}

public void stopMusic() {
    if (mPlayer != null) {
        mPlayer.stop();
        mPlayer.release();
        mPlayer = null;
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (mPlayer != null) {
        try {
            mPlayer.stop();
            mPlayer.release();
        } finally {
            mPlayer = null;
        }
    }
}

public boolean onError(MediaPlayer mp, int what, int extra) {

    Toast.makeText(this, "Music player failed", Toast.LENGTH_SHORT).show();
    if (mPlayer != null) {
        try {
            mPlayer.stop();
            mPlayer.release();
        } finally {
            mPlayer = null;
        }
    }
    return false;
}
</code>```

}

And in Main I created a Button and wrote this code:

```<code>      //added button for first song
    Button classic_music_Button = (Button) findViewById(R.id.button_classicmusic);
    classic_music_Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            playClassic();
        }
    });

}

void playClassic() {
    doBindService();
    Intent music = new Intent();
    music.setClass(this, MusicService.class);
    startService(music);
}

void doBindService() {
    bindService(new Intent(this, MusicService.class),
            Scon, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon = new ServiceConnection() {

    public void onServiceConnected(ComponentName name, IBinder
            binder) {
        mServ = ((MusicService.ServiceBinder) binder).getService();
    }

    public void onServiceDisconnected(ComponentName name) {
        mServ = null;
    }
};
</code>```

So for a second button that i will create what should I do to play a second song correctly?
Should I add a similar Class as MusicService for example? O r should I use MusicServiceForSecondButton and init everything as i did with first button?

答: Use a broadcast receiver to start the service and check if any service is running or not before playing any song. In case of playing musing try to use foreground service. </p>

Title: Android Studio music background

Body:
I want to play music in the background. I would like to change the song (there will be 2 songs) in my app. I successfully played a single song but I don't know how to add the second song.

I did it with Music Service:

public class MusicService extends Service implements MediaPlayer.OnErrorListener {

private final IBinder mBinder = new ServiceBinder();

MediaPlayer mPlayer;
private int length = 0;

public MusicService() {
}

public class ServiceBinder extends Binder {
    MusicService getService() {
        return MusicService.this;
    }
}

@Override
public IBinder onBind(Intent arg0) {
    return mBinder;
}

@Override
public void onCreate() {
    super.onCreate();

    mPlayer = MediaPlayer.create(this, R.raw.classic);
    mPlayer.setOnErrorListener(this);

    if (mPlayer != null) {
        mPlayer.setLooping(true);
        mPlayer.setVolume(50, 50);
    }

    mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

        public boolean onError(MediaPlayer mp, int what, int
                extra) {

            onError(mPlayer, what, extra);
            return true;
        }
    });
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (mPlayer != null) {
        mPlayer.start();
    }
    return START_NOT_STICKY;
}

public void pauseMusic() {
    if (mPlayer != null) {
        if (mPlayer.isPlaying()) {
            mPlayer.pause();
            length = mPlayer.getCurrentPosition();
        }
    }
}

public void resumeMusic() {
    if (mPlayer != null) {
        if (!mPlayer.isPlaying()) {
            mPlayer.seekTo(length);
            mPlayer.start();
        }
    }
}

public void startMusicClassic() {
    mPlayer = MediaPlayer.create(this, R.raw.classic);
    mPlayer.setOnErrorListener(this);

    if (mPlayer != null) {
        mPlayer.setLooping(true);
        mPlayer.setVolume(50, 50);
        mPlayer.start();
    }

}

public void stopMusic() {
    if (mPlayer != null) {
        mPlayer.stop();
        mPlayer.release();
        mPlayer = null;
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (mPlayer != null) {
        try {
            mPlayer.stop();
            mPlayer.release();
        } finally {
            mPlayer = null;
        }
    }
}

public boolean onError(MediaPlayer mp, int what, int extra) {

    Toast.makeText(this, "Music player failed", Toast.LENGTH_SHORT).show();
    if (mPlayer != null) {
        try {
            mPlayer.stop();
            mPlayer.release();
        } finally {
            mPlayer = null;
        }
    }
    return false;
}

}

And in Main I created a Button and wrote this code:

      //added button for first song
    Button classic_music_Button = (Button) findViewById(R.id.button_classicmusic);
    classic_music_Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            playClassic();
        }
    });

}

void playClassic() {
    doBindService();
    Intent music = new Intent();
    music.setClass(this, MusicService.class);
    startService(music);
}

void doBindService() {
    bindService(new Intent(this, MusicService.class),
            Scon, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon = new ServiceConnection() {

    public void onServiceConnected(ComponentName name, IBinder
            binder) {
        mServ = ((MusicService.ServiceBinder) binder).getService();
    }

    public void onServiceDisconnected(ComponentName name) {
        mServ = null;
    }
};

So for a second button that i will create what should I do to play a second song correctly?
Should I add a similar Class as MusicService for example? O r should I use MusicServiceForSecondButton and init everything as i did with first button?


问:
How to share data between fragments and activities in android
I am new to android.

Can anyone please tell me if it is possible to share data between activities and fragments using java interfaces. I have studied OOP but I am still stuck in interfaces and abstracts classes. I think if I implement a class on many activities, I will be able to share data like passing data from one activity and getting it from another.

Am I right about it? Please help me

答:
For between activities you can putExtra values such as below:

```<code>Intent intent = new Intent (this, newActivity.class);
intent.putExtra("someKey", someValue);
intent.putExtra(bundle);
startActivity(intent);
</code>```

To get it inside your activity:

```<code>getIntent().getExtra("someKey");
</code>```

For moving values between fragments i'd suggest using bundles:

```<code>//Where mainlayout is the top level id of your xml layout and R.id.viewProfile is the id of the action within your navigation xml.
       NavController navController = Navigation.findNavController(getActivity(), R.id.mainlayout);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("uid",snapshot.getKey());
                                    navController.navigate(R.id.viewProfile,bundle);
</code>```

to retrieve this value within your fragment:

```<code>String game = getArguments().getString("game");
</code>```

Hopefully that helps.

Body:
For between activities you can putExtra values such as below:

Intent intent = new Intent (this, newActivity.class);
intent.putExtra("someKey", someValue);
intent.putExtra(bundle);
startActivity(intent);

To get it inside your activity:

getIntent().getExtra("someKey");

For moving values between fragments i'd suggest using bundles:

//Where mainlayout is the top level id of your xml layout and R.id.viewProfile is the id of the action within your navigation xml.
       NavController navController = Navigation.findNavController(getActivity(), R.id.mainlayout);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("uid",snapshot.getKey());
                                    navController.navigate(R.id.viewProfile,bundle);

to retrieve this value within your fragment:

String game = getArguments().getString("game");

Hopefully that helps.


问:
linux recv() function flag parameter?
What will happen if I use recv(sockfd, buffer, len, 0); on a non-blocking socket?

If the socket sockfd is closed or nothing to be read, does the recv() block? (note: the flag in recv () is 0).

答:
If there is nothing to read it will block, if the socket is closed it will return with an error.

See the recv man page.

Title: linux recv() function flag parameter?