问:
How to make responsive datatable by adding panels to your left or right?
In the following example in the JS I create a basic datatable table, I easily create the functions to open and close the panels and define the data with which the table will be filled by means of a javascript variable.

In the CSS I define the styles for the left and right panels (sidebarLeft, sidebarRight), so that they occupy their position in their respective place, I add color and I add style for the position and color of their close button (closebtnLeft, closebtnRight) .

and finally in the HTML section I only add the left panel,
the main container that contains the table that will be seen at all times and the right panel.

As you can see by having a sufficient screen size for the table to be displayed complete, and pressing either the button left or right panel, the table does not become responsive keeping its size before adding the panel

show size error in the table here

$(document).ready(function() {
    $('#example').DataTable( {
        data: dataSet,
        columns: [
            { title: "Name" },
            { title: "Position" },
            { title: "Office" },
            { title: "Extn." },
            { title: "Start date" },
            { title: "Salary" }
        ],
      "searching": false,
      "lengthChange": false,
      responsive:true
    } );
} );

function openNavLeft() {
  document.getElementById("mySidebarLeft").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
}

function openNavRight() {
  document.getElementById("mySidebarRight").style.width = "250px";
  document.getElementById("main").style.marginRight = "250px";
  document.getElementById("example").style.marginRight = "250px";
}

function closeNavLeft() {
  document.getElementById("mySidebarLeft").style.width = "0";
  document.getElementById("main").style.marginLeft= "0";
}
function closeNavRight() {
  document.getElementById("mySidebarRight").style.width = "0";
  document.getElementById("main").style.marginRight= "0";
  document.getElementById("example").style.marginRight = "0";
}

var dataSet = [
    [ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800" ],
    [ "Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750" ],
    [ "Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000" ],
    [ "Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060" ],
    [ "Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700" ],
    [ "Brielle Williamson", "Integration Specialist", "New York", "4804", "2012/12/02", "$372,000" ],
    [ "Herrod Chandler", "Sales Assistant", "San Francisco", "9608", "2012/08/06", "$137,500" ],
    [ "Rhona Davidson", "Integration Specialist", "Tokyo", "6200", "2010/10/14", "$327,900" ],
    [ "Colleen Hurst", "Javascript Developer", "San Francisco", "2360", "2009/09/15", "$205,500" ],

];```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sidebarLeft {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebarRight {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebarRight .closebtnRight {
  position: absolute;
  top: 0;
  left: 25px;
  font-size: 36px;
  margin-right: 50px;
}

.sidebarLeft .closebtnLeft {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

.sidebarLeft a,.sidebarRight a {
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidebarLeft a:hover,.sidebarRight a:hover {
  color: #f1f1f1;
}

body {
  font-family: "Lato", sans-serif;
}</code>```

  ×

                                      <button class="btn fas fa-arrow-left openbtn" onclick="openNavLeft()">
                                        </button>
                                      <button class="btn fas fa-arrow-right openbtn" onclick="openNavRight()">
                                        </button>

  ×

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
<link rel = "stylesheet" href = "https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" />

<link rel = "stylesheet" href = "https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" />
<link rel = "stylesheet" href = "https://cdn.datatables.net/autofill/2.3.0/css/autoFill.dataTables.min.css" />
<link rel = "stylesheet" href = "https://cdn.datatables.net/fixedcolumns/3.2.5/css/fixedColumns.dataTables.min.css" />
<link rel = "stylesheet" href = "https://cdn.datatables.net/responsive/2.2.2/css/responsive.dataTables.min.css" />

```

I want that when you add the left or right panels, if the size of the table is not enough to show all the information, adjust the table and show the responsive mode for mobiles

attached photo of what I want to do

答:
Try recalculate the widths used by responsive after a change in the nav menu

```<code>table.responsive.recalc()
</code>```

var table;
$(document).ready(function() {
    table = $('#example').DataTable( {
        data: dataSet,
        columns: [
            { title: "Name" },
            { title: "Position" },
            { title: "Office" },
            { title: "Extn." },
            { title: "Start date" },
            { title: "Salary" }
        ],
      "searching": false,
      "lengthChange": false,
      "responsive":true
    });
});

function recalc() {
  table.responsive.recalc();
}

function openNavLeft() {
  document.getElementById("mySidebarLeft").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
  recalc();
}

function openNavRight() {
  document.getElementById("mySidebarRight").style.width = "250px";
  document.getElementById("main").style.marginRight = "250px";
  recalc();
}

function closeNavLeft() {
  document.getElementById("mySidebarLeft").style.width = "0";
  document.getElementById("main").style.marginLeft= "0";
  recalc();
}
function closeNavRight() {
  document.getElementById("mySidebarRight").style.width = "0";
  document.getElementById("main").style.marginRight= "0";
  recalc();
}

var dataSet = [
    [ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800" ],
    [ "Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750" ],
    [ "Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000" ],
    [ "Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060" ],
    [ "Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700" ],
    [ "Brielle Williamson", "Integration Specialist", "New York", "4804", "2012/12/02", "$372,000" ],
    [ "Herrod Chandler", "Sales Assistant", "San Francisco", "9608", "2012/08/06", "$137,500" ],
    [ "Rhona Davidson", "Integration Specialist", "Tokyo", "6200", "2010/10/14", "$327,900" ],
    [ "Colleen Hurst", "Javascript Developer", "San Francisco", "2360", "2009/09/15", "$205,500" ],

];```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sidebarLeft {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebarRight {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebarRight .closebtnRight {
  position: absolute;
  top: 0;
  left: 25px;
  font-size: 36px;
  margin-right: 50px;
}

.sidebarLeft .closebtnLeft {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

.sidebarLeft a,
.sidebarRight a {
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidebarLeft a:hover,
.sidebarRight a:hover {
  color: #f1f1f1;
}

body {
  font-family: "Lato", sans-serif;
}</code>```

  ×

            <button class="btn fas fa-arrow-left openbtn" onclick="openNavLeft()">
                                        </button>
            <button class="btn fas fa-arrow-right openbtn" onclick="openNavRight()">
                                        </button>

  ×

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" />

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/autofill/2.3.0/css/autoFill.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/fixedcolumns/3.2.5/css/fixedColumns.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.2/css/responsive.dataTables.min.css" />

```

Body:
In the following example in the JS I create a basic datatable table, I easily create the functions to open and close the panels and define the data with which the table will be filled by means of a javascript variable.

In the CSS I define the styles for the left and right panels (sidebarLeft, sidebarRight), so that they occupy their position in their respective place, I add color and I add style for the position and color of their close button (closebtnLeft, closebtnRight) .

and finally in the HTML section I only add the left panel,
the main container that contains the table that will be seen at all times and the right panel.

As you can see by having a sufficient screen size for the table to be displayed complete, and pressing either the button left or right panel, the table does not become responsive keeping its size before adding the panel

show size error in the table here

$(document).ready(function() {
    $('#example').DataTable( {
        data: dataSet,
        columns: [
            { title: "Name" },
            { title: "Position" },
            { title: "Office" },
            { title: "Extn." },
            { title: "Start date" },
            { title: "Salary" }
        ],
      "searching": false,
      "lengthChange": false,
      responsive:true
    } );
} );

function openNavLeft() {
  document.getElementById("mySidebarLeft").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
}

function openNavRight() {
  document.getElementById("mySidebarRight").style.width = "250px";
  document.getElementById("main").style.marginRight = "250px";
  document.getElementById("example").style.marginRight = "250px";
}

function closeNavLeft() {
  document.getElementById("mySidebarLeft").style.width = "0";
  document.getElementById("main").style.marginLeft= "0";
}
function closeNavRight() {
  document.getElementById("mySidebarRight").style.width = "0";
  document.getElementById("main").style.marginRight= "0";
  document.getElementById("example").style.marginRight = "0";
}

var dataSet = [
    [ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800" ],
    [ "Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750" ],
    [ "Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000" ],
    [ "Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060" ],
    [ "Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700" ],
    [ "Brielle Williamson", "Integration Specialist", "New York", "4804", "2012/12/02", "$372,000" ],
    [ "Herrod Chandler", "Sales Assistant", "San Francisco", "9608", "2012/08/06", "$137,500" ],
    [ "Rhona Davidson", "Integration Specialist", "Tokyo", "6200", "2010/10/14", "$327,900" ],
    [ "Colleen Hurst", "Javascript Developer", "San Francisco", "2360", "2009/09/15", "$205,500" ],

];

.sidebarLeft {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebarRight {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebarRight .closebtnRight {
  position: absolute;
  top: 0;
  left: 25px;
  font-size: 36px;
  margin-right: 50px;
}

.sidebarLeft .closebtnLeft {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

.sidebarLeft a,.sidebarRight a {
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidebarLeft a:hover,.sidebarRight a:hover {
  color: #f1f1f1;
}

body {
  font-family: "Lato", sans-serif;
}

  ×

                                      <button class="btn fas fa-arrow-left openbtn" onclick="openNavLeft()">
                                        </button>
                                      <button class="btn fas fa-arrow-right openbtn" onclick="openNavRight()">
                                        </button>

  ×

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
<link rel = "stylesheet" href = "https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" />

<link rel = "stylesheet" href = "https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" />
<link rel = "stylesheet" href = "https://cdn.datatables.net/autofill/2.3.0/css/autoFill.dataTables.min.css" />
<link rel = "stylesheet" href = "https://cdn.datatables.net/fixedcolumns/3.2.5/css/fixedColumns.dataTables.min.css" />
<link rel = "stylesheet" href = "https://cdn.datatables.net/responsive/2.2.2/css/responsive.dataTables.min.css" />

I want that when you add the left or right panels, if the size of the table is not enough to show all the information, adjust the table and show the responsive mode for mobiles

attached photo of what I want to do

Body:
Try recalculate the widths used by responsive after a change in the nav menu

table.responsive.recalc()

var table;
$(document).ready(function() {
    table = $('#example').DataTable( {
        data: dataSet,
        columns: [
            { title: "Name" },
            { title: "Position" },
            { title: "Office" },
            { title: "Extn." },
            { title: "Start date" },
            { title: "Salary" }
        ],
      "searching": false,
      "lengthChange": false,
      "responsive":true
    });
});

function recalc() {
  table.responsive.recalc();
}

function openNavLeft() {
  document.getElementById("mySidebarLeft").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
  recalc();
}

function openNavRight() {
  document.getElementById("mySidebarRight").style.width = "250px";
  document.getElementById("main").style.marginRight = "250px";
  recalc();
}

function closeNavLeft() {
  document.getElementById("mySidebarLeft").style.width = "0";
  document.getElementById("main").style.marginLeft= "0";
  recalc();
}
function closeNavRight() {
  document.getElementById("mySidebarRight").style.width = "0";
  document.getElementById("main").style.marginRight= "0";
  recalc();
}

var dataSet = [
    [ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800" ],
    [ "Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750" ],
    [ "Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000" ],
    [ "Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060" ],
    [ "Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700" ],
    [ "Brielle Williamson", "Integration Specialist", "New York", "4804", "2012/12/02", "$372,000" ],
    [ "Herrod Chandler", "Sales Assistant", "San Francisco", "9608", "2012/08/06", "$137,500" ],
    [ "Rhona Davidson", "Integration Specialist", "Tokyo", "6200", "2010/10/14", "$327,900" ],
    [ "Colleen Hurst", "Javascript Developer", "San Francisco", "2360", "2009/09/15", "$205,500" ],

];

.sidebarLeft {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebarRight {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebarRight .closebtnRight {
  position: absolute;
  top: 0;
  left: 25px;
  font-size: 36px;
  margin-right: 50px;
}

.sidebarLeft .closebtnLeft {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

.sidebarLeft a,
.sidebarRight a {
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidebarLeft a:hover,
.sidebarRight a:hover {
  color: #f1f1f1;
}

body {
  font-family: "Lato", sans-serif;
}

<!--sidebar left-->
<div id="mySidebarLeft" class="sidebarLeft">
  <a href="javascript:void(0)" class="closebtnLeft" onclick="closeNavLeft()">×</a>
</div>

<!--main card-->
<div id="main" class="card bg-light">
  <div class="pt-3">
    <div class="row pull-right">
      <div class="col-12 ">
        <ul class="flex-lg-row d-flex flex-column mb-0 p-0">
          <li class="d-inline px-lg-1">
            <button class="btn fas fa-arrow-left openbtn" onclick="openNavLeft()">
                                        </button>
            <button class="btn fas fa-arrow-right openbtn" onclick="openNavRight()">
                                        </button>
          </li>
        </ul>
      </div>
    </div>
    <div class="clearfix"></div>
  </div>
  <div class="card-block px-3 pb-0">
    <table id="example" class="table table-hover display responsive no-wrap" width="100%"></table>
  </div>
</div>

<!--sidebar right-->
<div id="mySidebarRight" class="sidebarRight">
  <a href="javascript:void(0)" class="closebtnRight" onclick="closeNavRight()">×</a>
</div>

<!-------------------------------- CDN's css-------------------------------------->

<!-- Bootstrap & fontawesome css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" />
<!-- Datatable css -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/autofill/2.3.0/css/autoFill.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/fixedcolumns/3.2.5/css/fixedColumns.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.2/css/responsive.dataTables.min.css" />
<!-------------------------------- CDN's js-------------------------------------->
<!-- Boostrap & fontawesome js-->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<!-- Datatable js -->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/autofill/2.3.0/js/dataTables.autoFill.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/fixedcolumns/3.2.5/js/dataTables.fixedColumns.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/scroller/2.0.0/js/dataTables.scroller.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.2/js/dataTables.responsive.min.js"></script>


来源: stackexchange

问:
Selenium: how to set mobile mode on Firefox Driver
I have worked on Selenium Firefox Driver with Java

I was seach for set mobile mode. but it just Code for ChromeDriver.
I know we will FirefoxProfile but i'm not clarify code on java
 so
How can i setup Mobile mode for FirfoxDriver.
Thanks

答:
of course most resource for chrome driver

so test it
it worked for me

```<code>firefox_options.set_capability("deviceName", "iPhone")
</code>```

and if you like to give user agent , this can help you

```<code>firefox_profile.set_preference("general.useragent.override", user_agent)
</code>```

as you can see this code for python if you use java maby this link helpful for that
https://stqatools.com/selenium-desired-capability-marionette/

ContentLicense: CC BY-SA 3.0

Body:
of course most resource for chrome driver

so test it
it worked for me

firefox_options.set_capability("deviceName", "iPhone")

and if you like to give user agent , this can help you

firefox_profile.set_preference("general.useragent.override", user_agent)

as you can see this code for python if you use java maby this link helpful for that
https://stqatools.com/selenium-desired-capability-marionette/

ContentLicense: CC BY-SA 4.0


问:
The method 'PermissionHandler' isn't defined for the class
After upgrading PermissionHandler to latest (5.0.0). The PermissionHandler() not found and also
The name 'PermissionGroup' isn't a type so it can't be used as a type argument..

Here is a code snippet:

```<code>  PermissionStatus permission = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
  if (permission != PermissionStatus.granted && permission != PermissionStatus.neverAskAgain) {
    Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler().requestPermissions([PermissionGroup.storage]);
    if (permissions.containsValue(2))
      fileDownload(context, finalUrl);
  }
</code>```

What is the problem?

答:
Those who are still struggling with this, please follow the instructions

The latest version for handling permissions is now

permission_handler: ^5.0.0+hotfix.8

Now I think they have changed the usage.

Use case: I have to give check contact permissions in order to save a contact in the phone directory. SO This works perfectly for me.

```<code>  Future<void> saveContactInPhone() async {
    try {

      print("saving Conatct");
      PermissionStatus permission = await Permission.contacts.status;

    if (permission != PermissionStatus.granted) {
      await Permission.contacts.request();
      PermissionStatus permission = await Permission.contacts.status;

      if (permission == PermissionStatus.granted) {
      Contact newContact = new Contact();

        newContact.givenName ="Ajay";
        newContact.familyName ="abc";

          newContact.phones = [Item(label: "mobile",value: "9998887771")];

        await ContactsService.addContact(newContact);

      } else {
        //_handleInvalidPermissions(context);
      }
    } else {
      Contact newContact = new Contact();

        newContact.givenName ="Ajay";
        newContact.familyName ="abc";

          newContact.phones = [Item(label: "mobile",value: "9998887771")];

        await ContactsService.addContact(newContact);
    }
      print("object");

    } catch (e) {
      print(e);
    }
  }
</code>```

Please refer Permission_handler_example for more info

Body:
After upgrading PermissionHandler to latest (5.0.0). The PermissionHandler() not found and also
The name 'PermissionGroup' isn't a type so it can't be used as a type argument..

Here is a code snippet:

  PermissionStatus permission = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
  if (permission != PermissionStatus.granted && permission != PermissionStatus.neverAskAgain) {
    Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler().requestPermissions([PermissionGroup.storage]);
    if (permissions.containsValue(2))
      fileDownload(context, finalUrl);
  }

What is the problem?

Body:
Those who are still struggling with this, please follow the instructions

The latest version for handling permissions is now

permission_handler: ^5.0.0+hotfix.8

Now I think they have changed the usage.

Use case: I have to give check contact permissions in order to save a contact in the phone directory. SO This works perfectly for me.

  Future<void> saveContactInPhone() async {
    try {

      print("saving Conatct");
      PermissionStatus permission = await Permission.contacts.status;

    if (permission != PermissionStatus.granted) {
      await Permission.contacts.request();
      PermissionStatus permission = await Permission.contacts.status;

      if (permission == PermissionStatus.granted) {
      Contact newContact = new Contact();

        newContact.givenName ="Ajay";
        newContact.familyName ="abc";

          newContact.phones = [Item(label: "mobile",value: "9998887771")];

        await ContactsService.addContact(newContact);

      } else {
        //_handleInvalidPermissions(context);
      }
    } else {
      Contact newContact = new Contact();

        newContact.givenName ="Ajay";
        newContact.familyName ="abc";

          newContact.phones = [Item(label: "mobile",value: "9998887771")];

        await ContactsService.addContact(newContact);
    }
      print("object");

    } catch (e) {
      print(e);
    }
  }

Please refer Permission_handler_example for more info


问:
Save Dataset to SQLite format file
I have a dataset with multiple tables.
I can obviously do a Dataset.WriteToXML("Somefile.xml")

What if I want to export the dataset to a SQLite formatted file.

In other words I want to be able to write (i.e. serialize) the contents of the dataset to a SQLite file.   Dataset.SerializeToSQLite("Sqliteformatted.bin")

Similarly I want to be able to read the SQLite file into a Dataset.

I would like to do this in c#.

Thanks in advance to any pointers.

Bob

答:
SQLite is not a file format, it's a database.

If you want to put all the data from a DataSet into a database you need to create a connection to the database (which can be a blank file, SQLite will create it upon initial connection), and then create the database structure.  Then issue INSERT statements to append the data to the database.  You can use a SQLiteDataAdapter to simplify creating the insert statements.

ContentLicense: CC BY-SA 2.5

Title: Save Dataset to SQLite format file


问:
Recyclerview not scrolling inside Nested ScrollView
I have Recyclerview which is under Coordinatorlayout > NestedScrollview > ViewPager and ViewPager has 3 fragment, one has image gallery which is working with the help of Recyclerview. Whenever i tried to scroll up or down it doesn't scroll at all. I have already set photosRecycler.setNestedScrollingEnabled(false); and as soon as i remove this line i am getting scroll working only down side and when i tried to move back up it move up with parent Nestedscrollview.

My layout manager is also showing StaggeredGrid as Grid i need to get this kind of layout

Here is my parent layout for Nestedscrollview

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="?android:attr/colorBackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways">

            <androidx.constraintlayout.widget.ConstraintLayout

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?android:colorBackground">

                <ImageView

                    android:layout_width="match_parent"
                    android:layout_height="500dp"
                    android:src="@color/custom_transparent_colorBlack"
                    android:scaleType="centerCrop"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="0.0"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    />

                <de.hdodenhof.circleimageview.CircleImageView

                    android:layout_width="128dp"
                    android:layout_height="128dp"
                    app:layout_constraintBottom_toBottomOf="@+id/coverPhoto"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="@+id/coverPhoto"
                    app:layout_constraintVertical_bias="0.44"
                    tools:srcCompat="@tools:sample/avatars" />

            </androidx.constraintlayout.widget.ConstraintLayout>
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>
    <androidx.core.widget.NestedScrollView
        android:id="@+id/up_NestedScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:overScrollMode="never"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"

        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            >
            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabItemes"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabGravity="fill"
                app:tabPaddingBottom="0dp"
                app:tabPaddingEnd="0dp"
                app:tabPaddingStart="0dp"
                app:tabPaddingTop="0dp"
                app:tabIndicatorHeight="0dp"
                app:tabMode="fixed"
                app:tabTextColor="@color/black"
                app:tabSelectedTextColor="@color/primary"
                app:tabIndicatorColor="@color/primary_light">

                <com.google.android.material.tabs.TabItem
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="About" />

                <com.google.android.material.tabs.TabItem
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Media" />

                <com.google.android.material.tabs.TabItem
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Con" />
            </com.google.android.material.tabs.TabLayout>

            <androidx.viewpager.widget.ViewPager

                android:layout_below="@id/tabItemes"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </RelativeLayout>
    </androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

Image Gallery Fragment

```<code>public class UserPhoto_fragment extends Fragment {
    public static final String TAG="### USER PHOTO ####";
    RecyclerView photosRecycler;
    fetchPhoto_Adapter adapter;
    StaggeredGridLayoutManager layoutManager;
    ArrayList<String> ImageList;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.userprofile_photos,container,false);
        setRetainInstance(true);
        photosRecycler=view.findViewById(R.id.userPhotos_recycler);
        layoutManager= new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        ImageList=new ArrayList<>();
        SpacesItemDecoration itemDecoration = new SpacesItemDecoration(16);
        photosRecycler.addItemDecoration(itemDecoration);
        photosRecycler.setLayoutManager(layoutManager);
        photosRecycler.setHasFixedSize(true);
        photosRecycler.setNestedScrollingEnabled(false);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: User Photo Fragment "+getView()+ ImageList.size() );
        if (ImageList.size()==0){
            new fetch_photo().execute();
        }
    }

    public class fetchPhoto_Adapter extends RecyclerView.Adapter<fetchPhoto_Adapter.ViewHolder>{

        @NonNull
        @Override
        public fetchPhoto_Adapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            LayoutInflater inflater= (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflater.inflate(R.layout.userprofile_photogallery,viewGroup,false);
            return new ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(fetchPhoto_Adapter.ViewHolder viewHolder, int i) {
            Glide.with(getActivity()).load(ImageList.get(i)).apply(new RequestOptions().centerCrop()).into(viewHolder.image);
        }

        @Override
        public int getItemCount() {
            if (ImageList!=null && ImageList.size()>0){
                return ImageList.size();
            }else {
                return 0;
            }
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            ImageView image;
            public ViewHolder(View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.UserProfile_photoThumb);
            }
        }

    }

}
</code>```

Layout file for image gallery

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_marginTop="20dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/userPhotos_recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:scrollbars="vertical">

    </androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</code>```

I am facing 2 issue with this code

Recyclerview not working in nestedscrollview.

StaggeredGridLayoutManager is showing images like GridLayoutManager

Please help me to resolve these issue.Thanks

答:
I have faced the same requirement but have solved it in a different manner,

```<code>app:layout_behavior="@string/appbar_scrolling_view_behavior"
</code>```

Set this attribute to the main content layout in your CoordinatorLayout.

```<code>    <string name="appbar_scrolling_view_behavior" translatable="false">com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior</string>
</code>```

The layout  looks like

```<code>    <androidx.coordinatorlayout.widget.CoordinatorLayout >

    <com.google.android.material.appbar.AppBarLayout>

        <androidx.appcompat.widget.Toolbar>

            <androidx.constraintlayout.widget.ConstraintLayout>

                <ImageView />
                //Header content

            </androidx.constraintlayout.widget.ConstraintLayout>

        </androidx.appcompat.widget.Toolbar>

        <com.google.android.material.tabs.TabLayout />

    </com.google.android.material.appbar.AppBarLayout>

    <LinearLayout

        app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <androidx.viewpager.widget.ViewPager
                android:id="@+id/viewPager"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/light_gray">

            </androidx.viewpager.widget.ViewPager>

    </LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

And the main fragments parent view must be nested scroll view with app:layout_behavior

Note: My fragment contains linear layout, so I just used wrap_content if you are using recycler view you should flatten it out inside the fragment

Body:
I have Recyclerview which is under Coordinatorlayout > NestedScrollview > ViewPager and ViewPager has 3 fragment, one has image gallery which is working with the help of Recyclerview. Whenever i tried to scroll up or down it doesn't scroll at all. I have already set photosRecycler.setNestedScrollingEnabled(false); and as soon as i remove this line i am getting scroll working only down side and when i tried to move back up it move up with parent Nestedscrollview.

My layout manager is also showing StaggeredGrid as Grid i need to get this kind of layout

Here is my parent layout for Nestedscrollview

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="?android:attr/colorBackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways">

            <androidx.constraintlayout.widget.ConstraintLayout

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?android:colorBackground">

                <ImageView

                    android:layout_width="match_parent"
                    android:layout_height="500dp"
                    android:src="@color/custom_transparent_colorBlack"
                    android:scaleType="centerCrop"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="0.0"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    />

                <de.hdodenhof.circleimageview.CircleImageView

                    android:layout_width="128dp"
                    android:layout_height="128dp"
                    app:layout_constraintBottom_toBottomOf="@+id/coverPhoto"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="@+id/coverPhoto"
                    app:layout_constraintVertical_bias="0.44"
                    tools:srcCompat="@tools:sample/avatars" />

            </androidx.constraintlayout.widget.ConstraintLayout>
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>
    <androidx.core.widget.NestedScrollView
        android:id="@+id/up_NestedScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:overScrollMode="never"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"

        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            >
            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabItemes"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabGravity="fill"
                app:tabPaddingBottom="0dp"
                app:tabPaddingEnd="0dp"
                app:tabPaddingStart="0dp"
                app:tabPaddingTop="0dp"
                app:tabIndicatorHeight="0dp"
                app:tabMode="fixed"
                app:tabTextColor="@color/black"
                app:tabSelectedTextColor="@color/primary"
                app:tabIndicatorColor="@color/primary_light">

                <com.google.android.material.tabs.TabItem
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="About" />

                <com.google.android.material.tabs.TabItem
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Media" />

                <com.google.android.material.tabs.TabItem
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Con" />
            </com.google.android.material.tabs.TabLayout>

            <androidx.viewpager.widget.ViewPager

                android:layout_below="@id/tabItemes"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </RelativeLayout>
    </androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Image Gallery Fragment

public class UserPhoto_fragment extends Fragment {
    public static final String TAG="### USER PHOTO ####";
    RecyclerView photosRecycler;
    fetchPhoto_Adapter adapter;
    StaggeredGridLayoutManager layoutManager;
    ArrayList<String> ImageList;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.userprofile_photos,container,false);
        setRetainInstance(true);
        photosRecycler=view.findViewById(R.id.userPhotos_recycler);
        layoutManager= new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        ImageList=new ArrayList<>();
        SpacesItemDecoration itemDecoration = new SpacesItemDecoration(16);
        photosRecycler.addItemDecoration(itemDecoration);
        photosRecycler.setLayoutManager(layoutManager);
        photosRecycler.setHasFixedSize(true);
        photosRecycler.setNestedScrollingEnabled(false);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: User Photo Fragment "+getView()+ ImageList.size() );
        if (ImageList.size()==0){
            new fetch_photo().execute();
        }
    }

    public class fetchPhoto_Adapter extends RecyclerView.Adapter<fetchPhoto_Adapter.ViewHolder>{

        @NonNull
        @Override
        public fetchPhoto_Adapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            LayoutInflater inflater= (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflater.inflate(R.layout.userprofile_photogallery,viewGroup,false);
            return new ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(fetchPhoto_Adapter.ViewHolder viewHolder, int i) {
            Glide.with(getActivity()).load(ImageList.get(i)).apply(new RequestOptions().centerCrop()).into(viewHolder.image);
        }

        @Override
        public int getItemCount() {
            if (ImageList!=null && ImageList.size()>0){
                return ImageList.size();
            }else {
                return 0;
            }
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            ImageView image;
            public ViewHolder(View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.UserProfile_photoThumb);
            }
        }

    }

}

Layout file for image gallery

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_marginTop="20dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/userPhotos_recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:scrollbars="vertical">

    </androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>

I am facing 2 issue with this code

Recyclerview not working in nestedscrollview.

StaggeredGridLayoutManager is showing images like GridLayoutManager

Please help me to resolve these issue.Thanks

Body:
I have faced the same requirement but have solved it in a different manner,

app:layout_behavior="@string/appbar_scrolling_view_behavior"

Set this attribute to the main content layout in your CoordinatorLayout.

    <string name="appbar_scrolling_view_behavior" translatable="false">com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior</string>

The layout  looks like

    <androidx.coordinatorlayout.widget.CoordinatorLayout >

    <com.google.android.material.appbar.AppBarLayout>

        <androidx.appcompat.widget.Toolbar>

            <androidx.constraintlayout.widget.ConstraintLayout>

                <ImageView />
                //Header content

            </androidx.constraintlayout.widget.ConstraintLayout>

        </androidx.appcompat.widget.Toolbar>

        <com.google.android.material.tabs.TabLayout />

    </com.google.android.material.appbar.AppBarLayout>

    <LinearLayout

        app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <androidx.viewpager.widget.ViewPager
                android:id="@+id/viewPager"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/light_gray">

            </androidx.viewpager.widget.ViewPager>

    </LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

And the main fragments parent view must be nested scroll view with app:layout_behavior

Note: My fragment contains linear layout, so I just used wrap_content if you are using recycler view you should flatten it out inside the fragment


问:
Are there any trade-offs between react-native-permissions and expo-permission?
I'm trying to select between react-native-permissions or expo-permissions for my project. They both work on iOS and Android but expo-permissions code is more concise. Other than that, are there any trade-offs between the two that I should be aware of?

I'm using bare react-native workflow without Expo.

答:
If you are using a bare react-native workflow you should use react-native-permissions, because expo-permissions is only for expo managed workflows.

Although Expo has react-native-unimodules package that can give you the permissions module.

If you read the docs for expo-permissions you can see this thing in installation guide. Thanks


问:
Ensemble classifiers (Random Forest, Bagging, Boosting, etc.) in SSAS
I am using SSAS (SQL Server 2008 R2) to develop a classification model for a data set where 80% of values are missing. Ensemble classifiers based on trees are supposedly the best solution (Random Forest for example).

Is there any nice way of adding an ensemble classifier into SSAS? For example an AdaBoost or any other Bagging or Boosting classifier?

I know SSAS provides plug-in functionality, but I have not come across anyone doing any ensemble solutions... Not to mention anything that you can just download and start using.

If not, is there any efficient method to connect various classifiers in SSAS? I hope I am missing something obvious that is there.

答:
I am not too familiar with the topic you are asking about, but technologically in SSAS you can register assemblies and use them in MDX. Therefore, it could be possible for you to code this in .NET and use the logic in SSAS. Please have a look at the following MSDN page for more information in case this sounds like something worth exploring.

http://technet.microsoft.com/en-us/library/ms175398.aspx

Additionally, have a look at the Data Mining SSAS provides out-of-the box as some classification objectives could be achievable by using the included algorithms:

http://technet.microsoft.com/en-us/library/ms175595.aspx


问:
Ue4 - Mobile Card Game - Draw Card Problem
I am trying to do mobile action game with a card system. I have a 8 different card in array as a text and they are calling function like a skill system. When game start system will shuffle deck and pick 4 card from inside, remove them and add to last of array as you can see downside. After use skills (buttons) if stamina is enough function will work and card will go to last index of array. Everything is working but when i try to start with 4th button ( All system is same) its always going infinite loop. When i press 1 or 2 or 3 its working and after that i can press 4th and its working but if i choose 4th button for a first card its crashing. I am sharing all system to look. I try to do for 5 days and couldnt found please help me and if you can share me your experiences about these systems to more optimize. If you want i can give more information.

Thanks A Lot!

https://imgur.com/a/uapK2u7

答:
capture of your blueprint image

in your GetDatas Function,

looping Deck array, you are trying to swapping (i) and (i-1)
but this logic could be dangerous if i == 0, it would try to access array[-1] and cause crash.


问:
How to generate sample XML documents from their DTD or XSD?
We are developing an application that involves a substantial amount of XML transformations. We do not have any proper input test data per se, only DTD or XSD files. We'd like to generate our test data ourselves from these files. Is there an easy/free way to do that?

Edit

There are apparently no free tools for this, and I agree that OxygenXML is one of the best tools for this.

答:
Seems like nobody was able to answer the question so far :)

I use EclipseLink's MOXy to dynamically generate binding classes and then recursively go through the bound types. It is somewhat heavy, but it allows XPath value injection once the object tree is instantiated:

```<code>InputStream in = new FileInputStream(PATH_TO_XSD);
DynamicJAXBContext jaxbContext =
            DynamicJAXBContextFactory.createContextFromXSD(in, null, Thread.currentThread().getContextClassLoader(), null);
DynamicType rootType = jaxbContext.getDynamicType(YOUR_ROOT_TYPE);
DynamicEntity root = rootType.newDynamicEntity();
traverseProps(jaxbContext, root, rootType, 0);
</code>```

TraverseProps is pretty simple recursive method:

```<code>private void traverseProps(DynamicJAXBContext c, DynamicEntity e, DynamicType t, int level) throws DynamicException, InstantiationException, IllegalAccessException{
        if (t!=null) {
            logger.info(indent(level) + "type [" + t.getName() + "] of class [" + t.getClassName() + "] has " + t.getNumberOfProperties() + " props");
            for (String pName:t.getPropertiesNames()){
                Class<?> clazz = t.getPropertyType(pName);
                logger.info(indent(level) + "prop [" + pName + "] in type: " + clazz);
                //logger.info("prop [" + pName + "] in entity: " + e.get(pName));

                if (clazz==null){
                    // need to create an instance of object
                    String updatedClassName = pName.substring(0, 1).toUpperCase() + pName.substring(1);
                    logger.info(indent(level) + "Creating new type instance for " + pName + " using following class name: " + updatedClassName );
                    DynamicType child = c.getDynamicType("generated." + updatedClassName);
                    DynamicEntity childEntity = child.newDynamicEntity();
                    e.set(pName, childEntity);
                    traverseProps(c, childEntity, child, level+1);
                } else {
                    // just set empty value
                    e.set(pName, clazz.newInstance());
                }
            }
        } else {
            logger.warn("type is null");
        }
    }
</code>```

Converting everything to XML is pretty easy:

```<code>Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
</code>```

OwnerDisplayName: lindelof

LastEditorDisplayName: lindelof

Body:
Seems like nobody was able to answer the question so far :)

I use EclipseLink's MOXy to dynamically generate binding classes and then recursively go through the bound types. It is somewhat heavy, but it allows XPath value injection once the object tree is instantiated:

InputStream in = new FileInputStream(PATH_TO_XSD);
DynamicJAXBContext jaxbContext =
            DynamicJAXBContextFactory.createContextFromXSD(in, null, Thread.currentThread().getContextClassLoader(), null);
DynamicType rootType = jaxbContext.getDynamicType(YOUR_ROOT_TYPE);
DynamicEntity root = rootType.newDynamicEntity();
traverseProps(jaxbContext, root, rootType, 0);

TraverseProps is pretty simple recursive method:

private void traverseProps(DynamicJAXBContext c, DynamicEntity e, DynamicType t, int level) throws DynamicException, InstantiationException, IllegalAccessException{
        if (t!=null) {
            logger.info(indent(level) + "type [" + t.getName() + "] of class [" + t.getClassName() + "] has " + t.getNumberOfProperties() + " props");
            for (String pName:t.getPropertiesNames()){
                Class<?> clazz = t.getPropertyType(pName);
                logger.info(indent(level) + "prop [" + pName + "] in type: " + clazz);
                //logger.info("prop [" + pName + "] in entity: " + e.get(pName));

                if (clazz==null){
                    // need to create an instance of object
                    String updatedClassName = pName.substring(0, 1).toUpperCase() + pName.substring(1);
                    logger.info(indent(level) + "Creating new type instance for " + pName + " using following class name: " + updatedClassName );
                    DynamicType child = c.getDynamicType("generated." + updatedClassName);
                    DynamicEntity childEntity = child.newDynamicEntity();
                    e.set(pName, childEntity);
                    traverseProps(c, childEntity, child, level+1);
                } else {
                    // just set empty value
                    e.set(pName, clazz.newInstance());
                }
            }
        } else {
            logger.warn("type is null");
        }
    }

Converting everything to XML is pretty easy:

Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);


问:
How to configure DNS for microsoft odbc driver for oracle (in 64 bit arch.)
I try to configure DNS for odbc running c:/windows/syswow64/odbcad32.exe.
After choosing microsoft ODBC for ORACLE it ends with this error :

the Oracle(tm) client and networking components were not found . These
  component are supplied by Oracle Corporation and are part  of the
  Oracle version 7.3(or greater) client software installation

you will be unable to use this driver untill these have been
  installed.

I installed  oracle 11g on my pc but it doesnot helps.

What should I do ?

答:
It depends on your application is 32-bit / 64-bit. If it is 64-bit, you can't connect to 32-bit Microsoft ODBC Driver for Oracle as they're different architecture, both must match. Besides that, MS didn't provide 64-bit ODBC Driver for Oracle, but you can use the driver provided by Oracle.

If your application is 32-bit, you need to install 32-bit Oracle client too. Same concept. The architecture must match.


问:
Using a limit on a left join in mysql
The following query selects all posts and each post's owner, all of the comments that belong to each post, and the owner of each comment.

I need to only retrieve 5 comments per post. I rewrote the query, but I get an error of "each derived table must have it's own alias".

```<code>SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname, comments.id AS commentId, comments.text, commenters.id, commenters.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN comments ON posts.id = comments.postid
    JOIN users AS commenters ON comments.userId = commenters.id
ORDER BY posts.createdAt
</code>```

New Query:

```<code>SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN (
    SELECT comments.id AS commentId, comments.text AS commentText, commenters.id AS commenterId, commenters.displayname AS commenterDisplayName
    FROM comments
    JOIN users AS commenters ON comments.userid = commenters.id
    LIMIT 0,5
        ) AS comments ON comments.postid = posts.id
ORDER BY posts.createdAt
</code>```

UPDATE The query now works, but it does not produce the desired output. I want to output 10 posts, with 5 comments for each post. This limit clause will only apply for the comments of the first post encountered.

答:
By Error

Add an alias following your subquery.

Example: SELECT * FROM foo JOIN (select * from bar) AS <alias_here>

Make sure you have a field in the posts table and that it is called createdAt.  I'm not sure MySQL is case-sensitive, but the error you posted says createdat (with the 'A' lowercased)

You have two LEFT JOINs, but only one ON statement.  A join isn't anything without the hook to join it on. Example:

```<code>SELECT *
FROM foo JOIN bar ON (foo.id=bar.id)
LEFT JOIN (select * from foobar) AS baz **ON foo.id=baz.id**
</code>```

In order to join on a field, the field needs to be present in the table involved in the join.  So in the above example, if you match foo.id with baz.id, id needs to be returned in the subquery (baz).

Title: Using a limit on a left join in mysql

Body:
The following query selects all posts and each post's owner, all of the comments that belong to each post, and the owner of each comment.

I need to only retrieve 5 comments per post. I rewrote the query, but I get an error of "each derived table must have it's own alias".

SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname, comments.id AS commentId, comments.text, commenters.id, commenters.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN comments ON posts.id = comments.postid
    JOIN users AS commenters ON comments.userId = commenters.id
ORDER BY posts.createdAt

New Query:

SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN (
    SELECT comments.id AS commentId, comments.text AS commentText, commenters.id AS commenterId, commenters.displayname AS commenterDisplayName
    FROM comments
    JOIN users AS commenters ON comments.userid = commenters.id
    LIMIT 0,5
        ) AS comments ON comments.postid = posts.id
ORDER BY posts.createdAt

UPDATE The query now works, but it does not produce the desired output. I want to output 10 posts, with 5 comments for each post. This limit clause will only apply for the comments of the first post encountered.

Body:
By Error

Add an alias following your subquery.

Example: SELECT * FROM foo JOIN (select * from bar) AS <alias_here>

Make sure you have a field in the posts table and that it is called createdAt.  I'm not sure MySQL is case-sensitive, but the error you posted says createdat (with the 'A' lowercased)

You have two LEFT JOINs, but only one ON statement.  A join isn't anything without the hook to join it on. Example:

SELECT *
FROM foo JOIN bar ON (foo.id=bar.id)
LEFT JOIN (select * from foobar) AS baz **ON foo.id=baz.id**

In order to join on a field, the field needs to be present in the table involved in the join.  So in the above example, if you match foo.id with baz.id, id needs to be returned in the subquery (baz).


问:
Pyttsx3 worked earlier but not now
In december, 2019, my pyttsx3 module was working fine with no error. After few months I uninstalled Python, But in May 2020 I installed it again. But this time, wierd errors came...
My os is win10Pro , Python 3.7(earier it was the same), IDE is Pycharm. The code is :

```<code>
import pyttsx3

def speak(text):
    engine = pyttsx3.init()
    engine.say(text)
    engine.runAndWait()

speak("Hello World!")
</code>```

When I run it :

```<code>Traceback (most recent call last):
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\__init__.py", line 20, in init
    eng = _activeEngines[driverName]
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\weakref.py", line 137, in __getitem__
    o = self.data[key]()
KeyError: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\drivers\sapi5.py", line 3, in <module>
    from comtypes.gen import SpeechLib  # comtypes
ImportError: cannot import name 'SpeechLib' from 'comtypes.gen' (C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\gen\__init__.py)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\ctypes\__init__.py", line 121, in WINFUNCTYPE
    return _win_functype_cache[(restype, argtypes, flags)]
KeyError: (<class 'ctypes.HRESULT'>, (<class 'comtypes.automation.tagVARIANT'>, <class 'comtypes.LP_POINTER(ISpeechRecoGrammar)'>), 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:\happy v6\stackoverflow.py", line 10, in <module>
    speak("Hello World!")
  File "E:\happy v6\stackoverflow.py", line 5, in speak
    engine = pyttsx3.init()
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\__init__.py", line 22, in init
    eng = Engine(driverName, debug)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\engine.py", line 30, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\driver.py", line 50, in __init__
    self._module = importlib.import_module(name)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\drivers\sapi5.py", line 6, in <module>
    engine = comtypes.client.CreateObject("SAPI.SpVoice")
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\client\__init__.py", line 250, in CreateObject
    return _manage(obj, clsid, interface=interface)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\client\__init__.py", line 188, in _manage
    obj = GetBestInterface(obj)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\client\__init__.py", line 110, in GetBestInterface
    mod = GetModule(tlib)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\client\_generate.py", line 110, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\client\_generate.py", line 184, in _CreateWrapper
    mod = _my_import(fullname)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\client\_generate.py", line 24, in _my_import
    return __import__(fullname, globals(), locals(), ['DUMMY'])
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\gen\_C866CA3A_32F7_11D2_9602_00C04F8EE628_0_5_4.py", line 726, in <module>
    ( ['in'], BSTR, 'AdaptationString' )),
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\__init__.py", line 329, in __setattr__
    self._make_methods(value)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\__init__.py", line 698, in _make_methods
    prototype = WINFUNCTYPE(restype, *argtypes)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\ctypes\__init__.py", line 123, in WINFUNCTYPE
    class WinFunctionType(_CFuncPtr):
TypeError: item 1 in _argtypes_ passes a union by value, which is unsupported
</code>```

I didn't get it. What shoud I do? If you know how to solve it, Please share it with me..

答: This may help. You should try installing tools for Python. By this I mean the Dev and other dependecies. One way to install python Dev tools is apt-get install python-dev if this didn't work, you will do this same thing but with the python version.

Title: Pyttsx3 worked earlier but not now

Body:
In december, 2019, my pyttsx3 module was working fine with no error. After few months I uninstalled Python, But in May 2020 I installed it again. But this time, wierd errors came...
My os is win10Pro , Python 3.7(earier it was the same), IDE is Pycharm. The code is :

import pyttsx3

def speak(text):
    engine = pyttsx3.init()
    engine.say(text)
    engine.runAndWait()

speak("Hello World!")

When I run it :

Traceback (most recent call last):
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\__init__.py", line 20, in init
    eng = _activeEngines[driverName]
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\weakref.py", line 137, in __getitem__
    o = self.data[key]()
KeyError: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\drivers\sapi5.py", line 3, in <module>
    from comtypes.gen import SpeechLib  # comtypes
ImportError: cannot import name 'SpeechLib' from 'comtypes.gen' (C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\gen\__init__.py)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\ctypes\__init__.py", line 121, in WINFUNCTYPE
    return _win_functype_cache[(restype, argtypes, flags)]
KeyError: (<class 'ctypes.HRESULT'>, (<class 'comtypes.automation.tagVARIANT'>, <class 'comtypes.LP_POINTER(ISpeechRecoGrammar)'>), 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:\happy v6\stackoverflow.py", line 10, in <module>
    speak("Hello World!")
  File "E:\happy v6\stackoverflow.py", line 5, in speak
    engine = pyttsx3.init()
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\__init__.py", line 22, in init
    eng = Engine(driverName, debug)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\engine.py", line 30, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\driver.py", line 50, in __init__
    self._module = importlib.import_module(name)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\drivers\sapi5.py", line 6, in <module>
    engine = comtypes.client.CreateObject("SAPI.SpVoice")
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\client\__init__.py", line 250, in CreateObject
    return _manage(obj, clsid, interface=interface)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\client\__init__.py", line 188, in _manage
    obj = GetBestInterface(obj)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\client\__init__.py", line 110, in GetBestInterface
    mod = GetModule(tlib)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\client\_generate.py", line 110, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\client\_generate.py", line 184, in _CreateWrapper
    mod = _my_import(fullname)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\client\_generate.py", line 24, in _my_import
    return __import__(fullname, globals(), locals(), ['DUMMY'])
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\gen\_C866CA3A_32F7_11D2_9602_00C04F8EE628_0_5_4.py", line 726, in <module>
    ( ['in'], BSTR, 'AdaptationString' )),
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\__init__.py", line 329, in __setattr__
    self._make_methods(value)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\site-packages\comtypes\__init__.py", line 698, in _make_methods
    prototype = WINFUNCTYPE(restype, *argtypes)
  File "C:\Users\Romoni Gogoi\AppData\Local\Programs\Python\Python37\lib\ctypes\__init__.py", line 123, in WINFUNCTYPE
    class WinFunctionType(_CFuncPtr):
TypeError: item 1 in _argtypes_ passes a union by value, which is unsupported

I didn't get it. What shoud I do? If you know how to solve it, Please share it with me..


问:
Activity not opening when clicking menu item
I am trying to tap on the "logout" option whose id is logout but nothing happens. Below is my code

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.requestpayment,menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.logout:
            Intent intent=new Intent(this,Logout.class);
            this.startActivity(intent);
            break;
    }
    return super.onOptionsItemSelected(item);
}
</code>```

please help

答: Restart Android studio. Let me know if that still persists</p>

Body:
I am trying to tap on the "logout" option whose id is logout but nothing happens. Below is my code

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.requestpayment,menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.logout:
            Intent intent=new Intent(this,Logout.class);
            this.startActivity(intent);
            break;
    }
    return super.onOptionsItemSelected(item);
}

please help


问:
Getting this error : Unhandled Exception: FormatException: Invalid envelope - While adding the contact
I am getting the error while adding the contact using contact service.</p>

```<code>Contact newContact = new Contact();

newContact.givenName ="Ajay";
newContact.familyName ="abc";

newContact.phones = [Item(label: "mobile",value: "9998887771")];

await ContactsService.addContact(newContact);
</code>```

答:
This will solve your problem:

The latest version for handling permissions is now

permission_handler: ^5.0.1+1

```<code>    Future<void> saveContactInPhone() async {
    try {

      print("saving Contact");
      PermissionStatus permission = await Permission.contacts.status;

    if (permission != PermissionStatus.granted) {
      await Permission.contacts.request();
      PermissionStatus permission = await Permission.contacts.status;

      if (permission == PermissionStatus.granted) {
      Contact newContact = new Contact();

        newContact.givenName ="Ajay";
        newContact.familyName ="abc";

          newContact.phones = [Item(label: "mobile",value: "9998887771")];

        await ContactsService.addContact(newContact);

      } else {
        //_handleInvalidPermissions(context);
      }
    } else {
      Contact newContact = new Contact();

        newContact.givenName ="Ajay";
        newContact.familyName ="abc";

          newContact.phones = [Item(label: "mobile",value: "9998887771")];

        await ContactsService.addContact(newContact);
    }
      print("object");

    } catch (e) {
      print(e);
    }
  }
</code>```

This worked perfectly fine for me.

Body:
I am getting the error while adding the contact using contact service.

Contact newContact = new Contact();

newContact.givenName ="Ajay";
newContact.familyName ="abc";

newContact.phones = [Item(label: "mobile",value: "9998887771")];

await ContactsService.addContact(newContact);

Body:
This will solve your problem:

The latest version for handling permissions is now

permission_handler: ^5.0.1+1

    Future<void> saveContactInPhone() async {
    try {

      print("saving Contact");
      PermissionStatus permission = await Permission.contacts.status;

    if (permission != PermissionStatus.granted) {
      await Permission.contacts.request();
      PermissionStatus permission = await Permission.contacts.status;

      if (permission == PermissionStatus.granted) {
      Contact newContact = new Contact();

        newContact.givenName ="Ajay";
        newContact.familyName ="abc";

          newContact.phones = [Item(label: "mobile",value: "9998887771")];

        await ContactsService.addContact(newContact);

      } else {
        //_handleInvalidPermissions(context);
      }
    } else {
      Contact newContact = new Contact();

        newContact.givenName ="Ajay";
        newContact.familyName ="abc";

          newContact.phones = [Item(label: "mobile",value: "9998887771")];

        await ContactsService.addContact(newContact);
    }
      print("object");

    } catch (e) {
      print(e);
    }
  }

This worked perfectly fine for me.


问:
Matching an string to regular expression when both the string and the regular expression has re reserved characters
I have a set of strings which may or may not match with a certain template.
I want to separate the strings that match with the template from the rest.
I could convert the template to regular expression.
But my template(which is eventually converted to a regex) and strings may have the regular expression reserved characters.
How can I match  the strings with the template in this scenario.

Ex:

Strings :

```<b>abc</b>[ ere <b>er</b> \ sfdf asdf.```

```<b>def</b>[ ere <b>we</b> \ sfdf asdf.```

```<b>ghi</b>[ ere <b>qs</b> \ sfdf asdf.```

Template :

```<code>(anything)[ ere (anything) \ sfdf asdf.
</code>```

Regex I used:

```<code>.+ ere .+ \ sfdf asdf.
</code>```

But this does not output that all 3 strings are matching with template.

答:
Based on the input strings and the template, would you please try:</p>

```<code>r'^.+?\[ ere .+? \\ sfdf asdf\.$'
</code>```

Body:
I have a set of strings which may or may not match with a certain template.
I want to separate the strings that match with the template from the rest.
I could convert the template to regular expression.
But my template(which is eventually converted to a regex) and strings may have the regular expression reserved characters.
How can I match  the strings with the template in this scenario.

Ex:

Strings :

abc[ ere er \ sfdf asdf.

def[ ere we \ sfdf asdf.

ghi[ ere qs \ sfdf asdf.

Template :

(anything)[ ere (anything) \ sfdf asdf.

Regex I used:

.+ ere .+ \ sfdf asdf.

But this does not output that all 3 strings are matching with template.

Body:
Based on the input strings and the template, would you please try:

r'^.+?\[ ere .+? \\ sfdf asdf\.$'


问:
Use Synergy on a computer on a workgroup and a laptop on a different domain
So, I recently installed synergy because I was tired of using two mice and keyboards. Problem is, set up is not working. First, the setup.

```<code>Server:
Desktop
Windows 7 64 - on our home network, part of Workgroup: WORKGROUP

Client:
work issued laptop
Windows XP SP2 32 - on home network, part of workd Domain: DOMAIN
</code>```

Server is set up, all the computer names are correct. I'm a bit of a noob at networking things, and I don't want to mess up the configuration of my work laptop again (I already switched the domain to my workgroup, BAD). So, any suggestions that aren't too crazy please, since it's a company laptop.

I've tried putting in the ip on the client as well, firewall is allowing on the port in use, just can't get it to work. I think I'm SOL with the Workgroup/Domain difference though...

答:
In a very similar situation I discovered that when trying to ping my non-domain desktop with its workgroup name the dns resolver was appending the work domain to the desktops name.  So when I tried synergy with an IP address I successfully connected the two computers.

The only caveat I can offer is maybe you needed to add the application to the windows firewall exception list for both machines.  I would assume the port setting was the same between the two computers (default is 24800) in which case you should only use the IP address because the application knows to access 24800 via that setting in the advanced configuration.

You can add the program to the whitelist or specifically the port if you prefer via the Windows Firewall.  On a side note - I am also using an older version of synergy (1.3.1) and not the latest as of this answer (1.4.2 Beta) which did not work for me, but I will assume it's because my server was running 1.3.1.

I chose not to update all 6 machines and their respective horrific configuration constructs that synergy loves to enforce upon us. [caution... rant: x is left of y and y is right of x... really? are you sure about that Einstein? Synergy could at least INFER that bit of logic instead of REQUIRING it!]

Hope that helps.

Body:
So, I recently installed synergy because I was tired of using two mice and keyboards. Problem is, set up is not working. First, the setup.

Server:
Desktop
Windows 7 64 - on our home network, part of Workgroup: WORKGROUP

Client:
work issued laptop
Windows XP SP2 32 - on home network, part of workd Domain: DOMAIN

Server is set up, all the computer names are correct. I'm a bit of a noob at networking things, and I don't want to mess up the configuration of my work laptop again (I already switched the domain to my workgroup, BAD). So, any suggestions that aren't too crazy please, since it's a company laptop.

I've tried putting in the ip on the client as well, firewall is allowing on the port in use, just can't get it to work. I think I'm SOL with the Workgroup/Domain difference though...


问:
Invalid Hook Calls In Validation in ReactJS
I have a problem in implementing login validations in ReactJS. I'm using Material-UI and Formik and Yap. I have implemented it but it has an error, it says invalid hook call. Hooks can only be called inside of the body of a function component.

Pls check my code below:

```<code>import React, { useState } from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/styles';
import { Card, CardHeader, CardContent, CardActions, Divider, Button, TextField } from '@material-ui/core';
import { useSelector, useDispatch } from 'react-redux';
import { Redirect } from 'react-router-dom';
import { login } from '../../../actions';
import AccountCircle from '@material-ui/icons/AccountCircle';
import InputAdornment from '@material-ui/core/InputAdornment';
import LockIcon from '@material-ui/icons/Lock';
import { withFormik } from 'formik';

const useStyles = makeStyles((theme) => ({
  root: {},
  cardHeader: {
    backgroundColor: theme.palette.primary.main,
    color: 'white',
    display: 'flex',
    justifyContent: 'center',
    fontSize: '2rem',
    padding: '15px',
  },
  textFieldSection: {
    padding: '40px 40px 0 40px',
  },
  loginButtonSection: {
    padding: '18px 40px 40px 40px',
  },
  loginButton: {
    width: '100%',
    height: '50px',
    textTransform: 'none',
    fontSize: '18px',
  },
}));

const LoginForm = (props) => {
  const { className, ...rest } = props;

  const isLoggedIn = useSelector((state) => state.auth.isLoggedIn);
  const referer = props.referer;
  const dispatch = useDispatch();

  const signIn = () => {
    dispatch(login(values.username, values.password));
  };

  const { classes, values, touched, errors, isSubmitting, handleChange, handleBlur, handleSubmit } = props;

  if (isLoggedIn) {
    return <Redirect to={referer} />;
  }

  return (
    <Card {...rest} className={clsx(classes.root, className)}>
      <form onSubmit={handleSubmit}>
        <CardHeader
          title="LOGIN"
          classes={{
            title: classes.cardHeader,
          }}
          className={classes.cardHeader}
        />

        <CardContent className={classes.textFieldSection}>
          <TextField
            fullWidth
            label="Username"
            name="username"
            type="text"
            variant="outlined"
            value={values.username}
            onChange={handleChange}
            onBlur={handleBlur}
            helperText={touched.username ? errors.username : ''}
            error={touched.username && Boolean(errors.username)}
            InputProps={{
              endAdornment: (
                <InputAdornment>
                  <AccountCircle />
                </InputAdornment>
              ),
            }}
          />
          <TextField
            fullWidth
            label="Password"
            name="password"
            style={{ marginTop: '1rem' }}
            type="password"
            variant="outlined"
            value={values.password}
            onChange={handleChange}
            onBlur={handleBlur}
            helperText={touched.password ? errors.password : ''}
            error={touched.password && Boolean(errors.password)}
            InputProps={{
              endAdornment: (
                <InputAdornment>
                  <LockIcon />
                </InputAdornment>
              ),
            }}
          />
        </CardContent>

        <CardActions className={classes.loginButtonSection}>
          <Button
            color="primary"
            variant="contained"
            onClick={signIn}
            className={classes.loginButton}
            disabled={isSubmitting}
          >
            Log In
          </Button>
        </CardActions>
      </form>
    </Card>
  );
};

let yup = require('yup');

const Form = withFormik({
  mapPropsToValues: ({ username, password }) => {
    return {
      username: username || '',
      password: password || '',
    };
  },

  validationSchema: yup.object().shape({
    username: yup.string().required('Required'),
    password: yup.string().min(8, 'Password must contain at least 8 characters').required('Enter your password'),
  }),

  handleSubmit: (values, { setSubmitting }) => {
    setTimeout(() => {
      // submit to the server
      alert(JSON.stringify(values, null, 2));
      setSubmitting(false);
    }, 1000);
  },
})(LoginForm);

LoginForm.propTypes = {
  className: PropTypes.string,
};

export default LoginForm(useStyles)(Form);
</code>```

答:
withFormik

Create a higher-order React component class that passes props and form handlers (the "FormikBag") into your component derived from supplied options.

Just export the Form not LoginForm. Also to use classes do const classes = useStyles(); inside the component rather than passing it as props.

Working copy of your code is here

Code Snippet

const useStyles = makeStyles(theme => ({
  root: {},
  cardHeader: {
    // backgroundColor: theme.palette.primary.main,
    backgroundColor: "blue",
    color: "white",
    display: "flex",
    justifyContent: "center",
    fontSize: "2rem",
    padding: "15px"
  },
  textFieldSection: {
    padding: "40px 40px 0 40px"
  },
  loginButtonSection: {
    padding: "18px 40px 40px 40px"
  },
  loginButton: {
    width: "100%",
    height: "50px",
    textTransform: "none",
    fontSize: "18px"
  }
}));

const LoginForm = props => {
  const { className, ...rest } = props;
  const classes = useStyles();

  const isLoggedIn = true;
  const referer = props.referer;

  const signIn = () => {
    console.log("signin");
  };

  const {
    // classes,
    values,
    touched,
    errors,
    isSubmitting,
    handleChange,
    handleBlur,
    handleSubmit
  } = props;

  if (isLoggedIn) {
    // return <Redirect to={referer} />;
    console.log("isLoggedIn", isLoggedIn);
  }

  return (
    <Card {...rest} className={clsx(classes.root, className)}>
      <form onSubmit={handleSubmit}>
        <CardHeader
          title="LOGIN"
          classes={{
            title: classes.cardHeader
          }}
          className={classes.cardHeader}
        />

        <CardContent className={classes.textFieldSection}>
          <TextField
            fullWidth
            label="Username"
            name="username"
            type="text"
            variant="outlined"
            value={values.username}
            onChange={handleChange}
            onBlur={handleBlur}
            helperText={touched.username ? errors.username : ""}
            error={touched.username && Boolean(errors.username)}
            InputProps={{
              endAdornment: (
                <InputAdornment>
                  <AccountCircle />
                </InputAdornment>
              )
            }}
          />
          <TextField
            fullWidth
            label="Password"
            name="password"
            style={{ marginTop: "1rem" }}
            type="password"
            variant="outlined"
            value={values.password}
            onChange={handleChange}
            onBlur={handleBlur}
            helperText={touched.password ? errors.password : ""}
            error={touched.password && Boolean(errors.password)}
            InputProps={{
              endAdornment: (
                <InputAdornment>
                  <LockIcon />
                </InputAdornment>
              )
            }}
          />
        </CardContent>

        <CardActions className={classes.loginButtonSection}>
          <Button
            type="submit" //<----------- see here
            color="primary"
            variant="contained"
            onClick={signIn}
            className={classes.loginButton}
            disabled={isSubmitting}
          >
            Log In
          </Button>
        </CardActions>
      </form>
    </Card>
  );
};

let yup = require("yup");

const Form = withFormik({
  mapPropsToValues: ({ username, password }) => {
    return {
      username: username || "",
      password: password || ""
    };
  },

  validationSchema: yup.object().shape({
    username: yup.string().required("Required"),
    password: yup
      .string()
      .min(8, "Password must contain at least 8 characters")
      .required("Enter your password")
  }),

  handleSubmit: (values, { setSubmitting }) => {
    setTimeout(() => {
      // submit to the server
      alert(JSON.stringify(values, null, 2));
      setSubmitting(false);
    }, 1000);
  }
})(LoginForm);

LoginForm.propTypes = {
  className: PropTypes.string
};

// export default LoginForm(useStyles)(Form);
export default Form;

```

Body:
I have a problem in implementing login validations in ReactJS. I'm using Material-UI and Formik and Yap. I have implemented it but it has an error, it says invalid hook call. Hooks can only be called inside of the body of a function component.

Pls check my code below:

import React, { useState } from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/styles';
import { Card, CardHeader, CardContent, CardActions, Divider, Button, TextField } from '@material-ui/core';
import { useSelector, useDispatch } from 'react-redux';
import { Redirect } from 'react-router-dom';
import { login } from '../../../actions';
import AccountCircle from '@material-ui/icons/AccountCircle';
import InputAdornment from '@material-ui/core/InputAdornment';
import LockIcon from '@material-ui/icons/Lock';
import { withFormik } from 'formik';

const useStyles = makeStyles((theme) => ({
  root: {},
  cardHeader: {
    backgroundColor: theme.palette.primary.main,
    color: 'white',
    display: 'flex',
    justifyContent: 'center',
    fontSize: '2rem',
    padding: '15px',
  },
  textFieldSection: {
    padding: '40px 40px 0 40px',
  },
  loginButtonSection: {
    padding: '18px 40px 40px 40px',
  },
  loginButton: {
    width: '100%',
    height: '50px',
    textTransform: 'none',
    fontSize: '18px',
  },
}));

const LoginForm = (props) => {
  const { className, ...rest } = props;

  const isLoggedIn = useSelector((state) => state.auth.isLoggedIn);
  const referer = props.referer;
  const dispatch = useDispatch();

  const signIn = () => {
    dispatch(login(values.username, values.password));
  };

  const { classes, values, touched, errors, isSubmitting, handleChange, handleBlur, handleSubmit } = props;

  if (isLoggedIn) {
    return <Redirect to={referer} />;
  }

  return (
    <Card {...rest} className={clsx(classes.root, className)}>
      <form onSubmit={handleSubmit}>
        <CardHeader
          title="LOGIN"
          classes={{
            title: classes.cardHeader,
          }}
          className={classes.cardHeader}
        />

        <CardContent className={classes.textFieldSection}>
          <TextField
            fullWidth
            label="Username"
            name="username"
            type="text"
            variant="outlined"
            value={values.username}
            onChange={handleChange}
            onBlur={handleBlur}
            helperText={touched.username ? errors.username : ''}
            error={touched.username && Boolean(errors.username)}
            InputProps={{
              endAdornment: (
                <InputAdornment>
                  <AccountCircle />
                </InputAdornment>
              ),
            }}
          />
          <TextField
            fullWidth
            label="Password"
            name="password"
            style={{ marginTop: '1rem' }}
            type="password"
            variant="outlined"
            value={values.password}
            onChange={handleChange}
            onBlur={handleBlur}
            helperText={touched.password ? errors.password : ''}
            error={touched.password && Boolean(errors.password)}
            InputProps={{
              endAdornment: (
                <InputAdornment>
                  <LockIcon />
                </InputAdornment>
              ),
            }}
          />
        </CardContent>

        <CardActions className={classes.loginButtonSection}>
          <Button
            color="primary"
            variant="contained"
            onClick={signIn}
            className={classes.loginButton}
            disabled={isSubmitting}
          >
            Log In
          </Button>
        </CardActions>
      </form>
    </Card>
  );
};

let yup = require('yup');

const Form = withFormik({
  mapPropsToValues: ({ username, password }) => {
    return {
      username: username || '',
      password: password || '',
    };
  },

  validationSchema: yup.object().shape({
    username: yup.string().required('Required'),
    password: yup.string().min(8, 'Password must contain at least 8 characters').required('Enter your password'),
  }),

  handleSubmit: (values, { setSubmitting }) => {
    setTimeout(() => {
      // submit to the server
      alert(JSON.stringify(values, null, 2));
      setSubmitting(false);
    }, 1000);
  },
})(LoginForm);

LoginForm.propTypes = {
  className: PropTypes.string,
};

export default LoginForm(useStyles)(Form);


问:
Calling git.init() when repository already exists
I am using the following snippet of code to initialize the git repository:

```<code>try (Git git = Git.init().setDirectory(gitFilename).call()) {
    log.info("Created repository: " + git.getRepository().getDirectory());
} catch (GitAPIException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
</code>```

What happens when the repository is already created and I call git.init() on it?

Thanks! Ana

答:
This appeared to work for me:</p>

```<code>//initialize git repository
        String gitDirectory = getGitRepoDirectory();
        File gitFilename = new File(gitDirectory);
        try (Git git = Git.open(gitFilename)){
            log.info("Git repo " + gitDirectory + " exists!");;
        } catch (RepositoryNotFoundException e) {
            log.info("Initialising " + gitDirectory + " as a git repo for backup purposes");
            try {
                Git git = Git.init().setDirectory(gitFilename).call();

                } catch (GitAPIException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
</code>```

Body:
I am using the following snippet of code to initialize the git repository:

try (Git git = Git.init().setDirectory(gitFilename).call()) {
    log.info("Created repository: " + git.getRepository().getDirectory());
} catch (GitAPIException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

What happens when the repository is already created and I call git.init() on it?

Thanks! Ana

Body:
This appeared to work for me:

//initialize git repository
        String gitDirectory = getGitRepoDirectory();
        File gitFilename = new File(gitDirectory);
        try (Git git = Git.open(gitFilename)){
            log.info("Git repo " + gitDirectory + " exists!");;
        } catch (RepositoryNotFoundException e) {
            log.info("Initialising " + gitDirectory + " as a git repo for backup purposes");
            try {
                Git git = Git.init().setDirectory(gitFilename).call();

                } catch (GitAPIException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }