问:
Viewport for the textbox is not showing properly using singlechildscrollview in flutter
hi guys to all who can help me figure my code,

```<code>import 'package:flutter/material.dart';
import 'package:survey/widgets/widgetlist.dart';
import 'dart:ui' as ui;
class Item {
   Item(this.name);
   String name;
}

class createnewsurv extends StatefulWidget {
  @override
  _createnewsurvState createState() => _createnewsurvState();
}

class _createnewsurvState extends State<createnewsurv> {

  TextEditingController _textcontroller = new TextEditingController();
  int surveyquestionnum = 1;
  Item selectedUser;
  List<Item> users = <Item>[
     Item('Sample 1'),
     Item('Sample 2'),
     Item('Sample 3'),
     Item('Sample 4'),
  ];
  List<Item> users2 = <Item>[
    Item('Sample EMOJI 1'),
    Item('Sample EMOJI 2'),
    Item('Sample EMOJI 3'),
    Item('Sample EMOJI 4'),
  ];

  @override
  Widget _dropdownbutton (List<Item> userlist){
    return Container(
      padding: EdgeInsets.all(1),
      width: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
        border: Border.all(),
        borderRadius: BorderRadius.all(
            Radius.circular(15.0)
        ),
      ),
      child: DropdownButton<Item>(
        underline: SizedBox(),
        isExpanded: true,
        icon: Icon(Icons.arrow_drop_down),
        hint:  Text("  SELECT FROM DROPDOWN"),
        value: selectedUser,
        onChanged: (Item Value) {
          setState(() {
            selectedUser = Value;
          });
        },
        items: userlist.map((Item user) {
          return  DropdownMenuItem<Item>(
            value: user,
            child: Row(
              children: <Widget>[
                SizedBox(width: 10,),
                Text(
                  user.name,
                  style:  TextStyle(color: Colors.black),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget build(BuildContext context) {
    final ui.Size logicalSize = MediaQuery.of(context).size;
    final double _height = logicalSize.height;
    return SafeArea(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
          backgroundColor: Colors.white,
          body: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text("CREATE A NEW SURVEY ",style: txtttitsize),
                    SizedBox(height: 10),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(" SURVEY TITLE",style: txtttitsize),
                    ),
                    _dropdownbutton(users),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(" SELECT EMOJI SET",style: txtttitsize),
                    ),
                    _dropdownbutton(users2),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(" SURVEY QUESTION #$surveyquestionnum",style: txtttitsize),
                    ),
                    TextFormField(
                      autocorrect: true,
                      controller: _textcontroller,
                      maxLines: 10,
                      onSaved: (value){
                      },
                      validator: (val){
                        if(val.isEmpty){
                          return "This page Cannot be Blank!";
                        }else{
                          return null;
                        }
                      },
                      decoration: InputDecoration(
                          labelText: "QUESTION",
                          fillColor: Colors.white,
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(25)
                          )
                      ),
                    )
                  ]
              ),
            ),
          )),
    );
  }
}
</code>```

this is an incomplete code, but if you noticed and tried running this, it will show
2 dropdown widget which for some reason when i select it crash showing ''there should be exactly one item with [DropDownButton]'s Value: error,

and the next one is the textform field, which i am hoping when i wrapped it on singlescrollview when somebody type it should or let the viewport focus its screen to the textbox while typing,
but its already on the third line and its already blocked by the keyboard,

i may be wrong but how can i use singlescrollview properly on this? or if there is an alternative widget to give this textbox a chance to be viewed properly by the user while they type?

Update

This error appears after clicking any drop down button.
I updated the code with the suggested answer and its still the same for me .

答:
You can copy paste run full code below

Two _dropdownbutton use the same selectedUser cause this error

You can use  List<Item> selectedUser = [null, null]; to keep result

and pass index to function like this _dropdownbutton(users, 0)

code snippet

```<code> Widget _dropdownbutton(List<Item> userlist, int index) {
 ...
  child: DropdownButton<Item>(
        underline: SizedBox(),
        isExpanded: true,
        icon: Icon(Icons.arrow_drop_down),
        hint: Text("  SELECT FROM DROPDOWN"),
        value: selectedUser[index],
        onChanged: (Item Value) {
          setState(() {
            selectedUser[index] = Value;
          });
        },
 ...

 _dropdownbutton(users, 0),

 _dropdownbutton(users2, 1),
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
//import 'package:survey/widgets/widgetlist.dart';
import 'dart:ui' as ui;

import 'package:flutter/services.dart';

class Item {
  Item(this.name);
  String name;
}

class createnewsurv extends StatefulWidget {
  @override
  _createnewsurvState createState() => _createnewsurvState();
}

class _createnewsurvState extends State<createnewsurv> {
  TextEditingController _textcontroller = new TextEditingController();
  int surveyquestionnum = 1;
  List<Item> selectedUser = [null, null];
  List<Item> users;
  List<Item> users2;

  @override
  void initState() {
    users = <Item>[
      Item('Sample 1'),
      Item('Sample 2'),
      Item('Sample 3'),
      Item('Sample 4'),
    ];

    users2 = <Item>[
      Item('Sample EMOJI 1'),
      Item('Sample EMOJI 2'),
      Item('Sample EMOJI 3'),
      Item('Sample EMOJI 4'),
    ];
    super.initState();
  }

  @override
  Widget _dropdownbutton(List<Item> userlist, int index) {
    return Container(
      padding: EdgeInsets.all(1),
      width: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
        border: Border.all(),
        borderRadius: BorderRadius.all(Radius.circular(15.0)),
      ),
      child: DropdownButton<Item>(
        underline: SizedBox(),
        isExpanded: true,
        icon: Icon(Icons.arrow_drop_down),
        hint: Text("  SELECT FROM DROPDOWN"),
        value: selectedUser[index],
        onChanged: (Item Value) {
          setState(() {
            selectedUser[index] = Value;
          });
        },
        items: userlist.map((Item user) {
          return DropdownMenuItem<Item>(
            value: user,
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: 10,
                ),
                Text(
                  user.name,
                  style: TextStyle(color: Colors.black),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget build(BuildContext context) {
    final ui.Size logicalSize = MediaQuery.of(context).size;
    final double _height = logicalSize.height;
    return SafeArea(
      child: Scaffold(
          resizeToAvoidBottomInset: false,
          backgroundColor: Colors.white,
          body: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "CREATE A NEW SURVEY ",
                    ),
                    SizedBox(height: 10),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        " SURVEY TITLE",
                      ),
                    ),
                    _dropdownbutton(users, 0),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        " SELECT EMOJI SET",
                      ),
                    ),
                    _dropdownbutton(users2, 1),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        " SURVEY QUESTION #$surveyquestionnum",
                      ),
                    ),
                    TextFormField(
                      autocorrect: true,
                      controller: _textcontroller,
                      maxLines: 10,
                      onSaved: (value) {},
                      validator: (val) {
                        if (val.isEmpty) {
                          return "This page Cannot be Blank!";
                        } else {
                          return null;
                        }
                      },
                      decoration: InputDecoration(
                          labelText: "QUESTION",
                          fillColor: Colors.white,
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(25))),
                    )
                  ]),
            ),
          )),
    );
  }
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(child: createnewsurv()),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Body:
hi guys to all who can help me figure my code,

import 'package:flutter/material.dart';
import 'package:survey/widgets/widgetlist.dart';
import 'dart:ui' as ui;
class Item {
   Item(this.name);
   String name;
}

class createnewsurv extends StatefulWidget {
  @override
  _createnewsurvState createState() => _createnewsurvState();
}

class _createnewsurvState extends State<createnewsurv> {

  TextEditingController _textcontroller = new TextEditingController();
  int surveyquestionnum = 1;
  Item selectedUser;
  List<Item> users = <Item>[
     Item('Sample 1'),
     Item('Sample 2'),
     Item('Sample 3'),
     Item('Sample 4'),
  ];
  List<Item> users2 = <Item>[
    Item('Sample EMOJI 1'),
    Item('Sample EMOJI 2'),
    Item('Sample EMOJI 3'),
    Item('Sample EMOJI 4'),
  ];

  @override
  Widget _dropdownbutton (List<Item> userlist){
    return Container(
      padding: EdgeInsets.all(1),
      width: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
        border: Border.all(),
        borderRadius: BorderRadius.all(
            Radius.circular(15.0)
        ),
      ),
      child: DropdownButton<Item>(
        underline: SizedBox(),
        isExpanded: true,
        icon: Icon(Icons.arrow_drop_down),
        hint:  Text("  SELECT FROM DROPDOWN"),
        value: selectedUser,
        onChanged: (Item Value) {
          setState(() {
            selectedUser = Value;
          });
        },
        items: userlist.map((Item user) {
          return  DropdownMenuItem<Item>(
            value: user,
            child: Row(
              children: <Widget>[
                SizedBox(width: 10,),
                Text(
                  user.name,
                  style:  TextStyle(color: Colors.black),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget build(BuildContext context) {
    final ui.Size logicalSize = MediaQuery.of(context).size;
    final double _height = logicalSize.height;
    return SafeArea(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
          backgroundColor: Colors.white,
          body: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text("CREATE A NEW SURVEY ",style: txtttitsize),
                    SizedBox(height: 10),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(" SURVEY TITLE",style: txtttitsize),
                    ),
                    _dropdownbutton(users),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(" SELECT EMOJI SET",style: txtttitsize),
                    ),
                    _dropdownbutton(users2),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(" SURVEY QUESTION #$surveyquestionnum",style: txtttitsize),
                    ),
                    TextFormField(
                      autocorrect: true,
                      controller: _textcontroller,
                      maxLines: 10,
                      onSaved: (value){
                      },
                      validator: (val){
                        if(val.isEmpty){
                          return "This page Cannot be Blank!";
                        }else{
                          return null;
                        }
                      },
                      decoration: InputDecoration(
                          labelText: "QUESTION",
                          fillColor: Colors.white,
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(25)
                          )
                      ),
                    )
                  ]
              ),
            ),
          )),
    );
  }
}

this is an incomplete code, but if you noticed and tried running this, it will show
2 dropdown widget which for some reason when i select it crash showing ''there should be exactly one item with [DropDownButton]'s Value: error,

and the next one is the textform field, which i am hoping when i wrapped it on singlescrollview when somebody type it should or let the viewport focus its screen to the textbox while typing,
but its already on the third line and its already blocked by the keyboard,

i may be wrong but how can i use singlescrollview properly on this? or if there is an alternative widget to give this textbox a chance to be viewed properly by the user while they type?

Update

This error appears after clicking any drop down button.
I updated the code with the suggested answer and its still the same for me .

Body:
You can copy paste run full code below

Two _dropdownbutton use the same selectedUser cause this error

You can use  List<Item> selectedUser = [null, null]; to keep result

and pass index to function like this _dropdownbutton(users, 0)

code snippet

 Widget _dropdownbutton(List<Item> userlist, int index) {
 ...
  child: DropdownButton<Item>(
        underline: SizedBox(),
        isExpanded: true,
        icon: Icon(Icons.arrow_drop_down),
        hint: Text("  SELECT FROM DROPDOWN"),
        value: selectedUser[index],
        onChanged: (Item Value) {
          setState(() {
            selectedUser[index] = Value;
          });
        },
 ...

 _dropdownbutton(users, 0),

 _dropdownbutton(users2, 1),

working demo

full code

import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
//import 'package:survey/widgets/widgetlist.dart';
import 'dart:ui' as ui;

import 'package:flutter/services.dart';

class Item {
  Item(this.name);
  String name;
}

class createnewsurv extends StatefulWidget {
  @override
  _createnewsurvState createState() => _createnewsurvState();
}

class _createnewsurvState extends State<createnewsurv> {
  TextEditingController _textcontroller = new TextEditingController();
  int surveyquestionnum = 1;
  List<Item> selectedUser = [null, null];
  List<Item> users;
  List<Item> users2;

  @override
  void initState() {
    users = <Item>[
      Item('Sample 1'),
      Item('Sample 2'),
      Item('Sample 3'),
      Item('Sample 4'),
    ];

    users2 = <Item>[
      Item('Sample EMOJI 1'),
      Item('Sample EMOJI 2'),
      Item('Sample EMOJI 3'),
      Item('Sample EMOJI 4'),
    ];
    super.initState();
  }

  @override
  Widget _dropdownbutton(List<Item> userlist, int index) {
    return Container(
      padding: EdgeInsets.all(1),
      width: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
        border: Border.all(),
        borderRadius: BorderRadius.all(Radius.circular(15.0)),
      ),
      child: DropdownButton<Item>(
        underline: SizedBox(),
        isExpanded: true,
        icon: Icon(Icons.arrow_drop_down),
        hint: Text("  SELECT FROM DROPDOWN"),
        value: selectedUser[index],
        onChanged: (Item Value) {
          setState(() {
            selectedUser[index] = Value;
          });
        },
        items: userlist.map((Item user) {
          return DropdownMenuItem<Item>(
            value: user,
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: 10,
                ),
                Text(
                  user.name,
                  style: TextStyle(color: Colors.black),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget build(BuildContext context) {
    final ui.Size logicalSize = MediaQuery.of(context).size;
    final double _height = logicalSize.height;
    return SafeArea(
      child: Scaffold(
          resizeToAvoidBottomInset: false,
          backgroundColor: Colors.white,
          body: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "CREATE A NEW SURVEY ",
                    ),
                    SizedBox(height: 10),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        " SURVEY TITLE",
                      ),
                    ),
                    _dropdownbutton(users, 0),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        " SELECT EMOJI SET",
                      ),
                    ),
                    _dropdownbutton(users2, 1),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        " SURVEY QUESTION #$surveyquestionnum",
                      ),
                    ),
                    TextFormField(
                      autocorrect: true,
                      controller: _textcontroller,
                      maxLines: 10,
                      onSaved: (value) {},
                      validator: (val) {
                        if (val.isEmpty) {
                          return "This page Cannot be Blank!";
                        } else {
                          return null;
                        }
                      },
                      decoration: InputDecoration(
                          labelText: "QUESTION",
                          fillColor: Colors.white,
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(25))),
                    )
                  ]),
            ),
          )),
    );
  }
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(child: createnewsurv()),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


来源: stackexchange

问:
Deploy Nuxt.js SPA to IIS
I have a simple project using Nuxt.js building in SPA mode.

The official documentation says that you simply need to put the content of the .nuxt/dist folder after a npm run build to the root of your hosting dir.

Here is what the npm run build generates for me:

```<code>.nuxt/dist/
┣ client/
┃ ┣ 3cf8385bf6a4566ef93b.js
┃ ┣ 7c79864121ddfa160949.js
┃ ┣ b70349e040bca7777d93.js
┃ ┣ edc78b0c0850b91edb72.js
┃ ┣ f537e3bf431bc43e1b91.js
┃ ┗ LICENSES
┗ server/
┃ ┣ client.manifest.json
┃ ┗ index.spa.html
</code>```

When I deploy this to an IIS 8.5 server, I get an error whenever I try to access the website (probably because I'm missing a web.config file or simply because IIS doesn't know how to serve this kind of app?).

How can I make this work?

I'm using nuxt@2.11.0

Thanks for your help.

答:
After creating application you just need to run below command to build the app:

```<code>npm run build
</code>```

it will create the dist folder inside of your application. point that folder in iis as a site folder path.

No need to move any folder or file anywhere.

root folder structure:

dist folder structure:

iis site detail:

make sure you assign the iis_iusrs and iusr full control permission to the site root folder.

below is the output:

ContentLicense: CC BY-SA 4.0

Title: Deploy Nuxt.js SPA to IIS

Body:
I have a simple project using Nuxt.js building in SPA mode.

The official documentation says that you simply need to put the content of the .nuxt/dist folder after a npm run build to the root of your hosting dir.

Here is what the npm run build generates for me:

.nuxt/dist/
┣ client/
┃ ┣ 3cf8385bf6a4566ef93b.js
┃ ┣ 7c79864121ddfa160949.js
┃ ┣ b70349e040bca7777d93.js
┃ ┣ edc78b0c0850b91edb72.js
┃ ┣ f537e3bf431bc43e1b91.js
┃ ┗ LICENSES
┗ server/
┃ ┣ client.manifest.json
┃ ┗ index.spa.html

When I deploy this to an IIS 8.5 server, I get an error whenever I try to access the website (probably because I'm missing a web.config file or simply because IIS doesn't know how to serve this kind of app?).

How can I make this work?

I'm using nuxt@2.11.0

Thanks for your help.

Body:
After creating application you just need to run below command to build the app:

npm run build

it will create the dist folder inside of your application. point that folder in iis as a site folder path.

No need to move any folder or file anywhere.

root folder structure:

dist folder structure:

iis site detail:

make sure you assign the iis_iusrs and iusr full control permission to the site root folder.

below is the output:


问:
Python substitute variable in SQL query
I am using Python3 and connecting to Impala DB using impala package as below:

```<code>#!/usr/bin/python3

import pandas as pd
from impala.dbapi import connect
from impala.util import as_pandas
import sys

def pull_from_dw(dw_conn, qry,qryparams):
    cur = dw_conn.cursor()
    if (qryparams is None):
        cur.execute(qry)
    else:
        cur.execute(qry,qryparams)
    custdata=as_pandas(cur)
    return custdata

x = sys.argv[1]
query_str="select * from <table_name> where <column_name> = '{}';"
print(query_str)
dw_conn = connect(host='10.xxx.xx.xx', port=21050, use_ssl=True,
    user='<username>',
    password='<password>',
    auth_mechanism='LDAP')
df =  pull_from_dw(dw_conn,query_str,x)
print(df)
</code>```

I can substitute directly by specifying .format(x) in the sql query. However, I need to variable substitution in the calling function df =  pull_from_dw(dw_conn,query_str,x) and getting error as below. Please assist:

$ /usr/bin/python3 script1.py 'abc'

impala.error.ProgrammingError: Query parameters argument should be a
  list, tuple, or dict object

答:
You are passing a string to qryparams while it takes a list tuple or dictionary. pass it the following and It should fix your issue:</p>

```<code>pull_from_dw(dw_conn, qry,[x])
</code>```

Title: Python substitute variable in SQL query

Body:
I am using Python3 and connecting to Impala DB using impala package as below:

#!/usr/bin/python3

import pandas as pd
from impala.dbapi import connect
from impala.util import as_pandas
import sys

def pull_from_dw(dw_conn, qry,qryparams):
    cur = dw_conn.cursor()
    if (qryparams is None):
        cur.execute(qry)
    else:
        cur.execute(qry,qryparams)
    custdata=as_pandas(cur)
    return custdata

x = sys.argv[1]
query_str="select * from <table_name> where <column_name> = '{}';"
print(query_str)
dw_conn = connect(host='10.xxx.xx.xx', port=21050, use_ssl=True,
    user='<username>',
    password='<password>',
    auth_mechanism='LDAP')
df =  pull_from_dw(dw_conn,query_str,x)
print(df)

I can substitute directly by specifying .format(x) in the sql query. However, I need to variable substitution in the calling function df =  pull_from_dw(dw_conn,query_str,x) and getting error as below. Please assist:

$ /usr/bin/python3 script1.py 'abc'

impala.error.ProgrammingError: Query parameters argument should be a
  list, tuple, or dict object

Body:
You are passing a string to qryparams while it takes a list tuple or dictionary. pass it the following and It should fix your issue:

pull_from_dw(dw_conn, qry,[x])


问:
Make v-text-field required based on v-radio choice
I am new to front end specially vue
in my register page, I have this v-radio-group

```<code><v-radio-group
  v-model="row"
    row
  >
  <v-radio
    label="personal"
    value="false"
    data-cy="input-individual"
  />
  <v-radio
    label="company"
    value="true"
  />
</v-radio-group>
</code>```

and I want to make the v-text-field phone number and company name required if the user choose company

```<code><v-text-field
  v-model="name"
  label="* fullname"
  :rules="requirerule"
  required
  data-cy="input-name"
/>

<v-text-field
  v-model="telephone"
    label="phone number"
    data-cy="input-telephone"
/>
<v-text-field
  v-model="companyname"
  label="company name"
  data-cy="input-companyname"
/>
</code>```

Does anyone has a solution what should I do, thank you very much

答:
You need to map the value of your v-radio-group to a model isCompany

```<code><v-radio-group v-model="isCompany" row>
  <v-radio
    label="personal"
    :value="false"
  />
  <v-radio
    label="company"
    :value="true"
  />
</v-radio-group>
</code>```

Then in your

Body:
I am new to front end specially vue
in my register page, I have this v-radio-group

<v-radio-group
  v-model="row"
    row
  >
  <v-radio
    label="personal"
    value="false"
    data-cy="input-individual"
  />
  <v-radio
    label="company"
    value="true"
  />
</v-radio-group>

and I want to make the v-text-field phone number and company name required if the user choose company

<v-text-field
  v-model="name"
  label="* fullname"
  :rules="requirerule"
  required
  data-cy="input-name"
/>

<v-text-field
  v-model="telephone"
    label="phone number"
    data-cy="input-telephone"
/>
<v-text-field
  v-model="companyname"
  label="company name"
  data-cy="input-companyname"
/>

Does anyone has a solution what should I do, thank you very much

Body:
You need to map the value of your v-radio-group to a model isCompany

<v-radio-group v-model="isCompany" row>
  <v-radio
    label="personal"
    :value="false"
  />
  <v-radio
    label="company"
    :value="true"
  />
</v-radio-group>

Then in your <script> methods section you need to define the validation method and set a rule to validate the text field based on the value of isCompany

data(): {
  return {
    // ...
    isCompany: false,
  }
  methods: {
    // .....
    requiredIfCompany: function(value) {
      if(this.isCompany) {
        return !!value || 'Required.';
      }
      return true;
    }
  }
}

Then on your v-text-field you need to set the rules

<v-text-field v-model="telephone"
    :rules=[requiredIfCompany]
    label="phone number"
/>


问:
Using HttpClient and HttpPost in Android with post parameters
I'm writing code for an Android application that is supposed to take data, package it as Json and post it to a web server, that in turn is supposed to respond with json.

Using a GET request works fine, but for some reason using POST all data seems to get stripped and the server does not receive anything.

Here's a snippet of the code:

```<code>HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
BasicCookieStore cookieStore = new BasicCookieStore();
httpClient.setCookieStore(cookieStore);

String uri = JSON_ADDRESS;
String result = "";
String username = "user";
String apikey = "something";
String contentType = "application/json";

JSONObject jsonObj = new JSONObject();

try {
    jsonObj.put("username", username);
    jsonObj.put("apikey", apikey);
} catch (JSONException e) {
    Log.e(TAG, "JSONException: " + e);
}

HttpPost httpPost = new HttpPost(uri);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", jsonObj.toString()));
HttpGet httpGet = null;
try {
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
    entity.setContentEncoding(HTTP.UTF_8);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);

    httpPost.setHeader("Content-Type", contentType);
    httpPost.setHeader("Accept", contentType);
} catch (UnsupportedEncodingException e) {
    Log.e(TAG, "UnsupportedEncodingException: " + e);
}

try {
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();

    if (httpEntity != null) {
        InputStream is = httpEntity.getContent();
        result = StringUtils.convertStreamToString(is);
        Log.i(TAG, "Result: " + result);
    }
} catch (ClientProtocolException e) {
    Log.e(TAG, "ClientProtocolException: " + e);
} catch (IOException e) {
    Log.e(TAG, "IOException: " + e);
}

return result;
</code>```

I think I have followed the general guidelines on how to create the parameters and post them, but apparently not.

Any help or pointers to where I can find a solution, are very welcome at this point (after spending a few hours realizing no post data was ever sent). The real server is running Wicket on Tomcat, but I've also tested it out on a simple PHP page, with no difference.

答:
have you tried doing it without the JSON object and just passed two basicnamevaluepairs?
also, it might have something to do with your serversettings

Update:
this is a piece of code I use:

```<code>InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate));

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(connection);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d("HTTP", "HTTP: OK");
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm writing code for an Android application that is supposed to take data, package it as Json and post it to a web server, that in turn is supposed to respond with json.

Using a GET request works fine, but for some reason using POST all data seems to get stripped and the server does not receive anything.

Here's a snippet of the code:

HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
BasicCookieStore cookieStore = new BasicCookieStore();
httpClient.setCookieStore(cookieStore);

String uri = JSON_ADDRESS;
String result = "";
String username = "user";
String apikey = "something";
String contentType = "application/json";

JSONObject jsonObj = new JSONObject();

try {
    jsonObj.put("username", username);
    jsonObj.put("apikey", apikey);
} catch (JSONException e) {
    Log.e(TAG, "JSONException: " + e);
}

HttpPost httpPost = new HttpPost(uri);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", jsonObj.toString()));
HttpGet httpGet = null;
try {
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
    entity.setContentEncoding(HTTP.UTF_8);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);

    httpPost.setHeader("Content-Type", contentType);
    httpPost.setHeader("Accept", contentType);
} catch (UnsupportedEncodingException e) {
    Log.e(TAG, "UnsupportedEncodingException: " + e);
}

try {
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();

    if (httpEntity != null) {
        InputStream is = httpEntity.getContent();
        result = StringUtils.convertStreamToString(is);
        Log.i(TAG, "Result: " + result);
    }
} catch (ClientProtocolException e) {
    Log.e(TAG, "ClientProtocolException: " + e);
} catch (IOException e) {
    Log.e(TAG, "IOException: " + e);
}

return result;

I think I have followed the general guidelines on how to create the parameters and post them, but apparently not.

Any help or pointers to where I can find a solution, are very welcome at this point (after spending a few hours realizing no post data was ever sent). The real server is running Wicket on Tomcat, but I've also tested it out on a simple PHP page, with no difference.

Body:
have you tried doing it without the JSON object and just passed two basicnamevaluepairs?
also, it might have something to do with your serversettings

Update:
this is a piece of code I use:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate));

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(connection);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d("HTTP", "HTTP: OK");
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
    }


问:
Disable the directory and file listing on web browser.Like we see all listing in source in google chrome
I am using PHP as my backend to develop the site, it contains a lot of files and directory. if the structure of my file is visible to the third person it can be easily hacked. So it is necessary to hide those directory form the user view.
I actually search many times on google  and found one case

Disable the directory listing shown in the browsers window if there is no any index.html, index.php like files like this screenshot on enabling directory listing.

Image with directory listing enable

I have successfully get rid of this problem just including these lines in the .htaccess file.

```<code>Options -Indexes
IndexIgnore *
</code>```

Now, What I actually want is not to show the directory in the source of the browser after inspecting like this image.

Directory listing showed in source console

But I don't want to show these directories to the user like https://www.bbc.com/ here I found that only (index) not other directories.

Thanks in advance ..

答:
How you enable directory listing depends on the type of server you're running. See the examples below and click on each server type for more information.

Apache: If apache detects any files in the directory such as:

index.html, index.htm, index.php, welcome.html, default.php, etc., it will load them and not display the list of files.

This list can be configured with the DirectoryIndex directive.

If none of these files are detected, the directory listing will be shown as long as the +Indexes option is set for the directory. For example:

```<code><Directory /usr/local/apache2/htdocs/listme>
  Options +Indexes
</Directory>
</code>```

Nginx: Add autoindex on; for the desired directory in your config file.

IIS: On the command line, enter:

```<code>appcmd set config /section:directoryBrowse /enabled:true
</code>```

Body:
I am using PHP as my backend to develop the site, it contains a lot of files and directory. if the structure of my file is visible to the third person it can be easily hacked. So it is necessary to hide those directory form the user view.
I actually search many times on google  and found one case

Disable the directory listing shown in the browsers window if there is no any index.html, index.php like files like this screenshot on enabling directory listing.

Image with directory listing enable

I have successfully get rid of this problem just including these lines in the .htaccess file.

Options -Indexes
IndexIgnore *

Now, What I actually want is not to show the directory in the source of the browser after inspecting like this image.

Directory listing showed in source console

But I don't want to show these directories to the user like https://www.bbc.com/ here I found that only (index) not other directories.

Thanks in advance ..

Body:
How you enable directory listing depends on the type of server you're running. See the examples below and click on each server type for more information.

Apache: If apache detects any files in the directory such as:

index.html, index.htm, index.php, welcome.html, default.php, etc., it will load them and not display the list of files.

This list can be configured with the DirectoryIndex directive.

If none of these files are detected, the directory listing will be shown as long as the +Indexes option is set for the directory. For example:

<Directory /usr/local/apache2/htdocs/listme>
  Options +Indexes
</Directory>

Nginx: Add autoindex on; for the desired directory in your config file.

IIS: On the command line, enter:

appcmd set config /section:directoryBrowse /enabled:true


问:
How to read images from a specific folder?
I have created a group folder in my Xcode project named USER_PHOTO

Then I store some images into that folder.

In my application, I open the camera mode.

How can I save the captured images into the "USER_PHOTO" folder? Also, how can I read all images from the folder?

Please give me ideas to solve these issues. Thanks in advance.

答:
I think you have a misconception there. The groups and folders you make in Xcode do not appear in your app when running on the iOS device. You can see what happens by finding the built app in the Simulator's folders (under ~/Library/Application Support/iPhone Simulator/" and look into its app package. You'll see that all your file are in there in one big folder. This is different from Mac app, where you have several folders for Resources, code, etc.).

So, to read the images, you simply read them from your app's folder. Use NSBundle pathForResource:ofType: to get to them. The "resource" path in iOS is identical to your app's folder.

Also, on iOS, your app can then only write to a few folders next to its .app package, e.g. "Documents". You can see that in the Simulator folders as well.

The NSBundle class offers functions to get you the paths to these folders.

You can then also set up your app (thru a plist key) to have the Documents folder visible in iTunes so that you can then copy the stored files to your Mac/PC via iTunes.


问:
How to edit rows from DataGridView? MS Access Database
Seems that this is the only query that I don't know, and don't understand. I've set a Query for my Edit Button and here's the code.

```<code>ExecuteQuery("Update ICT11 set [Author] = '" & AuthorTxt.Text & "', [Publisher] = '" & PublisherTxt.Text & "', [Subject Code] = '" & SubcodeTxt.Text & "', [Price] = '" & PriceTxt.Text & "', [DiscountAmount] = '" & DiscountTxt.Text & "' Where [Book Name] = '" & BooknameTxt.Text & "'")
</code>```

Also this is the Module for connecting to the Database

```<code>Module SQLDatabase
Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Anthony\Desktop\BookSelection\DataBase\BookListUE.accdb"
Public myConnection As OleDbConnection = New OleDbConnection(provider)
Public sql As String
Public cmd As OleDbCommand
Public da As OleDbDataAdapter = New OleDbDataAdapter
Public dt As New DataTable
Function ExecuteQuery(ByVal Query As String) As DataTable

    Dim sqlDT As New DataTable

    Dim sqlCon As New OleDbConnection(provider)
    Dim sqlDA As New OleDbDataAdapter(Query, sqlCon)
    Dim sqlCB As New OleDbCommandBuilder(sqlDA)

    sqlDA.Fill(sqlDT)
    Return sqlDT

End Function
</code>```

End Module

The functions on the Edit button seem to work fine as I don't encountered any Exceptions. However it doesn't really update the database, together with DataGridView.

答:
You are going about this in completely the wrong way.  You use a data adapter to populate a DataTable and bind that to the grid.  Any changes the user makes locally should be made to that DataTable.

If they edit via the grid, that happens automatically.  If they edit via TextBoxes and the like then those changes can still be pushed to the DataTable automatically if you bind the TextBoxes as well.  Otherwise, you should manually update the DataTable with the data from the TextBoxes.  Here's an example of binding to both the grid and the TextBoxes:

BindingSource1.DataSource = myDataTable
DataGridView1.DataSource = BindingSource1
TextBox1.DataBindings.Add("Text", BindingSource1, "Column1")
TextBox2.DataBindings.Add("Text", BindingSource1, "Column2")
```

<p>If you do that then selecting a row in the grid will automatically populate the <code>TextBoxes</code> with the data for that row.  Any edits made in the <code>TextBoxes</code> will be reflected in the grid when you navigate to another row.  If you weren't binding then you would copy data from the grid to the <code>TextBoxes</code>:</p>

<pre class="lang-vb prettyprint-override"><code>Dim row = DirectCast(BindingSource1.Current, DataRowView)

TextBox1.Text = CStr(row("Column1"))
TextBox2.Text = CStr(row("Column2"))
</code>```

and then back again:

Dim row = DirectCast(BindingSource1.Current, DataRowView)

row("Column1") = TextBox1.Text
row("Column2") = TextBox2.Text
```

<p>Note the use of the <code>BindingSource</code>, which is intended to be a one-stop-shop for accessing and manipulating bound data.  Note also that, when you bind a <code>DataTable</code>, the data actually comes from its <code>DefaultView</code> property, which is type <code>DataView</code>, rather than its <code>Rows</code> property, which is type <code>DataRowCollection</code>.  For that reason, each item is a <code>DataRowView</code> rather than a <code>DataRow</code>.  Also, note that you may not be able to use the <code>Current</code> item when copying the changes back, depending on when/where you do it.  If the selection has already changed by that point, you will have to remember the row that is being edited by assigning it to a field:</p>

<pre class="lang-vb prettyprint-override"><code>Private editingRow As DataRowView

'...

If editingRow IsNot Nothing Then
    editingRow("Column1") = TextBox1.Text
    editingRow("Column2") = TextBox2.Text
End If

editingRow = DirectCast(BindingSource1.Current, DataRowView)

TextBox1.Text = CStr(editingRow("Column1"))
TextBox2.Text = CStr(editingRow("Column2"))
</code>```

You can make as many changes as you like to the DataTable before saving, i.e. you can but you don't have to save after each edit.  Once you're ready to save, you use a data adapter - preferably the same one but not necessarily - to save the changes from the DataTable to the database by calling Update.  There's no "refreshing" to be done on the grid because it already reflects the changes in the bound DataTable before they are saved.

Here are some examples I wrote some time ago that may help you:

http://www.vbforums.com/showthread.php?469872

http://www.vbforums.com/showthread.php?469518

In all the ADO.NET code in the first thread, note the use of parameters rather than string concatenation to get values into SQL code.  To learn why and how to do that, check this out:

http://jmcilhinney.blogspot.com/2009/08/using-parameters-in-adonet.html

Body:
Seems that this is the only query that I don't know, and don't understand. I've set a Query for my Edit Button and here's the code.

ExecuteQuery("Update ICT11 set [Author] = '" & AuthorTxt.Text & "', [Publisher] = '" & PublisherTxt.Text & "', [Subject Code] = '" & SubcodeTxt.Text & "', [Price] = '" & PriceTxt.Text & "', [DiscountAmount] = '" & DiscountTxt.Text & "' Where [Book Name] = '" & BooknameTxt.Text & "'")

Also this is the Module for connecting to the Database

Module SQLDatabase
Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Anthony\Desktop\BookSelection\DataBase\BookListUE.accdb"
Public myConnection As OleDbConnection = New OleDbConnection(provider)
Public sql As String
Public cmd As OleDbCommand
Public da As OleDbDataAdapter = New OleDbDataAdapter
Public dt As New DataTable
Function ExecuteQuery(ByVal Query As String) As DataTable

    Dim sqlDT As New DataTable

    Dim sqlCon As New OleDbConnection(provider)
    Dim sqlDA As New OleDbDataAdapter(Query, sqlCon)
    Dim sqlCB As New OleDbCommandBuilder(sqlDA)

    sqlDA.Fill(sqlDT)
    Return sqlDT

End Function

End Module

The functions on the Edit button seem to work fine as I don't encountered any Exceptions. However it doesn't really update the database, together with DataGridView.

Body:
You are going about this in completely the wrong way.  You use a data adapter to populate a DataTable and bind that to the grid.  Any changes the user makes locally should be made to that DataTable.

If they edit via the grid, that happens automatically.  If they edit via TextBoxes and the like then those changes can still be pushed to the DataTable automatically if you bind the TextBoxes as well.  Otherwise, you should manually update the DataTable with the data from the TextBoxes.  Here's an example of binding to both the grid and the TextBoxes:

BindingSource1.DataSource = myDataTable
DataGridView1.DataSource = BindingSource1
TextBox1.DataBindings.Add("Text", BindingSource1, "Column1")
TextBox2.DataBindings.Add("Text", BindingSource1, "Column2")

If you do that then selecting a row in the grid will automatically populate the TextBoxes with the data for that row.  Any edits made in the TextBoxes will be reflected in the grid when you navigate to another row.  If you weren't binding then you would copy data from the grid to the TextBoxes:

Dim row = DirectCast(BindingSource1.Current, DataRowView)

TextBox1.Text = CStr(row("Column1"))
TextBox2.Text = CStr(row("Column2"))

and then back again:

Dim row = DirectCast(BindingSource1.Current, DataRowView)

row("Column1") = TextBox1.Text
row("Column2") = TextBox2.Text

Note the use of the BindingSource, which is intended to be a one-stop-shop for accessing and manipulating bound data.  Note also that, when you bind a DataTable, the data actually comes from its DefaultView property, which is type DataView, rather than its Rows property, which is type DataRowCollection.  For that reason, each item is a DataRowView rather than a DataRow.  Also, note that you may not be able to use the Current item when copying the changes back, depending on when/where you do it.  If the selection has already changed by that point, you will have to remember the row that is being edited by assigning it to a field:

Private editingRow As DataRowView

'...

If editingRow IsNot Nothing Then
    editingRow("Column1") = TextBox1.Text
    editingRow("Column2") = TextBox2.Text
End If

editingRow = DirectCast(BindingSource1.Current, DataRowView)

TextBox1.Text = CStr(editingRow("Column1"))
TextBox2.Text = CStr(editingRow("Column2"))

You can make as many changes as you like to the DataTable before saving, i.e. you can but you don't have to save after each edit.  Once you're ready to save, you use a data adapter - preferably the same one but not necessarily - to save the changes from the DataTable to the database by calling Update.  There's no "refreshing" to be done on the grid because it already reflects the changes in the bound DataTable before they are saved.

Here are some examples I wrote some time ago that may help you:

http://www.vbforums.com/showthread.php?469872

http://www.vbforums.com/showthread.php?469518

In all the ADO.NET code in the first thread, note the use of parameters rather than string concatenation to get values into SQL code.  To learn why and how to do that, check this out:

http://jmcilhinney.blogspot.com/2009/08/using-parameters-in-adonet.html


问:
Tkinter Scale Widget -- Continuous Operation
Newbie question:  How to make a tkinter scale operate continuously so that whenever the value is changed, the new value is written (to I2C or to a file) and this repeats until the user terminates operation of the overall program (there will need to be multiple scale controls that are operational on the GUI until the program is exited by user).  The purpose is to keep sending volume values as changed by the slider.  I've had no problem with buttons, text entry, radiobuttons, but I just don't see what I need to add to accomplish this. Here is code:

```<code>from tkinter import *  # Python 3
from math import log10

root = Tk()
root.title("Fidelity Science Audio Control GUI")
root.geometry("500x500")
Volume = IntVar
Vol = Scale(root, variable=Volume, from_=0, to=100, tickinterval=10, orient=VERTICAL,
       length=400, width=20, borderwidth=10, background="light blue", foreground="black",
       troughcolor="light blue", label="Volume")
Vol.set(50)
Vol.grid(row=10, column=1)
if Vol.get() > 0:
    Volume = Vol.get()
    LogVolume = log10(Volume)
    print("Volume = ", Volume)
    print("Value sent To I2C =", LogVolume)

root.mainloop()
</code>```

Do I need to use a loop function like while or if?  Thanks!

答:
You can use the callback associated to the Scale via command option to send the volume to I2C when the value of the Scale is changed:

```<code>from tkinter import *  # Python 3
from math import log10

def on_volume_change(volume):
    if volume > 0:
        LogVolume = log10(volume)
        print("Volume =", volume)
        print("Value sent to I2C =", LogVolume)
        # send the volume to I2C

root = Tk()
root.title("Fidelity Science Audio Control GUI")
root.geometry("500x500")

Volume = IntVar(value=50)
Vol = Scale(root, variable=Volume, from_=0, to=100, tickinterval=10, orient=VERTICAL,
            length=400, width=20, borderwidth=10, background="light blue", foreground="black",
            troughcolor="light blue", label="Volume", command=on_volume_change)
Vol.grid(row=10, column=1)

# send the initial volume
on_volume_change(Volume.get())

root.mainloop()
</code>```

Body:
Newbie question:  How to make a tkinter scale operate continuously so that whenever the value is changed, the new value is written (to I2C or to a file) and this repeats until the user terminates operation of the overall program (there will need to be multiple scale controls that are operational on the GUI until the program is exited by user).  The purpose is to keep sending volume values as changed by the slider.  I've had no problem with buttons, text entry, radiobuttons, but I just don't see what I need to add to accomplish this. Here is code:

from tkinter import *  # Python 3
from math import log10

root = Tk()
root.title("Fidelity Science Audio Control GUI")
root.geometry("500x500")
Volume = IntVar
Vol = Scale(root, variable=Volume, from_=0, to=100, tickinterval=10, orient=VERTICAL,
       length=400, width=20, borderwidth=10, background="light blue", foreground="black",
       troughcolor="light blue", label="Volume")
Vol.set(50)
Vol.grid(row=10, column=1)
if Vol.get() > 0:
    Volume = Vol.get()
    LogVolume = log10(Volume)
    print("Volume = ", Volume)
    print("Value sent To I2C =", LogVolume)

root.mainloop()

Do I need to use a loop function like while or if?  Thanks!

Body:
You can use the callback associated to the Scale via command option to send the volume to I2C when the value of the Scale is changed:

from tkinter import *  # Python 3
from math import log10

def on_volume_change(volume):
    if volume > 0:
        LogVolume = log10(volume)
        print("Volume =", volume)
        print("Value sent to I2C =", LogVolume)
        # send the volume to I2C

root = Tk()
root.title("Fidelity Science Audio Control GUI")
root.geometry("500x500")

Volume = IntVar(value=50)
Vol = Scale(root, variable=Volume, from_=0, to=100, tickinterval=10, orient=VERTICAL,
            length=400, width=20, borderwidth=10, background="light blue", foreground="black",
            troughcolor="light blue", label="Volume", command=on_volume_change)
Vol.grid(row=10, column=1)

# send the initial volume
on_volume_change(Volume.get())

root.mainloop()


问:
Multi-row writing of HEX-BIN conversion in a column with openpyxl (python)
My goal is to convert the cell's value (for each row in a certain range in column E) from HEX to BIN and write the BIN in column N for each row. There is no problem with the conversion itself as well as writing the BIN value to a certain cell. But I have issues with the iteration through the rows. Just to clarify: I want the HEX code in E1 printed in BIN code in N1, the value in E2 being printed in N2, and so on

```<code>A  B  C D  E  F  G  H  I  J  K  L  M  N
           90                         10010000
           8A                         10001010
           ..                         ....
</code>```

Here is my code:

```<code>theFile = openpyxl.load_workbook('T013.xlsx')
allSheetNames = theFile.sheetnames
print("All sheet names {} " .format(theFile.sheetnames))
sheet = theFile.active

for row in sheet.iter_rows(min_row=1, max_row=1210,values_only = True):
    for cell in sheet["E"]:
        if cell.value is None:
            print("Blank")
        else:
            inputHEX = str(cell.value)
            res = "{0:08b}".format(int(inputHEX,16))
            print(res)
            for x in sheet["N1:N1210"]:
                sheet.cell(row=x, column=1).value = str(res) #same error as with res without str
theFile.save("C:\\Users\\...\\Adapted_T013.xlsx")
</code>```

The error that I get is:

```<code>C:\Users\...\Desktop\Practical Part\CAN Python>python ExcelDecode.py
All sheet names ['T013']
Blank
11100001
Traceback (most recent call last):
  File "ExcelDecode.py", line 42, in <module>
    sheet.cell(row=x, column=1).value = res
  File "C:\Users\...\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl-3.0.3-py3.8.egg\openpyxl\worksheet\worksheet.py", line 235, in cell
TypeError: '<' not supported between instances of 'tuple' and 'int'`
</code>```

I tried using a tuple converting function but that did not change the outcome.

It would be great if you could show me a way to overcome this error. Thank you!

答:
Correct Implementation:

```<code>theFile = openpyxl.load_workbook('T013.xlsx')
allSheetNames = theFile.sheetnames
print("All sheet names {} " .format(theFile.sheetnames))
sheet = theFile.active

for row in sheet.iter_rows(min_row=1, max_row=1210,values_only = True):
    for cell in sheet["E"]:
        if cell.value is not None:
            inputHEX = str(cell.value)
            res = "{0:08b}".format(int(inputHEX,16))
            sheet.cell(row=cell.row, column=14).value = res
    break
theFile.save("C:\\Users\\..\\Adapted_T013.xlsx")
</code>```

Body:
My goal is to convert the cell's value (for each row in a certain range in column E) from HEX to BIN and write the BIN in column N for each row. There is no problem with the conversion itself as well as writing the BIN value to a certain cell. But I have issues with the iteration through the rows. Just to clarify: I want the HEX code in E1 printed in BIN code in N1, the value in E2 being printed in N2, and so on

A  B  C D  E  F  G  H  I  J  K  L  M  N
           90                         10010000
           8A                         10001010
           ..                         ....

Here is my code:

theFile = openpyxl.load_workbook('T013.xlsx')
allSheetNames = theFile.sheetnames
print("All sheet names {} " .format(theFile.sheetnames))
sheet = theFile.active

for row in sheet.iter_rows(min_row=1, max_row=1210,values_only = True):
    for cell in sheet["E"]:
        if cell.value is None:
            print("Blank")
        else:
            inputHEX = str(cell.value)
            res = "{0:08b}".format(int(inputHEX,16))
            print(res)
            for x in sheet["N1:N1210"]:
                sheet.cell(row=x, column=1).value = str(res) #same error as with res without str
theFile.save("C:\\Users\\...\\Adapted_T013.xlsx")

The error that I get is:

C:\Users\...\Desktop\Practical Part\CAN Python>python ExcelDecode.py
All sheet names ['T013']
Blank
11100001
Traceback (most recent call last):
  File "ExcelDecode.py", line 42, in <module>
    sheet.cell(row=x, column=1).value = res
  File "C:\Users\...\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl-3.0.3-py3.8.egg\openpyxl\worksheet\worksheet.py", line 235, in cell
TypeError: '<' not supported between instances of 'tuple' and 'int'`

I tried using a tuple converting function but that did not change the outcome.

It would be great if you could show me a way to overcome this error. Thank you!

Body:
Correct Implementation:

theFile = openpyxl.load_workbook('T013.xlsx')
allSheetNames = theFile.sheetnames
print("All sheet names {} " .format(theFile.sheetnames))
sheet = theFile.active

for row in sheet.iter_rows(min_row=1, max_row=1210,values_only = True):
    for cell in sheet["E"]:
        if cell.value is not None:
            inputHEX = str(cell.value)
            res = "{0:08b}".format(int(inputHEX,16))
            sheet.cell(row=cell.row, column=14).value = res
    break
theFile.save("C:\\Users\\..\\Adapted_T013.xlsx")


问:
Does VS 2017 allow two datasets for an rdlc report?
I have a framework for my applications that hold reports that are printed from the application. I have one report that I'm trying to add a second dataset to but I keep getting the error "A data source instance has not been supplied for the data source 'DataSetTwo'". Is it impossible to add a second dataset to a report?

The reason I'm adding a second data source is I have one that will populate nearly all information on the report and then the second is going to be used for a tablix in the report. I can't use the first dataset because for some reason the group by is not working on the SQL statement so I'm going to add a new dataset with less fields so the group by isn't a problem.

答:
The error

A data source instance has not been supplied for the data source 'DataSetTwo'

indicate you had not supply the data source.

When you generate the report, did you supply the second dataset?

It should look something like this:

```<code>ReportViewer.LocalReport.DataSources.Clear();
ReportDataSource rd1 = new ReportDataSource("DataSetOne", dataset1);
ReportDataSource rd2 = new ReportDataSource("DataSetTwo", dataset2);
ReportViewer.LocalReport.DataSources.Add(rd1);
ReportViewer.LocalReport.DataSources.Add(rd2);
ReportViewer.LocalReport.Refresh();
</code>```

Body:
The error

A data source instance has not been supplied for the data source 'DataSetTwo'

indicate you had not supply the data source.

When you generate the report, did you supply the second dataset?

It should look something like this:

ReportViewer.LocalReport.DataSources.Clear();
ReportDataSource rd1 = new ReportDataSource("DataSetOne", dataset1);
ReportDataSource rd2 = new ReportDataSource("DataSetTwo", dataset2);
ReportViewer.LocalReport.DataSources.Add(rd1);
ReportViewer.LocalReport.DataSources.Add(rd2);
ReportViewer.LocalReport.Refresh();


问:
C# Proxy with username and password
I set up a proxy instance and used it with a webrequest object.

```<code>        WebProxy a = new WebProxy("ip:port", true);
        proxy.Credentials = new NetworkCredential("username", "password");

        WebRequest b = WebRequest.Create("webpage url");
        b.Proxy = proxy;

        WebResponse c = req.GetResponse();

        StreamReader d = new StreamReader(c.GetResponseStream());

        d.ReadToEnd();//web page source
</code>```

Works as it should, but I want to display the page in a web browser control without loss of information and design. If I set my control's document text to the source that was just downloaded. It has very bad formatting.

edit: Is there a way for me to apply the proxy object to the web browser control itself?

答:
edit The WebBrowser control just uses IE's settings, so you don't have to set the proxy yourself. See http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/f4dc3550-f213-41ff-a17d-95c917bed027/ how to set the IE proxy in code.

Well the problem here is that the HTML that you've received via the WebRequest contains relative paths to the CSS files that are not present in the current context. You can modify the HTML, by adding the following tag in the  section:

```<code><base href="http://domainname.com/" />
</code>```

After that the WebBrowser control resolves the relative CSS paths to the domain in this tag.

OwnerDisplayName: Anon

LastEditorDisplayName: Anon

Title: C# Proxy with username and password

Body:
I set up a proxy instance and used it with a webrequest object.

        WebProxy a = new WebProxy("ip:port", true);
        proxy.Credentials = new NetworkCredential("username", "password");

        WebRequest b = WebRequest.Create("webpage url");
        b.Proxy = proxy;

        WebResponse c = req.GetResponse();

        StreamReader d = new StreamReader(c.GetResponseStream());

        d.ReadToEnd();//web page source

Works as it should, but I want to display the page in a web browser control without loss of information and design. If I set my control's document text to the source that was just downloaded. It has very bad formatting.

edit: Is there a way for me to apply the proxy object to the web browser control itself?

Body:
edit The WebBrowser control just uses IE's settings, so you don't have to set the proxy yourself. See http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/f4dc3550-f213-41ff-a17d-95c917bed027/ how to set the IE proxy in code.

Well the problem here is that the HTML that you've received via the WebRequest contains relative paths to the CSS files that are not present in the current context. You can modify the HTML, by adding the following tag in the <head> section:

<base href="http://domainname.com/" />

After that the WebBrowser control resolves the relative CSS paths to the domain in this tag.


问:
Cannot use Requests-Module on AWS Lambda
I need to do a rest-call within a python script, that runs once per day.
I can't pack the "requests" package into my python-package using the AWS Lambdas. I get the error: "Unable to import module 'lambda_function': No module named lambda_function"

I broke it down to the hello_world predefined script. I can pack it into a zip and upload it. Everything works. As soon as I put "import requests" into the file, I get this error.

Here is what I already did:

The permissions of the zip and the project folder (including subfolders) are set to `chmod 777`. So permissions shouldn't be a problem.

The script itself is within the root folder. When you open the zip file, you directly see it.

I installed the requests package into the root-folder of the project using `sudo pip install requests -t PATH_TO_ROOT_FOLDER`

The naming of everything looks like this:

zip-file: lambda_function.zip

py-file: lambda_function.py

handler method: lambda_handler(event, context)

handler-definition in the "webconfig: lambda_function.lambda_handler

The file I want to run in the end looks like this:

```<code>import requests
import json

def lambda_handler(event, context):
    url = 'xxx.elasticbeanstalk.com/users/login'
    headers = {"content-type": "application/json", "Authorization": "Basic Zxxxxxxxxx3NjxxZxxxxzcw==" }
    response = requests.put(url, headers=headers, verify=False)
    return 'hello lambda_handler'
</code>```

I'm glad for ANY kind of help. I already used multiple hours on this issue.

答:
If you're working with Python on AWS Lambda, and need to use requests, you better use urllib3, it is currently supported on AWS Lambda and you can import it directly, check the example on urllib3 site.

import urllib3

http = urllib3.PoolManager()
r = http.request('GET', 'http://httpbin.org/robots.txt')

r.data
# b'User-agent: *\nDisallow: /deny\n'
r.status
# 200
```

Body:
I need to do a rest-call within a python script, that runs once per day.
I can't pack the "requests" package into my python-package using the AWS Lambdas. I get the error: "Unable to import module 'lambda_function': No module named lambda_function"

I broke it down to the hello_world predefined script. I can pack it into a zip and upload it. Everything works. As soon as I put "import requests" into the file, I get this error.

Here is what I already did:

The permissions of the zip and the project folder (including subfolders) are set to `chmod 777`. So permissions shouldn't be a problem.

The script itself is within the root folder. When you open the zip file, you directly see it.

I installed the requests package into the root-folder of the project using `sudo pip install requests -t PATH_TO_ROOT_FOLDER`

The naming of everything looks like this:

zip-file: lambda_function.zip

py-file: lambda_function.py

handler method: lambda_handler(event, context)

handler-definition in the "webconfig: lambda_function.lambda_handler

The file I want to run in the end looks like this:

import requests
import json

def lambda_handler(event, context):
    url = 'xxx.elasticbeanstalk.com/users/login'
    headers = {"content-type": "application/json", "Authorization": "Basic Zxxxxxxxxx3NjxxZxxxxzcw==" }
    response = requests.put(url, headers=headers, verify=False)
    return 'hello lambda_handler'

I'm glad for ANY kind of help. I already used multiple hours on this issue.


问:
F# Add element created in a for loop to a list
I want to add an element to a list. The elements will be created inside of a for loop. What I currently have is

```<code>let MaxCubeVolume tpList =
    let list1 = []
    printfn "%A" list1
    for l,w,h in tpList do
        let vol = CubeVolume l w h
        let list = vol::list1
        printfn "%A" list
</code>```

Where list1 is the main list I am trying to add to, and list is what I am trying to use to add to that list. CubeVolume is working, it takes 3 floats and returns the volume of a cube. tpList is a list of tuples which contain 3 floats. Where I'm lost is how I add the vol to the main list?

答:
F# lists are immutable. You can't "change" them. You don't "add" elements to them. You can only create a new list out of the old one (but the old one remains unchanged and still available for use).

But this is the wrong frame of mind for functional programming. In functional programming you don't compute the result by repeatedly modifying data structures. Instead, you compose larger data structures out of smaller ones, or by using (and composing) primitive functions that do it for you.

In particular, if you have a list of, say, hypothetically, triples, and you have a function that can transform one such triple into, say, hypothetically, a number, and you'd like to make yourself a list of those numbers - that's a very well known primitive operation called map:

```<code>let tripleToNumber (l, w, h) = CubeVolume l w h
let list1 = List.map tripleToNumber tpList
</code>```

Or you can specify the transforming function inline, without giving it a separate name:

```<code>let list1 = List.map (fun (l, w, h) -> CubeVolume l w h) tpList
</code>```

And then you can use the |> operator to rearrange the parameters of List.map, just to make it look a bit nicer:

```<code>let list1 = tpList |> List.map (fun (l, w, h) -> CubeVolume l w h)
</code>```

Or, alternatively, you can use F# list comprehensions, which are syntactic sugar: they're doing the same thing under the hood, but have a (arguably) better look:

```<code>let list1 = [for (l, w, h) in tpList -> CubeVolume l w h]
</code>```

An important thing to note here that neither of the above snippets actually change any data in place. Both of them generate a new datum by transforming an old one.

Body:
I want to add an element to a list. The elements will be created inside of a for loop. What I currently have is

let MaxCubeVolume tpList =
    let list1 = []
    printfn "%A" list1
    for l,w,h in tpList do
        let vol = CubeVolume l w h
        let list = vol::list1
        printfn "%A" list

Where list1 is the main list I am trying to add to, and list is what I am trying to use to add to that list. CubeVolume is working, it takes 3 floats and returns the volume of a cube. tpList is a list of tuples which contain 3 floats. Where I'm lost is how I add the vol to the main list?

Body:
F# lists are immutable. You can't "change" them. You don't "add" elements to them. You can only create a new list out of the old one (but the old one remains unchanged and still available for use).

But this is the wrong frame of mind for functional programming. In functional programming you don't compute the result by repeatedly modifying data structures. Instead, you compose larger data structures out of smaller ones, or by using (and composing) primitive functions that do it for you.

In particular, if you have a list of, say, hypothetically, triples, and you have a function that can transform one such triple into, say, hypothetically, a number, and you'd like to make yourself a list of those numbers - that's a very well known primitive operation called map:

let tripleToNumber (l, w, h) = CubeVolume l w h
let list1 = List.map tripleToNumber tpList

Or you can specify the transforming function inline, without giving it a separate name:

let list1 = List.map (fun (l, w, h) -> CubeVolume l w h) tpList

And then you can use the |> operator to rearrange the parameters of List.map, just to make it look a bit nicer:

let list1 = tpList |> List.map (fun (l, w, h) -> CubeVolume l w h)

Or, alternatively, you can use F# list comprehensions, which are syntactic sugar: they're doing the same thing under the hood, but have a (arguably) better look:

let list1 = [for (l, w, h) in tpList -> CubeVolume l w h]

An important thing to note here that neither of the above snippets actually change any data in place. Both of them generate a new datum by transforming an old one.


问:
Get Users and Groups from tac_plus file
I've been tasked to get users and groups from tac_plus file which is in our Linux environment.
The person before me created a python script which isn't working anymore and i'm not a python person myself.

The script basically used to output Users First Name and Last Name as well as access group

Below is the script that was created by the person. If anyone can shed some light that would be much appreshiated

```<code>#!/usr/bin/python
# v0.1 read_tacacs.py
# Read tac_plus.cfg file and grep username/full_name/access type into column list.

from datetime import datetime

i = datetime.now()

user_name = []
full_name = []
group_access = []

with open('/usr/local/etc/tac_plus.cfg', 'r') as searchfile:
        for line in searchfile:
                if 'user =' in line:
                        user_name.append(line.split()[2])
                if 'Full Name:' in line:
                        full_name.append(line.split()[3]+ ' ' + line.split()[4])
                if 'member' in line:
                        if '@all' in line:
                                line = line.split()[2]
                                group_access.append(line.replace("@all",""))
                                #group_access.append(line)
                                #group_access.append(line.split()[2])

print '{0:20} {1:25} {2}'.format('TACACSID','Full Name', 'Access')

for x in range(len(user_name)):
        print '{0:20} {1:25} {2}'.format(user_name[x], full_name[x], group_access[x])

print '\nDate Generated: ' + i.strftime('%d/%m/%Y - %H:%M:%S')

searchfile.closed
</code>```

Below is the error i get.

Traceback (most recent call last):
  File "./read_tacacs.py", line 20, in
    full_name.append(line.split()[3]+ ' ' + line.split()[4])
IndexError: list index out of range

Any help would be much appreshiated

Thank you in advance

Ravi

答: it means that line match "'Full Name:' " in the file /usr/local/etc/tac_plus.cfg, may not contain either 3rd row or 4th row element. you may need check file /usr/local/etc/tac_plus.cfg for investigate.</p>

Title: Get Users and Groups from tac_plus file

Body:
I've been tasked to get users and groups from tac_plus file which is in our Linux environment.
The person before me created a python script which isn't working anymore and i'm not a python person myself.

The script basically used to output Users First Name and Last Name as well as access group

Below is the script that was created by the person. If anyone can shed some light that would be much appreshiated

#!/usr/bin/python
# v0.1 read_tacacs.py
# Read tac_plus.cfg file and grep username/full_name/access type into column list.

from datetime import datetime

i = datetime.now()

user_name = []
full_name = []
group_access = []

with open('/usr/local/etc/tac_plus.cfg', 'r') as searchfile:
        for line in searchfile:
                if 'user =' in line:
                        user_name.append(line.split()[2])
                if 'Full Name:' in line:
                        full_name.append(line.split()[3]+ ' ' + line.split()[4])
                if 'member' in line:
                        if '@all' in line:
                                line = line.split()[2]
                                group_access.append(line.replace("@all",""))
                                #group_access.append(line)
                                #group_access.append(line.split()[2])

print '{0:20} {1:25} {2}'.format('TACACSID','Full Name', 'Access')

for x in range(len(user_name)):
        print '{0:20} {1:25} {2}'.format(user_name[x], full_name[x], group_access[x])

print '\nDate Generated: ' + i.strftime('%d/%m/%Y - %H:%M:%S')

searchfile.closed

Below is the error i get.

Traceback (most recent call last):
  File "./read_tacacs.py", line 20, in
    full_name.append(line.split()[3]+ ' ' + line.split()[4])
IndexError: list index out of range

Any help would be much appreshiated

Thank you in advance

Ravi


问:
How do I increase the scrollback buffer in a running screen session?
Lets say I have a currently running screen session I am interacting with through putty.  I've realized that the scrollback buffer is too small and would like to increase it without starting a new screen session.

Is there a way to do this?

答:
```<code>WARNING: setting this value too high may cause your system to experience a significant hiccup.
The higher the value you set, the more virtual memory is allocated to the screen process when initiating the screen session.
</code>```

I set my ~/.screenrc to "defscrollback 123456789" and when I initiated a screen, my entire system froze up for a good 10 minutes before coming back to the point that I was able to kill the screen process (which was consuming 16.6GB of VIRT mem by then).

Body:
WARNING: setting this value too high may cause your system to experience a significant hiccup.
The higher the value you set, the more virtual memory is allocated to the screen process when initiating the screen session.

I set my ~/.screenrc to "defscrollback 123456789" and when I initiated a screen, my entire system froze up for a good 10 minutes before coming back to the point that I was able to kill the screen process (which was consuming 16.6GB of VIRT mem by then).


问:
CentOS8/RedHat8 - Disable AppStream modules when custom compiling?
This is a general question regarding AppStream modules in CentOS/RedHat 8. If we are custom compiling apps such as Apache or PHP, should we disable the AppStream module for that app? I don't seem to be finding any direct reference to this in documentation. Is there any benefit and/or necessity? Thanks!</p>

答:
Depending on which software you're going to install, you even might not be able to disable AppStream modules (due to dependencies or because you need a newer version of a library or so).

Whether AppStream modules are enabled or not doesn't matter except you're installing packages from such AppStream modules – especially if they overlap with your custom software: Imagine you're installing httpd from an AppStream module and you're also compiling it yourself using the same paths…the next dnf update will replace your binaries with that ones in the updated RPM package from the AppStream module.


问:
How to prevent Oracle archived redo log from filling up database server disk?
My database server's disk is getting full really quickly with archive files.
The size of the database is around 60Gb and I have about 30 Gb of free disk.

Problem is, the 30Gb get used by archived log in about a week even though my retention policy is set to REDUNDANCY 1.

```<code>RMAN> show all;

using target database control file instead of recovery catalog
RMAN configuration parameters for database with db_unique_name MYDB are:
CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
CONFIGURE BACKUP OPTIMIZATION OFF; # default
CONFIGURE DEFAULT DEVICE TYPE TO 'SBT_TAPE';
CONFIGURE CONTROLFILE AUTOBACKUP OFF; # default
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE SBT_TAPE TO '%F'; # default
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '%F'; # default
CONFIGURE DEVICE TYPE SBT_TAPE PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE SBT_TAPE TO 1; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE SBT_TAPE TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE CHANNEL DEVICE TYPE 'SBT_TAPE' PARMS  'SBT_LIBRARY=/u01/app/oracle/product/11.2.0/db_1/lib/libosbws11.so,   SBT_PARMS=(OSB_WS_PFILE=/u01/app/oracle/product/11.2.0/db_1/dbs/osbswsMYDB.ora)';
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
CONFIGURE COMPRESSION ALGORITHM 'BASIC' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE ; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO BACKED UP 1 TIMES TO 'TAPE';
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/u01/app/oracle/product/11.2.0/db_1/dbs/snapcf_MYDB.f'; # default
</code>```

So, if the flash recovery area is not cleared every week, the database server would run out of space and error ORA-00257 would be prompted.

```<code>ERROR: ORA-00257: archiver error. Connect internal only, until freed.
</code>```

Any ideas on how to resolve this issue?

答:
I wonder whether you understand the relation ship between "retention policy" of RMAN with the "action" of cleaning FRA?
Your current RETENTION POLICY is 1 means all backup (incre level 0, level 1, archive log, …) don't necessary will be marked OBSOLETE but Not deleted (they still consume storage space). OBSOLETE means they can safely but deleted but still satify your retention policy.
Solution in this case is to schedule crontab or job to automatically delete obsolete backup (rman> delete noprompt obsolete;) after each rman incre level 0 backup.
In case of deleting obsolete backup and still facing space pressure - then you have to request System Admin to increase your current FRA location (increase db_recovery_file_dest_size) or choose another location for db_recovery_file_dest init parameter.</p>

Body:
My database server's disk is getting full really quickly with archive files.
The size of the database is around 60Gb and I have about 30 Gb of free disk.

Problem is, the 30Gb get used by archived log in about a week even though my retention policy is set to REDUNDANCY 1.

RMAN> show all;

using target database control file instead of recovery catalog
RMAN configuration parameters for database with db_unique_name MYDB are:
CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
CONFIGURE BACKUP OPTIMIZATION OFF; # default
CONFIGURE DEFAULT DEVICE TYPE TO 'SBT_TAPE';
CONFIGURE CONTROLFILE AUTOBACKUP OFF; # default
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE SBT_TAPE TO '%F'; # default
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '%F'; # default
CONFIGURE DEVICE TYPE SBT_TAPE PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE SBT_TAPE TO 1; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE SBT_TAPE TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE CHANNEL DEVICE TYPE 'SBT_TAPE' PARMS  'SBT_LIBRARY=/u01/app/oracle/product/11.2.0/db_1/lib/libosbws11.so,   SBT_PARMS=(OSB_WS_PFILE=/u01/app/oracle/product/11.2.0/db_1/dbs/osbswsMYDB.ora)';
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
CONFIGURE COMPRESSION ALGORITHM 'BASIC' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE ; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO BACKED UP 1 TIMES TO 'TAPE';
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/u01/app/oracle/product/11.2.0/db_1/dbs/snapcf_MYDB.f'; # default

So, if the flash recovery area is not cleared every week, the database server would run out of space and error ORA-00257 would be prompted.

ERROR: ORA-00257: archiver error. Connect internal only, until freed.

Any ideas on how to resolve this issue?


问:
How to convert PdfContentBytes to Array of Bytes
I'm using iTextSharp DLLin asp.net.

```<code>PdfReader reader = new PdfReader(path);
        //create footer
        MemoryStream outStream = new MemoryStream();
        PdfStamper textStamp = new PdfStamper(reader, outStream);
        BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
        for (int i = 1; i <= reader.NumberOfPages; i++)
        {
            PdfContentByte pdfPageContents = textStamp.GetOverContent(i);
//How to convert the PdfContentByte  to array of bytes here?
}
</code>```

I want to convert each page of the PDF to JPEG. How to convert the PdfContentByte  to array of bytes here?

答:
You can get a byte[] of a PdfContentByte as follows:

```<code>pdfPageContents.getInternalBuffer().toByteArray();
</code>```

Body:
I'm using iTextSharp DLLin asp.net.

PdfReader reader = new PdfReader(path);
        //create footer
        MemoryStream outStream = new MemoryStream();
        PdfStamper textStamp = new PdfStamper(reader, outStream);
        BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
        for (int i = 1; i <= reader.NumberOfPages; i++)
        {
            PdfContentByte pdfPageContents = textStamp.GetOverContent(i);
//How to convert the PdfContentByte  to array of bytes here?
}

I want to convert each page of the PDF to JPEG. How to convert the PdfContentByte  to array of bytes here?

Body:
You can get a byte[] of a PdfContentByte as follows:

pdfPageContents.getInternalBuffer().toByteArray();


问:
How to write BFS function in C++?
```<code>#include <iostream>
#include <string>
#include <queue>

using namespace std;
void BFS(const string&, const string[], int[][10]);

int main()
{
    const int CAP = 10;

    string states[CAP] = { "Arizona", "California", "Idaho", "Nevada", "Oregon", "Utah", "Washington" };
    string Point;

    int matrix[CAP][CAP] =
    {
    {0,1,0,1,0,1,0},
    {1,0,0,1,1,0,0},
    {0,0,0,1,1,1,1},
    {0,1,1,1,0,0,1},
    {1,1,1,1,0,0,0},
    {0,0,1,0,1,0,0},
    {0,0,1,0,1,0,0}
    };

    BFS("California", states, matrix);

}

void BFS(const string& Point, const string states[], int matrix[][10])
{
    int SPoint = 0;
    queue<string> visited;
    queue<string> Queue;

    string temp = Point;

    visited.push(temp);
    do
    {

        for (int i = 0; i < 10; i++)
        {
            if (states[i] == temp)
            {
                SPoint = i;
            }
        }
        for (int i = 0; i < 10; i++)
        {
            if (matrix[SPoint][i] == 1)
            {
                Queue.push(states[i]);
            }
        }

        visited.push(Queue.front());
        Queue.pop();

        temp = visited.back();

    } while (!Queue.empty());

    for (int i = 0; i < 10; i++)
    {
        cout << visited.front();
        visited.pop();
    }

}
</code>```

I'm doing an exercise where I have to make a function that does Breadth-First Search and prints out the visited path. But my function wouldn't print anything. What am I doing wrong here?

Note: The matrix is alphabetical order and represents the connection between states.

My expected output: California Arizona Oregon Nevada Utah Idaho Washington

Exercise description

答:
While I won't offer a complete solution, I can help identify some of the issues the code exhibits.

Major issues

Since you have a cyclic graph, it's important to mark nodes as visited during the BFS else you'll wind up with an infinite loop (which is why nothing gets printed in your current implementation). Your visited queue could be an unordered_set. When nodes are visited, add them to the set and write a conditional to avoid visiting them again.

The adjacency matrix doesn't appear correct. Since it's an undirected graph, I would anticipate that the matrix would be mirrored from top left to bottom right, but it's not. Also, there are no self-edges in the graph yet Nevada appears to have an edge to itself in the matrix.

There's no need to loop over the adjacency matrix--you can index into it by mapping digit indexes and string names appropriately. If you do need to loop, running to 10 is out of bounds on a 7x7 matrix.

Minor issues

There's no sense in arbitrarily restricting the matrix size. Although the assignment enforces this, it's a poor design choice because the code needs to be rewritten any time you want to use a different input graph.

A matrix seems like a slightly awkward data structure here because it introduces an extra layer of indirection to translate strings into integers and back. Although the project doesn't permit it, I'd prefer using a structure like:

```<code>std::unordered_map<std::string, std::vector<std::string>> graph({
    {"California", {"Oregon", "Nevada", "Arizona"}},
    // ... more states ...
});
</code>```

Ideally, these would be Node objects with neighbor vector members instead of strings.

C++ offers std::vector and std::array which are preferable to C arrays. I assume they haven't been introduced yet in your class or aren't permitted on the assignment, but if you're stuck, you can try writing the code using them, then re-introducing your instructor's constraints after you get it working. If nothing else, it'd be a learning experience.

Avoid using namespace std;.

Reserve uppercase variable names for class names. Objects and primitives should be lowercase.

Pseudocode for BFS

This assumes the preferred data structure above; it's up to you to convert to and from strings and adjacency matrix indexes as needed.

```<code>func BFS(string start, unordered_map<string, vector<string>> graph):
    vector traversal
    queue worklist = {start}
    unordered_set visited = {start}

    while !worklist.empty():
        curr = worklist.pop_front()
        traversal.push_back(curr)

        for neighbor in graph[curr]:
            if neighbor not in visited:
                visited.insert(neighbor)
                worklist.push(neighbor)

    return traversal
</code>```

Since this is an assignment, I'll leave it at this and let you take another crack at the code. Good luck.

Title: How to write BFS function in C++?

Body:
#include <iostream>
#include <string>
#include <queue>

using namespace std;
void BFS(const string&, const string[], int[][10]);

int main()
{
    const int CAP = 10;

    string states[CAP] = { "Arizona", "California", "Idaho", "Nevada", "Oregon", "Utah", "Washington" };
    string Point;

    int matrix[CAP][CAP] =
    {
    {0,1,0,1,0,1,0},
    {1,0,0,1,1,0,0},
    {0,0,0,1,1,1,1},
    {0,1,1,1,0,0,1},
    {1,1,1,1,0,0,0},
    {0,0,1,0,1,0,0},
    {0,0,1,0,1,0,0}
    };

    BFS("California", states, matrix);

}

void BFS(const string& Point, const string states[], int matrix[][10])
{
    int SPoint = 0;
    queue<string> visited;
    queue<string> Queue;

    string temp = Point;

    visited.push(temp);
    do
    {

        for (int i = 0; i < 10; i++)
        {
            if (states[i] == temp)
            {
                SPoint = i;
            }
        }
        for (int i = 0; i < 10; i++)
        {
            if (matrix[SPoint][i] == 1)
            {
                Queue.push(states[i]);
            }
        }

        visited.push(Queue.front());
        Queue.pop();

        temp = visited.back();

    } while (!Queue.empty());

    for (int i = 0; i < 10; i++)
    {
        cout << visited.front();
        visited.pop();
    }

}

I'm doing an exercise where I have to make a function that does Breadth-First Search and prints out the visited path. But my function wouldn't print anything. What am I doing wrong here?

Note: The matrix is alphabetical order and represents the connection between states.

My expected output: California Arizona Oregon Nevada Utah Idaho Washington

Exercise description

Body:
While I won't offer a complete solution, I can help identify some of the issues the code exhibits.

Major issues

Since you have a cyclic graph, it's important to mark nodes as visited during the BFS else you'll wind up with an infinite loop (which is why nothing gets printed in your current implementation). Your visited queue could be an unordered_set. When nodes are visited, add them to the set and write a conditional to avoid visiting them again.

The adjacency matrix doesn't appear correct. Since it's an undirected graph, I would anticipate that the matrix would be mirrored from top left to bottom right, but it's not. Also, there are no self-edges in the graph yet Nevada appears to have an edge to itself in the matrix.

There's no need to loop over the adjacency matrix--you can index into it by mapping digit indexes and string names appropriately. If you do need to loop, running to 10 is out of bounds on a 7x7 matrix.

Minor issues

There's no sense in arbitrarily restricting the matrix size. Although the assignment enforces this, it's a poor design choice because the code needs to be rewritten any time you want to use a different input graph.

A matrix seems like a slightly awkward data structure here because it introduces an extra layer of indirection to translate strings into integers and back. Although the project doesn't permit it, I'd prefer using a structure like:

std::unordered_map<std::string, std::vector<std::string>> graph({
    {"California", {"Oregon", "Nevada", "Arizona"}},
    // ... more states ...
});

Ideally, these would be Node objects with neighbor vector members instead of strings.

C++ offers std::vector and std::array which are preferable to C arrays. I assume they haven't been introduced yet in your class or aren't permitted on the assignment, but if you're stuck, you can try writing the code using them, then re-introducing your instructor's constraints after you get it working. If nothing else, it'd be a learning experience.

Avoid using namespace std;.

Reserve uppercase variable names for class names. Objects and primitives should be lowercase.

Pseudocode for BFS

This assumes the preferred data structure above; it's up to you to convert to and from strings and adjacency matrix indexes as needed.

func BFS(string start, unordered_map<string, vector<string>> graph):
    vector traversal
    queue worklist = {start}
    unordered_set visited = {start}

    while !worklist.empty():
        curr = worklist.pop_front()
        traversal.push_back(curr)

        for neighbor in graph[curr]:
            if neighbor not in visited:
                visited.insert(neighbor)
                worklist.push(neighbor)

    return traversal

Since this is an assignment, I'll leave it at this and let you take another crack at the code. Good luck.