问:
Parsing an array of string to MVC method
Im trying to parse a simple array of guids/strings to json
the json is used as a parameter on a post call to my controller.

I have been trying a lot of different things but i simply cant make the controller method see my List.

The array is built from checkbox values:

```<code>$('input:checkbox').click(function () {
        if ($(this).attr("checked") == true) {
            selected.push($(this).val());
        }
    });
</code>```

and looks alright.
then i try to convert it to JSON

```<code>$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }
        var json = {
            SelectedQuantities: arrayJson
        };

        $.ajax({
            url: "/MVC/Physical/SelectQuantities/@Model.TopID",
            type: "POST",
            data: JSON.stringify(json),
            dataType: "json",
            contentType: 'application/json',
            success: function (result) {
                debugger;
                if (result.status == 200)
                    location.replace = "/MVC/Physical/QuantitySummaryView/@Model.TopID"
                else {
                    //Handle error
                }

            }
        });
    });
});
</code>```

My controller method looks as following:

```<code>public ActionResult QuantitySummaryView(Guid id, List<String> SelectedQuantities)
</code>```

But the list is always null. I figured it was because the JSON list doesnt contain the array of GUIDs directly underneath it.

Can you help me get it nudged in place?

JSON (as seen by Chromes  dev tools) looks as following:

```<code>{
"SelectedQuantities": {
    "0": "707c40bd-4434-41ed-80fd-4ac541a81e85",
    "1": "a8d78a4b-b107-4e1c-97b5-5d8abf530ba8",
    "2": "a19226cc-9b22-4174-97e3-bb003d4b2746"
}
</code>```

}

答:
For example:

A model which contains a collection of GUIDs:

```<code>public class GuidModel
{
    public GuidModel()
    {
        Guids = new List<Guid>();

        Guids.Add(Guid.NewGuid());
        Guids.Add(Guid.NewGuid());
        Guids.Add(Guid.NewGuid());
        Guids.Add(Guid.NewGuid());
        Guids.Add(Guid.NewGuid());
    }

    public IList<Guid> Guids { get; set; }
}
</code>```

The checkboxes are rendered by the view:

```<code><% var index = 1; %>
    <% foreach(var guid in Model.Guids) { %>
        <input type="checkbox" value="<%= guid %>" name="guid<%= index %>" />
     <%: guid %>
     <br />
     <% index++; %>
<% } %>
<br />
<input type="button" value="Summarize" id="Summarize" />
</code>```

The JavaScript / jQuery:

```<code><script type="text/javascript">
    var selected = [];

    $('input:checkbox').click(function () {
        if ($(this).attr("checked") == true) {
            selected.push($(this).val());
        }
    });

    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }

        var json = {
            SelectedQuantities: arrayJson
        };
        json = JSON.stringify(json);

        $.post("/Home/QuantitySummaryView?data=" + json);
    });
</script>
</code>```

The action method in the controller:

```<code>[HttpPost]
public ActionResult QuantitySummaryView(string data)
{
    // Deserialize the string containing JSON serialized data
    JavaScriptSerializer jss = new JavaScriptSerializer();
    //...
}
</code>```

Body:
Im trying to parse a simple array of guids/strings to json
the json is used as a parameter on a post call to my controller.

I have been trying a lot of different things but i simply cant make the controller method see my List.

The array is built from checkbox values:

$('input:checkbox').click(function () {
        if ($(this).attr("checked") == true) {
            selected.push($(this).val());
        }
    });

and looks alright.
then i try to convert it to JSON

$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }
        var json = {
            SelectedQuantities: arrayJson
        };

        $.ajax({
            url: "/MVC/Physical/SelectQuantities/@Model.TopID",
            type: "POST",
            data: JSON.stringify(json),
            dataType: "json",
            contentType: 'application/json',
            success: function (result) {
                debugger;
                if (result.status == 200)
                    location.replace = "/MVC/Physical/QuantitySummaryView/@Model.TopID"
                else {
                    //Handle error
                }

            }
        });
    });
});

My controller method looks as following:

public ActionResult QuantitySummaryView(Guid id, List<String> SelectedQuantities)

But the list is always null. I figured it was because the JSON list doesnt contain the array of GUIDs directly underneath it.

Can you help me get it nudged in place?

JSON (as seen by Chromes  dev tools) looks as following:

{
"SelectedQuantities": {
    "0": "707c40bd-4434-41ed-80fd-4ac541a81e85",
    "1": "a8d78a4b-b107-4e1c-97b5-5d8abf530ba8",
    "2": "a19226cc-9b22-4174-97e3-bb003d4b2746"
}

}

Body:
For example:

A model which contains a collection of GUIDs:

public class GuidModel
{
    public GuidModel()
    {
        Guids = new List<Guid>();

        Guids.Add(Guid.NewGuid());
        Guids.Add(Guid.NewGuid());
        Guids.Add(Guid.NewGuid());
        Guids.Add(Guid.NewGuid());
        Guids.Add(Guid.NewGuid());
    }

    public IList<Guid> Guids { get; set; }
}

The checkboxes are rendered by the view:

<% var index = 1; %>
    <% foreach(var guid in Model.Guids) { %>
        <input type="checkbox" value="<%= guid %>" name="guid<%= index %>" />
     <%: guid %>
     <br />
     <% index++; %>
<% } %>
<br />
<input type="button" value="Summarize" id="Summarize" />

The JavaScript / jQuery:

<script type="text/javascript">
    var selected = [];

    $('input:checkbox').click(function () {
        if ($(this).attr("checked") == true) {
            selected.push($(this).val());
        }
    });

    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }

        var json = {
            SelectedQuantities: arrayJson
        };
        json = JSON.stringify(json);

        $.post("/Home/QuantitySummaryView?data=" + json);
    });
</script>

The action method in the controller:

[HttpPost]
public ActionResult QuantitySummaryView(string data)
{
    // Deserialize the string containing JSON serialized data
    JavaScriptSerializer jss = new JavaScriptSerializer();
    //...
}


来源: stackexchange

问:
How to mark an Azure AD B2C App as Publisher Verified
I have a working Xamarin Forms app that uses Azure AD B2C to login to providers such as Microsoft, Google, LinkedIn, Apple, etc. The login process works smoothly except that I get the message "Let this app access your info? unverified". See picture below:

I know how to resolve this issue for an Azure AD application. See Publisher verification and app consent policies are now generally available

The Azure documentation clearly states that this is not supported for Azure AD B2C Apps. Is there an alternate way to get past the "unverified" messsage? This is causing a massive adoption problem for my app as downloaders are hesitant to login to an app with an "unverified" publisher.

Any and all help will be appreciated.

答:
I finally succeeded in marking my Azure AD B2C application as publisher verified. Now I no longer get the "unverified" description in the access screen.  To do this, I followed the instructions here:

https://learn.microsoft.com/en-us/azure/active-directory-b2c/identity-provider-microsoft-account?pivots=b2c-user-flow#verify-the-applications-publisher-domain

It is especially important to know that the MPN id cannot be set by a user interface but you have to use Graph Explorer to set it.

The code below is an example of using Graph Explorer to set the MPN Id:
Where appObjectId is the object id of your AD B2C App. It is NOT the app id but the object id.  The VerifiedPublisherID is your MPN Id that you wish to set.

```<code>POST /applications/appObjectId/setVerifiedPublisher

{

    "verifiedPublisherId": "12345678"

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I finally succeeded in marking my Azure AD B2C application as publisher verified. Now I no longer get the "unverified" description in the access screen.  To do this, I followed the instructions here:

https://learn.microsoft.com/en-us/azure/active-directory-b2c/identity-provider-microsoft-account?pivots=b2c-user-flow#verify-the-applications-publisher-domain

It is especially important to know that the MPN id cannot be set by a user interface but you have to use Graph Explorer to set it.

The code below is an example of using Graph Explorer to set the MPN Id:
Where appObjectId is the object id of your AD B2C App. It is NOT the app id but the object id.  The VerifiedPublisherID is your MPN Id that you wish to set.

POST /applications/appObjectId/setVerifiedPublisher

{

    "verifiedPublisherId": "12345678"

}


问:
Importing jar file to ruby script
This is my ruby script:

require 'java'

require_relative 'hmac_utility.jar'

dec_obj = Java::Hmac_utility::Hmac_utility.new

plaintext = dec_obj.decrypt_ruby(event.get('encypted_secret_pass'), event.get('gcm_key'))

This script sits in a maven project where I've imported hmac_utility jar file.

And this is my java class from the jar file(this is my first time making a jar file not sure how the main method would work if I need to use another function from the class)

public class hmac_decryptor {

```<code>private static final Charset UTF_8 = StandardCharsets.UTF_8;
private static final int TAG_LENGTH_BIT = 128;
private static final int IV_LENGTH_BYTE = 12;
private static final int SALT_LENGTH_BYTE = 16;
private static final String CIPHER_INSTANCE = "AES/GCM/NoPadding";
private static final String HASH_ALGO = "PBKDF2WithHmacSHA256";

public static void main(String[] args) {
}

public static String decrypt_ruby(String cText, String syslogKey) {
    try {
        byte[] decode = Base64.getDecoder().decode(cText.getBytes(UTF_8));
        ByteBuffer bb = ByteBuffer.wrap(decode);
        byte[] iv = new byte[IV_LENGTH_BYTE];
        bb.get(iv);
        byte[] salt = new byte[SALT_LENGTH_BYTE];
        bb.get(salt);
        byte[] cipherText = new byte[bb.remaining()];
        bb.get(cipherText);
        SecretKey aesKeyFromPassword = getAESKeyFromPassword(syslogKey.toCharArray(), salt);
        Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
        cipher.init(Cipher.DECRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
        byte[] plainText = cipher.doFinal(cipherText);

        return new String(plainText, UTF_8);
    }
    catch(Exception e) {
        return null;
    }
}

public static SecretKey getAESKeyFromPassword(char[] password, byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGO);
    KeySpec spec = new PBEKeySpec(password, salt, 2048, 256);
    SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
    return secret;
}
</code>```

}

Now my question is have I set up the class properly to use as a jar file and in the ruby script have I done it the right way to use the decrypt_ruby method?

答:
If you want to reference Java code from Ruby, your best bet is JRuby. Note that JRuby is basically an alternative to MRI (the C implementation of Ruby), so you will likely need to execute your script differently.

https://www.jruby.org/

Title: Importing jar file to ruby script

Body:
This is my ruby script:

require 'java'

require_relative 'hmac_utility.jar'

dec_obj = Java::Hmac_utility::Hmac_utility.new

plaintext = dec_obj.decrypt_ruby(event.get('encypted_secret_pass'), event.get('gcm_key'))

This script sits in a maven project where I've imported hmac_utility jar file.

And this is my java class from the jar file(this is my first time making a jar file not sure how the main method would work if I need to use another function from the class)

public class hmac_decryptor {

private static final Charset UTF_8 = StandardCharsets.UTF_8;
private static final int TAG_LENGTH_BIT = 128;
private static final int IV_LENGTH_BYTE = 12;
private static final int SALT_LENGTH_BYTE = 16;
private static final String CIPHER_INSTANCE = "AES/GCM/NoPadding";
private static final String HASH_ALGO = "PBKDF2WithHmacSHA256";

public static void main(String[] args) {
}

public static String decrypt_ruby(String cText, String syslogKey) {
    try {
        byte[] decode = Base64.getDecoder().decode(cText.getBytes(UTF_8));
        ByteBuffer bb = ByteBuffer.wrap(decode);
        byte[] iv = new byte[IV_LENGTH_BYTE];
        bb.get(iv);
        byte[] salt = new byte[SALT_LENGTH_BYTE];
        bb.get(salt);
        byte[] cipherText = new byte[bb.remaining()];
        bb.get(cipherText);
        SecretKey aesKeyFromPassword = getAESKeyFromPassword(syslogKey.toCharArray(), salt);
        Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
        cipher.init(Cipher.DECRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
        byte[] plainText = cipher.doFinal(cipherText);

        return new String(plainText, UTF_8);
    }
    catch(Exception e) {
        return null;
    }
}

public static SecretKey getAESKeyFromPassword(char[] password, byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGO);
    KeySpec spec = new PBEKeySpec(password, salt, 2048, 256);
    SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
    return secret;
}

}

Now my question is have I set up the class properly to use as a jar file and in the ruby script have I done it the right way to use the decrypt_ruby method?


问:
Navigate to another screen - 'navigation.navigate' is not a function
I am trying to navigate from Screen1 to Screen2. Screen1 is being rendered in my Home screen. So far I have tried using this.props.navigation.navigate as well as what you see currently implemented.

I have created a snack expo here that recreates the exact error as well as posted some code below.

Thank you for any insight at all, I appreciate it more than you know.

EDIT:: this needs to be ran on IOS and I am using react-native-navigation

App.js

```<code> /*passing props to home is from my overall project, I left it in incase it impacted the answer*/
<Stack.Navigator initialRouteName="Home">
      <Stack.Screen name="HomeScreen" options={{ headerShown: false }}>
        {(props) => (
          <Home {...props}/>
        )}
      </Stack.Screen>
       <Stack.Screen
        name="Screen1"
        component={Screen1}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Screen2"
        component={Screen2}
        options={{ headerShown: false }}
      />
  </Stack.Navigator>
);
}

export default function App() {

  return (
<NavigationContainer>
  <MyTabs/>
</NavigationContainer>
);
</code>```

Screen1

```<code>export default class Screen1 extends React.Component {
  renderList = (props, navigation) => {
    return List.map((item, i) => {
      return (
        <View
        key={List.name}
          style={{
            width: windowWidth,
            height: scale(100),
            paddingLeft: scale(10)
          }}>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate('Screen2')}
            activeOpacity={0.7}>
                <Text style={{fontSize: 20}}>{item.name}</Text>
          </TouchableOpacity>
        </View>
      );
    });
  };

  render() {
  return (
      <View style={{top: scale(50)}}>

          <ScrollView style={{ height: windowHeight }}>
            <this.renderList />
          </ScrollView>

      </View>
    );
  }
}

</code>```

答:
make use of hook useNavigation.

Home.js

```<code>const Home = (props) => {
  const navigation = useNavigation();
  return (
    <View>
      <Screen1 navigation={navigation} />
    </View>
  );
};
</code>```

Screen1.js

```<code>export default class Screen2 extends React.Component {

  renderList = (props) => {
    return List.map((item, i) => {
      return (
        <View
          key={List.name}
          style={{
            width: windowWidth,
            height: scale(100),
            paddingLeft: scale(10),
          }}>
          <TouchableOpacity onPress={() => {
            props.navigation.navigate('Screen2')
          }} activeOpacity={0.7}>
            <Text style={{ fontSize: 20 }}>{item.name}</Text>
          </TouchableOpacity>
        </View>
      );
    });
  };

render() {
  const props= this.props;
  return (
    <View style={{ top: scale(50) }}>
      <ScrollView style={{ height: windowHeight }}>
         { this.renderList (props) }
      </ScrollView>
    </View>
  );
}
}
</code>```

snack expo working code

Body:
I am trying to navigate from Screen1 to Screen2. Screen1 is being rendered in my Home screen. So far I have tried using this.props.navigation.navigate as well as what you see currently implemented.

I have created a snack expo here that recreates the exact error as well as posted some code below.

Thank you for any insight at all, I appreciate it more than you know.

EDIT:: this needs to be ran on IOS and I am using react-native-navigation

App.js

 /*passing props to home is from my overall project, I left it in incase it impacted the answer*/
<Stack.Navigator initialRouteName="Home">
      <Stack.Screen name="HomeScreen" options={{ headerShown: false }}>
        {(props) => (
          <Home {...props}/>
        )}
      </Stack.Screen>
       <Stack.Screen
        name="Screen1"
        component={Screen1}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Screen2"
        component={Screen2}
        options={{ headerShown: false }}
      />
  </Stack.Navigator>
);
}

export default function App() {

  return (
<NavigationContainer>
  <MyTabs/>
</NavigationContainer>
);

Screen1

export default class Screen1 extends React.Component {
  renderList = (props, navigation) => {
    return List.map((item, i) => {
      return (
        <View
        key={List.name}
          style={{
            width: windowWidth,
            height: scale(100),
            paddingLeft: scale(10)
          }}>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate('Screen2')}
            activeOpacity={0.7}>
                <Text style={{fontSize: 20}}>{item.name}</Text>
          </TouchableOpacity>
        </View>
      );
    });
  };

  render() {
  return (
      <View style={{top: scale(50)}}>

          <ScrollView style={{ height: windowHeight }}>
            <this.renderList />
          </ScrollView>

      </View>
    );
  }
}

Body:
make use of hook useNavigation.

Home.js

const Home = (props) => {
  const navigation = useNavigation();
  return (
    <View>
      <Screen1 navigation={navigation} />
    </View>
  );
};

Screen1.js

export default class Screen2 extends React.Component {

  renderList = (props) => {
    return List.map((item, i) => {
      return (
        <View
          key={List.name}
          style={{
            width: windowWidth,
            height: scale(100),
            paddingLeft: scale(10),
          }}>
          <TouchableOpacity onPress={() => {
            props.navigation.navigate('Screen2')
          }} activeOpacity={0.7}>
            <Text style={{ fontSize: 20 }}>{item.name}</Text>
          </TouchableOpacity>
        </View>
      );
    });
  };

render() {
  const props= this.props;
  return (
    <View style={{ top: scale(50) }}>
      <ScrollView style={{ height: windowHeight }}>
         { this.renderList (props) }
      </ScrollView>
    </View>
  );
}
}

snack expo working code


问:
Plaid API. We didn't find any checking or savings accounts at this institution
I have a credit card from Citi bank but I have no checking or savings accounts in Citi bank.

I'm facing this error message when I try to get access to my credit card.

```<code>We didn't find any checking or savings accounts at this institution. Please try linking another institution
</code>```

Is it possible to read balances and transactions from credit cards using Plaid API?

Should I use Liabilities API for that?

答:
The Plaid transactions API seems to not work for accounts like @Alex's, where he has a Credit Card, but no savings or checking account. Entering login information to link the Citi account results in a message that says "We didn't find any checking or savings accounts at this institution. Please try linking another institution."

Again this is using the Transactions API. Image of response show below:

Body:
I have a credit card from Citi bank but I have no checking or savings accounts in Citi bank.

I'm facing this error message when I try to get access to my credit card.

We didn't find any checking or savings accounts at this institution. Please try linking another institution

Is it possible to read balances and transactions from credit cards using Plaid API?

Should I use Liabilities API for that?


问:
How to get the index value whilst not getting duplicates within ListView.builder?
I'm trying to show the week's budget spending & timeline only when the user has put in the spending information.

This is the expected result and all seems to be working nicely until I add in more than just one spending in each week.

Here's what happens:

The problem that I understand is that the ListView.builder gets the date that is between "Initial" and "End" and builds the widgets. So because there's 2 spending between those dates, then it builds 2 of those widgets. The problem is I just can't seem to figure out a way to show them without duplication.

Here's my code:

```<code>Widget build(BuildContext context) {
    return ListView.builder(
      shrinkWrap: true,
      controller: ScrollController(),
      itemCount: snapshot.data!.length,
      padding: const EdgeInsets.only(bottom: 8),
      itemBuilder: (context, index) {
        final spending = snapshot.data![index];

        DateTime spendingDate = DateTime.parse(spending.date);
        var initial =
            DateTime(initialDate.year, initialDate.month, initialDate.day - 1);
        var end = DateTime(endDate.year, endDate.month, endDate.day + 1);

        return spendingDate.isAfter(initial) && spendingDate.isBefore(end)
            ? Column(
                children: [
                  WeekDivider(label: label, dateEstimation: dateEstimation),
                  WeeklySpendingStream(
                    color: color,
                    snapshot: snapshot,
                    initialDate: initialDate,
                    endDate: endDate,
                  ),
                ],
              )
            : const SizedBox();
      },
    );
  }
</code>```

WeeklySpendingStreamCode:

```<code>Widget build(BuildContext context) {
    return ListView.builder(
      shrinkWrap: true,
      controller: ScrollController(),
      itemCount: snapshot.data!.length,
      padding: const EdgeInsets.only(bottom: 8),
      itemBuilder: (context, index) {
        final spending = snapshot.data![index];

        DateTime spendingDate = DateTime.parse(spending.date);
        var initial =
            DateTime(initialDate.year, initialDate.month, initialDate.day - 1);
        var end = DateTime(endDate.year, endDate.month, endDate.day + 1);

        if (spendingDate.isAfter(initial) && spendingDate.isBefore(end)) {
          return SwipeActionCell(
            editModeOffset: 0,
            fullSwipeFactor: 0.50,
            key: ObjectKey(snapshot.data![index]),
            trailingActions: [
              SwipeAction(
                performsFirstActionWithFullSwipe: true,
                color: Colors.transparent,
                content: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(30),
                      color: Colors.red,
                    ),
                    child: getIconButton(Colors.red, IconlyBold.delete)),
                onTap: (handler) async {
                  handler(true);
                  await Future.delayed(const Duration(milliseconds: 100));
                  snapshot.data!.removeAt(index);
                  SpendingDatabaseHelper.instance.removeMethod(spending.id!);
                },
              ),
            ],
            child: SpendingCard(
              beneficiary: spending.beneficiary,
              budgetSpent: currency.format(int.parse(spending.budgetSpent)),
              date: DateFormat("dd-MM-yyyy")
                  .format(DateTime.parse(spending.date)),
              colorValue: color,
            ),
          );
        } else {
          return const SizedBox();
        }
      },
    );
  }
</code>```

The output of snapshot.data:

```<code>[
{id: 8, budgetName:  Food & Beverage, beneficiary: ddd, budgetSpent: 1, date: 2022-02-21},
{id: 7, budgetName:  Food & Beverage, beneficiary: dfgvsd, budgetSpent: 1, date: 2022-02-14},
{id: 4, budgetName:  Food & Beverage, beneficiary: ddd, budgetSpent: 1, date: 2022-02-11},
{id: 10, budgetName:  Food & Beverage, beneficiary: ddd, budgetSpent: 1, date: 2022-02-11},
{id: 5, budgetName:  Food & Beverage, beneficiary: asxasd, budgetSpent: 1, date: 2022-02-06}
]
</code>```

Would really appreciate any suggestions/ideas of how this can be resolved.
Thanks in advance!

答:
Nevermind, I somehow found the solution by getting the data using ".where" and checking whether it is empty or not. It worked nicely.</p>
```<code>var initial = DateTime(initialDate.year, initialDate.month, initialDate.day - 1);
    var end = DateTime(endDate.year, endDate.month, endDate.day + 1);

    final spending = snapshot.data!.where((s) =>
        DateTime.parse(s.date).isAfter(initial) &&
        DateTime.parse(s.date).isBefore(end));

    return spending.isNotEmpty ||
            DateTime.now().isAfter(initial) && DateTime.now().isBefore(end)
        ? spending.isEmpty
            ? Column(
                children: [
                  WeekDivider(label: label, dateEstimation: dateEstimation),
                  const Padding(
                    padding: EdgeInsets.only(top: 8, bottom: 16),
                    child: Text(
                      'No spending this week',
                      style: kCaption,
                    ),
                  ),
                ],
              )
            : ListView(
                shrinkWrap: true,
                controller: ScrollController(),
                padding: const EdgeInsets.only(bottom: 8),
                children: [
                  Column(
                    children: [
                      WeekDivider(label: label, dateEstimation: dateEstimation),
                      WeeklySpendingStream(
                        color: color,
                        snapshot: snapshot,
                        initialDate: initialDate,
                        endDate: endDate,
                      ),
                    ],
                  )
                ],
              )
        : const SizedBox();
  }
</code>```

Body:
I'm trying to show the week's budget spending & timeline only when the user has put in the spending information.

This is the expected result and all seems to be working nicely until I add in more than just one spending in each week.

Here's what happens:

The problem that I understand is that the ListView.builder gets the date that is between "Initial" and "End" and builds the widgets. So because there's 2 spending between those dates, then it builds 2 of those widgets. The problem is I just can't seem to figure out a way to show them without duplication.

Here's my code:

Widget build(BuildContext context) {
    return ListView.builder(
      shrinkWrap: true,
      controller: ScrollController(),
      itemCount: snapshot.data!.length,
      padding: const EdgeInsets.only(bottom: 8),
      itemBuilder: (context, index) {
        final spending = snapshot.data![index];

        DateTime spendingDate = DateTime.parse(spending.date);
        var initial =
            DateTime(initialDate.year, initialDate.month, initialDate.day - 1);
        var end = DateTime(endDate.year, endDate.month, endDate.day + 1);

        return spendingDate.isAfter(initial) && spendingDate.isBefore(end)
            ? Column(
                children: [
                  WeekDivider(label: label, dateEstimation: dateEstimation),
                  WeeklySpendingStream(
                    color: color,
                    snapshot: snapshot,
                    initialDate: initialDate,
                    endDate: endDate,
                  ),
                ],
              )
            : const SizedBox();
      },
    );
  }

WeeklySpendingStreamCode:

Widget build(BuildContext context) {
    return ListView.builder(
      shrinkWrap: true,
      controller: ScrollController(),
      itemCount: snapshot.data!.length,
      padding: const EdgeInsets.only(bottom: 8),
      itemBuilder: (context, index) {
        final spending = snapshot.data![index];

        DateTime spendingDate = DateTime.parse(spending.date);
        var initial =
            DateTime(initialDate.year, initialDate.month, initialDate.day - 1);
        var end = DateTime(endDate.year, endDate.month, endDate.day + 1);

        if (spendingDate.isAfter(initial) && spendingDate.isBefore(end)) {
          return SwipeActionCell(
            editModeOffset: 0,
            fullSwipeFactor: 0.50,
            key: ObjectKey(snapshot.data![index]),
            trailingActions: [
              SwipeAction(
                performsFirstActionWithFullSwipe: true,
                color: Colors.transparent,
                content: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(30),
                      color: Colors.red,
                    ),
                    child: getIconButton(Colors.red, IconlyBold.delete)),
                onTap: (handler) async {
                  handler(true);
                  await Future.delayed(const Duration(milliseconds: 100));
                  snapshot.data!.removeAt(index);
                  SpendingDatabaseHelper.instance.removeMethod(spending.id!);
                },
              ),
            ],
            child: SpendingCard(
              beneficiary: spending.beneficiary,
              budgetSpent: currency.format(int.parse(spending.budgetSpent)),
              date: DateFormat("dd-MM-yyyy")
                  .format(DateTime.parse(spending.date)),
              colorValue: color,
            ),
          );
        } else {
          return const SizedBox();
        }
      },
    );
  }

The output of snapshot.data:

[
{id: 8, budgetName:  Food & Beverage, beneficiary: ddd, budgetSpent: 1, date: 2022-02-21},
{id: 7, budgetName:  Food & Beverage, beneficiary: dfgvsd, budgetSpent: 1, date: 2022-02-14},
{id: 4, budgetName:  Food & Beverage, beneficiary: ddd, budgetSpent: 1, date: 2022-02-11},
{id: 10, budgetName:  Food & Beverage, beneficiary: ddd, budgetSpent: 1, date: 2022-02-11},
{id: 5, budgetName:  Food & Beverage, beneficiary: asxasd, budgetSpent: 1, date: 2022-02-06}
]

Would really appreciate any suggestions/ideas of how this can be resolved.
Thanks in advance!

Body:
Nevermind, I somehow found the solution by getting the data using ".where" and checking whether it is empty or not. It worked nicely.

var initial = DateTime(initialDate.year, initialDate.month, initialDate.day - 1);
    var end = DateTime(endDate.year, endDate.month, endDate.day + 1);

    final spending = snapshot.data!.where((s) =>
        DateTime.parse(s.date).isAfter(initial) &&
        DateTime.parse(s.date).isBefore(end));

    return spending.isNotEmpty ||
            DateTime.now().isAfter(initial) && DateTime.now().isBefore(end)
        ? spending.isEmpty
            ? Column(
                children: [
                  WeekDivider(label: label, dateEstimation: dateEstimation),
                  const Padding(
                    padding: EdgeInsets.only(top: 8, bottom: 16),
                    child: Text(
                      'No spending this week',
                      style: kCaption,
                    ),
                  ),
                ],
              )
            : ListView(
                shrinkWrap: true,
                controller: ScrollController(),
                padding: const EdgeInsets.only(bottom: 8),
                children: [
                  Column(
                    children: [
                      WeekDivider(label: label, dateEstimation: dateEstimation),
                      WeeklySpendingStream(
                        color: color,
                        snapshot: snapshot,
                        initialDate: initialDate,
                        endDate: endDate,
                      ),
                    ],
                  )
                ],
              )
        : const SizedBox();
  }


问:
Regular expression to find URLs within a string
Does anyone know of a regular expression I could use to find URLs within a string? I've found a lot of regular expressions on Google for determining if an entire string is a URL but I need to be able to search an entire string for URLs.  For example, I would like to be able to find www.google.com and http://yahoo.com in the following string:

Hello www.google.com World http://yahoo.com
```

I am not looking for specific URLs in the string. I am looking for ALL of the URLs in the string which is why I need a regular expression.

ContentLicense: CC BY-SA 3.0

Body:
Does anyone know of a regular expression I could use to find URLs within a string? I've found a lot of regular expressions on Google for determining if an entire string is a URL but I need to be able to search an entire string for URLs.  For example, I would like to be able to find www.google.com and http://yahoo.com in the following string:

Hello www.google.com World http://yahoo.com

I am not looking for specific URLs in the string. I am looking for ALL of the URLs in the string which is why I need a regular expression.

Body:
Try this, it can detect any kind of url with any kind of scheme and yes its tested , while copying remember that there should not be blank psace or a new line character

(?:http://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)){3}))(?::(?:\d+))?)(?:/(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[;:@&=])*)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[;:@&=])*))*)(?:\?(?:(?:(?:[a-zA-Z\d$\-_.+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?:/;[Ss][Ee][Cc][Tt][Ii][Oo][Nn]=(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{2}))|[&=~:@/])+)))?)))?)|(?:nfs:(?:(?://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)){3}))(?::(?:\d+))?)(?:(?:/(?:(?:(?:(?:(?:[a-zA-Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?)))?)|(?:/(?:(?:(?:(?:(?:[a-zA-Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?))|(?:(?:(?:(?:(?:[a-zA-Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?)))


问:
I am trying to get retrive data from mongodb but not getting expected output
DB Data -

```<code>[{
    title: "Vivo X50",
    category: "mobile",
    amount: 35000

},
{
    title: "Samsung M32",
    category: "mobile",
    amount: 18000

},
{
    title: "Lenovo 15E253",
    category: "laptop",
    amount: 85000

},
{
    title: "Dell XPS 15R",
    category: "laptop",
    amount: 115000
}]
</code>```

Expected Output:

```<code>[{
    category: "mobile",
    qty: 2,
    totalAmount: 53000
},
{
    category: "laptop",
    qty: 2,
    totalAmount: 200000
}]
</code>```

Code I am running (Using mongoose)

```<code>let products = await Product.aggregate([
    {
      $project: { _id: 0, category: 1, amount: 1 },
    },
    {
      $group: {
        _id: "$category",
        qty: { $sum: 1 },
        totalAmount: { $sum: "$amount" },
      },
    },
  ]);
</code>```

Result I am Getting.

```<code>[
{
"_id": "laptop",
"count": 2,
"totalSum": 200000
},
{
"_id": "mobile",
"count": 2,
"totalSum": 53000
}
]
</code>```

As you can clearly see that I am able to get correct data but I want correct name also category instead of _id. Please help me with that. Thanks in advance

答:
You need $project as the last stage to decorate the output document.

```<code>{
  $project: {
    _id: 0,
    category: "$_id",
    qty: "$qty",
    totalAmount: "$totalAmount"
  }
}
</code>```

Meanwhile, the first stage $project doesn't need.

```<code>db.collection.aggregate([
  {
    $group: {
      _id: "$category",
      qty: {
        $sum: 1
      },
      totalAmount: {
        $sum: "$amount"
      }
    }
  },
  {
    $project: {
      _id: 0,
      category: "$_id",
      qty: "$qty",
      totalAmount: "$totalAmount"
    }
  }
])
</code>```

Sample Mongo Playground

Body:
DB Data -

[{
    title: "Vivo X50",
    category: "mobile",
    amount: 35000

},
{
    title: "Samsung M32",
    category: "mobile",
    amount: 18000

},
{
    title: "Lenovo 15E253",
    category: "laptop",
    amount: 85000

},
{
    title: "Dell XPS 15R",
    category: "laptop",
    amount: 115000
}]

Expected Output:

[{
    category: "mobile",
    qty: 2,
    totalAmount: 53000
},
{
    category: "laptop",
    qty: 2,
    totalAmount: 200000
}]

Code I am running (Using mongoose)

let products = await Product.aggregate([
    {
      $project: { _id: 0, category: 1, amount: 1 },
    },
    {
      $group: {
        _id: "$category",
        qty: { $sum: 1 },
        totalAmount: { $sum: "$amount" },
      },
    },
  ]);

Result I am Getting.

[
{
"_id": "laptop",
"count": 2,
"totalSum": 200000
},
{
"_id": "mobile",
"count": 2,
"totalSum": 53000
}
]

As you can clearly see that I am able to get correct data but I want correct name also category instead of _id. Please help me with that. Thanks in advance

Body:
You need $project as the last stage to decorate the output document.

{
  $project: {
    _id: 0,
    category: "$_id",
    qty: "$qty",
    totalAmount: "$totalAmount"
  }
}

Meanwhile, the first stage $project doesn't need.

db.collection.aggregate([
  {
    $group: {
      _id: "$category",
      qty: {
        $sum: 1
      },
      totalAmount: {
        $sum: "$amount"
      }
    }
  },
  {
    $project: {
      _id: 0,
      category: "$_id",
      qty: "$qty",
      totalAmount: "$totalAmount"
    }
  }
])

Sample Mongo Playground


问:
How to scrollIntoView() inside a specific dropdown(div) in Python
I am trying to scrape a website that requires me to first fill out certain dropdowns.

However, most of the dropdown selections are hidden and only appear in the DOM tree when I scroll down WITHIN the dropdown. Is there a solution I can use to somehow mimic a scroll wheel, or are there other libraries that could complement Selenium?

答:
There are several ways to scroll an element into view but the most reliable one in Selenium is evaluating javascripts scrollIntoview() function.

For example I use this example for scraping twitch.tv in my blog:

```<code>from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.twitch.tv/directory/game/Art")
# find last item and scroll to it
driver.execute_script("""
let items=document.querySelectorAll('.tw-tower>div');
items[items.length-1].scrollIntoView();
""")
</code>```

The javascript finds all "items" in the pagination page and scrolls the last one into view. In your case you should use:

```<code>driver.execute_script("""
let item = document.querySelector('DROPDOWN CSS SELECTOR');
item.scrollIntoView();
""")
</code>```

You can read more about it here: https://scrapfly.io/blog/web-scraping-with-selenium-and-python/#advanced-selenium-functions

Body:
There are several ways to scroll an element into view but the most reliable one in Selenium is evaluating javascripts scrollIntoview() function.

For example I use this example for scraping twitch.tv in my blog:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.twitch.tv/directory/game/Art")
# find last item and scroll to it
driver.execute_script("""
let items=document.querySelectorAll('.tw-tower>div');
items[items.length-1].scrollIntoView();
""")

The javascript finds all "items" in the pagination page and scrolls the last one into view. In your case you should use:

driver.execute_script("""
let item = document.querySelector('DROPDOWN CSS SELECTOR');
item.scrollIntoView();
""")

You can read more about it here: https://scrapfly.io/blog/web-scraping-with-selenium-and-python/#advanced-selenium-functions


问:
Difference between MongoDB and Mongoose
I wanted to use the mongodb database, but I noticed that there are two different databases with either their own website and installation methods: mongodb and mongoose. So I came up asking myself this question: "Which one do I use?".

So in order to answer this question I ask the community if you could explain what are the differences between these two? And if possible pros and cons? Because they really look very similar to me.

答:
MongoDB is The official MongoDB Node.js driver allows Node.js applications to connect to MongoDB and work with data.
On the other side Mongoose it other library build on top of mongoDB. It is more easier to understand and use. If you are a beginner than mongoose is better for you to work with.</p>

Title: Difference between MongoDB and Mongoose


问:
How to make vim to show errors in a new buffer?
I am using vim for competitive programming and I am using this shell script to compile my c++ files.

```<code>g++ -static -DLOCAL -lm -s -x c++ -Wall -Wextra -O2 -std=c++17 -o $1 $1.cpp
</code>```

When I use this script I get all the errors and warnings in the terminal and when I press ENTER everything is gone. Is there a way to modify this script to display errors and warnings in a separate buffer in vim without going to terminal or is there anything that I should add in my .vimrc file ??

I want my vim to show errors like this one below.

答:
I fixed the problem by doing this

nnoremap <F9> :wa <bar> :compiler gcc <bar> :silent! make %:r <CR> :cw <CR>

But I don't know how to highlight errors of quickfix list.

Body:
I am using vim for competitive programming and I am using this shell script to compile my c++ files.

g++ -static -DLOCAL -lm -s -x c++ -Wall -Wextra -O2 -std=c++17 -o $1 $1.cpp

When I use this script I get all the errors and warnings in the terminal and when I press ENTER everything is gone. Is there a way to modify this script to display errors and warnings in a separate buffer in vim without going to terminal or is there anything that I should add in my .vimrc file ??

I want my vim to show errors like this one below.


问:
how to load data when scroll from api for flutter
I want to load more data when scrolling down from API, I tried many methods and packages like infinite_scroll_pagination,pull_to_refresh,lazy-loading-listview they work when I use their example, but I couldn't make it with my code, it's been more than four days and I couldn't solve it
here is my full code which displays all data from API at once I want to loop and display 10 items till the length of the data.
please any help</p>
```<code>    Future getData() async {
    var response = await http.post(
      Uri.parse("https://jokeapp6.000webhostapp.com/index0.php"),
    );
    var responsebody = jsonDecode(response.body);
    print('connected succsefully');
    return responsebody;
  }

  ScrollController scrollController = ScrollController();

 @override
  void initState() {
    scrollController.addListener(() {
      // call your api here
      getData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          endDrawer: NavigationDrawerWidget(),
          appBar: AppBar(
            automaticallyImplyLeading: true,
            backgroundColor: Colors.black,
            title: Text("      الصبر   "),
            centerTitle: true,
          ),
          backgroundColor: Colors.grey[900],
          body: FutureBuilder(
              future: getData(),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                List snap = snapshot.data;

                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(child: CircularProgressIndicator());
                }

   if (snapshot.hasError) {
              return Center(
                child: Text("error"),
              );
            }
            return ListView.separated(
              controller: scrollController,
              itemCount: 10,
              separatorBuilder: (context, index) {
                final data = snap[index];
                final dataJoke = data["joke"];
                final dataAnswer = data["answer"];

                return Card(
                  elevation: 6,
                  margin: EdgeInsets.symmetric(vertical: 3, horizontal: 6),
                  child: Container(
                    color: Colors.grey[600],
                    child: ListTile(
                      title: Text(
                    " ${snap[index]['joke']}",
                    textDirection: TextDirection.rtl,
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                          trailing: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                                minimumSize: Size(1, 30),
                                primary: Colors.grey[900], // background
                                onPrimary: Colors.white70,
                                elevation: 0),
                            onPressed: () async {
                              const urlPreview =
                                  "https://play.google.com/store/apps/details?id=com.amjadalmousawi.joke";
                              await Share.share(
                                  "$dataJoke \n $dataAnswer \n للمزيد من الطرائف والألغاز\n$urlPreview");
                            },
                            child: Icon(Icons.share),
                          ),
                        ),
                      ),
                    );
                  },
                  itemBuilder: (BuildContext context, int index) {
                    if (index % 10 == 5) {
                      return _getAdWidget();
                    }
                    return Text(
                      '',
                    );
                  },
                );
              }),
        ));
  }

  @override
  void dispose() {
    super.dispose();
    _inlineAdaptiveAd?.dispose();
  }
}
</code>```

答:
define scrollcontroller like

```<code>ScrollController scrollController = ScrollController();
</code>```

You need use controller scroll in initState so when your list is reach in the end it will call api

```<code>@override
  void initState() {
  scrollController.addListener(() {
      // call your api here
  });
  super.initState();
}
</code>```

You need to define your scrollcontroller in listview.separated like below

```<code> ListView.separated(
  controller: scrollcontroller,
  itemCount: 4,
  itemBuilder:(BuildContext context,int index) {
         // your code
         return Container();
     },
     separatorBuilder:(BuildContext context,int index) {
         // your code
         return Container();
     },
),
</code>```

Body:
I want to load more data when scrolling down from API, I tried many methods and packages like infinite_scroll_pagination,pull_to_refresh,lazy-loading-listview they work when I use their example, but I couldn't make it with my code, it's been more than four days and I couldn't solve it
here is my full code which displays all data from API at once I want to loop and display 10 items till the length of the data.
please any help

    Future getData() async {
    var response = await http.post(
      Uri.parse("https://jokeapp6.000webhostapp.com/index0.php"),
    );
    var responsebody = jsonDecode(response.body);
    print('connected succsefully');
    return responsebody;
  }

  ScrollController scrollController = ScrollController();

 @override
  void initState() {
    scrollController.addListener(() {
      // call your api here
      getData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          endDrawer: NavigationDrawerWidget(),
          appBar: AppBar(
            automaticallyImplyLeading: true,
            backgroundColor: Colors.black,
            title: Text("      الصبر   "),
            centerTitle: true,
          ),
          backgroundColor: Colors.grey[900],
          body: FutureBuilder(
              future: getData(),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                List snap = snapshot.data;

                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(child: CircularProgressIndicator());
                }

   if (snapshot.hasError) {
              return Center(
                child: Text("error"),
              );
            }
            return ListView.separated(
              controller: scrollController,
              itemCount: 10,
              separatorBuilder: (context, index) {
                final data = snap[index];
                final dataJoke = data["joke"];
                final dataAnswer = data["answer"];

                return Card(
                  elevation: 6,
                  margin: EdgeInsets.symmetric(vertical: 3, horizontal: 6),
                  child: Container(
                    color: Colors.grey[600],
                    child: ListTile(
                      title: Text(
                    " ${snap[index]['joke']}",
                    textDirection: TextDirection.rtl,
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                          trailing: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                                minimumSize: Size(1, 30),
                                primary: Colors.grey[900], // background
                                onPrimary: Colors.white70,
                                elevation: 0),
                            onPressed: () async {
                              const urlPreview =
                                  "https://play.google.com/store/apps/details?id=com.amjadalmousawi.joke";
                              await Share.share(
                                  "$dataJoke \n $dataAnswer \n للمزيد من الطرائف والألغاز\n$urlPreview");
                            },
                            child: Icon(Icons.share),
                          ),
                        ),
                      ),
                    );
                  },
                  itemBuilder: (BuildContext context, int index) {
                    if (index % 10 == 5) {
                      return _getAdWidget();
                    }
                    return Text(
                      '',
                    );
                  },
                );
              }),
        ));
  }

  @override
  void dispose() {
    super.dispose();
    _inlineAdaptiveAd?.dispose();
  }
}

Body:
define scrollcontroller like

ScrollController scrollController = ScrollController();

You need use controller scroll in initState so when your list is reach in the end it will call api

@override
  void initState() {
  scrollController.addListener(() {
      // call your api here
  });
  super.initState();
}

You need to define your scrollcontroller in listview.separated like below

 ListView.separated(
  controller: scrollcontroller,
  itemCount: 4,
  itemBuilder:(BuildContext context,int index) {
         // your code
         return Container();
     },
     separatorBuilder:(BuildContext context,int index) {
         // your code
         return Container();
     },
),


问:
How to delete Object if value of nested object property value < epoch
I have an object tree that contains the following values.

```<code>data = {
  TD2n9thHQgyvWdPhOkHQ: {
    heartbeat: 1644637961658,
    joinTime: 1644636756368,
  },
  IASJDAIODJiklk243oi: {
    heartbeat: 1644637961658,
    joinTime: 1644637961658,
  }
 }
</code>```

I am trying to check if the value of each heartbeat is 10 seconds less than the current time from epoch and if it is, delete the parent object.

Any help would be much appreciated!

答:
You can use the delete operator to completely remove the object that you want.

data = {
  TD2n9thHQgyvWdPhOkHQ: {
    heartbeat: 1644637961658,
    joinTime: 1644636756368,
  },
  IASJDAIODJiklk243oi: {
    heartbeat: 1644637961658,
    joinTime: 1644637961658,
  }
}

for (let i in data) {
  if ({"less than 10 sec condtion will appear here"}) {
    delete data[i]
  }
}```

Body:
I have an object tree that contains the following values.

data = {
  TD2n9thHQgyvWdPhOkHQ: {
    heartbeat: 1644637961658,
    joinTime: 1644636756368,
  },
  IASJDAIODJiklk243oi: {
    heartbeat: 1644637961658,
    joinTime: 1644637961658,
  }
 }

I am trying to check if the value of each heartbeat is 10 seconds less than the current time from epoch and if it is, delete the parent object.

Any help would be much appreciated!


问:
How to set dataProvider Name before specifying in my test method
I am trying to check the environment where I will be running my test before setting dataProvider name in my test method.

```<code>public class AssignmentSOAPTest {
    private static final String  ctdataProvName=System.getProperty("env");

   @BeforeClass
   public void setUp()  {
   }

   @Test(dataProvider = ctdataProvName, dataProviderClass CCCAssignmentSOAPDataProvider.class)
   @Feature("FullCCCAssignment")
   public void tc01FullCCCAssignment(int a,int b,int c) {

    System.out.println("These are the number provided by Data Provider "+  a+"," +b+","+c);

}
</code>```

}

In this case since my @Test Method is giving me an error: Attribute value must be constant. I discovered this is due because of the way I am setting the constant is not the correct way. I tried different ways to check the environment before setting the constant but could not figure it out. Is there a way to do this?

The reason I would like to check the environment before setting the name is because that way I will need fewer @Test methods in my testScript. I have 4 different environments as well as 10 different test cases. The test cases will be the same among environments but data will be different.

My Data provider class looks like this(did not add  all environments and data will be different):

```<code>   @DataProvider (name = "ct-environment-data-provider")
   public Object[][] ctDPMethod (Method m){
       switch (m.getName()) {
        case "tc01FullCCCAssignment":
            return new Object[][] {{2, 3 , 5}};
        case "minimumAssignment":
            return new Object[][] {{2, 3, -1}};
        case "updateAssignment":
            return new Object[][] {{1, 3, -1}};
        case "cancelAssignment":
            return new Object[][] {{3, 3, -1}};
        case "saveAssignment":
            return new Object[][] {{8, 3, -1}};
        case "openShopAssignment":
            return new Object[][] {{5, 3, -1}};
        case "casualtyAssignment":
            return new Object[][] {{6, 3, -1}};
   }
   return null;
}

@DataProvider (name = "int-environment-data-provider")
public Object[][] intDPMethod (Method m){
    switch (m.getName()) {
        case "tc01FullCCCAssignment":
            return new Object[][] {{1, 1 , 5}};
        case "minimumAssignment":
            return new Object[][] {{2, 3, -1}};
        case "updateAssignment":
            return new Object[][] {{1, 3, -1}};
        case "cancelAssignment":
            return new Object[][] {{3, 3, -1}};
        case "saveAssignment":
            return new Object[][] {{8, 3, -1}};
        case "openShopAssignment":
            return new Object[][] {{5, 3, -1}};
        case "casualtyAssignment":
            return new Object[][] {{6, 3, -1}};
    }
}
</code>```

答:
You could use the IAnnotationTransformer class to set the data provider name based on System.getProperty. Annotation transformer can be used to modify the @Test annotation and it would be executed before any test is run.

public class CustomTransformer implements IAnnotationTransformer {
    private static final String  ctdataProvName = System.getProperty("env");

    // include the name of all the test methods in the below list,
    // for which you need to update the data provider name
    private static final List<String> methods = Arrays.asList("tc01FullCCCAssignment");

    @Override
    public void transform(ITestAnnotation annotation,
                          Class testClass,
                          Constructor testConstructor,
                          Method testMethod) {

        if(testMethod != null && methods.contains(testMethod.getName())) {
            annotation.setDataProvider(ctdataProvName);
        }
    }
}
```
<p>Now, you need to mention the annotation transformer in your suite xml file under the <code><suite></code> tag:</p>
<pre class="lang-xml prettyprint-override"><code><listeners>
    <listener class-name="com.yourpackage.CustomTransformer" />
</listeners>
</code>```

Some listeners could be declared in the test class itself using @Listener annotation, but annotation transformers should be defined ONLY through suite xml. This is because the annotation transformers need to be executed before the test classes are processed so that the annotations are finalized.

Body:
I am trying to check the environment where I will be running my test before setting dataProvider name in my test method.

public class AssignmentSOAPTest {
    private static final String  ctdataProvName=System.getProperty("env");

   @BeforeClass
   public void setUp()  {
   }

   @Test(dataProvider = ctdataProvName, dataProviderClass CCCAssignmentSOAPDataProvider.class)
   @Feature("FullCCCAssignment")
   public void tc01FullCCCAssignment(int a,int b,int c) {

    System.out.println("These are the number provided by Data Provider "+  a+"," +b+","+c);

}

}

In this case since my @Test Method is giving me an error: Attribute value must be constant. I discovered this is due because of the way I am setting the constant is not the correct way. I tried different ways to check the environment before setting the constant but could not figure it out. Is there a way to do this?

The reason I would like to check the environment before setting the name is because that way I will need fewer @Test methods in my testScript. I have 4 different environments as well as 10 different test cases. The test cases will be the same among environments but data will be different.

My Data provider class looks like this(did not add  all environments and data will be different):

   @DataProvider (name = "ct-environment-data-provider")
   public Object[][] ctDPMethod (Method m){
       switch (m.getName()) {
        case "tc01FullCCCAssignment":
            return new Object[][] {{2, 3 , 5}};
        case "minimumAssignment":
            return new Object[][] {{2, 3, -1}};
        case "updateAssignment":
            return new Object[][] {{1, 3, -1}};
        case "cancelAssignment":
            return new Object[][] {{3, 3, -1}};
        case "saveAssignment":
            return new Object[][] {{8, 3, -1}};
        case "openShopAssignment":
            return new Object[][] {{5, 3, -1}};
        case "casualtyAssignment":
            return new Object[][] {{6, 3, -1}};
   }
   return null;
}

@DataProvider (name = "int-environment-data-provider")
public Object[][] intDPMethod (Method m){
    switch (m.getName()) {
        case "tc01FullCCCAssignment":
            return new Object[][] {{1, 1 , 5}};
        case "minimumAssignment":
            return new Object[][] {{2, 3, -1}};
        case "updateAssignment":
            return new Object[][] {{1, 3, -1}};
        case "cancelAssignment":
            return new Object[][] {{3, 3, -1}};
        case "saveAssignment":
            return new Object[][] {{8, 3, -1}};
        case "openShopAssignment":
            return new Object[][] {{5, 3, -1}};
        case "casualtyAssignment":
            return new Object[][] {{6, 3, -1}};
    }
}

Body:
You could use the IAnnotationTransformer class to set the data provider name based on System.getProperty. Annotation transformer can be used to modify the @Test annotation and it would be executed before any test is run.

public class CustomTransformer implements IAnnotationTransformer {
    private static final String  ctdataProvName = System.getProperty("env");

    // include the name of all the test methods in the below list,
    // for which you need to update the data provider name
    private static final List<String> methods = Arrays.asList("tc01FullCCCAssignment");

    @Override
    public void transform(ITestAnnotation annotation,
                          Class testClass,
                          Constructor testConstructor,
                          Method testMethod) {

        if(testMethod != null && methods.contains(testMethod.getName())) {
            annotation.setDataProvider(ctdataProvName);
        }
    }
}

Now, you need to mention the annotation transformer in your suite xml file under the <suite> tag:

<listeners>
    <listener class-name="com.yourpackage.CustomTransformer" />
</listeners>

Some listeners could be declared in the test class itself using @Listener annotation, but annotation transformers should be defined ONLY through suite xml. This is because the annotation transformers need to be executed before the test classes are processed so that the annotations are finalized.


问:
Why is binary_search not working as expected?
The question is to find the index of first element in the array that repeats itself atleast once in the array.

Input:

7

1 3 4 5 3 7 2

```<code>#include <bits/stdc++.h>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n;
    cin >> n;

    int a[n], curr = -1;
    int num = sizeof(a) / sizeof(a[0]);

    for (int i = 0; i < n; i++)
        cin >> a[i];

    for (int i = 0; i < n; i++)
    {
        int x = a[i];
        a[i] = -1;
        if (binary_search(a, a + num, x))
        {
            curr = i;
            cout << curr << endl;
            break;
        }
    }
    cout << curr + 1;
    return 0;
}
</code>```

Expected Output:
2
(As 3 is the first element to appear twice in the array)

Output received:
0

答:
```<code>cin >> n;

int a[n]
</code>```

This isn't allowed in C++. The size of an array variable must be compile time constant. n is not compile time constant. To create an array of runtime length, you must allocate it dynamically. Simplest solution is to use std::vector,

```<code>int num = sizeof(a) / sizeof(a[0]);
</code>```

Use std::size(a) to get the size of an array instead. However, in this case, just use n.

```<code>binary_search(a, a + num, x)
</code>```

The input range must be partially sorted in order to use std::binary_search with respect of the searched number. Since you use potentially all elements as the searched number, this effectively means that the array must be fully sorted.

Input:

```<code>7

1 3 4 5 3 7 2
</code>```

Your input array is not fully sorted. As result of violating the pre-condition, the behaviour of the program is undefined.

Body:
The question is to find the index of first element in the array that repeats itself atleast once in the array.

Input:

7

1 3 4 5 3 7 2

#include <bits/stdc++.h>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n;
    cin >> n;

    int a[n], curr = -1;
    int num = sizeof(a) / sizeof(a[0]);

    for (int i = 0; i < n; i++)
        cin >> a[i];

    for (int i = 0; i < n; i++)
    {
        int x = a[i];
        a[i] = -1;
        if (binary_search(a, a + num, x))
        {
            curr = i;
            cout << curr << endl;
            break;
        }
    }
    cout << curr + 1;
    return 0;
}

Expected Output:
2
(As 3 is the first element to appear twice in the array)

Output received:
0

Body:
cin >> n;

int a[n]

This isn't allowed in C++. The size of an array variable must be compile time constant. n is not compile time constant. To create an array of runtime length, you must allocate it dynamically. Simplest solution is to use std::vector,

int num = sizeof(a) / sizeof(a[0]);

Use std::size(a) to get the size of an array instead. However, in this case, just use n.

binary_search(a, a + num, x)

The input range must be partially sorted in order to use std::binary_search with respect of the searched number. Since you use potentially all elements as the searched number, this effectively means that the array must be fully sorted.

Input:

7

1 3 4 5 3 7 2

Your input array is not fully sorted. As result of violating the pre-condition, the behaviour of the program is undefined.


问:
Best way to handle EventListeners/Handlers for 1000 buttons?
I'm working on a game where users can win buttons/badges as awards.  I estimate there will be around 500 awards, in all.

I want to allow the users to sell their duplicate/unwanted badges to the bank and buy new ones from the bank.

I am showing the badges in multiple awards frames.  Below the badges, I show the count, along with a "Buy" and "Sell" button.

My question is: What's the best way to handle SO MANY buy & sell buttons?  Is there a way around coding 1000 eventListeners and 1000 eventHandlers?

One possible solution is to name my buttons, incrementally, like "buy_mc1", "buy_mc2", etc.  Then do a loop to create listeners for this["buy_mc" + i].  However, I would then have to make VERY sure that I link these back correctly to the awards.

Currently, I have an "award_mc" field in my database, which stores the name of the movieclip in my .fla.  From that, I can access related assets, like the count field, like: this[db.award_mc + "_count"].txt.

Unfortunately, this method does not lend itself well to looped access.

Maybe I can create an array of movieclip names that are in synch with the buy/sell buttons.  For example:

myArray = {aMissionAward, anotherAward, ubernessAward};

My buttons would be:
buy_0, buy_1, buy_2, etc.

When someone clicks a button, I can link buy_2 to "ubernessAward", then look for "ubernessAward" on the database.

How can I get the number from the button, though?  Even if I can loop through setting up the eventListeners, will I have to set up individuatl eventHandlers to process the correct index number?

I'm open to suggestions on another way to do this.

-------------------------- EDIT ----------------------------

Here's my solution.  Props to Jens Struwe for pointing me in the right direction.

I was not able to get this to work with buttons on the stage.  Apparently, buttons are a static class.  MovieClips are dynamic, so I was able to get this to work by using MovieClips.  Here's what I did:

Added 3 MovieClips to the stage.
Named them "mc0", "mc1", and "mc2".

Add this AS3 code:

```<code>for (var i:Number=0; i<3; i++)
{
    this["mc" + i].addEventListener( MouseEvent.CLICK, onMcClick );
    this["mc" + i].awardKey = i;
}

function onMcClick( evt:MouseEvent ):void
{
    trace("MC ID = " +(evt.target).awardKey);

    switch ((evt.target).awardKey)
    {
        case 0:
            trace("     Do stuff for 0");
            break;
        case 1:
            trace("     Do stuff for 1");
            break;
        case 2:
            trace("     Do stuff for 2");
            break;
    }
}
</code>```

From here, I can tie the awardKey to an array of MovieClip names.  Then, I can use the MovieClip names to read my database.

This is why I come to Stack Overflow, FIRST, when I have a problem.  :)

答:
There are several ways to handle this.

You haven't said whether you're using a custom event or a native Flash event.  If you're listening to a native Flash event that bubbles (check the docs for your event) or you're generating a custom event that you are bubbling, you can simply listen to the parent DisplayObjectContainer that contains all of the buttons. Then, use event.target to determine which button actually generated the event.

Another way you can handle this is to listen for the ADDED_TO_STAGE event, then have something like this in the handler:

```<code>protected function checkNewObject(e:Event):void  {
    if (e.target is YourButtonSubclass) {
       var btn:YourButtonSubclass = e.target as YourButtonSubclass;
       btn.addEventListener('SomeEvent', theHandler);
    }
}
</code>```

HTH;
Amy

Body:
I'm working on a game where users can win buttons/badges as awards.  I estimate there will be around 500 awards, in all.

I want to allow the users to sell their duplicate/unwanted badges to the bank and buy new ones from the bank.

I am showing the badges in multiple awards frames.  Below the badges, I show the count, along with a "Buy" and "Sell" button.

My question is: What's the best way to handle SO MANY buy & sell buttons?  Is there a way around coding 1000 eventListeners and 1000 eventHandlers?

One possible solution is to name my buttons, incrementally, like "buy_mc1", "buy_mc2", etc.  Then do a loop to create listeners for this["buy_mc" + i].  However, I would then have to make VERY sure that I link these back correctly to the awards.

Currently, I have an "award_mc" field in my database, which stores the name of the movieclip in my .fla.  From that, I can access related assets, like the count field, like: this[db.award_mc + "_count"].txt.

Unfortunately, this method does not lend itself well to looped access.

Maybe I can create an array of movieclip names that are in synch with the buy/sell buttons.  For example:

myArray = {aMissionAward, anotherAward, ubernessAward};

My buttons would be:
buy_0, buy_1, buy_2, etc.

When someone clicks a button, I can link buy_2 to "ubernessAward", then look for "ubernessAward" on the database.

How can I get the number from the button, though?  Even if I can loop through setting up the eventListeners, will I have to set up individuatl eventHandlers to process the correct index number?

I'm open to suggestions on another way to do this.

-------------------------- EDIT ----------------------------

Here's my solution.  Props to Jens Struwe for pointing me in the right direction.

I was not able to get this to work with buttons on the stage.  Apparently, buttons are a static class.  MovieClips are dynamic, so I was able to get this to work by using MovieClips.  Here's what I did:

Added 3 MovieClips to the stage.
Named them "mc0", "mc1", and "mc2".

Add this AS3 code:

for (var i:Number=0; i<3; i++)
{
    this["mc" + i].addEventListener( MouseEvent.CLICK, onMcClick );
    this["mc" + i].awardKey = i;
}

function onMcClick( evt:MouseEvent ):void
{
    trace("MC ID = " +(evt.target).awardKey);

    switch ((evt.target).awardKey)
    {
        case 0:
            trace("     Do stuff for 0");
            break;
        case 1:
            trace("     Do stuff for 1");
            break;
        case 2:
            trace("     Do stuff for 2");
            break;
    }
}

From here, I can tie the awardKey to an array of MovieClip names.  Then, I can use the MovieClip names to read my database.

This is why I come to Stack Overflow, FIRST, when I have a problem.  :)

Body:
There are several ways to handle this.

You haven't said whether you're using a custom event or a native Flash event.  If you're listening to a native Flash event that bubbles (check the docs for your event) or you're generating a custom event that you are bubbling, you can simply listen to the parent DisplayObjectContainer that contains all of the buttons. Then, use event.target to determine which button actually generated the event.

Another way you can handle this is to listen for the ADDED_TO_STAGE event, then have something like this in the handler:

protected function checkNewObject(e:Event):void  {
    if (e.target is YourButtonSubclass) {
       var btn:YourButtonSubclass = e.target as YourButtonSubclass;
       btn.addEventListener('SomeEvent', theHandler);
    }
}

HTH;
Amy


问:
How to download file from website that requires login information using Python?
I am trying to download some data from a website using Python. If you simply copy and paste the url, it shows nothing unless you fill in the login information. I have the login name and password, however how should I include these in Python?

My current code is:

```<code>import urllib, urllib2, cookielib

username = my_user_name
password = my_pwd

link = 'www.google.com' # just for instance
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})

opener.open(link, login_data)
resp = opener.open(link,login_data)
print resp.read()
</code>```

There is no error pops out, however resp.read() is a bunch of CSS and it only has the messages like "you have to login before reading news here."

So how can I retrieve the page that after logging in?

Just noticed that the website requires 3 entries:

```<code>Company:

Username:

Password:
</code>```

I have all of them but how can I put all three in the login variable?

If I run it without login it returns:

```<code>cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

opener.open(dd)
resp = opener.open(dd)

print resp.read()
</code>```

Here is the print-outs:

```<code><DIV id=header>
<DIV id=strapline><!-- login_display -->
<P><FONT color=#000000>All third party users of this website and/or data produced by the Baltic do so at their own risk. The Baltic owes no duty of care or any other obligation to any party other than the contractual obligations which it owes to its direct contractual partners. </FONT></P><IMG src="images/top-strap.gif"> <!-- template [strapline]--></DIV><!-- end strapline -->
<DIV id=memberNav>
<FORM class=members id=form1 name=form1 action=client_login/client_authorise.asp?action=login method=post onsubmits="return check()">
</code>```

答:
Try using another useragent in headers. It looks like the site has some type of scraper detection, you didnt provide the url to check for that.
Some sites make javascript tests to check if the request looks automated, in that case go for playwright or selenium.</p>

Body:
I am trying to download some data from a website using Python. If you simply copy and paste the url, it shows nothing unless you fill in the login information. I have the login name and password, however how should I include these in Python?

My current code is:

import urllib, urllib2, cookielib

username = my_user_name
password = my_pwd

link = 'www.google.com' # just for instance
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})

opener.open(link, login_data)
resp = opener.open(link,login_data)
print resp.read()

There is no error pops out, however resp.read() is a bunch of CSS and it only has the messages like "you have to login before reading news here."

So how can I retrieve the page that after logging in?

Just noticed that the website requires 3 entries:

Company:

Username:

Password:

I have all of them but how can I put all three in the login variable?

If I run it without login it returns:

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

opener.open(dd)
resp = opener.open(dd)

print resp.read()

Here is the print-outs:

All third party users of this website and/or data produced by the Baltic do so at their own risk. The Baltic owes no duty of care or any other obligation to any party other than the contractual obligations which it owes to its direct contractual partners.

<FORM class=members id=form1 name=form1 action=client_login/client_authorise.asp?action=login method=post onsubmits="return check()">


问:
How do I put a conditional and a loop in the same line?
I would like to put a conditional and loop on the same line on Perl. This is what I would like to achieve:

```<code>foreach (0 .. 10) {
    print $_ if $_ % 2;
}
</code>```

which should give me 13579. I'm looking for a statement like loop comprehension in Python, e.g.

```<code>[i for i in range(10) if i % 2]
</code>```

I know that print $_ foreach 0 .. 10; works but the problem is adding the conditional to the statement as well...

答:
Why not something like below?</p>
```<code>use warnings;
use strict;

print ($_ % 2 ? $_ : "") for (1..10);
</code>```

Body:
I would like to put a conditional and loop on the same line on Perl. This is what I would like to achieve:

foreach (0 .. 10) {
    print $_ if $_ % 2;
}

which should give me 13579. I'm looking for a statement like loop comprehension in Python, e.g.

[i for i in range(10) if i % 2]

I know that print $_ foreach 0 .. 10; works but the problem is adding the conditional to the statement as well...

Body:
Why not something like below?

use warnings;
use strict;

print ($_ % 2 ? $_ : "") for (1..10);


问:
Stack multiple columns on top of eachother on Google Sheet?
I am using Google SpreadSheet, and I'm trying to import data from different sources together using a combination of query, importrange and curly brackets:

```<code>={Query(Importrange(SheetA),"select Col1,Col2,Col3,Col4 where Col1 is not null");
Query(Importrange(SheetB),"select Col1,Col2,Col3,Col4 where Col1 is not null")}
</code>```

But the result formula only returns SheetA data.

Since I only need 4 particular columns from SheetA and SheetB, I'd want the columns from both sheets to stack on top of eachother like this:

Col1
Col2
Col3
Col4

Data SheetA
Data SheetA
Data SheetA
Data SheetA

Data SheetB
Data SheetB
Data SheetB
Data SheetB

I tried running each =query(importrange) individually and combine them afterwards using {A:D;E:H} but it gives Result was not automatically expanded, please insert more rows error.

I tried looking for other similar threads but they were mostly about stacking different columns into one singular column. Can you help me with my case?

答:
Turns out the issue was due to the infinite blank rows when trying to combine 2 infinite ranges A:D and E:H,

By enclosing them with a query, remove null value condition, my formula works fine now:

```<code>=query({A:D;E:H},"Select * where Col1 is not null")
</code>```

Nevertheless, are there any ways to stack those 4 columns using the original singular formula using query, importrange and curly brackets?

```<code>={Query(Importrange(SheetA),"select Col1,Col2,Col3,Col4 where Col1 is not null");
Query(Importrange(SheetB),"select Col1,Col2,Col3,Col4 where Col1 is not null")}
</code>```

Body:
I am using Google SpreadSheet, and I'm trying to import data from different sources together using a combination of query, importrange and curly brackets:

={Query(Importrange(SheetA),"select Col1,Col2,Col3,Col4 where Col1 is not null");
Query(Importrange(SheetB),"select Col1,Col2,Col3,Col4 where Col1 is not null")}

But the result formula only returns SheetA data.

Since I only need 4 particular columns from SheetA and SheetB, I'd want the columns from both sheets to stack on top of eachother like this:

Col1
Col2
Col3
Col4

Data SheetA
Data SheetA
Data SheetA
Data SheetA

Data SheetB
Data SheetB
Data SheetB
Data SheetB

I tried running each =query(importrange) individually and combine them afterwards using {A:D;E:H} but it gives Result was not automatically expanded, please insert more rows error.

I tried looking for other similar threads but they were mostly about stacking different columns into one singular column. Can you help me with my case?

Body:
Turns out the issue was due to the infinite blank rows when trying to combine 2 infinite ranges A:D and E:H,

By enclosing them with a query, remove null value condition, my formula works fine now:

=query({A:D;E:H},"Select * where Col1 is not null")

Nevertheless, are there any ways to stack those 4 columns using the original singular formula using query, importrange and curly brackets?

={Query(Importrange(SheetA),"select Col1,Col2,Col3,Col4 where Col1 is not null");
Query(Importrange(SheetB),"select Col1,Col2,Col3,Col4 where Col1 is not null")}


问:
Swipe event triggers tap event for ipod touch
I am using jquery mobile beta and jquery 1.6.
On ipod touch, a swipe event is also trigerring the tap event.
This issue is not hapenning on android devices.
I am trying to google out the solution, but looks like there are not many with the same problem. Is there something very basic that I am missing??

```<code>$("div.totapandswipe").bind('tap',function(event, ui){
    alert('event');
});

$("div.totapandswipe").bind('swipe',function(event, ui){
            alert('event');
});
</code>```

Thank you for the help!

答:
This seemed to help me:

```<code>$("selector").swiperight(function (e) {
  if (e.type === "swiperight") {
    myHandler(e);
  }
});
</code>```

It's lame that this would be an issue.  Jqm bug on this yet?

Body:
I am using jquery mobile beta and jquery 1.6.
On ipod touch, a swipe event is also trigerring the tap event.
This issue is not hapenning on android devices.
I am trying to google out the solution, but looks like there are not many with the same problem. Is there something very basic that I am missing??

$("div.totapandswipe").bind('tap',function(event, ui){
    alert('event');
});

$("div.totapandswipe").bind('swipe',function(event, ui){
            alert('event');
});

Thank you for the help!

Body:
This seemed to help me:

$("selector").swiperight(function (e) {
  if (e.type === "swiperight") {
    myHandler(e);
  }
});

It's lame that this would be an issue.  Jqm bug on this yet?


问:
How can I send a value with Select tag through the useState on ReactJS
I want my code to send the variable from onChange to useState here's my code at for displaying my table on each row

```<code>const dataTableElements = entireListData
.slice(0, maxRow)
.map((entireListData, index) => {
  var dotStatus = null;

  if (entireListData.PriceStatus == true) {
    dotStatus = <GreenDot>{entireListData.Price}</GreenDot>;
  } else {
    dotStatus = <RedDot>{entireListData.Price}</RedDot>;
  }
  return (
    <Tr data-index={index}>
      <Td>{entireListData.no}</Td>
      <Td>{entireListData.BillNo}</Td>
      <Td>{entireListData.Product}</Td>
      <Td>
        <StatusTableBox>{dotStatus}</StatusTableBox>
      </Td>
    </Tr>
  );
});
</code>```

next is my select tag

```<code>return (
<div>
  <Tabbar />
  <div>
    <p>
      Show
      <select
        value={entireListData.no}
        onChange={() => {
          sendCurrentRow(entireListData.no);
        }}
      >
        {rowTableElement}
      </select>
      Entires
    </p>
  </div>
</code>```

from the result of the above, it shows in console "undefined".

答:
Usually the select tag gives an event in the onChange method that you can use to extract the value which selected, take a look at this example:

```<code>      <select
        value={entireListData.no}
        onChange={(event) => {
          sendCurrentRow(event.target.value);
        }}
      >
         //here should be your options with different values
         <option value="1">
           1
         </option>
         <option value="2">
           2
         </option>
        // I don't know this value has the option or not => {rowTableElement}
      </select>
</code>```

Body:
I want my code to send the variable from onChange to useState here's my code at for displaying my table on each row

const dataTableElements = entireListData
.slice(0, maxRow)
.map((entireListData, index) => {
  var dotStatus = null;

  if (entireListData.PriceStatus == true) {
    dotStatus = <GreenDot>{entireListData.Price}</GreenDot>;
  } else {
    dotStatus = <RedDot>{entireListData.Price}</RedDot>;
  }
  return (

      {entireListData.no}
      {entireListData.BillNo}
      {entireListData.Product}

        <StatusTableBox>{dotStatus}</StatusTableBox>

  );
});

next is my select tag

return (

  <Tabbar />

      Show
      <select
        value={entireListData.no}
        onChange={() => {
          sendCurrentRow(entireListData.no);
        }}
      >
        {rowTableElement}
      </select>
      Entires

from the result of the above, it shows in console "undefined".

Body:
Usually the select tag gives an event in the onChange method that you can use to extract the value which selected, take a look at this example:

      <select
        value={entireListData.no}
        onChange={(event) => {
          sendCurrentRow(event.target.value);
        }}
      >
         //here should be your options with different values
         <option value="1">
           1
         </option>
         <option value="2">
           2
         </option>
        // I don't know this value has the option or not => {rowTableElement}
      </select>


问:
Getting current date and time in JavaScript
I have a script that prints the current date and time in JavaScript, but the DATE is always wrong. Here is the code:

```<code>var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDay() + "/" + currentdate.getMonth()
+ "/" + currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
</code>```

It should print 18/04/2012 15:07:33 and prints 3/3/2012 15:07:33

答:
Short and simple:-

```<code>console.log(new Date().toLocaleString());
</code>```

Reference

Body:
I have a script that prints the current date and time in JavaScript, but the DATE is always wrong. Here is the code:

var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDay() + "/" + currentdate.getMonth()
+ "/" + currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();

It should print 18/04/2012 15:07:33 and prints 3/3/2012 15:07:33

Body:
Short and simple:-

console.log(new Date().toLocaleString());

Reference


问:
Getting a fetch error using redux toolkit and RTK-Query
I am using RTK-Query, and Redux-toolkit for this app, and I created an api-slice with createApi, as per the docs.

When I run a request to the backend, I get a "FETCH_ERROR"; however, when I run the same request using Axios, I get the data correctly from the backend, which leads me to believe I have an error in my code. I am just not sure where exactly it is.

Here is the error:

Object {
  "api": Object {
    "config": Object {
      "focused": true,
      "keepUnusedDataFor": 60,
      "middlewareRegistered": true,
      "online": true,
      "reducerPath": "api",
      "refetchOnFocus": false,
      "refetchOnMountOrArgChange": false,
      "refetchOnReconnect": false,
    },
    "mutations": Object {},
    "provided": Object {},
    "queries": Object {
      "test(undefined)": Object {
        "endpointName": "test",
        "error": Object {
          "error": "TypeError: Network request failed",
          "status": "FETCH_ERROR",
        },
        "requestId": "BWOuLpOxoDKTzlUYFLW4x",
        "startedTimeStamp": 1643667104869,
        "status": "rejected",
      },
    },
    "subscriptions": Object {
      "test(undefined)": Object {
        "QJSCV641RznGWyudGWuMb": Object {
          "pollingInterval": 0,
          "refetchOnFocus": undefined,
          "refetchOnReconnect": undefined,
        },
      },
    },
  },
  "test": Object {
    "data": Array [],
  },
}
```
<p>Here is the test slice:</p>
<pre class="lang-js prettyprint-override"><code>import { createSlice } from "@reduxjs/toolkit";

const testSlice = createSlice({
  name: "test",
  initialState: {
    data: [],
  },
  reducers: {
    getData: (state) => {
      state;
    },
  },
});

export const { getData } = testSlice.actions;
export default testSlice.reducer;
</code>```

Here is the apiSlice:

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const apiSice = createApi({
  reducerPath: "test",
  baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_backend_url }),
  endpoints: (builder) => ({
    test: builder.query({
      query: () => "/test",
    }),
  }),
});

export const { useTestQuery } = apiSice;
```

答: I solved it by changing the backend URL to my current ipv4 (for expo development, otherwise just your whatever your backend URL is) address in my .env file, then deleting cache, and restarting my app. In my case I was using expo so, expo r -c, and it worked.

Body:
I am using RTK-Query, and Redux-toolkit for this app, and I created an api-slice with createApi, as per the docs.

When I run a request to the backend, I get a "FETCH_ERROR"; however, when I run the same request using Axios, I get the data correctly from the backend, which leads me to believe I have an error in my code. I am just not sure where exactly it is.

Here is the error:

Object {
  "api": Object {
    "config": Object {
      "focused": true,
      "keepUnusedDataFor": 60,
      "middlewareRegistered": true,
      "online": true,
      "reducerPath": "api",
      "refetchOnFocus": false,
      "refetchOnMountOrArgChange": false,
      "refetchOnReconnect": false,
    },
    "mutations": Object {},
    "provided": Object {},
    "queries": Object {
      "test(undefined)": Object {
        "endpointName": "test",
        "error": Object {
          "error": "TypeError: Network request failed",
          "status": "FETCH_ERROR",
        },
        "requestId": "BWOuLpOxoDKTzlUYFLW4x",
        "startedTimeStamp": 1643667104869,
        "status": "rejected",
      },
    },
    "subscriptions": Object {
      "test(undefined)": Object {
        "QJSCV641RznGWyudGWuMb": Object {
          "pollingInterval": 0,
          "refetchOnFocus": undefined,
          "refetchOnReconnect": undefined,
        },
      },
    },
  },
  "test": Object {
    "data": Array [],
  },
}

Here is the test slice:

import { createSlice } from "@reduxjs/toolkit";

const testSlice = createSlice({
  name: "test",
  initialState: {
    data: [],
  },
  reducers: {
    getData: (state) => {
      state;
    },
  },
});

export const { getData } = testSlice.actions;
export default testSlice.reducer;

Here is the apiSlice:

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const apiSice = createApi({
  reducerPath: "test",
  baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_backend_url }),
  endpoints: (builder) => ({
    test: builder.query({
      query: () => "/test",
    }),
  }),
});

export const { useTestQuery } = apiSice;