问:
I want to add items from js generated product table to cart table but I don't how to tell the system what table row am selecting
I'm still trying to find a way to get the addToCart() function to work.

fetch('server.php')
  .then((res) => res.json())
  .then((response) => {
    let output = '';
    for (let i in response) {
      output += `

            ${response[i].quantity}
            <button>${response[i].productName}</button>
            ₦${response[i].price}.00
            <button id="go" onclick="addToCart()">+1</button>
            <input type="text">

`;
    }
    document.querySelector('.tbody').innerHTML = output;
  })
  .catch((error) => console.log(error));

function addToCart() {
  document.getElementById('fillUp').innerHTML += '
123</d>
';
  console.log(val);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Product Table -->
<table id="myTable">
  <thead class="tHeadRow">
    <th>Quantity</th>
    <th>Products</th>
    <th>Price</th>
  </thead>
  <tbody class="tbody"></tbody>
</table>

<!-- Cart Table -->
<div class="cart">
  <h3>Checkout Cart</h3>
  <div class="cartContent">
    <table class="cartTable">
      <tbody id="fillUp"></tbody>
      <tfoot>
        <tr>
          <td style="font-weight: bold">Total:</td>
          <td style="font-weight: bold"></td>
        </tr>
      </tfoot>
    </table>
  </div>
</div>

<!--- I got a possible solution but when I tried it, I got Uncaught --->
<!--- TypeError: Cannot read properties of null (reading 'rows') --->

 var tbody = document.getElementById('tbody'),rIndex;
var tb = tbody.rows.length;
for(var i = 0; i < tb; i++) {
    tbody.rows[i].onclick = function() {
        console.log(this.cells[0].innerHTML);
    }</code>```

答:
Dropping a row into another table was accomplished mainly by cloneNode() and the original row was removed by .remove(). In the OP code:

```<code>  var tbody = document.getElementById('tbody'),rIndex;
</code>```

This makes very little sense. There is no tag with an id of #tbody there's a tag with a class of .tbody which at the very least can be accessed by .querySelector() that's why it's null.

The problem will run into as I see it is that you are using an inline event handler:

```<code>   onclick="addToCart()"
</code>```

Inline event handlers are garbage. Use on event properties and/or event listeners, read the following after reviewing the example below:

Events

Event Delegation

HTMLFormElement

const allTables = document.querySelectorAll('table');
const shop = allTables[0].tBodies[0];
const cart = allTables[1].tBodies[0];

fetch('https://my.api.mockaroo.com/i_mart.json?key=3634fcf0')
  .then((res) => res.json())
  .then((response) => {
    let output = '';
    for (let i in response) {
      output += `

            <button name='itm' class='itm' type='button'>${response[i].item}</button>
            ₦${response[i].price.substring(1)}
            <input name='qty' class='qty' value='${response[i].quantity}' readonly>
            <input name='def' value='${response[i].quantity}' type='hidden'>

            <input name='cnt' class='cnt' value='0' readonly><button name="add" class='btn add' type='button' disabled>+1</button>
            <button name="sub"  class='btn sub' type='button' disabled>-1</button>

            <input name='subT' class='subT' value='₦0.00' readonly>

`;
    }
    shop.innerHTML = output;
  })
  .catch((error) => console.log(error));

const itemTo = (row, dest) => {
  const copy = row.cloneNode(true);
  row.remove();
  dest.appendChild(copy);
  const btns = copy.querySelectorAll('.btn');
  const fields = copy.querySelectorAll('input');
  if (dest === cart) {
    btns[0].disabled = false;
  } else {
    btns.forEach(btn => btn.disabled = true);
    fields[0].value = fields[1].value;
    fields[2].value = '0';
    fields[3].value = '₦0.00';
  }
};

const addToSubFrom = (row, dir) => {
  let D = dir === undefined ? 1 : dir;
  const cells = row.children;
  let add = row.querySelector('.add');
  let sub = row.querySelector('.sub');
  let prc = cells[1].textContent.substring(1);
  let qty = cells[2].firstElementChild;
  let cnt = cells[3].firstElementChild;
  let subT = cells[4].firstElementChild;

  let c = +cnt.value + D;
  if (c === 0) {
    sub.disabled = true;
  } else {
    sub.disabled = false;
  }
  let q = +qty.value - D;
  if (q === 0) {
    add.disabled = true;
  } else {
    add.disabled = false;
  }
  let p = +prc;
  let sT = ((p * 100) * c) / 100;

  cnt.value = c;
  qty.value = q;
  subT.value = '₦' + sT.toFixed(2);
};

const getTotal = array => array.map(inp => +inp.value.substring(1) * 100).reduce((sum, cur) => sum + cur);

const addToCart = e => {
  const io = e.currentTarget.elements;
  const btn = e.target;

  if (btn.matches('button')) {
    let row = document.querySelector('#' + btn.closest('tr').id);
    let S;
    switch (btn.name) {
      case 'itm':
        let dest = btn.closest('tbody').className === 'shop' ? cart : shop;
        itemTo(row, dest);
        S = [...io.subT];
        io.total.value = (getTotal(S) / 100).toFixed(2);
        break;
      case 'add':
        S = [...io.subT];
        addToSubFrom(row);
        io.total.value = (getTotal(S) / 100).toFixed(2);
        break;
      case 'sub':
        S = [...io.subT];
        addToSubFrom(row, -1);
        io.total.value = (getTotal(S) / 100).toFixed(2);
        break;
      default:
        break;
    }
  }
  e.stopPropagation();
};

const UI = document.forms[0];
UI.onclick = addToCart;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  font: 1ch/1.5 'Segoe UI'
}

body {
  font-size: 3ch;
}

table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
}

caption {
  font-size: 2rem;
  font-weight: 900
}

.h1 {
  width: 35%;
}

.h3 {
  width: 20%;
}

.h3 {
  width: 10%;
}

.h4 {
  width: 20%;
  text-align: left;
}

.h5 {
  width: 15%;
}

td:nth-of-type(n+2) {
  text-align: center;
}

tfoot th {
  text-align: right;
}

input,
output {
  display: inline-block;
  font-size: 100%;
  line-height: 1.15;
}

input,
output,
td:nth-of-type(2) {
  font-family: Consolas
}

button {
  font-size: 1.25rem;
  cursor: pointer;
}

output {
  font-weight: 900;
}

.qty,
.cnt,
.subT {
  width: 2ch;
  border: 0;
}

.subT {
  width: 6ch
}</code>```

<form>

      iMart™ Online Wholesale

      Item
      Price
      Qty
      Count
      SubTotal

Checkout Cart

      Item
      Price
      Qty
      Count
      SubTotal

        Total: ₦
        <output id='total'></output>

</form>```

Body:
I'm still trying to find a way to get the addToCart() function to work.

fetch('server.php')
  .then((res) => res.json())
  .then((response) => {
    let output = '';
    for (let i in response) {
      output += `

            ${response[i].quantity}
            <button>${response[i].productName}</button>
            ₦${response[i].price}.00
            <button id="go" onclick="addToCart()">+1</button>
            <input type="text">

`;
    }
    document.querySelector('.tbody').innerHTML = output;
  })
  .catch((error) => console.log(error));

function addToCart() {
  document.getElementById('fillUp').innerHTML += '
123</d>
';
  console.log(val);
}

    Quantity
    Products
    Price

Checkout Cart

          Total:

 var tbody = document.getElementById('tbody'),rIndex;
var tb = tbody.rows.length;
for(var i = 0; i < tb; i++) {
    tbody.rows[i].onclick = function() {
        console.log(this.cells[0].innerHTML);
    }

Body:
Dropping a row into another table was accomplished mainly by cloneNode() and the original row was removed by .remove(). In the OP code:

  var tbody = document.getElementById('tbody'),rIndex;

This makes very little sense. There is no tag with an id of #tbody there's a tag with a class of .tbody which at the very least can be accessed by .querySelector() that's why it's null.

The problem will run into as I see it is that you are using an inline event handler:

   onclick="addToCart()"

Inline event handlers are garbage. Use on event properties and/or event listeners, read the following after reviewing the example below:

Events

Event Delegation

HTMLFormElement

const allTables = document.querySelectorAll('table');
const shop = allTables[0].tBodies[0];
const cart = allTables[1].tBodies[0];

fetch('https://my.api.mockaroo.com/i_mart.json?key=3634fcf0')
  .then((res) => res.json())
  .then((response) => {
    let output = '';
    for (let i in response) {
      output += `<tr id='R${i}'>
            <td><button name='itm' class='itm' type='button'>${response[i].item}</button></td>
            <td>₦${response[i].price.substring(1)}</td>
            <td><input name='qty' class='qty' value='${response[i].quantity}' readonly>
            <input name='def' value='${response[i].quantity}' type='hidden'>
            </td>
            <td><input name='cnt' class='cnt' value='0' readonly><button name="add" class='btn add' type='button' disabled>+1</button>
            <button name="sub"  class='btn sub' type='button' disabled>-1</button>
            </td>
            <td><input name='subT' class='subT' value='₦0.00' readonly></td>
        </tr>`;
    }
    shop.innerHTML = output;
  })
  .catch((error) => console.log(error));

const itemTo = (row, dest) => {
  const copy = row.cloneNode(true);
  row.remove();
  dest.appendChild(copy);
  const btns = copy.querySelectorAll('.btn');
  const fields = copy.querySelectorAll('input');
  if (dest === cart) {
    btns[0].disabled = false;
  } else {
    btns.forEach(btn => btn.disabled = true);
    fields[0].value = fields[1].value;
    fields[2].value = '0';
    fields[3].value = '₦0.00';
  }
};

const addToSubFrom = (row, dir) => {
  let D = dir === undefined ? 1 : dir;
  const cells = row.children;
  let add = row.querySelector('.add');
  let sub = row.querySelector('.sub');
  let prc = cells[1].textContent.substring(1);
  let qty = cells[2].firstElementChild;
  let cnt = cells[3].firstElementChild;
  let subT = cells[4].firstElementChild;

  let c = +cnt.value + D;
  if (c === 0) {
    sub.disabled = true;
  } else {
    sub.disabled = false;
  }
  let q = +qty.value - D;
  if (q === 0) {
    add.disabled = true;
  } else {
    add.disabled = false;
  }
  let p = +prc;
  let sT = ((p * 100) * c) / 100;

  cnt.value = c;
  qty.value = q;
  subT.value = '₦' + sT.toFixed(2);
};

const getTotal = array => array.map(inp => +inp.value.substring(1) * 100).reduce((sum, cur) => sum + cur);

const addToCart = e => {
  const io = e.currentTarget.elements;
  const btn = e.target;

  if (btn.matches('button')) {
    let row = document.querySelector('#' + btn.closest('tr').id);
    let S;
    switch (btn.name) {
      case 'itm':
        let dest = btn.closest('tbody').className === 'shop' ? cart : shop;
        itemTo(row, dest);
        S = [...io.subT];
        io.total.value = (getTotal(S) / 100).toFixed(2);
        break;
      case 'add':
        S = [...io.subT];
        addToSubFrom(row);
        io.total.value = (getTotal(S) / 100).toFixed(2);
        break;
      case 'sub':
        S = [...io.subT];
        addToSubFrom(row, -1);
        io.total.value = (getTotal(S) / 100).toFixed(2);
        break;
      default:
        break;
    }
  }
  e.stopPropagation();
};

const UI = document.forms[0];
UI.onclick = addToCart;

:root {
  font: 1ch/1.5 'Segoe UI'
}

body {
  font-size: 3ch;
}

table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
}

caption {
  font-size: 2rem;
  font-weight: 900
}

.h1 {
  width: 35%;
}

.h3 {
  width: 20%;
}

.h3 {
  width: 10%;
}

.h4 {
  width: 20%;
  text-align: left;
}

.h5 {
  width: 15%;
}

td:nth-of-type(n+2) {
  text-align: center;
}

tfoot th {
  text-align: right;
}

input,
output {
  display: inline-block;
  font-size: 100%;
  line-height: 1.15;
}

input,
output,
td:nth-of-type(2) {
  font-family: Consolas
}

button {
  font-size: 1.25rem;
  cursor: pointer;
}

output {
  font-weight: 900;
}

.qty,
.cnt,
.subT {
  width: 2ch;
  border: 0;
}

.subT {
  width: 6ch
}

<!-- Product Table -->
<form>
  <table>
    <caption>
      iMart™ Online Wholesale
    </caption>
    <thead>
      <th class='h1'>Item</th>
      <th class='h2'>Price</th>
      <th class='h3'>Qty</th>
      <th class='h4'>Count</th>
      <th class='h5'>SubTotal</th>
    </thead>
    <tbody class='shop'></tbody>
  </table>

  <!-- Cart Table -->

  <table>
    <caption>Checkout Cart</caption>
    <thead>
      <th class='h1'>Item</th>
      <th class='h2'>Price</th>
      <th class='h3'>Qty</th>
      <th class='h4'>Count</th>
      <th class='h5'>SubTotal</th>
    </thead>
    <tbody class='cart'></tbody>
    <tfoot>
      <tr>
        <th colspan='4'>Total: ₦</th>
        <td><output id='total'></output></td>
      </tr>
    </tfoot>
  </table>
</form>


来源: stackexchange

问:
using python I'm trying to insert ADMIN_ID as None in to a database in SQL and my date_time that converted into a suitable format into a table
this works but i cant seem to get the other format to work

```<code>conn=sqlite3.connect("Jakson.db")
("Database Opened successfully")

conn.execute('INSERT INTO SMITH(EXPIRE) VALUES (?)',  [date_time])
</code>```

i know that the date_time will work becasue ive already tested it on its own in a another database but i can seem to get this one to work

```<code>#conn=sqlite3.connect("Jakson.db")
#print("Database Opened successfully")
#conn.execute("""
#CREATE TABLE SMITH(
#ADMIN_ID INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL ,
#EXPIRE DATE
#)
#""")
import datetime
import pytz
import sqlite3

today = datetime.datetime.now()
date_time = today.strftime("%m/%d/%Y")

conn=sqlite3.connect("Jakson.db")
("Database Opened successfully")

conn.execute('INSERT INTO SMITH VALUES (:ADMIN_ID, :EXPIRE)',
         {
         'ADMIN_ID': None,
         'EXPIRE':[date_time]
          })
</code>```

InterfaceError: Error binding parameter :EXPIRE - probably unsupported type.

答:
```<code>conn.execute('INSERT INTO SMITH VALUES (:ADMIN_ID, :EXPIRE)',
             {
             'ADMIN_ID': None,
             'EXPIRE': date_time
              })
</code>```

figure it out had to remove the brackets [date_time]

ContentLicense: CC BY-SA 4.0

Body:
this works but i cant seem to get the other format to work

conn=sqlite3.connect("Jakson.db")
("Database Opened successfully")

conn.execute('INSERT INTO SMITH(EXPIRE) VALUES (?)',  [date_time])

i know that the date_time will work becasue ive already tested it on its own in a another database but i can seem to get this one to work

#conn=sqlite3.connect("Jakson.db")
#print("Database Opened successfully")
#conn.execute("""
#CREATE TABLE SMITH(
#ADMIN_ID INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL ,
#EXPIRE DATE
#)
#""")
import datetime
import pytz
import sqlite3

today = datetime.datetime.now()
date_time = today.strftime("%m/%d/%Y")

conn=sqlite3.connect("Jakson.db")
("Database Opened successfully")

conn.execute('INSERT INTO SMITH VALUES (:ADMIN_ID, :EXPIRE)',
         {
         'ADMIN_ID': None,
         'EXPIRE':[date_time]
          })

InterfaceError: Error binding parameter :EXPIRE - probably unsupported type.

Body:
conn.execute('INSERT INTO SMITH VALUES (:ADMIN_ID, :EXPIRE)',
             {
             'ADMIN_ID': None,
             'EXPIRE': date_time
              })

figure it out had to remove the brackets [date_time]


问:
How to send email to recipient with umlauts in domain name?
In my app I have to send email to recipient who has umlauts in domain name.
Example:
"test@äöü.test.com"

I'm using cfmail tag and I'm getting such error:
"invalid definition for attribute to at tag mail"
"Invalid E-Mail Address definition (test@äöü.test.com)"

Is there any way to send email to such recipients in coldfusion?

答:
There is even a easier solution! Why not use Oracles built in class:
http://download.oracle.com/javase/6/docs/api/java/net/IDN.html#toUnicode(java.lang.String)

Then you only have to do this (example shows from punycode to Unicode):

```<code><cfset strUrl = "xn--land-poa.se" />

<!--- Create a Java URL. --->
<cfset jUrl = CreateObject( "java", "java.net.IDN" ).toUnicode(strUrl) />

<cfoutput>
#jUrl#
</code>```

You don´t have to download anything!

ContentLicense: CC BY-SA 3.0

Body:
There is even a easier solution! Why not use Oracles built in class:
http://download.oracle.com/javase/6/docs/api/java/net/IDN.html#toUnicode(java.lang.String)

Then you only have to do this (example shows from punycode to Unicode):

<cfset strUrl = "xn--land-poa.se" />

<!--- Create a Java URL. --->
<cfset jUrl = CreateObject( "java", "java.net.IDN" ).toUnicode(strUrl) />

<cfoutput>
#jUrl#

You don´t have to download anything!


问:
SwiftUI clean up ContentView
I'm trying to simplify the ContentView within a project and I'm struggling to understand how to move @State based logic into its own file and have ContentView adapt to any changes. Currently I have dynamic views that display themselves based on @Binding actions which I'm passing the $binding down the view hierarchy to have buttons toggle the bool values.

Here's my current attempt. I'm not sure how in SwiftUI to change the view state of SheetPresenter from a nested view without passing the $binding all the way down the view stack. Ideally I'd like it to look like ContentView.overlay(sheetPresenter($isOpen, $present).

Also, I'm learning SwiftUI so if this isn't the best approach please provide guidance.

```<code>class SheetPresenter: ObservableObject {

@Published var present: Present = .none
@State var isOpen: Bool = false

enum Present {
    case none, login, register
}

@ViewBuilder
func makeView(with presenter: Present) -> some View {
    switch presenter {
    case .none:
        EmptyView()
    case .login:
        BottomSheetView(isOpen: $isOpen, maxHeight: UIConfig.Utils.screenHeight * 0.75) {
            LoginScreen()
        }
    case .register:
        BottomSheetView(isOpen: $isOpen, maxHeight: UIConfig.Utils.screenHeight * 0.75) {
            RegisterScreen()
        }
    }
}
</code>```

}

答:
if you don't want to pass  $binding all the way down the view  you can create a StateObject variable in the top view and pass it with .environmentObject(). and access it from any view with  EnvironmentObject</p>
```<code>struct testApp: App {
        @StateObject var s1:  sViewModel = sViewModel()
        var body: some Scene {
            WindowGroup {
                ContentView()
                    .environmentObject(s1)
            }
        }
    }
</code>```

Title: SwiftUI clean up ContentView

Body:
I'm trying to simplify the ContentView within a project and I'm struggling to understand how to move @State based logic into its own file and have ContentView adapt to any changes. Currently I have dynamic views that display themselves based on @Binding actions which I'm passing the $binding down the view hierarchy to have buttons toggle the bool values.

Here's my current attempt. I'm not sure how in SwiftUI to change the view state of SheetPresenter from a nested view without passing the $binding all the way down the view stack. Ideally I'd like it to look like ContentView.overlay(sheetPresenter($isOpen, $present).

Also, I'm learning SwiftUI so if this isn't the best approach please provide guidance.

class SheetPresenter: ObservableObject {

@Published var present: Present = .none
@State var isOpen: Bool = false

enum Present {
    case none, login, register
}

@ViewBuilder
func makeView(with presenter: Present) -> some View {
    switch presenter {
    case .none:
        EmptyView()
    case .login:
        BottomSheetView(isOpen: $isOpen, maxHeight: UIConfig.Utils.screenHeight * 0.75) {
            LoginScreen()
        }
    case .register:
        BottomSheetView(isOpen: $isOpen, maxHeight: UIConfig.Utils.screenHeight * 0.75) {
            RegisterScreen()
        }
    }
}

}

Body:
if you don't want to pass  $binding all the way down the view  you can create a StateObject variable in the top view and pass it with .environmentObject(). and access it from any view with  EnvironmentObject

struct testApp: App {
        @StateObject var s1:  sViewModel = sViewModel()
        var body: some Scene {
            WindowGroup {
                ContentView()
                    .environmentObject(s1)
            }
        }
    }


问:
What is difference between pg_squeeze and pg_repack?
I've been working on optimizing tables in database. One of our table requires monthly vacuuming because of cleaning up processes.pg_squeeze Table size can get upto 25 GB. As this table is used by production users, we can't afford downtime every month to run VACUUM FULL.

I found that pg_squeeze and pg_repack can be used for this purpose. But I'm not able to understand the difference between those two. Can someone please explain what is the difference and which will be more suitable for me to use?

Thank you.

答:
The main difference is that pg_squeeze operates entirely inside the database, with no need for an external binary.  It also has a background worker that will schedule table rewrites automatically if certain criteria are met.

So you could say that pg_repack is less invasive (for example, installation requires no restart of the database), but pg_squeeze is more feature complete.

Disclaimer: I work for the company who wrote pg_squeeze.


问:
Firebase dynamic links always opens app store
I have been trying to get dynamic links working all day to no success.

I have created a dynamic link using firebase web and with a google provided link.  I have added the associated domains as instructed (applinks:https://myapp.page.link/sZZL), and also have firebase hosting set up.

On firebase I have checked the Team ID and App store ID (its not released to the app store, but in uploaded to apple developer account and so has an ID) are correct.

The url type is set up correctly, with the bundle id set.

If I open the link in chrome, it redirects to the app just fine.

I've tried sending a email with the link and adding it to notes and opening from there. All open the app preview page which then redirects to the app store.

Thee app is not on the app store yet as it is in development - would this impact it?

I simply want it to redirect to the app (which is on the phone in question) rather than the app store

答:
I had the same issue that my app always went to the App Store page. The app was already live. I followed the complete instructions about Associated Domains etc, all setup was correct.

What my issue was that Firebase asks for Team ID & App ID.
The Team ID is used in the apple-app-site-association so you would get something like:

{"applinks":{"apps":[],"details":[{"appID":"TEAMID.bundleID","paths":["NOT /_/*","/*"]}]}}

I noticed in my app Identifier in Developer Center (at certificates & profiles) when you press the identifier that you're working with on the top right there is an App ID Prefix stated. And for most (newer) apps that will be the same as the Team ID but sometimes it's different.

When it's different, in Firebase at the Team ID field you should enter the App ID Prefix!

After a while (took me 15 min or so) the apple-app-site-association will be changed and the new prefix will be shown. Again after some time my Firebase Dynamic Links started to work nicely.

Hope this helps some people that have the same problem and save them some time.


问:
Allowing 2 date types for an attribute in an XML schema
I have written an XML schema and one of the elements is date. Below is the section of the schema that defines date

```<code><xs:element name="temporal">
    <!--start date and end date-->
    <xs:complexType>
        <xs:sequence>
            <xs:element maxOccurs="unbounded" name="date">
                <xs:complexType>
                    <xs:attribute name ="date" type ="xs:date" use="required"/>
                    <xs:attribute name="dateType" type="xs:string" use="required"/>
                    <xs:attribute name="dateFormat" type="xs:string" use="required"/>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>
</code>```

For the attribute
<xs:attribute name ="date" type ="xs:date" use="required"/>

I want to be able to have either type = "xs:date" or type = "xs:gYear" as some collections do not contain full YYYY-MM-DD formats. I attempted doing:

```<code><xs:element name="date">
    <xs:simpleType>
        <xs:union memberTypes="xs:date xs:gYear" />
    </xs:simpleType>
</xs:element>
</code>```

but this did not work and when I exported the excel form the YYYY date was stored as 1905-02-04. I do not really know if it is possible to have an "or" option with xml schemas? or a solution that allows the option of the two date types without having to have two separate elements?

Any advice or solutions would be helpful

答:
I think you want

```<code><xs:simpleType name="date-or-gYear">
    <xs:union memberTypes="xs:date xs:gYear" />
</xs:simpleType>
</code>```

and then

```<code><xs:attribute name="date" type ="date-or-gYear" use="required"/>

</code>```

Body:
I have written an XML schema and one of the elements is date. Below is the section of the schema that defines date

<xs:element name="temporal">

    <xs:complexType>
        <xs:sequence>
            <xs:element maxOccurs="unbounded" name="date">
                <xs:complexType>
                    <xs:attribute name ="date" type ="xs:date" use="required"/>
                    <xs:attribute name="dateType" type="xs:string" use="required"/>
                    <xs:attribute name="dateFormat" type="xs:string" use="required"/>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>

For the attribute
<xs:attribute name ="date" type ="xs:date" use="required"/>

I want to be able to have either type = "xs:date" or type = "xs:gYear" as some collections do not contain full YYYY-MM-DD formats. I attempted doing:

<xs:element name="date">
    <xs:simpleType>
        <xs:union memberTypes="xs:date xs:gYear" />
    </xs:simpleType>
</xs:element>

but this did not work and when I exported the excel form the YYYY date was stored as 1905-02-04. I do not really know if it is possible to have an "or" option with xml schemas? or a solution that allows the option of the two date types without having to have two separate elements?

Any advice or solutions would be helpful

Body:
I think you want

<xs:simpleType name="date-or-gYear">
    <xs:union memberTypes="xs:date xs:gYear" />
</xs:simpleType>

and then

<xs:attribute name="date" type ="date-or-gYear" use="required"/>


问:
Showing only some part of the list on the Grid Control
Here is an exemplary code piece:

Model.cs

```<code>public class Datas
{
    public int Region;
    public int Frequency;
    public int Amplitude;
}
</code>```

MainViewModel.cs

```<code>public Datas Data1;

public MainViewModel()
{
    DataList = new ObservableCollection<Datas>();
    GetDatas();
}

public ObservableCollection<Datas> DataList { get; set; }

public void GetDatas()
{
    ...
    ...

    var command = new SqlCommand($"Select [Region], [Frequency], [Amplitude].. WHERE REGION = '{SelectedRegion}..");
    var dataReader = command.ExecuteReader();

    while (dataReader.Read())
    {
        var Data1 = new Datas();
        Data1.Region = dataReader["Region"];
        Data1.Frequency = dataReader["Frequency"];
        Data1.Amplitude = dataReader["Amplitude"];

        DataList.Add(Data1);
    }

    connection.close();
}
</code>```

(I tried to use DevExpressMVVM tools.)

MainView.xaml

```<code><dxg:GridControl ItemsSource = "{Binding DataList} ...../>
</code>```

Now; I can see the table on the window with Region, Frequency, and Amplitude columns and their values.
But I want only to show the 2 columns; maybe like Frequency and Amplitude.

What would be the most efficient way to do this?

答:
In XAML or in code you can set the column visibility to hidden.
If you give a name to your datagrid you can access his properties.

```<code><dxg:GridControl Name="myDatagrid" ItemsSource = "{Binding DataList} ...../>
</code>```

then in code :

```<code>myDataGrid.Columns[0].Visibility = Visibility.Hidden;
</code>```

Body:
Here is an exemplary code piece:

Model.cs

public class Datas
{
    public int Region;
    public int Frequency;
    public int Amplitude;
}

MainViewModel.cs

public Datas Data1;

public MainViewModel()
{
    DataList = new ObservableCollection<Datas>();
    GetDatas();
}

public ObservableCollection<Datas> DataList { get; set; }

public void GetDatas()
{
    ...
    ...

    var command = new SqlCommand($"Select [Region], [Frequency], [Amplitude].. WHERE REGION = '{SelectedRegion}..");
    var dataReader = command.ExecuteReader();

    while (dataReader.Read())
    {
        var Data1 = new Datas();
        Data1.Region = dataReader["Region"];
        Data1.Frequency = dataReader["Frequency"];
        Data1.Amplitude = dataReader["Amplitude"];

        DataList.Add(Data1);
    }

    connection.close();
}

(I tried to use DevExpressMVVM tools.)

MainView.xaml

<dxg:GridControl ItemsSource = "{Binding DataList} ...../>

Now; I can see the table on the window with Region, Frequency, and Amplitude columns and their values.
But I want only to show the 2 columns; maybe like Frequency and Amplitude.

What would be the most efficient way to do this?

Body:
In XAML or in code you can set the column visibility to hidden.
If you give a name to your datagrid you can access his properties.

<dxg:GridControl Name="myDatagrid" ItemsSource = "{Binding DataList} ...../>

then in code :

myDataGrid.Columns[0].Visibility = Visibility.Hidden;


问:
How to put a Wrap widget in a Column widget in Flutter
What I want:
image

```<code>child: IntrinsicWidth(
  child: Column(
    children: [
      Stack(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: const [
              Red(),
              Green(),
            ],
          ),
          const Align(
            child: Yellow(),
          ),
        ],
      ),
      const Blue(),
      const PurpleWrap(),
    ],
  ),
),
</code>```

What I got:
image

How can I achieve what I want?

Also can I achieve it without using IntrinsicWidth/Stack?

答:
try this

```<code>SizedBox(
        // your blue size
        width: 300,
        child: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
          Row(children: [
            Container(
                height: 100,
                alignment: Alignment.center,
                color: Colors.pink,
                child: Text("Flexible 22222")),
            Expanded(
              child: Container(
                color: Colors.yellow,
                height: 100,
              ),
            ),
            Container(
                height: 100,
                alignment: Alignment.center,
                color: Colors.amber,
                child: const Text("Horizontally center")),
            Expanded(
              child: Container(
                color: Colors.yellow,
                height: 100,
              ),
            ),
            Container(
                height: 100, color: Colors.green, child: Text("Flexible")),
          ]),
          Container(
              height: 200,
              width: double.infinity,
              color: Colors.blue,
              alignment: Alignment.center,
              child: Text("Fixed Size")),
          Container(
              color: Colors.grey,
              height: 50,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [Text("Wrap 1")])),
          Container(
              color: Colors.grey,
              margin: EdgeInsets.only(top: 8),
              height: 50,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [Text("Wrap 2")])),
        ]),
      )
</code>```

Body:
What I want:
image

child: IntrinsicWidth(
  child: Column(
    children: [
      Stack(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: const [
              Red(),
              Green(),
            ],
          ),
          const Align(
            child: Yellow(),
          ),
        ],
      ),
      const Blue(),
      const PurpleWrap(),
    ],
  ),
),

What I got:
image

How can I achieve what I want?

Also can I achieve it without using IntrinsicWidth/Stack?

Body:
try this

SizedBox(
        // your blue size
        width: 300,
        child: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
          Row(children: [
            Container(
                height: 100,
                alignment: Alignment.center,
                color: Colors.pink,
                child: Text("Flexible 22222")),
            Expanded(
              child: Container(
                color: Colors.yellow,
                height: 100,
              ),
            ),
            Container(
                height: 100,
                alignment: Alignment.center,
                color: Colors.amber,
                child: const Text("Horizontally center")),
            Expanded(
              child: Container(
                color: Colors.yellow,
                height: 100,
              ),
            ),
            Container(
                height: 100, color: Colors.green, child: Text("Flexible")),
          ]),
          Container(
              height: 200,
              width: double.infinity,
              color: Colors.blue,
              alignment: Alignment.center,
              child: Text("Fixed Size")),
          Container(
              color: Colors.grey,
              height: 50,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [Text("Wrap 1")])),
          Container(
              color: Colors.grey,
              margin: EdgeInsets.only(top: 8),
              height: 50,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [Text("Wrap 2")])),
        ]),
      )


问:
Highcharts networkgraph datalabels on hover
there!

I have a networkgraph built on highcharts and I need the datalabels to start turned of for some of the points. Then, I want to turn them on whenever user hovers a connected point. For this image, for example, on hovering "Rio de Janeiro", all the 5 points connected to it should have their datalabels on.

Any ideas on how to do this?

Thanks

答:
You can initially create all data labels, but hide them by setting opacity style to 0. Then, use mouseOver and mouseOut events to toggle the opacity.

```<code>const toggleDLInLinks = (links, isVisible) => {
    links.forEach(link => {
        if (isVisible) {
            link.toNode.dataLabel.css({
                opacity: 1
            })
        } else {
            link.toNode.dataLabel.css({
                opacity: 0
            })
        }

        if (link.toNode.linksFrom.length) {
            toggleDLInLinks(link.toNode.linksFrom, isVisible);
        }
    });
};

Highcharts.chart('container', {
    plotOptions: {
        networkgraph: {
            ...,
            dataLabels: {
                allowOverlap: true,
                enabled: true,
                style: {
                    opacity: 0,
                    transition: ''
                }
            },
            point: {
                events: {
                    mouseOver: function() {
                        const point = this;

                        if (point.linksFrom.length) {
                            toggleDLInLinks(point.linksFrom, true);
                        }
                    },
                    mouseOut: function() {
                        const point = this;
                        if (point.linksFrom.length) {
                            toggleDLInLinks(point.linksFrom);
                        }
                    }
                }
            },
            keys: ['from', 'to']
        }
    },
    ...
});
</code>```

Live demo: https://jsfiddle.net/5n2u1b3L/

API Reference: https://api.highcharts.com/class-reference/Highcharts.SVGElement#css

Body:
You can initially create all data labels, but hide them by setting opacity style to 0. Then, use mouseOver and mouseOut events to toggle the opacity.

const toggleDLInLinks = (links, isVisible) => {
    links.forEach(link => {
        if (isVisible) {
            link.toNode.dataLabel.css({
                opacity: 1
            })
        } else {
            link.toNode.dataLabel.css({
                opacity: 0
            })
        }

        if (link.toNode.linksFrom.length) {
            toggleDLInLinks(link.toNode.linksFrom, isVisible);
        }
    });
};

Highcharts.chart('container', {
    plotOptions: {
        networkgraph: {
            ...,
            dataLabels: {
                allowOverlap: true,
                enabled: true,
                style: {
                    opacity: 0,
                    transition: ''
                }
            },
            point: {
                events: {
                    mouseOver: function() {
                        const point = this;

                        if (point.linksFrom.length) {
                            toggleDLInLinks(point.linksFrom, true);
                        }
                    },
                    mouseOut: function() {
                        const point = this;
                        if (point.linksFrom.length) {
                            toggleDLInLinks(point.linksFrom);
                        }
                    }
                }
            },
            keys: ['from', 'to']
        }
    },
    ...
});

Live demo: https://jsfiddle.net/5n2u1b3L/

API Reference: https://api.highcharts.com/class-reference/Highcharts.SVGElement#css


问:
Set view as percentage of width in portrait and percentage of height in landscape, in interface builder using autolayout
I am creating a launch screen that has a centered image. I want the image to be 0.7 of the width in portrait orientation and 0.7 of the height in landscape orientation, so the image is the same size in both orientations, but relative to device size. It would be smaller on iPhones and larger on iPads, while supporting both orientations on iPad.

I can do one of those constraints but not both. For example, if I make it 0.7 of the width in portrait then it looks good in portrait but then oversized in landscape, and vice versa.

How do I create such autolayout purely in interface builder? (I'm assuming launch screens must only use IB.)

答:
You need to make constraints in respective of the view. For that, you need to follow the steps mentioned below :

Select your imageView.

Hold the control key and move your cursor to the main view.

Now click Equal widths constraint and give it the desired multiplier.

Repeat the above steps for the Equal Height constraint.

You are ready to go.


问:
Zend_Validate good strategy to avoid repetition of code
I'm am currently building two custom validators that extends Zend_Validate_Abstract which are named respectively Lib_Validate_TimeAfter and Lib_Validate_TimeBetween. The names a pretty straight forward, the first one is used to test if a date/datetime/time comes after an other one and the second is used to test if a date/datetime/time comes between two other date/datetime/time.

Both of those validators would rely on the same method named _buildDate($value) which take a value in the form of a datestamp, a hourstamp(either hh:mm or  hh:mm:ss), a timestamp or an ISO_8601 timestamp and convert it in a usable date format.

Since I dont want to repeat myself and copy/paste the method in both of my validator, I was looking for the best way to do it.

The avenues I am looking at right now would be to develop somekind of class helper that my validators would be able to use (kind of messy way of doing things since it add unessesary dependencies) or I could add an other layer of abstraction by building an other validator that validate date/datetime/time and then extend my two validators on that since I could share the method _buildDate($value), but then I don't think I would really need the validator.

So, what would be a good way (I am not really looking for the "Way of the gods" of doing thing) to structure that kind of code to avoid repetition (DRY)?

答:
You might want to build one validator instead of two, where you can pass in a dateBefore, dateAfter which are both optional. If you pass only dateBefore, your $value will be valid if it is after that date, if you pass in both, it will have to be between them and if you pass in only dateAfter, the value will have to be before that date.

This would be flexible, clear, generic, less code and even cover one more case.


问:
Flutter pdf plugin long text is not going in new line
I am using a plugin

pdf : ^3.7.1

On Using Following Code

```<code>pw.Text(Very Long Text,
    style: pw.TextStyle(
              fontSize: 20,
           ),
),
</code>```

The very long text is not going in a new line it's going out of the bound of the page.

As you can see the text is cut after reaching the end. Even on using paragraph same happened.

答:
That happens because that package can't "go inside" a single widget and split it in order to make it fit the page (or, in other cases, to create a new page).
You have to either wrap the text yourself and make it a multiline widget, or split the text yourself (maybe using something like CR or LF as separator) and divide it over different widgets.</p>

Body:
I am using a plugin

pdf : ^3.7.1

On Using Following Code

pw.Text(Very Long Text,
    style: pw.TextStyle(
              fontSize: 20,
           ),
),

The very long text is not going in a new line it's going out of the bound of the page.

As you can see the text is cut after reaching the end. Even on using paragraph same happened.


问:
Compose Dialog closing on keyboard appearance when LazyColumn is in background
I have a layout where each item in a LazyColumn can display an item-specific dialog. The Dialogs showed and worked fine except for some of the larger ones where whenever I would try to edit text in one of the dialog's TextFields it would trigger the dialog to disappear.

I tried a lot of different approaches and the weirdest thing was that the dialog works fine and allows me do edit the textfields if I only scroll the LazyColumn by even 1 item before attempting to show the dialog.

It has proven hard to reproduce the issue in a simple setting as changing even basic elements of my code makes the bug disappear but I finally managed. The appearance of the bug seems to depend on the LazyColumn being Scrollable and on the KeyBoard to be of type text. Next a somewhat long code sample and a GIF showing the issue:

```<code>@Composable
fun JointCourseTemplate(courseTemplateDto: CourseTemplateDto) {
    LazyColumn(
        //state= LazyListState()
    ){
        for(i in 0..4){
            item { TestPart(i = i) }
            for (j in 0..8){
                item { TestItem(i = j) }
            }
        }

    }
}

@Composable
fun TestPart(i:Int) {
    var showDialog by remember {
        mutableStateOf(false)
    }
    Row(Modifier.padding(8.dp)) {
        Text("part"+i)
        Button(onClick = { showDialog=true }) {
            Text("show dialog")
        }
    }

    PartDialog(showDialog = showDialog, hideDialog = {showDialog=false})
}

@Composable
fun TestItem(i:Int) {
    Row(Modifier.padding(8.dp)) {
        Text("item"+i)
        Button(onClick = { /*TODO*/ }) {
            Text("show dialog")
        }
    }
}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun PartDialog(showDialog:Boolean, hideDialog: () -> Unit) {
    var text by remember {
        mutableStateOf("")
    }
    if (showDialog) {
        Dialog(properties = DialogProperties(
            dismissOnClickOutside = false,
            usePlatformDefaultWidth = false
        ),
            onDismissRequest = { hideDialog() }) {
            Surface(
                modifier = Modifier
                    //.wrapContentHeight()
                    //.fillMaxWidth(0.9f)
                    .width(400.dp)
                    .height(600.dp),
                shape = RoundedCornerShape(10.dp)
            ) {
                Column {
                    Text(text = "Some Dialog")
                    OutlinedTextField(value = text, onValueChange = {text=it}, label = { Text(text = "TroubleMaker")})
                }
            }
        }
    }
}
</code>```

答:
I am convinced this is a bug that needs fixing by google however the simple solution is to add the state argument to the LazyColumn as shown.

```<code>val listState by remember{mutableStateOf(LazyListState())}
LazyColumn(state = listState  ){...}
</code>```

I realize this is quite a niche bug but maybe it helps someone else save time

EDIT

This was clearly wrong and dindt always work. not sure why it worked the first time around

Body:
I have a layout where each item in a LazyColumn can display an item-specific dialog. The Dialogs showed and worked fine except for some of the larger ones where whenever I would try to edit text in one of the dialog's TextFields it would trigger the dialog to disappear.

I tried a lot of different approaches and the weirdest thing was that the dialog works fine and allows me do edit the textfields if I only scroll the LazyColumn by even 1 item before attempting to show the dialog.

It has proven hard to reproduce the issue in a simple setting as changing even basic elements of my code makes the bug disappear but I finally managed. The appearance of the bug seems to depend on the LazyColumn being Scrollable and on the KeyBoard to be of type text. Next a somewhat long code sample and a GIF showing the issue:

@Composable
fun JointCourseTemplate(courseTemplateDto: CourseTemplateDto) {
    LazyColumn(
        //state= LazyListState()
    ){
        for(i in 0..4){
            item { TestPart(i = i) }
            for (j in 0..8){
                item { TestItem(i = j) }
            }
        }

    }
}

@Composable
fun TestPart(i:Int) {
    var showDialog by remember {
        mutableStateOf(false)
    }
    Row(Modifier.padding(8.dp)) {
        Text("part"+i)
        Button(onClick = { showDialog=true }) {
            Text("show dialog")
        }
    }

    PartDialog(showDialog = showDialog, hideDialog = {showDialog=false})
}

@Composable
fun TestItem(i:Int) {
    Row(Modifier.padding(8.dp)) {
        Text("item"+i)
        Button(onClick = { /*TODO*/ }) {
            Text("show dialog")
        }
    }
}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun PartDialog(showDialog:Boolean, hideDialog: () -> Unit) {
    var text by remember {
        mutableStateOf("")
    }
    if (showDialog) {
        Dialog(properties = DialogProperties(
            dismissOnClickOutside = false,
            usePlatformDefaultWidth = false
        ),
            onDismissRequest = { hideDialog() }) {
            Surface(
                modifier = Modifier
                    //.wrapContentHeight()
                    //.fillMaxWidth(0.9f)
                    .width(400.dp)
                    .height(600.dp),
                shape = RoundedCornerShape(10.dp)
            ) {
                Column {
                    Text(text = "Some Dialog")
                    OutlinedTextField(value = text, onValueChange = {text=it}, label = { Text(text = "TroubleMaker")})
                }
            }
        }
    }
}

Body:
I am convinced this is a bug that needs fixing by google however the simple solution is to add the state argument to the LazyColumn as shown.

val listState by remember{mutableStateOf(LazyListState())}
LazyColumn(state = listState  ){...}

I realize this is quite a niche bug but maybe it helps someone else save time

EDIT

This was clearly wrong and dindt always work. not sure why it worked the first time around


问:
System_Daemon::setSigHandler
I am using system daemon inside a class,

I am wondering if the following code for setting a handler is ok or not

```<code>System_Daemon::setSigHandler(SIGTERM, array($this, myShutdownHandler) );
</code>```

in the documentation they don't mention how to pass an object method as a "handler"

here: array($this, shutdownHandler)

the qiven example in the docs:

```<code>System_Daemon::setSigHandler(SIGTERM, "ownShutdownHandler" );

function ownShutdownHandler($sig)
{
 //etc
}
</code>```

答: The "handler" is known as a "callback" in the PHP world. Have a look at the documentation.</p>

Title: System_Daemon::setSigHandler

Body:
I am using system daemon inside a class,

I am wondering if the following code for setting a handler is ok or not

System_Daemon::setSigHandler(SIGTERM, array($this, myShutdownHandler) );

in the documentation they don't mention how to pass an object method as a "handler"

here: array($this, shutdownHandler)

the qiven example in the docs:

System_Daemon::setSigHandler(SIGTERM, "ownShutdownHandler" );

function ownShutdownHandler($sig)
{
 //etc
}


问:
Azure role-based access control user cannot find resource
Assigned Azure Custom Vision role to user but unable to access resource.
Errors shown:

Subdomain does not map to a resource.

Please check if desired resource exists in subscription.

image

答:
As per this official documentation,

Azure Cognitive Services use custom subdomain names for each resource
created through the Azure portal, Azure Cloud Shell, or Azure CLI.
Unlike regional endpoints, which were common for all customers in a
specific Azure region, custom subdomain names are unique to the
resource. Custom subdomain names are required to enable features like
Azure Active Directory (Azure AD) for authentication.

So, I suggest you to first create a Custom subdomain name for the resource and then use RBAC user to access it.

Also, make sure the user has either Owner or atleast Contributor permission for that resource.

Follow below instructions to migrate an existing resource to leverage custom subdomain names:

Sign in to the Azure portal and locate the Cognitive Services resource that you'd like to add a custom subdomain name to.

In the Overview blade, locate and select Generate Custom Domain Name.

This opens a panel with instructions to create a unique custom subdomain for your resource.


问:
Airflow killing tasks that take too long with SIGKILL
I have a SQL Server database, in which I'm migrating to AWS S3 in the parquet format to build a data lake. I'm using Apache Airflow to automate this task using DAGS. Each table on schema, in this case, becomes a .parquet file, this serves for the S3 to become a Data Lake and thus be able to use AWS Athena a posteriori and/or to be further indexed in ElasticSearch.

There are some very large tables and the migration task for these tables obviously I hope it to take more time. For python, the only library that I found that connects with Microsoft SQL Server is pyodbc, which is officially developed and maintained by Microsoft.

For such large tables (order of 60 million registers) using cursor.fetchall() was taking too long and resulting in error because the task seems to being killed by Airlfow by a SIGNALKILL.

Bellow is an example of how big is the DAG (only part of it):

For fetching all tables in a given schema I'm using the following SQL Server query:

```<code>SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='{}';
</code>```

on the brackets, I use the .format() function in Python to insert the schema name and retrieve the tables for dynamically build the DAG structure. I have changed my python code to fetch the data in such large tables in batches, in order to minimize any potential data overflow:

```<code>def stream(cursor, batch_size=50000):
    while True:
        row = cursor.fetchmany(batch_size)
        if row is None or not row:
            break
        yield row

def fetch_data(query, schema, filename, remote_path, save_locally=False):
    cnxn = pyodbc.connect(driver='Here I Put the ODBC Driver Name',
                          host='Host for de SQL Server DB',
                          database='Nameof the DB Schema',
                          user='User for Auth in the DB',
                          password='Pass for Auth in the DB')
    print('Connetciton stabilished with {} ..'.format(schema))

    cursor = cnxn.cursor()
    print('Initializing cursor ...')
    print('Requestin query {} ..'.format(query))

    cursor.execute(query)
    print('Query fetched for {} ..'.format(schema))

    row_batch = stream(cursor)
    print('Getting Iterator ...')

    cols = cursor.description
    cols = [col[0] for col in cols]

    print('Creating batch data_frame ..')
    data_frame = pd.DataFrame(columns=cols)

    start_time = time.time()
    for rows in row_batch:
        batch_df = pd.DataFrame.from_records(rows, columns=cols)
        data_frame = data_frame.append(batch_df, ignore_index=True)
        batch_df = None
        print("-- Batch inserted in %s seconds --" % (time.time() - start_time))
        start_time = time.time()

    cnxn.close()
    print('Connetciton closed ..')

    // other code to convert to .parquet and send to S3
    save_to_bucket(data_frame, remote_path)
    return 'FETCHING DATA'
</code>```

That strategy seems to work quite all for 96% of the entire tables of the schema, the thing is, as I said before, when the table is very large, around 60 million records, the task runs for a while, about 30 minutes, but normally after that, Airflow kills the task, just like that. No connections error, neither the python exception or nothing. The only thing that show in terminal of the scheduler is:

```<code>[2021-04-17 23:03:59,719] {scheduler_job.py:1199} INFO - Executor reports execution of ORTOCLIN_TO_S3.FETCHING_HISTORICORESUMO_DATA execution_date=2021-04-17 20:00:17.426578+00:00 exited with status success for try_number 1
[2021-04-17 23:05:02,050] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:10:02,314] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:15:02,666] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:20:03,226] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:25:03,868] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:30:04,346] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:35:04,853] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:40:05,324] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
</code>```

And on the Airflow logs for the task we have simply:

Is there any workaround for that? Please help me!

答:
There are 3 things you can change here:

AIRFLOW__CELERY__WORKER_CONCURRENCY

Set this to a low value or at minimum to 1 to make the worker only concentrate on one task

AIRFLOW__CORE__KILLED_TASK_CLEANUP_TIME

Set this to a higher value, like 1200-3600 seconds

Increase the CPU and RAM of the worker machine

In the end this is a resource problem. The DAG is consuming too many resources and gets killed, so this is a logical step to take.

This list is not complete, there might be other solutions as well, that I am not aware of yet.

Body:
I have a SQL Server database, in which I'm migrating to AWS S3 in the parquet format to build a data lake. I'm using Apache Airflow to automate this task using DAGS. Each table on schema, in this case, becomes a .parquet file, this serves for the S3 to become a Data Lake and thus be able to use AWS Athena a posteriori and/or to be further indexed in ElasticSearch.

There are some very large tables and the migration task for these tables obviously I hope it to take more time. For python, the only library that I found that connects with Microsoft SQL Server is pyodbc, which is officially developed and maintained by Microsoft.

For such large tables (order of 60 million registers) using cursor.fetchall() was taking too long and resulting in error because the task seems to being killed by Airlfow by a SIGNALKILL.

Bellow is an example of how big is the DAG (only part of it):

For fetching all tables in a given schema I'm using the following SQL Server query:

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='{}';

on the brackets, I use the .format() function in Python to insert the schema name and retrieve the tables for dynamically build the DAG structure. I have changed my python code to fetch the data in such large tables in batches, in order to minimize any potential data overflow:

def stream(cursor, batch_size=50000):
    while True:
        row = cursor.fetchmany(batch_size)
        if row is None or not row:
            break
        yield row

def fetch_data(query, schema, filename, remote_path, save_locally=False):
    cnxn = pyodbc.connect(driver='Here I Put the ODBC Driver Name',
                          host='Host for de SQL Server DB',
                          database='Nameof the DB Schema',
                          user='User for Auth in the DB',
                          password='Pass for Auth in the DB')
    print('Connetciton stabilished with {} ..'.format(schema))

    cursor = cnxn.cursor()
    print('Initializing cursor ...')
    print('Requestin query {} ..'.format(query))

    cursor.execute(query)
    print('Query fetched for {} ..'.format(schema))

    row_batch = stream(cursor)
    print('Getting Iterator ...')

    cols = cursor.description
    cols = [col[0] for col in cols]

    print('Creating batch data_frame ..')
    data_frame = pd.DataFrame(columns=cols)

    start_time = time.time()
    for rows in row_batch:
        batch_df = pd.DataFrame.from_records(rows, columns=cols)
        data_frame = data_frame.append(batch_df, ignore_index=True)
        batch_df = None
        print("-- Batch inserted in %s seconds --" % (time.time() - start_time))
        start_time = time.time()

    cnxn.close()
    print('Connetciton closed ..')

    // other code to convert to .parquet and send to S3
    save_to_bucket(data_frame, remote_path)
    return 'FETCHING DATA'

That strategy seems to work quite all for 96% of the entire tables of the schema, the thing is, as I said before, when the table is very large, around 60 million records, the task runs for a while, about 30 minutes, but normally after that, Airflow kills the task, just like that. No connections error, neither the python exception or nothing. The only thing that show in terminal of the scheduler is:

[2021-04-17 23:03:59,719] {scheduler_job.py:1199} INFO - Executor reports execution of ORTOCLIN_TO_S3.FETCHING_HISTORICORESUMO_DATA execution_date=2021-04-17 20:00:17.426578+00:00 exited with status success for try_number 1
[2021-04-17 23:05:02,050] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:10:02,314] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:15:02,666] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:20:03,226] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:25:03,868] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:30:04,346] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:35:04,853] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs
[2021-04-17 23:40:05,324] {scheduler_job.py:1834} INFO - Resetting orphaned tasks for active dag runs

And on the Airflow logs for the task we have simply:

Is there any workaround for that? Please help me!


问:
Mixing C# and VB.NET projects = broken "Go to definition"
I have a large-ish solution, with C# and VB.NET projects mixed. Whenever I try to “Go to definition” on a class, property or method that’s defined in the other language, Visual Studio just takes me to the Object Browser, which is pretty annoying. Same for debugging: I can’t step into a project that's written in the other language.

Is there a way to fix this?

答: I have this problem too. As workaround I use Navigate to (CTRL + comma) instead of Goto Definition.


问:
Can you use a while loop on a dictionary in python?
If a value for one of the keys in my dictionary does satisfies a condition, I want to break out of the loop and set a property to True.

what I'm doing so far is:

```<code>fooBar = False
for key, value in my_dict.items():
    if (condition):
        fooBar = True
</code>```

Do I need to use a for loop and iterate through all items in the dictionary, or can I use a while loop?

答:
```<code>my_dict = {"a": 12, "b", 43, "c": 5"}
comp = my_dict.items() # [("a", 12), ("b", 43), ("c", 5)]
i = 0
while True:
    # some code
    current = comp[i]
    i += 1
</code>```

you can try using items() method on your dictionary

Body:
If a value for one of the keys in my dictionary does satisfies a condition, I want to break out of the loop and set a property to True.

what I'm doing so far is:

fooBar = False
for key, value in my_dict.items():
    if (condition):
        fooBar = True

Do I need to use a for loop and iterate through all items in the dictionary, or can I use a while loop?

Body:
my_dict = {"a": 12, "b", 43, "c": 5"}
comp = my_dict.items() # [("a", 12), ("b", 43), ("c", 5)]
i = 0
while True:
    # some code
    current = comp[i]
    i += 1

you can try using items() method on your dictionary


问:
Unable to set the formulaarray property of the range class 1004
I am trying to get sum of values from 1 column which is closest to the value that is in G2 cell, so i found this formula which works in excel (ctrl + Shift + Enter) but when I am trying to work this with vba, it throws error 1004. Please find below the formula that I am using. "G2" is where actual value is and C3:C10 is the range where it sums up each cells and find the closest value.</p>
```<code>wbapp.Sheets(1).Range("V2:AC2").FormulaArray = "=INDEX(MOD(INT((ROW($C$3:INDEX($C:$C, 2^ROWS($C$3:$C$10)))-1)/2^(TRANSPOSE(MATCH(ROW($C$3:$C$10), ROW($C$3:$C$10)))-1)), 2)*TRANSPOSE($C$3:$C$10), MATCH(MIN(ABS(MMULT(MOD(INT((ROW($C$3:INDEX($C:$C, 2^ROWS($C$3:$C$10)))-1)/2^(TRANSPOSE(MATCH(ROW($C$3:$C$10), ROW($C$3:$C$10)))-1)), 2), $C$3:$C$10)-$G$2)), ABS(MMULT(MOD(INT((ROW($C$3:INDEX($C:$C, 2^ROWS($C$3:$C$10)))-1)/2^(TRANSPOSE(MATCH(ROW($C$3:$C$10), ROW($C$3:$C$10)))-1)), 2), $C$3:$C$10)-$G$2), 0), 0)"
</code>```

答:
Because of the character limit, you could put your formula (or parts of it) in a defined name</p>
```<code>Sub ThroughNames()
Dim MyLongFormula As String
'Set wbapp = ThisWorkbook
 MyLongFormula = "=INDEX(MOD(INT((ROW($C$3:INDEX($C:$C, 2^ROWS($C$3:$C$10)))-1)/2^(TRANSPOSE(MATCH(ROW($C$3:$C$10), ROW($C$3:$C$10)))-1)), 2)*TRANSPOSE($C$3:$C$10), MATCH(MIN(ABS(MMULT(MOD(INT((ROW($C$3:INDEX($C:$C, 2^ROWS($C$3:$C$10)))-1)/2^(TRANSPOSE(MATCH(ROW($C$3:$C$10), ROW($C$3:$C$10)))-1)), 2), $C$3:$C$10)-$G$2)), ABS(MMULT(MOD(INT((ROW($C$3:INDEX($C:$C, 2^ROWS($C$3:$C$10)))-1)/2^(TRANSPOSE(MATCH(ROW($C$3:$C$10), ROW($C$3:$C$10)))-1)), 2), $C$3:$C$10)-$G$2), 0), 0)"

    wbapp.Names.Add Name:="test", RefersTo:=MyLongFormula
   wbapp.Sheets(1).Range("V2:AC2").FormulaArray = "=test"
End Sub
</code>```

Body:
I am trying to get sum of values from 1 column which is closest to the value that is in G2 cell, so i found this formula which works in excel (ctrl + Shift + Enter) but when I am trying to work this with vba, it throws error 1004. Please find below the formula that I am using. "G2" is where actual value is and C3:C10 is the range where it sums up each cells and find the closest value.

wbapp.Sheets(1).Range("V2:AC2").FormulaArray = "=INDEX(MOD(INT((ROW($C$3:INDEX($C:$C, 2^ROWS($C$3:$C$10)))-1)/2^(TRANSPOSE(MATCH(ROW($C$3:$C$10), ROW($C$3:$C$10)))-1)), 2)*TRANSPOSE($C$3:$C$10), MATCH(MIN(ABS(MMULT(MOD(INT((ROW($C$3:INDEX($C:$C, 2^ROWS($C$3:$C$10)))-1)/2^(TRANSPOSE(MATCH(ROW($C$3:$C$10), ROW($C$3:$C$10)))-1)), 2), $C$3:$C$10)-$G$2)), ABS(MMULT(MOD(INT((ROW($C$3:INDEX($C:$C, 2^ROWS($C$3:$C$10)))-1)/2^(TRANSPOSE(MATCH(ROW($C$3:$C$10), ROW($C$3:$C$10)))-1)), 2), $C$3:$C$10)-$G$2), 0), 0)"

Body:
Because of the character limit, you could put your formula (or parts of it) in a defined name

Sub ThroughNames()
Dim MyLongFormula As String
'Set wbapp = ThisWorkbook
 MyLongFormula = "=INDEX(MOD(INT((ROW($C$3:INDEX($C:$C, 2^ROWS($C$3:$C$10)))-1)/2^(TRANSPOSE(MATCH(ROW($C$3:$C$10), ROW($C$3:$C$10)))-1)), 2)*TRANSPOSE($C$3:$C$10), MATCH(MIN(ABS(MMULT(MOD(INT((ROW($C$3:INDEX($C:$C, 2^ROWS($C$3:$C$10)))-1)/2^(TRANSPOSE(MATCH(ROW($C$3:$C$10), ROW($C$3:$C$10)))-1)), 2), $C$3:$C$10)-$G$2)), ABS(MMULT(MOD(INT((ROW($C$3:INDEX($C:$C, 2^ROWS($C$3:$C$10)))-1)/2^(TRANSPOSE(MATCH(ROW($C$3:$C$10), ROW($C$3:$C$10)))-1)), 2), $C$3:$C$10)-$G$2), 0), 0)"

    wbapp.Names.Add Name:="test", RefersTo:=MyLongFormula
   wbapp.Sheets(1).Range("V2:AC2").FormulaArray = "=test"
End Sub


问:
How to compare large text files?
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

```<code>mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT
</code>```

file_2looks like this:

```<code>mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT
</code>```

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

答:
I think, your way is rather reasonable.

I can imagine different strategies -- for example, you can sort both files before compare (where is efficient implementation of filesort, and unix sort utility can sort several Gbs files in minutes), and, while sorted, you can compare files sequentally, reading line by line.

But this is rather complex way to go -- you need to run external program (sort), or write comparable efficient implementation of filesort in java by yourself -- which is by itself not an easy task. So, for the sake of simplicity, I think you way of chunked read is very promising;

As for how to find reasonable block -- first of all, it may not be correct what "the more -- the better" -- I think, time of all work will grow asymptotically, to some constant line. So, may be you'll be close to that line faster then you think -- you need benchmark for this.

Next -- you may read lines to buffer like this:

```<code>final List<String> lines = new ArrayList<>();
try{
    final List<String> block = new ArrayList<>(BLOCK_SIZE);
    for(int i=0;i<BLOCK_SIZE;i++){
       final String line = ...;//read line from file
       block.add(line);
    }
    lines.addAll(block);
}catch(OutOfMemory ooe){
    //break
}
</code>```

So you read as many lines, as you can -- leaving last BLOCK_SIZE of free memory. BLOCK_SIZE should be big enouth to the rest of you program to run without OOM

Title: How to compare large text files?

Body:
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT

file_2looks like this:

mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

Body:
I think, your way is rather reasonable.

I can imagine different strategies -- for example, you can sort both files before compare (where is efficient implementation of filesort, and unix sort utility can sort several Gbs files in minutes), and, while sorted, you can compare files sequentally, reading line by line.

But this is rather complex way to go -- you need to run external program (sort), or write comparable efficient implementation of filesort in java by yourself -- which is by itself not an easy task. So, for the sake of simplicity, I think you way of chunked read is very promising;

As for how to find reasonable block -- first of all, it may not be correct what "the more -- the better" -- I think, time of all work will grow asymptotically, to some constant line. So, may be you'll be close to that line faster then you think -- you need benchmark for this.

Next -- you may read lines to buffer like this:

final List<String> lines = new ArrayList<>();
try{
    final List<String> block = new ArrayList<>(BLOCK_SIZE);
    for(int i=0;i<BLOCK_SIZE;i++){
       final String line = ...;//read line from file
       block.add(line);
    }
    lines.addAll(block);
}catch(OutOfMemory ooe){
    //break
}

So you read as many lines, as you can -- leaving last BLOCK_SIZE of free memory. BLOCK_SIZE should be big enouth to the rest of you program to run without OOM


问:
Sympy: Is there a way to create the PDF of a Truncated Normal Distribution in Sympy?
I want to create a function that is the PDF of a truncated normal distribution.

With this kind of PDF I need to calculate others PDFs, that are obtainable with integration.

I want to know if is it possible to make this PDF in Sympy: https://en.wikipedia.org/wiki/Truncated_normal_distribution

Thanks!

答:
As you said in the comments, you can do that via sympy with:

```<code>pdf_gauss_trunc = smp.Piecewise((0, x<=a), (normal_adjusted, (x>a) & (x<b)), (0, x>=b))
</code>```

where a and b are the extremes.

Body:
As you said in the comments, you can do that via sympy with:

pdf_gauss_trunc = smp.Piecewise((0, x<=a), (normal_adjusted, (x>a) & (x<b)), (0, x>=b))

where a and b are the extremes.


问:
How do you redirect to a page using the POST verb?
When you call RedirectToAction within a controller, it automatically redirects using an HTTP GET.  How do I explicitly tell it to use an HTTP POST?

I have an action that accepts both GET and POST requests, and I want to be able to RedirectToAction using  POST and send it some values.

Like this:

```<code>this.RedirectToAction(
    "actionname",
    new RouteValueDictionary(new { someValue = 2, anotherValue = "text" })
);
</code>```

I want the someValue and anotherValue values to be sent using an HTTP POST instead of a GET. Does anyone know how to do this?

答:
I have just experienced the same problem.

The solution was to call the controller action like a function:

```<code>return await ResendConfirmationEmail(new ResendConfirmationEmailViewModel() { Email = input.Email });
</code>```

The controller action:

```<code>[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> ResendConfirmationEmail(ResendConfirmationEmailViewModel input)
{
    ...

    return View("ResendConfirmationEmailConfirmed");
}
</code>```

OwnerDisplayName: Chris Pietschmann

Body:
When you call RedirectToAction within a controller, it automatically redirects using an HTTP GET.  How do I explicitly tell it to use an HTTP POST?

I have an action that accepts both GET and POST requests, and I want to be able to RedirectToAction using  POST and send it some values.

Like this:

this.RedirectToAction(
    "actionname",
    new RouteValueDictionary(new { someValue = 2, anotherValue = "text" })
);

I want the someValue and anotherValue values to be sent using an HTTP POST instead of a GET. Does anyone know how to do this?

Body:
I have just experienced the same problem.

The solution was to call the controller action like a function:

return await ResendConfirmationEmail(new ResendConfirmationEmailViewModel() { Email = input.Email });

The controller action:

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> ResendConfirmationEmail(ResendConfirmationEmailViewModel input)
{
    ...

    return View("ResendConfirmationEmailConfirmed");
}


问:
Input Box with multiple values in the same field
I have a macro created which does the following:

Asks for a value to be entered in an Input Box

Then searches for this value in all Workbooks in a specific folder

Returns (copies) specific cells from the same row the value found in a new worksheet.

However, i would like to search all those different Workbooks based on multiple values. For example to search if text "AXL" or "JBO" exist in any of the Workbooks and returns the values as per my code.

Any help and even a different approach to what i'm trying to achive is more than welcome.
Thanks for your time!

```<code>Sub SearchFolders()
Dim fso As Object
Dim fld As Object
Dim strSearch As String
Dim strPath As String
Dim strFile As String
Dim wOut As Worksheet
Dim wbk As Workbook
Dim wks As Worksheet
Dim lRow As Long
Dim rFound As Range
Dim strFirstAddress As String

On Error GoTo ErrHandler
Application.ScreenUpdating = False

strPath = "C:\Users\cmkon\Desktop\CAMS"
strSearch = InputBox("Enter Criteria")

Set wOut = Worksheets.Add
lRow = 1
With wOut
    .Cells(lRow, 1) = "Workbook"
    .Cells(lRow, 2) = "Worksheet"
    .Cells(lRow, 3) = "Cell"
    .Cells(lRow, 4) = "Text in Cell"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fld = fso.GetFolder(strPath)

    strFile = Dir(strPath & "\*.xls*")
    Do While strFile <> ""
        Set wbk = Workbooks.Open _
          (Filename:=strPath & "\" & strFile, _
          UpdateLinks:=0, _
          ReadOnly:=True, _
          AddToMRU:=False)

        For Each wks In wbk.Worksheets
        Set rFound = wks.UsedRange.Find(strSearch)

            If Not rFound Is Nothing Then
                strFirstAddress = rFound.Address
            End If
            Do
                If rFound Is Nothing Then
                    Exit Do
                Else
                    lRow = lRow + 1
                    .Cells(lRow, 1) = wbk.Name
                    .Cells(lRow, 2) = wks.Name
                    .Cells(lRow, 3) = rFound.Address
                    .Cells(lRow, 4) = rFound.Value
                End If
                Set rFound = wks.Cells.FindNext(After:=rFound)
            Loop While strFirstAddress <> rFound.Address
        Next

        wbk.Close (False)
        strFile = Dir
    Loop
    .Columns("A:D").EntireColumn.AutoFit
End With

MsgBox "Done"

ExitHandler:
Set wOut = Nothing
Set wks = Nothing
Set wbk = Nothing
Set fld = Nothing
Set fso = Nothing
Application.ScreenUpdating = True
Exit Sub

ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler
End Sub
</code>```

答:
My final code!</p>
```<code>Sub SearchFolders()

Dim fso As Object
Dim fld As Object
Dim strSearch As String
Dim strPath As String
Dim strFile As String
Dim wOut As Worksheet
Dim wbk As Workbook
Dim wks As Worksheet
Dim lRow As Long
Dim rFound As Range
Dim strFirstAddress As String

On Error GoTo ErrHandler
Application.ScreenUpdating = False

strPath = "C:\Users\cmkon\Desktop\CAMS"
strSearch = InputBox("Enter Criteria")

Dim MyArray() As String, I As Variant
MyArray = Split(strSearch, ";")

For Each I In MyArray

Set wOut = Worksheets.Add
lRow = 1
With wOut
    .Cells(lRow, 1) = "Workbook"
    .Cells(lRow, 2) = "Worksheet"
    .Cells(lRow, 3) = "Cell"
    .Cells(lRow, 4) = "Text in Cell"
    .Cells(lRow, 5) = "Instructions"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fld = fso.GetFolder(strPath)

    strFile = Dir(strPath & "\*.xls*")
    Do While strFile <> ""
        Set wbk = Workbooks.Open _
          (Filename:=strPath & "\" & strFile, _
          UpdateLinks:=0, _
          ReadOnly:=True, _
          AddToMRU:=False)

        For Each wks In wbk.Worksheets
        Set rFound = wks.UsedRange.Find(I)

            If Not rFound Is Nothing Then
                strFirstAddress = rFound.Address
            End If
            Do
                If rFound Is Nothing Then
                    Exit Do
                Else
                    lRow = lRow + 1
                   .Cells(lRow, 1) = wbk.Name
                   .Cells(lRow, 2) = wks.Name
                   .Cells(lRow, 3) = rFound.Address
                   .Cells(lRow, 4) = rFound.Value

                End If
                Set rFound = wks.Cells.FindNext(After:=rFound)
            Loop While strFirstAddress <> rFound.Address
        Next

        wbk.Close (False)
        strFile = Dir
    Loop
    .Columns("A:E").EntireColumn.AutoFit
End With
Next I MsgBox "Done"

ExitHandler:
Set wOut = Nothing
Set wks = Nothing
Set wbk = Nothing
Set fld = Nothing
Set fso = Nothing
Application.ScreenUpdating = True
Exit Sub

ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler

End Sub
</code>```

Body:
I have a macro created which does the following:

Asks for a value to be entered in an Input Box

Then searches for this value in all Workbooks in a specific folder

Returns (copies) specific cells from the same row the value found in a new worksheet.

However, i would like to search all those different Workbooks based on multiple values. For example to search if text "AXL" or "JBO" exist in any of the Workbooks and returns the values as per my code.

Any help and even a different approach to what i'm trying to achive is more than welcome.
Thanks for your time!

Sub SearchFolders()
Dim fso As Object
Dim fld As Object
Dim strSearch As String
Dim strPath As String
Dim strFile As String
Dim wOut As Worksheet
Dim wbk As Workbook
Dim wks As Worksheet
Dim lRow As Long
Dim rFound As Range
Dim strFirstAddress As String

On Error GoTo ErrHandler
Application.ScreenUpdating = False

strPath = "C:\Users\cmkon\Desktop\CAMS"
strSearch = InputBox("Enter Criteria")

Set wOut = Worksheets.Add
lRow = 1
With wOut
    .Cells(lRow, 1) = "Workbook"
    .Cells(lRow, 2) = "Worksheet"
    .Cells(lRow, 3) = "Cell"
    .Cells(lRow, 4) = "Text in Cell"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fld = fso.GetFolder(strPath)

    strFile = Dir(strPath & "\*.xls*")
    Do While strFile <> ""
        Set wbk = Workbooks.Open _
          (Filename:=strPath & "\" & strFile, _
          UpdateLinks:=0, _
          ReadOnly:=True, _
          AddToMRU:=False)

        For Each wks In wbk.Worksheets
        Set rFound = wks.UsedRange.Find(strSearch)

            If Not rFound Is Nothing Then
                strFirstAddress = rFound.Address
            End If
            Do
                If rFound Is Nothing Then
                    Exit Do
                Else
                    lRow = lRow + 1
                    .Cells(lRow, 1) = wbk.Name
                    .Cells(lRow, 2) = wks.Name
                    .Cells(lRow, 3) = rFound.Address
                    .Cells(lRow, 4) = rFound.Value
                End If
                Set rFound = wks.Cells.FindNext(After:=rFound)
            Loop While strFirstAddress <> rFound.Address
        Next

        wbk.Close (False)
        strFile = Dir
    Loop
    .Columns("A:D").EntireColumn.AutoFit
End With

MsgBox "Done"

ExitHandler:
Set wOut = Nothing
Set wks = Nothing
Set wbk = Nothing
Set fld = Nothing
Set fso = Nothing
Application.ScreenUpdating = True
Exit Sub

ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler
End Sub

Body:
My final code!

Sub SearchFolders()

Dim fso As Object
Dim fld As Object
Dim strSearch As String
Dim strPath As String
Dim strFile As String
Dim wOut As Worksheet
Dim wbk As Workbook
Dim wks As Worksheet
Dim lRow As Long
Dim rFound As Range
Dim strFirstAddress As String

On Error GoTo ErrHandler
Application.ScreenUpdating = False

strPath = "C:\Users\cmkon\Desktop\CAMS"
strSearch = InputBox("Enter Criteria")

Dim MyArray() As String, I As Variant
MyArray = Split(strSearch, ";")

For Each I In MyArray

Set wOut = Worksheets.Add
lRow = 1
With wOut
    .Cells(lRow, 1) = "Workbook"
    .Cells(lRow, 2) = "Worksheet"
    .Cells(lRow, 3) = "Cell"
    .Cells(lRow, 4) = "Text in Cell"
    .Cells(lRow, 5) = "Instructions"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fld = fso.GetFolder(strPath)

    strFile = Dir(strPath & "\*.xls*")
    Do While strFile <> ""
        Set wbk = Workbooks.Open _
          (Filename:=strPath & "\" & strFile, _
          UpdateLinks:=0, _
          ReadOnly:=True, _
          AddToMRU:=False)

        For Each wks In wbk.Worksheets
        Set rFound = wks.UsedRange.Find(I)

            If Not rFound Is Nothing Then
                strFirstAddress = rFound.Address
            End If
            Do
                If rFound Is Nothing Then
                    Exit Do
                Else
                    lRow = lRow + 1
                   .Cells(lRow, 1) = wbk.Name
                   .Cells(lRow, 2) = wks.Name
                   .Cells(lRow, 3) = rFound.Address
                   .Cells(lRow, 4) = rFound.Value

                End If
                Set rFound = wks.Cells.FindNext(After:=rFound)
            Loop While strFirstAddress <> rFound.Address
        Next

        wbk.Close (False)
        strFile = Dir
    Loop
    .Columns("A:E").EntireColumn.AutoFit
End With
Next I MsgBox "Done"

ExitHandler:
Set wOut = Nothing
Set wks = Nothing
Set wbk = Nothing
Set fld = Nothing
Set fso = Nothing
Application.ScreenUpdating = True
Exit Sub

ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler

End Sub


问:
How to detect incomplet date from list and replace with flutter?
Hello I don't find how to detect an incomplet date from listString. I think about regex but don't know how to extract this sequence input.

```<code>input=[2022-01-20 20:01, 2022-01-20 21, 2022-01-20 22:25, 2022-01-20 23:01]
</code>```

Here I tried to match 2022-01-20 21 (it's the only who not have minute)
after match I want to add minute :00 to remove wrong date format

Here is what I search to have

```<code>output=[2022-01-20 20:01, 2022-01-20 21:00, 2022-01-20 22:25, 2022-01-20 23:01]
</code>```

here is what I tried

```<code> dateList=[2022-01-20 20:01, 2022-01-20 21, 2022-01-20 22:25, 2022-01-20 23:01];

for (var i = 1; i < dateList.length; i++) {

        RegExp regExp = new RegExp(
          r"^((?!:).)*$",
        );

        var match = regExp.firstMatch("${dateList}");

        var index = dateList1.indexOf(match);

        dateList.replaceRange(index, index + 1, ["$match:00"]);
      }
</code>```

for each index of my stringlist I seach the only who not have : after I found the index who have a problem, and I replace the index with the add :00

problem match return null...

Thank you

答:
I agree that using regular expressions is the way to go here. Detecting a date is relatively simple, you're basically looking for

```<code>4-digits dash 2-digits dash 2-digits space 2-digits colon 2-digits
</code>```

Which, in RegExp language is

```<code>\d{4}-\d{2}-\d{2} \d{2}:\d{2}
</code>```

Now we can detect whether a given String contains a complete datetime. The only thing that's left is to add the trailing minutes when it is missing. Note that you can decide what to add using another regular expression, but this code will just add the minutes, assuming that's always the issue.

List<String> input = ['2022-01-20 20:01', '2022-01-20 21', '2022-01-20 22:25', '2022-01-20 23:01'];
List<String> output = [];

// detect a date + time
RegExp regex = RegExp(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}');

for (String maybeDate in input) {
  bool isCompleteDate = regex.hasMatch(maybeDate);

  if (isCompleteDate) {
    output.add(maybeDate);
  } else {
    // we want to comlete the String
    // in this case, I assume it's always just the minutes missing, but you could use another regex to see which part is missing
    output.add(maybeDate + ':00');
  }
}

print(output);
```
<p>Alternatively, you can indeed use negative lookahead to find the missing minutes:</p>
<pre class="lang-dart prettyprint-override"><code>// detects a date and hour, without a colon and two digits (the minutes)
RegExp missingMinutes = RegExp(r'(\d{4}-\d{2}-\d{2} \d{2})(?!:\d{2})');
</code>```

Which, in case you have a String instead of a List<String> would result in

List<String> input = ['2022-01-20 20:01', '2022-01-20 21', '2022-01-20 22:25', '2022-01-20 23:01'];
String listAsString = input.toString();
RegExp missingMinutes = RegExp(r'(\d{4}-\d{2}-\d{2} \d{2})(?!:\d{2})');
List<RegExpMatch?> matches = missingMinutes.allMatches(listAsString).toList();

for (int i = matches.length - 1; i >= 0; i--) {
  // walk through all matches
  if (matches[i] == null) continue;
  listAsString = listAsString.substring(0, matches[i]!.end) + ':00' + listAsString.substring(matches[i]!.end);
}

print(listAsString);
```

Body:
Hello I don't find how to detect an incomplet date from listString. I think about regex but don't know how to extract this sequence input.

input=[2022-01-20 20:01, 2022-01-20 21, 2022-01-20 22:25, 2022-01-20 23:01]

Here I tried to match 2022-01-20 21 (it's the only who not have minute)
after match I want to add minute :00 to remove wrong date format

Here is what I search to have

output=[2022-01-20 20:01, 2022-01-20 21:00, 2022-01-20 22:25, 2022-01-20 23:01]

here is what I tried

 dateList=[2022-01-20 20:01, 2022-01-20 21, 2022-01-20 22:25, 2022-01-20 23:01];

for (var i = 1; i < dateList.length; i++) {

        RegExp regExp = new RegExp(
          r"^((?!:).)*$",
        );

        var match = regExp.firstMatch("${dateList}");

        var index = dateList1.indexOf(match);

        dateList.replaceRange(index, index + 1, ["$match:00"]);
      }

for each index of my stringlist I seach the only who not have : after I found the index who have a problem, and I replace the index with the add :00

problem match return null...

Thank you

Body:
I agree that using regular expressions is the way to go here. Detecting a date is relatively simple, you're basically looking for

4-digits dash 2-digits dash 2-digits space 2-digits colon 2-digits

Which, in RegExp language is

\d{4}-\d{2}-\d{2} \d{2}:\d{2}

Now we can detect whether a given String contains a complete datetime. The only thing that's left is to add the trailing minutes when it is missing. Note that you can decide what to add using another regular expression, but this code will just add the minutes, assuming that's always the issue.

List<String> input = ['2022-01-20 20:01', '2022-01-20 21', '2022-01-20 22:25', '2022-01-20 23:01'];
List<String> output = [];

// detect a date + time
RegExp regex = RegExp(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}');

for (String maybeDate in input) {
  bool isCompleteDate = regex.hasMatch(maybeDate);

  if (isCompleteDate) {
    output.add(maybeDate);
  } else {
    // we want to comlete the String
    // in this case, I assume it's always just the minutes missing, but you could use another regex to see which part is missing
    output.add(maybeDate + ':00');
  }
}

print(output);

Alternatively, you can indeed use negative lookahead to find the missing minutes:

// detects a date and hour, without a colon and two digits (the minutes)
RegExp missingMinutes = RegExp(r'(\d{4}-\d{2}-\d{2} \d{2})(?!:\d{2})');

Which, in case you have a String instead of a List<String> would result in

List<String> input = ['2022-01-20 20:01', '2022-01-20 21', '2022-01-20 22:25', '2022-01-20 23:01'];
String listAsString = input.toString();
RegExp missingMinutes = RegExp(r'(\d{4}-\d{2}-\d{2} \d{2})(?!:\d{2})');
List<RegExpMatch?> matches = missingMinutes.allMatches(listAsString).toList();

for (int i = matches.length - 1; i >= 0; i--) {
  // walk through all matches
  if (matches[i] == null) continue;
  listAsString = listAsString.substring(0, matches[i]!.end) + ':00' + listAsString.substring(matches[i]!.end);
}

print(listAsString);


问:
JSON output format for Hive Query results
Is there any way to convert the Hive query result in JSON format?</p>

答: 'SELECT to_json' will work, but all the columns should be listed</p>