问:
Is possible update value cross pages by using Provider in flutter?
I'm working with Provider

```<code>provider: ^4.1.2
</code>```

I had 2 pages : A, B.

Page A and B show same simple design, with below codes :

PageA.dart

```<code>class PageA extends StatelessWidget {

   var songTitle = '';

   @override
   Widget build(BuildContext c) {
     return Column(children: <Widget>[
         FloatingActionButton.extended(
            onPressed: () {
                 // LOGIC : TRANSFER TO PAGE B AFTER CLICKED BUTTON FROM PAGE A
                 Navigator.push(context, MaterialPageRoute(
                     builder: (context) => PageB()));
            },
            label: Text('Click'),
           ),
         ),
         Text('$songTitle');
         // STEP 2 : while page B already got `songTitle`
         // to show on UI, I want `songTitle` also update on this page A
         // in the same time
     ]);

  }
}
</code>```

PageB.dart

```<code>class PageB extends StatelessWidget {

   var songTitle = '';

   @override
   Widget build(BuildContext c) {
     return Text('$songTitle');
   }

   @override
   void initState() {
     super.initState();

     // LOGIC : CALL API TO GET `songTitle` TO UPDATE ON UI
     api.request().then((title) {
        setState(() {
           this.songTitle = title;
           // STEP 1 : this causes update to page B
           // show `songTitle` got from api success
        });
     });
   }

}
</code>```

These codes run with no bugs.

What I want is after Step 1 got songTitle data,

It will updated its data to page A (Step 2) and page B (Step 1) in
the same time by using Provider (ex. Provider.of(context) ...)

People who knows,

Please tell me,

Thank you,

UPDATED I got correct @Chichebe answer in below already.

答:
main.dart

```<code>import 'dart:async';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [ChangeNotifierProvider<Song>(create: (context) => Song())],
      child: MaterialApp(home: PageA()),
    );
  }
}
</code>```

Song Model

```<code>class Song extends ChangeNotifier {
  String songTitle = 'Title';

  void updateSongTitle(String newTitle) {
    songTitle = newTitle;

    notifyListeners();
  }
}
</code>```

pageA

```<code>class PageA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Consumer<Song>(builder: (context, song, child) {
          print('Consumer() : ${song.songTitle}');

          return Column(
            children: <Widget>[
              // SONG TITLE
              Text(song.songTitle),
              // Button
              MaterialButton(
                onPressed: () => Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => PageB()),
                ),
                child: Text('Button'),
              ),
            ],
            mainAxisAlignment: MainAxisAlignment.center,
          );
        }),
      ),
    );
  }
}
</code>```

pageB

```<code>class PageB extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return PageBState();
  }
}

class PageBState extends State<PageB> {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    Timer(Duration(seconds: 2), () {
      final song = Provider.of<Song>(context, listen: false);

      song.updateSongTitle('New Title');
    });
  }

  @override
  Widget build(BuildContext c) {
    return Container(
      child: Text('Page B'),
      color: Colors.white,
    );
  }
}
</code>```

p/s :I understand that

use the Provider package in managing your state and passing data down your widget tree.

use ChangeNotifier alongside ChangeNotifierProvider to achieve this.

Body:
I'm working with Provider

provider: ^4.1.2

I had 2 pages : A, B.

Page A and B show same simple design, with below codes :

PageA.dart

class PageA extends StatelessWidget {

   var songTitle = '';

   @override
   Widget build(BuildContext c) {
     return Column(children: <Widget>[
         FloatingActionButton.extended(
            onPressed: () {
                 // LOGIC : TRANSFER TO PAGE B AFTER CLICKED BUTTON FROM PAGE A
                 Navigator.push(context, MaterialPageRoute(
                     builder: (context) => PageB()));
            },
            label: Text('Click'),
           ),
         ),
         Text('$songTitle');
         // STEP 2 : while page B already got `songTitle`
         // to show on UI, I want `songTitle` also update on this page A
         // in the same time
     ]);

  }
}

PageB.dart

class PageB extends StatelessWidget {

   var songTitle = '';

   @override
   Widget build(BuildContext c) {
     return Text('$songTitle');
   }

   @override
   void initState() {
     super.initState();

     // LOGIC : CALL API TO GET `songTitle` TO UPDATE ON UI
     api.request().then((title) {
        setState(() {
           this.songTitle = title;
           // STEP 1 : this causes update to page B
           // show `songTitle` got from api success
        });
     });
   }

}

These codes run with no bugs.

What I want is after Step 1 got songTitle data,

It will updated its data to page A (Step 2) and page B (Step 1) in
the same time by using Provider (ex. Provider.of(context) ...)

People who knows,

Please tell me,

Thank you,

UPDATED I got correct @Chichebe answer in below already.

Body:
main.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [ChangeNotifierProvider<Song>(create: (context) => Song())],
      child: MaterialApp(home: PageA()),
    );
  }
}

Song Model

class Song extends ChangeNotifier {
  String songTitle = 'Title';

  void updateSongTitle(String newTitle) {
    songTitle = newTitle;

    notifyListeners();
  }
}

pageA

class PageA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Consumer<Song>(builder: (context, song, child) {
          print('Consumer() : ${song.songTitle}');

          return Column(
            children: <Widget>[
              // SONG TITLE
              Text(song.songTitle),
              // Button
              MaterialButton(
                onPressed: () => Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => PageB()),
                ),
                child: Text('Button'),
              ),
            ],
            mainAxisAlignment: MainAxisAlignment.center,
          );
        }),
      ),
    );
  }
}

pageB

class PageB extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return PageBState();
  }
}

class PageBState extends State<PageB> {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    Timer(Duration(seconds: 2), () {
      final song = Provider.of<Song>(context, listen: false);

      song.updateSongTitle('New Title');
    });
  }

  @override
  Widget build(BuildContext c) {
    return Container(
      child: Text('Page B'),
      color: Colors.white,
    );
  }
}

p/s :I understand that

use the Provider package in managing your state and passing data down your widget tree.

use ChangeNotifier alongside ChangeNotifierProvider to achieve this.


来源: stackexchange

问:
Efficient way to create pairs of all combinations of column names as a rows in a data.frame
I have this data.frame in R:

```<code>df = data.frame("blue" = c(0,1,1,0,1),
                "yellow" = c(0,0,1,0,1),
                "green" = c(1,1,1,0,0),
                "letter" = c("A","B","C","D","E"),
                "id" = c(23,57,48,3,12))
</code>```

```<code>  blue yellow green Letter ID
1    0      0     1      A 23
2    1      0     1      B 57
3    1      1     1      C 48
4    0      0     0      D  3
5    1      1     0      E 12
</code>```

and would like to turn it into a data frame with all possible combinations of colors (colnames to rows), maintaining the Letter and ID of each pair, like in here:

```<code>   Col_1    Col_2    C1  C2  Letter  ID
1  blue     yellow   0   0   A       23
2  blue     green    0   1   A       23
3  yellow   green    0   1   A       23
4  blue     yellow   1   0   B       57
5  blue     green    1   1   B       57
6  yellow   green    0   1   B       57
7  blue     yellow   1   1   C       48
8  blue     green    1   1   C       48
9  yellow   green    1   1   C       48
10 blue     yellow   0   1   D       3
11 blue     green    0   0   D       3
12 yellow   green    1   0   D       3
13 blue     yellow   1   1   E       12
14 blue     green    1   0   E       12
15 yellow   green    1   0   E       12
</code>```

Since my database is huge doing so with loops is taking too long. Any suggestions to do it more efficiently?

Thank you.

答:
Here's a data.table solution using melt that should work well unless the database is absolutely massive, in which case you can always split it by ID, but I'd guess this works fast for your case.

```<code>library(data.table)
df = data.frame("blue" = c(0,1,1,0,1),
                "yellow" = c(0,0,1,0,1),
                "green" = c(1,1,1,0,0),
                "letter" = c("A","B","C","D","E"),
                "id" = c(23,57,48,3,12))

#convert to data.table and melt
setDT(df)

df = melt(df, id.vars = c("letter","id"))

#combine blue/yellow, blue/green, and yellow/green
df1 = merge(df[variable == "blue"],df[variable == "yellow"], by = c("letter","id"))
df2 = merge(df[variable == "blue"],df[variable == "green"], by = c("letter","id"))
df3 = merge(df[variable == "yellow"],df[variable == "green"], by = c("letter","id"))

df = rbindlist(list(df1,df2,df3))

#now fix names..
setnames(df, c("variable.x","value.x","variable.y","value.y"), c("col_1","c1","col_2","c2"))

#optionally rearrange cols...
df = df[,.(col_1,col_2,c1,c2,letter,id)]
</code>```

OwnerDisplayName: Bruna Amaral

ContentLicense: CC BY-SA 4.0

Body:
I have this data.frame in R:

df = data.frame("blue" = c(0,1,1,0,1),
                "yellow" = c(0,0,1,0,1),
                "green" = c(1,1,1,0,0),
                "letter" = c("A","B","C","D","E"),
                "id" = c(23,57,48,3,12))

  blue yellow green Letter ID
1    0      0     1      A 23
2    1      0     1      B 57
3    1      1     1      C 48
4    0      0     0      D  3
5    1      1     0      E 12

and would like to turn it into a data frame with all possible combinations of colors (colnames to rows), maintaining the Letter and ID of each pair, like in here:

   Col_1    Col_2    C1  C2  Letter  ID
1  blue     yellow   0   0   A       23
2  blue     green    0   1   A       23
3  yellow   green    0   1   A       23
4  blue     yellow   1   0   B       57
5  blue     green    1   1   B       57
6  yellow   green    0   1   B       57
7  blue     yellow   1   1   C       48
8  blue     green    1   1   C       48
9  yellow   green    1   1   C       48
10 blue     yellow   0   1   D       3
11 blue     green    0   0   D       3
12 yellow   green    1   0   D       3
13 blue     yellow   1   1   E       12
14 blue     green    1   0   E       12
15 yellow   green    1   0   E       12

Since my database is huge doing so with loops is taking too long. Any suggestions to do it more efficiently?

Thank you.

Body:
Here's a data.table solution using melt that should work well unless the database is absolutely massive, in which case you can always split it by ID, but I'd guess this works fast for your case.

library(data.table)
df = data.frame("blue" = c(0,1,1,0,1),
                "yellow" = c(0,0,1,0,1),
                "green" = c(1,1,1,0,0),
                "letter" = c("A","B","C","D","E"),
                "id" = c(23,57,48,3,12))

#convert to data.table and melt
setDT(df)

df = melt(df, id.vars = c("letter","id"))

#combine blue/yellow, blue/green, and yellow/green
df1 = merge(df[variable == "blue"],df[variable == "yellow"], by = c("letter","id"))
df2 = merge(df[variable == "blue"],df[variable == "green"], by = c("letter","id"))
df3 = merge(df[variable == "yellow"],df[variable == "green"], by = c("letter","id"))

df = rbindlist(list(df1,df2,df3))

#now fix names..
setnames(df, c("variable.x","value.x","variable.y","value.y"), c("col_1","c1","col_2","c2"))

#optionally rearrange cols...
df = df[,.(col_1,col_2,c1,c2,letter,id)]


问:
Flutter how to pass two arguments in route, parameters that have different classes?
This is object that needs to pass as argument in navigation.

```<code>Test test = Test(name:'name');
SecondTest testSecond = SecondTest(id:'dfdad');

//This is not working
//Navigator.pushNamed(context, "some-screen",arguments:{test , testSecond });

class SomeScreen extends StatefulWidget {

  final Test test;
  SecondTest testSecond;

  SomeScreen(this.test, this.testSecond);
</code>```

}

This is argument for that screen. How to send multiple values?

答:
you can create Map and pass the Map like below:

```<code>Map args = {
  'test': test,
  'testSecond': testSecond,
};

Navigator.pushNamed(context, 'some-screen',arguments: args );
</code>```

after handle navigation like this

```<code>  return MaterialPageRoute(builder: (_) => SomeScreen(data: args));
</code>```

you can retrieve data in SomeScreen like this

```<code>class SomeScreen extends StatefulWidget {

  final Map data;

  SomeScreen({this.data});

  //....

}

class _SomeScreenState extends State<SomeScreen> {

  Test _test;
  SecondTest _testSecond;

  @override
  void initState() {
    super.initState();

    _test = widget.data['test'];
    _testSecond = widget.data['testSecond'];

    //...

  }
}

</code>```

Body:
This is object that needs to pass as argument in navigation.

Test test = Test(name:'name');
SecondTest testSecond = SecondTest(id:'dfdad');

//This is not working
//Navigator.pushNamed(context, "some-screen",arguments:{test , testSecond });

class SomeScreen extends StatefulWidget {

  final Test test;
  SecondTest testSecond;

  SomeScreen(this.test, this.testSecond);

}

This is argument for that screen. How to send multiple values?

Body:
you can create Map and pass the Map like below:

Map args = {
  'test': test,
  'testSecond': testSecond,
};

Navigator.pushNamed(context, 'some-screen',arguments: args );

after handle navigation like this

  return MaterialPageRoute(builder: (_) => SomeScreen(data: args));

you can retrieve data in SomeScreen like this

class SomeScreen extends StatefulWidget {

  final Map data;

  SomeScreen({this.data});

  //....

}

class _SomeScreenState extends State<SomeScreen> {

  Test _test;
  SecondTest _testSecond;

  @override
  void initState() {
    super.initState();

    _test = widget.data['test'];
    _testSecond = widget.data['testSecond'];

    //...

  }
}


问:
akka http complete or redirect based on a future
This snipped of akka http server code works:

```<code>path("test") {
  if (shouldRedirect())
    redirect(redirectUrl, StatusCodes.PermanentRedirect)
  else
    complete("hello")
}
</code>```

however, my shouldRedirect() returns a Future[Boolean]. I would need something like this, but returning a Future is not allowed here.

```<code>path("test") {
  futureShouldRedirect().map { shouldRedirect =>
    if (shouldRedirect)
      redirect(redirectUrl, StatusCodes.PermanentRedirect)
    else
      complete("hello")
    }
  }
}
</code>```

How to solve this?
ps: I am aware the the complete function accepts a Future inside, however this is not useful in this case I need to either return a complete or a redirect.

答:
Akka provides predefined directives using you can solve the same.

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/

Solution Using onComplete Future Directive:

```<code>import akka.http.scaladsl.server.directives._

path("test") {
  onComplete(shouldRedirect()) {
    case Success(true)  => redirect(redirectUrl, StatusCodes.PermanentRedirect)
    case Success(false) => complete("hello")
    case Failure(ex) =>
      complete((InternalServerError, s"An error occurred: ${ex.getMessage}"))
  }
}
</code>```

The above solution will handle both success and failure cases in case if your shouldRedirect fails.

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/future-directives/onComplete.html

Solution Using onSuccess Future Directive:

```<code>import akka.http.scaladsl.server.directives._

path("test") {
  onSuccess(shouldRedirect()) { isRedirect =>
    {
      if (isRedirect) redirect(redirectUrl, StatusCodes.PermanentRedirect)
      else complete("hello")
    }
  }
}
</code>```

The above solution will handle only success scenarios, in case of failure, it will be bubbled up to the exception handler in case if you have defined, else to default exception handler.

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/future-directives/onSuccess.html

Body:
This snipped of akka http server code works:

path("test") {
  if (shouldRedirect())
    redirect(redirectUrl, StatusCodes.PermanentRedirect)
  else
    complete("hello")
}

however, my shouldRedirect() returns a Future[Boolean]. I would need something like this, but returning a Future is not allowed here.

path("test") {
  futureShouldRedirect().map { shouldRedirect =>
    if (shouldRedirect)
      redirect(redirectUrl, StatusCodes.PermanentRedirect)
    else
      complete("hello")
    }
  }
}

How to solve this?
ps: I am aware the the complete function accepts a Future inside, however this is not useful in this case I need to either return a complete or a redirect.

Body:
Akka provides predefined directives using you can solve the same.

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/

Solution Using onComplete Future Directive:

import akka.http.scaladsl.server.directives._

path("test") {
  onComplete(shouldRedirect()) {
    case Success(true)  => redirect(redirectUrl, StatusCodes.PermanentRedirect)
    case Success(false) => complete("hello")
    case Failure(ex) =>
      complete((InternalServerError, s"An error occurred: ${ex.getMessage}"))
  }
}

The above solution will handle both success and failure cases in case if your shouldRedirect fails.

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/future-directives/onComplete.html

Solution Using onSuccess Future Directive:

import akka.http.scaladsl.server.directives._

path("test") {
  onSuccess(shouldRedirect()) { isRedirect =>
    {
      if (isRedirect) redirect(redirectUrl, StatusCodes.PermanentRedirect)
      else complete("hello")
    }
  }
}

The above solution will handle only success scenarios, in case of failure, it will be bubbled up to the exception handler in case if you have defined, else to default exception handler.

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/future-directives/onSuccess.html


问:
EntityFramework Core Group By with Sum
Haven't written any code in a while and I'm trying to shake the rust off by writing a small app for my kids to track the books they've read over the summer.  The DB is simple, only 3 tables. 1 for books (title, author, pages etc), 1 for reader names and 1 is the actual reading log (1 row for each book they read, foreign key relationship to book table and reader table).

Trying to use EntityFramework core to write a query that will return the total pages read by reader.  I can run this in SSMS and it works fine

```<code>select r.Name, sum(b.Pages) as PagesRead
from ReadingLog rl
inner join Readers r on rl.ReaderId = r.Id
inner join Books b on rl.BookId = b.Id
where rl.IsActive = 1
group by r.Name
</code>```

I tried writing it in EF as this:

```<code>var pagesByReader = _context.ReadingLog
                            .Where(m => m.IsActive)
                            .GroupBy(m => m.Reader.Name)
                            .Select(m => new GraphViewModel()
                                   {
                                      Reader = m.Key,
                                      PagesRead = m.Sum(b => b.Book.Pages)
                                   })
                            .ToList();
</code>```

but I get this error at runtime: ).Book.Pages' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

I think I'm just writing the EF query wrong but I can't figure out why.  Any help is appreciated

答:
As mentioned in the comment, the sql is tranlated to Linq, like the following code:</p>

```<code>var result = (from rl in _context.ReadingLog
            join r in _context.Readers on rl.ReaderId equals r.Id
            join b in _context.Books on rl.BookId equals b.Id
            where rl.IsActive
            group new {r,b} by r.Name int g
            select
            new GraphViewModel
            {
                Reader = g.Key,
                PagesRead = g.Sum(x => x.b.Pages)
            }).ToList();
</code>```

Title: EntityFramework Core Group By with Sum

Body:
Haven't written any code in a while and I'm trying to shake the rust off by writing a small app for my kids to track the books they've read over the summer.  The DB is simple, only 3 tables. 1 for books (title, author, pages etc), 1 for reader names and 1 is the actual reading log (1 row for each book they read, foreign key relationship to book table and reader table).

Trying to use EntityFramework core to write a query that will return the total pages read by reader.  I can run this in SSMS and it works fine

select r.Name, sum(b.Pages) as PagesRead
from ReadingLog rl
inner join Readers r on rl.ReaderId = r.Id
inner join Books b on rl.BookId = b.Id
where rl.IsActive = 1
group by r.Name

I tried writing it in EF as this:

var pagesByReader = _context.ReadingLog
                            .Where(m => m.IsActive)
                            .GroupBy(m => m.Reader.Name)
                            .Select(m => new GraphViewModel()
                                   {
                                      Reader = m.Key,
                                      PagesRead = m.Sum(b => b.Book.Pages)
                                   })
                            .ToList();

but I get this error at runtime: ).Book.Pages' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

I think I'm just writing the EF query wrong but I can't figure out why.  Any help is appreciated

Body:
As mentioned in the comment, the sql is tranlated to Linq, like the following code:

var result = (from rl in _context.ReadingLog
            join r in _context.Readers on rl.ReaderId equals r.Id
            join b in _context.Books on rl.BookId equals b.Id
            where rl.IsActive
            group new {r,b} by r.Name int g
            select
            new GraphViewModel
            {
                Reader = g.Key,
                PagesRead = g.Sum(x => x.b.Pages)
            }).ToList();


问:
Can I combine both AddSignIn() with AddProtectedWebApi() when using Microsoft.Indentity.Web for authentication?
I'm in the process of setting up a SPA client which calls to an Api service. Using the Microsoft Identity platform I have the Spa client set up in AzureAD to return the required Access Token.

On the Api side I've got basic app with a Home page then a seperate api controller.

I can protect the Api calls by using services.AddProtectedWebApi(Configuration) call and setting up the Cors Policy to allow requests from the location where the Spa is deployed.

What I would like to be able to do is have the user Sign In separately when using the Api service as this will have a few monitoring screens and Hangfire running to manage background tasks.

If I do this by adding 'services.AddSignIn(Configuration)' it must be overwriting the settings made in services.AddProtectedWebApi(Configuration) as the sign in works but the Api calls do not, and vice versa.

Is there a way to use both the AddSignIn(...) and AddProtectedWebApi(...); perhaps through separate Authtenication Policy's...?

答:
Yes, you can. Just add this (to default authentication to your MVC controllers):

services.AddAuthentication(o =>
{
    o.DefaultAuthenticateScheme = "OpenIdConnect";
});
```

<p>And this in your Api Controllers:</p>

<pre class="lang-cs prettyprint-override"><code>[Authorize(AuthenticationSchemes = "Bearer")]
</code>```

Or this (to default authentication to your API controllers):

services.AddAuthentication(o =>
{
    o.DefaultAuthenticateScheme = "Bearer";
});
```

<p>And this in your MVC Controllers:</p>

<pre class="lang-cs prettyprint-override"><code>[Authorize(AuthenticationSchemes = "OpenIdConnect")]
</code>```

Body:
Yes, you can. Just add this (to default authentication to your MVC controllers):

services.AddAuthentication(o =>
{
    o.DefaultAuthenticateScheme = "OpenIdConnect";
});

And this in your Api Controllers:

[Authorize(AuthenticationSchemes = "Bearer")]

Or this (to default authentication to your API controllers):

services.AddAuthentication(o =>
{
    o.DefaultAuthenticateScheme = "Bearer";
});

And this in your MVC Controllers:

[Authorize(AuthenticationSchemes = "OpenIdConnect")]


问:
Acumatica Manufacturing error on publishing
I suddenly encountered an error in my manufacturing edition and it came out of nowhere so this is the error that I have.

```<code>Cannot insert duplicate key row in object 'dbo.SYProviderField' with unique index 'SYProviderField_UK'. The duplicate key value is (3, f7761087-6293-4dbe-b4d9-81feaf4a6f12, Data, 31).
The statement has been terminated.
</code>```

this error just suddenly showed on the publishing of the customization project of the JAMS manufacturing edition I cant figure out if what i will do with it i tried using another Manufacturing customization but still no luck.

答:
This seems to pop up randomly. The key points to the import provider

```<code>ProviderID="f7761087-6293-4dbe-b4d9-81feaf4a6f12" Name="Import BOM 2018R2"
</code>```

Remove the import "Import BOM 2018R2" from the manufacturing customization and try to publish again

Body:
I suddenly encountered an error in my manufacturing edition and it came out of nowhere so this is the error that I have.

Cannot insert duplicate key row in object 'dbo.SYProviderField' with unique index 'SYProviderField_UK'. The duplicate key value is (3, f7761087-6293-4dbe-b4d9-81feaf4a6f12, Data, 31).
The statement has been terminated.

this error just suddenly showed on the publishing of the customization project of the JAMS manufacturing edition I cant figure out if what i will do with it i tried using another Manufacturing customization but still no luck.

Body:
This seems to pop up randomly. The key points to the import provider

ProviderID="f7761087-6293-4dbe-b4d9-81feaf4a6f12" Name="Import BOM 2018R2"

Remove the import "Import BOM 2018R2" from the manufacturing customization and try to publish again


问:
Bash Script Efficiency / Logic
I have a very specific script I wrote about two years ago.  It runs fantastically and has never failed ...  However the more websites we put into the system the script gets slower and slower (as expected) ... The cron that runs the script every 10 mins now takes about 3 minutes to complete.  I am looking to reduce that time.  So let me explain what the script does.

1) Here is the MAIN LOOP -- It checks the database for all websites for paying customers:

```<code>mysql --login-path=main-data -e "SELECT user_file FROM database" | while read user_file; do
</code>```

2) Inside the main loop I build the individual conf files :

```<code>p=$user_file
echo "<VirtualHost *:80>" > /etc/apache2/sites-available/$p.conf
.........
</code>```

3) Still inside the main loop, I check to see if they have extra domains and create their aliases :

```<code>mysql --login-path=main-data -e "SELECT domain
    FROM database
    WHERE user_file = '$user_file';" | while read domain; do
        echo "  ServerAlias $domain" >> /etc/apache2/sites-available/$p.conf
        echo "  ServerAlias www.$domain" >> /etc/apache2/sites-available/$p.conf
    done
</code>```

4) Still inside the main loop -- I check for SSL and create that part of the conf file.  NOTE that there's some openssl config tests here that may slow things down:

```<code>mysql --login-path=main-data --skip-column-names -e"SELECT ssl FROM database
    WHERE user_file = '$user_file'
    AND a.primary_domain = '1'
    AND b.https = '1'" | while read ssl; do

    if [ $ssl = 1 ]
    then
        ########################### START SSL TEST
        crt="/var/www/liveSites/websites/$user_file/ssl/$domain.crt"
        key="/var/www/liveSites/websites/$user_file/ssl/$domain.key"

       key_test=$(openssl x509 -in $crt -pubkey -noout -outform pem | sha256sum 2>&1)
       crt_test=$(openssl pkey -in $key -pubout -outform pem | sha256sum 2>&1)

       if [ "$key_test" = "$crt_test" ]
       then
           echo "\n - Matched -- Cert Good - \n";
       else
           echo "SSL match failed for $user_file -> $domain" > /etc/apache2/websitesCron/ssl_fail.txt
           cat /etc/apache2/websitesCron/ssl_fail.txt | mail -s "SSL INSTALLATION ERROR" it@mycompany.com
        fi
        ####################### END SSL TEST

       echo "<VirtualHost *:443>
             ServerName    $domain
             ServerAlias   www.$domain
             DocumentRoot /var/www/liveSites/websites/$user_file/public_html
             ........
    fi
done
</code>```

5) Finally, still inside main loop I check to see if the site is enabled, if not enable it

```<code>if test -f "/etc/apache2/sites-enabled/$p.conf"; then
    echo "Configuration exists \n"
else
    A2ENSITE=/usr/sbin/a2ensite
    ${A2ENSITE} $p.conf
fi
</code>```

After the main loop -- I check the Apache config, to make sure it will reload gracefully and I check that ssl didn't fail the openssl comparison check:

```<code>/usr/sbin/apachectl configtest > /etc/apache2/websitesCron/configtest 2>&1

if grep "failed" /etc/apache2/websitesCron/configtest
then
    # Do failed stuff stop script and turn cron off
elif grep "failed" /etc/apache2/websitesCron/ssl_fail.txt
then
    # Do failed SSL stuff stop script and turn cron off
else
    # gracefully reload Apache
    /etc/init.d/apache2 reload
fi
</code>```

It's a pretty simple script, but there's a few moving parts -- For 1,000+ websites, does it seem like 3 mins for it to run is reasonable?  Should I fork?  Is there logic changes that could "clean it up"?

答:
I would not bother changing the logic if its working for you.  But you can make these changes to run it in parallel:

Move the entire main loop into a Bash function that takes one argument user_file.

Change the main loop to invoke this function in the background.

Your outer loop would look something like this:

```<code>mysql --login-path=main-data -e "SELECT user_file FROM database" | while read user_file; do
    mainFunction "$user_file" &
done
</code>```

Note: If the 1000+ background processes swamp your machine, then consider applying some of these techniques to limit the number of concurrent jobs.

Title: Bash Script Efficiency / Logic

Body:
I have a very specific script I wrote about two years ago.  It runs fantastically and has never failed ...  However the more websites we put into the system the script gets slower and slower (as expected) ... The cron that runs the script every 10 mins now takes about 3 minutes to complete.  I am looking to reduce that time.  So let me explain what the script does.

1) Here is the MAIN LOOP -- It checks the database for all websites for paying customers:

mysql --login-path=main-data -e "SELECT user_file FROM database" | while read user_file; do

2) Inside the main loop I build the individual conf files :

p=$user_file
echo "<VirtualHost *:80>" > /etc/apache2/sites-available/$p.conf
.........

3) Still inside the main loop, I check to see if they have extra domains and create their aliases :

mysql --login-path=main-data -e "SELECT domain
    FROM database
    WHERE user_file = '$user_file';" | while read domain; do
        echo "  ServerAlias $domain" >> /etc/apache2/sites-available/$p.conf
        echo "  ServerAlias www.$domain" >> /etc/apache2/sites-available/$p.conf
    done

4) Still inside the main loop -- I check for SSL and create that part of the conf file.  NOTE that there's some openssl config tests here that may slow things down:

mysql --login-path=main-data --skip-column-names -e"SELECT ssl FROM database
    WHERE user_file = '$user_file'
    AND a.primary_domain = '1'
    AND b.https = '1'" | while read ssl; do

    if [ $ssl = 1 ]
    then
        ########################### START SSL TEST
        crt="/var/www/liveSites/websites/$user_file/ssl/$domain.crt"
        key="/var/www/liveSites/websites/$user_file/ssl/$domain.key"

       key_test=$(openssl x509 -in $crt -pubkey -noout -outform pem | sha256sum 2>&1)
       crt_test=$(openssl pkey -in $key -pubout -outform pem | sha256sum 2>&1)

       if [ "$key_test" = "$crt_test" ]
       then
           echo "\n - Matched -- Cert Good - \n";
       else
           echo "SSL match failed for $user_file -> $domain" > /etc/apache2/websitesCron/ssl_fail.txt
           cat /etc/apache2/websitesCron/ssl_fail.txt | mail -s "SSL INSTALLATION ERROR" it@mycompany.com
        fi
        ####################### END SSL TEST

       echo "<VirtualHost *:443>
             ServerName    $domain
             ServerAlias   www.$domain
             DocumentRoot /var/www/liveSites/websites/$user_file/public_html
             ........
    fi
done

5) Finally, still inside main loop I check to see if the site is enabled, if not enable it

if test -f "/etc/apache2/sites-enabled/$p.conf"; then
    echo "Configuration exists \n"
else
    A2ENSITE=/usr/sbin/a2ensite
    ${A2ENSITE} $p.conf
fi

After the main loop -- I check the Apache config, to make sure it will reload gracefully and I check that ssl didn't fail the openssl comparison check:

/usr/sbin/apachectl configtest > /etc/apache2/websitesCron/configtest 2>&1

if grep "failed" /etc/apache2/websitesCron/configtest
then
    # Do failed stuff stop script and turn cron off
elif grep "failed" /etc/apache2/websitesCron/ssl_fail.txt
then
    # Do failed SSL stuff stop script and turn cron off
else
    # gracefully reload Apache
    /etc/init.d/apache2 reload
fi

It's a pretty simple script, but there's a few moving parts -- For 1,000+ websites, does it seem like 3 mins for it to run is reasonable?  Should I fork?  Is there logic changes that could "clean it up"?

Body:
I would not bother changing the logic if its working for you.  But you can make these changes to run it in parallel:

Move the entire main loop into a Bash function that takes one argument user_file.

Change the main loop to invoke this function in the background.

Your outer loop would look something like this:

mysql --login-path=main-data -e "SELECT user_file FROM database" | while read user_file; do
    mainFunction "$user_file" &
done

Note: If the 1000+ background processes swamp your machine, then consider applying some of these techniques to limit the number of concurrent jobs.


问:
Changing values of object with integers as keys not working
I have an object that has numbers as the keys.

```<code>item:{
   1:'test 1'
   2:'test 2'
   3:'test 3'
}
</code>```

The object is generated automatically so the keys are not always the same. So in my method, I pass in the key as a string (ex:'1') and the changed value like so:

```<code>function changeValues(key,value){
   this.item[key] = value
}
</code>```

For some reason, this doesn't change my data but instead if I do this, it works perfectly fine.

```<code>function changeValues(key,value){
   this.item['1'] = value
}
</code>```

Is there a reason for this behavior and is there anyway to fix it so I can use dynamic property names?

答:
You cannot use an integer value as a key in an object. It will be converted to a string value. See this answer to a similar question.

As for accessing a value by a constant string key or by a key from a variable there si no difference.
Try this code:

```<code>var a = { 1: 'test1', 2: 'test2' }
var b = '1'
console.log(a['1']  === a[b])
</code>```

Body:
I have an object that has numbers as the keys.

item:{
   1:'test 1'
   2:'test 2'
   3:'test 3'
}

The object is generated automatically so the keys are not always the same. So in my method, I pass in the key as a string (ex:'1') and the changed value like so:

function changeValues(key,value){
   this.item[key] = value
}

For some reason, this doesn't change my data but instead if I do this, it works perfectly fine.

function changeValues(key,value){
   this.item['1'] = value
}

Is there a reason for this behavior and is there anyway to fix it so I can use dynamic property names?

Body:
You cannot use an integer value as a key in an object. It will be converted to a string value. See this answer to a similar question.

As for accessing a value by a constant string key or by a key from a variable there si no difference.
Try this code:

var a = { 1: 'test1', 2: 'test2' }
var b = '1'
console.log(a['1']  === a[b])


问:
Binary serialization protocol
I have a requirement where i need to transfer information through the wire(binary over tcp) between 2 applications. One is in Java and the other in C++. I need a protocol implementation to transfer objects between these 2 applications. The Object classes are present in both the applications (are mapped accordingly). I just need some encoding scheme on one side which retains the Object representation on one side and can be decoded on the other side as a complete Object.

For eg,

C++ class

```<code>class Person
{
   int age;
   string name;
};
</code>```

Java class

```<code>class Person
{
   int age;
   String name;
}
</code>```

C++ encoding

```<code>Person p;
p.age = 20;
p.name = "somename";
char[] arr = SomeProtocolEncoder.encode(p);
socket.send(arr);
</code>```

Java decoding

```<code>byte[] arr = socket.read();
SomeProtocolIntermediateObject object = SomeProtocolDecoder.decode(arr);
Person p = (Person)ReflectionUtil.get(object);
</code>```

The protocol should provide some intermediate object which maintains the object representational state so that using reflection i can get back the object later.

答:
What about plain old ASN.1?

It would have the advantage of being really backed by a standard (and widely used). The problem is finding a compiler/runtime for each language.

ContentLicense: CC BY-SA 3.0

Title: Binary serialization protocol

Body:
I have a requirement where i need to transfer information through the wire(binary over tcp) between 2 applications. One is in Java and the other in C++. I need a protocol implementation to transfer objects between these 2 applications. The Object classes are present in both the applications (are mapped accordingly). I just need some encoding scheme on one side which retains the Object representation on one side and can be decoded on the other side as a complete Object.

For eg,

C++ class

class Person
{
   int age;
   string name;
};

Java class

class Person
{
   int age;
   String name;
}

C++ encoding

Person p;
p.age = 20;
p.name = "somename";
char[] arr = SomeProtocolEncoder.encode(p);
socket.send(arr);

Java decoding

byte[] arr = socket.read();
SomeProtocolIntermediateObject object = SomeProtocolDecoder.decode(arr);
Person p = (Person)ReflectionUtil.get(object);

The protocol should provide some intermediate object which maintains the object representational state so that using reflection i can get back the object later.


问:
OSMNX Shortest path Nodes - Get node traveled time
I wanted to get the travel time between nodes in shortest path route using Osmnx. Is there a way to get the travel time between the nodes.

```<code>import networkx as nx
import osmnx as ox
ox.config(use_cache=True, log_console=True)
import pandas as pd

pla__version__Piedmont, CA, USA
G = ox.graph_from_place(place, network_type='drive')

orig = list(G)[0]
dest = list(G)[-1]
route = nx.shortest_path(G, orig, dest)
#fig, ax = ox.plot_graph_route(G, route, route_linewidth=6, node_size=0, bgcolor='k')

for i, val in enumerate(route):
    print(i, val, G.nodes[val]['x'], G.nodes[val]['y'])
</code>```

I want to store the nodes, the latitude and longitude which is implemented in the above loop, but is there a way to store also the travel time between the two nodes and/or distance between the two nodes.

答:
OSM's data on speeds and travel times tend to be spotty. Use OSMnx's speed module to impute missing edge speeds and calculate free-flow travel times.

import networkx as nx
import osmnx as ox
import pandas as pd
ox.config(use_cache=True, log_console=True)

place = 'Piedmont, CA, USA'
G = ox.graph_from_place(place, network_type='drive')

# impute missing edge speeds and add travel times
G = ox.add_edge_speeds(G)
G = ox.add_edge_travel_times(G)

# calculate route minimizing some weight
orig, dest = list(G)[0], list(G)[-1]
route = nx.shortest_path(G, orig, dest, weight='travel_time')

# OPTION 1: see the travel time for the whole route
travel_time = nx.shortest_path_length(G, orig, dest, weight='travel_time')
print(round(travel_time))

# OPTION 2: loop through the edges in your route
# and print the length and travel time of each edge
for u, v in zip(route[:-1], route[1:]):
    length = round(G.edges[(u, v, 0)]['length'])
    travel_time = round(G.edges[(u, v, 0)]['travel_time'])
    print(u, v, length, travel_time, sep='\t')

# OPTION 3: use get_route_edge_attributes
cols = ['osmid', 'length', 'travel_time']
attrs = ox.utils_graph.get_route_edge_attributes(G, route)
print(pd.DataFrame(attrs)[cols])
```

Body:
I wanted to get the travel time between nodes in shortest path route using Osmnx. Is there a way to get the travel time between the nodes.

import networkx as nx
import osmnx as ox
ox.config(use_cache=True, log_console=True)
import pandas as pd

pla__version__Piedmont, CA, USA
G = ox.graph_from_place(place, network_type='drive')

orig = list(G)[0]
dest = list(G)[-1]
route = nx.shortest_path(G, orig, dest)
#fig, ax = ox.plot_graph_route(G, route, route_linewidth=6, node_size=0, bgcolor='k')

for i, val in enumerate(route):
    print(i, val, G.nodes[val]['x'], G.nodes[val]['y'])

I want to store the nodes, the latitude and longitude which is implemented in the above loop, but is there a way to store also the travel time between the two nodes and/or distance between the two nodes.


问:
Sharing of footnote between different part of tables using flextable
I need to create table with same footnote being placed in both header and body of the table, I cannot figure out how to make it happen using flextable, what I can create is something as below:

```<code>library(flextable)
library(dplyr)
library(tidyr)

data(iris)
iris %>%
  as_tibble %>%
  gather(.,key = variable,value = value,-Species) %>%
  group_by(Species,variable) %>%
  summarise(value=formatC(mean(value),digits = 2,format = 'f')) %>%
  ungroup %>%
  spread(.,key = variable,value = value) %>%
  flextable %>%
  footnote(.,part = 'header',i = 1,j = c(2:5),
           value = as_paragraph(c('Rounded to two decimal places')),
           ref_symbols = c('*'),
           inline=FALSE) %>%
  footnote(.,part = 'body',i = c(1:3),j = 1,
           value = as_paragraph(c('Rounded to two decimal places')),
           ref_symbols = c('*'),
           inline=FALSE)
</code>```

Currently I created two footnotes with the same statement for header and body, I wonder if I can merge the two statements into one.

Thanks!

答:
(I did not imagine footnotes would be repeated when this function has been implemented but) by using merge_v, you can merge them if identical:

```<code>library(flextable)
library(dplyr)
library(tidyr)

data(iris)
iris %>%
  as_tibble %>%
  gather(.,key = variable,value = value,-Species) %>%
  group_by(Species,variable) %>%
  summarise(value=formatC(mean(value),digits = 2,format = 'f')) %>%
  ungroup %>%
  spread(.,key = variable,value = value) %>%
  flextable %>%
  footnote(.,part = 'header',i = 1,j = c(2:5),
           value = as_paragraph(c('Rounded to two decimal places')),
           ref_symbols = c('*'),
           inline=FALSE) %>%
  footnote(.,part = 'body',i = c(1:3),j = 1,
           value = as_paragraph(c('Rounded to two decimal places')),
           ref_symbols = c('*'),
           inline=FALSE) %>%
  merge_v(part = "footer")

</code>```

Body:
I need to create table with same footnote being placed in both header and body of the table, I cannot figure out how to make it happen using flextable, what I can create is something as below:

library(flextable)
library(dplyr)
library(tidyr)

data(iris)
iris %>%
  as_tibble %>%
  gather(.,key = variable,value = value,-Species) %>%
  group_by(Species,variable) %>%
  summarise(value=formatC(mean(value),digits = 2,format = 'f')) %>%
  ungroup %>%
  spread(.,key = variable,value = value) %>%
  flextable %>%
  footnote(.,part = 'header',i = 1,j = c(2:5),
           value = as_paragraph(c('Rounded to two decimal places')),
           ref_symbols = c('*'),
           inline=FALSE) %>%
  footnote(.,part = 'body',i = c(1:3),j = 1,
           value = as_paragraph(c('Rounded to two decimal places')),
           ref_symbols = c('*'),
           inline=FALSE)

Currently I created two footnotes with the same statement for header and body, I wonder if I can merge the two statements into one.

Thanks!

Body:
(I did not imagine footnotes would be repeated when this function has been implemented but) by using merge_v, you can merge them if identical:

library(flextable)
library(dplyr)
library(tidyr)

data(iris)
iris %>%
  as_tibble %>%
  gather(.,key = variable,value = value,-Species) %>%
  group_by(Species,variable) %>%
  summarise(value=formatC(mean(value),digits = 2,format = 'f')) %>%
  ungroup %>%
  spread(.,key = variable,value = value) %>%
  flextable %>%
  footnote(.,part = 'header',i = 1,j = c(2:5),
           value = as_paragraph(c('Rounded to two decimal places')),
           ref_symbols = c('*'),
           inline=FALSE) %>%
  footnote(.,part = 'body',i = c(1:3),j = 1,
           value = as_paragraph(c('Rounded to two decimal places')),
           ref_symbols = c('*'),
           inline=FALSE) %>%
  merge_v(part = "footer")


问:
How to cut part of string from a sentence in linux?
How can I get release version detail using cut or awk or grep?

```<code>|1NP|192.168.4.10|disprofiling-blue|dts|136190715|awsxxxxxxx:5100/bdltts/disprofiling:perf-latest-release-20-05-13-REL
|1NP|192.168.4.10|disprofiling-green|dts|136191553|awsxxxxxxx:5100/bdltts/disprofiling:perf-latest-release-20-04-29-REL
|1NP|192.168.4.10|profileing-blue|bdllts|144765480|awsxxxxxxx:5100/bdltts/profileing:perf-latest-release-20-05-12-REL
|1NP|192.168.4.10|profileing-green|bdllts|138530558|awsxxxxxxx:5100/bdltts/profileing:perf-latest-release-20-05-12-REL
|1NP|192.168.4.10|recorsrv-blue|bdllts|139683172|awsxxxxxxx:5100/bdltts/recorsrv:perf-latest-release-20-05-12-REL
</code>```

Example:

```<code>|1NP|192.168.4.10|recorsrv-blue|bdllts|139683172|awsxxxxxxx:5100/bdltts/recorsrv:perf-latest-release-20-05-12-REL
</code>```

Expected output:

```<code>-20-05-12-REL
</code>```

答:
Assuming that the output you are asking for comes from a file (let's say file.txt), and assuming that such file may look like this:

```<code>|1NP|192.168.4.10|disprofiling-blue|dts|136190715|awsxxxxxxx:5100/bdltts/disprofiling:perf-latest-release-20-05-13-REL
|1NP|192.168.4.10|disprofiling-green|dts|136191553|awsxxxxxxx:5100/bdltts/disprofiling:perf-latest-release-20-04-29-REL
|1NP|192.168.4.10|profileing-blue|bdllts|144765480|awsxxxxxxx:5100/bdltts/profileing:perf-latest-release-20-05-12-REL
|1NP|192.168.4.10|profileing-green|bdllts|138530558|awsxxxxxxx:5100/bdltts/profileing:perf-latest-release-20-05-12-REL
|1NP|192.168.4.10|recorsrv-blue|bdllts|139683172|awsxxxxxxx:5100/bdltts/recorsrv:perf-latest-release-20-05-12-REL
</code>```

And also assuming that the desired output you want to get is as follows:

```<code>20-05-12-REL
</code>```

You can try this:

```<code>cat file.txt |cut -d\: -f3 |cut -d\- -f4-7
</code>```

Body:
How can I get release version detail using cut or awk or grep?

|1NP|192.168.4.10|disprofiling-blue|dts|136190715|awsxxxxxxx:5100/bdltts/disprofiling:perf-latest-release-20-05-13-REL
|1NP|192.168.4.10|disprofiling-green|dts|136191553|awsxxxxxxx:5100/bdltts/disprofiling:perf-latest-release-20-04-29-REL
|1NP|192.168.4.10|profileing-blue|bdllts|144765480|awsxxxxxxx:5100/bdltts/profileing:perf-latest-release-20-05-12-REL
|1NP|192.168.4.10|profileing-green|bdllts|138530558|awsxxxxxxx:5100/bdltts/profileing:perf-latest-release-20-05-12-REL
|1NP|192.168.4.10|recorsrv-blue|bdllts|139683172|awsxxxxxxx:5100/bdltts/recorsrv:perf-latest-release-20-05-12-REL

Example:

|1NP|192.168.4.10|recorsrv-blue|bdllts|139683172|awsxxxxxxx:5100/bdltts/recorsrv:perf-latest-release-20-05-12-REL

Expected output:

-20-05-12-REL

Body:
Assuming that the output you are asking for comes from a file (let's say file.txt), and assuming that such file may look like this:

|1NP|192.168.4.10|disprofiling-blue|dts|136190715|awsxxxxxxx:5100/bdltts/disprofiling:perf-latest-release-20-05-13-REL
|1NP|192.168.4.10|disprofiling-green|dts|136191553|awsxxxxxxx:5100/bdltts/disprofiling:perf-latest-release-20-04-29-REL
|1NP|192.168.4.10|profileing-blue|bdllts|144765480|awsxxxxxxx:5100/bdltts/profileing:perf-latest-release-20-05-12-REL
|1NP|192.168.4.10|profileing-green|bdllts|138530558|awsxxxxxxx:5100/bdltts/profileing:perf-latest-release-20-05-12-REL
|1NP|192.168.4.10|recorsrv-blue|bdllts|139683172|awsxxxxxxx:5100/bdltts/recorsrv:perf-latest-release-20-05-12-REL

And also assuming that the desired output you want to get is as follows:

20-05-12-REL

You can try this:

cat file.txt |cut -d\: -f3 |cut -d\- -f4-7


问:
Remove pattern from string with gsub
I am struggling to remove the substring before the underscore in my string.
I want to use * (wildcard) as the bit before the underscore can vary:

```<code>a <- c("foo_5", "bar_7")

a <- gsub("*_", "", a, perl = TRUE)
</code>```

The result should look like:

```<code>> a
[1] 5 7
</code>```

I also tried stuff like "^*" or "?" but did not really work.

答:
Just to point out that there is an approach using functions from the tidyverse, which I find more readable than gsub:

```<code>a %>% stringr::str_remove(pattern = ".*_")
</code>```

Title: Remove pattern from string with gsub

Body:
I am struggling to remove the substring before the underscore in my string.
I want to use * (wildcard) as the bit before the underscore can vary:

a <- c("foo_5", "bar_7")

a <- gsub("*_", "", a, perl = TRUE)

The result should look like:

> a
[1] 5 7

I also tried stuff like "^*" or "?" but did not really work.

Body:
Just to point out that there is an approach using functions from the tidyverse, which I find more readable than gsub:

a %>% stringr::str_remove(pattern = ".*_")


问:
Build condition comparison for if statement
Is this possible?

```<code>$var_1 = 1;
$var_2 = 10;
$comparison = '>';

if($var_1 $comparison $var_2) {
    // do something...
}
</code>```

The syntax right now is not valid but is there a way to do this?

答:
I'm not sure if this is possible without the hackish use of an eval statement. You could of course wrap simply test what comparison is being used within another if statement.

```<code>if($comparison == '>' && $var_1 > $var_2)
    //Do something
elseif($comparison == '<' && $var_1 < $var_2)
    //Do something, and so on
</code>```

The eval method should work too if you build you code into an a string.

```<code>if(eval("$var_1 $comparison $var_2")) //Do something
</code>```

But the first method is probably far more preferable.

Body:
Is this possible?

$var_1 = 1;
$var_2 = 10;
$comparison = '>';

if($var_1 $comparison $var_2) {
    // do something...
}

The syntax right now is not valid but is there a way to do this?

Body:
I'm not sure if this is possible without the hackish use of an eval statement. You could of course wrap simply test what comparison is being used within another if statement.

if($comparison == '>' && $var_1 > $var_2)
    //Do something
elseif($comparison == '<' && $var_1 < $var_2)
    //Do something, and so on

The eval method should work too if you build you code into an a string.

if(eval("$var_1 $comparison $var_2")) //Do something

But the first method is probably far more preferable.


问:
Laravel - how to use Uppy for image uploading
I have this project with image uploading and I use Uppy for it. Here is my code:

```<code>...
<div id="drag-drop-area" name="fotografije[]"></div>
<script src="https://transloadit.edgly.net/releases/uppy/v1.6.0/uppy.min.js"></script>
    <script>
        var uppy = Uppy.Core()
        .use(Uppy.Dashboard, {
          inline: true,
          target: '#drag-drop-area'
        })
        .use(Uppy.Tus, {endpoint: 'https://master.tus.io/files/'}) //you can put upload URL here, where you want to upload images

      uppy.on('complete', (result) => {
        console.log('Upload complete! We’ve uploaded these files:', result.successful)
      })
    </script>
...
</code>```

I tried with name="fotografije[]" in div but of course it doesn't help. All I need is to name this input so that my images can be uploaded to server. How can I do this with Uppy?

答:
So you need to download multiple files using Uppy Dashbord and Laravel

Is your backend server at https://master.tus.io/files/ ? correct it if needed.

Then you have to get back request sent from frontend to a controller (in your backend Laravel) that handle this request as Ajax POST.

This may be looks like (after adding in routes.php as POST)

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UploadFileController extends Controller
{

public function showUploadFile(Request $request) {

    $file = $request->file('fotografije');

    //Display File Name just for check or do a dd
    echo 'File Name: '.$file[0]->getClientOriginalName();

    //Move Uploaded File
    $destinationPath = 'uploads';
    $file->move($destinationPath,$file->getClientOriginalName());
 }
}
</code>```

Also, don't forget to add crsf token to your uppy code to avoid bad request.

Hope this help

Body:
I have this project with image uploading and I use Uppy for it. Here is my code:

...

...

I tried with name="fotografije[]" in div but of course it doesn't help. All I need is to name this input so that my images can be uploaded to server. How can I do this with Uppy?

Body:
So you need to download multiple files using Uppy Dashbord and Laravel

Is your backend server at https://master.tus.io/files/ ? correct it if needed.

Then you have to get back request sent from frontend to a controller (in your backend Laravel) that handle this request as Ajax POST.

This may be looks like (after adding in routes.php as POST)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UploadFileController extends Controller
{

public function showUploadFile(Request $request) {

    $file = $request->file('fotografije');

    //Display File Name just for check or do a dd
    echo 'File Name: '.$file[0]->getClientOriginalName();

    //Move Uploaded File
    $destinationPath = 'uploads';
    $file->move($destinationPath,$file->getClientOriginalName());
 }
}

Also, don't forget to add crsf token to your uppy code to avoid bad request.

Hope this help


问:
Anaconda Error - module 'brotli' has no attribute 'error'
I updated anaconda using Anaconda Command Prompt.

After update whenever I run any command ex: conda info or conda list I get the below error

```<code>module 'brotli' has no attribute 'error'
</code>```

I would Really appreciate any help on this! Not sure how it solve it

答:
I solved this issue by commenting lines 376 & 377 in the file

```<code>C:\ProgramData\Anaconda3\Lib\site-packages\urllib3\response.py
</code>```

and then install brotli library by running either

```<code>pip install brotli
</code>```

or

```<code>conda install brotli
</code>```

After successful installation, uncomment above lines.
Do whatever you want now. Error should not come.

Body:
I updated anaconda using Anaconda Command Prompt.

After update whenever I run any command ex: conda info or conda list I get the below error

module 'brotli' has no attribute 'error'

I would Really appreciate any help on this! Not sure how it solve it

Body:
I solved this issue by commenting lines 376 & 377 in the file

C:\ProgramData\Anaconda3\Lib\site-packages\urllib3\response.py

and then install brotli library by running either

pip install brotli

or

conda install brotli

After successful installation, uncomment above lines.
Do whatever you want now. Error should not come.


问:
JavaScript: A countdown timer that uses only TIME
Apologies, I know this question has been asked severally but none of the questions/answers meet my exact need. I have tried writing, Googling and even Stackoverflow.
My use-case is to start a timer using JavaScript (as gotten from the database using PHP) for a test to be taken immediately the student clicks on "Start Test", when the time is up, submission is made and result is collated unless the student submits before time.
A teacher enters the duration for the test in the format (also saved to DB as) "2:30:45" for 2hrs 30mins 45secs. I need this to countdown until its "0:00:00" before automatic submission is made.
Thanks a lot.</p>

答:
I'm not sure what level of trust you are giving your students, but the best idea to keep track of time spent on something like this is server side, and probably best to starting session for the duration of the test.

I would use a javascript function that asynchronously updates the time remaining. Also I would write a javascript that async updates the students submissions so less likely answers are lost (plus you can get more interesting statistics that way like how long students spend on answer)


问:
Position the legend outside the plot area with Bokeh
I am making a plot following the example found here

Unfortunately, I have 17 curves I need to display, and the legend overlaps them. I know I can create a legend object that can be displayed outside the plot area like here, but I have 17 curves so using a loop is much more convenient.

Do you know how to combine both methods?

答:
I'd like to expand on joelostbloms answer.
It is also possible to pull out the legend from an existing plot and add it
somewhere else after the plot has been created.</p>

```<code>from bokeh.palettes import Category10
from bokeh.plotting import figure, show
from bokeh.sampledata.iris import flowers

# add a column with colors to the data
colors = dict(zip(flowers['species'].unique(), Category10[10]))
flowers["color"] = [colors[species] for species in flowers["species"]]

# make plot
p = figure(height=350, width=500)
p.circle("petal_length", "petal_width", source=flowers, legend_group='species',
         color="color")
p.add_layout(p.legend[0], 'right')

show(p)
</code>```

Body:
I'd like to expand on joelostbloms answer.
It is also possible to pull out the legend from an existing plot and add it
somewhere else after the plot has been created.

from bokeh.palettes import Category10
from bokeh.plotting import figure, show
from bokeh.sampledata.iris import flowers

# add a column with colors to the data
colors = dict(zip(flowers['species'].unique(), Category10[10]))
flowers["color"] = [colors[species] for species in flowers["species"]]

# make plot
p = figure(height=350, width=500)
p.circle("petal_length", "petal_width", source=flowers, legend_group='species',
         color="color")
p.add_layout(p.legend[0], 'right')

show(p)


问:
Draw out of canvas JavaScript
I have been developing a program which includes some sort of genetic algorithm. For my program, let's say there is a population of 200 units, and each unit can be in 5 different states. Inititlly, they all start at state 0, and they can randomly jump to states 1 to 4, and influence other units to jump as well. This way, the more units are on state 2, the more units will jump to state 2 and so on. I have these units moving randomly inside my canvas, bouncing off the walls when they hit them.
The one thing I want to do now is visualize the evolution on a chart, and for that I would like to have the canvas with the units jumping states on one side and the chart next to it, dynamically representing the percentage of units in state 0, 1, 2... simultaneously. I will presumably have no problem in coding the chart, however I cannot find a way of displaying it outside the canvas or without altering it.
Just in case, I am programming in Atom and have mostly used p5 libraries.
Any ideas??</p>

答:
You have 2 options:

Make a second canvas (Like enhzflep said), but this might be complicated for you, becuase you will not have access to P5.js drawing tools on that second canvas, look at this:

(On your first canvas)

```<code>fill(255,0,0)
rect(50,50,50,50);
</code>```

To make and draw to a second canvas:

```<code>const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
//deal with positioning, scaling, and other stuff (comment if you need help with that)
...

const c = canvas.getContext('2d');
c.fillStyle = "rgb(255,0,0)";
c.fillRect(50,50,50,50);
</code>```

(See, lots of effort)

Or, you can just use your first canvas, and partition a section off that is dedicated to the graph

```<code>createCanvas(600 + graphWidth, 600);

//Wherever your bouncing off walls code is
//for the right side of the screen

if(this.x > width - graphWidth){
  bounce();
}

//that leaves you a graphWidth by 600 rectangle for you to draw you graph
</code>```

The second option is much easier to read and will save you some headaches (I would use that).

Title: Draw out of canvas JavaScript

Body:
You have 2 options:

Make a second canvas (Like enhzflep said), but this might be complicated for you, becuase you will not have access to P5.js drawing tools on that second canvas, look at this:

(On your first canvas)

fill(255,0,0)
rect(50,50,50,50);

To make and draw to a second canvas:

const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
//deal with positioning, scaling, and other stuff (comment if you need help with that)
...

const c = canvas.getContext('2d');
c.fillStyle = "rgb(255,0,0)";
c.fillRect(50,50,50,50);

(See, lots of effort)

Or, you can just use your first canvas, and partition a section off that is dedicated to the graph

createCanvas(600 + graphWidth, 600);

//Wherever your bouncing off walls code is
//for the right side of the screen

if(this.x > width - graphWidth){
  bounce();
}

//that leaves you a graphWidth by 600 rectangle for you to draw you graph

The second option is much easier to read and will save you some headaches (I would use that).


问:
Add discord role to someone in direct message
I have a discord bot where you can activate your key with !activate.
At the event i want the bot to give the message.author the PREMIUM MEMBER role at my discord.
How can i make that work

I'm using @client.event and not ctx.

Thanks for your answers!

答:
You'll need the guild object that the bot is in, so then it knows where to get the role from. Additionally, the message.author object will return a User, not a Member,  but we'll need the Member object in order to add a role.

@client.event
async def on_message(message):
    if message.content.lower().startswith("!activate") and not message.guild:
        guild = client.get_guild(112233445566778899) # the guild's ID
        role = discord.utils.get(guild.roles, name="PREMIUM MEMBER") # or you can use id=
        member = await guild.fetch_member(message.author.id)
        await member.add_roles(role)
```

References:

Guild.fetch_member()

Client.get_guild()

utils.get()

Guild.roles

Member.add_roles()

Body:
You'll need the guild object that the bot is in, so then it knows where to get the role from. Additionally, the message.author object will return a User, not a Member,  but we'll need the Member object in order to add a role.

@client.event
async def on_message(message):
    if message.content.lower().startswith("!activate") and not message.guild:
        guild = client.get_guild(112233445566778899) # the guild's ID
        role = discord.utils.get(guild.roles, name="PREMIUM MEMBER") # or you can use id=
        member = await guild.fetch_member(message.author.id)
        await member.add_roles(role)

References:

Guild.fetch_member()

Client.get_guild()

utils.get()

Guild.roles

Member.add_roles()


问:
Getting accurate file size in megabytes?
How can I get the accurate file size in MB? I tried this:

```<code>compressed_file_size = File.size("Compressed/#{project}.tar.bz2") / 1024000

puts "file size is #{compressed_file_size} MB"
</code>```

But it chopped the 0.9 and showed 2 MB instead of 2.9 MB

答: You're doing integer division (which drops the fractional part).   Try dividing by 1024000.0 so ruby knows you want to do floating point math.</p>

Body:
How can I get the accurate file size in MB? I tried this:

compressed_file_size = File.size("Compressed/#{project}.tar.bz2") / 1024000

puts "file size is #{compressed_file_size} MB"

But it chopped the 0.9 and showed 2 MB instead of 2.9 MB


问:
To call a function from a class, does Python iterate through every function the class has until it finds the function to call?
For example, let's say I have this:

class RandomFunctions:
    def function_1:
        print('function 1 calling')

    def function_2:
        print('function_2 activated')

    def function_3:
        print('function_3 activated')

    def function_4:
        print('function_4 activated')

RandomFunctions().function_4()
```

To call function_4, does Python iterate through every other function in the class, checking if it's the right function, or directly calls it?

答:
I did a little experiment, here is the result:

```<code>from time import perf_counter

class RandomFunctions: # Defines 20000 functions
    for n in range(20000):
        exec(f"""def function_{n}(self):
            print(f'function {n} calling')""")

a = RandomFunctions()
start = perf_counter()
a.function_0() # Calls first function
end = perf_counter()
print(end-start)
</code>```

Output:

```<code>function 0 calling
0.03125423399999949
</code>```

#

```<code>start = perf_counter()
a.function_1999() # Calls the 1999th function
end = perf_counter()
print(end-start)
</code>```

Output:

```<code>function 1999 calling
0.0849990759999999
</code>```

The conclusion of this experiment appears to be that:
The class does iterate through the functions to find the right one.

Body:
For example, let's say I have this:

class RandomFunctions:
    def function_1:
        print('function 1 calling')

    def function_2:
        print('function_2 activated')

    def function_3:
        print('function_3 activated')

    def function_4:
        print('function_4 activated')

RandomFunctions().function_4()

To call function_4, does Python iterate through every other function in the class, checking if it's the right function, or directly calls it?

Body:
I did a little experiment, here is the result:

from time import perf_counter

class RandomFunctions: # Defines 20000 functions
    for n in range(20000):
        exec(f"""def function_{n}(self):
            print(f'function {n} calling')""")

a = RandomFunctions()
start = perf_counter()
a.function_0() # Calls first function
end = perf_counter()
print(end-start)

Output:

function 0 calling
0.03125423399999949

#

start = perf_counter()
a.function_1999() # Calls the 1999th function
end = perf_counter()
print(end-start)

Output:

function 1999 calling
0.0849990759999999

The conclusion of this experiment appears to be that:
The class does iterate through the functions to find the right one.


问:
I am doing a Lottery smart contract in solidity but sometimes when I execute the setWinner function I get an error. Can someone tell me why?
I am doing a Lottery smart contract in solidity but sometimes when I execute the setWinner function I get an error. Can someone tell me why? I starting to program so I know my code isn't the best, I accept some recommendations. For exemple, for pick a random number, I took the hash of the timestamp and then I divided in 8 parts, each one for one number of the lottery game. Is there a better way to do it, instead of dividing it by two each time to get a random number?</p>

```<code>function setWinner() public {

    bytes32 hash = keccak256(abi.encode(block.timestamp));

    bytes4[2] memory x0 = [bytes4(0), 0];
    assembly {
        mstore(x0, hash)
        mstore(add(x0, 4), hash)
    }
    bytes4[2] memory x1 = [bytes4(0), 0];
    assembly {
        mstore(x1, hash)
        mstore(add(x1, 8), hash)
    }
    bytes4[2] memory x2 = [bytes4(0), 0];
    assembly {
        mstore(x2, hash)
        mstore(add(x2, 12), hash)
    }
    bytes4[2] memory x3 = [bytes4(0), 0];
    assembly {
        mstore(x3, hash)
        mstore(add(x3, 16), hash)
    }
    bytes4[2] memory x4 = [bytes4(0), 0];
    assembly {
        mstore(x4, hash)
        mstore(add(x4, 20), hash)
    }
    bytes4[2] memory x5 = [bytes4(0), 0];
    assembly {
        mstore(x5, hash)
        mstore(add(x5, 24), hash)
    }
    bytes4[2] memory x6 = [bytes4(0), 0];
    assembly {
        mstore(x6, hash)
        mstore(add(x6, 28), hash)
    }
    bytes4[2] memory x7 = [bytes4(0), 0];
    assembly {
        mstore(x7, hash)
        mstore(add(x7, 32), hash)
    }

    uint n0 = uint32 (x0[1]);
    n0 = n0%numberMax;
    uint n1 = uint32 (x1[1]);
    n1 = n1%numberMax;
    uint n2 = uint32 (x2[1]);
    n2 = n2%numberMax;
    uint n3 = uint32 (x3[1]);
    n3 = n3%numberMax;
    uint n4 = uint32 (x4[1]);
    n4 = n4%numberMax;
    uint n5 = uint32 (x5[1]);
    n5 = n5%numberMax;
    uint n6 = uint32 (x6[1]);
    n6 = n6%numberMax;
    uint n7 = uint32 (x7[1]);
    n7 = n7%numberMax;

    //emit numbersCheck(n0,n1,n2,n3,n4,n5,n6,n7);

    uint[qntNumbers] memory tabNumbers = [n0,n1,n2,n3,n4,n5,n6,n7];

    quickSort(tabNumbers,0,tabNumbers.length -1);
    //emit tabCheck(tabNumbers);

    /*for (uint i=0;i<tabNumbers.length;i++){

        if (tabNumbers[i]==0){
                tabNumbers[i]= 60;
            }
        if ( (i <= tabNumbers.length)&& (tabNumbers[i]==tabNumbers[i+1])){

            tabNumbers[i+1]= tabNumbers[i+1] + 1;

        }
    }
    quickSort(tabNumbers,0,tabNumbers.length -1);*/
    //emit tabCheck(tabNumbers);
    removeDoubles(tabNumbers);

    winnerGame = tabNumbers;

}
</code>```

答:
block.timestamp is a bad source of entropy. You should avoid it to keep your contract safe from malicious participants.

When submitting blocks, miners determine the value of block.timestamp and so could trivially affect the outcome of your lottery.

You might refer to these similar SO questions:

How-to generate a random number

How can we generate multiple random number in ethereum?

Body:
I am doing a Lottery smart contract in solidity but sometimes when I execute the setWinner function I get an error. Can someone tell me why? I starting to program so I know my code isn't the best, I accept some recommendations. For exemple, for pick a random number, I took the hash of the timestamp and then I divided in 8 parts, each one for one number of the lottery game. Is there a better way to do it, instead of dividing it by two each time to get a random number?

function setWinner() public {

    bytes32 hash = keccak256(abi.encode(block.timestamp));

    bytes4[2] memory x0 = [bytes4(0), 0];
    assembly {
        mstore(x0, hash)
        mstore(add(x0, 4), hash)
    }
    bytes4[2] memory x1 = [bytes4(0), 0];
    assembly {
        mstore(x1, hash)
        mstore(add(x1, 8), hash)
    }
    bytes4[2] memory x2 = [bytes4(0), 0];
    assembly {
        mstore(x2, hash)
        mstore(add(x2, 12), hash)
    }
    bytes4[2] memory x3 = [bytes4(0), 0];
    assembly {
        mstore(x3, hash)
        mstore(add(x3, 16), hash)
    }
    bytes4[2] memory x4 = [bytes4(0), 0];
    assembly {
        mstore(x4, hash)
        mstore(add(x4, 20), hash)
    }
    bytes4[2] memory x5 = [bytes4(0), 0];
    assembly {
        mstore(x5, hash)
        mstore(add(x5, 24), hash)
    }
    bytes4[2] memory x6 = [bytes4(0), 0];
    assembly {
        mstore(x6, hash)
        mstore(add(x6, 28), hash)
    }
    bytes4[2] memory x7 = [bytes4(0), 0];
    assembly {
        mstore(x7, hash)
        mstore(add(x7, 32), hash)
    }

    uint n0 = uint32 (x0[1]);
    n0 = n0%numberMax;
    uint n1 = uint32 (x1[1]);
    n1 = n1%numberMax;
    uint n2 = uint32 (x2[1]);
    n2 = n2%numberMax;
    uint n3 = uint32 (x3[1]);
    n3 = n3%numberMax;
    uint n4 = uint32 (x4[1]);
    n4 = n4%numberMax;
    uint n5 = uint32 (x5[1]);
    n5 = n5%numberMax;
    uint n6 = uint32 (x6[1]);
    n6 = n6%numberMax;
    uint n7 = uint32 (x7[1]);
    n7 = n7%numberMax;

    //emit numbersCheck(n0,n1,n2,n3,n4,n5,n6,n7);

    uint[qntNumbers] memory tabNumbers = [n0,n1,n2,n3,n4,n5,n6,n7];

    quickSort(tabNumbers,0,tabNumbers.length -1);
    //emit tabCheck(tabNumbers);

    /*for (uint i=0;i<tabNumbers.length;i++){

        if (tabNumbers[i]==0){
                tabNumbers[i]= 60;
            }
        if ( (i <= tabNumbers.length)&& (tabNumbers[i]==tabNumbers[i+1])){

            tabNumbers[i+1]= tabNumbers[i+1] + 1;

        }
    }
    quickSort(tabNumbers,0,tabNumbers.length -1);*/
    //emit tabCheck(tabNumbers);
    removeDoubles(tabNumbers);

    winnerGame = tabNumbers;

}


问:
Tomcat Basic Authentication Permissions Issue
I currently have a web service running some basic authentication through Tomcat. I get the login box to pop up fine, and I can log in with accounts I have defined in the tomcat-users.xml file.  However, when it comes to defining permissions based on roles, I'm having some issues.

Currently, I have three roles: manager, admin, and user.  I have a few methods which should be only accessible by, say, an admin role.  I can log in as my manager/admin/user super account and see everything just fine- but I can do the same as a normal user as well.

The methods are defined like so:

```<code>@Path("/Test")
@RolesAllowed("admin")
public class Test
{
    @GET
    @RolesAllowed("user")
    public methodThatMyUsersCanAcess{}

    @GET
    @Path("/Secure")
    @RolesAllowed("admin")
    public methodThatOnlyAdminsCanAcess{}
}
</code>```

I'm really not sure how a 'user' role would be able to access the second method, but somehow it still happens.

答: After some more investigation, I discovered that using @RolesAllowed was doing nothing in my code due to the way my web.xml file was configured.  I decided to move in the direction of setting authentication by URI path.  This is done through modifying the web.xml to allow a subset of users to access each path under separate <security-constraint> tags.  I found my best resource for this here: http://www.coderanch.com/t/176095/java-Web-Component-SCWCD/certification/auth-constraint-confusion in the second post.

Body:
I currently have a web service running some basic authentication through Tomcat. I get the login box to pop up fine, and I can log in with accounts I have defined in the tomcat-users.xml file.  However, when it comes to defining permissions based on roles, I'm having some issues.

Currently, I have three roles: manager, admin, and user.  I have a few methods which should be only accessible by, say, an admin role.  I can log in as my manager/admin/user super account and see everything just fine- but I can do the same as a normal user as well.

The methods are defined like so:

@Path("/Test")
@RolesAllowed("admin")
public class Test
{
    @GET
    @RolesAllowed("user")
    public methodThatMyUsersCanAcess{}

    @GET
    @Path("/Secure")
    @RolesAllowed("admin")
    public methodThatOnlyAdminsCanAcess{}
}

I'm really not sure how a 'user' role would be able to access the second method, but somehow it still happens.


问:
Execute home assistant test cases using tox not working
I have installed python3.7 on my ubuntu18.04 and trying to run home assistant test cases , The installation of python and all dependencies was successfully,

So upon installing python3.7, It internally install various packages for development and test python code. one of the package is typing which is internally installed. (typing is added as default since python 3.5)

On executing these test cases I am facing an error.

```<code>File "/home/phil/repos/core/.tox/py38/lib/python3.8/site-packages/typing.py", line 1357, in <module>
      class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
    File "/home/phil/repos/core/.tox/py38/lib/python3.8/site-packages/typing.py", line 1005, in __new__
      self._abc_registry = extra._abc_registry
  AttributeError: type object 'Callable' has no attribute '_abc_registry'
  ----------------------------------------
ERROR: Command errored out with exit status 1: /home/phil/repos/core/.tox/py38/bin/python /home/phil/repos/core/.tox/py38/lib/python3.8/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-pqbbs22j/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.8.0' wheel Check the logs for full command output.
</code>```

One solution provided on SO question 55833509 is pip uninstall typing, which is also not working.

Is there a way I can uninstall this default typing package as well?

Can we prevent install this typing package?

Any Other solution to fix this issue?

答:
tox is run in a virtual environment. Thus, removing typing will not help.

I assume that you script/setup after you cloned the repos and you have the system's dependencies installed.

tox -r would rebuild the environment then.

Body:
I have installed python3.7 on my ubuntu18.04 and trying to run home assistant test cases , The installation of python and all dependencies was successfully,

So upon installing python3.7, It internally install various packages for development and test python code. one of the package is typing which is internally installed. (typing is added as default since python 3.5)

On executing these test cases I am facing an error.

File "/home/phil/repos/core/.tox/py38/lib/python3.8/site-packages/typing.py", line 1357, in <module>
      class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
    File "/home/phil/repos/core/.tox/py38/lib/python3.8/site-packages/typing.py", line 1005, in __new__
      self._abc_registry = extra._abc_registry
  AttributeError: type object 'Callable' has no attribute '_abc_registry'
  ----------------------------------------
ERROR: Command errored out with exit status 1: /home/phil/repos/core/.tox/py38/bin/python /home/phil/repos/core/.tox/py38/lib/python3.8/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-pqbbs22j/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.8.0' wheel Check the logs for full command output.

One solution provided on SO question 55833509 is pip uninstall typing, which is also not working.

Is there a way I can uninstall this default typing package as well?

Can we prevent install this typing package?

Any Other solution to fix this issue?


问:
How to get this pattern in iOS?
I am wondering where I can get this pattern in Xcode?

Thanks!

答:
You can have it with:</p>

```<code>[UIColor scrollViewTexturedBackgroundColor]
</code>```

Title: How to get this pattern in iOS?

Body:
You can have it with:

[UIColor scrollViewTexturedBackgroundColor]


问:
How to display django tags in update form (django-taggit)?
I made a basic blog post app in django and I'm using the django-taggit project (https://github.com/jazzband/django-taggit) to create taggable Model objects. However, tags show up as a query set in my update form field:

<QuerySet[<Tag:wow]>

Here is what my html looks like:

<input type="text" name="tags" data-role="tagsinput" class="form-control" id="tags" name="tags" value="{{ post.tags.all }}">

I know there's a way to loop through the tags when displaying them, but is there a way to loop through them within the form? I'm using a single text field to add tags separated by a comma using this tutorial:

https://dev.to/coderasha/how-to-add-tags-to-your-models-in-django-django-packages-series-1-3704

I don't have an issue saving tags. My only issue is displaying tags that already exist in an editable field on my update form.

thanks!

forms.py:

```<code>from taggit.forms import TagWidget

    class PostForm(ModelForm):
        class Meta:
            model = Post
            widgets = {'content_text': forms.Textarea(attrs={'cols': 80, 'rows': 80}),
                        'tags': TagWidget(),
                    }
            fields = ['title', 'video_URL', 'content_text', 'score', 'tags',]
</code>```

答:
post.tags.all is a queryset so it does not get evaluated since django queries are lazy and you just get the queryset since this returns a set of data (array if you want) not an value. Try this:

<input type="text" name="tags" data-role="tagsinput" class="form-control" id="tags" name="tags" value="{% for tag in post.tags.all %}{{ tag }},{% endfor %}">
# I used a comma to separate them but feel free to use whatever you want
```

Body:
I made a basic blog post app in django and I'm using the django-taggit project (https://github.com/jazzband/django-taggit) to create taggable Model objects. However, tags show up as a query set in my update form field:

<QuerySet[<Tag:wow]>

Here is what my html looks like:

<input type="text" name="tags" data-role="tagsinput" class="form-control" id="tags" name="tags" value="{{ post.tags.all }}">

I know there's a way to loop through the tags when displaying them, but is there a way to loop through them within the form? I'm using a single text field to add tags separated by a comma using this tutorial:

https://dev.to/coderasha/how-to-add-tags-to-your-models-in-django-django-packages-series-1-3704

I don't have an issue saving tags. My only issue is displaying tags that already exist in an editable field on my update form.

thanks!

forms.py:

from taggit.forms import TagWidget

    class PostForm(ModelForm):
        class Meta:
            model = Post
            widgets = {'content_text': forms.Textarea(attrs={'cols': 80, 'rows': 80}),
                        'tags': TagWidget(),
                    }
            fields = ['title', 'video_URL', 'content_text', 'score', 'tags',]


答:
Try this

def check_activation_key(activation_key):
    # do your check here, return True or False

@client.event
async def on_message(message):

    if message.content.startswith('!activate ') and message.channel == message.author.dm_channel: # !activate, dms only
        activation_key = message.content[10:]
        if check_activation_key(activation_key):
            guild = client.get_guild(ID_OF_SERVER_TO_ASSIGN_ROLE_IN) # right click and "copy id"
            role = guild.get_role(ID_OF_ROLE_TO_ASSIGN) # right click and "copy id"
            await guild.get_member(message.author.id).add_roles(role)
    if message.content.startswith('!unactivate') and message.channel == message.author.dm_channel:
        guild = client.get_guild(ID_OF_SERVER_TO_TAKE_ROLE_IN)
        if ('PREMIUM MEMBER' in [role.name for role in guild.get_member(message.author.id).roles]):
            await guild.get_member(message.author.id).remove_roles(guild.get_role(ID_OF_ROLE_GOES_HERE))
        else:
            await message.channel.send('You did not verify yet')
```

A drawback is that this does not support multiple servers, only 1, but you can make different activator commands with different server IDs.

Get the ID of a guild by right clicking the icon/banner and choosing "copy id". Get the ID of a role by right clicking a role (either in server settings or in someones profile) and choosing "copy id".

Title: Add discord role to someone in direct message

Body:
I have a discord bot where you can activate your key with !activate.
At the event i want the bot to give the message.author the PREMIUM MEMBER role at my discord.
How can i make that work

I'm using @client.event and not ctx.

Thanks for your answers!

Body:
Try this

def check_activation_key(activation_key):
    # do your check here, return True or False

@client.event
async def on_message(message):

    if message.content.startswith('!activate ') and message.channel == message.author.dm_channel: # !activate, dms only
        activation_key = message.content[10:]
        if check_activation_key(activation_key):
            guild = client.get_guild(ID_OF_SERVER_TO_ASSIGN_ROLE_IN) # right click and "copy id"
            role = guild.get_role(ID_OF_ROLE_TO_ASSIGN) # right click and "copy id"
            await guild.get_member(message.author.id).add_roles(role)
    if message.content.startswith('!unactivate') and message.channel == message.author.dm_channel:
        guild = client.get_guild(ID_OF_SERVER_TO_TAKE_ROLE_IN)
        if ('PREMIUM MEMBER' in [role.name for role in guild.get_member(message.author.id).roles]):
            await guild.get_member(message.author.id).remove_roles(guild.get_role(ID_OF_ROLE_GOES_HERE))
        else:
            await message.channel.send('You did not verify yet')

A drawback is that this does not support multiple servers, only 1, but you can make different activator commands with different server IDs.

Get the ID of a guild by right clicking the icon/banner and choosing "copy id". Get the ID of a role by right clicking a role (either in server settings or in someones profile) and choosing "copy id".


问:
Cannot use Color.FromArgb in DataGridView cell BackColor
I am looping through a DataGridView control and adding rows dynamically. I am setting the BackColor property of each cell based on the following logic:

```<code>if (bidVolume != null)
{
    this.Rows[this.RowCount - 1].Cells[1].Style.BackColor = Color.Green;
}
else
{
    this.Rows[this.RowCount - 1].Cells[1].Style.BackColor = Color.FromArgb(150, Color.Green);
}
</code>```

This is causing problems, the color is not properly set visually and when re-sizing the DataGridView it looks like this:

When I don't use Color.FromArgb and just use Color.Red for example, then everything works fine ..

Is it possible to set a cell BackColor using Color.FromArgb ?

Thanks

答:
Old question, but I ran into the same issue. The simplest solution is just to use the Color.FromArgb() override that excludes the alpha parameter from the constructor. As long as you don't specify an alpha transparency, the color works perfectly.

```<code>public static Color SeaFoamGreen = Color.FromArgb(20, 125, 115);
</code>```

Body:
I am looping through a DataGridView control and adding rows dynamically. I am setting the BackColor property of each cell based on the following logic:

if (bidVolume != null)
{
    this.Rows[this.RowCount - 1].Cells[1].Style.BackColor = Color.Green;
}
else
{
    this.Rows[this.RowCount - 1].Cells[1].Style.BackColor = Color.FromArgb(150, Color.Green);
}

This is causing problems, the color is not properly set visually and when re-sizing the DataGridView it looks like this:

When I don't use Color.FromArgb and just use Color.Red for example, then everything works fine ..

Is it possible to set a cell BackColor using Color.FromArgb ?

Thanks

Body:
Old question, but I ran into the same issue. The simplest solution is just to use the Color.FromArgb() override that excludes the alpha parameter from the constructor. As long as you don't specify an alpha transparency, the color works perfectly.

public static Color SeaFoamGreen = Color.FromArgb(20, 125, 115);


问:
Xamarin-System.UnauthorizedAccessException: Access to the path is denied
I'm trying to download a file and I'm getting System.UnauthorizedAccessException: Access to the path "/storage/emulated/0/Download/test.pdf" is denied. I have set required permission in Android Manifest file.

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Download Path:

```<code>Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)
</code>```

If i use the below path as my download path i can able to download the file. But i cant able to share the PDF file to google drive, drop box or any other System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)

I am using Xamarin.Forms v2.4.0.282 and Xamarin.Android.Support packages v25.4.0.2.

Note: The code was woking fine when use Xamarin.Forms version 2.3.5.256-pre2 and Xamarin.Android.Support packages v23.3.0
Please suggest your ideas to resolve the issue.

Thanks in Advance.

答:
If targeting API 29+, you will get the error even if you request the permission and user grants it, because they changed how storage works.

The correct solution is to look how it should be done on API 29+ and do it.

But if you are like me, tired of Android making things more complicated every day, just add android:requestLegacyExternalStorage="true" to your manifest <application> tag and you are saved until you start targeting API 30.

Body:
I'm trying to download a file and I'm getting System.UnauthorizedAccessException: Access to the path "/storage/emulated/0/Download/test.pdf" is denied. I have set required permission in Android Manifest file.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Download Path:

Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)

If i use the below path as my download path i can able to download the file. But i cant able to share the PDF file to google drive, drop box or any other System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)

I am using Xamarin.Forms v2.4.0.282 and Xamarin.Android.Support packages v25.4.0.2.

Note: The code was woking fine when use Xamarin.Forms version 2.3.5.256-pre2 and Xamarin.Android.Support packages v23.3.0
Please suggest your ideas to resolve the issue.

Thanks in Advance.


问:
Qt: PRO to CMake conversion -- AutoMoc subprocess error
I'm new to Qt and I'm trying to convert a .pro file into a
CMakeLists.text to use the project with CMake.

OS: Windows 10

.pro files:

```<code>QT += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

DEFINES += QT_DEPRECATED_WARNINGS

SOURCES += \
    main.cpp \
    mainwindow.cpp \
    parallelogrambutton.cpp \
    rombusbutton.cpp \
    scrollarea.cpp \
    skewedbutton.cpp \
    trapezbutton.cpp

HEADERS += \
    mainwindow.h \
    parallelogrambutton.h \
    rombusbutton.h \
    scrollarea.h \
    skewedbutton.h \
    trapezbutton.h

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

RESOURCES += \
    Resources.qrc
</code>```

The result of manual conversion to CMakeText.txt

```<code>cmake_minimum_required(VERSION 3.15)

project(Project)

set(CMAKE_PREFIX_PATH "C:/Qt/5.14.1/mingw73_64")
set(CMAKE_INCLUDE_PATH "C:/Qt/5.14.1/mingw73_64/bin")

set(CMAKE_CXX_STANDARD 11)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

find_package(Qt5 COMPONENTS Core Gui REQUIRED)

qt5_add_resources(Resources.qrc)

set(SOURCES
        main.cpp
        mainwindow.cpp
        parallelogrambutton.cpp
        rombusbutton.cpp
        scrollarea.cpp
        skewedbutton.cpp
        trapezbutton.cpp
        )

set(HEADERS
        mainwindow.h
        parallelogrambutton.h
        rombusbutton.h
        scrollarea.h
        skewedbutton.h
        trapezbutton.h
        )

add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS})

qt5_use_modules(${PROJECT_NAME} Core Gui)
</code>```

But when I'm trying to run this CMake file I'm getting the following error:

The error message:

```<code>/<CMAKE_PATH>\cmake.exe --build /<PATH>/cmake-build-debug --target Project -- -j 4
[ 10%] Automatic MOC and UIC for target Project

AutoMoc subprocess error
------------------------
The moc process failed to compile
  "/<PATH>/mainwindow.h"
into
  "/<PATH>/cmake-build-debug/Project_autogen/EWIEGA46WW/moc_mainwindow.cpp".

Command
-------
/<CMAKE_PREFIX_PATH>/bin/moc.exe -I/<PATH>/cmake-build-debug -I/<PATH> -I/<CMAKE_PREFIX_PATH>/include -I/<CMAKE_PREFIX_PATH>/include/QtCore -I/<CMAKE_PREFIX_PATH>/./mkspecs/win32-g++ -I/<CMAKE_PREFIX_PATH>/include/QtGui -I/<CMAKE_PREFIX_PATH>/include/QtANGLE -I/usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include/c++ -I/usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include/c++/x86_64-pc-cygwin -I/usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include/c++/backward -I/usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include -I/usr/include -I/usr/include/w32api -DQT_CORE_LIB -DQT_GUI_LIB --include /<PATH>/cmake-build-debug/Project_autogen/moc_predefs.h -o /<PATH>/cmake-build-debug/Project_autogen/EWIEGA46WW/moc_mainwindow.cpp /<PATH>/mainwindow.h

Output
------

make[3]: *** [CMakeFiles/Project_autogen.dir/build.make:58: CMakeFiles/Project_autogen] Error 1
make[2]: *** [CMakeFiles/Makefile2:104: CMakeFiles/Project_autogen.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:84: CMakeFiles/Project.dir/rule] Error 2
make: *** [Makefile:118: Project] Error 2
</code>```

Can any of you explain to me what I'm doing wrong here?

答:
It looks like you are using obsolete CMake commands of Qt, see https://doc.qt.io/qt-5/cmake-command-reference.html.

You can create a new CMake-based project in Qt Creator and take it as a base. Qt Creator v4.12.x will generate something like:

```<code>cmake_minimum_required(VERSION 3.15)

project(Project)

set(CMAKE_PREFIX_PATH "C:/Qt/5.14.1/mingw73_64")
set(CMAKE_INCLUDE_PATH "C:/Qt/5.14.1/mingw73_64/bin")

set(CMAKE_CXX_STANDARD 11)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

find_package(Qt5 COMPONENTS Core Gui REQUIRED)

set(SOURCES
    main.cpp
    Resources.qrc
    mainwindow.cpp
    parallelogrambutton.cpp
    rombusbutton.cpp
    scrollarea.cpp
    skewedbutton.cpp
    trapezbutton.cpp
)

set(HEADERS
    mainwindow.h
    parallelogrambutton.h
    rombusbutton.h
    scrollarea.h
    skewedbutton.h
    trapezbutton.h
)

add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS})

target_link_libraries(${PROJECT_NAME} PRIVATE Qt5::Core Qt5::Gui)
</code>```

Body:
I'm new to Qt and I'm trying to convert a .pro file into a
CMakeLists.text to use the project with CMake.

OS: Windows 10

.pro files:

QT += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

DEFINES += QT_DEPRECATED_WARNINGS

SOURCES += \
    main.cpp \
    mainwindow.cpp \
    parallelogrambutton.cpp \
    rombusbutton.cpp \
    scrollarea.cpp \
    skewedbutton.cpp \
    trapezbutton.cpp

HEADERS += \
    mainwindow.h \
    parallelogrambutton.h \
    rombusbutton.h \
    scrollarea.h \
    skewedbutton.h \
    trapezbutton.h

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

RESOURCES += \
    Resources.qrc

The result of manual conversion to CMakeText.txt

cmake_minimum_required(VERSION 3.15)

project(Project)

set(CMAKE_PREFIX_PATH "C:/Qt/5.14.1/mingw73_64")
set(CMAKE_INCLUDE_PATH "C:/Qt/5.14.1/mingw73_64/bin")

set(CMAKE_CXX_STANDARD 11)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

find_package(Qt5 COMPONENTS Core Gui REQUIRED)

qt5_add_resources(Resources.qrc)

set(SOURCES
        main.cpp
        mainwindow.cpp
        parallelogrambutton.cpp
        rombusbutton.cpp
        scrollarea.cpp
        skewedbutton.cpp
        trapezbutton.cpp
        )

set(HEADERS
        mainwindow.h
        parallelogrambutton.h
        rombusbutton.h
        scrollarea.h
        skewedbutton.h
        trapezbutton.h
        )

add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS})

qt5_use_modules(${PROJECT_NAME} Core Gui)

But when I'm trying to run this CMake file I'm getting the following error:

The error message:

/<CMAKE_PATH>\cmake.exe --build /<PATH>/cmake-build-debug --target Project -- -j 4
[ 10%] Automatic MOC and UIC for target Project

AutoMoc subprocess error
------------------------
The moc process failed to compile
  "/<PATH>/mainwindow.h"
into
  "/<PATH>/cmake-build-debug/Project_autogen/EWIEGA46WW/moc_mainwindow.cpp".

Command
-------
/<CMAKE_PREFIX_PATH>/bin/moc.exe -I/<PATH>/cmake-build-debug -I/<PATH> -I/<CMAKE_PREFIX_PATH>/include -I/<CMAKE_PREFIX_PATH>/include/QtCore -I/<CMAKE_PREFIX_PATH>/./mkspecs/win32-g++ -I/<CMAKE_PREFIX_PATH>/include/QtGui -I/<CMAKE_PREFIX_PATH>/include/QtANGLE -I/usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include/c++ -I/usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include/c++/x86_64-pc-cygwin -I/usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include/c++/backward -I/usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include -I/usr/include -I/usr/include/w32api -DQT_CORE_LIB -DQT_GUI_LIB --include /<PATH>/cmake-build-debug/Project_autogen/moc_predefs.h -o /<PATH>/cmake-build-debug/Project_autogen/EWIEGA46WW/moc_mainwindow.cpp /<PATH>/mainwindow.h

Output
------

make[3]: *** [CMakeFiles/Project_autogen.dir/build.make:58: CMakeFiles/Project_autogen] Error 1
make[2]: *** [CMakeFiles/Makefile2:104: CMakeFiles/Project_autogen.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:84: CMakeFiles/Project.dir/rule] Error 2
make: *** [Makefile:118: Project] Error 2

Can any of you explain to me what I'm doing wrong here?

Body:
It looks like you are using obsolete CMake commands of Qt, see https://doc.qt.io/qt-5/cmake-command-reference.html.

You can create a new CMake-based project in Qt Creator and take it as a base. Qt Creator v4.12.x will generate something like:

cmake_minimum_required(VERSION 3.15)

project(Project)

set(CMAKE_PREFIX_PATH "C:/Qt/5.14.1/mingw73_64")
set(CMAKE_INCLUDE_PATH "C:/Qt/5.14.1/mingw73_64/bin")

set(CMAKE_CXX_STANDARD 11)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

find_package(Qt5 COMPONENTS Core Gui REQUIRED)

set(SOURCES
    main.cpp
    Resources.qrc
    mainwindow.cpp
    parallelogrambutton.cpp
    rombusbutton.cpp
    scrollarea.cpp
    skewedbutton.cpp
    trapezbutton.cpp
)

set(HEADERS
    mainwindow.h
    parallelogrambutton.h
    rombusbutton.h
    scrollarea.h
    skewedbutton.h
    trapezbutton.h
)

add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS})

target_link_libraries(${PROJECT_NAME} PRIVATE Qt5::Core Qt5::Gui)