问:
Laravel - Missing required parameters for [Route: appraisal.appraisal_goals.manager_employee_goal]
With Laravel-5.8, I tried to route from:

```<code>public function manager_employee_goal($id)
{
    if (! Gate::allows('appraisal_goal_review')) {
        return abort(401);
    }

    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;
    $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
    $linemanager = DB::table('hr_employees')->select('line_manager_id')->where('id', $userEmployee)->first();
    $linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->pluck('id');
   $appraisedemployees = HrEmployee::select('id', 'employee_code', 'first_name', 'last_name')->where('id', $id)->get();

    $goals = AppraisalGoal::where('employee_id', $id)->where('appraisal_identity_id', $identities->id)->where('id', '!=', $linemanager->line_manager_id)->get();

    return view('appraisal.appraisal_goals.manager_employee_goal')->with('goals', $goals)->with('appraisedemployees', $appraisedemployees);
}
</code>```

view: manager_employee_goal.blade

```<code>  <a class="btn btn-xs btn-primary" href="{{ route('appraisal.appraisal_goals.manager_employee_goal_list', ['goalid'=>$goal->id]) }}">
           {{ trans('global.view') }}
  </a>
</code>```

to this route:

```<code>public function manager_employee_goal_list($goalid)
{
        $goal           =       AppraisalGoal::findOrFail($goalid);
    $goaldetails    = AppraisalGoalDetail::where('appraisal_goal_id', $goalid)->get();
    return view('appraisal.appraisal_goals.manager_employee_goal_list')
                ->with('goal', $goal)
                ->with('goaldetails', $goaldetails);
}
</code>```

using

```<code>Route::get('appraisal_goals/manager_employee_goal/{id}', 'Appraisal\AppraisalGoalsController@manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');
Route::get('appraisal_goals/manager_employee_goal_list/{goalid}', 'Appraisal\AppraisalGoalsController@manager_employee_goal_list')->name('appraisal.appraisal_goals.manager_employee_goal_list');
</code>```

But I got this error:

Missing required parameters for [Route: appraisal.appraisal_goals.manager_employee_goal] [URI: appraisal_goals/manager_employee_goal/{id}]. (View: C:\xampp\htdocs\peopleedge\resources\views\appraisal\appraisal_goals\manager_employee_goal_list.blade.php)

How do I get it resolved?

Thank you

答:
Change route('appraisal.appraisal_goals.manager_employee_goal_list', ['goalid'=>$goal->id]) to url('appraisal.appraisal_goals.manager_employee_goal_list', ['id'=>$goal->id]).

Check the usage of the url generator:- https://laravel.com/docs/6.x/urls#urls-for-named-routes

Body:
With Laravel-5.8, I tried to route from:

public function manager_employee_goal($id)
{
    if (! Gate::allows('appraisal_goal_review')) {
        return abort(401);
    }

    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;
    $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
    $linemanager = DB::table('hr_employees')->select('line_manager_id')->where('id', $userEmployee)->first();
    $linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->pluck('id');
   $appraisedemployees = HrEmployee::select('id', 'employee_code', 'first_name', 'last_name')->where('id', $id)->get();

    $goals = AppraisalGoal::where('employee_id', $id)->where('appraisal_identity_id', $identities->id)->where('id', '!=', $linemanager->line_manager_id)->get();

    return view('appraisal.appraisal_goals.manager_employee_goal')->with('goals', $goals)->with('appraisedemployees', $appraisedemployees);
}

view: manager_employee_goal.blade

  $goal->id]) }}">
           {{ trans('global.view') }}

to this route:

public function manager_employee_goal_list($goalid)
{
        $goal           =       AppraisalGoal::findOrFail($goalid);
    $goaldetails    = AppraisalGoalDetail::where('appraisal_goal_id', $goalid)->get();
    return view('appraisal.appraisal_goals.manager_employee_goal_list')
                ->with('goal', $goal)
                ->with('goaldetails', $goaldetails);
}

using

Route::get('appraisal_goals/manager_employee_goal/{id}', 'Appraisal\AppraisalGoalsController@manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');
Route::get('appraisal_goals/manager_employee_goal_list/{goalid}', 'Appraisal\AppraisalGoalsController@manager_employee_goal_list')->name('appraisal.appraisal_goals.manager_employee_goal_list');

But I got this error:

Missing required parameters for [Route: appraisal.appraisal_goals.manager_employee_goal] [URI: appraisal_goals/manager_employee_goal/{id}]. (View: C:\xampp\htdocs\peopleedge\resources\views\appraisal\appraisal_goals\manager_employee_goal_list.blade.php)

How do I get it resolved?

Thank you


来源: stackexchange

问:
Create database in UseInMemoryDatabase in ASP.NET Core and identity
I need to create a database in ASP.NET Core and use identity, and I need to use UseInMemoryDatabase but when I try to add a migration, I get this error:

Unable to create an object of type 'DortajContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

This is my start up:

```<code> public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<DortajContext>(options => options.UseInMemoryDatabase(databaseName: "DortajDistance"));
        services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<DortajContext>();
        services.AddControllers();
    }
</code>```

and this is my context :

```<code> public class DortajContext : IdentityDbContext<User, Role, int>
{
    public DortajContext(DbContextOptions<DortajContext> options)
  : base(options)
    {
    }

    public DbSet<UserDistanceHistory> UserDistanceHistories { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.ApplyConfigurationsFromAssembly(typeof(IType).Assembly);
    }
}
</code>```

How can I solve this problem?

答:
Why do you need migrations for in-memory database?

Migrations are used to versioning database. It is useful when you have a database in production, you changed smth and you can update it with migrations. There is no need to use it for in-memory databases. You can read more about migrations here.

Anyway, InMemory provider was designed only for unit and integration testing. If you want to use in-memory in developing and production, you should use SQLite. Here is issue oh the github

ContentLicense: CC BY-SA 4.0

Body:
I need to create a database in ASP.NET Core and use identity, and I need to use UseInMemoryDatabase but when I try to add a migration, I get this error:

Unable to create an object of type 'DortajContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

This is my start up:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<DortajContext>(options => options.UseInMemoryDatabase(databaseName: "DortajDistance"));
        services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<DortajContext>();
        services.AddControllers();
    }

and this is my context :

 public class DortajContext : IdentityDbContext<User, Role, int>
{
    public DortajContext(DbContextOptions<DortajContext> options)
  : base(options)
    {
    }

    public DbSet<UserDistanceHistory> UserDistanceHistories { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.ApplyConfigurationsFromAssembly(typeof(IType).Assembly);
    }
}

How can I solve this problem?


问:
jquery- stop auto refreshing onClick
I'm running a jquery autorefresh code which get active soon the page is loaded. I've set timeinterval to 1second.which means that for every 1 sec page gets refreshed.
I want to know is there any method to stop auto refreshing onclick?

Code:

```<code>$(document).ready(function(){
    setTimeout("dummy()",500);
});
function dummy(){
    setTimeout("checkalerts()",50);
}
function checkalerts() {
    var url="includes/adda/hangouts/display_all_hangouts.php";
    $.post(url,function(data){
        $("#print").html(data).show();
        setTimeout("dummy()",1000);
    });
}
</code>```

答: use preventDefault() after your first click</p>

ContentLicense: CC BY-SA 3.0

Title: jquery- stop auto refreshing onClick

Body:
I'm running a jquery autorefresh code which get active soon the page is loaded. I've set timeinterval to 1second.which means that for every 1 sec page gets refreshed.
I want to know is there any method to stop auto refreshing onclick?

Code:

$(document).ready(function(){
    setTimeout("dummy()",500);
});
function dummy(){
    setTimeout("checkalerts()",50);
}
function checkalerts() {
    var url="includes/adda/hangouts/display_all_hangouts.php";
    $.post(url,function(data){
        $("#print").html(data).show();
        setTimeout("dummy()",1000);
    });
}


问:
How can i sort multidimension array with specific name in swift?
In my json result, there is odds array. And inside of it, there will be 8 types of bet. And i want to sort the array by bet type as i want to show.  Eg. first "name": "3Way Result", second another one, third "over/under" etc..

Here is my json result from server.

```<code> {
    "success": true,
    "result": [
        {
            "league_id": 5,
            "localTeam": {"data": {}},
            "visitorTeam": {"data": {}},
            "scores": {},
            "time": {"starting_at": {},},
            "league": {"data": {"coverage": {}}},
            "odds": [
                {
                    "id": 12,
                    "name": "Over/Under",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "Over",
                                            "value": "2.00",
                                            "extra": null,
                                            "probability": "50%",
                                            "dp3": "2.000",
                                            "american": 100,
                                            "handicap": null,
                                            "total": "2.5",
                                            "winning": null,
                                            "stop": false,
                                            "bookmaker_event_id": 84922729,
                                        },
                                        {
                                            "label": "Under",
                                            "value": "1.80",
                                            "probability": "55.56%",
                                            "dp3": "1.800",

                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "id": 1,
                    "name": "3Way Result",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "1",
                                            "value": "2.10",
                                            "extra": null,
                                            "probability": "47.62%",
                                            "dp3": "2.100",
                                            "american": 110,

                                        },
                                        {
                                            "label": "X",
                                            "value": "3.30",
                                            "extra": null,
                                            "probability": "30.3%",
                                            "dp3": "3.300",
                                            "american": 229,

                                        },
                                        {
                                            "label": "2",
                                            "value": "3.60",

                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "id": 975909,
                    "name": "Correct Score",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "1:0",
                                            "value": "7.50",
                                            "extra": null,
                                            "probability": "13.33%",
                                            "dp3": "7.500",
                                            "american": 650,
                                            "factional": null,
                                            "handicap": null,
                                            "total": null,
                                            "winning": null,
                                            "stop": false,
                                            "bookmaker_event_id": 84922729,
                                            "last_update": {
                                                "date": "2020-02-20 10:59:06.746514",
                                                "timezone_type": 3,
                                                "timezone": "UTC"
                                            }
                                        },
                                        {
                                            "label": "2:0",
                                            "value": "10.00",

                                        },

                                    ]
                                }
                            }
                        ]
                    }
                },

            ],
            "tipsters": 2
        }
    ]
}
</code>```

so it is not alphabetically, datetime or anytype i could access. How could i do ?

Update: I have added model.

```<code>struct BetterMatchResults: APIModel, Codable {
    var success: Bool?
    var result: [BetterMatch]?
}
struct BetterMatch: APIModel, Codable  {
    var id,_id: String?
    var localTeam, visitorTeam: BetterTeam?
    var spId, league_id, seasonID: Int?
    var winningOddsCalculated: Bool?
    var time: BetterTime?
    var league: BetterLeague?
    var createdAt, updatedAt: String?
    var odds: [BetterOdd]!
    var resultID: String?
    var tipsters: Int?
    var stats_url: String?
}

struct BetterLeague : APIModel, Codable {
    var data: LeagueData?
}

struct LeagueData : APIModel, Codable{
    var id: Int?
    var active: Bool?
    //var legacyID, countryID: Int?
    var logo_path: String?
    var name: String?
    //var isCup: Bool?

}

struct BetterOdd : APIModel, Codable {
    var id: Int?
    var name: String?
    var suspended: Bool?
    var bookmaker: BetterBookmaker?
   }

// MARK: - Bookmaker
struct BetterBookmaker : APIModel, Codable {
    var data: [BetterBookmakerDatum]?
}

// MARK: - BookmakerDatum
struct BetterBookmakerDatum : APIModel, Codable {
    var id: Int?
    var name: String?
    var odds: BetterOdds?
}

// MARK: - Odds
struct BetterOdds : APIModel, Codable {
    var data: [BetterOddsDatum]?
}

class BetterOddsDatum: APIModel , Codable {

    var label: String?
     //var extra: NSNull?
     //var probability, dp3: String?
     var american: Int?
     //var factional, handicap: NSNull?
     var total: String?
     var winning: Bool?
     var stop: Bool?
     var bookmakerEventID: Int?
    //private var odd: Double
    public var value: String?
    init() {

    }
}
</code>```

答:
i changed model

```<code>struct BetterOdd : APIModel, Codable {
    var id: Int?
    var name: String?
    var suspended: Bool?
    var bookmaker: BetterBookmaker?
    //var betType: BetType = .threeWayResult

    enum BetType:Int, APIModel, Codable {
        case threeWayResult = 7
        case overUnder = 6
        case doubleChance = 5
        case bothTeamsToScore = 4
        case threeWayResultFirstHalf = 3
        case threeWayResultSecondHalf = 2
        case correctScore = 1
        case hTfTdouble = 0
    }
//
    func getBetType() -> BetType {
        if name == "3Way Result" {
            return .threeWayResult
        } else if name == "Over/Under" {
            return .overUnder
        } else if name == "Double Chance"  {
            return .doubleChance
        } else if name == "Both Teams To Score"  {
            return .bothTeamsToScore
        } else if  name == "3Way Result 1st Half" {
            return .threeWayResultFirstHalf
        } else if name == "3Way Result 2nd Half"{
            return .threeWayResultSecondHalf
        } else if name == "Correct Score"{
            return .correctScore
        } else if name == "HF/FT Double" {
            return .hTfTdouble
        } else {
            return .correctScore
        }
    }
}
</code>```

and then :

```<code>let matchOddsArray  = match.odds!
let result = matchOddsArray.sorted(by: { $0.betType.rawValue > $1.betType.rawValue})
let bet = result[indexPath.row]
</code>```

works perfect.

Body:
In my json result, there is odds array. And inside of it, there will be 8 types of bet. And i want to sort the array by bet type as i want to show.  Eg. first "name": "3Way Result", second another one, third "over/under" etc..

Here is my json result from server.

 {
    "success": true,
    "result": [
        {
            "league_id": 5,
            "localTeam": {"data": {}},
            "visitorTeam": {"data": {}},
            "scores": {},
            "time": {"starting_at": {},},
            "league": {"data": {"coverage": {}}},
            "odds": [
                {
                    "id": 12,
                    "name": "Over/Under",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "Over",
                                            "value": "2.00",
                                            "extra": null,
                                            "probability": "50%",
                                            "dp3": "2.000",
                                            "american": 100,
                                            "handicap": null,
                                            "total": "2.5",
                                            "winning": null,
                                            "stop": false,
                                            "bookmaker_event_id": 84922729,
                                        },
                                        {
                                            "label": "Under",
                                            "value": "1.80",
                                            "probability": "55.56%",
                                            "dp3": "1.800",

                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "id": 1,
                    "name": "3Way Result",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "1",
                                            "value": "2.10",
                                            "extra": null,
                                            "probability": "47.62%",
                                            "dp3": "2.100",
                                            "american": 110,

                                        },
                                        {
                                            "label": "X",
                                            "value": "3.30",
                                            "extra": null,
                                            "probability": "30.3%",
                                            "dp3": "3.300",
                                            "american": 229,

                                        },
                                        {
                                            "label": "2",
                                            "value": "3.60",

                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "id": 975909,
                    "name": "Correct Score",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "1:0",
                                            "value": "7.50",
                                            "extra": null,
                                            "probability": "13.33%",
                                            "dp3": "7.500",
                                            "american": 650,
                                            "factional": null,
                                            "handicap": null,
                                            "total": null,
                                            "winning": null,
                                            "stop": false,
                                            "bookmaker_event_id": 84922729,
                                            "last_update": {
                                                "date": "2020-02-20 10:59:06.746514",
                                                "timezone_type": 3,
                                                "timezone": "UTC"
                                            }
                                        },
                                        {
                                            "label": "2:0",
                                            "value": "10.00",

                                        },

                                    ]
                                }
                            }
                        ]
                    }
                },

            ],
            "tipsters": 2
        }
    ]
}

so it is not alphabetically, datetime or anytype i could access. How could i do ?

Update: I have added model.

struct BetterMatchResults: APIModel, Codable {
    var success: Bool?
    var result: [BetterMatch]?
}
struct BetterMatch: APIModel, Codable  {
    var id,_id: String?
    var localTeam, visitorTeam: BetterTeam?
    var spId, league_id, seasonID: Int?
    var winningOddsCalculated: Bool?
    var time: BetterTime?
    var league: BetterLeague?
    var createdAt, updatedAt: String?
    var odds: [BetterOdd]!
    var resultID: String?
    var tipsters: Int?
    var stats_url: String?
}

struct BetterLeague : APIModel, Codable {
    var data: LeagueData?
}

struct LeagueData : APIModel, Codable{
    var id: Int?
    var active: Bool?
    //var legacyID, countryID: Int?
    var logo_path: String?
    var name: String?
    //var isCup: Bool?

}

struct BetterOdd : APIModel, Codable {
    var id: Int?
    var name: String?
    var suspended: Bool?
    var bookmaker: BetterBookmaker?
   }

// MARK: - Bookmaker
struct BetterBookmaker : APIModel, Codable {
    var data: [BetterBookmakerDatum]?
}

// MARK: - BookmakerDatum
struct BetterBookmakerDatum : APIModel, Codable {
    var id: Int?
    var name: String?
    var odds: BetterOdds?
}

// MARK: - Odds
struct BetterOdds : APIModel, Codable {
    var data: [BetterOddsDatum]?
}

class BetterOddsDatum: APIModel , Codable {

    var label: String?
     //var extra: NSNull?
     //var probability, dp3: String?
     var american: Int?
     //var factional, handicap: NSNull?
     var total: String?
     var winning: Bool?
     var stop: Bool?
     var bookmakerEventID: Int?
    //private var odd: Double
    public var value: String?
    init() {

    }
}

Body:
i changed model

struct BetterOdd : APIModel, Codable {
    var id: Int?
    var name: String?
    var suspended: Bool?
    var bookmaker: BetterBookmaker?
    //var betType: BetType = .threeWayResult

    enum BetType:Int, APIModel, Codable {
        case threeWayResult = 7
        case overUnder = 6
        case doubleChance = 5
        case bothTeamsToScore = 4
        case threeWayResultFirstHalf = 3
        case threeWayResultSecondHalf = 2
        case correctScore = 1
        case hTfTdouble = 0
    }
//
    func getBetType() -> BetType {
        if name == "3Way Result" {
            return .threeWayResult
        } else if name == "Over/Under" {
            return .overUnder
        } else if name == "Double Chance"  {
            return .doubleChance
        } else if name == "Both Teams To Score"  {
            return .bothTeamsToScore
        } else if  name == "3Way Result 1st Half" {
            return .threeWayResultFirstHalf
        } else if name == "3Way Result 2nd Half"{
            return .threeWayResultSecondHalf
        } else if name == "Correct Score"{
            return .correctScore
        } else if name == "HF/FT Double" {
            return .hTfTdouble
        } else {
            return .correctScore
        }
    }
}

and then :

let matchOddsArray  = match.odds!
let result = matchOddsArray.sorted(by: { $0.betType.rawValue > $1.betType.rawValue})
let bet = result[indexPath.row]

works perfect.


问:
Extracting numerical data from string
I have text data in a csv file in this format:

76.76% @ 26.2° C D: 20.7° C G/KG: 15.5

Date,Value,Formatted Value

2019-10-11 14:50:00,71.19,71.19% @ 24.4° C D: 17.7° C G/KG: 12.8

2019-10-11 15:00:00,72.2,72.2% @ 24.4° C D: 17.9° C G/KG: 13

2019-10-11 15:10:00,71.35,71.35% @ 24.4° C D: 17.8° C G/KG: 12.9

I would like to extract the each numerical data and store it in a different column. The numbers don't always contain a decimal place though.

Edit: The data is from a csv file and I would like to store each numerical data in a different column.

Title: Extracting numerical data from string

Body:
Try:

df.join(df['Formatted Value'].str.findall(r'\d+\.\d+|\d+').str.join(' ').str.split(expand=True)).drop('Formatted Value',axis=1)

                  Date  Value      0     1     2     3
0  2019-10-11 14:50:00  71.19  71.19  24.4  17.7  12.8
1  2019-10-11 15:00:00  72.20   72.2  24.4  17.9    13
2  2019-10-11 15:10:00  71.35  71.35  24.4  17.8  12.9


问:
Best practices of timeout after Ajax call
I have implemented a timeout after my table is reloaded with new data, previously. I was having trouble on how to update my dom after ajax was called as I'm developing front end js on top of an analytical webapp. I've come to a solution to use timeout which will load the dom after its refreshed but I am unsure if this is the best practice as I have to preset the time and different view will have different queries and rendering time.

```<code>  $( document ).ajaxSuccess(function( event, xhr, settings ) {
     setInterval(function(){
        let update = d3.selectAll("#" + arcapi.chartId() + ' tbody td')
        update.filter(function(){
           if(this.innerHTML === 'Tier 2'){
             return true;
            }
        }).style('background-color','green');
     }, 2000);
  });
</code>```

Note: I could not directly update from ajax code right after ajaxComplete is because I don't have access ajax file. This is the best solution I have so far in 8 days. Do let me know your input and opinion.

答:
You could follow below format as it mostly recommended among the engineers.
You could also read this official document

```<code>$.ajax({
        url: "YourRequestURL",
        error: function(){
            // This function would triggered when timeout occurred
        },
        success: function(){
            //Your logic after success request
        },
        timeout: 3000 // sets timeout 1 to 3 seconds is mostly used
    });
</code>```

Though there is no concrete rules for timeout but its recommended to
set it between 1000-5000. However, as per your requirement it might change.

Hope this would help

Body:
I have implemented a timeout after my table is reloaded with new data, previously. I was having trouble on how to update my dom after ajax was called as I'm developing front end js on top of an analytical webapp. I've come to a solution to use timeout which will load the dom after its refreshed but I am unsure if this is the best practice as I have to preset the time and different view will have different queries and rendering time.

  $( document ).ajaxSuccess(function( event, xhr, settings ) {
     setInterval(function(){
        let update = d3.selectAll("#" + arcapi.chartId() + ' tbody td')
        update.filter(function(){
           if(this.innerHTML === 'Tier 2'){
             return true;
            }
        }).style('background-color','green');
     }, 2000);
  });

Note: I could not directly update from ajax code right after ajaxComplete is because I don't have access ajax file. This is the best solution I have so far in 8 days. Do let me know your input and opinion.

Body:
You could follow below format as it mostly recommended among the engineers.
You could also read this official document

$.ajax({
        url: "YourRequestURL",
        error: function(){
            // This function would triggered when timeout occurred
        },
        success: function(){
            //Your logic after success request
        },
        timeout: 3000 // sets timeout 1 to 3 seconds is mostly used
    });

Though there is no concrete rules for timeout but its recommended to
set it between 1000-5000. However, as per your requirement it might change.

Hope this would help


问:
React-router and nginx
I am transitioning my react app from webpack-dev-server to nginx.

When I go to the root url "localhost:8080/login" I simply get a 404 and in my nginx log I see that it is trying to get:

```<code>my-nginx-container | 2017/05/12 21:07:01 [error] 6#6: *11 open() "/wwwroot/login" failed (2: No such file or directory), client: 172.20.0.1, server: , request: "GET /login HTTP/1.1", host: "localhost:8080"
my-nginx-container | 172.20.0.1 - - [12/May/2017:21:07:01 +0000] "GET /login HTTP/1.1" 404 169 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0) Gecko/20100101 Firefox/53.0" "-"
</code>```

Where should I look for a fix ?

My router bit in react looks like this:

```<code>render(

  <Provider store={store}>
    <MuiThemeProvider>
      <BrowserRouter history={history}>
        <div>
          Hello there p
          <Route path="/login" component={Login} />
          <App>

            <Route path="/albums" component={Albums}/>

            <Photos>
              <Route path="/photos" component={SearchPhotos}/>
            </Photos>
            <div></div>
            <Catalogs>
              <Route path="/catalogs/list" component={CatalogList}/>
              <Route path="/catalogs/new" component={NewCatalog}/>
              <Route path="/catalogs/:id/photos/" component={CatalogPhotos}/>
              <Route path="/catalogs/:id/photos/:photoId/card" component={PhotoCard}/>
            </Catalogs>
          </App>
        </div>
      </BrowserRouter>
    </MuiThemeProvider>
  </Provider>, app);
</code>```

And my nginx file like this:

```<code>user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;

    server {
        listen 8080;
        root /wwwroot;

        location / {
            root /wwwroot;
            index index.html;

            try_files $uri $uri/ /wwwroot/index.html;
        }

    }
}
</code>```

EDIT:

I know that most of the setup works because when I go to localhost:8080 without being logged in I get the login page as well. this is not through a redirect to localhost:8080/login - it is some react code.

答:
Maybe this is not the exact case here but for anyone running a docker container for their react project with react-router and webpack-dev-server, in my case I had everything I needed in my nginx.conf:

```<code>server {
    listen 80;
    location / {
      root   /usr/share/nginx/html;
      index  index.html index.htm;
      try_files $uri $uri/ /index.html;
    }
    error_page 404 /index.html;
    location = / {
      root /usr/share/nginx/html;
      internal;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   /usr/share/nginx/html;
    }
  }
</code>```

But still nginx wouldn't send 404 erros to the root /. After looking into the container I noticed that there's some configs in /etc/nginx/conf.d/default.conf which would somehow overrides my configs, so deleting that file in my dockerfile solved the problem:

```<code>...
FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf  # <= This line solved my issue
COPY nginx.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
</code>```

Title: React-router and nginx

Body:
I am transitioning my react app from webpack-dev-server to nginx.

When I go to the root url "localhost:8080/login" I simply get a 404 and in my nginx log I see that it is trying to get:

my-nginx-container | 2017/05/12 21:07:01 [error] 6#6: *11 open() "/wwwroot/login" failed (2: No such file or directory), client: 172.20.0.1, server: , request: "GET /login HTTP/1.1", host: "localhost:8080"
my-nginx-container | 172.20.0.1 - - [12/May/2017:21:07:01 +0000] "GET /login HTTP/1.1" 404 169 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0) Gecko/20100101 Firefox/53.0" "-"

Where should I look for a fix ?

My router bit in react looks like this:

render(

  <Provider store={store}>
    <MuiThemeProvider>
      <BrowserRouter history={history}>

          Hello there p
          <Route path="/login" component={Login} />
          <App>

            <Route path="/albums" component={Albums}/>

            <Photos>
              <Route path="/photos" component={SearchPhotos}/>
            </Photos>

            <Catalogs>
              <Route path="/catalogs/list" component={CatalogList}/>
              <Route path="/catalogs/new" component={NewCatalog}/>
              <Route path="/catalogs/:id/photos/" component={CatalogPhotos}/>
              <Route path="/catalogs/:id/photos/:photoId/card" component={PhotoCard}/>
            </Catalogs>
          </App>

      </BrowserRouter>
    </MuiThemeProvider>
  </Provider>, app);

And my nginx file like this:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;

    server {
        listen 8080;
        root /wwwroot;

        location / {
            root /wwwroot;
            index index.html;

            try_files $uri $uri/ /wwwroot/index.html;
        }

    }
}

EDIT:

I know that most of the setup works because when I go to localhost:8080 without being logged in I get the login page as well. this is not through a redirect to localhost:8080/login - it is some react code.

Body:
Maybe this is not the exact case here but for anyone running a docker container for their react project with react-router and webpack-dev-server, in my case I had everything I needed in my nginx.conf:

server {
    listen 80;
    location / {
      root   /usr/share/nginx/html;
      index  index.html index.htm;
      try_files $uri $uri/ /index.html;
    }
    error_page 404 /index.html;
    location = / {
      root /usr/share/nginx/html;
      internal;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   /usr/share/nginx/html;
    }
  }

But still nginx wouldn't send 404 erros to the root /. After looking into the container I noticed that there's some configs in /etc/nginx/conf.d/default.conf which would somehow overrides my configs, so deleting that file in my dockerfile solved the problem:

...
FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf  # <= This line solved my issue
COPY nginx.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]


问:
I have a .csv file that contains the edges of a graph (Name1, Name2). How do I convert this into a adjacency matrix?
I'm doing a machine learning project on Python that requires me to process some data and convert them into an adjacency matrix. The data is saved in csv files, and are saved as such:

```<code>114787,375519
114787,285613
114787,7448
114787,4914
114787,51343
.
.
</code>```

The problem is, these numbers do not represent indices but just names. There are only 19000 nodes or so, and the numbers in the .csv file are basically random names given to the various nodes of a graph.

I need to put all these into an adjacency matrix while retaining the information about which index is represented by which name and I cannot for the life of me figure out how to do so. Would really appreciate some help.

答:
I think below way will work.

import networkx as nx

f = open("edge_lst.csv", "rb")
G = nx.read_edgelist(f)
f.close()
```

Body:
I'm doing a machine learning project on Python that requires me to process some data and convert them into an adjacency matrix. The data is saved in csv files, and are saved as such:

114787,375519
114787,285613
114787,7448
114787,4914
114787,51343
.
.

The problem is, these numbers do not represent indices but just names. There are only 19000 nodes or so, and the numbers in the .csv file are basically random names given to the various nodes of a graph.

I need to put all these into an adjacency matrix while retaining the information about which index is represented by which name and I cannot for the life of me figure out how to do so. Would really appreciate some help.


问:
ASIHTTPRequest only works when i hardcode the strings
I have a problem that really makes me scratch my head. There seems to be no logical reason why this is happening. If i hardcode the string into the NSURL it works. But if I pass a NSString instead it doesnt work. I have confirmed that the NSString is identical to hardcoded string by NSLog both of them.

Code that works. Server returns a 200 responce code.

```<code>        //NSString * urlStr = [NSString stringWithFormat:@"http://www.server.com/%@",monograph.uri];
    NSURL *url = [NSURL URLWithString:@"http://www.server.com/api/monograph/com/3894.json"];

    ASIHTTPRequest *request;
    request = [ASIHTTPRequest requestWithURL:url];
    [request setUsername:appDelegate.key];
    [request setPassword:appDelegate.secret];
    [request setDelegate:self];
    [request startAsynchronous];
</code>```

Code that fails. Server returns 204 response code for this:

```<code>NSString * urlStr = [NSString stringWithFormat:@"http://www.server.com/%@",monograph.uri];
    NSURL *url = [NSURL URLWithString:urlStr];

    ASIHTTPRequest *request;
    request = [ASIHTTPRequest requestWithURL:url];
    [request setUsername:appDelegate.key];
    [request setPassword:appDelegate.secret];
    [request setDelegate:self];
    [request startAsynchronous];
</code>```

When i NSLog urlStr it contains:

```<code>http://www.server.com/api/monograph/com/3894.json
</code>```

What am i missing? There must be something to explain it -.-

Regards,
Code

EDIT

checked the length of both strings and they are both same length so seems not white spaces or anything hidden in there.

答:
Have you checked whether the NSURL object you get from the string variable is not nil? That could help you home in on the location of the problem.

Also, you might try escaping the string variable, just incase something funny is getting in with the stringWithFormat call.

Body:
I have a problem that really makes me scratch my head. There seems to be no logical reason why this is happening. If i hardcode the string into the NSURL it works. But if I pass a NSString instead it doesnt work. I have confirmed that the NSString is identical to hardcoded string by NSLog both of them.

Code that works. Server returns a 200 responce code.

        //NSString * urlStr = [NSString stringWithFormat:@"http://www.server.com/%@",monograph.uri];
    NSURL *url = [NSURL URLWithString:@"http://www.server.com/api/monograph/com/3894.json"];

    ASIHTTPRequest *request;
    request = [ASIHTTPRequest requestWithURL:url];
    [request setUsername:appDelegate.key];
    [request setPassword:appDelegate.secret];
    [request setDelegate:self];
    [request startAsynchronous];

Code that fails. Server returns 204 response code for this:

NSString * urlStr = [NSString stringWithFormat:@"http://www.server.com/%@",monograph.uri];
    NSURL *url = [NSURL URLWithString:urlStr];

    ASIHTTPRequest *request;
    request = [ASIHTTPRequest requestWithURL:url];
    [request setUsername:appDelegate.key];
    [request setPassword:appDelegate.secret];
    [request setDelegate:self];
    [request startAsynchronous];

When i NSLog urlStr it contains:

http://www.server.com/api/monograph/com/3894.json

What am i missing? There must be something to explain it -.-

Regards,
Code

EDIT

checked the length of both strings and they are both same length so seems not white spaces or anything hidden in there.


问:
Table from the mapped JSON object consisting of many arrays
I'm working on a project in React and I'm having trouble mapping the JSON object that gets from the API. I want to get a table like this:

Image

and the JSON object looks like this:

```<code>{
"userName": "user1",
"memberCommunity": [
    {
        "userName": "user5",
        "community": [
            {
                "level": 1,
                "members": 3
            },
            {
                "level": 2,
                "members": 3
            },
            {
                "level": 3,
                "members": 1
            }
        ]
    },
    {
        "userName": "user18",
        "community": []
    },
    {
        "userName": "user2",
        "community": [
            {
                "level": 1,
                "members": 3
            },
            {
                "level": 2,
                "members": 4
            },
            {
                "level": 3,
                "members": 3
            },
            {
                "level": 4,
                "members": 6
            },
            {
                "level": 5,
                "members": 2
            },
            {
                "level": 6,
                "members": 1
            }
        ]
    }
]
</code>```

}

The table image was created exactly on the data that I gave. The problem here is the proper use of the Map function, thanks to which I will get records with three users and for each of them the appropriate value in the level field. I hope I won't mix it up and you know what's going on :) Please help.

答:
You can accomplish this with 2 reduce functions to iterate over the nested arrays.

const data = {
  userName: "user1",
  memberCommunity: [
    {
      userName: "user5",
      community: [
        {
          level: 1,
          members: 3
        },
        {
          level: 2,
          members: 3
        },
        {
          level: 3,
          members: 1
        }
      ]
    },
    {
      userName: "user18",
      community: []
    },
    {
      userName: "user2",
      community: [
        {
          level: 1,
          members: 3
        },
        {
          level: 2,
          members: 4
        },
        {
          level: 3,
          members: 3
        },
        {
          level: 4,
          members: 6
        },
        {
          level: 5,
          members: 2
        },
        {
          level: 6,
          members: 1
        }
      ]
    }
  ]
};

const format = data.memberCommunity.reduce((acc, curr) => {
  return {
    ...acc,
    [curr.userName]: curr.community.reduce((acc2, curr2) => {
      return {
        ...acc2,
        [`level ${curr2.level}`]: curr2.members
      }
    }, {}),
  };
}, {});

console.log(format);```

Body:
I'm working on a project in React and I'm having trouble mapping the JSON object that gets from the API. I want to get a table like this:

Image

and the JSON object looks like this:

{
"userName": "user1",
"memberCommunity": [
    {
        "userName": "user5",
        "community": [
            {
                "level": 1,
                "members": 3
            },
            {
                "level": 2,
                "members": 3
            },
            {
                "level": 3,
                "members": 1
            }
        ]
    },
    {
        "userName": "user18",
        "community": []
    },
    {
        "userName": "user2",
        "community": [
            {
                "level": 1,
                "members": 3
            },
            {
                "level": 2,
                "members": 4
            },
            {
                "level": 3,
                "members": 3
            },
            {
                "level": 4,
                "members": 6
            },
            {
                "level": 5,
                "members": 2
            },
            {
                "level": 6,
                "members": 1
            }
        ]
    }
]

}

The table image was created exactly on the data that I gave. The problem here is the proper use of the Map function, thanks to which I will get records with three users and for each of them the appropriate value in the level field. I hope I won't mix it up and you know what's going on :) Please help.


问:
I am trying to migrate my model - but it's giving me error -
Error - client.Client.status: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples.

Here is the code:

```<code>class Client(models.Model):
    client_name = models.CharField(max_length=300)
    address = models.CharField(max_length=300)
    start_date = models.DateField(default=datetime.now, blank=True)
    end_date = models.DateField(default=datetime.now, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    ACTIVE = 'AC',
    TO_EXPIRE = 'TE',
    EXPIRED = 'EX',
    STATUS_CHOICES = [
        (ACTIVE, 'Active'),
        (TO_EXPIRE, 'To Expire'),
        (EXPIRED, 'Expired'),

    ]
    status = models.CharField(max_length=2, choices=STATUS_CHOICES, default=ACTIVE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
</code>```

答:
Your issue is simple, but subtle:

```<code>ACTIVE = 'AC',
TO_EXPIRE = 'TE',
EXPIRED = 'EX',
</code>```

You must remove the trailing commas here. Python interprets these as tuples of length one with the 0 index value equal to the string.

eg

```<code>ACTIVE = ('AC',)
# is equivalent to
ACTIVE = 'AC',
</code>```

What you want here is simply ACTIVE = 'AC'

Body:
Error - client.Client.status: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples.

Here is the code:

class Client(models.Model):
    client_name = models.CharField(max_length=300)
    address = models.CharField(max_length=300)
    start_date = models.DateField(default=datetime.now, blank=True)
    end_date = models.DateField(default=datetime.now, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    ACTIVE = 'AC',
    TO_EXPIRE = 'TE',
    EXPIRED = 'EX',
    STATUS_CHOICES = [
        (ACTIVE, 'Active'),
        (TO_EXPIRE, 'To Expire'),
        (EXPIRED, 'Expired'),

    ]
    status = models.CharField(max_length=2, choices=STATUS_CHOICES, default=ACTIVE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

Body:
Your issue is simple, but subtle:

ACTIVE = 'AC',
TO_EXPIRE = 'TE',
EXPIRED = 'EX',

You must remove the trailing commas here. Python interprets these as tuples of length one with the 0 index value equal to the string.

eg

ACTIVE = ('AC',)
# is equivalent to
ACTIVE = 'AC',

What you want here is simply ACTIVE = 'AC'


问:
Escape $ sign using sed
I have a string in file a:

```<code>  my_password: "@$hp!sN0t"
</code>```

I want to escape the dollar sign by adding a backslash before it using sed. The output file b should contain:

```<code>  my_password: "@\$hp!sN0t"
</code>```

I used the command:

```<code>sed 's/\$/\\$/g' a >b
</code>```

And it works well.

But I want to skip escaping the dollar signs that are purposefully used for variables in the file.

For example, ${KEY_FILE_URI} is a variable mentioned inside the same file and its dollar sign should not be escaped.

Otherwise, the command should be able to replace the $ with \$ only if the $ comes inside double-quotes.

The other way is to use a second command to relace the \${ in file b with ${ and write to file c.

```<code>sed 's/\\${/${/g' b >c
</code>```

Is there any simpler method for this? How can I do that correctly?

答:
If you insist on metaprogramming:

```<code>awk '$1 == "my_password:" {gsub(/\$/, "\\$")} 1' a
</code>```

On lines wherein the first field (word) is "my_password:", perform a global substitution: literal dollar signs (not end-of-line regex markers) are replaced by literal backslashes followed by literal dollar signs. The 1 effectively means true and will perform the default action (print record) for all records. It could be written {print} or {print $0}.

Title: Escape $ sign using sed

Body:
I have a string in file a:

  my_password: "@$hp!sN0t"

I want to escape the dollar sign by adding a backslash before it using sed. The output file b should contain:

  my_password: "@\$hp!sN0t"

I used the command:

sed 's/\$/\\$/g' a >b

And it works well.

But I want to skip escaping the dollar signs that are purposefully used for variables in the file.

For example, ${KEY_FILE_URI} is a variable mentioned inside the same file and its dollar sign should not be escaped.

Otherwise, the command should be able to replace the $ with \$ only if the $ comes inside double-quotes.

The other way is to use a second command to relace the \${ in file b with ${ and write to file c.

sed 's/\\${/${/g' b >c

Is there any simpler method for this? How can I do that correctly?

Body:
If you insist on metaprogramming:

awk '$1 == "my_password:" {gsub(/\$/, "\\$")} 1' a

On lines wherein the first field (word) is "my_password:", perform a global substitution: literal dollar signs (not end-of-line regex markers) are replaced by literal backslashes followed by literal dollar signs. The 1 effectively means true and will perform the default action (print record) for all records. It could be written {print} or {print $0}.


问:
Stream images with h.264 encoding
I am extracting frames from camera and doing processing on the extracted frame.Once the processing is done, I want to stream these frames with h.264 encoding to other system.How can I do that?</p>

答:
if you want to stream data over UDP socket - use RTP protocol for streaming.

Please go through the rfc specification of RFC 6184

Media Pieline for processing the camera data:

Camera RAW data ( RGB/YUV/NV12) -> H.264 encoder -> NALU packets RTP packetization-> Socket communication.

You can use ffmpeg python interface to achieve this goal.

Title: Stream images with h.264 encoding


问:
Angular pushing an array of an user object into a subject
I'm developping a single app and at the moment the only good behavior is that I'm getting an user from an API with HttpClient method.
The method is store in a service.

Getting the user is a success but now I want to get a specific array from that user to re-use it by my will.

Should I make another service since this value will be use in 2 components ?
How should I procced to get this array in a var ?

Exemple of user object :

```<code>{
  firstName: '',
  lastName: '',
  arrayIWant: []
}
</code>```

My user is in a subject and here is the way I use it in a component

```<code>  user: User;
  userSubscription: Subscription;

  constructor(
    public userService: UserService
  ) {
  }

  ngOnInit() {
    this.userSubscription = this.userService.userSubject.subscribe(
      (user: User) => {
        this.user = user;
      }
    );
    this.userService.getSingleUserFromServer();
    this.userService.emitUser();
  }

  ngOnDestroy() {
    this.userSubscription.unsubscribe();
  }
</code>```

Should I put this code in every component where I want to use the user or is there a way to definie globaly the user ?

答:
You can use a BehaviourSubject which will hold the last value of whatever that service populates the userSubject with

```<code>public userSubject: BehaviourSubject<User> = new BehaviourSubject(null);

getSingleUserFromServer(): void {
   //get your user from http
   userSubject.next(result);
}
</code>```

In you HTML you can use the async pipe to display the values of the inner array you want. Or just use it in your component by subscribing to the last emission of the behaviourSubject

```<code>//X.Component
public subscriptionKiller: Subject<void> = new Subject();
ngOnInit(): void {
    this.userService.userSubject
        .pipe(takeUntil(this.subscriptionKiller))
        .subscribe((lastUser: User) => {
        someMethod(this.userService.userSubject.value.arrayIWant);
    }
}

ngOnDestroy(): void {
    this.subscriptionKiller.next()
}
</code>```

Body:
I'm developping a single app and at the moment the only good behavior is that I'm getting an user from an API with HttpClient method.
The method is store in a service.

Getting the user is a success but now I want to get a specific array from that user to re-use it by my will.

Should I make another service since this value will be use in 2 components ?
How should I procced to get this array in a var ?

Exemple of user object :

{
  firstName: '',
  lastName: '',
  arrayIWant: []
}

My user is in a subject and here is the way I use it in a component

  user: User;
  userSubscription: Subscription;

  constructor(
    public userService: UserService
  ) {
  }

  ngOnInit() {
    this.userSubscription = this.userService.userSubject.subscribe(
      (user: User) => {
        this.user = user;
      }
    );
    this.userService.getSingleUserFromServer();
    this.userService.emitUser();
  }

  ngOnDestroy() {
    this.userSubscription.unsubscribe();
  }

Should I put this code in every component where I want to use the user or is there a way to definie globaly the user ?

Body:
You can use a BehaviourSubject which will hold the last value of whatever that service populates the userSubject with

public userSubject: BehaviourSubject<User> = new BehaviourSubject(null);

getSingleUserFromServer(): void {
   //get your user from http
   userSubject.next(result);
}

In you HTML you can use the async pipe to display the values of the inner array you want. Or just use it in your component by subscribing to the last emission of the behaviourSubject

//X.Component
public subscriptionKiller: Subject<void> = new Subject();
ngOnInit(): void {
    this.userService.userSubject
        .pipe(takeUntil(this.subscriptionKiller))
        .subscribe((lastUser: User) => {
        someMethod(this.userService.userSubject.value.arrayIWant);
    }
}

ngOnDestroy(): void {
    this.subscriptionKiller.next()
}


问:
How to Export the CSV in MongoDB with out giving any fields
I have a collection where it has many fields, from that i have to export the CSV with all the fields.

As of now i am using the below command to export the CSV file.

mongoexport --db test --host 172.00.00.000 --port 97027 -c RdMergeData --type csv  --fields name,phone,group --out /Users/macair/data.csv

With the above command i have to use the field names always when i want to export an CSV, in my data i have many fields where i cannot type all those field names every time.

How can we export an CSV with all the fields without typing the field names manually in the command.

答:
According to the documentation, you must specify the field list when exporting to CSV.  If you want to export to JSON instead, you do not have to specify the field list.

You can use a file to specify the fields to export, which may be easier for you as you can create the file once and then reuse it for multiple exports.

See https://docs.mongodb.com/manual/reference/program/mongoexport/#export-in-csv-format for more details.


问:
C# code showing error "A namespace cannot directly contain members such as fields or methods"
I don't know why this error pops up I don't have anything declared out of class my full code is this:

```<code>using System;
using Microsoft.CSharp;
using System.IO;
using System.CodeDom.Compiler;
using System.Text;

namespace test
  {
  public class comp
   {
    static void Main()
    {
        string code="0x4d,0x41,0x2......"; //and soo onnn
        string Arch = " /platform:x86 /optimize";
        string filePath = "C:/menmon.exe";
        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerParameters parameters = new CompilerParameters();

        parameters.ReferencedAssemblies.Add("System.Core.dll");
        parameters.GenerateInMemory = false;
        parameters.GenerateExecutable = true;
        parameters.IncludeDebugInformation = false;
        parameters.ReferencedAssemblies.Add("mscorlib.dll");
        parameters.ReferencedAssemblies.Add("System.dll");

        parameters.OutputAssembly = filePath;
        parameters.CompilerOptions = "/target:exe" + Arch;
        CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
        if (results.Errors.HasErrors)
        {
        StringBuilder sb = new StringBuilder();
        foreach (CompilerError error in results.Errors)
          {
            sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
          }
        }

        throw new InvalidOperationException(sb.ToString());
      }
    }
  }
</code>```

}

Compiled this using cmd on Windows machine on .Net framework64 v4.0.30319
error happens after compilation(on compilation no error is shown) when I run the program this error pops up:

Unhandled Exception: System.InvalidOperationException: Error (CS0116):
  A namespace cannot directly contain members such as fields or methods

at comp.Main()

I ran csc.exe like this

csc /t:exe /out:"C:\output.exe" "C:\input.cs"

答:
Not sure will this help you but can you please try to add namespace of your App just up of the class so it looks like this:

```<code>namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}
</code>```

Also you are missing semi colon on the last line in main function.

Body:
I don't know why this error pops up I don't have anything declared out of class my full code is this:

using System;
using Microsoft.CSharp;
using System.IO;
using System.CodeDom.Compiler;
using System.Text;

namespace test
  {
  public class comp
   {
    static void Main()
    {
        string code="0x4d,0x41,0x2......"; //and soo onnn
        string Arch = " /platform:x86 /optimize";
        string filePath = "C:/menmon.exe";
        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerParameters parameters = new CompilerParameters();

        parameters.ReferencedAssemblies.Add("System.Core.dll");
        parameters.GenerateInMemory = false;
        parameters.GenerateExecutable = true;
        parameters.IncludeDebugInformation = false;
        parameters.ReferencedAssemblies.Add("mscorlib.dll");
        parameters.ReferencedAssemblies.Add("System.dll");

        parameters.OutputAssembly = filePath;
        parameters.CompilerOptions = "/target:exe" + Arch;
        CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
        if (results.Errors.HasErrors)
        {
        StringBuilder sb = new StringBuilder();
        foreach (CompilerError error in results.Errors)
          {
            sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
          }
        }

        throw new InvalidOperationException(sb.ToString());
      }
    }
  }

}

Compiled this using cmd on Windows machine on .Net framework64 v4.0.30319
error happens after compilation(on compilation no error is shown) when I run the program this error pops up:

Unhandled Exception: System.InvalidOperationException: Error (CS0116):
  A namespace cannot directly contain members such as fields or methods

at comp.Main()

I ran csc.exe like this

csc /t:exe /out:"C:\output.exe" "C:\input.cs"

Body:
Not sure will this help you but can you please try to add namespace of your App just up of the class so it looks like this:

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

Also you are missing semi colon on the last line in main function.


问:
How to make code wait for okay/cancel button selection?
I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.

I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.

Here is my complete source code
http://pastebin.com/uw7bvtn7

The section where I have the problem is at line 127-151.

```<code>$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 600,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("<h3><b>Users</b></h3>" + makeDialogTable(users) + "<h3><b>Owners</b></h3>" + makeDialogTable(owners));
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },

    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    } // buttons

}); // dialog

alert(is_okay);
</code>```

What the code does right now is to first show the dialog and then the alert(is_okay) on top.

What I would like is that the code first continues when the user have pressed OK or Cancel.

How could that be done?

答:
```<code>$("#dialog-confirm").dialog({  ...
close :(event, ui) { alert(is_okay);}
})
</code>```

Or you can bind function later :

```<code>$( "#dialog-confirm" ).bind( "dialogclose", function(event, ui) {
   alert(is_okay);
});
</code>```

The code doesn't stop and continue like it does with alert , but it will display message only when dialog is closed.

Body:
I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.

I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.

Here is my complete source code
http://pastebin.com/uw7bvtn7

The section where I have the problem is at line 127-151.

$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 600,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("
Users
" + makeDialogTable(users) + "
Owners
" + makeDialogTable(owners));
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },

    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    } // buttons

}); // dialog

alert(is_okay);

What the code does right now is to first show the dialog and then the alert(is_okay) on top.

What I would like is that the code first continues when the user have pressed OK or Cancel.

How could that be done?

Body:
$("#dialog-confirm").dialog({  ...
close :(event, ui) { alert(is_okay);}
})

Or you can bind function later :

$( "#dialog-confirm" ).bind( "dialogclose", function(event, ui) {
   alert(is_okay);
});

The code doesn't stop and continue like it does with alert , but it will display message only when dialog is closed.


问:
Delete X files in each folders and sub folders
I want to delete files in a folder and its subfolders but not X last files again in each folder. For example in C:\Test I want to keep 10 txt files but also in C:\Test\subtest1 and C:\Test\subtest2. Here, X X is the number of files I want to keep.

But it will not keep 10 files in each folder but in the entire arborescence.

My script is not fully functional, but it did it well in the C:\Test directory:

```<code>Set-ExecutionPolicy unrestricted $txtfiles = 'C:\Users\MUC8VX\Documents\Test
ForEach-Object {    Get-ChildItem $txtfiles | where{ -not $_.PsIsContainer}|
     sort LastWriteTime -desc| select -Skip 10 |
     Remove-Item -Include *.txt* -Force }
</code>```

And if I add -Recurse it will not keep 10 files in each folders but in the entire arborescence:

```<code>Set-ExecutionPolicy unrestricted
$txtfiles =`C:\Users\MUC8VX\Documents\Test'
ForEach-Object {    Get-ChildItem $txtfiles -Recurse | where{ -not
 $_.PsIsContainer}| sort LastWriteTime -desc|
     select -Skip 10 | Remove-Item -Include *.txt* -Force }
</code>```

edit :
Thanks a lot Manuel Batsching.

Here's a generic script :

```<code>#Insert your parent folder which contains files and subfolders

Get-Childitem -Path C:\Your\Parent\Folder -Recurse |

Group-Object Directory |
ForEach-Object {
    $_.Group |

        #sort by the last written files
        Sort-Object LastWriteTime -Descending |

        #Keep the X last files you want to keep
        Select-Object -Skip X |

        #Remove files according to their extension
        Remove-Item -Include *.extension* -Force }
</code>```

答:
If you are looking for a solution, that also applies to nested subfolders, you can list all files recursively and then group them by the path of their respective parent folder. Then apply your sorting rules and reduce each group to 10 elements.</p>

```<code>Get-Childitem *.txt -Recurse |
    Group-Object Directory |
    ForEach-Object {
        $_.Group |
            Sort-Object LastWriteTime -Descending |
            Select-Object -Skip 10 |
            Remove-Item }
</code>```

Body:
I want to delete files in a folder and its subfolders but not X last files again in each folder. For example in C:\Test I want to keep 10 txt files but also in C:\Test\subtest1 and C:\Test\subtest2. Here, X X is the number of files I want to keep.

But it will not keep 10 files in each folder but in the entire arborescence.

My script is not fully functional, but it did it well in the C:\Test directory:

Set-ExecutionPolicy unrestricted $txtfiles = 'C:\Users\MUC8VX\Documents\Test
ForEach-Object {    Get-ChildItem $txtfiles | where{ -not $_.PsIsContainer}|
     sort LastWriteTime -desc| select -Skip 10 |
     Remove-Item -Include *.txt* -Force }

And if I add -Recurse it will not keep 10 files in each folders but in the entire arborescence:

Set-ExecutionPolicy unrestricted
$txtfiles =`C:\Users\MUC8VX\Documents\Test'
ForEach-Object {    Get-ChildItem $txtfiles -Recurse | where{ -not
 $_.PsIsContainer}| sort LastWriteTime -desc|
     select -Skip 10 | Remove-Item -Include *.txt* -Force }

edit :
Thanks a lot Manuel Batsching.

Here's a generic script :

#Insert your parent folder which contains files and subfolders

Get-Childitem -Path C:\Your\Parent\Folder -Recurse |

Group-Object Directory |
ForEach-Object {
    $_.Group |

        #sort by the last written files
        Sort-Object LastWriteTime -Descending |

        #Keep the X last files you want to keep
        Select-Object -Skip X |

        #Remove files according to their extension
        Remove-Item -Include *.extension* -Force }

Body:
If you are looking for a solution, that also applies to nested subfolders, you can list all files recursively and then group them by the path of their respective parent folder. Then apply your sorting rules and reduce each group to 10 elements.

Get-Childitem *.txt -Recurse |
    Group-Object Directory |
    ForEach-Object {
        $_.Group |
            Sort-Object LastWriteTime -Descending |
            Select-Object -Skip 10 |
            Remove-Item }


问:
How do I replace a character in a string in Java?
Using Java, I want to go through the lines of a text and replace all ampersand symbols (&) with the XML entity reference &.

I scan the lines of the text and then each word in the text with the Scanner class. Then I use the CharacterIterator to iterate over each characters of the word.  However, how can I replace the character?  First, Strings are immutable objects.  Second, I want to replace a character (&) with several characters(amp&;).  How should I approach this?

```<code>CharacterIterator it = new StringCharacterIterator(token);
for(char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
       if(ch == '&') {

       }
}
</code>```

答:
You can use stream and flatMap to map & to &

```<code>    String str = "begin&end";
    String newString = str.chars()
        .flatMap(ch -> (ch == '&') ? "&".chars() : IntStream.of(ch))
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Using Java, I want to go through the lines of a text and replace all ampersand symbols (&) with the XML entity reference &.

I scan the lines of the text and then each word in the text with the Scanner class. Then I use the CharacterIterator to iterate over each characters of the word.  However, how can I replace the character?  First, Strings are immutable objects.  Second, I want to replace a character (&) with several characters(amp&;).  How should I approach this?

CharacterIterator it = new StringCharacterIterator(token);
for(char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
       if(ch == '&') {

       }
}

Body:
You can use stream and flatMap to map & to &amp;

    String str = "begin&end";
    String newString = str.chars()
        .flatMap(ch -> (ch == '&') ? "&amp;".chars() : IntStream.of(ch))
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();


问:
Can someone help me with this linked list? C++
I have an object oriented exam tomorrow and I'm still stuck with linked lists. For some reason I cant quite understand how they work or how to implement them properly. I've watched a lot of videos and tutorials but it still is quite complex. I always get an error which prints nothing to the console, just a blank black page. Can someone tell em what am I doing wrong?
Thank you.</p>

```<code>#include <iostream>
#include <string>

using namespace std;

struct node
{
    string name;
    int number;
    node* next;
};
struct node* head = 0;

class Employees
{
private:
    node* head, * tail;
public:
    Employees()
    {
        head = NULL;
        tail = NULL;
    }
    void addToList(string Name, int Num)
    {
        node* n = new node;
        n->name = Name;
        n->number = Num;
        n->next = NULL;
        if (head == NULL)
        {
            head = n;
            tail = n;
        }
        else
        {
            tail->next = n;
            tail = tail->next;
        }
    }
    void PrintAll()
    {
        while (head != NULL)
        {
            node* current;
            while (current != NULL)
            {
                cout << current->name << "\t";
                cout << current->number;
            }
        }
    }
};

int main()
{
    Employees a;
    a.addToList("Robert", 54);
    a.addToList("Manny", 77);

    a.PrintAll();

}
</code>```

答:
For starters this declaration in the global namespace

```<code>struct node
{
    string name;
    int number;
    node* next;
};
struct node* head = 0;
^^^^^^^^^^^^^^^^^^^^^
</code>```

is redundant and is used nowhere. Remove it.

It is better to make the structure node an inner member of the class Employees. For example

```<code>class Employees
{
private:
    struct node
    {
        string name;
        int number;
        node* next;
    } *head = nullptr, *tail = nullptr;
    //...
</code>```

The constructor does nothing special. So it can be defined as a default constructor.

```<code> Employees() = default;
</code>```

Th function addToList should accept the first argument by constant reference

```<code>void addToList( const string &Name, int Num )
                ^^^^^^^^^^^^^^^^^^
</code>```

The function PrintAll has an infinite loop when the pointer head is not a null pointer

```<code>void PrintAll()
{
    while (head != NULL)
    {
        //...
    }
}
</code>```

and moreover it invokes undefined behavior because the used pointer current was not initialized

```<code>node* current;
while (current != NULL)
</code>```

The function should be declared with the qualifier const because it does not change the list itself.

Also you need a destructor to free the dynamically allocated memory for nodes. Also you could suppress the copy construction and assignment.

Here is a demonstrative program that shows how the class can be implemented.

```<code>#include <iostream>
#include <string>

using namespace std;

class Employees
{
private:
    struct node
    {
        string name;
        int number;
        node* next;
    } *head = nullptr, *tail = nullptr;

public:
    Employees() = default;

    ~Employees()
    {
        while ( head != nullptr )
        {
            node *tmp = head;
            head = head->next;
            delete tmp;
        }
        tail = nullptr;
    }

    Employees( const Employees & ) = delete;
    Employees & operator =( const Employees & ) = delete;

    void addToList( const string &Name, int Num )
    {
        node *n = new node { Name, Num, nullptr };

        if ( head == nullptr )
        {
            head = n;
            tail = n;
        }
        else
        {
            tail->next = n;
            tail = tail->next;
        }
    }

    void PrintAll() const
    {
        for ( node *current = head; current != nullptr; current = current->next )
        {
            cout << current->name << ' ';
            cout << current->number << '\t';
        }
    }
};

int main()
{
    Employees a;
    a.addToList( "Robert", 54 );
    a.addToList( "Manny", 77 );

    a.PrintAll();

    cout << endl;
}
</code>```

The program output is

```<code>Robert 54   Manny 77
</code>```

Body:
I have an object oriented exam tomorrow and I'm still stuck with linked lists. For some reason I cant quite understand how they work or how to implement them properly. I've watched a lot of videos and tutorials but it still is quite complex. I always get an error which prints nothing to the console, just a blank black page. Can someone tell em what am I doing wrong?
Thank you.

#include <iostream>
#include <string>

using namespace std;

struct node
{
    string name;
    int number;
    node* next;
};
struct node* head = 0;

class Employees
{
private:
    node* head, * tail;
public:
    Employees()
    {
        head = NULL;
        tail = NULL;
    }
    void addToList(string Name, int Num)
    {
        node* n = new node;
        n->name = Name;
        n->number = Num;
        n->next = NULL;
        if (head == NULL)
        {
            head = n;
            tail = n;
        }
        else
        {
            tail->next = n;
            tail = tail->next;
        }
    }
    void PrintAll()
    {
        while (head != NULL)
        {
            node* current;
            while (current != NULL)
            {
                cout << current->name << "\t";
                cout << current->number;
            }
        }
    }
};

int main()
{
    Employees a;
    a.addToList("Robert", 54);
    a.addToList("Manny", 77);

    a.PrintAll();

}

Body:
For starters this declaration in the global namespace

struct node
{
    string name;
    int number;
    node* next;
};
struct node* head = 0;
^^^^^^^^^^^^^^^^^^^^^

is redundant and is used nowhere. Remove it.

It is better to make the structure node an inner member of the class Employees. For example

class Employees
{
private:
    struct node
    {
        string name;
        int number;
        node* next;
    } *head = nullptr, *tail = nullptr;
    //...

The constructor does nothing special. So it can be defined as a default constructor.

 Employees() = default;

Th function addToList should accept the first argument by constant reference

void addToList( const string &Name, int Num )
                ^^^^^^^^^^^^^^^^^^

The function PrintAll has an infinite loop when the pointer head is not a null pointer

void PrintAll()
{
    while (head != NULL)
    {
        //...
    }
}

and moreover it invokes undefined behavior because the used pointer current was not initialized

node* current;
while (current != NULL)

The function should be declared with the qualifier const because it does not change the list itself.

Also you need a destructor to free the dynamically allocated memory for nodes. Also you could suppress the copy construction and assignment.

Here is a demonstrative program that shows how the class can be implemented.

#include <iostream>
#include <string>

using namespace std;

class Employees
{
private:
    struct node
    {
        string name;
        int number;
        node* next;
    } *head = nullptr, *tail = nullptr;

public:
    Employees() = default;

    ~Employees()
    {
        while ( head != nullptr )
        {
            node *tmp = head;
            head = head->next;
            delete tmp;
        }
        tail = nullptr;
    }

    Employees( const Employees & ) = delete;
    Employees & operator =( const Employees & ) = delete;

    void addToList( const string &Name, int Num )
    {
        node *n = new node { Name, Num, nullptr };

        if ( head == nullptr )
        {
            head = n;
            tail = n;
        }
        else
        {
            tail->next = n;
            tail = tail->next;
        }
    }

    void PrintAll() const
    {
        for ( node *current = head; current != nullptr; current = current->next )
        {
            cout << current->name << ' ';
            cout << current->number << '\t';
        }
    }
};

int main()
{
    Employees a;
    a.addToList( "Robert", 54 );
    a.addToList( "Manny", 77 );

    a.PrintAll();

    cout << endl;
}

The program output is

Robert 54   Manny 77


问:
Ionicons version 5 with angular
How to add ionicons version 5 to angular, with version 4.5 there was a scss available and I can use in that way but now in version 5 ionicons use svgs and don't know how to integrate it with angular.

Current approach
In angular.json

```<code>"styles": [
              "./node_modules/ionicons/dist/scss/ionicons.scss",
              "src/app/theme/styles/styles.scss"
            ],
</code>```

Then in my app.component.ts (I'm using nebular UI)
https://akveo.github.io/nebular/docs/guides/register-icon-pack#register-icon-pack

```<code>export class AppComponent implements OnInit {

  constructor(private iconsLibrary: NbIconLibraries, public store$: Store<any>, ) {
    iconsLibrary.registerFontPack('ion', { iconClassPrefix: 'ion' });
    iconsLibrary.registerFontPack('nebular', { iconClassPrefix: 'nb' });
    iconsLibrary.setDefaultPack('nebular');
    // @ts-ignore
    if (window.Cypress) {
      // @ts-ignore
      window.__appStore__ = store$;
    }
  }

  ngOnInit() {
  }
}
</code>```

I see in issues that for ionic with angular them add

```<code>"assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "assets"
              },
              {
                "glob": "**/*.svg",
                "input": "node_modules/ionicons/dist/ionicons/svg",
                "output": "./svg"
              }
            ]
</code>```

but I don't know how to continue

答: Ionicons ver 5 doesn't looks like supporting font icon file like Ionic 4 ,https://github.com/ionic-team/ionicons/tree/4.x#using-the-font-icon anymore.</p>

Title: Ionicons version 5 with angular

Body:
How to add ionicons version 5 to angular, with version 4.5 there was a scss available and I can use in that way but now in version 5 ionicons use svgs and don't know how to integrate it with angular.

Current approach
In angular.json

"styles": [
              "./node_modules/ionicons/dist/scss/ionicons.scss",
              "src/app/theme/styles/styles.scss"
            ],

Then in my app.component.ts (I'm using nebular UI)
https://akveo.github.io/nebular/docs/guides/register-icon-pack#register-icon-pack

export class AppComponent implements OnInit {

  constructor(private iconsLibrary: NbIconLibraries, public store$: Store<any>, ) {
    iconsLibrary.registerFontPack('ion', { iconClassPrefix: 'ion' });
    iconsLibrary.registerFontPack('nebular', { iconClassPrefix: 'nb' });
    iconsLibrary.setDefaultPack('nebular');
    // @ts-ignore
    if (window.Cypress) {
      // @ts-ignore
      window.__appStore__ = store$;
    }
  }

  ngOnInit() {
  }
}

I see in issues that for ionic with angular them add

"assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "assets"
              },
              {
                "glob": "**/*.svg",
                "input": "node_modules/ionicons/dist/ionicons/svg",
                "output": "./svg"
              }
            ]

but I don't know how to continue


问:
Custom number format with unit in EPPlus
Is it possible to set the format for a cell/column in excel like shown in the image using EPPlus?
What's the proper syntax to achieve that? The following code doesn't work.

```<code>worksheet.Cells[row, col].Style.Numberformat.Format = @"@"" Mhz""";
</code>```

答:
convert the value to string

```<code>worksheet.Cells[row, col].Style.Numberformat.Format = @"@"" Mhz""";
worksheet.Cells[row, col].Value = "10.5";
</code>```

Body:
Is it possible to set the format for a cell/column in excel like shown in the image using EPPlus?
What's the proper syntax to achieve that? The following code doesn't work.

worksheet.Cells[row, col].Style.Numberformat.Format = @"@"" Mhz""";

Body:
convert the value to string

worksheet.Cells[row, col].Style.Numberformat.Format = @"@"" Mhz""";
worksheet.Cells[row, col].Value = "10.5";


问:
Gradle single-project pluginManagement block not working (Kotlin DSL)
I need to change a multi-project build to a single-project build, as there is and only ever will be one project in this repo.  Currently, in settings.gradle, I have a custom plugin repo that currently uses a pluginManagement block with resolutionStrategy and my list of repo's:

```<code>pluginManagement {
    resolutionStrategy {
        eachPlugin {
            if (requested.id.namespace == 'com.meanwhileinhell.plugin') {
                useModule('com.meanwhileinhell:gradle-plugin:1.0.0-SNAPSHOT')
            }
        }
    }

    repositories {
        mavenLocal()
        maven { url "https://repo.spring.io/milestone" }
        maven { url "https://plugins.gradle.org/m2/" }

        // Meanwhileinhell repo
        maven {
            url "s3://mvn.meanwhileinhell.com/releases"
            credentials(AwsCredentials) {
                accessKey s3_access_key
                secretKey s3_access_secret
            }
        }
    }

    plugins {
        ...
        ...
    }
}
</code>```

However, deleting settings.gradle and moving this block into my build.gradle.kts (Kotlin DSL) seems to do nothing.  I've tried wrapping in a

```<code>configurations {
    all {
        resolutionStrategy {
            eachPlugin {
                ...
            }
        }
    }
}
</code>```

and also

```<code>settings {
    pluginManagement {
        resolutionStrategy {
            eachPlugin {
                ...
            }
        }
    }
}
</code>```

I found a SO answer that used settingsEvaluated in order to get the settings object, but again this was a no go.

Currently my build.gradle.kts looks like this, without pulling any plugin in from my repo:

```<code>val springBootVersion: String by project

group = "com.meanwhileinhell.myapp"
version = "$version"

repositories {
    mavenCentral()
    mavenLocal()
    maven ("https://repo.spring.io/snapshot")
    maven ("https://repo.spring.io/milestone")
    maven ("https://plugins.gradle.org/m2/")

    maven {
        url = uri("s3://mvn.meanwhileinhell.com/releases")
        credentials(AwsCredentials::class) {
            accessKey = (project.property("s3_access_key") as String)
            secretKey = (project.property("s3_access_secret") as String)
        }
    }
}

plugins {
    base
    eclipse
    idea
    java
    id("io.spring.dependency-management") version "1.0.9.RELEASE"
    // Load but don't apply to root project
    id("org.springframework.boot") version "1.5.14.RELEASE" apply false
}

dependencies {
    ...
}
</code>```

Whenever I try to add a plugin id like id("com.meanwhileinhell.plugin.hell2java") version "1.0.0-SNAPSHOT" I get an error that looks like it isn't even looking in my S3 location:

```<code>* What went wrong:
Plugin [id: 'com.meanwhileinhell.plugin.hell2java', version: '1.0.0-SNAPSHOT'] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'com.meanwhileinhell.plugin.hell2java:com.meanwhileinhell.plugin.hell2java.gradle.plugin:1.0.0-SNAPSHOT')
  Searched in the following repositories:
    Gradle Central Plugin Repository
</code>```

Any help on this would be appreciated!

EDIT !!!! -----------------------

I've just found this in the Gradle docs:
https://docs.gradle.org/current/userguide/plugins.html#sec:plugin_management

The pluginManagement {} block may only appear in either the settings.gradle file....

Looks like I'm going down the wrong way entirely, so will look into the initialisation script route.

答:
I think you may have missed something about the file structure.

In the Groovy DSL, you have the following files:

build.gradle

settings.gradle

init.gradle

In the Kotlin DSL, you have the same files but with the .kts extension:

build.gradle.kts

settings.gradle.kts

init.gradle.kts

The Kotlin DSL doesn't differ to the Groovy DSL in where to put things. pluginManagement need to go in to the settings file, so for Kotlin that would be settings.gradle.kts. If you are in doubt, look at the documentation. For almost all code examples, you can switch between Groovy and Kotlin DSL to see how to do it (and which files they are supposed go to into).

Body:
I need to change a multi-project build to a single-project build, as there is and only ever will be one project in this repo.  Currently, in settings.gradle, I have a custom plugin repo that currently uses a pluginManagement block with resolutionStrategy and my list of repo's:

pluginManagement {
    resolutionStrategy {
        eachPlugin {
            if (requested.id.namespace == 'com.meanwhileinhell.plugin') {
                useModule('com.meanwhileinhell:gradle-plugin:1.0.0-SNAPSHOT')
            }
        }
    }

    repositories {
        mavenLocal()
        maven { url "https://repo.spring.io/milestone" }
        maven { url "https://plugins.gradle.org/m2/" }

        // Meanwhileinhell repo
        maven {
            url "s3://mvn.meanwhileinhell.com/releases"
            credentials(AwsCredentials) {
                accessKey s3_access_key
                secretKey s3_access_secret
            }
        }
    }

    plugins {
        ...
        ...
    }
}

However, deleting settings.gradle and moving this block into my build.gradle.kts (Kotlin DSL) seems to do nothing.  I've tried wrapping in a

configurations {
    all {
        resolutionStrategy {
            eachPlugin {
                ...
            }
        }
    }
}

and also

settings {
    pluginManagement {
        resolutionStrategy {
            eachPlugin {
                ...
            }
        }
    }
}

I found a SO answer that used settingsEvaluated in order to get the settings object, but again this was a no go.

Currently my build.gradle.kts looks like this, without pulling any plugin in from my repo:

val springBootVersion: String by project

group = "com.meanwhileinhell.myapp"
version = "$version"

repositories {
    mavenCentral()
    mavenLocal()
    maven ("https://repo.spring.io/snapshot")
    maven ("https://repo.spring.io/milestone")
    maven ("https://plugins.gradle.org/m2/")

    maven {
        url = uri("s3://mvn.meanwhileinhell.com/releases")
        credentials(AwsCredentials::class) {
            accessKey = (project.property("s3_access_key") as String)
            secretKey = (project.property("s3_access_secret") as String)
        }
    }
}

plugins {
    base
    eclipse
    idea
    java
    id("io.spring.dependency-management") version "1.0.9.RELEASE"
    // Load but don't apply to root project
    id("org.springframework.boot") version "1.5.14.RELEASE" apply false
}

dependencies {
    ...
}

Whenever I try to add a plugin id like id("com.meanwhileinhell.plugin.hell2java") version "1.0.0-SNAPSHOT" I get an error that looks like it isn't even looking in my S3 location:

* What went wrong:
Plugin [id: 'com.meanwhileinhell.plugin.hell2java', version: '1.0.0-SNAPSHOT'] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'com.meanwhileinhell.plugin.hell2java:com.meanwhileinhell.plugin.hell2java.gradle.plugin:1.0.0-SNAPSHOT')
  Searched in the following repositories:
    Gradle Central Plugin Repository

Any help on this would be appreciated!

EDIT !!!! -----------------------

I've just found this in the Gradle docs:
https://docs.gradle.org/current/userguide/plugins.html#sec:plugin_management

The pluginManagement {} block may only appear in either the settings.gradle file....

Looks like I'm going down the wrong way entirely, so will look into the initialisation script route.


问:
MVC C# Count Records Based on Condition
I am trying to count and display the number of logs conducted by various users from the Admin section.
Each user has a  UserID and through this, I would like to count and display data from a specific table.
I have made of a stored procedure and passed it to the Controller via a ViewBag but it keeps returning 1 as the total for all values.
 the procedure is Below

```<code>CREATE proc [Usp_GetCallCountByUserID]
@UserID int output
AS
BEGIN
SELECT COUNT (*) FROM Customer Where UserID= @UserID
GROUP BY UserID
set @UserID =@@ROWCOUNT
END
GO
</code>```

Controller:

```<code>     public ActionResult Index()
       {
        con.Open();
        SqlCommand comm = new SqlCommand("Usp_GetCallCountByUserID", con);
        comm.CommandType = CommandType.StoredProcedure;
        comm.Parameters.Add("@UserID", SqlDbType.Int).Direction =
            ParameterDirection.Output;
        SqlDataReader reader;
        reader = comm.ExecuteReader();
        reader.Close();
        ViewBag.CountLog = comm.Parameters["@UserID"].Value.ToString();
        con.Close();

        var callCustomers = db.Registrations;
        return View(callCustomers.ToList());
    }
</code>```

答:
First of all your stored procedure does exactly as expected, since @@ROWCOUNT returns the number of rows in the result.

You have to write your result in another variable like shown below.

For your Stored Procedure

```<code>

DECLARE @Result INT
SELECT  @Result = COUNT (*) FROM Customer Where UserID= @UserID
GROUP BY UserID

</code>```

And then Read this value ;)

And Changes for your Code

```<code>reader.Close();
ViewBag.CountLog = comm.Parameters["@Result"].Value.ToString();
con.Close();
</code>```

Title: MVC C# Count Records Based on Condition

Body:
I am trying to count and display the number of logs conducted by various users from the Admin section.
Each user has a  UserID and through this, I would like to count and display data from a specific table.
I have made of a stored procedure and passed it to the Controller via a ViewBag but it keeps returning 1 as the total for all values.
 the procedure is Below

CREATE proc [Usp_GetCallCountByUserID]
@UserID int output
AS
BEGIN
SELECT COUNT (*) FROM Customer Where UserID= @UserID
GROUP BY UserID
set @UserID =@@ROWCOUNT
END
GO

Controller:

     public ActionResult Index()
       {
        con.Open();
        SqlCommand comm = new SqlCommand("Usp_GetCallCountByUserID", con);
        comm.CommandType = CommandType.StoredProcedure;
        comm.Parameters.Add("@UserID", SqlDbType.Int).Direction =
            ParameterDirection.Output;
        SqlDataReader reader;
        reader = comm.ExecuteReader();
        reader.Close();
        ViewBag.CountLog = comm.Parameters["@UserID"].Value.ToString();
        con.Close();

        var callCustomers = db.Registrations;
        return View(callCustomers.ToList());
    }

Body:
First of all your stored procedure does exactly as expected, since @@ROWCOUNT returns the number of rows in the result.

You have to write your result in another variable like shown below.

For your Stored Procedure

DECLARE @Result INT
SELECT  @Result = COUNT (*) FROM Customer Where UserID= @UserID
GROUP BY UserID

And then Read this value ;)

And Changes for your Code

reader.Close();
ViewBag.CountLog = comm.Parameters["@Result"].Value.ToString();
con.Close();


问:
Need some guidance on executing Javascript with Jmeter
I've been learning Jmeter during the last couple of weeks so it's still a fresh subject for me. The last test I created consists of a login, some page navigation and a form submission in the end. The whole test works, but the content of the last form is not submitted to the database and I believe that happens because that's made through JavaScript, specifically this script:

```<code><script type="text/javascript">
//<![CDATA[
var theForm = document.forms['WebForm1'];
if (!theForm) {
    theForm = document.WebForm1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>
</code>```

From what I've learned I should use JSR223 Sampler or Post-processor to execute scripts, but I don't know how to do it. Should I replicate the JavaScript code so it produces the same result <s>or can I simply reuse the original JavaScript</s>?

Thanks in advance!

Edit: I guess I asked too early. I obviously can't reuse the JavaScript code. I guess it should be done with the methods from JMeterContext and JMeterVariables, which I just found out about. Am I going in the right direction?

答:
The idea of a tool like JMeter is to replicate user behaviour on a protocol level (in this case HTTP). JMeter will not build a DOM representation of your web site and therefore will not be able to execute the Javascript that you see executed in your browser. You should use an HTTP Request sampler, select POST HTTP method and put your form data into the parameters section. All that Javascript is pure client side behavior and therefore does not belong into your JMeter test.

Please provide some more detail, if you already tried that and it failed!

Body:
I've been learning Jmeter during the last couple of weeks so it's still a fresh subject for me. The last test I created consists of a login, some page navigation and a form submission in the end. The whole test works, but the content of the last form is not submitted to the database and I believe that happens because that's made through JavaScript, specifically this script:

From what I've learned I should use JSR223 Sampler or Post-processor to execute scripts, but I don't know how to do it. Should I replicate the JavaScript code so it produces the same result <s>or can I simply reuse the original JavaScript</s>?

Thanks in advance!

Edit: I guess I asked too early. I obviously can't reuse the JavaScript code. I guess it should be done with the methods from JMeterContext and JMeterVariables, which I just found out about. Am I going in the right direction?