问:
How to add or remove an item from state array in react
I have state array and when user click on an item , item should be added to state array. I use type script, interface for data model.

This is the code I used

```<code>this.setState(prevState => ({
  this.state.activeItemList: [...prevState.activeItemList, newItem]
}))
</code>```

Interface

```<code>interface IState {     activeItemList?: IItem[] | null;  }
</code>```

Is this the correct way?

答:
Actually, I would write it as

```<code>this.setState(prevState => ({
  ...prevState,
  activeItemList: [...prevState.activeItemList, newItem]
}))
</code>```

With the current definition of IState, it means the exact same thing, but if IState ever changes, I'm prepare.  Plus, the code emphasizes that all it's doing is adding newItem and not erasing anything else.

Removing I would implement as:

```<code>this.setState(prevState => ({
  ...prevState,
  activeItemList: prevState.activeItemList.filter(item => item !== oldItem)
}))
</code>```

Body:
I have state array and when user click on an item , item should be added to state array. I use type script, interface for data model.

This is the code I used

this.setState(prevState => ({
  this.state.activeItemList: [...prevState.activeItemList, newItem]
}))

Interface

interface IState {     activeItemList?: IItem[] | null;  }

Is this the correct way?

Body:
Actually, I would write it as

this.setState(prevState => ({
  ...prevState,
  activeItemList: [...prevState.activeItemList, newItem]
}))

With the current definition of IState, it means the exact same thing, but if IState ever changes, I'm prepare.  Plus, the code emphasizes that all it's doing is adding newItem and not erasing anything else.

Removing I would implement as:

this.setState(prevState => ({
  ...prevState,
  activeItemList: prevState.activeItemList.filter(item => item !== oldItem)
}))


来源: stackexchange

问:
How to add object member in array?
I have json file like this.

Use nlohmann.

```<code>{"Fans": [
        {
            "MemberID": "0",
            "Name": "Fan 0 ABC",
            "Reading": 30
        },
        {
            "MemberID": "1",
            "Name": "Fan 1 ABC",
            "Reading": 40,
            "Unit": "RPM" // add object
        }
]
}
</code>```

I want find "Fan 1" then add new object.

I can find index of Fans[].

But I don't know how to add object in.

```<code>nlohmann::json &tempArray = Resp->res.jsonValue[Fans];
for(auto &x : tempArray.items())
{
   auto &Value = x.value();
   auto iter = Value.find("Name");
   if(iter != Value.end())
   {
      std::string str = iter.value();
      if(str.find("Fan 1", 0) != std::string::npos)
      {
           // add object?
      }
   }
}
</code>```

答:
I had to restructure your code to produce a MCVE, but you can simply use operator[] to assign new fields to an object:

```<code>void modifyJson(json & j) {
    json &tempArray = j["Fans"];
    for(auto &x : tempArray)
    {
        auto iter = x.find("Name");
        if(iter != x.end())
        {
            std::string str = iter.value();
            if(str.find("Fan 1", 0) != std::string::npos)
            {
                x["Unit"] = "RPM";
                return;
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to add object member in array?

Body:
I have json file like this.

Use nlohmann.

{"Fans": [
        {
            "MemberID": "0",
            "Name": "Fan 0 ABC",
            "Reading": 30
        },
        {
            "MemberID": "1",
            "Name": "Fan 1 ABC",
            "Reading": 40,
            "Unit": "RPM" // add object
        }
]
}

I want find "Fan 1" then add new object.

I can find index of Fans[].

But I don't know how to add object in.

nlohmann::json &tempArray = Resp->res.jsonValue[Fans];
for(auto &x : tempArray.items())
{
   auto &Value = x.value();
   auto iter = Value.find("Name");
   if(iter != Value.end())
   {
      std::string str = iter.value();
      if(str.find("Fan 1", 0) != std::string::npos)
      {
           // add object?
      }
   }
}

Body:
I had to restructure your code to produce a MCVE, but you can simply use operator[] to assign new fields to an object:

void modifyJson(json & j) {
    json &tempArray = j["Fans"];
    for(auto &x : tempArray)
    {
        auto iter = x.find("Name");
        if(iter != x.end())
        {
            std::string str = iter.value();
            if(str.find("Fan 1", 0) != std::string::npos)
            {
                x["Unit"] = "RPM";
                return;
            }
        }
    }
}


问:
Binding json - formgroup
I have a form and I want to display data that comes from an API (JSon file) in mode readonly. Do you have tracks?
I take an example of a form:
Thank you

```<code><div class="col-sm-8 col-sm-offset-2">
  <form [formGroup]="userForm" (ngSubmit)="onSubmitForm()">
    <div class="form-group">
      <label for="firstName">Prénom</label>
      <input type="text" id="firstName" class="form-control" formControlName="firstName">
    </div>
    <div class="form-group">
      <label for="lastName">Nom</label>
      <input type="text" id="lastName" class="form-control" formControlName="lastName">
    </div>
    <div class="form-group">
      <label for="email">Adresse e-mail</label>
      <input type="text" id="email" class="form-control" formControlName="email">
    </div>
    <div class="form-group">
      <label for="email">Adresse address</label>
      <input type="text" id="address" class="form-control" formControlName="address">
    </div>
    <button type="submit" class="btn btn-primary">Soumettre</button>
  </form>
</div>
</code>```

File JSON

```<code>User:
    - User1:
        firstName: toto
        lastName: titi
        email: toto@toto.com
        address: 2 rue titi
</code>```

答:
In your component (.ts file), as soon as the data comes back (typically inside of your ngOnInit), you should be able to do this.userForm.setValue(data).

As for making them readonly, an easy way I know is to set the FormGroup as disabled when you create it. So userForm = new FormGroup({_property_names_}, { disabled: true }).

Title: Binding json - formgroup

Body:
I have a form and I want to display data that comes from an API (JSon file) in mode readonly. Do you have tracks?
I take an example of a form:
Thank you

  <form [formGroup]="userForm" (ngSubmit)="onSubmitForm()">

      Prénom
      <input type="text" id="firstName" class="form-control" formControlName="firstName">

      Nom
      <input type="text" id="lastName" class="form-control" formControlName="lastName">

      Adresse e-mail
      <input type="text" id="email" class="form-control" formControlName="email">

      Adresse address
      <input type="text" id="address" class="form-control" formControlName="address">

    <button type="submit" class="btn btn-primary">Soumettre</button>
  </form>

File JSON

User:
    - User1:
        firstName: toto
        lastName: titi
        email: toto@toto.com
        address: 2 rue titi


问:
Composer require. "Your requirements could not be resolved to an installable set of packages"
I have an error when I want to run the composer require on my project. errors issued like this:

```<code># composer require spatie/laravel-link-checker
Using version ^4.1 for spatie/laravel-link-checker
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: remove laravel/framework v5.8.18
    - Conclusion: don't install laravel/framework v5.8.18
    - spatie/laravel-link-checker 4.1.0 requires illuminate/support ~5.6.0 -> satisfiable by illuminate/support[5.6.x-dev, v5.6.0, v5.6.1, v5.6.10, v5.6.11, v5.6.12, v5.6.13, v5.6.14, v5.6.15, v5.6.16, v5.6.17, v5.6.19, v5.6.2, v5.6.20, v5.6.21, v5.6.22, v5.6.23, v5.6.24, v5.6.25, v5.6.26, v5.6.27, v5.6.28, v5.6.29, v5.6.3, v5.6.30, v5.6.31, v5.6.32, v5.6.33, v5.6.34, v5.6.35, v5.6.36, v5.6.37, v5.6.38, v5.6.39, v5.6.4, v5.6.5, v5.6.6, v5.6.7, v5.6.8, v5.6.9], laravel/framework[5.6.x-dev].
    - spatie/laravel-link-checker 4.1.1 requires laravel/framework ~5.6.0|~5.7.0 -> satisfiable by laravel/framework[5.6.x-dev, 5.7.x-dev].
    - don't install illuminate/support 5.6.x-dev|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.0|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.1|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.10|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.11|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.12|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.13|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.14|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.15|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.16|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.17|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.19|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.2|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.20|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.21|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.22|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.23|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.24|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.25|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.26|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.27|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.28|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.29|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.3|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.30|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.31|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.32|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.33|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.34|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.35|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.36|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.37|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.38|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.39|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.4|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.5|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.6|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.7|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.8|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.9|don't install laravel/framework v5.8.18
    - Can only install one of: laravel/framework[5.6.x-dev, v5.8.18].
    - Can only install one of: laravel/framework[5.7.x-dev, v5.8.18].
    - Installation request for laravel/framework (locked at v5.8.18, required as 5.8.*) -> satisfiable by laravel/framework[v5.8.18].
    - Installation request for spatie/laravel-link-checker ^4.1 -> satisfiable by spatie/laravel-link-checker[4.1.0, 4.1.1].

Installation failed, reverting ./composer.json to its original content.
</code>```

I'm using Laravel 5.8.

This is my Composer.json

```<code>{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "appzcoder/laravel-admin": "^3.1",
        "barryvdh/laravel-debugbar": "^3.2",
        "chriskonnertz/open-graph": "^1.0",
        "cviebrock/eloquent-sluggable": "4.8",
        "davejamesmiller/laravel-breadcrumbs": "5.x",
        "doctrine/dbal": "v2.4.2",
        "fideloper/proxy": "^4.0",
        "gpressutto5/laravel-slack": "^1.1",
        "guzzlehttp/guzzle": "^6.3",
        "intervention/image": "^2.4",
        "laravel/framework": "5.8.*",
        "laravel/slack-notification-channel": "^2.0",
        "laravel/tinker": "^1.0",
        "layershifter/tld-extract": "^2.0",
        "malhal/laravel-geographical": "^1.0",
        "yajra/laravel-datatables-oracle": "^9.0"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "laravel/telescope": "^2.0",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {

        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}
</code>```

anyone who can help me?
Thanks

答:
laravel-link-checker package (which is, by the way, abandoned) requires laravel framework 5.6/5.7 (as you can see in its packagist page. You have Laravel 5.8 and that is not satisfiable.

You can take the sources of laravel-link-checker and re-package it but it's not guaranteed it will work for Laravel 5.8.

Body:
I have an error when I want to run the composer require on my project. errors issued like this:

# composer require spatie/laravel-link-checker
Using version ^4.1 for spatie/laravel-link-checker
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: remove laravel/framework v5.8.18
    - Conclusion: don't install laravel/framework v5.8.18
    - spatie/laravel-link-checker 4.1.0 requires illuminate/support ~5.6.0 -> satisfiable by illuminate/support[5.6.x-dev, v5.6.0, v5.6.1, v5.6.10, v5.6.11, v5.6.12, v5.6.13, v5.6.14, v5.6.15, v5.6.16, v5.6.17, v5.6.19, v5.6.2, v5.6.20, v5.6.21, v5.6.22, v5.6.23, v5.6.24, v5.6.25, v5.6.26, v5.6.27, v5.6.28, v5.6.29, v5.6.3, v5.6.30, v5.6.31, v5.6.32, v5.6.33, v5.6.34, v5.6.35, v5.6.36, v5.6.37, v5.6.38, v5.6.39, v5.6.4, v5.6.5, v5.6.6, v5.6.7, v5.6.8, v5.6.9], laravel/framework[5.6.x-dev].
    - spatie/laravel-link-checker 4.1.1 requires laravel/framework ~5.6.0|~5.7.0 -> satisfiable by laravel/framework[5.6.x-dev, 5.7.x-dev].
    - don't install illuminate/support 5.6.x-dev|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.0|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.1|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.10|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.11|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.12|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.13|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.14|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.15|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.16|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.17|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.19|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.2|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.20|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.21|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.22|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.23|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.24|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.25|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.26|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.27|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.28|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.29|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.3|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.30|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.31|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.32|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.33|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.34|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.35|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.36|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.37|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.38|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.39|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.4|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.5|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.6|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.7|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.8|don't install laravel/framework v5.8.18
    - don't install illuminate/support v5.6.9|don't install laravel/framework v5.8.18
    - Can only install one of: laravel/framework[5.6.x-dev, v5.8.18].
    - Can only install one of: laravel/framework[5.7.x-dev, v5.8.18].
    - Installation request for laravel/framework (locked at v5.8.18, required as 5.8.*) -> satisfiable by laravel/framework[v5.8.18].
    - Installation request for spatie/laravel-link-checker ^4.1 -> satisfiable by spatie/laravel-link-checker[4.1.0, 4.1.1].

Installation failed, reverting ./composer.json to its original content.

I'm using Laravel 5.8.

This is my Composer.json

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "appzcoder/laravel-admin": "^3.1",
        "barryvdh/laravel-debugbar": "^3.2",
        "chriskonnertz/open-graph": "^1.0",
        "cviebrock/eloquent-sluggable": "4.8",
        "davejamesmiller/laravel-breadcrumbs": "5.x",
        "doctrine/dbal": "v2.4.2",
        "fideloper/proxy": "^4.0",
        "gpressutto5/laravel-slack": "^1.1",
        "guzzlehttp/guzzle": "^6.3",
        "intervention/image": "^2.4",
        "laravel/framework": "5.8.*",
        "laravel/slack-notification-channel": "^2.0",
        "laravel/tinker": "^1.0",
        "layershifter/tld-extract": "^2.0",
        "malhal/laravel-geographical": "^1.0",
        "yajra/laravel-datatables-oracle": "^9.0"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "laravel/telescope": "^2.0",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {

        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

anyone who can help me?
Thanks


问:
Dependency Injection failed in spring boot , maven based multiple modules project
Hi friends i am developing a maven based spring boot project project , this project is multiple module form one module is Main module and second module is Service Module. I have one controller in Main module and one service in Serivce module

Controller

```<code>package com.aquevix.controller;

import com.aquevix.common.MyService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.inject.Inject;

/**
 * Created by mohdqasim on 11/9/15.
 */
@RestController
@RequestMapping("/api")
public class MyController {

    @Inject MyService myService;
    @Inject BookRepository bookRepository;
    @RequestMapping(value = "/data" , method = RequestMethod.GET)
    public String getData(){
     return myService.getData();
    }
}
</code>```

Service

```<code>package com.aquevix.common;

import org.springframework.stereotype.Service;

/**
 * Created by mohdqasim on 11/9/15.
 */
@Service
public class MyService {
    public String getData(){
        return "hello qasim";
    }
}
</code>```

In maven multiple modules this scenerio is working fine but i have also one repository in the form of interface in service module.

```<code>package com.aquevix.common;

import org.springframework.data.jpa.repository.*;

/**
 * Spring Data JPA repository for the Book entity.
 */
public interface BookRepository extends JpaRepository<Book,Long> {

}
</code>```

So when i execute main class from Main module my project works fine without bookrepository in service module( or present in Main module) but if i put bookrepository in Service module then MyController could not instantiate due dependency injection failure of bookRepository in MyController.
Can anyone help me how to to avoid this failure i put any interface in Service module which is being injected into Main module

答:
I had a similar problem and solved it using this post: Spring Boot: autowire beans from library project

In short, add this annotation to your application:

```<code>@Import(SharedConfigurationReference.class)
</code>```

And then in your Service project create the SharedConfigurationReference class

```<code>package com.aquevix.common;

import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@ComponentScan("com.aquevix")
@EnableJpaRepositories("com.aquevix")
@EntityScan("com.aquevix")
public class SharedConfigurationReference {}
</code>```

For the entity and component scan annotations, make sure to specify a package that is parent to all your projects, i.e. parent to controller and service

ContentLicense: CC BY-SA 3.0

Body:
Hi friends i am developing a maven based spring boot project project , this project is multiple module form one module is Main module and second module is Service Module. I have one controller in Main module and one service in Serivce module

Controller

package com.aquevix.controller;

import com.aquevix.common.MyService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.inject.Inject;

/**
 * Created by mohdqasim on 11/9/15.
 */
@RestController
@RequestMapping("/api")
public class MyController {

    @Inject MyService myService;
    @Inject BookRepository bookRepository;
    @RequestMapping(value = "/data" , method = RequestMethod.GET)
    public String getData(){
     return myService.getData();
    }
}

Service

package com.aquevix.common;

import org.springframework.stereotype.Service;

/**
 * Created by mohdqasim on 11/9/15.
 */
@Service
public class MyService {
    public String getData(){
        return "hello qasim";
    }
}

In maven multiple modules this scenerio is working fine but i have also one repository in the form of interface in service module.

package com.aquevix.common;

import org.springframework.data.jpa.repository.*;

/**
 * Spring Data JPA repository for the Book entity.
 */
public interface BookRepository extends JpaRepository<Book,Long> {

}

So when i execute main class from Main module my project works fine without bookrepository in service module( or present in Main module) but if i put bookrepository in Service module then MyController could not instantiate due dependency injection failure of bookRepository in MyController.
Can anyone help me how to to avoid this failure i put any interface in Service module which is being injected into Main module

Body:
I had a similar problem and solved it using this post: Spring Boot: autowire beans from library project

In short, add this annotation to your application:

@Import(SharedConfigurationReference.class)

And then in your Service project create the SharedConfigurationReference class

package com.aquevix.common;

import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@ComponentScan("com.aquevix")
@EnableJpaRepositories("com.aquevix")
@EntityScan("com.aquevix")
public class SharedConfigurationReference {}

For the entity and component scan annotations, make sure to specify a package that is parent to all your projects, i.e. parent to controller and service


问:
performing multiple preg_replace with different search & replace each time
I've done something similar with str_replace using this:

```<code>$string = $url;
$patterns = array();
    $patterns[0] = 'searchforme';
    $patterns[1] = 'searchforme1';
    $patterns[2] = 'searchforme2';
$replacements = array();
    $replacements[0] = 'replacewithme';
    $replacements[1] = 'replacewithme1';
    $replacements[2] = 'replacewithme2';
$searchReplace = str_replace($patterns, $replacements, $string);
</code>```

How would I go about doing something similar with preg_replace?

I've built a very simple little css parser that searches for a specific tag within a comment wrapped around CSS properties, and replaces it with new data.

```<code>$stylesheet = file_get_contents('temp/'.$user.'/css/mobile.css');

$cssTag = 'bodybg';
$stylesheet = preg_replace("/(\/\*".$cssTag."\*\/).*?(\/\*\/".$cssTag."\*\/)/i", "\\1 background: $bg url(../images/bg.png) repeat-x; \\2", $stylesheet);

file_put_contents('temp/'.$user.'/css/mobile.css',''.$stylesheet.'');
</code>```

I have multiple "cssTag"'s and they'll all need unique css to replace with (background, color, font-size etc) which is why I'm looking for a method like the str_replace one above.

答:
You can also use T-Regx library

```<code><?php
$stylesheet = file_get_contents('temp/'.$user.'/css/mobile.css');

$cssTag = 'bodybg';
$stylesheet = pattern("(/\*" . $cssTag . "\*/).*?(/\*/" . $cssTag . "\*/)", 'i')
    ->replace($stylesheet)
    ->all()
    ->by()
    ->map([
        'searchforme' => 'replacewithme',
        'searchforme1' => 'replacewithme2',
        'searchforme1' => 'replacewithme2',
    ]);
</code>```

You don't need delimiters /, because T-Regx automatically adds them

Body:
I've done something similar with str_replace using this:

$string = $url;
$patterns = array();
    $patterns[0] = 'searchforme';
    $patterns[1] = 'searchforme1';
    $patterns[2] = 'searchforme2';
$replacements = array();
    $replacements[0] = 'replacewithme';
    $replacements[1] = 'replacewithme1';
    $replacements[2] = 'replacewithme2';
$searchReplace = str_replace($patterns, $replacements, $string);

How would I go about doing something similar with preg_replace?

I've built a very simple little css parser that searches for a specific tag within a comment wrapped around CSS properties, and replaces it with new data.

$stylesheet = file_get_contents('temp/'.$user.'/css/mobile.css');

$cssTag = 'bodybg';
$stylesheet = preg_replace("/(\/\*".$cssTag."\*\/).*?(\/\*\/".$cssTag."\*\/)/i", "\\1 background: $bg url(../images/bg.png) repeat-x; \\2", $stylesheet);

file_put_contents('temp/'.$user.'/css/mobile.css',''.$stylesheet.'');

I have multiple "cssTag"'s and they'll all need unique css to replace with (background, color, font-size etc) which is why I'm looking for a method like the str_replace one above.

Body:
You can also use T-Regx library

<?php
$stylesheet = file_get_contents('temp/'.$user.'/css/mobile.css');

$cssTag = 'bodybg';
$stylesheet = pattern("(/\*" . $cssTag . "\*/).*?(/\*/" . $cssTag . "\*/)", 'i')
    ->replace($stylesheet)
    ->all()
    ->by()
    ->map([
        'searchforme' => 'replacewithme',
        'searchforme1' => 'replacewithme2',
        'searchforme1' => 'replacewithme2',
    ]);

You don't need delimiters /, because T-Regx automatically adds them


问:
Call Monitor using C# TAPI
I need to create a program to monitor activity of phone call.And get information about the calls, like number and Name.
I'm not strong with TAPI code and C#, so hope that anybody can help me, I'm desperate.

I have this code where I try to detect the available devices and obtain information from those devices when a call comes in:

```<code>using System;
using TAPI3Lib;
using JulMar.Atapi;

namespace ConsoleApp1
{
  class Program
  {
    private void tapi_ITTAPIEventNotification_Event(TAPI_EVENT TapiEvent, object pEvent)
    {
        try
        {
            ITCallNotificationEvent cn = pEvent as ITCallNotificationEvent;
            if(cn.Call.CallState == CALL_STATE.CS_CONNECTED)
            {
                string calledidname = cn.Call.get_CallInfoString(CALLINFO_STRING.CIS_CALLEDIDNAME);
                Console.WriteLine("Called ID Name " + calledidname);
                string callednumber = cn.Call.get_CallInfoString(CALLINFO_STRING.CIS_CALLEDIDNUMBER);
                Console.WriteLine("Called Number " + callednumber);
                string calleridname = cn.Call.get_CallInfoString(CALLINFO_STRING.CIS_CALLERIDNAME);
                Console.WriteLine("Caller ID Name " + calleridname);
                string callernumber = cn.Call.get_CallInfoString(CALLINFO_STRING.CIS_CALLERIDNUMBER);
                Console.WriteLine("Caller Number " + callernumber);

            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

    static void Main(string[] args)
    {
        TapiManager mgr = new TapiManager("ConsoleApp1");
        mgr.Initialize();

        foreach(TapiLine line in mgr.Lines)
        {
            foreach (string s in line.Capabilities.AvailableDeviceClasses)
                Console.WriteLine("{0} - {1}", line.Name, s);
        }
    }
}
}
</code>```

But when I run it, just see the available devices but don't see any information about calls. I'm used to programming in java so I guess I should send to call the method that gets the call information in the main, but I do not know how to do that and in any code I've seen they do.
So, hope that you can help me to understand how TAPI works and what can I do to do my code work.

答:
Okay, first, you want to stick to one Version of TAPI. In your using statements, youre importing a TAPI 2.x managed libaray and a TAPI 3.x managed library.

using TAPI3Lib; // this is a TAPI 3.x library
using JulMar.Atapi; // this is a TAPI 2.x library
```
<p>If you're choosing to go with TAPI 3.x, you should start by creating a new class, which handles different kinds of TAPI events. To do so, it needs to implement the <code>ITTAPIEventNotification</code> interface:</p>
<pre class="lang-cs prettyprint-override"><code>public class CallNotification : ITTAPIEventNotification
{
    public void Event(TAPI_EVENT TapiEvent, object pEvent)
    {
        if(pEvent == null)
            throw new ArgumentNullException(nameof(pEvent));

        switch (TapiEvent)
        {
            case TAPI_EVENT.TE_CALLNOTIFICATION:
                // This event will be raised every time a new call is created on an monitored line-
                // You can use CALLINFO_LONG.CIL_ORIGIN to see weather it's an inbound call, or an
                // outbound call.
                break;
            case TAPI_EVENT.TE_CALLSTATE:
                // This event will be raised every time the state of a call on one of your monitored
                // Lines changes.
                // If you'd want to read information about a call, you can do it here:
                ITCallStateEvent callStateEvent = (ITCallStateEvent)pEvent;
                ITCallInfo call = callStateEvent.Call;

                string calledidname = call.get_CallInfoString(CALLINFO_STRING.CIS_CALLEDIDNAME);
                Console.WriteLine("Called ID Name " + calledidname);

                string callednumber = call.get_CallInfoString(CALLINFO_STRING.CIS_CALLEDIDNUMBER);
                Console.WriteLine("Called Number " + callednumber);

                string calleridname = call.get_CallInfoString(CALLINFO_STRING.CIS_CALLERIDNAME);
                Console.WriteLine("Caller ID Name " + calleridname);

                string callernumber = call.get_CallInfoString(CALLINFO_STRING.CIS_CALLERIDNUMBER);
                Console.WriteLine("Caller Number " + callernumber);
                break;
        }

        // Since you're working with COM objects, you should release any used references.
        Marshal.ReleaseComObject(pEvent);
    }
}
</code>```

In order to use this class, you need to create a new instance of TAPI3Lib.TAPIClass and  call its Initialize method. After that, you can attach your newly create CallNotification class as an event handler. You could also specify which types of events you want your handler to receive. Notice that you wont receive any event notifications at this point, because you haven't told TAPIClass which lines it should monitor:

CallNotification callevent = new CallNotification();
TAPIClass tapi = new TAPIClass();
tapi.Initialize();
tapi.EventFilter = (int)(TAPI_EVENT.TE_CALLNOTIFICATION | TAPI_EVENT.TE_CALLSTATE);
tapi.ITTAPIEventNotification_Event_Event += new ITTAPIEventNotification_EventEventHandler(callevent.Event);
```
<p>In order to tell <code>TAPIClass</code> which lines it should monitor, you need to do two things. ask for all lines registered to you IPBX and determine, weather its a line you have the rights to monitor (this is an IPBX configuration):</p>
<pre class="lang-java prettyprint-override"><code>public List<ITAddress> EnumerateLines(TAPIClass tapi)
{
    List<ITAddress> addresses = new List<ITAddress>();

    ITAddress address;
    uint arg = 0;

    ITAddressCapabilities addressCapabilities;
    int callfeatures;
    int linefeatures;
    bool hasCallFeaturesDial;
    bool hasLineFeaturesMakeCall;

    IEnumAddress ea = tapi.EnumerateAddresses();

    do
    {
        ea.Next(1, out address, ref arg);

        if (address != null)
        {
            addressCapabilities = (ITAddressCapabilities)address;

            callfeatures = addressCapabilities.get_AddressCapability(ADDRESS_CAPABILITY.AC_CALLFEATURES1);
            linefeatures = addressCapabilities.get_AddressCapability(ADDRESS_CAPABILITY.AC_LINEFEATURES);

            hasCallFeaturesDial = (callfeatures1 & (int)0x00000040) != 0; //Contains LineCallFeatures Dial; see Tapi.h for details
            hasLineFeaturesMakeCall = (linefeatures & (int)0x00000008) != 0; //Contains LineFeatures MakeCall; see Tapi.h for details

            // this is basically saying "Am I allowed to dial numbers and create calls on this specific line?"
            if(hasCallFeaturesDial && hasLineFeaturesMakeCall)
                addresses.Add(address);
        }
    } while (address != null);

    return addresses;
}

public void RegisterLines(TAPIClass tapi, IEnumerable<ITAddress> addresses)
{
    if (tapi == null)
        throw new ArgumentNullException(nameof(tapi));

    if (addresses == null)
        throw new ArgumentNullException(nameof(addresses));

    foreach (ITAddress address in addresses)
    {
        tapi.RegisterCallNotifications(address, true, true, TapiConstants.TAPIMEDIATYPE_AUDIO, 2);
    }
}
</code>```

so Your initialization would look like this:

CallNotification callevent = new CallNotification();
TAPIClass tapi = new TAPIClass();
tapi.Initialize();

IEnumerable<ITAddress> addresses = this.EnumerateLines(tapi);
this.RegisterLines(tapi, addresses);

tapi.EventFilter = (int)(TAPI_EVENT.TE_CALLNOTIFICATION | TAPI_EVENT.TE_CALLSTATE);
tapi.ITTAPIEventNotification_Event_Event += callevent.Event;
```

Once you run your program, and it's done executing above code, you will get notifications from incoming and outgoing calls when their call state changes.

I hope you could follow this post. If you have any questions, just ask =)

Title: Call Monitor using C# TAPI

Body:
I need to create a program to monitor activity of phone call.And get information about the calls, like number and Name.
I'm not strong with TAPI code and C#, so hope that anybody can help me, I'm desperate.

I have this code where I try to detect the available devices and obtain information from those devices when a call comes in:

using System;
using TAPI3Lib;
using JulMar.Atapi;

namespace ConsoleApp1
{
  class Program
  {
    private void tapi_ITTAPIEventNotification_Event(TAPI_EVENT TapiEvent, object pEvent)
    {
        try
        {
            ITCallNotificationEvent cn = pEvent as ITCallNotificationEvent;
            if(cn.Call.CallState == CALL_STATE.CS_CONNECTED)
            {
                string calledidname = cn.Call.get_CallInfoString(CALLINFO_STRING.CIS_CALLEDIDNAME);
                Console.WriteLine("Called ID Name " + calledidname);
                string callednumber = cn.Call.get_CallInfoString(CALLINFO_STRING.CIS_CALLEDIDNUMBER);
                Console.WriteLine("Called Number " + callednumber);
                string calleridname = cn.Call.get_CallInfoString(CALLINFO_STRING.CIS_CALLERIDNAME);
                Console.WriteLine("Caller ID Name " + calleridname);
                string callernumber = cn.Call.get_CallInfoString(CALLINFO_STRING.CIS_CALLERIDNUMBER);
                Console.WriteLine("Caller Number " + callernumber);

            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

    static void Main(string[] args)
    {
        TapiManager mgr = new TapiManager("ConsoleApp1");
        mgr.Initialize();

        foreach(TapiLine line in mgr.Lines)
        {
            foreach (string s in line.Capabilities.AvailableDeviceClasses)
                Console.WriteLine("{0} - {1}", line.Name, s);
        }
    }
}
}

But when I run it, just see the available devices but don't see any information about calls. I'm used to programming in java so I guess I should send to call the method that gets the call information in the main, but I do not know how to do that and in any code I've seen they do.
So, hope that you can help me to understand how TAPI works and what can I do to do my code work.

Body:
Okay, first, you want to stick to one Version of TAPI. In your using statements, youre importing a TAPI 2.x managed libaray and a TAPI 3.x managed library.

using TAPI3Lib; // this is a TAPI 3.x library
using JulMar.Atapi; // this is a TAPI 2.x library

If you're choosing to go with TAPI 3.x, you should start by creating a new class, which handles different kinds of TAPI events. To do so, it needs to implement the ITTAPIEventNotification interface:

public class CallNotification : ITTAPIEventNotification
{
    public void Event(TAPI_EVENT TapiEvent, object pEvent)
    {
        if(pEvent == null)
            throw new ArgumentNullException(nameof(pEvent));

        switch (TapiEvent)
        {
            case TAPI_EVENT.TE_CALLNOTIFICATION:
                // This event will be raised every time a new call is created on an monitored line-
                // You can use CALLINFO_LONG.CIL_ORIGIN to see weather it's an inbound call, or an
                // outbound call.
                break;
            case TAPI_EVENT.TE_CALLSTATE:
                // This event will be raised every time the state of a call on one of your monitored
                // Lines changes.
                // If you'd want to read information about a call, you can do it here:
                ITCallStateEvent callStateEvent = (ITCallStateEvent)pEvent;
                ITCallInfo call = callStateEvent.Call;

                string calledidname = call.get_CallInfoString(CALLINFO_STRING.CIS_CALLEDIDNAME);
                Console.WriteLine("Called ID Name " + calledidname);

                string callednumber = call.get_CallInfoString(CALLINFO_STRING.CIS_CALLEDIDNUMBER);
                Console.WriteLine("Called Number " + callednumber);

                string calleridname = call.get_CallInfoString(CALLINFO_STRING.CIS_CALLERIDNAME);
                Console.WriteLine("Caller ID Name " + calleridname);

                string callernumber = call.get_CallInfoString(CALLINFO_STRING.CIS_CALLERIDNUMBER);
                Console.WriteLine("Caller Number " + callernumber);
                break;
        }

        // Since you're working with COM objects, you should release any used references.
        Marshal.ReleaseComObject(pEvent);
    }
}

In order to use this class, you need to create a new instance of TAPI3Lib.TAPIClass and  call its Initialize method. After that, you can attach your newly create CallNotification class as an event handler. You could also specify which types of events you want your handler to receive. Notice that you wont receive any event notifications at this point, because you haven't told TAPIClass which lines it should monitor:

CallNotification callevent = new CallNotification();
TAPIClass tapi = new TAPIClass();
tapi.Initialize();
tapi.EventFilter = (int)(TAPI_EVENT.TE_CALLNOTIFICATION | TAPI_EVENT.TE_CALLSTATE);
tapi.ITTAPIEventNotification_Event_Event += new ITTAPIEventNotification_EventEventHandler(callevent.Event);

In order to tell TAPIClass which lines it should monitor, you need to do two things. ask for all lines registered to you IPBX and determine, weather its a line you have the rights to monitor (this is an IPBX configuration):

public List<ITAddress> EnumerateLines(TAPIClass tapi)
{
    List<ITAddress> addresses = new List<ITAddress>();

    ITAddress address;
    uint arg = 0;

    ITAddressCapabilities addressCapabilities;
    int callfeatures;
    int linefeatures;
    bool hasCallFeaturesDial;
    bool hasLineFeaturesMakeCall;

    IEnumAddress ea = tapi.EnumerateAddresses();

    do
    {
        ea.Next(1, out address, ref arg);

        if (address != null)
        {
            addressCapabilities = (ITAddressCapabilities)address;

            callfeatures = addressCapabilities.get_AddressCapability(ADDRESS_CAPABILITY.AC_CALLFEATURES1);
            linefeatures = addressCapabilities.get_AddressCapability(ADDRESS_CAPABILITY.AC_LINEFEATURES);

            hasCallFeaturesDial = (callfeatures1 & (int)0x00000040) != 0; //Contains LineCallFeatures Dial; see Tapi.h for details
            hasLineFeaturesMakeCall = (linefeatures & (int)0x00000008) != 0; //Contains LineFeatures MakeCall; see Tapi.h for details

            // this is basically saying "Am I allowed to dial numbers and create calls on this specific line?"
            if(hasCallFeaturesDial && hasLineFeaturesMakeCall)
                addresses.Add(address);
        }
    } while (address != null);

    return addresses;
}

public void RegisterLines(TAPIClass tapi, IEnumerable<ITAddress> addresses)
{
    if (tapi == null)
        throw new ArgumentNullException(nameof(tapi));

    if (addresses == null)
        throw new ArgumentNullException(nameof(addresses));

    foreach (ITAddress address in addresses)
    {
        tapi.RegisterCallNotifications(address, true, true, TapiConstants.TAPIMEDIATYPE_AUDIO, 2);
    }
}

so Your initialization would look like this:

CallNotification callevent = new CallNotification();
TAPIClass tapi = new TAPIClass();
tapi.Initialize();

IEnumerable<ITAddress> addresses = this.EnumerateLines(tapi);
this.RegisterLines(tapi, addresses);

tapi.EventFilter = (int)(TAPI_EVENT.TE_CALLNOTIFICATION | TAPI_EVENT.TE_CALLSTATE);
tapi.ITTAPIEventNotification_Event_Event += callevent.Event;

Once you run your program, and it's done executing above code, you will get notifications from incoming and outgoing calls when their call state changes.

I hope you could follow this post. If you have any questions, just ask =)


问:
How can I count the invocations of a method?
Use interceptors to count the number of invocations.

I created an application with java ee consisting of an ejb side and a client. Now I have to count the number of times the client invokes a method, for each method, using the interceptors.

I don't understand how to modify the interceptors class. This is my code.

```<code>import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class InterceptorsBean {

    @AroundInvoke
    public Object methodInterceptors (InvocationContext ctx) throws Exception {
        System.out.println("Method invocated: " + ctx.getMethod().getName());
        return ctx.proceed();
    }

}
</code>```

How can I add the function to count?

答:
You could use a map to hold the method name and the number of invocations of that method.</p>

```<code>import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import java.util.Map;

public class InterceptorsBean {

    private Map<String, Integer> numberOfInvocations;

    @AroundInvoke
    public Object methodInterceptors (InvocationContext ctx) throws Exception {
        int invocations = 1;

        if(numberOfInvocations.containsKey(ctx.getMethod().getName())) {
           invocations = numberOfInvocations.get(ctx.getMethod().getName()) + 1;
        }

        numberOfInvocations.put(ctx.getMethod().getName(), invocations);

        System.out.println("Method invocated: " + ctx.getMethod().getName());
        System.out.println("Number of invocations: " + invocations);
        return ctx.proceed();
    }

}
</code>```

Body:
Use interceptors to count the number of invocations.

I created an application with java ee consisting of an ejb side and a client. Now I have to count the number of times the client invokes a method, for each method, using the interceptors.

I don't understand how to modify the interceptors class. This is my code.

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class InterceptorsBean {

    @AroundInvoke
    public Object methodInterceptors (InvocationContext ctx) throws Exception {
        System.out.println("Method invocated: " + ctx.getMethod().getName());
        return ctx.proceed();
    }

}

How can I add the function to count?

Body:
You could use a map to hold the method name and the number of invocations of that method.

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import java.util.Map;

public class InterceptorsBean {

    private Map<String, Integer> numberOfInvocations;

    @AroundInvoke
    public Object methodInterceptors (InvocationContext ctx) throws Exception {
        int invocations = 1;

        if(numberOfInvocations.containsKey(ctx.getMethod().getName())) {
           invocations = numberOfInvocations.get(ctx.getMethod().getName()) + 1;
        }

        numberOfInvocations.put(ctx.getMethod().getName(), invocations);

        System.out.println("Method invocated: " + ctx.getMethod().getName());
        System.out.println("Number of invocations: " + invocations);
        return ctx.proceed();
    }

}


问:
ADAL [AquireTokenAsync] timeout while running in WebAPI within company proxy network
We encounter a very bizarre issue with Azure AD library in a asp.net web api app. When we try to get token using AcquireTokenAsync with a Certificate, there is no response and then time out.

Bizarre part:

If we copy the same code in a console app, console app works, get token instantly.

if we use fiddler to start a proxy which overtake our company's default proxy, webapi app works.

The testing code we are using is exactly from the documentation.

Sample code we use :

```<code>public async Task < string > GetTokenAsync() {

    var context = new AuthenticationContext(authority);

    var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

    store.Open(OpenFlags.ReadOnly);

    var results = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);

    var cert = new ClientAssertionCertificate(clientid, results[0]);

    var token = await context.AcquireTokenAsync(resource, cert).AccessToken;

    return token;

}
</code>```

Basically the code should work properly since it is from documentation directly. is it something relative to the networking?

The Error we get in short:

at System.Web.Http.Results.ExceptionResult..ctor(Exception exception, IDependencyProvider dependencies)
  at System.Web.Http.ApiController.InternalServerError(Exception exception)
  at WebApplication1.Controllers.TokenController.d__0.MoveNext() in C:\Users\QiaoH\source\repos\WebApplication1\WebApplication1\Controllers\TokenController.cs:line 55 --- End of stack trace from previous location where exception was thrown
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Threading.Tasks.TaskHelpersExtensions.d__1`1.MoveNext()
  End of stack trace from previous location where exception was thrown
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Controllers.ApiControllerActionInvoker.d__1.MoveNext() --- End of stack trace from previous location where exception was thrown
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Controllers.ActionFilterResult.d__5.MoveNext()
  End of stack trace from previous location where exception was thrown
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()

答:
Problem solved:

Due to the proxy, we have to enabled default proxy with default credential.

We put below in web.config and it works.

```<code>    <system.net>
        <defaultProxy enabled="true" useDefaultCredentials="true">
        </defaultProxy>
    </system.net>
</code>```

Body:
We encounter a very bizarre issue with Azure AD library in a asp.net web api app. When we try to get token using AcquireTokenAsync with a Certificate, there is no response and then time out.

Bizarre part:

If we copy the same code in a console app, console app works, get token instantly.

if we use fiddler to start a proxy which overtake our company's default proxy, webapi app works.

The testing code we are using is exactly from the documentation.

Sample code we use :

public async Task < string > GetTokenAsync() {

    var context = new AuthenticationContext(authority);

    var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

    store.Open(OpenFlags.ReadOnly);

    var results = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);

    var cert = new ClientAssertionCertificate(clientid, results[0]);

    var token = await context.AcquireTokenAsync(resource, cert).AccessToken;

    return token;

}

Basically the code should work properly since it is from documentation directly. is it something relative to the networking?

The Error we get in short:

at System.Web.Http.Results.ExceptionResult..ctor(Exception exception, IDependencyProvider dependencies)
  at System.Web.Http.ApiController.InternalServerError(Exception exception)
  at WebApplication1.Controllers.TokenController.d__0.MoveNext() in C:\Users\QiaoH\source\repos\WebApplication1\WebApplication1\Controllers\TokenController.cs:line 55 --- End of stack trace from previous location where exception was thrown
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Threading.Tasks.TaskHelpersExtensions.d__1`1.MoveNext()
  End of stack trace from previous location where exception was thrown
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Controllers.ApiControllerActionInvoker.d__1.MoveNext() --- End of stack trace from previous location where exception was thrown
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Controllers.ActionFilterResult.d__5.MoveNext()
  End of stack trace from previous location where exception was thrown
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()

Body:
Problem solved:

Due to the proxy, we have to enabled default proxy with default credential.

We put below in web.config and it works.

    <system.net>
        <defaultProxy enabled="true" useDefaultCredentials="true">
        </defaultProxy>
    </system.net>


问:
How can I stop input with newline character
I am reading a list of numbers separated by spaces. Currently the loop stops when I press Ctrl + Z. I just need to know how to modify the loop to terminate when I hit enter or if it meets the newline('\n') character. </p>

```<code>    int numArrayCount = 0;
    int num, count = 0;
    int binaryArray[CAPACITY];
    int numArray[CAPACITY];

    //takes in positive numbers higher than zero and less than 64.
    //End output with Ctrl+Z

    while (scanf_s( "%d", &num ) == 1) {
        if (num < 64 && num > 0) {
            binaryArray[ count++ ] = base10ToBinary(num);
            numArray[ numArrayCount++ ] = num;
        }
    }
</code>```

答:
There is no direct way, because scanf and friends are only a poor man's parser. As long as you have values separated with an arbitrary number of space characters (space, tab, return, linefeed and vtab) and it does not matter what those separators are, scanf is fine.

If you want to process lines, and then can parse the content of a line, fgets is the way to go. Unfortunately, you cannot repeatedly scan from a string, but you can build nice string parsers with strtok or better strcspn

Other languages (C++, Java, etc.) or maybe other libraries may have smarter tools. But C was initially build as a low level language...

Body:
I am reading a list of numbers separated by spaces. Currently the loop stops when I press Ctrl + Z. I just need to know how to modify the loop to terminate when I hit enter or if it meets the newline('\n') character.

    int numArrayCount = 0;
    int num, count = 0;
    int binaryArray[CAPACITY];
    int numArray[CAPACITY];

    //takes in positive numbers higher than zero and less than 64.
    //End output with Ctrl+Z

    while (scanf_s( "%d", &num ) == 1) {
        if (num < 64 && num > 0) {
            binaryArray[ count++ ] = base10ToBinary(num);
            numArray[ numArrayCount++ ] = num;
        }
    }


问:
Need to trim the extension for double extension filename
I have some files with the names as below,

Input could be one of the below,

ABC.sample.tar.gz

XYZ.sample.tar.gz.Manifest

123.sample.zip

i have couple of requirements

Need to trim off the extension totally and store the filename without extension into a variable.

Sample output: $filename=ABC.sample or XYZ.sample or 123.sample

Need to trim only ".manifest" if it exists and stores into another variable.

Code:

```<code>$SURL = "ABC.sample.tar.gz.manifest"
$UDRname = [IO.Path]::GetFileNameWithoutExtension($SURL)
$UDRname
</code>```

Output: ABC.sample.tar.gz

Expectation:

Actual file extensions have to removed like below

$filename=ABC.sample

$filename=XYZ.sample

$filename=123.sample

If the file name is having .manifest in the filename.
It has to trimmed away.

$trimed = XYZ.sample.tar.gz

答:
The main problem you will hit is with the [IO.Path]::GetFileNameWithoutExtension($SURL) which does not support the concept of multiple extensions.

By adding a special consideration for multiple dot extensions,
here's something that should work for you.

Add any other multiple extensions (excluding the manifest one) in the $DoubleExtensions to cover other cases you might have.

Consider the following:

```<code>Function Get-FileInfos($FullName) {
    $DoubleExtensions = @('.tar.gz')
    $Manifestext = '.manifest'
    $IsManifest = $FullName.EndsWith($Manifestext)
    $Extension, $TrimmedName = $null
    $NameToProcess = $FullName

    # Process manifest extention
    if ($IsManifest) {
        $TrimmedName = [IO.Path]::GetFileNameWithoutExtension($FullName)
        $NameToProcess = $TrimmedName
    }

    # Process double extensions
    Foreach ($Ext in $DoubleExtensions) {
        if ($NameToProcess.EndsWith($Ext)) {
            if ($IsManifest -eq $false) {
                $Extension = $Ext
                $ShortName = $NameToProcess.Substring(0, $NameToProcess.Length - $ext.Length)
            }
            else {
                $Extension = $Ext
                $ShortName = $NameToProcess
            }
            break
        }
    }

    # Process normal extensions
    if ($null -eq $Extension ) {

        if ($IsManifest -eq $false) {
            $Extension = [io.Path]::GetExtension($NameToProcess)
            $ShortName = [IO.Path]::GetFileNameWithoutExtension($NameToProcess)
        }
        else {
            $ShortName = $NameToProcess
        }

    }

    # If manifest, extension should be .manifest without original file extension
    if ($IsManifest) { $Extension = $Manifestext }

    return [PSCustomObject]@{
        FullName    = $FullName
        TrimmedName = $TrimmedName
        ShortName   = $ShortName
        Extension   = $Extension
    }
}
</code>```

Sample test

```<code>$TestList = @(
    'ABC.sample.tar.gz.manifest'
    'DEF.sample.tar.gz'
    'GHI.Sample.manifest'
    'JKL.exe'
)

$TestList | foreach { Get-FileInfos -FullName $_ }
</code>```

Result

Body:
I have some files with the names as below,

Input could be one of the below,

ABC.sample.tar.gz

XYZ.sample.tar.gz.Manifest

123.sample.zip

i have couple of requirements

Need to trim off the extension totally and store the filename without extension into a variable.

Sample output: $filename=ABC.sample or XYZ.sample or 123.sample

Need to trim only ".manifest" if it exists and stores into another variable.

Code:

$SURL = "ABC.sample.tar.gz.manifest"
$UDRname = [IO.Path]::GetFileNameWithoutExtension($SURL)
$UDRname

Output: ABC.sample.tar.gz

Expectation:

Actual file extensions have to removed like below

$filename=ABC.sample

$filename=XYZ.sample

$filename=123.sample

If the file name is having .manifest in the filename.
It has to trimmed away.

$trimed = XYZ.sample.tar.gz

Body:
The main problem you will hit is with the [IO.Path]::GetFileNameWithoutExtension($SURL) which does not support the concept of multiple extensions.

By adding a special consideration for multiple dot extensions,
here's something that should work for you.

Add any other multiple extensions (excluding the manifest one) in the $DoubleExtensions to cover other cases you might have.

Consider the following:

Function Get-FileInfos($FullName) {
    $DoubleExtensions = @('.tar.gz')
    $Manifestext = '.manifest'
    $IsManifest = $FullName.EndsWith($Manifestext)
    $Extension, $TrimmedName = $null
    $NameToProcess = $FullName

    # Process manifest extention
    if ($IsManifest) {
        $TrimmedName = [IO.Path]::GetFileNameWithoutExtension($FullName)
        $NameToProcess = $TrimmedName
    }

    # Process double extensions
    Foreach ($Ext in $DoubleExtensions) {
        if ($NameToProcess.EndsWith($Ext)) {
            if ($IsManifest -eq $false) {
                $Extension = $Ext
                $ShortName = $NameToProcess.Substring(0, $NameToProcess.Length - $ext.Length)
            }
            else {
                $Extension = $Ext
                $ShortName = $NameToProcess
            }
            break
        }
    }

    # Process normal extensions
    if ($null -eq $Extension ) {

        if ($IsManifest -eq $false) {
            $Extension = [io.Path]::GetExtension($NameToProcess)
            $ShortName = [IO.Path]::GetFileNameWithoutExtension($NameToProcess)
        }
        else {
            $ShortName = $NameToProcess
        }

    }

    # If manifest, extension should be .manifest without original file extension
    if ($IsManifest) { $Extension = $Manifestext }

    return [PSCustomObject]@{
        FullName    = $FullName
        TrimmedName = $TrimmedName
        ShortName   = $ShortName
        Extension   = $Extension
    }
}

Sample test

$TestList = @(
    'ABC.sample.tar.gz.manifest'
    'DEF.sample.tar.gz'
    'GHI.Sample.manifest'
    'JKL.exe'
)

$TestList | foreach { Get-FileInfos -FullName $_ }

Result