问:
Asp Net Core with Identity not working after removing HTTPS
I was trying to remove HTTPS to test some caching features and my authentication stopped working. I read that when using Identity authentication will stop working without HTTP, even a custom authentication cookie with an authentication scheme won't work either.

After I comment these 2 lines my app won't work anymore.

```<code>    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();

    app.UseHttpsRedirection();
</code>```

The use of HTTPS is not mandatory, the application is to be used on our intranet and I have used Identity just to manage users. What options do I have right now?

even with all this, when I try to login it redirects me back to login page, and this using a custom authentication cookie not indentity.

```<code>  services.AddAuthentication().AddCookie(AuthenticationSchemes.Production, options =>
        {
            options.ExpireTimeSpan = TimeSpan.FromHours(8);
            options.LoginPath = new PathString("/Login");
            options.LogoutPath = new PathString("/Logout");
            options.Cookie.HttpOnly = true;
            options.AccessDeniedPath = new PathString("/AccessDenied");
            options.SlidingExpiration = true;
            options.Cookie.Name = "NoPaper.Production";
            options.ExpireTimeSpan = TimeSpan.FromHours(8);
        });
</code>```

UPDATE

It seems the only solution that worked was to create a new project without https and just copy everything from the other and install nuget packages and it worked.

答:
Please explain more detail about the Authentication not working, is there any error? Try to use F12 developer tools to check it. And please make sure you are not using the ex

As far as I know, when we create dotnet core application via Visual Studio, if we select the Individual User Accounts(using Identity), it will generally force the usage of https for best practice reasons.

In this scenario, to disable HTTPS, we could refer to the following steps:

remove the UseHttpsRedirection from the Startup.cs:

```<code>app.UseHsts();
app.UseHttpsRedirection();
</code>```

Right click the project, and click the Properties, in the Debug tab, unchecked the Enable SSL option. Then, the application will be launched using HTTP requests.

If you are not using the Visual Studio, you could also removing the SSL references in the launchSettings.json file:

Besides, please make sure you are not using the external authentication services in your application. I have created new dotnet core application and use above method to disable HTTPS, and then, I could use Identity to register a new user and login.

Body:
I was trying to remove HTTPS to test some caching features and my authentication stopped working. I read that when using Identity authentication will stop working without HTTP, even a custom authentication cookie with an authentication scheme won't work either.

After I comment these 2 lines my app won't work anymore.

    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();

    app.UseHttpsRedirection();

The use of HTTPS is not mandatory, the application is to be used on our intranet and I have used Identity just to manage users. What options do I have right now?

even with all this, when I try to login it redirects me back to login page, and this using a custom authentication cookie not indentity.

  services.AddAuthentication().AddCookie(AuthenticationSchemes.Production, options =>
        {
            options.ExpireTimeSpan = TimeSpan.FromHours(8);
            options.LoginPath = new PathString("/Login");
            options.LogoutPath = new PathString("/Logout");
            options.Cookie.HttpOnly = true;
            options.AccessDeniedPath = new PathString("/AccessDenied");
            options.SlidingExpiration = true;
            options.Cookie.Name = "NoPaper.Production";
            options.ExpireTimeSpan = TimeSpan.FromHours(8);
        });

UPDATE

It seems the only solution that worked was to create a new project without https and just copy everything from the other and install nuget packages and it worked.

Body:
Please explain more detail about the Authentication not working, is there any error? Try to use F12 developer tools to check it. And please make sure you are not using the ex

As far as I know, when we create dotnet core application via Visual Studio, if we select the Individual User Accounts(using Identity), it will generally force the usage of https for best practice reasons.

In this scenario, to disable HTTPS, we could refer to the following steps:

remove the UseHttpsRedirection from the Startup.cs:

app.UseHsts();
app.UseHttpsRedirection();

Right click the project, and click the Properties, in the Debug tab, unchecked the Enable SSL option. Then, the application will be launched using HTTP requests.

If you are not using the Visual Studio, you could also removing the SSL references in the launchSettings.json file:

Besides, please make sure you are not using the external authentication services in your application. I have created new dotnet core application and use above method to disable HTTPS, and then, I could use Identity to register a new user and login.


来源: stackexchange

问:
How to check if i`m touching something in Unity
I've got OnCollisionEnter2D function, but it say's only once, when i`m landing on ground, i want function that will return object name(or smthng like this) if i'm touching it, so if i'll stay on it it will say me about it not only once but every frame.</p>

答:
It's as simple as using the correct method OnCollisionStay2D which is called every frame while you are colliding with another object

Sent each frame where a collider on another object is touching this object's collider (2D physics only).

To be fair: Their example in that link is bullshit since it is for OnTriggerStay2D ^^

It could look like

```<code>private void OnCollisionStay2D(Collision2D collision)
{
    Debug.Log($"I am touching {collision.gameObject.name}", this);
}
</code>```

If instead you want to keep track of every touching object I would rather use something like

```<code>private HashSet<GameObject> _currentlyTouching = new HashSet<GameObject>();

private void OnCollisionEnter2D(Collision2D collision)
{
    if(!_currentlyTouching.Contains(collision.gameObject))
    {
        _currentlyTouching.Add(collision.gameObject);
    }
}

private void OnCollisionExit2D(Collision2D collision)
{
    if(_currentlyTouching.Contains(collision.gameObject))
    {
        _currentlyTouching.Remove(collision.gameObject);
    }
}

private void Update()
{
    var logString = new StringBuilder("I am touching ");
    foreach(var touchingObject in _currentlyTouching)
    {
        logString.Append(touchingObject.name).Append(" ");
    }
    Debug.Log(logString.ToString(), this);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It's as simple as using the correct method OnCollisionStay2D which is called every frame while you are colliding with another object

Sent each frame where a collider on another object is touching this object's collider (2D physics only).

To be fair: Their example in that link is bullshit since it is for OnTriggerStay2D ^^

It could look like

private void OnCollisionStay2D(Collision2D collision)
{
    Debug.Log($"I am touching {collision.gameObject.name}", this);
}

If instead you want to keep track of every touching object I would rather use something like

private HashSet<GameObject> _currentlyTouching = new HashSet<GameObject>();

private void OnCollisionEnter2D(Collision2D collision)
{
    if(!_currentlyTouching.Contains(collision.gameObject))
    {
        _currentlyTouching.Add(collision.gameObject);
    }
}

private void OnCollisionExit2D(Collision2D collision)
{
    if(_currentlyTouching.Contains(collision.gameObject))
    {
        _currentlyTouching.Remove(collision.gameObject);
    }
}

private void Update()
{
    var logString = new StringBuilder("I am touching ");
    foreach(var touchingObject in _currentlyTouching)
    {
        logString.Append(touchingObject.name).Append(" ");
    }
    Debug.Log(logString.ToString(), this);
}


问:
How to invoke multiple methods from Struts 2.5 with SMI and when DMI is off
Right now we are using Struts 2.5 and I have    Dynamic Method Invocation=true in Struts configuration file .

And i have action mappings as below.

<action name="action name" class="action class"
   <result name="view" type="redirectAction"></result>
   <allowed-methods>
         view,modify,delete,duplicate
   </allowed-methods>
</action>
```

To remediate App-sec finding i have to set Dynamic Method Invocation to false.

I have set Dynamic Method Invocation value="false" . Now allowed methods are not working.

I did specify multiple actions with methods, it did not work as well. It is calling default reset and process method from the Action class instead the specified method.

I have read that for allowed-methods to work we have to have Dynamic Method Invocation set to true?

How do i call multiple methods with the same action with disabling Dynamic Method Invocation?

答:
If DMI is turned off you cannot invoke methods dynamically; that's the point of turning it off.

You can use Strict Method Invocation to explicitly allow methods; SMI is enabled by default.

You can't have it both ways--DMI is either enabled, or not.

Body:
Right now we are using Struts 2.5 and I have    Dynamic Method Invocation=true in Struts configuration file .

And i have action mappings as below.

<action name="action name" class="action class"
   <result name="view" type="redirectAction"></result>
   <allowed-methods>
         view,modify,delete,duplicate
   </allowed-methods>
</action>

To remediate App-sec finding i have to set Dynamic Method Invocation to false.

I have set Dynamic Method Invocation value="false" . Now allowed methods are not working.

I did specify multiple actions with methods, it did not work as well. It is calling default reset and process method from the Action class instead the specified method.

I have read that for allowed-methods to work we have to have Dynamic Method Invocation set to true?

How do i call multiple methods with the same action with disabling Dynamic Method Invocation?


问:
Azure AD account had option to send password to another email address - where is this address in user's Azure AD?
I was just recently created as a new user in Microsoft 365 Admin Center (https://admin.microsoft.com/) and during account creation, when setting up password, there was a field to send the password /setup details to me through another email address (my previous email address, outside O365).

I received my new account notification at this other email address, and now this email address gets notifications etc. but when we look at my Azure AD membership, I can't find where this email address is configured in the settings.  Where is this forwarding address being stored?

We checked Azure Admin portal (portal.azure.com) Authentication contact info for my entry and it's not filled in.

It's not in Manage User Name or contact information in the https://admin.microsoft.com/Adminportal/Home#/users page

It's not in my account profile anywhere in https://portal.office.com/account/#personalinfo

Totally stumped!  Apologies if the answer is obvious.

答:
Mystery solved: The forwarding was happening through billing notifications setup:
https://admin.microsoft.com/AdminPortal/Home#/BillingNotifications</p>


问:
What package should I use to create a diagram in Angular?
I want to have a diagram for a project that has drag and drop and the user can add a node.
I want to implement something like the image below with Angular9.
Please introduce me to a package of npm that will not be a problem in the next angular updates and can be implemented with Angular.
thank you

答:
Try `@syncfusion/ej2-angular-diagrams'

NPM

Syncfusion Angular UI (Essential JS 2) is a collection of modern TypeScript based true Angular Components. It has support for Ahead Of Time (AOT) compilation and Tree-Shaking. All the components are developed from the ground up to be lightweight, responsive, modular and touch friendly.

You can install it from npm using npm install @syncfusion/ej2-angular-grids --save


问:
Currency Format Apache POI
I need to set format for BRL coin into my sheet. I'm using Apache POI for set currency style with code below:

```<code>XSSFCellStyle style = xssfWorkbook.createCellStyle();
style.setDataFormat(cf.getFormat("R$#,##0.00;\\R$-#,##0.00"));
</code>```

But when i open my xlsx file into LibreOffice (i'm a linux user ), my  cells are not formatted. Checking the cell contains a quote ' at beggin of cell value and when retired this quote, my cell value is formatted correctly. Prints of my sheet after and before. Please any sugestions?

Edit: My method that create and setValue into cell (
passing as parameter the style above):

```<code> public XSSFCell criarCelula(int indice, String conteudo, XSSFRow linha, XSSFCellStyle estilo) {
   XSSFCell celula = linha.createCell(indice);
   celula.setCellValue(conteudo);
   celula.setCellStyle(estilo);
   return celula;
}
</code>```

答:
I got it with sugestion of Axel Ritcher. Using my content into double type instead of string. </p>

```<code>Double conteudo;
celula.setCellValue(conteudo);
</code>```

Title: Currency Format Apache POI

Body:
I need to set format for BRL coin into my sheet. I'm using Apache POI for set currency style with code below:

XSSFCellStyle style = xssfWorkbook.createCellStyle();
style.setDataFormat(cf.getFormat("R$#,##0.00;\\R$-#,##0.00"));

But when i open my xlsx file into LibreOffice (i'm a linux user ), my  cells are not formatted. Checking the cell contains a quote ' at beggin of cell value and when retired this quote, my cell value is formatted correctly. Prints of my sheet after and before. Please any sugestions?

Edit: My method that create and setValue into cell (
passing as parameter the style above):

 public XSSFCell criarCelula(int indice, String conteudo, XSSFRow linha, XSSFCellStyle estilo) {
   XSSFCell celula = linha.createCell(indice);
   celula.setCellValue(conteudo);
   celula.setCellStyle(estilo);
   return celula;
}

Body:
I got it with sugestion of Axel Ritcher. Using my content into double type instead of string.

Double conteudo;
celula.setCellValue(conteudo);


问:
What's the best way to get rid of nested ifs in code while checking for conditions?
I'm developing a BlackBerry app in Java and I have an Options class where all user settings are stored. The problem is I need to check some conditions in order to know how to react. As I keep adding more features, more GUI options are shown to the user, more settings are stored in the Options class and more conditions need to be checked for.

Take the following code for example:

```<code>private void doCallMonitoring(int callId){
    /*This is the part that I want to avoid. Having
      multiple nested ifs. Here's just two conditions
      but as I add more, it will get unmantainable
      very quickly.*/
    if(Options.isActive().booleanValue()){
        callTime = new Timer();
        TimerTask callTimeTask = new TimerTask(){
            public void run(){
                callTimeSeconds++;
        if((callTimeSeconds == Options.getSoftLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectDTMFTone(Phone.getActiveCall());
        }else if((callTimeSeconds >= Options.getHardLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectEndCall();
                }
             }
        };
        callTime.schedule(callTimeTask, 0,1000);
    }else{
    System.out.println("Service not active");
    }
}
</code>```

How I would want it to work is to verify all options with a single call and from there determine the curse of action. How can I achieve such a design?

答:
Another option is to make methods such as injectDMTFTone() check to see if they want to handle that condition, and return true or false depending on if it was handled or not.

For instance:

```<code>public void run() {
    callTimeSeconds++;
    do {
        if (handleInjectDMTFTone())
            break;
        if (handleInjectEndCall())
            break;
    } while(false);

    callTime.schedule(callTimeTask, 0,1000);
}

boolean handleInjectDMTFTone() {
    if ((callTimeSeconds != Options.getSoftLimit().intValue()) ||
        (Phone.getActiveCall().getStatus() != PhoneCall.STATUS_CONNECTED))
        return false;

    injectDTMFTone(Phone.getActiveCall());
    return true;
}

boolean handleInjectEndCall() {

    if ((callTimeSeconds < Options.getHardLimit().intValue()) ||
        (Phone.getActiveCall().getStatus() != PhoneCall.STATUS_CONNECTED))
        return false;

    injectEndCall();
    return true;
}
</code>```

Of course, instead of calling another injectDMTFTone() method or injectEndCall() method, you would just inline that logic right in those methods. In that way you've grouped all the logic of how and when to deal with those conditions in the same place.

This is one of my favorite patterns; use if statements as close to the top of methods as makes sense to eliminate conditions and return. The rest of the method is not indented many levels, and is easy and straightforward to read.

You can further extend this by creating objects that all implement the same interface and are in a repository of handlers that your run method can iterate over to see which will handle it. That may or may not be overkill to your case.

OwnerDisplayName: Cesar

ContentLicense: CC BY-SA 2.5

Body:
I'm developing a BlackBerry app in Java and I have an Options class where all user settings are stored. The problem is I need to check some conditions in order to know how to react. As I keep adding more features, more GUI options are shown to the user, more settings are stored in the Options class and more conditions need to be checked for.

Take the following code for example:

private void doCallMonitoring(int callId){
    /*This is the part that I want to avoid. Having
      multiple nested ifs. Here's just two conditions
      but as I add more, it will get unmantainable
      very quickly.*/
    if(Options.isActive().booleanValue()){
        callTime = new Timer();
        TimerTask callTimeTask = new TimerTask(){
            public void run(){
                callTimeSeconds++;
        if((callTimeSeconds == Options.getSoftLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectDTMFTone(Phone.getActiveCall());
        }else if((callTimeSeconds >= Options.getHardLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectEndCall();
                }
             }
        };
        callTime.schedule(callTimeTask, 0,1000);
    }else{
    System.out.println("Service not active");
    }
}

How I would want it to work is to verify all options with a single call and from there determine the curse of action. How can I achieve such a design?

Body:
Another option is to make methods such as injectDMTFTone() check to see if they want to handle that condition, and return true or false depending on if it was handled or not.

For instance:

public void run() {
    callTimeSeconds++;
    do {
        if (handleInjectDMTFTone())
            break;
        if (handleInjectEndCall())
            break;
    } while(false);

    callTime.schedule(callTimeTask, 0,1000);
}

boolean handleInjectDMTFTone() {
    if ((callTimeSeconds != Options.getSoftLimit().intValue()) ||
        (Phone.getActiveCall().getStatus() != PhoneCall.STATUS_CONNECTED))
        return false;

    injectDTMFTone(Phone.getActiveCall());
    return true;
}

boolean handleInjectEndCall() {

    if ((callTimeSeconds < Options.getHardLimit().intValue()) ||
        (Phone.getActiveCall().getStatus() != PhoneCall.STATUS_CONNECTED))
        return false;

    injectEndCall();
    return true;
}

Of course, instead of calling another injectDMTFTone() method or injectEndCall() method, you would just inline that logic right in those methods. In that way you've grouped all the logic of how and when to deal with those conditions in the same place.

This is one of my favorite patterns; use if statements as close to the top of methods as makes sense to eliminate conditions and return. The rest of the method is not indented many levels, and is easy and straightforward to read.

You can further extend this by creating objects that all implement the same interface and are in a repository of handlers that your run method can iterate over to see which will handle it. That may or may not be overkill to your case.

OwnerDisplayName: Jared Oberhaus


问:
How do I cancel a coroutine run inside a withContext?
I have a Repository defined as the following.

```<code>class StoryRepository {
    private val firestore = Firebase.firestore

    suspend fun fetchStories(): QuerySnapshot? {
        return try {
            firestore
                .collection("stories")
                .get()
                .await()
        } catch(e: Exception) {
            Log.e("StoryRepository", "Error in fetching Firestore stories: $e")
            null
        }
    }
}
</code>```

I also have a ViewModel like this.

```<code>class HomeViewModel(
    application: Application
) : AndroidViewModel(application) {
    private var viewModelJob = Job()
    private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
    private val storyRepository = StoryRepository()

    private var _stories = MutableLiveData<List<Story>>()
    val stories: LiveData<List<Story>>
        get() = _stories

    init {
        uiScope.launch {
            getStories()
        }
        uiScope.launch {
            getMetadata()
        }
    }

    private suspend fun getStories() {
        withContext(Dispatchers.IO) {
            val snapshots = storyRepository.fetchStories()
            // Is this correct?
            if (snapshots == null) {
                cancel(CancellationException("Task is null; local DB not refreshed"))
                return@withContext
            }
            val networkStories = snapshots.toObjects(NetworkStory::class.java)
            val stories = NetworkStoryContainer(networkStories).asDomainModel()
            _stories.postValue(stories)
        }
    }

    suspend fun getMetadata() {
        // Does some other fetching
    }

    override fun onCleared() {
        super.onCleared()
        viewModelJob.cancel()
    }
}
</code>```

As you can see, sometimes, StoryRepository().fetchStories() may fail and return null. If the return value is null, I would like to not continue what follows after the checking for snapshots being null block. Therefore, I would like to cancel that particular coroutine (the one that runs getStories() without cancelling the other coroutine (the one that runs getMetadata()). How do I achieve this and is return-ing from withContext a bad-practice?

答:
Although your approach is right, you can always make some improvements to make it simpler or more idiomatic (especially when you're not pleased with your own code).

These are just some suggestions that you may want to take into account:

You can make use of Kotlin Scope Functions, or more specifically the let function like this:

```<code>private suspend fun getStories() = withContext(Dispatchers.IO) {
    storyRepository.fetchStories()?.let { snapshots ->
        val networkStories = snapshots.toObjects(NetworkStory::class.java)
        NetworkStoryContainer(networkStories).asDomainModel()
    } ?: throw CancellationException("Task is null; local DB not refreshed")
}
</code>```

This way you'll be returning your data or throwing a CancellationException if null.

When you're working with coroutines inside a ViewModel you have a CoroutineScope ready to be used if you add this dependendy to your gradle file:

```<code>androidx.lifecycle:lifecycle-viewmodel-ktx:{version}
</code>```

So you can use viewModelScope to build your coroutines, which will run on the main thread:

```<code>init {
    viewModelScope.launch {
        _stories.value = getStories()
    }

    viewModelScope.launch {
        getMetadata()
    }
}
</code>```

You can forget about cancelling its Job during onCleared since viewModelScope is lifecycle-aware.

Now all you have left to do is handling the exception with a try-catch block or with the  invokeOnCompletion function applied on the Job returned by the launch builder.

Body:
I have a Repository defined as the following.

class StoryRepository {
    private val firestore = Firebase.firestore

    suspend fun fetchStories(): QuerySnapshot? {
        return try {
            firestore
                .collection("stories")
                .get()
                .await()
        } catch(e: Exception) {
            Log.e("StoryRepository", "Error in fetching Firestore stories: $e")
            null
        }
    }
}

I also have a ViewModel like this.

class HomeViewModel(
    application: Application
) : AndroidViewModel(application) {
    private var viewModelJob = Job()
    private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
    private val storyRepository = StoryRepository()

    private var _stories = MutableLiveData<List<Story>>()
    val stories: LiveData<List<Story>>
        get() = _stories

    init {
        uiScope.launch {
            getStories()
        }
        uiScope.launch {
            getMetadata()
        }
    }

    private suspend fun getStories() {
        withContext(Dispatchers.IO) {
            val snapshots = storyRepository.fetchStories()
            // Is this correct?
            if (snapshots == null) {
                cancel(CancellationException("Task is null; local DB not refreshed"))
                return@withContext
            }
            val networkStories = snapshots.toObjects(NetworkStory::class.java)
            val stories = NetworkStoryContainer(networkStories).asDomainModel()
            _stories.postValue(stories)
        }
    }

    suspend fun getMetadata() {
        // Does some other fetching
    }

    override fun onCleared() {
        super.onCleared()
        viewModelJob.cancel()
    }
}

As you can see, sometimes, StoryRepository().fetchStories() may fail and return null. If the return value is null, I would like to not continue what follows after the checking for snapshots being null block. Therefore, I would like to cancel that particular coroutine (the one that runs getStories() without cancelling the other coroutine (the one that runs getMetadata()). How do I achieve this and is return-ing from withContext a bad-practice?

Body:
Although your approach is right, you can always make some improvements to make it simpler or more idiomatic (especially when you're not pleased with your own code).

These are just some suggestions that you may want to take into account:

You can make use of Kotlin Scope Functions, or more specifically the let function like this:

private suspend fun getStories() = withContext(Dispatchers.IO) {
    storyRepository.fetchStories()?.let { snapshots ->
        val networkStories = snapshots.toObjects(NetworkStory::class.java)
        NetworkStoryContainer(networkStories).asDomainModel()
    } ?: throw CancellationException("Task is null; local DB not refreshed")
}

This way you'll be returning your data or throwing a CancellationException if null.

When you're working with coroutines inside a ViewModel you have a CoroutineScope ready to be used if you add this dependendy to your gradle file:

androidx.lifecycle:lifecycle-viewmodel-ktx:{version}

So you can use viewModelScope to build your coroutines, which will run on the main thread:

init {
    viewModelScope.launch {
        _stories.value = getStories()
    }

    viewModelScope.launch {
        getMetadata()
    }
}

You can forget about cancelling its Job during onCleared since viewModelScope is lifecycle-aware.

Now all you have left to do is handling the exception with a try-catch block or with the  invokeOnCompletion function applied on the Job returned by the launch builder.


问:
How to check if clicked on UI object?
I am new to Unity and trying to make a basic minesweeper game. I have a square prefab and I want to learn if it is clicked. But I can not do it listening because I need both left click and right click. How can I do that?</p>

答:
The absolute quickest way should be to implement something like this on the prefab you wish to listen for clicks on:

```<code>void OnMouseOver()
{
    if (Input.GetMouseDown(0)) {
         // Left click
    }
    else if (Input.GetMouseDown(1)) {
        // Right click
    }

}
</code>```

If you instead want to detect mouseclicks from a more central position (as in, not distributed to each GameObject) you will need to create a component that fires Raycasts depending on left & right-clicks and look for specific objects, and then do you logic

Short example:

```<code>if (Input.GetMouseDown(0)) {

    if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100)) {
        // something was hit
    }

}

</code>```

https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

Title: How to check if clicked on UI object?

Body:
The absolute quickest way should be to implement something like this on the prefab you wish to listen for clicks on:

void OnMouseOver()
{
    if (Input.GetMouseDown(0)) {
         // Left click
    }
    else if (Input.GetMouseDown(1)) {
        // Right click
    }

}

If you instead want to detect mouseclicks from a more central position (as in, not distributed to each GameObject) you will need to create a component that fires Raycasts depending on left & right-clicks and look for specific objects, and then do you logic

Short example:

if (Input.GetMouseDown(0)) {

    if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100)) {
        // something was hit
    }

}

https://docs.unity3d.com/ScriptReference/Physics.Raycast.html


问:
How do I get the key's value after I release the key
I understand by using for example,

```<code>Space & a::b
</code>```

I can have b by holding Space then press a. However this disable the Space's output. How do I get a Space character, for example by releasing Space key or press Space key twice.

答:
Try this:</p>

```<code>#If GetKeyState("Space")
a::b
</code>```

Body:
I understand by using for example,

Space & a::b

I can have b by holding Space then press a. However this disable the Space's output. How do I get a Space character, for example by releasing Space key or press Space key twice.

Body:
Try this:

#If GetKeyState("Space")
a::b


问:
Talend MySQL flow keeps stopping at 11599 rows
I have created a job in Talend Open Studio for Data Integration. It runs and does the right thing but keeps stopping at 11599 rows when I run it. The only advanced setting I have used is Enable Stream to ease memory usage.

答: Ah so it turns out there was something wrong with the row 11600 (hence why it went to 11599 and then stopped). Still trying to figure out what though.</p>


问:
Correctly Release cell from UITAbleView
I would like to know how to correctly release a cell and fix a memory leak I have. and also ask if a memory leak can cause crashing on scrolling if the numbers cell numbers get high?

Here is my cell where the leak is coming from any suggestions?

```<code>NSString *identifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

if (cell == nil) {

}

//add subtitle
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:@"cell"];

  /*
  //Here it adds a nice shadow to the table view but will crash on rotation and send a
  wierd dump to ApplistViewController !!!????
  tableView.layer.shadowColor = [[UIColor blackColor] CGColor];
  tableView.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
  tableView.layer.shadowRadius = 8.0f;
  tableView.layer.shadowOpacity = 1.0f;
  */

[cell.textLabel setNumberOfLines:1];
[cell.textLabel setText:[(Tweet*)[authors objectAtIndex:indexPath.row] author]];

[cell.detailTextLabel setText:[(Tweet*)[tweets objectAtIndex:indexPath.row] tweet]];
[cell.detailTextLabel setNumberOfLines:10];
[cell.textLabel setTextColor:[UIColor darkGrayColor]];
[cell.textLabel setShadowColor:[UIColor whiteColor]];
[cell.textLabel setShadowOffset:CGSizeMake(0.5, 0.5)];
[cell.detailTextLabel setTextColor:[UIColor blackColor]];
//[cell.detailTextLabel setText:[(Tweet*)[retweetCount objectAtIndex:indexPath.row]
reTweetCount]];
[cell.textLabel setUserInteractionEnabled:YES];
[cell.contentView setMultipleTouchEnabled:YES];
// cell.text = [[NSString alloc] initWithFormat:@"Cell :%i", indexPath.row];

 NSURL *url = [NSURL URLWithString:[(Tweet*)[avatarsURL
 objectAtIndex:indexPath.row]avatarURL]];
 NSData *data = [NSData dataWithContentsOfURL:url];
 // NSLog(@"http://a0.twimg.com/profile_images/1268205919/iDD_normal.png");
 UIImage *tableImage = [[UIImage alloc] initWithData:data];
 [cell.imageView setImage:tableImage];
 cell.imageView.image = tableImage ;
 CGSize imageSize = CGSizeMake(45,45);
 UIGraphicsBeginImageContext(imageSize);
 CGRect imageRect = CGRectMake(0.2, 0.1, imageSize.width, imageSize.height);
 [tableImage drawInRect:imageRect];
 cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

//PlaceMent avatars! would like to use a if statment to place this image in the cell if
before it retrives the avatar just like the method above for the profile!

/*
 NSString *avatar = [[NSBundle mainBundle] pathForResource:@"avatar" ofType:@"png"];
 UIImage *setAvatar = [[UIImage alloc] initWithContentsOfFile:avatar];

 //now place avatar in cell
 cell.imageView.image = setAvatar;
 */

 //add gradient to cell
 UIImage *gradient = [UIImage imageNamed:@"gradientcell2.png"];
 UIImageView *cellimage = [[UIImageView alloc] initWithImage:gradient];
 cellimage.contentMode = UIViewContentModeScaleToFill;
 cell.backgroundView = cellimage;

  [cellimage release];

UIImage *selectedGradient = [UIImage imageNamed:@"selectedcell.png"];

UIImageView *selectedCell = [[UIImageView alloc] initWithImage:selectedGradient];
selectedCell.contentMode = UIViewContentModeScaleToFill;
cell.selectedBackgroundView = selectedCell;

//subtitle if needed !! Also change UITableViewStlyle from default to Subtitle up 7
lines
// cell.detailTextLabel.text = @"subtile";

//yeah another warning within the tableview whats new =P
[tableView setBackgroundColor:[UIColor clearColor]];

return cell;

[cell autorelease];
}
</code>```

ALL the LEAKS are fixed!!!! Thank You   but why do I crash when I add a count integer ?

Any Suggestions?

```<code>2011-06-01 18:24:55.663 ThemeCatcher[4641:207] *** Terminating app due to uncaught
exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 16
beyond bounds [0 .. 15]'
*** Call stack at first throw:
(
0   CoreFoundation                      0x014dcbe9 __exceptionPreprocess + 185
1   libobjc.A.dylib                     0x016315c2 objc_exception_throw + 47
2   CoreFoundation                      0x014d26e5 -[__NSArrayM objectAtIndex:] +
261
3   ThemeCatcher                        0x00025833 -[TwitterVeiwController
tableView:cellForRowAtIndexPath:] + 531
4   UIKit                               0x007bb7fa -
[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 634
5   UIKit                               0x007b177f -
[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] + 75
6   UIKit                               0x007c6450 -
[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1561
7   UIKit                               0x007be538 -[UITableView layoutSubviews] +
242
8   QuartzCore                          0x00460451 -[CALayer layoutSublayers] + 181
9   QuartzCore                          0x0046017c CALayerLayoutIfNeeded + 220
10  QuartzCore                          0x0045937c
_ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310
11  QuartzCore                          0x004590d0 _ZN2CA11Transaction6commitEv +
292
12  QuartzCore                          0x004897d5
_ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 99
13  CoreFoundation                      0x014bdfbb
__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 27
14  CoreFoundation                      0x014530e7 __CFRunLoopDoObservers + 295
15  CoreFoundation                      0x0141bbd7 __CFRunLoopRun + 1575
16  CoreFoundation                      0x0141b240 CFRunLoopRunSpecific + 208
17  CoreFoundation                      0x0141b161 CFRunLoopRunInMode + 97
18  GraphicsServices                    0x01efa268 GSEventRunModal + 217
19  GraphicsServices                    0x01efa32d GSEventRun + 115
20  UIKit                               0x0075642e UIApplicationMain + 1160
21  ThemeCatcher                        0x000021c9 main + 121
22  ThemeCatcher                        0x00002145 start + 53
23  ???                                 0x00000001 0x0 + 1

)

terminate called after throwing an instance of 'NSException'
Current language:  auto; currently objective-c
(gdb)
</code>```

答:
cell object needs to be autoreleased here – cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:@"cell"]; and this line needs to be inside if ( cell == nil ) { //here }.

You alloc-init tableImage but do not release it.

selectedCell is not released either.

You are autoreleaseing after returning from the method. This won't happen and in case of reusable cell, it will send an additional release message crashing your app.

There seem to more issues within your comments which I have chosen not to include. Try using the Leaks application to check for memory leaks.

ContentLicense: CC BY-SA 3.0

Title: Correctly Release cell from UITAbleView

Body:
I would like to know how to correctly release a cell and fix a memory leak I have. and also ask if a memory leak can cause crashing on scrolling if the numbers cell numbers get high?

Here is my cell where the leak is coming from any suggestions?

NSString *identifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

if (cell == nil) {

}

//add subtitle
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:@"cell"];

  /*
  //Here it adds a nice shadow to the table view but will crash on rotation and send a
  wierd dump to ApplistViewController !!!????
  tableView.layer.shadowColor = [[UIColor blackColor] CGColor];
  tableView.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
  tableView.layer.shadowRadius = 8.0f;
  tableView.layer.shadowOpacity = 1.0f;
  */

[cell.textLabel setNumberOfLines:1];
[cell.textLabel setText:[(Tweet*)[authors objectAtIndex:indexPath.row] author]];

[cell.detailTextLabel setText:[(Tweet*)[tweets objectAtIndex:indexPath.row] tweet]];
[cell.detailTextLabel setNumberOfLines:10];
[cell.textLabel setTextColor:[UIColor darkGrayColor]];
[cell.textLabel setShadowColor:[UIColor whiteColor]];
[cell.textLabel setShadowOffset:CGSizeMake(0.5, 0.5)];
[cell.detailTextLabel setTextColor:[UIColor blackColor]];
//[cell.detailTextLabel setText:[(Tweet*)[retweetCount objectAtIndex:indexPath.row]
reTweetCount]];
[cell.textLabel setUserInteractionEnabled:YES];
[cell.contentView setMultipleTouchEnabled:YES];
// cell.text = [[NSString alloc] initWithFormat:@"Cell :%i", indexPath.row];

 NSURL *url = [NSURL URLWithString:[(Tweet*)[avatarsURL
 objectAtIndex:indexPath.row]avatarURL]];
 NSData *data = [NSData dataWithContentsOfURL:url];
 // NSLog(@"http://a0.twimg.com/profile_images/1268205919/iDD_normal.png");
 UIImage *tableImage = [[UIImage alloc] initWithData:data];
 [cell.imageView setImage:tableImage];
 cell.imageView.image = tableImage ;
 CGSize imageSize = CGSizeMake(45,45);
 UIGraphicsBeginImageContext(imageSize);
 CGRect imageRect = CGRectMake(0.2, 0.1, imageSize.width, imageSize.height);
 [tableImage drawInRect:imageRect];
 cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

//PlaceMent avatars! would like to use a if statment to place this image in the cell if
before it retrives the avatar just like the method above for the profile!

/*
 NSString *avatar = [[NSBundle mainBundle] pathForResource:@"avatar" ofType:@"png"];
 UIImage *setAvatar = [[UIImage alloc] initWithContentsOfFile:avatar];

 //now place avatar in cell
 cell.imageView.image = setAvatar;
 */

 //add gradient to cell
 UIImage *gradient = [UIImage imageNamed:@"gradientcell2.png"];
 UIImageView *cellimage = [[UIImageView alloc] initWithImage:gradient];
 cellimage.contentMode = UIViewContentModeScaleToFill;
 cell.backgroundView = cellimage;

  [cellimage release];

UIImage *selectedGradient = [UIImage imageNamed:@"selectedcell.png"];

UIImageView *selectedCell = [[UIImageView alloc] initWithImage:selectedGradient];
selectedCell.contentMode = UIViewContentModeScaleToFill;
cell.selectedBackgroundView = selectedCell;

//subtitle if needed !! Also change UITableViewStlyle from default to Subtitle up 7
lines
// cell.detailTextLabel.text = @"subtile";

//yeah another warning within the tableview whats new =P
[tableView setBackgroundColor:[UIColor clearColor]];

return cell;

[cell autorelease];
}

ALL the LEAKS are fixed!!!! Thank You   but why do I crash when I add a count integer ?

Any Suggestions?

2011-06-01 18:24:55.663 ThemeCatcher[4641:207] *** Terminating app due to uncaught
exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 16
beyond bounds [0 .. 15]'
*** Call stack at first throw:
(
0   CoreFoundation                      0x014dcbe9 __exceptionPreprocess + 185
1   libobjc.A.dylib                     0x016315c2 objc_exception_throw + 47
2   CoreFoundation                      0x014d26e5 -[__NSArrayM objectAtIndex:] +
261
3   ThemeCatcher                        0x00025833 -[TwitterVeiwController
tableView:cellForRowAtIndexPath:] + 531
4   UIKit                               0x007bb7fa -
[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 634
5   UIKit                               0x007b177f -
[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] + 75
6   UIKit                               0x007c6450 -
[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1561
7   UIKit                               0x007be538 -[UITableView layoutSubviews] +
242
8   QuartzCore                          0x00460451 -[CALayer layoutSublayers] + 181
9   QuartzCore                          0x0046017c CALayerLayoutIfNeeded + 220
10  QuartzCore                          0x0045937c
_ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310
11  QuartzCore                          0x004590d0 _ZN2CA11Transaction6commitEv +
292
12  QuartzCore                          0x004897d5
_ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 99
13  CoreFoundation                      0x014bdfbb
__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 27
14  CoreFoundation                      0x014530e7 __CFRunLoopDoObservers + 295
15  CoreFoundation                      0x0141bbd7 __CFRunLoopRun + 1575
16  CoreFoundation                      0x0141b240 CFRunLoopRunSpecific + 208
17  CoreFoundation                      0x0141b161 CFRunLoopRunInMode + 97
18  GraphicsServices                    0x01efa268 GSEventRunModal + 217
19  GraphicsServices                    0x01efa32d GSEventRun + 115
20  UIKit                               0x0075642e UIApplicationMain + 1160
21  ThemeCatcher                        0x000021c9 main + 121
22  ThemeCatcher                        0x00002145 start + 53
23  ???                                 0x00000001 0x0 + 1

)

terminate called after throwing an instance of 'NSException'
Current language:  auto; currently objective-c
(gdb)


问:
Incorrect results drawing horizontal and vertical lines to the LFB returned by VBE
I finally managed to draw a cyan pixel on the screen using the VESA BIOS Extensions (1920px * 1080px, 24bpp).

```<code>;esi = bytes per scan line
;edx = physical address of linear framebuffer memory.
;ebx = x coord * 3
;ecx = y coord

DrawPixel:
    push edx
    mov edx, 0
    mov eax, 0
    lea eax, [esi]
    ;mov ecx, 0
    mul ecx
    add eax, ebx
    jmp draw

draw:
    pop edx
    add edx, eax
    mov ebx, 0x3296fa

    mov [edx], ebx
    ret
</code>```

I tried to draw a cyan horizontal line on the screen using a "for loop" this way:

```<code>mov edi, 1920
call drawLoop
jmp $

drawLoop:
    dec edi                                       ;decrease edi
    cmp edi, 0                                    ;is edi equal to zero?
    jl doneLoop                                   ;then return
    imul ebx, edi, 3                              ;multiply edi by three and save the result in ebx
    mov ecx, 0                                    ;y = 0
    mov esi, ModeInfoBlock + 10h
    mov edx, dword[ModeInfoBlock + 28h]
    call DrawPixel                                ;Draw it!
    jmp drawLoop                                  ;run this again

doneLoop:
    ret
</code>```

However, this doesn't work: it draws a green line instead.

When I try to draw a vertical line again with the draw/draw pixel code, it doesn't work either. It plots pixels with random colors everywhere. Here's how I use the DrawPixel function to draw a vertical line:

```<code>%include "../kernel/Services/Display/display.asm"

kernel:
    mov edi, 1080
    call drawLoop
    jmp $

drawLoop:
    dec edi
    cmp edi, 0
    jl doneLoop
    mov ecx, edi
    mov ebx, 0
    mov esi, ModeInfoBlock + 10h
    mov edx, dword[ModeInfoBlock + 28h]
    call DrawPixel
    jmp drawLoop

doneLoop:
    ret
</code>```

Any way to solve these problems?

答:
Drawing Horizontal Line

Based on comments I solved my problem with drawing the horizontal line by only writing 3 bytes to the video display instead of 4 bytes for each pixel. The extra byte was altering the color of the next pixel on the screen. My revised code looks like:

```<code>DrawPixel:
    push edx
    mov edx, 0
    mov eax, 0
    mov eax, esi
    mul ecx
    add eax, ebx
    jmp draw

draw:
    pop edx
    add edx, eax
    mov word[edx], 0x96fa
    mov byte[edx + 2], 0x32
    ret
</code>```

Drawing Vertical Line

In the code that generates a vertical line I managed to fix the issue by replacing mov esi, ModeInfoBlock + 10h with movzx esi, word[ModeInfoBlock + 10h].

Because the movzx instruction moves the 16bit bytesPerScanLine value into the 32bit esi register and fills the rest with zeros. It stands for "move zero extend".

My revised vertical drawing code:

```<code>%include "../kernel/Services/Display/display.asm"
kernel:
    mov edi, 1920
    call drawLoop
    jmp $

drawLoop:
    dec edi
    cmp edi, 0
    jl doneLoop
    imul ebx, edi, 3
    mov ecx, edi
    movzx esi, word[ModeInfoBlock + 10h]
    mov edx, dword[ModeInfoBlock + 28h]
    call DrawPixel
    jmp drawLoop

doneLoop:
    ret
</code>```

These are my final drawing functions:

```<code>;esi = bytes per scan line
;edx = physical address of linear framebuffer memory.
;ebx = x coord * 3
;ecx = y coord

DrawPixel:
    push edx
    mov edx, 0
    mov eax, 0
    mov eax, esi
    mul ecx
    add eax, ebx
    jmp draw

draw:
    pop edx
    add edx, eax
    mov word[edx], 0x96fa
    mov byte[edx + 2], 0x32
    ret
</code>```

Body:
I finally managed to draw a cyan pixel on the screen using the VESA BIOS Extensions (1920px * 1080px, 24bpp).

;esi = bytes per scan line
;edx = physical address of linear framebuffer memory.
;ebx = x coord * 3
;ecx = y coord

DrawPixel:
    push edx
    mov edx, 0
    mov eax, 0
    lea eax, [esi]
    ;mov ecx, 0
    mul ecx
    add eax, ebx
    jmp draw

draw:
    pop edx
    add edx, eax
    mov ebx, 0x3296fa

    mov [edx], ebx
    ret

I tried to draw a cyan horizontal line on the screen using a "for loop" this way:

mov edi, 1920
call drawLoop
jmp $

drawLoop:
    dec edi                                       ;decrease edi
    cmp edi, 0                                    ;is edi equal to zero?
    jl doneLoop                                   ;then return
    imul ebx, edi, 3                              ;multiply edi by three and save the result in ebx
    mov ecx, 0                                    ;y = 0
    mov esi, ModeInfoBlock + 10h
    mov edx, dword[ModeInfoBlock + 28h]
    call DrawPixel                                ;Draw it!
    jmp drawLoop                                  ;run this again

doneLoop:
    ret

However, this doesn't work: it draws a green line instead.

When I try to draw a vertical line again with the draw/draw pixel code, it doesn't work either. It plots pixels with random colors everywhere. Here's how I use the DrawPixel function to draw a vertical line:

%include "../kernel/Services/Display/display.asm"

kernel:
    mov edi, 1080
    call drawLoop
    jmp $

drawLoop:
    dec edi
    cmp edi, 0
    jl doneLoop
    mov ecx, edi
    mov ebx, 0
    mov esi, ModeInfoBlock + 10h
    mov edx, dword[ModeInfoBlock + 28h]
    call DrawPixel
    jmp drawLoop

doneLoop:
    ret

Any way to solve these problems?

Body:
Drawing Horizontal Line

Based on comments I solved my problem with drawing the horizontal line by only writing 3 bytes to the video display instead of 4 bytes for each pixel. The extra byte was altering the color of the next pixel on the screen. My revised code looks like:

DrawPixel:
    push edx
    mov edx, 0
    mov eax, 0
    mov eax, esi
    mul ecx
    add eax, ebx
    jmp draw

draw:
    pop edx
    add edx, eax
    mov word[edx], 0x96fa
    mov byte[edx + 2], 0x32
    ret

Drawing Vertical Line

In the code that generates a vertical line I managed to fix the issue by replacing mov esi, ModeInfoBlock + 10h with movzx esi, word[ModeInfoBlock + 10h].

Because the movzx instruction moves the 16bit bytesPerScanLine value into the 32bit esi register and fills the rest with zeros. It stands for "move zero extend".

My revised vertical drawing code:

%include "../kernel/Services/Display/display.asm"
kernel:
    mov edi, 1920
    call drawLoop
    jmp $

drawLoop:
    dec edi
    cmp edi, 0
    jl doneLoop
    imul ebx, edi, 3
    mov ecx, edi
    movzx esi, word[ModeInfoBlock + 10h]
    mov edx, dword[ModeInfoBlock + 28h]
    call DrawPixel
    jmp drawLoop

doneLoop:
    ret

These are my final drawing functions:

;esi = bytes per scan line
;edx = physical address of linear framebuffer memory.
;ebx = x coord * 3
;ecx = y coord

DrawPixel:
    push edx
    mov edx, 0
    mov eax, 0
    mov eax, esi
    mul ecx
    add eax, ebx
    jmp draw

draw:
    pop edx
    add edx, eax
    mov word[edx], 0x96fa
    mov byte[edx + 2], 0x32
    ret


问:
ASP.Net XUnit check if list of objects cointains a specific object
I am trying to add unit tests to my project. Some of these tests are checking if a list of objects does of does not contain an object. For checking if a list contains an object i've tried Assert.Contains(MyList, ExpectedObject), but it still gives an error that says that the list does not contain this object. Even when i debug the test i can see that the object is correctly added to the list.

The same happens with Assert.DoesNotContain(MyList, ExpectedObject). When i remove an item from the list and do this check it does say that it not in the list. But when i no longer remove the item, it still says that it is no longer in the list. Even though it is still in the list.

When i try it with a test list:List<string>. and do the same operations of adding and removing items, and then checking if these items are in the list or not. It does work.
Maybe Assert.Contains does not work for lists of objects. But the compiler does not give any errors. And i've also already checked if the ExpectedObject is the same type as the objects in the list.

Is there maybe another way of checking if an object is or isn't in a list.
any help is appreciated.

答:
I have faced a similar problem before and I used fluentAssertions to solve it.

So for example if you have a list of objects called myList, this snipped should do the trick.

```<code>myList.Should().Contain(expectedItem);
</code>```

There is more info on collections here: https://fluentassertions.com/collections/

The other option is to loop through the list and check if any of the objects are equal to your object. When doing this, if you use the ShouldBeEquivalentTo() method you will not need to check equality of every property. This is very useful if your object is large or nested, since this method checks each property recursively.

```<code>actual.Should().BeEquivalentTo(expected);
</code>```

There is more information on this here: https://fluentassertions.com/objectgraphs/

I like using fluentAssetions because it makes my tests and assertions more readable, and also provides very clear messages when errors do occurs or assertions fail, so you find the problem faster.

Body:
I have faced a similar problem before and I used fluentAssertions to solve it.

So for example if you have a list of objects called myList, this snipped should do the trick.

myList.Should().Contain(expectedItem);

There is more info on collections here: https://fluentassertions.com/collections/

The other option is to loop through the list and check if any of the objects are equal to your object. When doing this, if you use the ShouldBeEquivalentTo() method you will not need to check equality of every property. This is very useful if your object is large or nested, since this method checks each property recursively.

actual.Should().BeEquivalentTo(expected);

There is more information on this here: https://fluentassertions.com/objectgraphs/

I like using fluentAssetions because it makes my tests and assertions more readable, and also provides very clear messages when errors do occurs or assertions fail, so you find the problem faster.


问:
Using the same method multiple times in a row
Context:

I'm using barba js to make some page transitions on a wordpress website, and i have to load some scripts everytime the page changes, mainly some js/css files from a wordpress plugin so that ajax search works. I made a method that receives the script src/href and then adds the element to the head.
the problem might be happenning from my poor code structure or from the library i dont know to be honest.

Problem:

The code only runs the first script i call, and as i said above, i dont know if its from my code or from the library !

Code:

At first i thought i needed some kinda of timeout for the code to work , so i did this

```<code>{
                namespace: 'product',
                beforeEnter(data) {
                    //loads styles
                    setTimeout(reloadStyles('ivory-search-styles-css', 'wp-content/plugins/add-search-to-menu/public/css/ivory-search.css?ver=4.4.7'), 500)

//loads javascript files.
                    setTimeout(reloadScripts('wp-content/plugins/add-search-to-menu/public/js/ivory-ajax-search.js?ver=4.4.7'), 800)
                    setTimeout(reloadScripts('/wp-content/plugins/add-search-to-menu/public/js/ivory-search.js?ver=4.4.7'), 1000)
                    setTimeout(reloadScripts('/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=5.1.7'), 1200)

                    searchTranslations()
                    // refresh breadcrumbs
                    let documentAjax = (new DOMParser()).parseFromString(data.next.html, 'text/html');
                    let breadcrumbsAjax = documentAjax.querySelector('.breadcrumbs')
                    let breadcrumbs = document.querySelector('.breadcrumbs')
                    breadcrumbs.innerHTML = breadcrumbsAjax.innerHTML;

                    logoPath.style.fill = "black"

                }
            },

</code>```

This is the original Code (Without the timeouts) :

```<code>{
                namespace: 'product',
                beforeEnter(data) {

                    reloadStyles('ivory-search-styles-css', '/wp-content/plugins/add-search-to-menu/public/css/ivory-search.css?ver=4.4.7')

                    reloadScripts('/wp-content/plugins/add-search-to-menu/public/js/ivory-ajax-search.js?ver=4.4.7')
                    reloadScripts('/wp-content/plugins/add-search-to-menu/public/js/ivory-search.js?ver=4.4.7')
                    reloadScripts('/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=5.1.7')

                    searchTranslations()
                    // refresh breadcrumbs
                    let documentAjax = (new DOMParser()).parseFromString(next.html, 'text/html');
                    let breadcrumbsAjax = documentAjax.querySelector('.breadcrumbs')
                    let breadcrumbs = document.querySelector('.breadcrumbs')
                    breadcrumbs.innerHTML = breadcrumbsAjax.innerHTML;

                    logoPath.style.fill = "black"

                }
            },
</code>```

Thanks in advance !

Edit:  This is the method

```<code>    const reloadScripts = (scrpSrc) => {

        console.log("Script loaded:  " + scrpSrc)

        var wpcf7 = { "apiSettings": { "root": "/wp-json\/contact-form-7\/v1", "namespace": "contact-form-7\/v1" } };

        let head = document.getElementsByTagName('head')[0]
        let script = document.createElement('script')

        script.src = scrpSrc;

        if (script != undefined || script != null) {
            head.removeChild(script)
            head.appendChild(script)
        }
        else head.appendChild(script)

    }
</code>```

答:
Try making the amendments below. the major change would be that you are checking the wrong variable before removing and adding the script. Check if the head contains a script and remove that. After that i made some changes to help the code be more readable and slightly drier.

const reloadScripts = (scrpSrc) => {
        console.log("Script loaded:  " + scrpSrc)
        const wpcf7 = {
          "apiSettings": {
            "root": "/wp-json\/contact-form-7\/v1",
            "namespace": "contact-form-7\/v1"
            }
          };
        let head = document.querySelector('head'),
          headScript = head.querySelector('[src="='+ scrpSrc +'"]'),
          script = document.createElement('script');
         //checking if head already has a script
        if (headScript != undefined || headScript != null) {
            head.removeChild(headScript);
        }
        //then always do this piece. not DRY to have it inside and outside the if stmt
        script.src = scrpSrc;
        head.appendChild(script)
    }```

Body:
Context:

I'm using barba js to make some page transitions on a wordpress website, and i have to load some scripts everytime the page changes, mainly some js/css files from a wordpress plugin so that ajax search works. I made a method that receives the script src/href and then adds the element to the head.
the problem might be happenning from my poor code structure or from the library i dont know to be honest.

Problem:

The code only runs the first script i call, and as i said above, i dont know if its from my code or from the library !

Code:

At first i thought i needed some kinda of timeout for the code to work , so i did this

{
                namespace: 'product',
                beforeEnter(data) {
                    //loads styles
                    setTimeout(reloadStyles('ivory-search-styles-css', 'wp-content/plugins/add-search-to-menu/public/css/ivory-search.css?ver=4.4.7'), 500)

//loads javascript files.
                    setTimeout(reloadScripts('wp-content/plugins/add-search-to-menu/public/js/ivory-ajax-search.js?ver=4.4.7'), 800)
                    setTimeout(reloadScripts('/wp-content/plugins/add-search-to-menu/public/js/ivory-search.js?ver=4.4.7'), 1000)
                    setTimeout(reloadScripts('/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=5.1.7'), 1200)

                    searchTranslations()
                    // refresh breadcrumbs
                    let documentAjax = (new DOMParser()).parseFromString(data.next.html, 'text/html');
                    let breadcrumbsAjax = documentAjax.querySelector('.breadcrumbs')
                    let breadcrumbs = document.querySelector('.breadcrumbs')
                    breadcrumbs.innerHTML = breadcrumbsAjax.innerHTML;

                    logoPath.style.fill = "black"

                }
            },

This is the original Code (Without the timeouts) :

{
                namespace: 'product',
                beforeEnter(data) {

                    reloadStyles('ivory-search-styles-css', '/wp-content/plugins/add-search-to-menu/public/css/ivory-search.css?ver=4.4.7')

                    reloadScripts('/wp-content/plugins/add-search-to-menu/public/js/ivory-ajax-search.js?ver=4.4.7')
                    reloadScripts('/wp-content/plugins/add-search-to-menu/public/js/ivory-search.js?ver=4.4.7')
                    reloadScripts('/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=5.1.7')

                    searchTranslations()
                    // refresh breadcrumbs
                    let documentAjax = (new DOMParser()).parseFromString(next.html, 'text/html');
                    let breadcrumbsAjax = documentAjax.querySelector('.breadcrumbs')
                    let breadcrumbs = document.querySelector('.breadcrumbs')
                    breadcrumbs.innerHTML = breadcrumbsAjax.innerHTML;

                    logoPath.style.fill = "black"

                }
            },

Thanks in advance !

Edit:  This is the method

    const reloadScripts = (scrpSrc) => {

        console.log("Script loaded:  " + scrpSrc)

        var wpcf7 = { "apiSettings": { "root": "/wp-json\/contact-form-7\/v1", "namespace": "contact-form-7\/v1" } };

        let head = document.getElementsByTagName('head')[0]
        let script = document.createElement('script')

        script.src = scrpSrc;

        if (script != undefined || script != null) {
            head.removeChild(script)
            head.appendChild(script)
        }
        else head.appendChild(script)

    }


问:
In a Svelte readable store array, How can I update only one item without touching the others?
I guess this question is more on JS sysntax, but I have a store array like this:

```<code>export const store = readable( {id: 0, value: 0} , set => {
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        set({id: 0, value: data});
    }
})
</code>```

The store defines its set method to update the value from a websockets connection.
How can I do the same but with a store array? Something like:

```<code>arr = [];
for(i=0; i<numberOfItems; i++) {
    arr = [...arr,{id: i, value: 0}];
}

export const store = readable( [{arr}] , set => {
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        var channel = data.channel;
        set({id: data.channel, value: data.value});
    }
})
</code>```

Here is where I dont manage to "set" o the array, and without having to declare the whole array every update.

答:
I think in your case what you want to save in the store is not an array, but an object, it would make easier this step. Something like:

```<code>export const store = readable({} , set => {
    let channels = {};
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function ({data}) {
        let { channel, value } = JSON.parse(data);

        // update `channels`
        channels = {...channels, [channel]: value };

        // set the new `channels` as store value
        set(channels)
    }
})
</code>```

Notice that in this way you will have directly the channel as key of the object: so if a channel already exists, it will be updated instead of added. And if it doesn't exists, it will be added.

In your subscriber you can therefore have something like:

```<code>store.subscribe(channels => {
  for (let [channel, value] of Object.entries(channels)) {
    console.log(`channel ${channel} received ${value}`);
  }
});
</code>```

As final note, consider that this code creates a new object every update to avoid side effect, that's common practice.
However, if you have a lot of data in the object and you're aware of the possible implication, you could just add / update the single key without duplicating the object every time, for performance / memory reason.

Hope it helps!

Body:
I guess this question is more on JS sysntax, but I have a store array like this:

export const store = readable( {id: 0, value: 0} , set => {
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        set({id: 0, value: data});
    }
})

The store defines its set method to update the value from a websockets connection.
How can I do the same but with a store array? Something like:

arr = [];
for(i=0; i<numberOfItems; i++) {
    arr = [...arr,{id: i, value: 0}];
}

export const store = readable( [{arr}] , set => {
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        var channel = data.channel;
        set({id: data.channel, value: data.value});
    }
})

Here is where I dont manage to "set" o the array, and without having to declare the whole array every update.

Body:
I think in your case what you want to save in the store is not an array, but an object, it would make easier this step. Something like:

export const store = readable({} , set => {
    let channels = {};
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function ({data}) {
        let { channel, value } = JSON.parse(data);

        // update `channels`
        channels = {...channels, [channel]: value };

        // set the new `channels` as store value
        set(channels)
    }
})

Notice that in this way you will have directly the channel as key of the object: so if a channel already exists, it will be updated instead of added. And if it doesn't exists, it will be added.

In your subscriber you can therefore have something like:

store.subscribe(channels => {
  for (let [channel, value] of Object.entries(channels)) {
    console.log(`channel ${channel} received ${value}`);
  }
});

As final note, consider that this code creates a new object every update to avoid side effect, that's common practice.
However, if you have a lot of data in the object and you're aware of the possible implication, you could just add / update the single key without duplicating the object every time, for performance / memory reason.

Hope it helps!


问:
Is there a way I can create infinite closures in JavaScript
I was presented with question and I had no idea how to do it

add() - > returns 0

add(1)() -> returns 1

add(1)(2)() -> returns 3

add(1)(2)(3)(4)() -> 10

Basically it can go on

答:
Here is my one line solution if you love aesthetics

const add = (val) => (val ? (arg) => (arg ? add(val + arg) : val) : 0);

console.log(add(1)(2)(3)())```
</div>
</div>
</p>
<p>For Readability:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const add = (val) => {
  if (val) {
    return (arg) => {
      if (arg) {
        return add(val + arg);
      } else {
        return val;
      }
    };
  }
  return 0;
};

console.log(add(1)(2)(3)())</code>```

Edit : Explaination

I'll try to explain it in a simple way

lets break it down with a example add(1)(2)(3)()

So it happens like this

add(1) is evaluated first

add(1)  -> returns a function (say _add())

_add() is a closure so it has access to the val variable (with value  1) and has its own parameter args with value 2

_add(2) ->  calls add() again with the result of the addition (val + args)

add(1)(2)(3)() becomes -> _add(2)(3)()

_add(2) checks if it has a parameter args and if it does then it computes val + args and returns add(val +args) else 0

_add(2)(3)() becomes -> add(3)(3)()

add(3) -> _add()

_add(3) -> val + args -> add(val+args) -> add(6)

add(3)(3)() becomes -> _add(6)()

add(6)() -> returns _add()

_add() this time no parameter so return the value

I hope I was able to explain, comment if you have any doubts, I'll try my best

Body:
Here is my one line solution if you love aesthetics

const add = (val) => (val ? (arg) => (arg ? add(val + arg) : val) : 0);

console.log(add(1)(2)(3)())

For Readability:

const add = (val) => {
  if (val) {
    return (arg) => {
      if (arg) {
        return add(val + arg);
      } else {
        return val;
      }
    };
  }
  return 0;
};

console.log(add(1)(2)(3)())

Edit : Explaination

I'll try to explain it in a simple way

lets break it down with a example add(1)(2)(3)()

So it happens like this

add(1) is evaluated first

add(1)  -> returns a function (say _add())

_add() is a closure so it has access to the val variable (with value  1) and has its own parameter args with value 2

_add(2) ->  calls add() again with the result of the addition (val + args)

add(1)(2)(3)() becomes -> _add(2)(3)()

_add(2) checks if it has a parameter args and if it does then it computes val + args and returns add(val +args) else 0

_add(2)(3)() becomes -> add(3)(3)()

add(3) -> _add()

_add(3) -> val + args -> add(val+args) -> add(6)

add(3)(3)() becomes -> _add(6)()

add(6)() -> returns _add()

_add() this time no parameter so return the value

I hope I was able to explain, comment if you have any doubts, I'll try my best


问:
Return only values between two values in array?
I've got this array.

```<code>const array = [0, 5.476, 11.251, 31.916, 44.007, 53.911, 58.628, 65.729, 75.222, 88.849, 100]
</code>```

How would I go about only returning values between 23.419 and 46.839 without calling by index. I wouldn't be surprised if there's a native function for this, as to why my question is short. Thanks.

答:
Simply use filter function :

array.filter(item => item >= 23.419 && item <= 46.839);
```

Body:
I've got this array.

const array = [0, 5.476, 11.251, 31.916, 44.007, 53.911, 58.628, 65.729, 75.222, 88.849, 100]

How would I go about only returning values between 23.419 and 46.839 without calling by index. I wouldn't be surprised if there's a native function for this, as to why my question is short. Thanks.


问:
FILE *tmp = tmpfile() always generates NULL pointer in C?
I have the following code:

```<code>char buffer[8];

int main(int argc, char *argv[]) {
    FILE *input, *output, *tempFile;
    input = fopen(argv[1], "rb");
    if (input == NULL) {
        printf("%s", strerror(2));
        exit(EXIT_FAILURE);
    }
    else {
        output = fopen(argv[2], "wb");
        if (output == NULL) {
            printf("%s", strerror(2));
            exit(EXIT_FAILURE);
        }
    }
    tempFile = tmpfile();
    for (int i = 0; i < 8; i++) {
        fputc(buffer[i], tempFile);
        fillBuffer(tempFile);
        printf("%s", buffer);
    }
    if (tempFile == NULL) {
        printf("Unable to create temp file");
        return 0;
    }
}
</code>```

Some things have been left out but I believe that this is the relevant portion. The buffer[] array is valid. If in the for loop I use

fputc(buffer[i], output);

The correct info gets stored in the output file. Whenever I run this program I get a bunch of null results followed by "Unable to create temp file". Advice?

答:
I should use:

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

int main()
{
    FILE *f = tmpfile();
    if (!f) {
        fprintf(stderr,
                "couldn't create tmpfile: %s (errno = %d)\n",
                strerror(errno), errno);
        exit(EXIT_FAILURE);
    }
}
</code>```

in order to know the reason of the failure to create a temporary file.  I've just run it on my system and it creates the file correctly.  (and this should be a Minimal, Complete and Verifiable example as I recommend you to read in my comment to your question)  but most probably had you have done this, you should never have asked this question (as the reason probably is shown in the output of your program).

Body:
I have the following code:

char buffer[8];

int main(int argc, char *argv[]) {
    FILE *input, *output, *tempFile;
    input = fopen(argv[1], "rb");
    if (input == NULL) {
        printf("%s", strerror(2));
        exit(EXIT_FAILURE);
    }
    else {
        output = fopen(argv[2], "wb");
        if (output == NULL) {
            printf("%s", strerror(2));
            exit(EXIT_FAILURE);
        }
    }
    tempFile = tmpfile();
    for (int i = 0; i < 8; i++) {
        fputc(buffer[i], tempFile);
        fillBuffer(tempFile);
        printf("%s", buffer);
    }
    if (tempFile == NULL) {
        printf("Unable to create temp file");
        return 0;
    }
}

Some things have been left out but I believe that this is the relevant portion. The buffer[] array is valid. If in the for loop I use

fputc(buffer[i], output);

The correct info gets stored in the output file. Whenever I run this program I get a bunch of null results followed by "Unable to create temp file". Advice?

Body:
I should use:

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

int main()
{
    FILE *f = tmpfile();
    if (!f) {
        fprintf(stderr,
                "couldn't create tmpfile: %s (errno = %d)\n",
                strerror(errno), errno);
        exit(EXIT_FAILURE);
    }
}

in order to know the reason of the failure to create a temporary file.  I've just run it on my system and it creates the file correctly.  (and this should be a Minimal, Complete and Verifiable example as I recommend you to read in my comment to your question)  but most probably had you have done this, you should never have asked this question (as the reason probably is shown in the output of your program).


问:
Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type
In testing my UserRouter, I am using a json file

data.json

```<code>[
  {
    "id": 1,
    "name": "Luke Cage",
    "aliases": ["Carl Lucas", "Power Man", "Mr. Bulletproof", "Hero for Hire"],
    "occupation": "bartender",
    "gender": "male",
    "height": {
      "ft": 6,
      "in": 3
    },
    "hair": "bald",
    "eyes": "brown",
    "powers": [
      "strength",
      "durability",
      "healing"
    ]
  },
  {
  ...
  }
]
</code>```

Building my app, I get the following TS error

```<code>ERROR in ...../UserRouter.ts
(30,27): error TS7006: Parameter 'user' implicitly has an 'any' type.
</code>```

UserRouter.ts

```<code>import {Router, Request, Response, NextFunction} from 'express';
const Users = require('../data');

export class UserRouter {
  router: Router;

  constructor() {
  ...
  }

  /**
   * GET one User by id
   */
  public getOne(req: Request, res: Response, _next: NextFunction) {
    let query = parseInt(req.params.id);
 /*[30]->*/let user = Users.find(user => user.id === query);
    if (user) {
      res.status(200)
        .send({
          message: 'Success',
          status: res.status,
          user
        });
    }
    else {
      res.status(404)
        .send({
          message: 'No User found with the given id.',
          status: res.status
        });
    }
  }

}

const userRouter = new UserRouter().router;
export default userRouter;
</code>```

答:
Minimal error reproduction

```<code>export const users = require('../data'); // presumes @types/node are installed
const foundUser = users.find(user => user.id === 42);
// error: Parameter 'user' implicitly has an 'any' type.ts(7006)
</code>```

Recommended solution: --resolveJsonModule

The simplest way for your case is to use --resolveJsonModule compiler option:
```<code>import users from "./data.json" // `import` instead of `require`
const foundUser = users.find(user => user.id === 42); // user is strongly typed, no `any`!
</code>```

There are some alternatives for other cases than static JSON import.

Option 1: Explicit user type (simple, no checks)

```<code>type User = { id: number; name: string /* and others */ }
const foundUser = users.find((user: User) => user.id === 42)
</code>```

Option 2: Type guards (middleground)

Type guards are a good middleground between simplicity and strong types:
```<code>function isUserArray(maybeUserArr: any): maybeUserArr is Array<User> {
  return Array.isArray(maybeUserArr) && maybeUserArr.every(isUser)
}

function isUser(user: any): user is User {
  return "id" in user && "name" in user
}

if (isUserArray(users)) {
  const foundUser = users.find((user) => user.id === 42)
}
</code>```
You can even switch to assertion functions (TS 3.7+) to get rid of if and throw an error instead.
```<code>function assertIsUserArray(maybeUserArr: any): asserts maybeUserArr is Array<User> {
  if(!isUserArray(maybeUserArr)) throw Error("wrong json type")
}

assertIsUserArray(users)
const foundUser = users.find((user) => user.id === 42) // works
</code>```

Option 3: Runtime type system library (sophisticated)

A runtime type check library like io-ts or ts-runtime can be integrated for more complex cases.

Not recommended solutions

noImplicitAny: false undermines many useful checks of the type system:
```<code>function add(s1, s2) { // s1,s2 implicitely get `any` type
  return s1 * s2 // `any` type allows string multiplication and all sorts of types :(
}
add("foo", 42)
</code>```

Also better provide an explicit User type for user. This will avoid propagating any to inner layer types. Instead typing and validating is kept in the JSON processing code of the outer API layer.

Body:
In testing my UserRouter, I am using a json file

data.json

[
  {
    "id": 1,
    "name": "Luke Cage",
    "aliases": ["Carl Lucas", "Power Man", "Mr. Bulletproof", "Hero for Hire"],
    "occupation": "bartender",
    "gender": "male",
    "height": {
      "ft": 6,
      "in": 3
    },
    "hair": "bald",
    "eyes": "brown",
    "powers": [
      "strength",
      "durability",
      "healing"
    ]
  },
  {
  ...
  }
]

Building my app, I get the following TS error

ERROR in ...../UserRouter.ts
(30,27): error TS7006: Parameter 'user' implicitly has an 'any' type.

UserRouter.ts

import {Router, Request, Response, NextFunction} from 'express';
const Users = require('../data');

export class UserRouter {
  router: Router;

  constructor() {
  ...
  }

  /**
   * GET one User by id
   */
  public getOne(req: Request, res: Response, _next: NextFunction) {
    let query = parseInt(req.params.id);
 /*[30]->*/let user = Users.find(user => user.id === query);
    if (user) {
      res.status(200)
        .send({
          message: 'Success',
          status: res.status,
          user
        });
    }
    else {
      res.status(404)
        .send({
          message: 'No User found with the given id.',
          status: res.status
        });
    }
  }

}

const userRouter = new UserRouter().router;
export default userRouter;

Body:
Minimal error reproduction

export const users = require('../data'); // presumes @types/node are installed
const foundUser = users.find(user => user.id === 42);
// error: Parameter 'user' implicitly has an 'any' type.ts(7006)

Recommended solution: --resolveJsonModule

The simplest way for your case is to use --resolveJsonModule compiler option:

import users from "./data.json" // `import` instead of `require`
const foundUser = users.find(user => user.id === 42); // user is strongly typed, no `any`!

There are some alternatives for other cases than static JSON import.

Option 1: Explicit user type (simple, no checks)

type User = { id: number; name: string /* and others */ }
const foundUser = users.find((user: User) => user.id === 42)

Option 2: Type guards (middleground)

Type guards are a good middleground between simplicity and strong types:

function isUserArray(maybeUserArr: any): maybeUserArr is Array<User> {
  return Array.isArray(maybeUserArr) && maybeUserArr.every(isUser)
}

function isUser(user: any): user is User {
  return "id" in user && "name" in user
}

if (isUserArray(users)) {
  const foundUser = users.find((user) => user.id === 42)
}

You can even switch to assertion functions (TS 3.7+) to get rid of if and throw an error instead.

function assertIsUserArray(maybeUserArr: any): asserts maybeUserArr is Array<User> {
  if(!isUserArray(maybeUserArr)) throw Error("wrong json type")
}

assertIsUserArray(users)
const foundUser = users.find((user) => user.id === 42) // works

Option 3: Runtime type system library (sophisticated)

A runtime type check library like io-ts or ts-runtime can be integrated for more complex cases.

Not recommended solutions

noImplicitAny: false undermines many useful checks of the type system:

function add(s1, s2) { // s1,s2 implicitely get `any` type
  return s1 * s2 // `any` type allows string multiplication and all sorts of types :(
}
add("foo", 42)

Also better provide an explicit User type for user. This will avoid propagating any to inner layer types. Instead typing and validating is kept in the JSON processing code of the outer API layer.


问:
Pandas: How to find whether address in one dataframe is from city and state in another dataframe?
I have a dataframe of addresses as below:

```<code>main_df =
                                          address
0               3, my_street, Mumbai, Maharashtra
1                 Bangalore Karnataka 45th Avenue
2  TelanganaHyderabad some_street, some apartment
</code>```

And I have a dataframe with city and state as below (note few states have cities with same names too:

```<code>city_state_df =
         city        state
0      Mumbai  Maharashtra
1  Ahmednagar  Maharashtra
2  Ahmednagar        Bihar
3   Bangalore    Karnataka
4   Hyderabad    Telangana
</code>```

I want to have a mapping of city and state next to each address. I am able to do so with iterrows() with nested for loops. However, both take more than an hour each for mere 15k records. What is the optimum way of achieving this considering addresses are randomly written and multiple states have same city name?

My code below:

```<code>main_df = pd.DataFrame({'address': ['3, my_street, Mumbai, Maharashtra', 'Bangalore Karnataka 45th Avenue', 'TelanganaHyderabad some_street, some apartment']})
city_state_df = pd.DataFrame({'city': ['Mumbai', 'Ahmednagar', 'Ahmednagar', 'Bangalore', 'Hyderabad'],
                     'state': ['Maharashtra', 'Maharashtra', 'Bihar', 'Karnataka', 'Telangana']})

df['city'] = np.nan
df['state'] = np.nan

for i, df_row in df.iterrows():
    for j, city_row in city_state_df.iterrows():
        if city_row['city'] in df_row['address']:
            city_filtered = city[city['city'] == city_row['city']]
            for k, fil_row in city_filtered.iterrows():
                if fil_row['state'] in df_row['address']:
                    df_row['city'] = fil_row['city']
                    df_row['state'] = fil_row['state']
                    break
            break

</code>```

答:
Hello maybe something like this:</p>

```<code>main_df = main_df.reindex(columns=[*main_df.columns.tolist(), 'state', 'city'],fill_value=None)

for i, row in city_state_df.iterrows():
    main_df.loc[(main_df.address.str.contains(row.city)) & \
                 (main_df.address.str.contains(row.state)), \
                ['city', 'state']] = [row.city, row.state]
</code>```

Body:
I have a dataframe of addresses as below:

main_df =
                                          address
0               3, my_street, Mumbai, Maharashtra
1                 Bangalore Karnataka 45th Avenue
2  TelanganaHyderabad some_street, some apartment

And I have a dataframe with city and state as below (note few states have cities with same names too:

city_state_df =
         city        state
0      Mumbai  Maharashtra
1  Ahmednagar  Maharashtra
2  Ahmednagar        Bihar
3   Bangalore    Karnataka
4   Hyderabad    Telangana

I want to have a mapping of city and state next to each address. I am able to do so with iterrows() with nested for loops. However, both take more than an hour each for mere 15k records. What is the optimum way of achieving this considering addresses are randomly written and multiple states have same city name?

My code below:

main_df = pd.DataFrame({'address': ['3, my_street, Mumbai, Maharashtra', 'Bangalore Karnataka 45th Avenue', 'TelanganaHyderabad some_street, some apartment']})
city_state_df = pd.DataFrame({'city': ['Mumbai', 'Ahmednagar', 'Ahmednagar', 'Bangalore', 'Hyderabad'],
                     'state': ['Maharashtra', 'Maharashtra', 'Bihar', 'Karnataka', 'Telangana']})

df['city'] = np.nan
df['state'] = np.nan

for i, df_row in df.iterrows():
    for j, city_row in city_state_df.iterrows():
        if city_row['city'] in df_row['address']:
            city_filtered = city[city['city'] == city_row['city']]
            for k, fil_row in city_filtered.iterrows():
                if fil_row['state'] in df_row['address']:
                    df_row['city'] = fil_row['city']
                    df_row['state'] = fil_row['state']
                    break
            break

Body:
Hello maybe something like this:

main_df = main_df.reindex(columns=[*main_df.columns.tolist(), 'state', 'city'],fill_value=None)

for i, row in city_state_df.iterrows():
    main_df.loc[(main_df.address.str.contains(row.city)) & \
                 (main_df.address.str.contains(row.state)), \
                ['city', 'state']] = [row.city, row.state]


问:
How to trace requests in normal Spring micro service app (non Spring boot)?
How to trace requests in normal Spring micro service app (non Spring boot) ?
I know Spring boot give Sleuth but I wanted to do the similar for non Spring boot app, its a normal Spring app. When request passes through the different micro-service, we want to trace them.</p>

答:
You need to configure the Spring app to use a logback.xml file for logging.

Create an interceptor that would set additional MDC contexts as Sleuth does

You need to pass the same additional MDC contexts to other services in HTTP headers.

Log back Configuration

```<code><configuration>
      <appender class="ch.qos.logback.core.ConsoleAppender" name="STDOUT">
        <encoder>
          <pattern>[%date{dd-MM-yyyy HH:mm:ss.SSS}]  [%thread] %-5level %X{traceId:-} %X{spanId:-} ${PID:-} %logger{36} - %msg%n</pattern>
        </encoder>
      </appender>
      <appender class="ch.qos.logback.core.rolling.RollingFileAppender" name="FILE">
        <encoder>
          <pattern>[%date{dd-MM-yyyy HH:mm:ss.SSS}]  [%thread] %-5level %X{traceId:-} %X{spanId:-} ${PID:-} %logger{36} - %msg%n</pattern>
        </encoder>
        <file>log/app.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
          <fileNamePattern>log/app.%d{yyyy-MM-dd-HH}.log</fileNamePattern>
          <maxHistory>30</maxHistory>
          <totalSizeCap>200MB</totalSizeCap>
        </rollingPolicy>
      </appender>

      <logger level="INFO" name="root">
        <appender-ref ref="STDOUT"/>
      </logger>
    </configuration>
</code>```

Interceptor that sets the MDC context for tracing.

```<code>@Slf4j
public class LoggerInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    String traceId = request.getHeader("TRACE_ID");
    String spanId = request.getHeader("SPAN_ID");
    if (traceId == null) {
      traceId = UUID.randomUUID().toString();
    }
    // You can generate new spanId or use the same one
    if (spanId == null) {
      spanId = UUID.randomUUID().toString();
    }
    MDC.put("TRACE_ID", traceId);
    MDC.put("traceId", traceId);
    MDC.put("SPAN_ID", spanId);
    MDC.put("spanId", spanId);
    log.info("[preHandle] HTTP: {}, URL: {} ", request.getMethod(), request.getRequestURI());
    return true;
  }

  @Override
  public void postHandle(
      HttpServletRequest request,
      HttpServletResponse response,
      Object handler,
      ModelAndView modelAndView)
      throws Exception {
    log.info("[postHandle] HTTP: {}, URL: {} ", request.getMethod(), request.getRequestURI());
    MDC.clear();
  }
}
</code>```

If you want to measure execution time then add a profiler for the same. Read more about the same at the example at Profiling Spring Boot, it says specific about Spring boot but you can use the same approach in Spring app as well.

If you're using RestTemplate then you can set these headers.

```<code>  HttpHeaders headers = new HttpHeaders();
  headers.set("TRACE_ID", MDC.get("TRACE_ID"));
  headers.set("SPAN_ID", MDC.get("SPAN_ID"));

  HttpEntity entity = new HttpEntity(headers);
  RestTemplate restTemplate = new RestTemplate();
  SimpleClientHttpRequestFactory rf =
      (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
  rf.setReadTimeout(2 * Constants.ONE_MILLI_INT);
  rf.setConnectTimeout(2 * Constants.ONE_MILLI_INT);
  ResponseEntity<String> response =
      restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
</code>```

In this simple example, TRACE_ID and SPAN_ID headers have been set.

Body:
You need to configure the Spring app to use a logback.xml file for logging.

Create an interceptor that would set additional MDC contexts as Sleuth does

You need to pass the same additional MDC contexts to other services in HTTP headers.

Log back Configuration

<configuration>
      <appender class="ch.qos.logback.core.ConsoleAppender" name="STDOUT">
        <encoder>
          <pattern>[%date{dd-MM-yyyy HH:mm:ss.SSS}]  [%thread] %-5level %X{traceId:-} %X{spanId:-} ${PID:-} %logger{36} - %msg%n</pattern>
        </encoder>
      </appender>
      <appender class="ch.qos.logback.core.rolling.RollingFileAppender" name="FILE">
        <encoder>
          <pattern>[%date{dd-MM-yyyy HH:mm:ss.SSS}]  [%thread] %-5level %X{traceId:-} %X{spanId:-} ${PID:-} %logger{36} - %msg%n</pattern>
        </encoder>
        <file>log/app.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
          <fileNamePattern>log/app.%d{yyyy-MM-dd-HH}.log</fileNamePattern>
          <maxHistory>30</maxHistory>
          <totalSizeCap>200MB</totalSizeCap>
        </rollingPolicy>
      </appender>

      <logger level="INFO" name="root">
        <appender-ref ref="STDOUT"/>
      </logger>
    </configuration>

Interceptor that sets the MDC context for tracing.

@Slf4j
public class LoggerInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    String traceId = request.getHeader("TRACE_ID");
    String spanId = request.getHeader("SPAN_ID");
    if (traceId == null) {
      traceId = UUID.randomUUID().toString();
    }
    // You can generate new spanId or use the same one
    if (spanId == null) {
      spanId = UUID.randomUUID().toString();
    }
    MDC.put("TRACE_ID", traceId);
    MDC.put("traceId", traceId);
    MDC.put("SPAN_ID", spanId);
    MDC.put("spanId", spanId);
    log.info("[preHandle] HTTP: {}, URL: {} ", request.getMethod(), request.getRequestURI());
    return true;
  }

  @Override
  public void postHandle(
      HttpServletRequest request,
      HttpServletResponse response,
      Object handler,
      ModelAndView modelAndView)
      throws Exception {
    log.info("[postHandle] HTTP: {}, URL: {} ", request.getMethod(), request.getRequestURI());
    MDC.clear();
  }
}

If you want to measure execution time then add a profiler for the same. Read more about the same at the example at Profiling Spring Boot, it says specific about Spring boot but you can use the same approach in Spring app as well.

If you're using RestTemplate then you can set these headers.

  HttpHeaders headers = new HttpHeaders();
  headers.set("TRACE_ID", MDC.get("TRACE_ID"));
  headers.set("SPAN_ID", MDC.get("SPAN_ID"));

  HttpEntity entity = new HttpEntity(headers);
  RestTemplate restTemplate = new RestTemplate();
  SimpleClientHttpRequestFactory rf =
      (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
  rf.setReadTimeout(2 * Constants.ONE_MILLI_INT);
  rf.setConnectTimeout(2 * Constants.ONE_MILLI_INT);
  ResponseEntity<String> response =
      restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

In this simple example, TRACE_ID and SPAN_ID headers have been set.