问:
Is there a simple way to change a column of yes/no to 1/0 in a Pandas dataframe?
I read a csv file into a pandas dataframe, and would like to convert the columns with binary answers from strings of yes/no to integers of 1/0. Below, I show one of such columns ("sampleDF" is the pandas dataframe).

```<code>In [13]: sampleDF.housing[0:10]
Out[13]:
0     no
1     no
2    yes
3     no
4     no
5     no
6     no
7     no
8    yes
9    yes
Name: housing, dtype: object
</code>```

Help is much appreciated!

答:
A simple and intuitive way to convert the whole dataframe to 0's and 1's might be:</p>

```<code>sampleDF = sampleDF.replace(to_replace = "yes", value = 1)
sampleDF = sampleDF.replace(to_replace = "no", value = 0)
</code>```

Body:
I read a csv file into a pandas dataframe, and would like to convert the columns with binary answers from strings of yes/no to integers of 1/0. Below, I show one of such columns ("sampleDF" is the pandas dataframe).

In [13]: sampleDF.housing[0:10]
Out[13]:
0     no
1     no
2    yes
3     no
4     no
5     no
6     no
7     no
8    yes
9    yes
Name: housing, dtype: object

Help is much appreciated!

Body:
A simple and intuitive way to convert the whole dataframe to 0's and 1's might be:

sampleDF = sampleDF.replace(to_replace = "yes", value = 1)
sampleDF = sampleDF.replace(to_replace = "no", value = 0)


来源: stackexchange

问:
How to pad images to a specific size like 720*576 with a pixel value/border value?
I have images of various sizes like 122*98, 98*65, 320*256, 620*540. How to make all images to a fixed size say 720*576 by padding them with border/some pixel value? Is there a generic way to do it which works for input images of any size? I tried some methods using PIL module, but didn't get a generic solution.</p>

答: You're looking for the cv2.remap() function. This function has a parameter that let's you define a constant border value. The Opencv tutorial at https://docs.opencv.org/3.4/d1/da0/tutorial_remap.html should give you enough info to start. The if-block ind == 0: in the tutorial resizes the image by 50%. You should be able to use this to get the fixed size of 720x576.

ContentLicense: CC BY-SA 4.0


问:
Link to id but navbar in the way
I have a navbar with links to a article with id="about", but my navbar is fixed-top, so when I click on the link, my navbar is in front of the title of the section.

I solved this problem by using this:

```<code>.main-content article .anchor{
    position: absolute;
    top: -106px;
}
</code>```

But for scrollspy I need the href of the link to be the same as the id of the section where I want to "scrollspy" but I can't use the same id twice.

How can I solve this? Is there a way to go to add -100px to your href or something like that?

答:
You can add a 'false' anchor like this above your about content:

```<code><div style="margin-top: -95px; position: absolute;" id="about"></div>
</code>```

This will add a margin to your section above and after some adjustment you can change the px value to suit your situation.

Title: Link to id but navbar in the way

Body:
I have a navbar with links to a article with id="about", but my navbar is fixed-top, so when I click on the link, my navbar is in front of the title of the section.

I solved this problem by using this:

.main-content article .anchor{
    position: absolute;
    top: -106px;
}

But for scrollspy I need the href of the link to be the same as the id of the section where I want to "scrollspy" but I can't use the same id twice.

How can I solve this? Is there a way to go to add -100px to your href or something like that?

Body:
You can add a 'false' anchor like this above your about content:

<div style="margin-top: -95px; position: absolute;" id="about"></div>

This will add a margin to your section above and after some adjustment you can change the px value to suit your situation.


问:
Deleted Git tags restore themselves
We recently ran into an issue with tags in our Git repository.

We deleted our tags locally and remotely, yet they kept restoring itself every time we either push to or fetch from remote.

We are currently working in a team of three and when we think we actually got rid of the tags, someone would do a push and we all get them again.

We all tried:

```<code>git tag -d 12345
git push origin :refs/tags/12345
</code>```

Anyone else ran into this issue?

答:
A handy way to solve this problem for all tags at once :

1) To be done ONCE, from any one of the local repos

```<code>git push <remoteName> :<tagToDelete>
# (for example) git push origin :tag_foo_bar
</code>```

2) Then, to be done from EACH local repo involved

```<code>git tag -d `git tag -d` && git fetch -t
</code>```

This will list then delete all local copies of the repo's tags, then get them back anew from the remote.

ContentLicense: CC BY-SA 3.0

Title: Deleted Git tags restore themselves

Body:
We recently ran into an issue with tags in our Git repository.

We deleted our tags locally and remotely, yet they kept restoring itself every time we either push to or fetch from remote.

We are currently working in a team of three and when we think we actually got rid of the tags, someone would do a push and we all get them again.

We all tried:

git tag -d 12345
git push origin :refs/tags/12345

Anyone else ran into this issue?

Body:
A handy way to solve this problem for all tags at once :

1) To be done ONCE, from any one of the local repos

git push <remoteName> :<tagToDelete>
# (for example) git push origin :tag_foo_bar

2) Then, to be done from EACH local repo involved

git tag -d `git tag -d` && git fetch -t

This will list then delete all local copies of the repo's tags, then get them back anew from the remote.


问:
How to add data in list below previous one?
I want to add data in list. When I click the button, it takes data from different classes and adds it as a row in the list and comes back.

And again, when I insert data in form and press the button, it adds it below the previous one on another row. So an array is created of rows, and now when I click on any position of list item row, I get its content. So how to implement it?

答:
Your question is not very clear. But from what I understand, you what to use a ListView or a ListActivity.
In either case, you will need an adapter which manages the data displayed in the list. I would suggest that your "different class" which provides the data should subclass BaseAdapter.

You can then bind the class providing the data to the view using setAdapter(ListAdapter)

When your data changes, all you need to do is call notifyDataSetChanged() on your data class which provides the data and the view will be updated.

To get the clicked item, you will need to create and set an OnItemClickListener on your ListView
See this list activity example for guidance.


问:
cyclomatic complexity on spring controller method: **Best Practice**
I have a spring-boot controller that gets data from service and return thymeleaf html page. Everything works fine.

The problem here is i have to create bunch of list and map that will be used by thymeleaf and controller method is getting bigger.

```<code>   @Controller
    public class MyController {

        @Autowired
        MyService myService;

        @RequestMapping("/my-page")
        public String getMypage(Model model) {

            //get data from service

            //i have alot of code to extract data and prepare different list to be used by thymeleaf

        }
}
</code>```

Now my question is about best practice.

Is it good idea to create method inside controller so code would be more readable something like below

```<code>@Controller
public class MyController {

    @Autowired
    MyService myService;

    @RequestMapping("/my-page")
    public String getMypage(Model model) {

        //get data from service

        myMethod1();
        //some code here
        //myMethod2();
        // code here

    }

    private void myMethod1(){

        //myMethod 1 code here
    }

    private void myMethod2(){

        //method 2 code here
    }
}
</code>```

答:
Yes that's for sure a good idea.

Do you know the book Clean Code from Robert C. Martin:

https://www.amazon.de/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

Body:
I have a spring-boot controller that gets data from service and return thymeleaf html page. Everything works fine.

The problem here is i have to create bunch of list and map that will be used by thymeleaf and controller method is getting bigger.

   @Controller
    public class MyController {

        @Autowired
        MyService myService;

        @RequestMapping("/my-page")
        public String getMypage(Model model) {

            //get data from service

            //i have alot of code to extract data and prepare different list to be used by thymeleaf

        }
}

Now my question is about best practice.

Is it good idea to create method inside controller so code would be more readable something like below

@Controller
public class MyController {

    @Autowired
    MyService myService;

    @RequestMapping("/my-page")
    public String getMypage(Model model) {

        //get data from service

        myMethod1();
        //some code here
        //myMethod2();
        // code here

    }

    private void myMethod1(){

        //myMethod 1 code here
    }

    private void myMethod2(){

        //method 2 code here
    }
}


问:
Flutter Marking locations (Latitude, Longitude) on Flutter Map from Sqflite Database
I have list of latitude and longitude which I am storing them in database.I want those latitude and longitude to be represented in flutter map with markers.

My code for saving latitude and longitude using sqlite

homeScreen.dart

```<code>class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => new _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
  List<Note> items = new List();
  DatabaseHelper db = new DatabaseHelper();

  LatLng _center ;
  Position currentLocation;

  MapController _mapctl = MapController();

  Future<Position> locateUser() async {
    try{
      return await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    }on PlatformException catch(e){
      currentLocation = null;
    }
    return currentLocation;
  }

  getUserLocation() async {
    currentLocation = await locateUser();
    setState(() {
      _center = LatLng(currentLocation.latitude, currentLocation.longitude);
    });
    print('center $_center');
  }
  @override
  void initState() {
    super.initState();
    getUserLocation();
     db.getAllNotes().then((notes) {
      setState(() {
        notes.forEach((note) {
          items.add(Note.fromMap(note));
        });
      });
    });
  }

  @override
  Widget build(BuildContext context){
    var markers = <Marker>[
      Marker(
        width: 80.0,
        height: 80.0,
        point: LatLng(12.9716, 77.5946),
        builder: (ctx) => Container(
              child: Icon(Icons.location_on,color: Colors.green[700],size: 30,),
            ),
      ),
      Marker(
        width: 80.0,
        height: 80.0,
        point: LatLng(12.9716, 77.5946),
        builder: (ctx) => Container(
              child: Icon(Icons.location_on)
            ),
      ),
    ];
    return Scaffold(
      appBar: AppBar(
        title: Text('Plants Watch'),
        backgroundColor: Colors.green[700],
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.person),
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (context)=>UserProfile()));
            },
          ),
          IconButton(
            icon: Icon(Icons.exit_to_app),
            onPressed: () {
              BlocProvider.of<AuthenticationBloc>(context).dispatch(
                LoggedOut(),
              );
            },
          )
        ],
      ),
      body: Stack(
        children: <Widget>[
          new FlutterMap(
            mapController: _mapctl,
                options: new MapOptions(
                  center: new LatLng(12.9716, 77.5946),
                  maxZoom: 20.0,
                ),
                layers: [
                  new TileLayerOptions(
                    urlTemplate: "https://api.tiles.mapbox.com/v4/"
                    "{id}/{z}/{x}/{y}@2x.png?access_token={accessToken}",
                    additionalOptions: {
                      'accessToken': 'accessToken',
                      'id': 'mapbox.streets',
                      },
                    ),
                  MarkerLayerOptions(markers: markers)
                  ],
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Align(
                alignment: Alignment.bottomRight,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    FloatingActionButton(
                      backgroundColor: Colors.green[700],
                      child: Icon(Icons.my_location),
                      onPressed: () {
                        _mapctl.move(_center,16.0);
                        },
                    ),
                    SizedBox(height: 16.0),
                    FloatingActionButton(
                      backgroundColor: Colors.green[700],
                      child: Icon(Icons.add),
                      heroTag: null,
                      onPressed: () {
                        Navigator.push(context,
                        MaterialPageRoute(builder: (context) => NoteScreen(Note('', '', ''))));
                      },
                    ),
                  ],
            )
           ),
        ),
      ],
    )
  );
 }
}
</code>```

Listview.dart

```<code>
class ListViewNote extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new ListViewNoteState();
}

class ListViewNoteState extends State<ListViewNote> {
  List<Note> items = new List();
  DatabaseHelper db = new DatabaseHelper();

  @override
  void initState() {
    super.initState();
    db.getAllNotes().then((notes) {
      setState(() {
        notes.forEach((note) {
          items.add(Note.fromMap(note));
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
        title: Text('Plant List',
        ),
        centerTitle: true,
        actions: <Widget>[
          IconButton(icon: Icon(Icons.search,
            color: Colors.white,), onPressed: (){
            showSearch(context: context,
            delegate: DataSearch(this.items));
          })
        ],
      ),
      body: Center(
        child: ListView.builder(
          itemCount: items.length,
          padding: const EdgeInsets.all(15.0),
          itemBuilder: (context, position) {
            return Dismissible(
              background: stackBehindDismiss(),
              key: ObjectKey(items[position]),
              child: Card(
                elevation: 2.0,
                margin: new EdgeInsets.symmetric(horizontal: 0.0,vertical: 2.0),
                child: Column(
                  children: <Widget>[
                    ListTile(
                      title: Text(
                        '${items[position].title}',
                        style: TextStyle(
                          fontSize: 22.0,
                          color: Colors.deepOrangeAccent,
                          ),
                        ),
                        subtitle: Text(
                          '${items[position].description}' + '' + '${items[position].location}',
                          style: new TextStyle(
                            fontSize: 18.0,
                            fontStyle: FontStyle.italic,
                            ),
                          ),
                          onTap: () => _navigateToNote(context, items[position]),
                      ),
                    ],
                  ),
                ),
                onDismissed: (dirction){
                  var item   = items.elementAt(position);
                  _deleteNote(context, items[position], position);
                  Scaffold.of(context).showSnackBar(SnackBar(
                    content: Text("Item deleted"),
                    ));
                  },
              );
            }
         ),
         ),
         floatingActionButton: FloatingActionButton(
           backgroundColor: Colors.green[700],
           child: Icon(Icons.add),
           onPressed: () => _createNewNote(context),
          ),
      );
    }
    void _deleteNote(BuildContext context, Note note, int position) async {
      db.deleteNote(note.id).then((notes) {
       setState(() {
         items.removeAt(position);
         });
        });
      }
    void _navigateToNote(BuildContext context, Note note) async {
      String result = await Navigator.push(
        context,MaterialPageRoute(builder: (context) => NoteScreen(note)),
        );
        if (result == 'update') {
          db.getAllNotes().then((notes) {
            setState(() {
              items.clear();
              notes.forEach((note) {
                items.add(Note.fromMap(note));
                });
              });
            });
          }
        }
    void _createNewNote(BuildContext context) async {
      String result = await Navigator.push(
        context,MaterialPageRoute(builder: (context) => NoteScreen(Note('', '', ''))),
        );
        if (result == 'save') {
          db.getAllNotes().then((notes) {
            setState(() {
              items.clear();
              notes.forEach((note) {
                items.add(Note.fromMap(note));
                });
              });
            });
          }
        }
     stackBehindDismiss() {
       return Container(
         alignment: Alignment.centerRight,
         padding: EdgeInsets.only(right: 20.0),
         color: Colors.green[700],
         child: Icon(
           Icons.delete,
           color: Colors.white,
          ),
        );
       }
 }

class DataSearch extends SearchDelegate<Note> {
  DatabaseHelper db = new DatabaseHelper();
  List<Note> items = new List();
  final List<Note> suggestion = new List();
  // ListViewNoteState i = ListViewNoteState();

   DataSearch(this.items);

  @override
  ThemeData appBarTheme(BuildContext context) {
    assert(context != null);
    final ThemeData theme = Theme.of(context);
    assert(theme != null);
    return theme;
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(icon: Icon(Icons.clear), onPressed: () {
        query = '';

      } )
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: AnimatedIcon(
        icon: AnimatedIcons.menu_arrow,
        progress: transitionAnimation,
      ),
      onPressed: (){
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return Text(query);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestion = query.isEmpty
    ? items
    : items.where((target) => target.title.startsWith(query)).toList();
    if(items.isEmpty)
    {
      print("Null");
    }
     // return Text('$suggestion');
    return ListView.builder(
      itemCount: suggestion.length,
      itemBuilder: (context, position){
        return new  ListTile(
            title: RichText(
              text: TextSpan(
                text: suggestion[position].title.substring(0,query.length),
                style: TextStyle(
                  color: Colors.black,fontWeight: FontWeight.bold),
                  children: [
                    TextSpan(
                      text: suggestion[position].title.substring(query.length),
                      style: TextStyle(color: Colors.black54)
                    )
                  ]
              ),
            )
          );
      }
    );
  }
}
</code>```

Below is my databse classes where i am creating dbHelper and class note for creating table

dbHelper.dart

```<code>

class DatabaseHelper {
  static final DatabaseHelper _instance = new DatabaseHelper.internal();

  factory DatabaseHelper() => _instance;

  final String tableNote = 'noteTable';
  final String columnId = 'id';
  final String columnLocation = 'location';
  final String columnTitle = 'title';
  final String columnDescription = 'description';

  static Database _db;

  DatabaseHelper.internal();

  Future<Database> get db async {
    if (_db != null) {
      return _db;
    }
    _db = await initDb();

    return _db;
  }

  initDb() async {
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'notes.db');

//    await deleteDatabase(path); // just for testing

    var db = await openDatabase(path, version: 1, onCreate: _onCreate);
    return db;
  }

  void _onCreate(Database db, int newVersion) async {
    await db.execute(
        'CREATE TABLE $tableNote($columnId INTEGER PRIMARY KEY,$columnLocation TEXT, $columnTitle TEXT, $columnDescription TEXT)');
  }

  Future<int> saveNote(Note note) async {
    var dbClient = await db;
    var result = await dbClient.insert(tableNote, note.toMap());
//    var result = await dbClient.rawInsert(
//        'INSERT INTO $tableNote ($columnTitle, $columnDescription) VALUES (\'${note.title}\', \'${note.description}\')');

    return result;
  }

  Future<List> getAllNotes() async {
    var dbClient = await db;
    var result = await dbClient.query(tableNote, columns: [columnId, columnLocation , columnTitle, columnDescription]);
//    var result = await dbClient.rawQuery('SELECT * FROM $tableNote');

    return result.toList();
  }

  Future<int> getCount() async {
    var dbClient = await db;
    return Sqflite.firstIntValue(await dbClient.rawQuery('SELECT COUNT(*) FROM $tableNote'));
  }

  Future<Note> getNote(int id) async {
    var dbClient = await db;
    List<Map> result = await dbClient.query(tableNote,
        columns: [columnId, columnLocation , columnTitle, columnDescription],
        where: '$columnId = ?',
        whereArgs: [id]);
//    var result = await dbClient.rawQuery('SELECT * FROM $tableNote WHERE $columnId = $id');

    if (result.length > 0) {
      return new Note.fromMap(result.first);
    }

    return null;
  }

  Future<int> deleteNote(int id) async {
    var dbClient = await db;
    return await dbClient.delete(tableNote, where: '$columnId = ?', whereArgs: [id]);
//    return await dbClient.rawDelete('DELETE FROM $tableNote WHERE $columnId = $id');
  }

  Future<int> updateNote(Note note) async {
    var dbClient = await db;
    return await dbClient.update(tableNote, note.toMap(), where: "$columnId = ?", whereArgs: [note.id]);
//    return await dbClient.rawUpdate(
//        'UPDATE $tableNote SET $columnTitle = \'${note.title}\', $columnDescription = \'${note.description}\' WHERE $columnId = ${note.id}');
  }

  Future close() async {
    var dbClient = await db;
    return dbClient.close();
  }
}
</code>```

classNote.dart

```<code>class Note {
  int _id;
  String _location;
  String _title;
  String _description;

  Note(this._location,this._title, this._description);

  Note.map(dynamic obj) {
    this._id = obj['id'];
    this._location = obj['location'];
    this._title = obj['title'];
    this._description = obj['description'];
  }

  int get id => _id;
  String get location => _location;
  String get title => _title;
  String get description => _description;

  Map<String, dynamic> toMap() {
    var map = new Map<String, dynamic>();
    if (_id != null) {
      map['id'] = _id;
    }
    map['location'] = _location;
    map['title'] = _title;
    map['description'] = _description;

    return map;
  }

  Note.fromMap(Map<String, dynamic> map) {
    this._id = map['id'];
    this._location = map ['location'];
    this._title = map['title'];
    this._description = map['description'];
  }
}
</code>```

AddItem.dart

```<code>import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:latlong/latlong.dart';
import 'dbhelper.dart';
import 'package:geolocator/geolocator.dart';

class NoteScreen extends StatefulWidget {
  final Note note;
  NoteScreen(this.note);

  @override
  State<StatefulWidget> createState() => new _NoteScreenState();
}

class _NoteScreenState extends State<NoteScreen> {
  DatabaseHelper db = new DatabaseHelper();

  TextEditingController _titleController;
  TextEditingController _descriptionController;
  TextEditingController _locationController;

  @override
  void initState() {
    super.initState();
    getUserLocation();
    _titleController = new TextEditingController(text: widget.note.title);
    _descriptionController = new TextEditingController(text: widget.note.description);
    _locationController = new TextEditingController(text: widget.note.location);
  }

  LatLng _center ;
  Position currentLocation;

  Future<Position> locateUser() async {
    try{
      return await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    }on PlatformException catch(e){
      currentLocation = null;
    }
    return currentLocation;
  }

  getUserLocation() async {
    currentLocation = await locateUser();
    setState(() {
      _center = LatLng(currentLocation.latitude, currentLocation.longitude);
      _locationController.text = _center.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Add Plant'),
        actions: <Widget>[
            new IconButton(
              icon: const Icon(Icons.view_list),
              tooltip: 'Next choice',
              onPressed: () {
              navigateToPlantList();
              },
              ),
          ]
        ),
        body: Container(
          margin: EdgeInsets.all(15.0),
          alignment: Alignment.center,
          child: Column(
            children: <Widget>[
              TextField(
                  controller: _locationController,
                  decoration: InputDecoration(
                    labelText: 'Current location',
                    ),
                  ),
                  Padding(padding: new EdgeInsets.all(5.0)),
              TextField(
                controller: _titleController,
                decoration: InputDecoration(labelText: 'Title'),
                ),
                Padding(padding: new EdgeInsets.all(5.0)),
                TextField(
                  controller: _descriptionController,
                  decoration: InputDecoration(labelText: 'Description'),
                  ),
                  Padding(padding: new EdgeInsets.all(5.0)),
                  RaisedButton(
                    child: (widget.note.id != null) ? Text('Update') : Text('Add'),
                    onPressed: () {
                      if (widget.note.id != null) {
                        db.updateNote(Note.fromMap({
                          'id': widget.note.id,
                          'location': _locationController.text,
                          'title': _titleController.text,
                          'description': _descriptionController.text
                          })).then((_) {
                            Navigator.pop(context, 'update');
                            });
                            }else {
                              db.saveNote(Note(_locationController.text,_titleController.text, _descriptionController.text)).then((_) {
                                Navigator.pop(context, 'save');
                                });
                              }
                            },
                          ),
                        ],
                      ),
                    ),
                  );
                }
                void navigateToPlantList() {
                   Navigator.push(context,
                  new MaterialPageRoute(builder: (context) => new ListViewNote()),);
                }
}
</code>```

Now using this I want to written marker in my home screen

答:
First of all, you should store latitude and longitude as two separate real value columns. This simplifies further steps.

Then you need a list of markers which can be updated later as field in the class:

List<Marker> _markers = [];
```
<p>To update the markers (e. g. from the database) a function is used:</p>
```void setMarkers() async {
  var notes = await db.getAllNotes();

  List<Marker> markers = notes.map((n) {
    LatLng point = LatLng(n.latitude, n.longitude);

    return Marker(
      width: 80.0,
      height: 80.0,
      point: point,
      builder: (ctx) => Container(
            child: Icon(
              Icons.location_on,
              color: Colors.green[700],
              size: 30,
            ),
          ),
    );
  }).toList();

  setState(() {
    _markers.clear();
    _markers = markers;
  });
}
```
<p>This function fetches all Notes from the database and updates the Markers.</p>
<p>In the FlutterMap widget replace the list of markers with the <code>_markers</code> field:</p>
<pre class="lang-dart prettyprint-override"><code>MarkerLayerOptions(markers: _markers)
</code>```

To ensure, that all items are loaded shortly after the app started, call the setMarkers() function in initState() and to add a new Marker, which can be created in your NoteScreen widget, to the map replace the call from your FloatingActionButton of the HomeScreen with

```<code>onPressed: () async {
  await Navigator.push(
      context, MaterialPageRoute(builder: (context) => AddPlantScreen(Plant.empty())));
  setMarkers();
},
</code>```

This updates the map after a new entry was created.

Note: Clearing and fully reloading the data every time from the database is not the best way, but this is up to you to optimize.

Edit #1:

You do get the current location separated:

```<code>  void getCurrentPosition() async {
    Position currentLocation = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

    setState(() {
      _center = LatLng(currentLocation.latitude, currentLocation.longitude);
    });
  }
</code>```

What you need to do in order for that to work is update your Note class to support a double _latitude; and double _longitude; instead of String _location; So you need to update the map functions, the getters and the constructor.

Furthermore, you need to adjust your DatabaseHelper class:

```<code>final String columnLatitude = 'latitude';
final String columnLongitude = 'longitude';

// new create table statement
'CREATE TABLE $tableNote($columnId INTEGER PRIMARY KEY, $columnLatitude REAL, $columnLongitude REAL, $columnTitle TEXT, $columnDescription TEXT)'
</code>```

And of course, all requests to the database must be adapted to the new fields so that no errors occur.

Body:
I have list of latitude and longitude which I am storing them in database.I want those latitude and longitude to be represented in flutter map with markers.

My code for saving latitude and longitude using sqlite

homeScreen.dart

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => new _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
  List<Note> items = new List();
  DatabaseHelper db = new DatabaseHelper();

  LatLng _center ;
  Position currentLocation;

  MapController _mapctl = MapController();

  Future<Position> locateUser() async {
    try{
      return await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    }on PlatformException catch(e){
      currentLocation = null;
    }
    return currentLocation;
  }

  getUserLocation() async {
    currentLocation = await locateUser();
    setState(() {
      _center = LatLng(currentLocation.latitude, currentLocation.longitude);
    });
    print('center $_center');
  }
  @override
  void initState() {
    super.initState();
    getUserLocation();
     db.getAllNotes().then((notes) {
      setState(() {
        notes.forEach((note) {
          items.add(Note.fromMap(note));
        });
      });
    });
  }

  @override
  Widget build(BuildContext context){
    var markers = <Marker>[
      Marker(
        width: 80.0,
        height: 80.0,
        point: LatLng(12.9716, 77.5946),
        builder: (ctx) => Container(
              child: Icon(Icons.location_on,color: Colors.green[700],size: 30,),
            ),
      ),
      Marker(
        width: 80.0,
        height: 80.0,
        point: LatLng(12.9716, 77.5946),
        builder: (ctx) => Container(
              child: Icon(Icons.location_on)
            ),
      ),
    ];
    return Scaffold(
      appBar: AppBar(
        title: Text('Plants Watch'),
        backgroundColor: Colors.green[700],
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.person),
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (context)=>UserProfile()));
            },
          ),
          IconButton(
            icon: Icon(Icons.exit_to_app),
            onPressed: () {
              BlocProvider.of<AuthenticationBloc>(context).dispatch(
                LoggedOut(),
              );
            },
          )
        ],
      ),
      body: Stack(
        children: <Widget>[
          new FlutterMap(
            mapController: _mapctl,
                options: new MapOptions(
                  center: new LatLng(12.9716, 77.5946),
                  maxZoom: 20.0,
                ),
                layers: [
                  new TileLayerOptions(
                    urlTemplate: "https://api.tiles.mapbox.com/v4/"
                    "{id}/{z}/{x}/{y}@2x.png?access_token={accessToken}",
                    additionalOptions: {
                      'accessToken': 'accessToken',
                      'id': 'mapbox.streets',
                      },
                    ),
                  MarkerLayerOptions(markers: markers)
                  ],
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Align(
                alignment: Alignment.bottomRight,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    FloatingActionButton(
                      backgroundColor: Colors.green[700],
                      child: Icon(Icons.my_location),
                      onPressed: () {
                        _mapctl.move(_center,16.0);
                        },
                    ),
                    SizedBox(height: 16.0),
                    FloatingActionButton(
                      backgroundColor: Colors.green[700],
                      child: Icon(Icons.add),
                      heroTag: null,
                      onPressed: () {
                        Navigator.push(context,
                        MaterialPageRoute(builder: (context) => NoteScreen(Note('', '', ''))));
                      },
                    ),
                  ],
            )
           ),
        ),
      ],
    )
  );
 }
}

Listview.dart

class ListViewNote extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new ListViewNoteState();
}

class ListViewNoteState extends State<ListViewNote> {
  List<Note> items = new List();
  DatabaseHelper db = new DatabaseHelper();

  @override
  void initState() {
    super.initState();
    db.getAllNotes().then((notes) {
      setState(() {
        notes.forEach((note) {
          items.add(Note.fromMap(note));
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
        title: Text('Plant List',
        ),
        centerTitle: true,
        actions: <Widget>[
          IconButton(icon: Icon(Icons.search,
            color: Colors.white,), onPressed: (){
            showSearch(context: context,
            delegate: DataSearch(this.items));
          })
        ],
      ),
      body: Center(
        child: ListView.builder(
          itemCount: items.length,
          padding: const EdgeInsets.all(15.0),
          itemBuilder: (context, position) {
            return Dismissible(
              background: stackBehindDismiss(),
              key: ObjectKey(items[position]),
              child: Card(
                elevation: 2.0,
                margin: new EdgeInsets.symmetric(horizontal: 0.0,vertical: 2.0),
                child: Column(
                  children: <Widget>[
                    ListTile(
                      title: Text(
                        '${items[position].title}',
                        style: TextStyle(
                          fontSize: 22.0,
                          color: Colors.deepOrangeAccent,
                          ),
                        ),
                        subtitle: Text(
                          '${items[position].description}' + '' + '${items[position].location}',
                          style: new TextStyle(
                            fontSize: 18.0,
                            fontStyle: FontStyle.italic,
                            ),
                          ),
                          onTap: () => _navigateToNote(context, items[position]),
                      ),
                    ],
                  ),
                ),
                onDismissed: (dirction){
                  var item   = items.elementAt(position);
                  _deleteNote(context, items[position], position);
                  Scaffold.of(context).showSnackBar(SnackBar(
                    content: Text("Item deleted"),
                    ));
                  },
              );
            }
         ),
         ),
         floatingActionButton: FloatingActionButton(
           backgroundColor: Colors.green[700],
           child: Icon(Icons.add),
           onPressed: () => _createNewNote(context),
          ),
      );
    }
    void _deleteNote(BuildContext context, Note note, int position) async {
      db.deleteNote(note.id).then((notes) {
       setState(() {
         items.removeAt(position);
         });
        });
      }
    void _navigateToNote(BuildContext context, Note note) async {
      String result = await Navigator.push(
        context,MaterialPageRoute(builder: (context) => NoteScreen(note)),
        );
        if (result == 'update') {
          db.getAllNotes().then((notes) {
            setState(() {
              items.clear();
              notes.forEach((note) {
                items.add(Note.fromMap(note));
                });
              });
            });
          }
        }
    void _createNewNote(BuildContext context) async {
      String result = await Navigator.push(
        context,MaterialPageRoute(builder: (context) => NoteScreen(Note('', '', ''))),
        );
        if (result == 'save') {
          db.getAllNotes().then((notes) {
            setState(() {
              items.clear();
              notes.forEach((note) {
                items.add(Note.fromMap(note));
                });
              });
            });
          }
        }
     stackBehindDismiss() {
       return Container(
         alignment: Alignment.centerRight,
         padding: EdgeInsets.only(right: 20.0),
         color: Colors.green[700],
         child: Icon(
           Icons.delete,
           color: Colors.white,
          ),
        );
       }
 }

class DataSearch extends SearchDelegate<Note> {
  DatabaseHelper db = new DatabaseHelper();
  List<Note> items = new List();
  final List<Note> suggestion = new List();
  // ListViewNoteState i = ListViewNoteState();

   DataSearch(this.items);

  @override
  ThemeData appBarTheme(BuildContext context) {
    assert(context != null);
    final ThemeData theme = Theme.of(context);
    assert(theme != null);
    return theme;
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(icon: Icon(Icons.clear), onPressed: () {
        query = '';

      } )
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: AnimatedIcon(
        icon: AnimatedIcons.menu_arrow,
        progress: transitionAnimation,
      ),
      onPressed: (){
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return Text(query);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestion = query.isEmpty
    ? items
    : items.where((target) => target.title.startsWith(query)).toList();
    if(items.isEmpty)
    {
      print("Null");
    }
     // return Text('$suggestion');
    return ListView.builder(
      itemCount: suggestion.length,
      itemBuilder: (context, position){
        return new  ListTile(
            title: RichText(
              text: TextSpan(
                text: suggestion[position].title.substring(0,query.length),
                style: TextStyle(
                  color: Colors.black,fontWeight: FontWeight.bold),
                  children: [
                    TextSpan(
                      text: suggestion[position].title.substring(query.length),
                      style: TextStyle(color: Colors.black54)
                    )
                  ]
              ),
            )
          );
      }
    );
  }
}

Below is my databse classes where i am creating dbHelper and class note for creating table

dbHelper.dart

class DatabaseHelper {
  static final DatabaseHelper _instance = new DatabaseHelper.internal();

  factory DatabaseHelper() => _instance;

  final String tableNote = 'noteTable';
  final String columnId = 'id';
  final String columnLocation = 'location';
  final String columnTitle = 'title';
  final String columnDescription = 'description';

  static Database _db;

  DatabaseHelper.internal();

  Future<Database> get db async {
    if (_db != null) {
      return _db;
    }
    _db = await initDb();

    return _db;
  }

  initDb() async {
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'notes.db');

//    await deleteDatabase(path); // just for testing

    var db = await openDatabase(path, version: 1, onCreate: _onCreate);
    return db;
  }

  void _onCreate(Database db, int newVersion) async {
    await db.execute(
        'CREATE TABLE $tableNote($columnId INTEGER PRIMARY KEY,$columnLocation TEXT, $columnTitle TEXT, $columnDescription TEXT)');
  }

  Future<int> saveNote(Note note) async {
    var dbClient = await db;
    var result = await dbClient.insert(tableNote, note.toMap());
//    var result = await dbClient.rawInsert(
//        'INSERT INTO $tableNote ($columnTitle, $columnDescription) VALUES (\'${note.title}\', \'${note.description}\')');

    return result;
  }

  Future<List> getAllNotes() async {
    var dbClient = await db;
    var result = await dbClient.query(tableNote, columns: [columnId, columnLocation , columnTitle, columnDescription]);
//    var result = await dbClient.rawQuery('SELECT * FROM $tableNote');

    return result.toList();
  }

  Future<int> getCount() async {
    var dbClient = await db;
    return Sqflite.firstIntValue(await dbClient.rawQuery('SELECT COUNT(*) FROM $tableNote'));
  }

  Future<Note> getNote(int id) async {
    var dbClient = await db;
    List<Map> result = await dbClient.query(tableNote,
        columns: [columnId, columnLocation , columnTitle, columnDescription],
        where: '$columnId = ?',
        whereArgs: [id]);
//    var result = await dbClient.rawQuery('SELECT * FROM $tableNote WHERE $columnId = $id');

    if (result.length > 0) {
      return new Note.fromMap(result.first);
    }

    return null;
  }

  Future<int> deleteNote(int id) async {
    var dbClient = await db;
    return await dbClient.delete(tableNote, where: '$columnId = ?', whereArgs: [id]);
//    return await dbClient.rawDelete('DELETE FROM $tableNote WHERE $columnId = $id');
  }

  Future<int> updateNote(Note note) async {
    var dbClient = await db;
    return await dbClient.update(tableNote, note.toMap(), where: "$columnId = ?", whereArgs: [note.id]);
//    return await dbClient.rawUpdate(
//        'UPDATE $tableNote SET $columnTitle = \'${note.title}\', $columnDescription = \'${note.description}\' WHERE $columnId = ${note.id}');
  }

  Future close() async {
    var dbClient = await db;
    return dbClient.close();
  }
}

classNote.dart

class Note {
  int _id;
  String _location;
  String _title;
  String _description;

  Note(this._location,this._title, this._description);

  Note.map(dynamic obj) {
    this._id = obj['id'];
    this._location = obj['location'];
    this._title = obj['title'];
    this._description = obj['description'];
  }

  int get id => _id;
  String get location => _location;
  String get title => _title;
  String get description => _description;

  Map<String, dynamic> toMap() {
    var map = new Map<String, dynamic>();
    if (_id != null) {
      map['id'] = _id;
    }
    map['location'] = _location;
    map['title'] = _title;
    map['description'] = _description;

    return map;
  }

  Note.fromMap(Map<String, dynamic> map) {
    this._id = map['id'];
    this._location = map ['location'];
    this._title = map['title'];
    this._description = map['description'];
  }
}

AddItem.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:latlong/latlong.dart';
import 'dbhelper.dart';
import 'package:geolocator/geolocator.dart';

class NoteScreen extends StatefulWidget {
  final Note note;
  NoteScreen(this.note);

  @override
  State<StatefulWidget> createState() => new _NoteScreenState();
}

class _NoteScreenState extends State<NoteScreen> {
  DatabaseHelper db = new DatabaseHelper();

  TextEditingController _titleController;
  TextEditingController _descriptionController;
  TextEditingController _locationController;

  @override
  void initState() {
    super.initState();
    getUserLocation();
    _titleController = new TextEditingController(text: widget.note.title);
    _descriptionController = new TextEditingController(text: widget.note.description);
    _locationController = new TextEditingController(text: widget.note.location);
  }

  LatLng _center ;
  Position currentLocation;

  Future<Position> locateUser() async {
    try{
      return await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    }on PlatformException catch(e){
      currentLocation = null;
    }
    return currentLocation;
  }

  getUserLocation() async {
    currentLocation = await locateUser();
    setState(() {
      _center = LatLng(currentLocation.latitude, currentLocation.longitude);
      _locationController.text = _center.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Add Plant'),
        actions: <Widget>[
            new IconButton(
              icon: const Icon(Icons.view_list),
              tooltip: 'Next choice',
              onPressed: () {
              navigateToPlantList();
              },
              ),
          ]
        ),
        body: Container(
          margin: EdgeInsets.all(15.0),
          alignment: Alignment.center,
          child: Column(
            children: <Widget>[
              TextField(
                  controller: _locationController,
                  decoration: InputDecoration(
                    labelText: 'Current location',
                    ),
                  ),
                  Padding(padding: new EdgeInsets.all(5.0)),
              TextField(
                controller: _titleController,
                decoration: InputDecoration(labelText: 'Title'),
                ),
                Padding(padding: new EdgeInsets.all(5.0)),
                TextField(
                  controller: _descriptionController,
                  decoration: InputDecoration(labelText: 'Description'),
                  ),
                  Padding(padding: new EdgeInsets.all(5.0)),
                  RaisedButton(
                    child: (widget.note.id != null) ? Text('Update') : Text('Add'),
                    onPressed: () {
                      if (widget.note.id != null) {
                        db.updateNote(Note.fromMap({
                          'id': widget.note.id,
                          'location': _locationController.text,
                          'title': _titleController.text,
                          'description': _descriptionController.text
                          })).then((_) {
                            Navigator.pop(context, 'update');
                            });
                            }else {
                              db.saveNote(Note(_locationController.text,_titleController.text, _descriptionController.text)).then((_) {
                                Navigator.pop(context, 'save');
                                });
                              }
                            },
                          ),
                        ],
                      ),
                    ),
                  );
                }
                void navigateToPlantList() {
                   Navigator.push(context,
                  new MaterialPageRoute(builder: (context) => new ListViewNote()),);
                }
}

Now using this I want to written marker in my home screen

Body:
First of all, you should store latitude and longitude as two separate real value columns. This simplifies further steps.

Then you need a list of markers which can be updated later as field in the class:

List<Marker> _markers = [];

To update the markers (e. g. from the database) a function is used:

void setMarkers() async {
  var notes = await db.getAllNotes();

  List<Marker> markers = notes.map((n) {
    LatLng point = LatLng(n.latitude, n.longitude);

    return Marker(
      width: 80.0,
      height: 80.0,
      point: point,
      builder: (ctx) => Container(
            child: Icon(
              Icons.location_on,
              color: Colors.green[700],
              size: 30,
            ),
          ),
    );
  }).toList();

  setState(() {
    _markers.clear();
    _markers = markers;
  });
}

This function fetches all Notes from the database and updates the Markers.

In the FlutterMap widget replace the list of markers with the _markers field:

MarkerLayerOptions(markers: _markers)

To ensure, that all items are loaded shortly after the app started, call the setMarkers() function in initState() and to add a new Marker, which can be created in your NoteScreen widget, to the map replace the call from your FloatingActionButton of the HomeScreen with

onPressed: () async {
  await Navigator.push(
      context, MaterialPageRoute(builder: (context) => AddPlantScreen(Plant.empty())));
  setMarkers();
},

This updates the map after a new entry was created.

Note: Clearing and fully reloading the data every time from the database is not the best way, but this is up to you to optimize.

Edit #1:

You do get the current location separated:

  void getCurrentPosition() async {
    Position currentLocation = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

    setState(() {
      _center = LatLng(currentLocation.latitude, currentLocation.longitude);
    });
  }

What you need to do in order for that to work is update your Note class to support a double _latitude; and double _longitude; instead of String _location; So you need to update the map functions, the getters and the constructor.

Furthermore, you need to adjust your DatabaseHelper class:

final String columnLatitude = 'latitude';
final String columnLongitude = 'longitude';

// new create table statement
'CREATE TABLE $tableNote($columnId INTEGER PRIMARY KEY, $columnLatitude REAL, $columnLongitude REAL, $columnTitle TEXT, $columnDescription TEXT)'

And of course, all requests to the database must be adapted to the new fields so that no errors occur.


问:
MS Access AcDialog hiding the form
I had a button click event in my access form which has

```<code>DoCmd.OpenForm "frmStudentsAll", acNormal, , , , acDialog
</code>```

Clicking this button opened the frmStudentAll in dialog view but all of a sudden today clicking this button did not open the form. I thought Access was crashing everytime I clicked this button but I can still edit the VBA but I cannot press any of the buttons in GUI. My thought is that the acDialog is opening a really small form somewhere that I cannot see and I cannot press anything without closing it. I am having to close Access using task manager.

```<code> DoCmd.OpenForm "frmStudentsAll", acNormal
</code>```

Opening the form in just normal view works fine but this is not really what I want. I did not do any new Access updates recently. Not sure why this is happening.

答: Not sure if this will help or not but, I'll throw it out there anyways. I had a similar problem when I had two monitors set up. Then lost one. There was one program that I would use all the time but, all of the sudden it wouldn't work. Took a while for it to kick in. That program was opening on the second screen that was no longer there. Just a shot in the dark... Good luck!</p>

Title: MS Access AcDialog hiding the form

Body:
I had a button click event in my access form which has

DoCmd.OpenForm "frmStudentsAll", acNormal, , , , acDialog

Clicking this button opened the frmStudentAll in dialog view but all of a sudden today clicking this button did not open the form. I thought Access was crashing everytime I clicked this button but I can still edit the VBA but I cannot press any of the buttons in GUI. My thought is that the acDialog is opening a really small form somewhere that I cannot see and I cannot press anything without closing it. I am having to close Access using task manager.

 DoCmd.OpenForm "frmStudentsAll", acNormal

Opening the form in just normal view works fine but this is not really what I want. I did not do any new Access updates recently. Not sure why this is happening.


问:
Versioning of REST API Built With ASP.NET MVC 3 - Best Practices
I am wondering if there is a best practice for creating a REST API with ASP.NET MVC 3?  At the moment I am thinking of creating a controller for each version of the REST API.  For example, so far I have:

```<code>public class V1Controller : Controller
{
    public V1Controller()
    {
    }

    public ActionResult GetUser(string userId, IUserRepository userRepostory)
    {
        //code to pull data and convert to JSON string
        return View("Results");
    }

    public ActionResult GetUsersByGroup(string groupId, IUserRepository userRepostory)
    {
        //code to pull data and convert to JSON string
        return View("Results");
    }
}
</code>```

Then for the views I overwrite the _ViewStart.cshtml to remove the layout and then I have  Results.cshtml that just outputs the data that is formatted in the controller action, right now JSON.  Having every single REST call in one controller seems like a bit too much but it is the best way I can think of so that I can keep clean separate versions of the API so that when it comes to creating version 2 of the API, I can create a V2Controller and not break the existing API to give people time to switch over to the new API.

Is there a better way to create a REST API with ASP.NET MVC 3?

答:
If all you are returning is JSON, you do not need a view. Jusr return

```<code>new JsonResult(){Data = Data};
</code>```

Look in here.

Also in terms of versioning, versions can be implemented as different controllers or as extra methods in the same controller. But without knowing why you would need versions and why your clients (which I assume are browsers) would need to know about versioning is not clear from your question.

Body:
I am wondering if there is a best practice for creating a REST API with ASP.NET MVC 3?  At the moment I am thinking of creating a controller for each version of the REST API.  For example, so far I have:

public class V1Controller : Controller
{
    public V1Controller()
    {
    }

    public ActionResult GetUser(string userId, IUserRepository userRepostory)
    {
        //code to pull data and convert to JSON string
        return View("Results");
    }

    public ActionResult GetUsersByGroup(string groupId, IUserRepository userRepostory)
    {
        //code to pull data and convert to JSON string
        return View("Results");
    }
}

Then for the views I overwrite the _ViewStart.cshtml to remove the layout and then I have  Results.cshtml that just outputs the data that is formatted in the controller action, right now JSON.  Having every single REST call in one controller seems like a bit too much but it is the best way I can think of so that I can keep clean separate versions of the API so that when it comes to creating version 2 of the API, I can create a V2Controller and not break the existing API to give people time to switch over to the new API.

Is there a better way to create a REST API with ASP.NET MVC 3?

Body:
If all you are returning is JSON, you do not need a view. Jusr return

new JsonResult(){Data = Data};

Look in here.

Also in terms of versioning, versions can be implemented as different controllers or as extra methods in the same controller. But without knowing why you would need versions and why your clients (which I assume are browsers) would need to know about versioning is not clear from your question.


问:
How to find the component path in AEM Touch UI Dialog?
I want to e.g. fetch the path /content/branc/region/microsite_name/en/mypage/jcr:content/par/mycomponent in jQuery.

I am able to fetch the page path using Granite.author.page.

Code to fetch page path:

```<code>(function ($, $document, author) {
    "use strict";
$(document).on("dialog-ready", function() {
    var path = author.page`enter code here`.path; //This works
    var component = author.component.path; //This is not working
    console.log("component path " +component);
   });
})($, $(document), Granite.author);
</code>```

Kindly advice how to fetch the component path in jquery.

答:
As @sharath-madappa points out, the resourceType is available from Granite.author.DialogFrame.currentDialog.editable.type.

If you want the exact path to the component that invoked the dialog, you can use Granite.author.DialogFrame.currentDialog.editable.path.

More documentation about it: https://helpx.adobe.com/experience-manager/6-3/sites/developing/using/reference-materials/jsdoc/ui-touch/editor-core/Granite.author.DialogFrame.html

Body:
I want to e.g. fetch the path /content/branc/region/microsite_name/en/mypage/jcr:content/par/mycomponent in jQuery.

I am able to fetch the page path using Granite.author.page.

Code to fetch page path:

(function ($, $document, author) {
    "use strict";
$(document).on("dialog-ready", function() {
    var path = author.page`enter code here`.path; //This works
    var component = author.component.path; //This is not working
    console.log("component path " +component);
   });
})($, $(document), Granite.author);

Kindly advice how to fetch the component path in jquery.


问:
object property undefined, One line after being console.log()'d
I am trying to draw a table and form to add data to said table on a page, based on a json object retrieved from the server. I am getting a Uncaught typeError and cannot figure out why.

If I console.log() the object, It prints out in the console as expected. I can even output specific properties no problem. But when I try and use any of the properties, In a html sting, I get "Uncaught TypeError: Cannot read property 'formName' of undefined"

```<code>function testFunc(subform){
    console.log(subForm.layout.formName); //<--- prints the name to the console

    var form = '<div class="assetSubForm"><h2>' + subForm.layout.formName + '</h2>';
    console.log(form); //<--- error's out???

    return form;
}
</code>```

The object is as follows:

```<code>{records: false, layout: {…}}
layout:
    fields: (5) [{…}, {…}, {…}, {…}, {…}]
    formID: 30
    formName: "Part 11 - Building Clearance And Fire Appliances"
    position: 120
    __proto__: Object
records: false
__proto__: Object
</code>```

I can't for the life of me wrap my head around why. I have tried googling it but have come up empty as I can't figure out how to word it in an appropriate search term and all the results that do come up relate to scope or spelling errors (eg. object defined in anonymous function and referenced outside).

答:
Your argument name is subform, you refer to subForm in other parts of the code.
I'm assuming there is a subForm variable visible in that scope, but its value changes, so depending on when you call the function it sometimes does not work.

Body:
I am trying to draw a table and form to add data to said table on a page, based on a json object retrieved from the server. I am getting a Uncaught typeError and cannot figure out why.

If I console.log() the object, It prints out in the console as expected. I can even output specific properties no problem. But when I try and use any of the properties, In a html sting, I get "Uncaught TypeError: Cannot read property 'formName' of undefined"

function testFunc(subform){
    console.log(subForm.layout.formName); //<--- prints the name to the console

    var form = '

' + subForm.layout.formName + '
';
    console.log(form); //<--- error's out???

    return form;
}

The object is as follows:

{records: false, layout: {…}}
layout:
    fields: (5) [{…}, {…}, {…}, {…}, {…}]
    formID: 30
    formName: "Part 11 - Building Clearance And Fire Appliances"
    position: 120
    __proto__: Object
records: false
__proto__: Object

I can't for the life of me wrap my head around why. I have tried googling it but have come up empty as I can't figure out how to word it in an appropriate search term and all the results that do come up relate to scope or spelling errors (eg. object defined in anonymous function and referenced outside).


问:
Cannot access JWT claim in WebApi authorization token
I was able to implement the below JWT solution in my MVC WebApi following below link JWT Authentication for Asp.Net Web Api

Now, I want to access claim in the controllers, but all claims are null. I have tried a few things and all of them returns null.

How is claim added in JwtAuthenticationAttribute:

```<code>protected Task<IPrincipal> AuthenticateJwtToken(string token)
        {
            string username;

            if (ValidateToken(token, out username))
            {
                //Getting user department to add to claim.
                eTaskEntities _db = new eTaskEntities();
                var _user = (from u in _db.tblUsers join d in _db.tblDepartments on u.DepartmentID equals d.DepartmentID select u).FirstOrDefault();
                var department = _user.DepartmentID;

                // based on username to get more information from database in order to build local identity
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, username),
                    new Claim(ClaimTypes.SerialNumber, department.ToString())
                    // Add more claims if needed: Roles, ...
                };

                var identity = new ClaimsIdentity(claims, "Jwt");
                IPrincipal user = new ClaimsPrincipal(identity);

                return Task.FromResult(user);
            }

            return Task.FromResult<IPrincipal>(null);
        }
</code>```

What I have tried so far

Extension method to get claim:

```<code>public static class IPrincipleExtension
{
    public static String GetDepartment(this IIdentity principal)
    {
        var identity = HttpContext.Current.User.Identity as ClaimsIdentity;
        if (identity != null)
        {
            return identity.FindFirst("SerialNumber").Value;
        }
        else
            return null;
    }
}
</code>```

Using the function defined in the post (link above):

```<code>TokenManager.GetPrincipal(Request.Headers.Authorization.Parameter).FindFirst("SerialNumber")
</code>```

Trying to access Claim through thread:

```<code>((ClaimsPrincipal)System.Threading.Thread.CurrentPrincipal.Identity).FindFirst("SerialNumber")
</code>```

For all the above, a claim is always null. What am I doing wrong?

答:
You should try this to get your claim:

```<code>if (HttpContext.User.Identity is System.Security.Claims.ClaimsIdentity identity)
{
    var serialNum = identity.FindFirst(System.Security.Claims.ClaimTypes.SerialNumber).Value;
}

</code>```

I reserve the identity.FindFirst("string_here").Value for when I set my claims like this:

var usersClaims = new[]
{
    new Claim("string_here", "value_of_string", ClaimValueTypes.String),
    ...
};
```

<p>rather than using "prebuilt" values like this:</p>

<pre class="lang-cs prettyprint-override"><code>var usersClaims = new[]
{
    new Claim(ClaimTypes.Name, "value_of_name", ClaimValueTypes.String),
    ...
};
</code>```

Body:
I was able to implement the below JWT solution in my MVC WebApi following below link JWT Authentication for Asp.Net Web Api

Now, I want to access claim in the controllers, but all claims are null. I have tried a few things and all of them returns null.

How is claim added in JwtAuthenticationAttribute:

protected Task<IPrincipal> AuthenticateJwtToken(string token)
        {
            string username;

            if (ValidateToken(token, out username))
            {
                //Getting user department to add to claim.
                eTaskEntities _db = new eTaskEntities();
                var _user = (from u in _db.tblUsers join d in _db.tblDepartments on u.DepartmentID equals d.DepartmentID select u).FirstOrDefault();
                var department = _user.DepartmentID;

                // based on username to get more information from database in order to build local identity
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, username),
                    new Claim(ClaimTypes.SerialNumber, department.ToString())
                    // Add more claims if needed: Roles, ...
                };

                var identity = new ClaimsIdentity(claims, "Jwt");
                IPrincipal user = new ClaimsPrincipal(identity);

                return Task.FromResult(user);
            }

            return Task.FromResult<IPrincipal>(null);
        }

What I have tried so far

Extension method to get claim:

public static class IPrincipleExtension
{
    public static String GetDepartment(this IIdentity principal)
    {
        var identity = HttpContext.Current.User.Identity as ClaimsIdentity;
        if (identity != null)
        {
            return identity.FindFirst("SerialNumber").Value;
        }
        else
            return null;
    }
}

Using the function defined in the post (link above):

TokenManager.GetPrincipal(Request.Headers.Authorization.Parameter).FindFirst("SerialNumber")

Trying to access Claim through thread:

((ClaimsPrincipal)System.Threading.Thread.CurrentPrincipal.Identity).FindFirst("SerialNumber")

For all the above, a claim is always null. What am I doing wrong?

Body:
You should try this to get your claim:

if (HttpContext.User.Identity is System.Security.Claims.ClaimsIdentity identity)
{
    var serialNum = identity.FindFirst(System.Security.Claims.ClaimTypes.SerialNumber).Value;
}

I reserve the identity.FindFirst("string_here").Value for when I set my claims like this:

var usersClaims = new[]
{
    new Claim("string_here", "value_of_string", ClaimValueTypes.String),
    ...
};

rather than using "prebuilt" values like this:

var usersClaims = new[]
{
    new Claim(ClaimTypes.Name, "value_of_name", ClaimValueTypes.String),
    ...
};


问:
Logging module weirdness, wrong display of log message?
Here is a small example of something I find very weird about the logging module:

import logging
logging.basicConfig()

#
# making a hierarchy like this:
#     root
#       |- session
#             |-session.foo
#
root_logger = logging.getLogger()
session_logger = logging.getLogger("session")
foo_logger = logging.getLogger("session.foo")
#
# root_logger and session_logger effective log levels
# are set to 30 (= WARNING)
#
foo_logger.debug("WA") #nothing is printed, so far so good
#
# and now enters the problem...
#
foo_logger.setLevel(logging.DEBUG)
foo_logger.debug("HELLO") #HELLO log message is printed!!!
```

I do not get why the 'HELLO' log message is printed, to my understanding
since there is no handler attached to logger foo_logger the log message should
bubble up, and effectively be stopped by higher level logger (session),
since its level is set to WARNING (by default).

It seems like setting the level on foo_logger gives it rights to display
through the handler but it is very unclear to me.

Can someone explain to me why the message is printed ?
And what should I do to have the logger hierarchy as I would like ?

答:
Both loggers AND handlers have a level setting, and the default level for handlers is 0. You'd need to set the level of the parent handler - in your case root_logger.handlers[0] above logging.DEBUG to filter out the debug() calls on foo_logger:

```<code>root_logger.handlers[0].level = logging.WARN
foo_logger.debug("peekaboo") # should not be printed
</code>```

Note that logging.basicConfig() only does a very simplistic config - it's mostly meant as a way to get started with logging, for any serious configuration you want dictConfig instead, which let you specify the handlers, formatters, levels etc as you see fit. Also note that a logger actually has a list of handlers (not a single one) and that multiple loggers can use the same handler, so who logs what (and where) depends on the combination of loggers AND handlers levels (and on the logger's propagate option too).

As a practical example, on my current (django) project we have (amongst others) a "console" handler (logs to stdout, which gunicorn redirects to it's own log file) whose level is set to INFO and a "notify" handler (sends emails notifications) with level set to WARN, so that some of our loggers (those for the most sensitive parts) will send INFO and above messages to gunicorn's logs and send WARN messages and above as notification emails too.

Body:
Here is a small example of something I find very weird about the logging module:

import logging
logging.basicConfig()

#
# making a hierarchy like this:
#     root
#       |- session
#             |-session.foo
#
root_logger = logging.getLogger()
session_logger = logging.getLogger("session")
foo_logger = logging.getLogger("session.foo")
#
# root_logger and session_logger effective log levels
# are set to 30 (= WARNING)
#
foo_logger.debug("WA") #nothing is printed, so far so good
#
# and now enters the problem...
#
foo_logger.setLevel(logging.DEBUG)
foo_logger.debug("HELLO") #HELLO log message is printed!!!

I do not get why the 'HELLO' log message is printed, to my understanding
since there is no handler attached to logger foo_logger the log message should
bubble up, and effectively be stopped by higher level logger (session),
since its level is set to WARNING (by default).

It seems like setting the level on foo_logger gives it rights to display
through the handler but it is very unclear to me.

Can someone explain to me why the message is printed ?
And what should I do to have the logger hierarchy as I would like ?

Body:
Both loggers AND handlers have a level setting, and the default level for handlers is 0. You'd need to set the level of the parent handler - in your case root_logger.handlers[0] above logging.DEBUG to filter out the debug() calls on foo_logger:

root_logger.handlers[0].level = logging.WARN
foo_logger.debug("peekaboo") # should not be printed

Note that logging.basicConfig() only does a very simplistic config - it's mostly meant as a way to get started with logging, for any serious configuration you want dictConfig instead, which let you specify the handlers, formatters, levels etc as you see fit. Also note that a logger actually has a list of handlers (not a single one) and that multiple loggers can use the same handler, so who logs what (and where) depends on the combination of loggers AND handlers levels (and on the logger's propagate option too).

As a practical example, on my current (django) project we have (amongst others) a "console" handler (logs to stdout, which gunicorn redirects to it's own log file) whose level is set to INFO and a "notify" handler (sends emails notifications) with level set to WARN, so that some of our loggers (those for the most sensitive parts) will send INFO and above messages to gunicorn's logs and send WARN messages and above as notification emails too.


问:
NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<org.springframework.shell.ParameterResolver>'
I'm currently trying to create a Spring Shell Application in Scala.
It works in IntelliJ but does not work when creating the jar.

I have a working proof of concept in Java, that does also successfully create a running jar.

However, my Scala version fails with several:

```<code>Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterValidationExceptionResultHandler': Unsatisfied dependency expressed through field 'parameterResolvers'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<org.springframework.shell.ParameterResolver>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code>```

I've tried several minimal examples, moving the classes around (same package) and different Spring annotations (like @SpringBootApplication for both).

Java version:

```<code>@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@ShellComponent
public class MyCommands {

    @ShellMethod("Add two integers together.")
    public int add(int a, int b) {
        return a + b;
    }
}
</code>```

Scala Version:

```<code>@EnableAutoConfiguration
@ComponentScan
class DemoApplication

object Scark extends App {
  SpringApplication.run(classOf[DemoApplication], args:_*)
}

@ShellComponent class MyCommands {
  @ShellMethod("Add two integers together.") def add(a: Int, b: Int): Int = a + b
}
</code>```

I expect to also be able to successfully build a jar from the Scala version.

Edit: I've uploaded the minimal example:
https://github.com/Zethson/Scala-Spring-Shell-Example/tree/feature/minimal_scala_issues_SO

答:
It seems to be unable to resolve your shell command parameters. Can you try this :</p>

```<code>@ShellComponent class MyCommands {
  @ShellMethod("Add two integers together.") def add(
    @ShellOption(mandatory = true) a: Int,
    @ShellOption(mandatory = true) b: Int): Int = a + b
}
</code>```

Body:
I'm currently trying to create a Spring Shell Application in Scala.
It works in IntelliJ but does not work when creating the jar.

I have a working proof of concept in Java, that does also successfully create a running jar.

However, my Scala version fails with several:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterValidationExceptionResultHandler': Unsatisfied dependency expressed through field 'parameterResolvers'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<org.springframework.shell.ParameterResolver>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I've tried several minimal examples, moving the classes around (same package) and different Spring annotations (like @SpringBootApplication for both).

Java version:

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@ShellComponent
public class MyCommands {

    @ShellMethod("Add two integers together.")
    public int add(int a, int b) {
        return a + b;
    }
}

Scala Version:

@EnableAutoConfiguration
@ComponentScan
class DemoApplication

object Scark extends App {
  SpringApplication.run(classOf[DemoApplication], args:_*)
}

@ShellComponent class MyCommands {
  @ShellMethod("Add two integers together.") def add(a: Int, b: Int): Int = a + b
}

I expect to also be able to successfully build a jar from the Scala version.

Edit: I've uploaded the minimal example:
https://github.com/Zethson/Scala-Spring-Shell-Example/tree/feature/minimal_scala_issues_SO

Body:
It seems to be unable to resolve your shell command parameters. Can you try this :

@ShellComponent class MyCommands {
  @ShellMethod("Add two integers together.") def add(
    @ShellOption(mandatory = true) a: Int,
    @ShellOption(mandatory = true) b: Int): Int = a + b
}


问:
Need some help having this work the way i need
ok so I just launched a new website and I have a bit of an issue with redirection. htaccess redirects don't like handling the values in a php url and push them to the new one and soIi got this but I need a little help

redirect plugins for wordpress
cpanel
making my own

```<code><?php

$redirect[0] = 'http://url-1.com';
$redirect[1] = 'http://url-2.com';
$redirect[2] = 'http://url-3.com';

$number = mt_rand(0,2);

header("Location:$redirect[$number]");

?>
</code>```

i need this to be able to work like this

Page.php?redirect=name
to redirect to a url

I know I'm damn close but how to i make it the proper name and request?
all the old site urls are
article.php?articlelist=bobdo_14_ol
or article.php?articlelist=taco_23_tt
etc

I'm trying to make them redirect but it's beyond my skill range

答:
this code worked great
thanks for the idea on get values</p>

```<code>$var = $_GET['article'];

if($var == 'one'){
    header("Location: http://www.one.com/");
}else if ($var == 'two'){
    header("Location: http://www.two.com/");
}
</code>```

Body:
ok so I just launched a new website and I have a bit of an issue with redirection. htaccess redirects don't like handling the values in a php url and push them to the new one and soIi got this but I need a little help

redirect plugins for wordpress
cpanel
making my own

<?php

$redirect[0] = 'http://url-1.com';
$redirect[1] = 'http://url-2.com';
$redirect[2] = 'http://url-3.com';

$number = mt_rand(0,2);

header("Location:$redirect[$number]");

?>

i need this to be able to work like this

Page.php?redirect=name
to redirect to a url

I know I'm damn close but how to i make it the proper name and request?
all the old site urls are
article.php?articlelist=bobdo_14_ol
or article.php?articlelist=taco_23_tt
etc

I'm trying to make them redirect but it's beyond my skill range

Body:
this code worked great
thanks for the idea on get values

$var = $_GET['article'];

if($var == 'one'){
    header("Location: http://www.one.com/");
}else if ($var == 'two'){
    header("Location: http://www.two.com/");
}


问:
Issues with socket buffer reader
I've been given this code for an assignment, there supposed to be errors in it but I can't actually figure out what this function is supposed to do, never mind figure out if there's any issues with it...

I am guessing that it's supposed to read the buffer line by line, but I've never seen it done this way before

The buffer that is sent to the function is empty.

```<code>int read_line(int sock, char *buffer) {
    size_t length = 0;

    while (1) {
        char data;
        int result = recv(sock, &data, 1, 0);

        if ((result <= 0) || (data == EOF)){
            perror("Connection closed");
            exit(1);
        }

        buffer[length] = data;
        length++;

        if (length >= 2 && buffer[length-2] == '\r' && buffer[length-1] == '\n') {
            buffer[length-2] = '\0';
            return length;
        }
    }
}
</code>```

Thanks in advance!

答:
I'd say the purpose of this function is to read a line that ends with \r\n from socket stream and store it in a char array as a string, therefore the \0 (string termination character) placement.

Ok, so what's wrong with the code?

I'd start with the input parameter char *buffer - inside the function you do not know its size so you cannot check if it exceeds its size limit and it could lead to buffer overflow.
So it would be better to send buffer length as a parameter and check with every received byte if it can be stored.

EOF - it is defined as -1 and in this case actually doesn't make any sense, because nothing will be setting your data variable to EOF. The only thing you need to look out for is the end of socket stream (recv documentation). And here is an example for EOFusage.
Feel free to remove (data == EOF) from condition.

Let's say you are receiving everything regularly and you receive your last input and connection closes, so you enter this case:

```<code>if ((result <= 0) || (data == EOF)){
    perror("Connection closed");
    exit(1);
}
</code>```

The problem here is that you won't process your last line and the program will just end. Although, I might be wrong here since I don't know when the connection is getting regularly shut down.
And a minor note here, result that equals to 0 isn't considered as an error, but a regular connection shutdown (or a 0-byte datagram was received).

I hope I haven't missed anything.

Title: Issues with socket buffer reader

Body:
I've been given this code for an assignment, there supposed to be errors in it but I can't actually figure out what this function is supposed to do, never mind figure out if there's any issues with it...

I am guessing that it's supposed to read the buffer line by line, but I've never seen it done this way before

The buffer that is sent to the function is empty.

int read_line(int sock, char *buffer) {
    size_t length = 0;

    while (1) {
        char data;
        int result = recv(sock, &data, 1, 0);

        if ((result <= 0) || (data == EOF)){
            perror("Connection closed");
            exit(1);
        }

        buffer[length] = data;
        length++;

        if (length >= 2 && buffer[length-2] == '\r' && buffer[length-1] == '\n') {
            buffer[length-2] = '\0';
            return length;
        }
    }
}

Thanks in advance!

Body:
I'd say the purpose of this function is to read a line that ends with \r\n from socket stream and store it in a char array as a string, therefore the \0 (string termination character) placement.

Ok, so what's wrong with the code?

I'd start with the input parameter char *buffer - inside the function you do not know its size so you cannot check if it exceeds its size limit and it could lead to buffer overflow.
So it would be better to send buffer length as a parameter and check with every received byte if it can be stored.

EOF - it is defined as -1 and in this case actually doesn't make any sense, because nothing will be setting your data variable to EOF. The only thing you need to look out for is the end of socket stream (recv documentation). And here is an example for EOFusage.
Feel free to remove (data == EOF) from condition.

Let's say you are receiving everything regularly and you receive your last input and connection closes, so you enter this case:

if ((result <= 0) || (data == EOF)){
    perror("Connection closed");
    exit(1);
}

The problem here is that you won't process your last line and the program will just end. Although, I might be wrong here since I don't know when the connection is getting regularly shut down.
And a minor note here, result that equals to 0 isn't considered as an error, but a regular connection shutdown (or a 0-byte datagram was received).

I hope I haven't missed anything.


问:
Running script on page load
I am using the following code to run a calculation as the user type in a number.

```<code>   <form action="index.php" method="post" autocomplete="off" data-abide>
   <input type="text" id="rate" name="rate">
   <input type="text" name="supplier_cost" class="value-right" pattern="\d*" value="<?php echo $supplier_cost; ?>" id="decimal" required>
   <input type="text" name="sterling" id="sterling" class="value-right" disabled>
   <button type="submit" class="button tiny ebc-theme" name="save"><i class="fa fa-floppy-o" aria-hidden="true"></i> SAVE</button>
   </form>

$(document).ready(function(){

        var supplier_id = $('#supplier').val().split(",");
        var period = "<?php echo $period; ?>";
        $.ajax({
            url: "fetch_rate.php",
            method: "POST",
            data:{supplierID:supplier_id[1], periodID:period},
            dataType:"text",
            success:function(data)
            {
                $('#rate').val(data);
            }
        });

});

   $(document).ready(SterlingCalc);
   document.getElementById('decimal').addEventListener("keyup", SterlingCalc);

   var rate = document.getElementById('rate');
   var sup_cost = document.getElementById('decimal');

   function SterlingCalc(){

      document.getElementById('sterling').value = (sup_cost.value / rate.value).toFixed(2) || 0;

   }
</code>```

How do I add code so that the calulation runs on the page load if both the "rate" and "decimal" fields are already loaded (for example, values are populated by database)?

Thanks,

John

答:
Try this:

```<code>$(document).ready(function() {
    SterlingCalc();
    document.getElementById('decimal').addEventListener("keyup", function(){SterlingCalc()});
});

function SterlingCalc(){
    var rate = document.getElementById('rate');
    var sup_cost = document.getElementById('decimal');
    document.getElementById('sterling').value = (sup_cost.value / rate.value).toFixed(2) || 0;
}
</code>```

Reasoning:
With $(document).ready(function(){ XXX }) you basically execute the code (XXX) when the document is loaded. Therefore, if the page loads the keybinding is put on 'decimal'.

Title: Running script on page load

Body:
I am using the following code to run a calculation as the user type in a number.

   <form action="index.php" method="post" autocomplete="off" data-abide>
   <input type="text" id="rate" name="rate">
   <input type="text" name="supplier_cost" class="value-right" pattern="\d*" value="<?php echo $supplier_cost; ?>" id="decimal" required>
   <input type="text" name="sterling" id="sterling" class="value-right" disabled>
   <button type="submit" class="button tiny ebc-theme" name="save"> SAVE</button>
   </form>

$(document).ready(function(){

        var supplier_id = $('#supplier').val().split(",");
        var period = "<?php echo $period; ?>";
        $.ajax({
            url: "fetch_rate.php",
            method: "POST",
            data:{supplierID:supplier_id[1], periodID:period},
            dataType:"text",
            success:function(data)
            {
                $('#rate').val(data);
            }
        });

});

   $(document).ready(SterlingCalc);
   document.getElementById('decimal').addEventListener("keyup", SterlingCalc);

   var rate = document.getElementById('rate');
   var sup_cost = document.getElementById('decimal');

   function SterlingCalc(){

      document.getElementById('sterling').value = (sup_cost.value / rate.value).toFixed(2) || 0;

   }

How do I add code so that the calulation runs on the page load if both the "rate" and "decimal" fields are already loaded (for example, values are populated by database)?

Thanks,

John

Body:
Try this:

$(document).ready(function() {
    SterlingCalc();
    document.getElementById('decimal').addEventListener("keyup", function(){SterlingCalc()});
});

function SterlingCalc(){
    var rate = document.getElementById('rate');
    var sup_cost = document.getElementById('decimal');
    document.getElementById('sterling').value = (sup_cost.value / rate.value).toFixed(2) || 0;
}

Reasoning:
With $(document).ready(function(){ XXX }) you basically execute the code (XXX) when the document is loaded. Therefore, if the page loads the keybinding is put on 'decimal'.


问:
How to type special characters using keyboard module?
I have a program which will detect when the keyboard presses a specified order of keys, and then replace it with something. How can I do this with special symbols?

def replace():
    if keyboard.is_pressed('p'):
        if keyboard.is_pressed('i'):
            for x in range (1, 3):
                keyboard.press_and_release('Backspace')
            keyboard.typewrite( #special symbol goes here )
```

答:
Not having a num-lock key does not matter. Python is acting as a keyboard (separate from yours). We just need the scan code for the numpad numbers.

Let's type an Omega Ω char which is alt + 2,3,4. First we get the scan codes -

```<code>import keyboard

print(keyboard.key_to_scan_codes('2'))
>> (3, 80)
print(keyboard.key_to_scan_codes('3'))
>> (4, 81)
print(keyboard.key_to_scan_codes('4'))
>> (5, 75)
</code>```

The 2nd numbers are the scan codes for the numpad numbers. Knowing this, we can now make the code -

```<code>keyboard.press('alt')
keyboard.press_and_release(80)
keyboard.press_and_release(81)
keyboard.press_and_release(75)
keyboard.release('alt')
</code>```

Body:
Not having a num-lock key does not matter. Python is acting as a keyboard (separate from yours). We just need the scan code for the numpad numbers.

Let's type an Omega Ω char which is alt + 2,3,4. First we get the scan codes -

import keyboard

print(keyboard.key_to_scan_codes('2'))
>> (3, 80)
print(keyboard.key_to_scan_codes('3'))
>> (4, 81)
print(keyboard.key_to_scan_codes('4'))
>> (5, 75)

The 2nd numbers are the scan codes for the numpad numbers. Knowing this, we can now make the code -

keyboard.press('alt')
keyboard.press_and_release(80)
keyboard.press_and_release(81)
keyboard.press_and_release(75)
keyboard.release('alt')


问:
Bash script containing git commands behaves differently when used together with perl
I wrote a script that replaces last 3 digits of a version number in a file containing a string in this format

"version-all:255.24.788"

There are 2 modes for the script: regular and advanced. Regular mode just makes the necessary changes, adds the files to git and commits them. Advanced version creates a branch to make those changes in, modifies the files, adds, commits, then returns to the original working branch.

I observe an odd behavior when running the script. The script works when ran first time, but when ran second time, it stops committing the results and tries to change the branch resulting in merge conflicts. I can't figure out why the script would only work odd number of times (first, third, fifth time) and when ran even number of times (second, fourth, sixth), fails.

I've tried changing the syntax of variables and replaced perl calls with a simple

```<code>echo "test" > file1.txt
</code>```

for debugging purposes and it seems to work fine then. When adding perl commands back, the script seems to return to its odd behaviour.

```<code>#!/bin/bash
# This script replaces last 3 digits of a version number in a file
# There are 2 modes for the script
#   1. Regular - no flag needed, requires 1 argument: a version number
#   2. Advanced - flag "-a" needs to be used followed by 3 arguments: version number, push repo name, remote repo name.

advanced_script=false
version="none"

if [ "$1" = "-a" ] ; then
    advanced_script=true
fi

if [ "$advanced_script" = true ] ; then
    if [ $# -ne 4 ] ; then
        echo -e "ERROR: Please supply the following 3 arguments and try again.\n"
        echo -e "       1. New version number\n"
        echo -e "       2. Push repository name\n"
        echo -e "       3. Remote repository name\n"
        exit 1
    fi
    version="$2"
else
    if [ $# -ne 1 ] ; then
        echo -e "ERROR: Please supply version number and try again.\n"
        exit 1
    fi
    version="$1"
fi

old_version_full="version-all:255.24.788"
old_version=${old_version_full##*all:}
new_version=${old_version%.*}
new_version+=".${version}"

current_branch=$(git branch | grep \* | cut -d ' ' -f2)
commit_string="Bump the version to $version"

if [ "$advanced_script" = true ] ; then
    local_branch="new_$version"
    remote_master="$4/master"
    git stash
    git checkout -b "$local_branch" "$remote_master"
fi

perl -i -pe"s/${old_version}/${new_version}/g" file1.txt
perl -i -pe"s/${old_version}/${new_version}/g" file2.txt

git add file1.txt
git add file2.txt

git status

git commit -m "$commit_string"

if [ "$advanced_script" = true ] ; then
    git push "$3"
    git checkout "$current_branch"
    git stash apply
fi
</code>```

答:
The problem was in regex pattern used in the perl call. Changing it the following line has solved the problem:

perl -i -spe's/\Q$o/$n/g' -- -o="$old_version" -n="$new_version" file1.txt file2.txt

Thanks @ikegami for the solution

Body:
I wrote a script that replaces last 3 digits of a version number in a file containing a string in this format

"version-all:255.24.788"

There are 2 modes for the script: regular and advanced. Regular mode just makes the necessary changes, adds the files to git and commits them. Advanced version creates a branch to make those changes in, modifies the files, adds, commits, then returns to the original working branch.

I observe an odd behavior when running the script. The script works when ran first time, but when ran second time, it stops committing the results and tries to change the branch resulting in merge conflicts. I can't figure out why the script would only work odd number of times (first, third, fifth time) and when ran even number of times (second, fourth, sixth), fails.

I've tried changing the syntax of variables and replaced perl calls with a simple

echo "test" > file1.txt

for debugging purposes and it seems to work fine then. When adding perl commands back, the script seems to return to its odd behaviour.

#!/bin/bash
# This script replaces last 3 digits of a version number in a file
# There are 2 modes for the script
#   1. Regular - no flag needed, requires 1 argument: a version number
#   2. Advanced - flag "-a" needs to be used followed by 3 arguments: version number, push repo name, remote repo name.

advanced_script=false
version="none"

if [ "$1" = "-a" ] ; then
    advanced_script=true
fi

if [ "$advanced_script" = true ] ; then
    if [ $# -ne 4 ] ; then
        echo -e "ERROR: Please supply the following 3 arguments and try again.\n"
        echo -e "       1. New version number\n"
        echo -e "       2. Push repository name\n"
        echo -e "       3. Remote repository name\n"
        exit 1
    fi
    version="$2"
else
    if [ $# -ne 1 ] ; then
        echo -e "ERROR: Please supply version number and try again.\n"
        exit 1
    fi
    version="$1"
fi

old_version_full="version-all:255.24.788"
old_version=${old_version_full##*all:}
new_version=${old_version%.*}
new_version+=".${version}"

current_branch=$(git branch | grep \* | cut -d ' ' -f2)
commit_string="Bump the version to $version"

if [ "$advanced_script" = true ] ; then
    local_branch="new_$version"
    remote_master="$4/master"
    git stash
    git checkout -b "$local_branch" "$remote_master"
fi

perl -i -pe"s/${old_version}/${new_version}/g" file1.txt
perl -i -pe"s/${old_version}/${new_version}/g" file2.txt

git add file1.txt
git add file2.txt

git status

git commit -m "$commit_string"

if [ "$advanced_script" = true ] ; then
    git push "$3"
    git checkout "$current_branch"
    git stash apply
fi


问:
Calling a firebase cloud function from nodejs
I want to call a cloud function from firebase from another nodejs server or just a nodejs script.

My firebase function is an onCall function.

I am using https://www.npmjs.com/package/firebase-admin for interacting with firebase but it doesn't seem to have a way of calling cloud functions...

Can I do it any other way? Like a http request?

答:
In short: You have to trigger http event.

Currently, firebase does support two invoke options.

If you read through documentation here and here, there is always has to be some trigger.

And firebase accept http request.

Even if you use mobile app from example one, under the hood, firebase SDK will make http request.

The other option is scheduled invocations, but as I get from comments, it's not what you're looking for.