问:
Flutter Format Time of Day from time picker
I am trying to format the selected time from time-picker in my flutter app. I don't know why but this is proving to be more difficult than it should be. The end result I am trying to achieve is hour:minuets or 5:00pm. This will display in a box container after user has picked the time from the time-picker widget. I have a method called 'timeFormater()' which will format the selcted time but i'm getting the error 'flutter: type 'TimeOfDay' is not a subtype of type 'Widget' when I run my code. Is there an easier way/method in flutter for formatting TimeOfDay()?

My Code:

```<code>      import 'package:flutter/material.dart';
    import 'package:flutter/cupertino.dart';
    import 'package:intl/intl.dart';
    import 'package:auto_size_text/auto_size_text.dart';
    import 'dart:io' show Platform;

    class DateTimePicker extends StatefulWidget {
      @override
      _DateTimePickerState createState() => _DateTimePickerState();
    }

    class _DateTimePickerState extends State<DateTimePicker> {
      DateTime _date = new DateTime.now();
      TimeOfDay _time = new TimeOfDay.now();
      Duration initialtimer = new Duration();
      DateTime _datePicked;
      TimeOfDay _timePicked;

      @override
      void initState() {
       // timeController.addListener(_time);

      }

      @override
      Widget build(BuildContext context) {
        return Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                // mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  dateContainer(),
                  timeContainer()
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  customDatePicker(context),
                  customTimePicker(context)
                ],
              ),
            ],
          ),
        );
      }
 Widget customTimePicker(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 12.0),
      child: FlatButton(
          child: Text('Time', style: TextStyle(
              color: Colors.white
          ),),
          color: Colors.deepOrange,
          onPressed: () => _selectedTime(context)
      ),
    );
  }
 Future<Null> _selectedTime(BuildContext context) async {
    _timePicked = await showTimePicker(
        context: context,
        initialTime: _time);

    if (_timePicked != null) {
      setState(() {
        _time = _timePicked;
      });
    }
  }
 Widget timeContainer() {
    return Container(
      width: 100,
      height: 100,
      child: Padding(
          padding: const EdgeInsets.only(left: 16.0, top: 16.0,bottom: 16.0),
          child: Container(
            decoration: BoxDecoration(
              border: Border.all(
                width: .5,
                color: Colors.black
              )
            ),
            child: timeFormater(),
          )
      ),
    );
  }

  Widget timeFormater() {
    return Column(
      children: <Widget>[
        SizedBox(
          height: 20.0,
        ),
        _timePicked != null
            ? TimeOfDay(hour: _timePicked.hour, minute: _timePicked.minute)
            : SizedBox(
          width: 0.0,
          height: 0.0,
        ),
      ],
    );
  }
}
</code>```

Error Message:

```<code>flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building DateTimePicker(dirty, dependencies: [_InheritedTheme,
flutter: _LocalizationsScope-[GlobalKey#6c45d]], state: _DateTimePickerState#7eeb8):
flutter: type 'TimeOfDay' is not a subtype of type 'Widget'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter:   https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      _DateTimePickerState.timeFormater (package:rallie_app/utils/custom_date_timer.dart:176:13)
flutter: #1      _DateTimePickerState.timeContainer (package:rallie_app/utils/custom_date_timer.dart:163:20)
flutter: #2      _DateTimePickerState.build (package:rallie_app/utils/custom_date_timer.dart:37:15)
flutter: #3      StatefulElement.build (package:flutter/src/widgets/framework.dart:3830:27)
flutter: #4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3741:15)
flutter: #5      Element.rebuild (package:flutter/src/widgets/framework.dart:3564:5)
flutter: #6      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2277:33)
flutter: #7      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
flutter: #8      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:275:5)
flutter: #9      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
flutter: #10     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
flutter: #11     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
flutter: #15     _invoke (dart:ui/hooks.dart:209:10)
flutter: #16     _drawFrame (dart:ui/hooks.dart:168:3)
flutter: (elided 3 frames from package dart:async)
</code>```

答: String time = _timePicked.format(context);</p>

Body:
I am trying to format the selected time from time-picker in my flutter app. I don't know why but this is proving to be more difficult than it should be. The end result I am trying to achieve is hour:minuets or 5:00pm. This will display in a box container after user has picked the time from the time-picker widget. I have a method called 'timeFormater()' which will format the selcted time but i'm getting the error 'flutter: type 'TimeOfDay' is not a subtype of type 'Widget' when I run my code. Is there an easier way/method in flutter for formatting TimeOfDay()?

My Code:

      import 'package:flutter/material.dart';
    import 'package:flutter/cupertino.dart';
    import 'package:intl/intl.dart';
    import 'package:auto_size_text/auto_size_text.dart';
    import 'dart:io' show Platform;

    class DateTimePicker extends StatefulWidget {
      @override
      _DateTimePickerState createState() => _DateTimePickerState();
    }

    class _DateTimePickerState extends State<DateTimePicker> {
      DateTime _date = new DateTime.now();
      TimeOfDay _time = new TimeOfDay.now();
      Duration initialtimer = new Duration();
      DateTime _datePicked;
      TimeOfDay _timePicked;

      @override
      void initState() {
       // timeController.addListener(_time);

      }

      @override
      Widget build(BuildContext context) {
        return Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                // mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  dateContainer(),
                  timeContainer()
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  customDatePicker(context),
                  customTimePicker(context)
                ],
              ),
            ],
          ),
        );
      }
 Widget customTimePicker(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 12.0),
      child: FlatButton(
          child: Text('Time', style: TextStyle(
              color: Colors.white
          ),),
          color: Colors.deepOrange,
          onPressed: () => _selectedTime(context)
      ),
    );
  }
 Future<Null> _selectedTime(BuildContext context) async {
    _timePicked = await showTimePicker(
        context: context,
        initialTime: _time);

    if (_timePicked != null) {
      setState(() {
        _time = _timePicked;
      });
    }
  }
 Widget timeContainer() {
    return Container(
      width: 100,
      height: 100,
      child: Padding(
          padding: const EdgeInsets.only(left: 16.0, top: 16.0,bottom: 16.0),
          child: Container(
            decoration: BoxDecoration(
              border: Border.all(
                width: .5,
                color: Colors.black
              )
            ),
            child: timeFormater(),
          )
      ),
    );
  }

  Widget timeFormater() {
    return Column(
      children: <Widget>[
        SizedBox(
          height: 20.0,
        ),
        _timePicked != null
            ? TimeOfDay(hour: _timePicked.hour, minute: _timePicked.minute)
            : SizedBox(
          width: 0.0,
          height: 0.0,
        ),
      ],
    );
  }
}

Error Message:

flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building DateTimePicker(dirty, dependencies: [_InheritedTheme,
flutter: _LocalizationsScope-[GlobalKey#6c45d]], state: _DateTimePickerState#7eeb8):
flutter: type 'TimeOfDay' is not a subtype of type 'Widget'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter:   https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      _DateTimePickerState.timeFormater (package:rallie_app/utils/custom_date_timer.dart:176:13)
flutter: #1      _DateTimePickerState.timeContainer (package:rallie_app/utils/custom_date_timer.dart:163:20)
flutter: #2      _DateTimePickerState.build (package:rallie_app/utils/custom_date_timer.dart:37:15)
flutter: #3      StatefulElement.build (package:flutter/src/widgets/framework.dart:3830:27)
flutter: #4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3741:15)
flutter: #5      Element.rebuild (package:flutter/src/widgets/framework.dart:3564:5)
flutter: #6      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2277:33)
flutter: #7      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
flutter: #8      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:275:5)
flutter: #9      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
flutter: #10     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
flutter: #11     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
flutter: #15     _invoke (dart:ui/hooks.dart:209:10)
flutter: #16     _drawFrame (dart:ui/hooks.dart:168:3)
flutter: (elided 3 frames from package dart:async)


来源: stackexchange

问:
Google Sheet Array Formula to automatically transpose responses from a Google Form into a single cell
I want to tweak an Array Formula that I'm trying to use to transpose a set of responses from a Google Form into a single 'list' in a cell in the linked Google Sheet.

Here is a simplified mock-up of the Google Sheet: https://docs.google.com/spreadsheets/d/1BKgjGK2RbXC5FkCgBOU53dLEb3fDeQADujenrqRgnT0/edit?usp=sharing

As you can see, I have a working Array Formula 'hidden' in the header for Column A, which takes the content from columns B:K in each row and transposes them with line breaks to make a nice neat list in the first cell at the start of each row (A2, A3, A4, etc.) Here is the Array Formula for ease of reference:

```<code>=ARRAYFORMULA({"Points to Develop";
transpose(query(transpose ($B$2:$B&CHAR(10)&$C$2:$C&CHAR(10)&$D$2:$D&CHAR(10)&$E$2:$E&CHAR(10)&$F$2:$F&CHAR(10)&$G$2:$G&CHAR(10)&$H$2:$H&CHAR(10)&$I$2:$I&CHAR(10)&$J$2:$J&CHAR(10)&$K$2:$K)
))})
</code>```

The problem I'm having is that the formula stops working as soon as a new Google Form is submitted, as the new row of responses arrives at the top and 'pushes the formula down'/throws everything out of alignment, when all I want is for it to stay in place and run automatically every time a Form is submitted. As you can probably gauge by my limited technical terminology, I'm very much a novice at this!

How can I fix this formula, or is there a simpler or better alternative that will achieve the same results?

答:
As often happens in life, the nature of the problem turned out to be the source of the solution. Here’s a condensed version of my thoughts as I slowly found my way to an answer (you can almost hear the hamster wheels turning in my head!):

The problem with formulas in a Google Sheet linked to a Google Form is that each new entry/submission from the form always arrives in Row 2 …

In fact, the only thing that stays ‘in place’ in the Google Sheet is the Header Row/Row 1 …

So, rather than using a formula that refers to a ‘Row 2’ that will become ‘Row 3/4/5/etc.’ as new Google Forms are submitted, I should use a formula that always refers to Row 1, that is, by using OFFSET

The obvious (if inelegant) formula that resulted from this is [I've also placed this in the final column in the Google Sheet that I linked to in my original question]:

```<code>= ARRAYFORMULA({"Points to Develop [Working OFFSET Formula]"; transpose(query(transpose(OFFSET(A1:A,1,1)&CHAR(10)&OFFSET(A1:A,1,2)&CHAR(10)&OFFSET(A1:A,1,3)&CHAR(10)&OFFSET(A1:A,1,4)&CHAR(10)&OFFSET(A1:A,1,5)&CHAR(10)&OFFSET(A1:A,1,6)&CHAR(10)&OFFSET(A1:A,1,7)&CHAR(10)&OFFSET(A1:A,1,8)&CHAR(10)&OFFSET(A1:A,1,9)&CHAR(10)&OFFSET(A1:A,1,10)))) })
</code>```

I am sure that there are neater ways of getting to the same result, but this is one that works for me … and is within my levels of comprehension, so I can fine-tune and fix it as needed.

ContentLicense: CC BY-SA 4.0

Body:
I want to tweak an Array Formula that I'm trying to use to transpose a set of responses from a Google Form into a single 'list' in a cell in the linked Google Sheet.

Here is a simplified mock-up of the Google Sheet: https://docs.google.com/spreadsheets/d/1BKgjGK2RbXC5FkCgBOU53dLEb3fDeQADujenrqRgnT0/edit?usp=sharing

As you can see, I have a working Array Formula 'hidden' in the header for Column A, which takes the content from columns B:K in each row and transposes them with line breaks to make a nice neat list in the first cell at the start of each row (A2, A3, A4, etc.) Here is the Array Formula for ease of reference:

=ARRAYFORMULA({"Points to Develop";
transpose(query(transpose ($B$2:$B&CHAR(10)&$C$2:$C&CHAR(10)&$D$2:$D&CHAR(10)&$E$2:$E&CHAR(10)&$F$2:$F&CHAR(10)&$G$2:$G&CHAR(10)&$H$2:$H&CHAR(10)&$I$2:$I&CHAR(10)&$J$2:$J&CHAR(10)&$K$2:$K)
))})

The problem I'm having is that the formula stops working as soon as a new Google Form is submitted, as the new row of responses arrives at the top and 'pushes the formula down'/throws everything out of alignment, when all I want is for it to stay in place and run automatically every time a Form is submitted. As you can probably gauge by my limited technical terminology, I'm very much a novice at this!

How can I fix this formula, or is there a simpler or better alternative that will achieve the same results?

Body:
As often happens in life, the nature of the problem turned out to be the source of the solution. Here’s a condensed version of my thoughts as I slowly found my way to an answer (you can almost hear the hamster wheels turning in my head!):

The problem with formulas in a Google Sheet linked to a Google Form is that each new entry/submission from the form always arrives in Row 2 …

In fact, the only thing that stays ‘in place’ in the Google Sheet is the Header Row/Row 1 …

So, rather than using a formula that refers to a ‘Row 2’ that will become ‘Row 3/4/5/etc.’ as new Google Forms are submitted, I should use a formula that always refers to Row 1, that is, by using OFFSET

The obvious (if inelegant) formula that resulted from this is [I've also placed this in the final column in the Google Sheet that I linked to in my original question]:

= ARRAYFORMULA({"Points to Develop [Working OFFSET Formula]"; transpose(query(transpose(OFFSET(A1:A,1,1)&CHAR(10)&OFFSET(A1:A,1,2)&CHAR(10)&OFFSET(A1:A,1,3)&CHAR(10)&OFFSET(A1:A,1,4)&CHAR(10)&OFFSET(A1:A,1,5)&CHAR(10)&OFFSET(A1:A,1,6)&CHAR(10)&OFFSET(A1:A,1,7)&CHAR(10)&OFFSET(A1:A,1,8)&CHAR(10)&OFFSET(A1:A,1,9)&CHAR(10)&OFFSET(A1:A,1,10)))) })

I am sure that there are neater ways of getting to the same result, but this is one that works for me … and is within my levels of comprehension, so I can fine-tune and fix it as needed.


问:
Why is my instance variable accessible without an instance?
My understanding of the Instance variables is that they are created when an object is created.  If that is true then why can print the variable "data"?  Shouldn't I have to create an object of class JavaTesting first?

```<code>public class JavaTesting
{
    static int a = 1;
    private int data = 99;

    @Test
    public void f1()
    {
        System.out.println("Print a = "+a);
        System.out.println("Print data = "+data);
    }

}
</code>```

答: Your method f1() is not a static method.  This means it can only be called on an instance.  Whatever method is calling f1() is probably creating an instance of JavaTesting first.  If you made f1() static, your IDE would probably have a fit and start coughing up red flags.

Body:
My understanding of the Instance variables is that they are created when an object is created.  If that is true then why can print the variable "data"?  Shouldn't I have to create an object of class JavaTesting first?

public class JavaTesting
{
    static int a = 1;
    private int data = 99;

    @Test
    public void f1()
    {
        System.out.println("Print a = "+a);
        System.out.println("Print data = "+data);
    }

}


问:
Identify GoogleTv from Android app
Is there a way for an Android app to tell in the Java code if it is running on GoogleTV vs tablets or phones? </p>

答:
Here's how I collect useful information for the feedback. I'm not aware if it's possible to detect type of the device (phone, vs table, vs. Google TV) but it's possible to build some sort of mapping database and match info against it</p>

```<code>private String getDeviceInfo() {
    final StringBuilder sb = new StringBuilder("\n\n---\n");
    try {
        sb.append("Version: ").append(getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName)
                .append('\n');
    } catch (final NameNotFoundException e) {
        // Shouldn't happen but if did - ignore
        Log.e(TAG, "failed to get app version", e);
    }
    sb.append("Model: ").append(Build.MODEL).append('\n');
    sb.append("Brand: ").append(Build.BRAND).append('\n');
    sb.append("Device: ").append(Build.DEVICE).append('\n');
    sb.append("Display: ").append(Build.DISPLAY).append('\n');
    sb.append("Hardware: ").append(Build.HARDWARE).append('\n');
    sb.append("Manufacturer: ").append(Build.MANUFACTURER).append('\n');
    sb.append("Host: ").append(Build.HOST).append('\n');
    sb.append("Release: ").append(Build.VERSION.RELEASE).append('\n');
    sb.append("Board: ").append(Build.BOARD).append('\n');
    sb.append("Radio: ").append(Build.RADIO).append('\n');
    sb.append("Product: ").append(Build.PRODUCT).append('\n');
    return sb.toString();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Identify GoogleTv from Android app

Body:
Here's how I collect useful information for the feedback. I'm not aware if it's possible to detect type of the device (phone, vs table, vs. Google TV) but it's possible to build some sort of mapping database and match info against it

private String getDeviceInfo() {
    final StringBuilder sb = new StringBuilder("\n\n---\n");
    try {
        sb.append("Version: ").append(getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName)
                .append('\n');
    } catch (final NameNotFoundException e) {
        // Shouldn't happen but if did - ignore
        Log.e(TAG, "failed to get app version", e);
    }
    sb.append("Model: ").append(Build.MODEL).append('\n');
    sb.append("Brand: ").append(Build.BRAND).append('\n');
    sb.append("Device: ").append(Build.DEVICE).append('\n');
    sb.append("Display: ").append(Build.DISPLAY).append('\n');
    sb.append("Hardware: ").append(Build.HARDWARE).append('\n');
    sb.append("Manufacturer: ").append(Build.MANUFACTURER).append('\n');
    sb.append("Host: ").append(Build.HOST).append('\n');
    sb.append("Release: ").append(Build.VERSION.RELEASE).append('\n');
    sb.append("Board: ").append(Build.BOARD).append('\n');
    sb.append("Radio: ").append(Build.RADIO).append('\n');
    sb.append("Product: ").append(Build.PRODUCT).append('\n');
    return sb.toString();
}


问:
Getting an error while trying to clone a repo from Azure DevOps project using VS Code
I am getting the following error while trying to clone a repo using VS Code in Windows 10.
Visual Studio Code
Git: remote: TF401019: The Git repository with name or identifier  does not exist or you do not have permissions for the operation you are attempting.

The developer has full permission to the repo and the project does exist in Azure DevOps.

Thank you for your help

Pedro Reinoso

答:
I was able to resolve the issue following another link in SO.  It had to do with clearing the Git credentials in the PC affected.  Below is the link we followed to resolve the issue:

Remove credentials from Git

Thank you


问:
Reactjs Helmet, GoogleSEO
Does somebody know about a Helmet in ReactJS (https://github.com/nfl/react-helmet). I try to use Helmet for google seo.

```<code><Helmet>
    <meta charSet="utf-8" />
    <title>My Title</title>
    <link rel="canonical" href={process.env.PUBLIC_URL} />
</Helmet>
</code>```

Why comes mistakes in console?

答:
componentWillMount has been deprecated.

These methods are considered legacy and you should avoid them in new code:

Title: Reactjs Helmet, GoogleSEO

Body:
Does somebody know about a Helmet in ReactJS (https://github.com/nfl/react-helmet). I try to use Helmet for google seo.

<Helmet>
    <meta charSet="utf-8" />
    <title>My Title</title>
    <link rel="canonical" href={process.env.PUBLIC_URL} />
</Helmet>

Why comes mistakes in console?


问:
How can I define a 5x3 array of strings in python?
How can I define a 5x3 array of strings in python?

I want to save the following data in an array of strings:

```<code>Name    Surname Grade
Steve   Black   10
Jane    Red     10
Peter   Green   0
Kelly   Pink    7
</code>```

I am coming from C/C++ and in this programming language it would look like this:

```<code>matrix[5][3];

matrix[0][0] = "Name";
matrix[0][1] = "Surname";
matrix[0][2] = "Grade";

matrix[1][0] = "Steve";
matrix[1][1] = "Black";
matrix[1][2] = "10";

...
...
...

matrix[4][0] = "Kelly";
matrix[4][1] = "Pink";
matrix[4][2] = "7";
</code>```

Is there a way in python to create such table?

In case you know what kind of data type that is in python and how it work, please let me know.

答: Python doesn't have multidimensional arrays, but you can achieve a similar affect by nesting lists. Python Arrays - w3 schools</p>

Body:
How can I define a 5x3 array of strings in python?

I want to save the following data in an array of strings:

Name    Surname Grade
Steve   Black   10
Jane    Red     10
Peter   Green   0
Kelly   Pink    7

I am coming from C/C++ and in this programming language it would look like this:

matrix[5][3];

matrix[0][0] = "Name";
matrix[0][1] = "Surname";
matrix[0][2] = "Grade";

matrix[1][0] = "Steve";
matrix[1][1] = "Black";
matrix[1][2] = "10";

...
...
...

matrix[4][0] = "Kelly";
matrix[4][1] = "Pink";
matrix[4][2] = "7";

Is there a way in python to create such table?

In case you know what kind of data type that is in python and how it work, please let me know.


问:
Possible to join pdf-forms, fill and use passthrough in one command (PDFTK and PHP)?
I use pdftk successfully to fill a pdfform in PHP with the following code:

```<code>passthru( '/usr/bin/pdftk /mallpdf/1.pdf fill_form '.$tmpfname.' output - ');
</code>```

Now I have two pdfforms which I would like to join and then fill with data.

Tried the code below but no success, any thoughts? Or perhaps not possible?

```<code>passthru( '/usr/bin/pdftk /mallpdf/1.pdf /mallpdf/2.pdf cat fill_form '.$tmpfname.' output - flatten');
</code>```

答: You cannot do two operations at once with a single call to pdftk. Fill each of the forms with a separate call, then merge them together with a third call.</p>

Body:
I use pdftk successfully to fill a pdfform in PHP with the following code:

passthru( '/usr/bin/pdftk /mallpdf/1.pdf fill_form '.$tmpfname.' output - ');

Now I have two pdfforms which I would like to join and then fill with data.

Tried the code below but no success, any thoughts? Or perhaps not possible?

passthru( '/usr/bin/pdftk /mallpdf/1.pdf /mallpdf/2.pdf cat fill_form '.$tmpfname.' output - flatten');


问:
Counting zeros in a rolling - numpy array (including NaNs)
I am trying to find a way of Counting zeros in a rolling using numpy array ?

Using pandas I can get it using:

```<code>df['demand'].apply(lambda x: (x == 0).rolling(7).sum()).fillna(0))
</code>```

or

```<code>df['demand'].transform(lambda x: x.rolling(7).apply(lambda x: 7 - np.count _nonzero(x))).fillna(0)
</code>```

In numpy, using the code from Here

```<code>def rolling_window(a, window_size):
    shape = (a.shape[0] - window_size + 1, window_size) + a.shape[1:]
    print(shape)
    strides = (a.strides[0],) + a.strides
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

arr = np.asarray([10, 20, 30, 5, 6, 0, 0, 0])

np.count_nonzero(rolling_window(arr==0, 7), axis=1)

Output:
    array([2, 3])
</code>```

However, I need the first 6 NaNs as well, and fill it with zeros:

Expected output:

```<code>array([0, 0, 0, 0, 0, 0, 2, 3])
</code>```

答:
I would modify the function as follow:

```<code>def count_rolling(a, window_size):
    shape = (a.shape[0] - window_size + 1, window_size) + a.shape[1:]

    strides = (a.strides[0],) + a.strides
    rolling = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

    out = np.zeros_like(a)
    out[window_size-1:] = (rolling == 0).sum(1)
    return out

arr = np.asarray([10, 20, 30, 5, 6, 0, 0, 0])
count_rolling(arr,7)
</code>```

Output:

```<code>array([0, 0, 0, 0, 0, 0, 2, 3])
</code>```

Body:
I am trying to find a way of Counting zeros in a rolling using numpy array ?

Using pandas I can get it using:

df['demand'].apply(lambda x: (x == 0).rolling(7).sum()).fillna(0))

or

df['demand'].transform(lambda x: x.rolling(7).apply(lambda x: 7 - np.count _nonzero(x))).fillna(0)

In numpy, using the code from Here

def rolling_window(a, window_size):
    shape = (a.shape[0] - window_size + 1, window_size) + a.shape[1:]
    print(shape)
    strides = (a.strides[0],) + a.strides
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

arr = np.asarray([10, 20, 30, 5, 6, 0, 0, 0])

np.count_nonzero(rolling_window(arr==0, 7), axis=1)

Output:
    array([2, 3])

However, I need the first 6 NaNs as well, and fill it with zeros:

Expected output:

array([0, 0, 0, 0, 0, 0, 2, 3])

Body:
I would modify the function as follow:

def count_rolling(a, window_size):
    shape = (a.shape[0] - window_size + 1, window_size) + a.shape[1:]

    strides = (a.strides[0],) + a.strides
    rolling = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

    out = np.zeros_like(a)
    out[window_size-1:] = (rolling == 0).sum(1)
    return out

arr = np.asarray([10, 20, 30, 5, 6, 0, 0, 0])
count_rolling(arr,7)

Output:

array([0, 0, 0, 0, 0, 0, 2, 3])


问:
How to limit DBA_AUDIT_TRAIL activity visibility by schema or other possibilities to see activity for targeted schemas
I am asking the DBA to turn on DBA_AUDIT_TRAIL logging and I am getting push back.  In some environments, I see change activity logged when I query this table, in other environments, I do not.

I am only interested in a handful of schemas. In my opinion, if my visibility of this table could be limited to the schemas that I have an interest in tracking, then there might potentially be less resistance to granting me access. What is the best way to grant me access to only the objects in a target schema list? Is there an alternate view that I could be granted access to?

Is there an existing Oracle view that limits row activity to only those objects that a user otherwise has visibility to or do we have to create our own view or more primitively, say, create a view like this

```<code>SELECT * FROM DBA_AUDIT_TRAIL WHERE OWNER IN ('schema1','schema2')
</code>```

and limit SELECT access to the view? I'm not sure if this query is returning no rows in some envs because logging isn't turned on or whether I just don't have the proper access.

答:
Generally, it's best to install a database where you have access to everything (DBA, SYSDBA etc.) Then you can just lookup the documentation and try things out. You'll gain the trust of your DBAs much quicker if they notice that you know what you're talking about. For example here or here.

To your question: Auditing can be switched of totally for a database, but this is rare. If it is enabled, you need to enable it for a whole schema or for individual objects like tables. Restricting read access to DBA_AUDIT_TRAIL is good practice, as there is likely data in there that needs to be protected (like personal log ons etc).

Secondly, one has to be very careful about the amount of data that will be generated by enabling audit on a table. My DBAs enable it only for a short period of time and switch it off again to check how much data was generated.

A view that restricts data is an excellent idea, you should work together with the DBAs to create one for you.

EDIT: Apparently, and example is in order. Took a while as I had to switch on auditing which is disabled by default on Oracle's vagrant boxes.

As you suggest, a DBA could create AS SYSDBA a view on top of DBA_AUDIT_TRAIL filtering out a specific OWNER, or the current connected session (so that every user can see the audit actions of his/her own tables):

```<code>CREATE OR REPLACE VIEW USER_AUDIT_TRAIL
AS
SELECT *
  FROM DBA_AUDIT_TRAIL
 WHERE username = SYS_CONTEXT('USERENV','SESSION_USER');
</code>```

Access to this view can be granted to you or to all users:

```<code>CREATE PUBLIC SYNONYM USER_AUDIT_TRAIL FOR SYS.USER_AUDIT_TRAIL;
GRANT SELECT ON USER_AUDIT_TRAIL TO PUBLIC;
</code>```

Please do speak to the DBAs, they may want to exclude some columns and rows of the view from public exposure.

Body:
I am asking the DBA to turn on DBA_AUDIT_TRAIL logging and I am getting push back.  In some environments, I see change activity logged when I query this table, in other environments, I do not.

I am only interested in a handful of schemas. In my opinion, if my visibility of this table could be limited to the schemas that I have an interest in tracking, then there might potentially be less resistance to granting me access. What is the best way to grant me access to only the objects in a target schema list? Is there an alternate view that I could be granted access to?

Is there an existing Oracle view that limits row activity to only those objects that a user otherwise has visibility to or do we have to create our own view or more primitively, say, create a view like this

SELECT * FROM DBA_AUDIT_TRAIL WHERE OWNER IN ('schema1','schema2')

and limit SELECT access to the view? I'm not sure if this query is returning no rows in some envs because logging isn't turned on or whether I just don't have the proper access.

Body:
Generally, it's best to install a database where you have access to everything (DBA, SYSDBA etc.) Then you can just lookup the documentation and try things out. You'll gain the trust of your DBAs much quicker if they notice that you know what you're talking about. For example here or here.

To your question: Auditing can be switched of totally for a database, but this is rare. If it is enabled, you need to enable it for a whole schema or for individual objects like tables. Restricting read access to DBA_AUDIT_TRAIL is good practice, as there is likely data in there that needs to be protected (like personal log ons etc).

Secondly, one has to be very careful about the amount of data that will be generated by enabling audit on a table. My DBAs enable it only for a short period of time and switch it off again to check how much data was generated.

A view that restricts data is an excellent idea, you should work together with the DBAs to create one for you.

EDIT: Apparently, and example is in order. Took a while as I had to switch on auditing which is disabled by default on Oracle's vagrant boxes.

As you suggest, a DBA could create AS SYSDBA a view on top of DBA_AUDIT_TRAIL filtering out a specific OWNER, or the current connected session (so that every user can see the audit actions of his/her own tables):

CREATE OR REPLACE VIEW USER_AUDIT_TRAIL
AS
SELECT *
  FROM DBA_AUDIT_TRAIL
 WHERE username = SYS_CONTEXT('USERENV','SESSION_USER');

Access to this view can be granted to you or to all users:

CREATE PUBLIC SYNONYM USER_AUDIT_TRAIL FOR SYS.USER_AUDIT_TRAIL;
GRANT SELECT ON USER_AUDIT_TRAIL TO PUBLIC;

Please do speak to the DBAs, they may want to exclude some columns and rows of the view from public exposure.


问:
A* Path Finder (Java) is inefficient using a 1024 multidimentional array
I have the below code for a A* pathfinder, however it is taking upwards of 10 minutes to find a solution using a simple 1024 x 1024 array.

I had to comment out //Collections.sort(this.openList); as it was throwing a comparison method violates its general contract! error when running.

Is the algorithm correct and any idea why the bottleneck? Some people using C++ are getting a response time of 40ms, not 10+ mins!

When using the maze array it does it in the blink of an eye, but thats using something like a 14x10 array, rather than 1024 from the collisionMap.

Is the method flawed in some way? Or using the wrong data structures?

```<code>import java.util.List;

import javax.imageio.ImageIO;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.GraphicsConfiguration;
import java.awt.Paint;
import java.awt.image.BufferedImage;
import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

class AStarTwo {

    // Closed list, open list and calculatedPath lists
    private final List<Node> openList;
    private final List<Node> closedList;
    private final List<Node> calcPath;

    // Collision Map to store tha map in
    private final int[][] collisionMap;

    // Current node the  program is executing
    private Node currentNode;

    // Define the start and end coords
    private final int xstart;
    private final int ystart;
    private int xEnd, yEnd;

    // Node class
    static class Node implements Comparable {
        public Node parent;
        public int x, y;
        public double g;
        public double h;
        Node(Node parent, int xpos, int ypos, double g, double h) {
            this.parent = parent;
            this.x = xpos;
            this.y = ypos;
            this.g = g;
            this.h = h;
       }

       // Compare f value (g + h)
       @Override
       public int compareTo(Object o) {
           Node that = (Node) o;
           return (int)((this.g + this.h) - (that.g + that.h));
       }
   }

    // construct and initialise
    public AStarTwo(int[][] collisionMap, int xstart, int ystart) {
        this.openList = new ArrayList<>();
        this.closedList = new ArrayList<>();
        this.calcPath = new ArrayList<>();
        this.collisionMap = collisionMap;
        this.currentNode = new Node(null, xstart, ystart, 0, 0);
        this.xstart = xstart;
        this.ystart = ystart;

    }

    // returns a List<> of nodes to target
    public List<Node> findPathTo(int xTo, int yTo) {

        this.xEnd = xTo;
        this.yEnd = yTo;

        // Add this to the closed list
        this.closedList.add(this.currentNode);

        // Add neighbours to openList for iteration
        addNeigborsToOpenList();

        // Whilst not at our target
        while (this.currentNode.x != this.xEnd || this.currentNode.y != this.yEnd) {

            // If nothing in the open list then return with null - handled in error message in main calling func
            if (this.openList.isEmpty()) {
                return null;
            }

            // get the lowest f value and add it to the closed list, f calculated when neighbours are sorted
            this.currentNode = this.openList.get(0);
            this.openList.remove(0);
            this.closedList.add(this.currentNode);

            addNeigborsToOpenList();

        }

        // add this node to the calculated path
        this.calcPath.add(0, this.currentNode);

        while (this.currentNode.x != this.xstart || this.currentNode.y != this.ystart) {

            this.currentNode = this.currentNode.parent;

            this.calcPath.add(0, this.currentNode);

        }

        return this.calcPath;
    }

    // Searches the current list for neighbouring nodes returns bool
    private static boolean checkNeighbourHasBeenSearched(List<Node> array, Node node) {
        return array.stream().anyMatch((n) -> (n.x == node.x && n.y == node.y));
    }

    // Calculate distance from current node to the target
    private double distance(int dx, int dy) {
        return Math.hypot(this.currentNode.x + dx - this.xEnd, this.currentNode.y + dy - this.yEnd); // return hypothenuse
    }

    // Add neighbouring nodes to the open list to iterate through next
    @SuppressWarnings("unchecked")
    private void addNeigborsToOpenList() {

        Node node;

        for (int x = -1; x <= 1; x++) {

            for (int y = -1; y <= 1; y++) {

                node = new Node(this.currentNode, this.currentNode.x + x, this.currentNode.y + y, this.currentNode.g, this.distance(x, y));

                // if we are not on the current node
                if ((x != 0 || y != 0)
                    && this.currentNode.x + x >= 0 && this.currentNode.x + x < this.collisionMap[0].length // check collision map boundaries
                    && this.currentNode.y + y >= 0 && this.currentNode.y + y < this.collisionMap.length
                    && this.collisionMap[this.currentNode.y + y][this.currentNode.x + x] != -1) { // check if tile is walkable (-1)

                    // and finally check we haven't already searched the nodes
                    if(!checkNeighbourHasBeenSearched(this.openList, node) && !checkNeighbourHasBeenSearched(this.closedList, node)){
                        node.g = node.parent.g + 1.; // Horizontal/vertical cost = 1.0
                        node.g += collisionMap[this.currentNode.y + y][this.currentNode.x + x]; // add movement cost for this square

                        // Add diagonal movement cost sqrt(hor_cost² + vert_cost²) + 0.4
                        if (x != 0 && y != 0) {
                            node.g += .4;
                        }

                        // Add the node to the List<>
                        this.openList.add(node);
                    }

                }
            }
        }

        // sort in ascending order
        //Collections.sort(this.openList);
    }

    public static void main(String[] args) {

        int [][] maze =
            { {1,1,1,1,1,1,1,1,1,1,1,1,1},
              {1,0,-1,0,-1,0,1,0,0,0,0,0,1},
              {1,0,-1,0,0,0,1,0,1,1,1,0,1},
              {1,0,0,0,-1,-1,-1,0,0,0,0,0,1},
              {1,0,1,0,0,0,0,0,1,1,1,0,1},
              {1,0,1,0,-1,-1,-1,0,1,0,0,0,-1},
              {1,0,-1,0,-1,0,0,0,-1,-1,-1,0,-1},
              {1,0,1,0,-1,-1,-1,0,1,0,-1,0,-1},
              {1,0,0,0,0,0,0,0,0,0,1,0,1},
              {1,1,1,1,1,1,1,1,1,1,1,1,1}

            };

        // Define the size of the grid
        final int sizeOf = 20;

        int[][] collisionMap = new int[sizeOf][];

        for(int i=0;i < sizeOf; i++) {
            // -1 = blocked
            // 0+ = cost
            collisionMap[i] = new int[sizeOf];
        }

        // set the value of the nodes
        for (int k = 0; k < sizeOf; k++) {
            for (int j = 0; j < sizeOf; j++) {
                if(j == 30 && k < 100) {
                    collisionMap[k][j] = -1;
                } else if (j == 50 && k > 230) {
                    collisionMap[k][j] = -1;
                }else {
                    collisionMap[k][j] = 0;
                }

            }
        }

        AStarTwo as = new AStarTwo(maze, 9, 9);
        List<Node> path = as.findPathTo(0,0);

        if(path == null) {
            System.out.println("Unable to reach target");
        }

        // create image buffer to write output to
        BufferedImage img = new BufferedImage(sizeOf, sizeOf, BufferedImage.TYPE_INT_RGB);

        // Set colours
        int r = 255;
        int g = 0;
        int b = 0;

        int colRed = (r << 16) | (g << 8) | b;

        r = 0;
        g = 255;
        b = 0;

        int colGreen = (r << 16) | (g << 8) | b;

        r = 0;
        g = 0;
        b = 255;

        int colBlue = (r << 16) | (g << 8) | b;

        r = 255;
        g = 255;
        b = 255;

        int colWhite = (r << 16) | (g << 8) | b;

        int i = 0;
        int j = 0;

        if (path != null) {

            path.forEach((n) -> {
                System.out.print("[" + n.x + ", " + n.y + "] ");
                maze[n.y][n.x] = 2;
            });

            for (int[] maze_row : maze) {
                for (int maze_entry : maze_row) {
                    switch (maze_entry) {

                        // normal tile
                        case 0:
                            img.setRGB(j, i, colWhite);
                            break;

                        // final path
                        case 2:
                            img.setRGB(j, i, colBlue);
                            break;

                        // Object to avoid
                        case -1:
                            img.setRGB(j, i, colRed);
                            break;

                        // Any other value
                        default:
                            img.setRGB(j, i, colWhite);
                    }

                    j++;
                }
                // count j - reset as if it were a for loop
                if(i != 12) {
                    j=0;
                }
                i++;
                System.out.println();
            }
        }

        // output file
        File f = new File("aStarPath.png");

        try {
            ImageIO.write(img, "PNG", f);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("i: " + i + ", j: " + j);
    }
}
</code>```

答:
I suspect your problem is this line:

```<code>return array.stream().anyMatch((n) -> (n.x == node.x && n.y == node.y));
</code>```

which is called around O(n^2) times and will take time proportional to the size of the array (which will also be O(n^2) in the worst case for a n by n maze).

You want a faster method of performing this test.

For example:

Use a set to hold the open and closed lists instead of list

Or use an extra field in the node structure to indicate if it is in the open or closed list

Body:
I have the below code for a A* pathfinder, however it is taking upwards of 10 minutes to find a solution using a simple 1024 x 1024 array.

I had to comment out //Collections.sort(this.openList); as it was throwing a comparison method violates its general contract! error when running.

Is the algorithm correct and any idea why the bottleneck? Some people using C++ are getting a response time of 40ms, not 10+ mins!

When using the maze array it does it in the blink of an eye, but thats using something like a 14x10 array, rather than 1024 from the collisionMap.

Is the method flawed in some way? Or using the wrong data structures?

import java.util.List;

import javax.imageio.ImageIO;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.GraphicsConfiguration;
import java.awt.Paint;
import java.awt.image.BufferedImage;
import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

class AStarTwo {

    // Closed list, open list and calculatedPath lists
    private final List<Node> openList;
    private final List<Node> closedList;
    private final List<Node> calcPath;

    // Collision Map to store tha map in
    private final int[][] collisionMap;

    // Current node the  program is executing
    private Node currentNode;

    // Define the start and end coords
    private final int xstart;
    private final int ystart;
    private int xEnd, yEnd;

    // Node class
    static class Node implements Comparable {
        public Node parent;
        public int x, y;
        public double g;
        public double h;
        Node(Node parent, int xpos, int ypos, double g, double h) {
            this.parent = parent;
            this.x = xpos;
            this.y = ypos;
            this.g = g;
            this.h = h;
       }

       // Compare f value (g + h)
       @Override
       public int compareTo(Object o) {
           Node that = (Node) o;
           return (int)((this.g + this.h) - (that.g + that.h));
       }
   }

    // construct and initialise
    public AStarTwo(int[][] collisionMap, int xstart, int ystart) {
        this.openList = new ArrayList<>();
        this.closedList = new ArrayList<>();
        this.calcPath = new ArrayList<>();
        this.collisionMap = collisionMap;
        this.currentNode = new Node(null, xstart, ystart, 0, 0);
        this.xstart = xstart;
        this.ystart = ystart;

    }

    // returns a List<> of nodes to target
    public List<Node> findPathTo(int xTo, int yTo) {

        this.xEnd = xTo;
        this.yEnd = yTo;

        // Add this to the closed list
        this.closedList.add(this.currentNode);

        // Add neighbours to openList for iteration
        addNeigborsToOpenList();

        // Whilst not at our target
        while (this.currentNode.x != this.xEnd || this.currentNode.y != this.yEnd) {

            // If nothing in the open list then return with null - handled in error message in main calling func
            if (this.openList.isEmpty()) {
                return null;
            }

            // get the lowest f value and add it to the closed list, f calculated when neighbours are sorted
            this.currentNode = this.openList.get(0);
            this.openList.remove(0);
            this.closedList.add(this.currentNode);

            addNeigborsToOpenList();

        }

        // add this node to the calculated path
        this.calcPath.add(0, this.currentNode);

        while (this.currentNode.x != this.xstart || this.currentNode.y != this.ystart) {

            this.currentNode = this.currentNode.parent;

            this.calcPath.add(0, this.currentNode);

        }

        return this.calcPath;
    }

    // Searches the current list for neighbouring nodes returns bool
    private static boolean checkNeighbourHasBeenSearched(List<Node> array, Node node) {
        return array.stream().anyMatch((n) -> (n.x == node.x && n.y == node.y));
    }

    // Calculate distance from current node to the target
    private double distance(int dx, int dy) {
        return Math.hypot(this.currentNode.x + dx - this.xEnd, this.currentNode.y + dy - this.yEnd); // return hypothenuse
    }

    // Add neighbouring nodes to the open list to iterate through next
    @SuppressWarnings("unchecked")
    private void addNeigborsToOpenList() {

        Node node;

        for (int x = -1; x <= 1; x++) {

            for (int y = -1; y <= 1; y++) {

                node = new Node(this.currentNode, this.currentNode.x + x, this.currentNode.y + y, this.currentNode.g, this.distance(x, y));

                // if we are not on the current node
                if ((x != 0 || y != 0)
                    && this.currentNode.x + x >= 0 && this.currentNode.x + x < this.collisionMap[0].length // check collision map boundaries
                    && this.currentNode.y + y >= 0 && this.currentNode.y + y < this.collisionMap.length
                    && this.collisionMap[this.currentNode.y + y][this.currentNode.x + x] != -1) { // check if tile is walkable (-1)

                    // and finally check we haven't already searched the nodes
                    if(!checkNeighbourHasBeenSearched(this.openList, node) && !checkNeighbourHasBeenSearched(this.closedList, node)){
                        node.g = node.parent.g + 1.; // Horizontal/vertical cost = 1.0
                        node.g += collisionMap[this.currentNode.y + y][this.currentNode.x + x]; // add movement cost for this square

                        // Add diagonal movement cost sqrt(hor_cost² + vert_cost²) + 0.4
                        if (x != 0 && y != 0) {
                            node.g += .4;
                        }

                        // Add the node to the List<>
                        this.openList.add(node);
                    }

                }
            }
        }

        // sort in ascending order
        //Collections.sort(this.openList);
    }

    public static void main(String[] args) {

        int [][] maze =
            { {1,1,1,1,1,1,1,1,1,1,1,1,1},
              {1,0,-1,0,-1,0,1,0,0,0,0,0,1},
              {1,0,-1,0,0,0,1,0,1,1,1,0,1},
              {1,0,0,0,-1,-1,-1,0,0,0,0,0,1},
              {1,0,1,0,0,0,0,0,1,1,1,0,1},
              {1,0,1,0,-1,-1,-1,0,1,0,0,0,-1},
              {1,0,-1,0,-1,0,0,0,-1,-1,-1,0,-1},
              {1,0,1,0,-1,-1,-1,0,1,0,-1,0,-1},
              {1,0,0,0,0,0,0,0,0,0,1,0,1},
              {1,1,1,1,1,1,1,1,1,1,1,1,1}

            };

        // Define the size of the grid
        final int sizeOf = 20;

        int[][] collisionMap = new int[sizeOf][];

        for(int i=0;i < sizeOf; i++) {
            // -1 = blocked
            // 0+ = cost
            collisionMap[i] = new int[sizeOf];
        }

        // set the value of the nodes
        for (int k = 0; k < sizeOf; k++) {
            for (int j = 0; j < sizeOf; j++) {
                if(j == 30 && k < 100) {
                    collisionMap[k][j] = -1;
                } else if (j == 50 && k > 230) {
                    collisionMap[k][j] = -1;
                }else {
                    collisionMap[k][j] = 0;
                }

            }
        }

        AStarTwo as = new AStarTwo(maze, 9, 9);
        List<Node> path = as.findPathTo(0,0);

        if(path == null) {
            System.out.println("Unable to reach target");
        }

        // create image buffer to write output to
        BufferedImage img = new BufferedImage(sizeOf, sizeOf, BufferedImage.TYPE_INT_RGB);

        // Set colours
        int r = 255;
        int g = 0;
        int b = 0;

        int colRed = (r << 16) | (g << 8) | b;

        r = 0;
        g = 255;
        b = 0;

        int colGreen = (r << 16) | (g << 8) | b;

        r = 0;
        g = 0;
        b = 255;

        int colBlue = (r << 16) | (g << 8) | b;

        r = 255;
        g = 255;
        b = 255;

        int colWhite = (r << 16) | (g << 8) | b;

        int i = 0;
        int j = 0;

        if (path != null) {

            path.forEach((n) -> {
                System.out.print("[" + n.x + ", " + n.y + "] ");
                maze[n.y][n.x] = 2;
            });

            for (int[] maze_row : maze) {
                for (int maze_entry : maze_row) {
                    switch (maze_entry) {

                        // normal tile
                        case 0:
                            img.setRGB(j, i, colWhite);
                            break;

                        // final path
                        case 2:
                            img.setRGB(j, i, colBlue);
                            break;

                        // Object to avoid
                        case -1:
                            img.setRGB(j, i, colRed);
                            break;

                        // Any other value
                        default:
                            img.setRGB(j, i, colWhite);
                    }

                    j++;
                }
                // count j - reset as if it were a for loop
                if(i != 12) {
                    j=0;
                }
                i++;
                System.out.println();
            }
        }

        // output file
        File f = new File("aStarPath.png");

        try {
            ImageIO.write(img, "PNG", f);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("i: " + i + ", j: " + j);
    }
}

Body:
I suspect your problem is this line:

return array.stream().anyMatch((n) -> (n.x == node.x && n.y == node.y));

which is called around O(n^2) times and will take time proportional to the size of the array (which will also be O(n^2) in the worst case for a n by n maze).

You want a faster method of performing this test.

For example:

Use a set to hold the open and closed lists instead of list

Or use an extra field in the node structure to indicate if it is in the open or closed list


问:
Regex - how to exclude 4 digit number from wider numeric pattern
Really tried to browse and search if this specific question has been posted previously, so I hope I'm not asking an obvious one here.

My problem: I have a regex expression, with few different possible criteria for pattern matching separated by pipes. I'm OK with all of them except one, where I basically want to:

Find any expression which would be number between 4 and 6 digits (regardless of position in the string)

Exclude from this pattern expressions which would relate to years in this century (so starting with 20 and followed by two digits)

So for example, I would like to match: 4149, 20259, 202046, but would like to exclude 2019 as it will refer to a year and not the code I'm searching for.

Currently, I tried applying this one (only last part of the expression): |\d{4,6}?!20\d{2}) , but it's not working properly. I know that the expressions preceeding pipe are fine and was able to notice that \d{4,6} stops to work once I add the "exclusion" in this case, so I assume I'm not using the ?! properly. Could I ask you for an advice on this one?

Edit: Solved! Thank you very much for immediate answers (I was really positively surprised how fast there were few alternative solutions). Sorry I had to pick just one, all of others would be adjustable and viable for my needs, I just found this one most appealing and tailored for my needs.

答:
You could use the following regular expression.

```<code>r'\b(?:20\d{3,4}|2[1-9]\d{2,4}|[1,3-9]\d{3,5})\b'
</code>```

Demo

Body:
You could use the following regular expression.

r'\b(?:20\d{3,4}|2[1-9]\d{2,4}|[1,3-9]\d{3,5})\b'

Demo


问:
Calculate total in SQL from two different rows by date
I have a table with: date, daily_count and total_count and total_count is empty and has to be calculated with MySQL. Date and daily_count are known and I want to calculate today's total_count from daily_count(today) + total count(yesterday).

I can calculate it with:

```<code>SELECT t2.daily_count + t1.total_count total
 FROM mytbl t1, mytbl t2
 WHERE t1.date = '2020-2-27' AND t2.date = '2020-2-28'
</code>```

How can I do that at once for a table with more than one year of data and with only date en daily count. So all the total_counts have to be calculated. And later I want to UPDATE the total into total_count in mytbl. Or do I have two write down all the 365 SQL lines with different dates for one year of data?

答:
For cumulative sum you can do the following:

```<code>SET @t=0;
SELECT daily_count,@t:=@t+daily_count FROM mytbl ORDER BY mytbl.date;
</code>```

Same can be done with update as well. Use ORDER BY to ensure correct processing order.

```<code>SET @t=0;
UPDATE mytbl SET total_count=@t:=@t+daily_count ORDER BY mytbl.date;
</code>```

Body:
I have a table with: date, daily_count and total_count and total_count is empty and has to be calculated with MySQL. Date and daily_count are known and I want to calculate today's total_count from daily_count(today) + total count(yesterday).

I can calculate it with:

SELECT t2.daily_count + t1.total_count total
 FROM mytbl t1, mytbl t2
 WHERE t1.date = '2020-2-27' AND t2.date = '2020-2-28'

How can I do that at once for a table with more than one year of data and with only date en daily count. So all the total_counts have to be calculated. And later I want to UPDATE the total into total_count in mytbl. Or do I have two write down all the 365 SQL lines with different dates for one year of data?

Body:
For cumulative sum you can do the following:

SET @t=0;
SELECT daily_count,@t:=@t+daily_count FROM mytbl ORDER BY mytbl.date;

Same can be done with update as well. Use ORDER BY to ensure correct processing order.

SET @t=0;
UPDATE mytbl SET total_count=@t:=@t+daily_count ORDER BY mytbl.date;


问:
Can I pass Cypress.env inside of plugin/index.js file?
I have created a cypress 'task' to grab data from DB , I dont want to store credentials for configDB in index file and wanted to pass it through cypress.json . Cypress.env didnt work is there a workaround ? </p>

```<code>const configDB = {
      server: "xxx",
      port: xxx,
      domain: "US",
      user: "username",
      password: "password",
      database: "database",
      driver: "tedious",
      options: {
        enableArithAbort: true,
      },
    };
    const sql = require("mssql");

</code>```

答:
Refer here.

In plugins/index.js file, set it as config.env:

```<code>module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config

  // modify env var value
  config.env.ENVIRONMENT = 'dev';

  // return config to update the global configuration
  return config
}
</code>```

Body:
I have created a cypress 'task' to grab data from DB , I dont want to store credentials for configDB in index file and wanted to pass it through cypress.json . Cypress.env didnt work is there a workaround ?

const configDB = {
      server: "xxx",
      port: xxx,
      domain: "US",
      user: "username",
      password: "password",
      database: "database",
      driver: "tedious",
      options: {
        enableArithAbort: true,
      },
    };
    const sql = require("mssql");

Body:
Refer here.

In plugins/index.js file, set it as config.env:

module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config

  // modify env var value
  config.env.ENVIRONMENT = 'dev';

  // return config to update the global configuration
  return config
}


问:
Rails Action Text for existing text field
I am upgrading one of my news app to Rails 6.0.0. While working around I got a problem using Rich Text. My app is pointing the rich text body field instead of the my existing table body field.

Is it possible to use the existing table text field for the rich text, so that I can edit the contents whenever I need it. Like for new posts I can use the action_text_rich_texts table but for the existing posts I want to use the existing table body field.

答:
Assuming there's a content in your model and that's what you want to migrate, first, add to your model:

```<code>has_rich_text :content
</code>```

Then create a migration

```<code>rails g migration MigratePostContentToActionText
</code>```

Result:

```<code>class MigratePostContentToActionText < ActiveRecord::Migration[6.0]
  include ActionView::Helpers::TextHelper
  def change
    rename_column :posts, :content, :content_old
    Post.all.each do |post|
      post.update_attribute(:content, simple_format(post.content_old))
    end
    remove_column :posts, :content_old
  end
end
</code>```

Refer to this Rails Issue comment.

Body:
Assuming there's a content in your model and that's what you want to migrate, first, add to your model:

has_rich_text :content

Then create a migration

rails g migration MigratePostContentToActionText

Result:

class MigratePostContentToActionText < ActiveRecord::Migration[6.0]
  include ActionView::Helpers::TextHelper
  def change
    rename_column :posts, :content, :content_old
    Post.all.each do |post|
      post.update_attribute(:content, simple_format(post.content_old))
    end
    remove_column :posts, :content_old
  end
end

Refer to this Rails Issue comment.


问:
Is it possible to read php code from other sites?
Just a curious question. I was wondering is it possible to read a sites php/server side codes? Is there any software/method that can be used to do so? Sometimes for educational purposes, i really want to see how people form the backend infrastructure of their sites. </p>

答: As long a website is not open source (which is not going to happen), NO, you cannot see the PHP code of any page. Except, as noted, the site is badly coded or ...</p>


问:
no valid “aps-environment” entitlement string found for application error when implementing FCM
When attempting to implement Firebase Cloud Messaging into my application, I am receiving the following error at runtime:

I am receiving an FCM token, so it appears to be establishing a connection with firebase. I have read many suggestions on what the problem could be, many seem to indicate that there is a problem with my provisioning profile not allowing push notifications. I have checked these settings under "Signing & Capabilities" and it appears that the profile allows for push notifications, and has the aps-environment value in the entitlements section:

Is there something else I'm missing?

Here is my development environment:

macOS 10.15 (Catalina)

Xcode 11.5

iPad Air 2 (test deployment device)

答:
I finally found the answer. Although my provisioning profile states that I have the aps-environment entitlement, and that I have Push Notification capability included, I STILL had to enable push notifications manually in the project. Additionally, the Background Modes (Remote notifications) capability needed to be added as well. These menus have changed in recent versions of xcode (for instance, the capabilities menu is now called signing and capabilities, and the add capability button is nestled up above all the settings).

In Xcode 11.5, follow these steps:

Click on your workspace name

Select your project in the target list

Select Signing & Capabilities

Click the +Capability button

Add Push Notifications and Background Modes (Remote notifications) from the list.


问:
Problem with highlight dates in datepicker
I'm trying to make dates highlighting using a known code, but I need a little help since the dates are not highlighted.

var highlightdate = ["2020-06-19", "2020-06-20", "2020-06-26", "2020-06-25", "2020-06-30"];
var date = new Date();
jQuery(document).ready(function() {
    $( "#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',
        beforeShowDay: function(date) {
            var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
            for (i = 0; i < highlightdate.length; i++) {
                if($.inArray(y + '-' + (m+1) + '-' + d,highlightdate) != -1) {

                    return [true, 'highlighdate', ''];
                }
            }
            return [true];

        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   .highlightdate {
       background-color: #ff0;
   }</code>```

   <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">

```

答:
You can do it like this: Add a 0 in case the value for month is smaller than 10 because you get for June 6 as value for m and not 06. Also adjust the typo "highlighdate" you have in  return [true, 'highlighdate', '']; to "highlightdate".

var highlightdate = ["2020-06-19", "2020-06-20", "2020-06-26", "2020-06-25", "2020-06-30"];
var date = new Date();
jQuery(document).ready(function() {
  $("#datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    beforeShowDay: function(date) {
      var m = date.getMonth(),
        d = date.getDate(),
        y = date.getFullYear();
      if (m < 10) {
        m = "0" + (m + 1);
      }
      else {
         m = m + 1
      }
      for (i = 0; i < highlightdate.length; i++) {
        if ($.inArray(y + '-' + m + '-' + d, highlightdate) != -1) {
          return [true, 'highlightdate', ''];
        }
      }
      return [true];

    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.highlightdate {
       background-color: #ff0;
   }</code>```

 <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"rel = "stylesheet">

```

Body:
I'm trying to make dates highlighting using a known code, but I need a little help since the dates are not highlighted.

var highlightdate = ["2020-06-19", "2020-06-20", "2020-06-26", "2020-06-25", "2020-06-30"];
var date = new Date();
jQuery(document).ready(function() {
    $( "#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',
        beforeShowDay: function(date) {
            var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
            for (i = 0; i < highlightdate.length; i++) {
                if($.inArray(y + '-' + (m+1) + '-' + d,highlightdate) != -1) {

                    return [true, 'highlighdate', ''];
                }
            }
            return [true];

        }
    });
});

   .highlightdate {
       background-color: #ff0;
   }

   <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">

Body:
You can do it like this: Add a 0 in case the value for month is smaller than 10 because you get for June 6 as value for m and not 06. Also adjust the typo "highlighdate" you have in  return [true, 'highlighdate', '']; to "highlightdate".

var highlightdate = ["2020-06-19", "2020-06-20", "2020-06-26", "2020-06-25", "2020-06-30"];
var date = new Date();
jQuery(document).ready(function() {
  $("#datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    beforeShowDay: function(date) {
      var m = date.getMonth(),
        d = date.getDate(),
        y = date.getFullYear();
      if (m < 10) {
        m = "0" + (m + 1);
      }
      else {
         m = m + 1
      }
      for (i = 0; i < highlightdate.length; i++) {
        if ($.inArray(y + '-' + m + '-' + d, highlightdate) != -1) {
          return [true, 'highlightdate', ''];
        }
      }
      return [true];

    }
  });
});

.highlightdate {
       background-color: #ff0;
   }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"rel = "stylesheet">
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<div id="datepicker"></div>


问:
Android Bottom Navigation Activity gives a Null Pointer Exception in onCreate
I added a Bottom Navigation Activity to my project but when i start the relevant activity it gives out a Null Pointer Exception.

It says that the exception is fired at line number 28

at lk.apiit.eea.mobile.Activities.CompanyProfile.onCreate(CompanyProfile.java:28)

Following is the Exception and the Code
PLease help me fix this.. Thank you

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{lk.apiit.eea.mobile/lk.apiit.eea.mobile.Activities.CompanyProfile}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2720)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:241)
    at android.app.ActivityThread.main(ActivityThread.java:6274)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
    at androidx.navigation.ui.ActionBarOnDestinationChangedListener.setTitle(ActionBarOnDestinationChangedListener.java:48)
    at androidx.navigation.ui.AbstractAppBarOnDestinationChangedListener.onDestinationChanged(AbstractAppBarOnDestinationChangedListener.java:100)
    at androidx.navigation.NavController.addOnDestinationChangedListener(NavController.java:218)
    at androidx.navigation.ui.NavigationUI.setupActionBarWithNavController(NavigationUI.java:220)
    at lk.apiit.eea.mobile.Activities.CompanyProfile.onCreate(CompanyProfile.java:28)
    at android.app.Activity.performCreate(Activity.java:6720)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2673)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:241)
    at android.app.ActivityThread.main(ActivityThread.java:6274)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

An this is the code in onCreateMethod

```<code> @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_company_profile);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);
}
</code>```

答:
Navigation graph is searching for the default app bar and in case if you don't have a default action bar in your code then please remove the line.</p>

```<code>NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
</code>```

Body:
I added a Bottom Navigation Activity to my project but when i start the relevant activity it gives out a Null Pointer Exception.

It says that the exception is fired at line number 28

at lk.apiit.eea.mobile.Activities.CompanyProfile.onCreate(CompanyProfile.java:28)

Following is the Exception and the Code
PLease help me fix this.. Thank you

java.lang.RuntimeException: Unable to start activity ComponentInfo{lk.apiit.eea.mobile/lk.apiit.eea.mobile.Activities.CompanyProfile}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2720)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:241)
    at android.app.ActivityThread.main(ActivityThread.java:6274)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
    at androidx.navigation.ui.ActionBarOnDestinationChangedListener.setTitle(ActionBarOnDestinationChangedListener.java:48)
    at androidx.navigation.ui.AbstractAppBarOnDestinationChangedListener.onDestinationChanged(AbstractAppBarOnDestinationChangedListener.java:100)
    at androidx.navigation.NavController.addOnDestinationChangedListener(NavController.java:218)
    at androidx.navigation.ui.NavigationUI.setupActionBarWithNavController(NavigationUI.java:220)
    at lk.apiit.eea.mobile.Activities.CompanyProfile.onCreate(CompanyProfile.java:28)
    at android.app.Activity.performCreate(Activity.java:6720)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2673)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:241)
    at android.app.ActivityThread.main(ActivityThread.java:6274)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

An this is the code in onCreateMethod

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_company_profile);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);
}

Body:
Navigation graph is searching for the default app bar and in case if you don't have a default action bar in your code then please remove the line.

NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);


问:
Convert date string (from gmail) to timestamp | Python
I want to save the received date of emails from a Gmail account into a time-series database.

The problem is that I cannot convert the string that I got from the email to timestamp.

I tried this:

```<code>from datetime import datetime

date1 = 'Thu, 28 May 2020 08:15:58 -0700 (PDT)'

date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')

print(date1_obj)
</code>```

But got this error:

```<code>Traceback (most recent call last):
  File "/format_date.py", line 11, in <module>
    date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 359, in _strptime
    (data_string, format))
ValueError: time data 'Thu, 28 May 2020 08:15:58 -0700 (PDT)' does not match format '%a, %d %b %Y %H:%M:%S %z %Z'
</code>```

Tried with or without parenthesis wrapping Timezone.
Read a lot, but nothing about how to deal with date strings containing "(PDT)" or any other timezones. It's very important to get the right date... If I run the same code without "(PDT)", got an incorrect time (because of my local time).

I know I can use string methods to manipulate it and convert to a right datetime, but I feel like this would be flexible.

Sorry for my terrible English.

Thank you!

答:
If it does not work even if you enclose %Z in brackets then the problem lies within the %Z directive
https://docs.python.org/3/library/time.html

Support for the %Z directive is based on the values contained in
  tzname and whether daylight is true. Because of this, it is
  platform-specific except for recognizing UTC and GMT which are always
  known (and are considered to be non-daylight savings timezones).

In example the following results in a ValueError for me (in Europe)

```<code>date1 = 'Thu, 28 May 2020 08:15:58 -0700 (PST)'
date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z (%Z)')
print(date1_obj)
</code>```

While with GMT it the output is 2020-05-28 08:15:58-07:00

```<code>date1 = 'Thu, 28 May 2020 08:15:58 -0700 (GMT)'
date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z (%Z)')
print(date1_obj)
</code>```

Based on your comment under this answer you could split the string if the Timezone bit is not important:

```<code>date1 = 'Thu, 28 May 2020 08:15:58 -0700 (GMT)'
date1_obj = datetime.strptime(date1.split(" (")[0], '%a, %d %b %Y %H:%M:%S %z')
</code>```

Body:
I want to save the received date of emails from a Gmail account into a time-series database.

The problem is that I cannot convert the string that I got from the email to timestamp.

I tried this:

from datetime import datetime

date1 = 'Thu, 28 May 2020 08:15:58 -0700 (PDT)'

date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')

print(date1_obj)

But got this error:

Traceback (most recent call last):
  File "/format_date.py", line 11, in <module>
    date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 359, in _strptime
    (data_string, format))
ValueError: time data 'Thu, 28 May 2020 08:15:58 -0700 (PDT)' does not match format '%a, %d %b %Y %H:%M:%S %z %Z'

Tried with or without parenthesis wrapping Timezone.
Read a lot, but nothing about how to deal with date strings containing "(PDT)" or any other timezones. It's very important to get the right date... If I run the same code without "(PDT)", got an incorrect time (because of my local time).

I know I can use string methods to manipulate it and convert to a right datetime, but I feel like this would be flexible.

Sorry for my terrible English.

Thank you!

Body:
If it does not work even if you enclose %Z in brackets then the problem lies within the %Z directive
https://docs.python.org/3/library/time.html

Support for the %Z directive is based on the values contained in
  tzname and whether daylight is true. Because of this, it is
  platform-specific except for recognizing UTC and GMT which are always
  known (and are considered to be non-daylight savings timezones).

In example the following results in a ValueError for me (in Europe)

date1 = 'Thu, 28 May 2020 08:15:58 -0700 (PST)'
date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z (%Z)')
print(date1_obj)

While with GMT it the output is 2020-05-28 08:15:58-07:00

date1 = 'Thu, 28 May 2020 08:15:58 -0700 (GMT)'
date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z (%Z)')
print(date1_obj)

Based on your comment under this answer you could split the string if the Timezone bit is not important:

date1 = 'Thu, 28 May 2020 08:15:58 -0700 (GMT)'
date1_obj = datetime.strptime(date1.split(" (")[0], '%a, %d %b %Y %H:%M:%S %z')


问:
Adding two 1D arrays is giving me a 2D array (python)
I'm having an issue where I'm adding two 4x1 arrays and the result is a 4x4 array where the first column is repeated 4 times. The result I need is a 4x1 array.

I've initialized an array as such (m = 4): z = np.zeros((m, len(t))

Later in my code I pass this array into a function as z[:,k+1] so the dimensionality becomes a 4x1 array. (Note that when I print this array to my terminal is shows up as a row vector and not a column vector: [0. 0. 0. 0.], I'm not sure why this is either). The array that I'm trying to add to z has the following structure when printed to my terminal:

[[#]
  [#]
  [#]
  [#]]

Clearly the addition is pulling the above array into each element of z instead of adding their respective components together, but I'm not sure why as they should both be column vectors. I'd appreciate any help with this.

EDIT: I have a lot of code so I've included a condensed version that hopefully gets the idea accross.

n = 4   # Defines number of states
m = 4   # Defines number of measurements
x = np.zeros((n, len(t)), dtype=np.float64) # Initializes states
z = np.zeros((m, len(t)), dtype=np.float64) # Initializes measurements
u = np.zeros((1, len(t)), dtype=np.float64) # Initializes input
...
C = np.eye(m) # Defines measurement matrix
...
for k in range(len(t)-1):
  ...
  x_ukf[:,k+1], P_ukf[k+1,:,:] = function_call(x_ukf[:,k], z[:,k+1], u[:,k], P_ukf[k,:,:], C, Q, R, T) # Calls UKF function
```

<p>This then leads to the function where the following occurrs (note that <code>measurement_matrix = C</code> (4x4 matrix), <code>X</code> is a 4x9 matrix, and <code>W</code> a 1x9 row vector):</p>

<pre class="lang-py prettyprint-override"><code>Z = measurement_matrix @ X  # Calculates measurements based on sigma points
zhat = Z @ W.T
...
state_vec = state_vec + K @ (measurement_vec - zhat) # Updates state estimates
</code>```

The issue I'm having is with the expression (measurement_vec - zhat). This is where the result should be a 4x1 vector but I'm getting a 4x4 matric.

Body:
I'm having an issue where I'm adding two 4x1 arrays and the result is a 4x4 array where the first column is repeated 4 times. The result I need is a 4x1 array.

I've initialized an array as such (m = 4): z = np.zeros((m, len(t))

Later in my code I pass this array into a function as z[:,k+1] so the dimensionality becomes a 4x1 array. (Note that when I print this array to my terminal is shows up as a row vector and not a column vector: [0. 0. 0. 0.], I'm not sure why this is either). The array that I'm trying to add to z has the following structure when printed to my terminal:

[[#]
  [#]
  [#]
  [#]]

Clearly the addition is pulling the above array into each element of z instead of adding their respective components together, but I'm not sure why as they should both be column vectors. I'd appreciate any help with this.

EDIT: I have a lot of code so I've included a condensed version that hopefully gets the idea accross.

n = 4   # Defines number of states
m = 4   # Defines number of measurements
x = np.zeros((n, len(t)), dtype=np.float64) # Initializes states
z = np.zeros((m, len(t)), dtype=np.float64) # Initializes measurements
u = np.zeros((1, len(t)), dtype=np.float64) # Initializes input
...
C = np.eye(m) # Defines measurement matrix
...
for k in range(len(t)-1):
  ...
  x_ukf[:,k+1], P_ukf[k+1,:,:] = function_call(x_ukf[:,k], z[:,k+1], u[:,k], P_ukf[k,:,:], C, Q, R, T) # Calls UKF function

This then leads to the function where the following occurrs (note that measurement_matrix = C (4x4 matrix), X is a 4x9 matrix, and W a 1x9 row vector):

Z = measurement_matrix @ X  # Calculates measurements based on sigma points
zhat = Z @ W.T
...
state_vec = state_vec + K @ (measurement_vec - zhat) # Updates state estimates

The issue I'm having is with the expression (measurement_vec - zhat). This is where the result should be a 4x1 vector but I'm getting a 4x4 matric.

Body:
This is sometimes called broadcasting:

a, b = np.arange(4), np.arange(8,12)

c = a + b[:,None]

Output:

array([[ 8,  9, 10, 11],
       [ 9, 10, 11, 12],
       [10, 11, 12, 13],
       [11, 12, 13, 14]])


问:
Google Maps API 3 overlay, need to get the projection
I'm trying to do an overlay on Google Maps. I have generated tiles of my image using maptiler, but the example generated by maptiler is in v2 and i want to use v3. The example generated by maptiler is also very complex and does some unnecessary opacity stuff. Now v3 of GM has changed a lot since v2 and i have some problems to generate the LatLng of a certain point on the screen. getProjection() keeps being undefined, whatever i do, any idea how to get the projection?

```<code><script>
  var mapBounds = new google.maps.LatLngBounds();
  var mapMinZoom = 8;
  var mapMaxZoom = 14;
  var overlay;

  var maptiler = new google.maps.ImageMapType({
    getTileUrl: function(coord, zoom) {
          if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
        return "none.png";
      }
      var ymax = 1 << zoom;
      var y = ymax - coord.y -1;
      var tileBounds = new google.maps.LatLngBounds(
        overlay.getProjection().fromDivPixelToLatLng( new google.maps.Point( (coord.x)*256, (coord.y+1)*256 ) , zoom ),
        overlay.getProjection().fromDivPixelToLatLng( new google.maps.Point( (coord.x+1)*256, (coord.y)*256 ) , zoom )
      );
      if (mapBounds.intersects(tileBounds)) {
        return "" + zoom + "/" + coord.x + "/" + (Math.pow(2,zoom)-coord.y-1) + ".png";
      } else {
       return "none.png";
      }
   },
   tileSize: new google.maps.Size(256, 256),
   isPng: true
  });

  var map;
  function initialize() {
    map = new google.maps.Map(document.getElementById("map_canvas"));
    map.setZoom(11);
    map.setMapTypeId('satellite');
    mapBounds.extend(new google.maps.LatLng(50.9388615939, 3.80480816501));
    mapBounds.extend(new google.maps.LatLng(51.4402541425, 4.73612507791));
    map.fitBounds(mapBounds);

    overlay = new google.maps.OverlayView();
    overlay.draw = function() {};
    overlay.setMap(map);

    map.overlayMapTypes.insertAt(0, maptiler);
  }
</script>
</code>```

the overlay part is a hack i found on the internet which supposed to get you to the projection. unfortunately it didn't work. Any idea's how to fix this? in V2 you could do something like this:

```<code>var mercator = new GMercatorProjection()
mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom )
</code>```

But this isn't possible anymore in v3.

Anyone that can help?

The example generated by maptiler can be found here:

http://gmapsexample.staging1.kunstmaan.be/googlemapsv2.html

This is a simple example in v3 which works:

http://gmapsexample.staging1.kunstmaan.be/googlemapsv3_simple.html

but i want everything except the map to be a specific color, so this is the example i'm trying to get working:

http://gmapsexample.staging1.kunstmaan.be/googlemapsv3.html

thanks,

Daan

答:
You do not need to worry about getting or setting the projection if you are using MapTiler

These two YouTube videos will walk you through (among other things) using MapTiler with Google Maps API v3 map styled to be a certain color which is (if I understand correctly) exactly what you're asking about:

http://www.youtube.com/watch?v=CeSFUSZLeao

http://www.youtube.com/watch?v=WqSOLca2xOc

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to do an overlay on Google Maps. I have generated tiles of my image using maptiler, but the example generated by maptiler is in v2 and i want to use v3. The example generated by maptiler is also very complex and does some unnecessary opacity stuff. Now v3 of GM has changed a lot since v2 and i have some problems to generate the LatLng of a certain point on the screen. getProjection() keeps being undefined, whatever i do, any idea how to get the projection?

the overlay part is a hack i found on the internet which supposed to get you to the projection. unfortunately it didn't work. Any idea's how to fix this? in V2 you could do something like this:

var mercator = new GMercatorProjection()
mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom )

But this isn't possible anymore in v3.

Anyone that can help?

The example generated by maptiler can be found here:

http://gmapsexample.staging1.kunstmaan.be/googlemapsv2.html

This is a simple example in v3 which works:

http://gmapsexample.staging1.kunstmaan.be/googlemapsv3_simple.html

but i want everything except the map to be a specific color, so this is the example i'm trying to get working:

http://gmapsexample.staging1.kunstmaan.be/googlemapsv3.html

thanks,

Daan


问:
How can I open calendar .ics files in ios?
I am trying to download and open .ics file in my app.

I found few question, and here's some code I am using

```<code>// NSString *path = [[NSBundle mainBundle] pathForResource:@"http://www.nmsd.wednet.edu//site/handlers/icalfeed.ashx?MIID=607" ofType:@"ics"];
NSURL *url = [NSURL fileURLWithPath:@"http://www.nmsd.wednet.edu//site/handlers/icalfeed.ashx?MIID=607"];
UIDocumentInteractionController *dc = [UIDocumentInteractionController interactionControllerWithURL:url];
dc.delegate = self;
[dc presentPreviewAnimated:YES];
</code>```

Nothing at all happens. no errors at all. Would it be easier to look for a library to achieve this.

答: You use NSURL fileURLWithPath with an URL string as parameter although it expects file path. Change it to NSURL URLWithString.

Body:
I am trying to download and open .ics file in my app.

I found few question, and here's some code I am using

// NSString *path = [[NSBundle mainBundle] pathForResource:@"http://www.nmsd.wednet.edu//site/handlers/icalfeed.ashx?MIID=607" ofType:@"ics"];
NSURL *url = [NSURL fileURLWithPath:@"http://www.nmsd.wednet.edu//site/handlers/icalfeed.ashx?MIID=607"];
UIDocumentInteractionController *dc = [UIDocumentInteractionController interactionControllerWithURL:url];
dc.delegate = self;
[dc presentPreviewAnimated:YES];

Nothing at all happens. no errors at all. Would it be easier to look for a library to achieve this.


问:
How can I define a 5x3 array of strings in python?
How can I define a 5x3 array of strings in python?

I want to save the following data in an array of strings:

```<code>Name    Surname Grade
Steve   Black   10
Jane    Red     10
Peter   Green   0
Kelly   Pink    7
</code>```

I am coming from C/C++ and in this programming language it would look like this:

```<code>matrix[5][3];

matrix[0][0] = "Name";
matrix[0][1] = "Surname";
matrix[0][2] = "Grade";

matrix[1][0] = "Steve";
matrix[1][1] = "Black";
matrix[1][2] = "10";

...
...
...

matrix[4][0] = "Kelly";
matrix[4][1] = "Pink";
matrix[4][2] = "7";
</code>```

Is there a way in python to create such table?

In case you know what kind of data type that is in python and how it work, please let me know.

答:
You could just create a 2-d list in python and loop through it filling the required values in following manner -</p>

```<code>lst = []        #currently a 1-d list but you can insert lists into it and make it a 2-d list.
#just for demo...you can loop instead to fill all the values
new_row = []
new_row.append("Steve")
new_row.append("Black")
new_row.append(10)
lst.append(new_row)
print(lst)     #this would print a 2-d list - [["Steve","Black",10]]
</code>```

Body:
How can I define a 5x3 array of strings in python?

I want to save the following data in an array of strings:

Name    Surname Grade
Steve   Black   10
Jane    Red     10
Peter   Green   0
Kelly   Pink    7

I am coming from C/C++ and in this programming language it would look like this:

matrix[5][3];

matrix[0][0] = "Name";
matrix[0][1] = "Surname";
matrix[0][2] = "Grade";

matrix[1][0] = "Steve";
matrix[1][1] = "Black";
matrix[1][2] = "10";

...
...
...

matrix[4][0] = "Kelly";
matrix[4][1] = "Pink";
matrix[4][2] = "7";

Is there a way in python to create such table?

In case you know what kind of data type that is in python and how it work, please let me know.

Body:
You could just create a 2-d list in python and loop through it filling the required values in following manner -

lst = []        #currently a 1-d list but you can insert lists into it and make it a 2-d list.
#just for demo...you can loop instead to fill all the values
new_row = []
new_row.append("Steve")
new_row.append("Black")
new_row.append(10)
lst.append(new_row)
print(lst)     #this would print a 2-d list - [["Steve","Black",10]]


问:
Why do we use a custom type instead string?
I am reading a book about typescript. In one chapter I have found example of code:

```<code>type OptionsType = {
    db: string;
};

export const connect = ({ db }: OptionsType): void => {
  mongoose.connect(db);
};
</code>```

And using is:

```<code>const db = "mongodb://";
connect({ db });
</code>```

Why did we wrap db string connection to the custom type OptionsType? Why dont use string db, because mongoose.connect(db); accepts this.

答:
Function connect is defined by the book author. He decided it should take a single parameter that is an object with a property named db.

He implemented that function so that it takes the value out of the property named db of function argument and uses it to call mongoose.connect which requires its first parameter to be connection string.

There was no particular reason why the author decided to define his function like that. Maybe he wanted to illustrate how you can pass values into the function as properties of an object?

Since he's passing just a single value there was really no reason to wrap in in an object.

Body:
I am reading a book about typescript. In one chapter I have found example of code:

type OptionsType = {
    db: string;
};

export const connect = ({ db }: OptionsType): void => {
  mongoose.connect(db);
};

And using is:

const db = "mongodb://";
connect({ db });

Why did we wrap db string connection to the custom type OptionsType? Why dont use string db, because mongoose.connect(db); accepts this.


问:
how to show in the view a object and the attribute of another table
Well, I am using laravel, I have two tables, one for users and the other for roles, and I am showing in a view a table with each user with their attributes and also the role they have associated. the problem is that the attribute is the id, and what is shown is the id of the role table, how can I show the role name instead of the id?

This is the function where I get the list of users:

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

    $users = User::latest()->get();
    return view('users.index', [
        'users'=>$users,
    ]);
}
</code>```

and this is the view where I build a table to show the attributes, and in the role_id attribute, I only have the number associated with the role table. when I really need to show the name.

```<code>            @foreach($users as $user)
                <tr>
                    <td>{{$user->name}}</td>
                    <td>{{$user->last_name}}</td>
                    <td>{{$user->age}}</td>
                    <td>{{$user->DOB}}</td>
                    <td>{{$user->height}}</td>
                    <td>{{$user->role_id}}</td>
                    <td><a href="{{$user->path_edit()}}">Edit</a> <a href="/users/{{$user->id}}/destroy" > - Delete </a></td>

                </tr>
            @endforeach
</code>```

This is the database :

答:
Make a relation to your user with role table. Write the below code in your user model

```<code>    public function role()
    {
        return $this->belongsTo(Role::class);
    }
</code>```

Use it in your view file

```<code><td>{{$user->role->name}}</td>
</code>```

Body:
Well, I am using laravel, I have two tables, one for users and the other for roles, and I am showing in a view a table with each user with their attributes and also the role they have associated. the problem is that the attribute is the id, and what is shown is the id of the role table, how can I show the role name instead of the id?

This is the function where I get the list of users:

public function index()
{

    $users = User::latest()->get();
    return view('users.index', [
        'users'=>$users,
    ]);
}

and this is the view where I build a table to show the attributes, and in the role_id attribute, I only have the number associated with the role table. when I really need to show the name.

            @foreach($users as $user)

                    {{$user->name}}
                    {{$user->last_name}}
                    {{$user->age}}
                    {{$user->DOB}}
                    {{$user->height}}
                    {{$user->role_id}}
                    path_edit()}}">Edit id}}/destroy" > - Delete

            @endforeach

This is the database :

Body:
Make a relation to your user with role table. Write the below code in your user model

    public function role()
    {
        return $this->belongsTo(Role::class);
    }

Use it in your view file

<td>{{$user->role->name}}</td>