问:
How to solve flutter_local_notifications PlatformException error?
I'm using flutter_local_notifications package in a project for the first time.

Followed the codes given in the documentation in pub.dev site. But the problem is when I press the button that should trigger the notification it is causing a PlatformException error.

The Error

```<code>E/flutter (15180): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null)
E/flutter (15180): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (15180): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:318:33)
E/flutter (15180): <asynchronous suspension>
E/flutter (15180): #2      FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications.dart:120:20)
E/flutter (15180): <asynchronous suspension>
E/flutter (15180): #3      _NewsfeedState.showNotification (package:news_app/screens/newsfeed_screen.dart:129:43)

</code>```

The codes are given below.

initState()

```<code>  @override
  void initState() {
   super.initState();

    var android = AndroidInitializationSettings('mipmap-hdpi/ic_launcher.png');
    var ios = IOSInitializationSettings();
    var initSettings = InitializationSettings(android, ios);
    flutterLocalNotificationsPlugin.initialize(initSettings, onSelectNotification: onSelectNotification);

}
</code>```

onSelectNotification() : It shows a Dialog box when the notification is pressed.

```<code>Future onSelectNotification(String payload) {
    showDialog(context: context, builder: (_) => AlertDialog(
      title: Text("Notfication"),
      content: Text("This is notification"),
    ));
  }

</code>```

Main widget : I was using this Press button to check if the notification works, as a test purpose.

```<code>
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        RaisedButton(
          onPressed: showNotification,
          child: Text(
              "Press"
          ),
        ),
      ],
    );
  }

</code>```

showNotification()

```<code>showNotification() async {
    var android = AndroidNotificationDetails(
        'channel id',
        'channel NAME',
        'CHANNEL DESCRIPTION',
        importance: Importance.Max,
        priority: Priority.High,
        ticker: 'ticker'
    );
    var ios = IOSNotificationDetails();
    var platform = NotificationDetails(android, ios);
    await flutterLocalNotificationsPlugin.show(0, "New Notification", "I'm notification",
    platform, payload: "It works");
  }

</code>```

There is a question that I found about this error, but the solution it provides was of no use for me.

I tried changing the version of the flutter_local_notifications package couple of times, did not work.

Then traced back the files that were shown in the error to see what exactly is causing null value.

In the file platform_channel.dart, inside the invokeMethod<T>(String method, [dynamic arguments]) I tried to print the method and arguments to see what is coming out to be null. This method is called from flutter_local_notifications.dart.

invokeMethod(String method, [ dynamic arguments ])

```<code> @optionalTypeArgs
  Future<T> invokeMethod<T>(String method, [ dynamic arguments ]) async {
    assert(method != null);
    final ByteData result = await binaryMessenger.send(
      name,
      codec.encodeMethodCall(MethodCall(method, arguments)),
    );

    print(arguments);
    print(method);

    if(result == null) {
      throw MissingPluginException('No implementation found for method $method on channel
      $name');
    }
    final T typedResult = codec.decodeEnvelope(result);
    return typedResult;
  }

</code>```

The output of arguments is,

I/flutter (15180): {id: 0, title: New News!, body: I'm news., platformSpecifics: {icon: null, channelId: channel id, channelName: channel NAME, channelDescription: CHANNEL DESCRIPTION, channelShowBadge: true, channelAction: 0, importance: 5, priority: 1, playSound: true, sound: null, enableVibration: true, vibrationPattern: null, style: 0, styleInformation: {htmlFormatContent: false, htmlFormatTitle: false}, groupKey: null, setAsGroupSummary: null, groupAlertBehavior: 0, autoCancel: true, ongoing: null, colorAlpha: null, colorRed: null, colorGreen: null, colorBlue: null, largeIcon: null, largeIconBitmapSource: null, onlyAlertOnce: null, showProgress: false, maxProgress: 0, progress: 0, indeterminate: false, enableLights: false, ledColorAlpha: null, ledColorRed: null, ledColorGreen: null, ledColorBlue: null, ledOnMs: null, ledOffMs: null, ticker: ticker}, payload: I'm the one}

You can see the title, body, channel id, channel NAME these are all the ones I gave but there are many other fields which are null. I'm guessing these to cause the error, but not certain.

As I followed the documentation, I did not see any instruction for such fields.

Some clue would mean great help. Thanks a lot for your time.

答:
From plugin's readme:

app_icon needs to be a added as a drawable resource to the Android head project

So put your app_icon into drawable folder instead of mipmap, and change your code to:

```<code>var android = AndroidInitializationSettings('app_icon');
</code>```

Body:
I'm using flutter_local_notifications package in a project for the first time.

Followed the codes given in the documentation in pub.dev site. But the problem is when I press the button that should trigger the notification it is causing a PlatformException error.

The Error

E/flutter (15180): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null)
E/flutter (15180): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (15180): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:318:33)
E/flutter (15180): <asynchronous suspension>
E/flutter (15180): #2      FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications.dart:120:20)
E/flutter (15180): <asynchronous suspension>
E/flutter (15180): #3      _NewsfeedState.showNotification (package:news_app/screens/newsfeed_screen.dart:129:43)

The codes are given below.

initState()

  @override
  void initState() {
   super.initState();

    var android = AndroidInitializationSettings('mipmap-hdpi/ic_launcher.png');
    var ios = IOSInitializationSettings();
    var initSettings = InitializationSettings(android, ios);
    flutterLocalNotificationsPlugin.initialize(initSettings, onSelectNotification: onSelectNotification);

}

onSelectNotification() : It shows a Dialog box when the notification is pressed.

Future onSelectNotification(String payload) {
    showDialog(context: context, builder: (_) => AlertDialog(
      title: Text("Notfication"),
      content: Text("This is notification"),
    ));
  }

Main widget : I was using this Press button to check if the notification works, as a test purpose.

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        RaisedButton(
          onPressed: showNotification,
          child: Text(
              "Press"
          ),
        ),
      ],
    );
  }

showNotification()

showNotification() async {
    var android = AndroidNotificationDetails(
        'channel id',
        'channel NAME',
        'CHANNEL DESCRIPTION',
        importance: Importance.Max,
        priority: Priority.High,
        ticker: 'ticker'
    );
    var ios = IOSNotificationDetails();
    var platform = NotificationDetails(android, ios);
    await flutterLocalNotificationsPlugin.show(0, "New Notification", "I'm notification",
    platform, payload: "It works");
  }

There is a question that I found about this error, but the solution it provides was of no use for me.

I tried changing the version of the flutter_local_notifications package couple of times, did not work.

Then traced back the files that were shown in the error to see what exactly is causing null value.

In the file platform_channel.dart, inside the invokeMethod<T>(String method, [dynamic arguments]) I tried to print the method and arguments to see what is coming out to be null. This method is called from flutter_local_notifications.dart.

invokeMethod(String method, [ dynamic arguments ])

 @optionalTypeArgs
  Future<T> invokeMethod<T>(String method, [ dynamic arguments ]) async {
    assert(method != null);
    final ByteData result = await binaryMessenger.send(
      name,
      codec.encodeMethodCall(MethodCall(method, arguments)),
    );

    print(arguments);
    print(method);

    if(result == null) {
      throw MissingPluginException('No implementation found for method $method on channel
      $name');
    }
    final T typedResult = codec.decodeEnvelope(result);
    return typedResult;
  }

The output of arguments is,

I/flutter (15180): {id: 0, title: New News!, body: I'm news., platformSpecifics: {icon: null, channelId: channel id, channelName: channel NAME, channelDescription: CHANNEL DESCRIPTION, channelShowBadge: true, channelAction: 0, importance: 5, priority: 1, playSound: true, sound: null, enableVibration: true, vibrationPattern: null, style: 0, styleInformation: {htmlFormatContent: false, htmlFormatTitle: false}, groupKey: null, setAsGroupSummary: null, groupAlertBehavior: 0, autoCancel: true, ongoing: null, colorAlpha: null, colorRed: null, colorGreen: null, colorBlue: null, largeIcon: null, largeIconBitmapSource: null, onlyAlertOnce: null, showProgress: false, maxProgress: 0, progress: 0, indeterminate: false, enableLights: false, ledColorAlpha: null, ledColorRed: null, ledColorGreen: null, ledColorBlue: null, ledOnMs: null, ledOffMs: null, ticker: ticker}, payload: I'm the one}

You can see the title, body, channel id, channel NAME these are all the ones I gave but there are many other fields which are null. I'm guessing these to cause the error, but not certain.

As I followed the documentation, I did not see any instruction for such fields.

Some clue would mean great help. Thanks a lot for your time.

Body:
From plugin's readme:

app_icon needs to be a added as a drawable resource to the Android head project

So put your app_icon into drawable folder instead of mipmap, and change your code to:

var android = AndroidInitializationSettings('app_icon');


来源: stackexchange

问:
Why input event for value EU citizen does not work
[Input not working ][1]

I added an event with the goal of listening to an event when the value of the input is EU citizen so I added it on the button with id 'submit'
The function does work but when I write EU citizen in the input the message 'You are eligible should show' but nothing happens.

```<code>//1. Listen for submit buttton for Nationality
document.getElementById('submit').addEventListener('click', function(e) {

    e.preventDefault();

})

//UI vars for Nationality

const nationality = document.getElementById('submit')

//show message you are eligible if it evaluates to EU citizen

function checkNationality(input) {
if(input === 'EU citizen') {

    console.log('You are eligible')

} else {

  console.log('You are not eligible')

}
}

</code>```

What am I missing? help, please

答:
Since you have not posted the full code. Thinking about what you are trying to achieve , please see the code below:</p>

```<code><input type="text" id="data"/>
<button id="submit" value="Submit" onclick="getData();">Submit</button>

function getData(){
    var inputVal = document.getElementById("data").value;
  //console.log(inputVal);
  if(inputVal === "EU citizen"){
    console.log("You are eligible");
  } else {
    console.log("You are not eligible");
  }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
[Input not working ][1]

I added an event with the goal of listening to an event when the value of the input is EU citizen so I added it on the button with id 'submit'
The function does work but when I write EU citizen in the input the message 'You are eligible should show' but nothing happens.

//1. Listen for submit buttton for Nationality
document.getElementById('submit').addEventListener('click', function(e) {

    e.preventDefault();

})

//UI vars for Nationality

const nationality = document.getElementById('submit')

//show message you are eligible if it evaluates to EU citizen

function checkNationality(input) {
if(input === 'EU citizen') {

    console.log('You are eligible')

} else {

  console.log('You are not eligible')

}
}

What am I missing? help, please

Body:
Since you have not posted the full code. Thinking about what you are trying to achieve , please see the code below:

<input type="text" id="data"/>
<button id="submit" value="Submit" onclick="getData();">Submit</button>

function getData(){
    var inputVal = document.getElementById("data").value;
  //console.log(inputVal);
  if(inputVal === "EU citizen"){
    console.log("You are eligible");
  } else {
    console.log("You are not eligible");
  }

}


问:
ValueError: could not convert string to float: balance = float(clean)
I'm using Python3 in a bot on Telegram, but I'm encountering an error when trying to execute some commands.
The bot is a cryptocurrency wallet, and this bot is connected to a wallet that is running on the same server where the bot is hosted.
The connection is made via RPC commands.
Error follows:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/telegram/ext/dispatcher.py", line 343, in process_update
    handler.handle_update(update, self, check, context)
  File "/usr/local/lib/python3.5/dist-packages/telegram/ext/handler.py", line 122, in handle_update
    return self.callback(dispatcher.bot, update, **optional_args)
  File "command.py", line 86, in funds
    balance  = float(clean)
ValueError: could not convert string to float:
```

<p><img src="https://i.stack.imgur.com/uBLOt.png" alt="enter image description here"></p>

<p>This would be my code:</p>

```#-*- coding: utf-8 -*-

import json
import codecs
import requests
from bs4 import BeautifulSoup, SoupStrainer
import re
import subprocess
from telegram.ext.dispatcher import run_async
from telegram.ext import Updater
from html import escape

updater = Updater(token='TOKEN_TELEGRAM')
dispatcher = updater.dispatcher

import logging
logging.basicConfig(filename='log.log',
                    filemode='w',
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.DEBUG)

def commands(bot, update):
    user = update.message.from_user.username
    bot.send_message(chat_id=update.message.chat_id, text=" List of commands: \n "+
        " /hello \n /commands \n /recharge \n /pay \n /drawout \n /funds \n /price \n /help")

def help(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text=" /pay & /drawout have a specfic format use them like so:"+
        "\n Parameters: \n <user> = target user to pay \n <amount> = amount of SperoCoin to utilise \n <address> = SperoCoin address to withdraw to \n \n Tipping format: \n /pay <user> <amount> \n \n Withdrawing format: \n /drawout <address> <amount>")

def recharge(bot, update):
    user = update.message.from_user.username
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        address = "/usr/local/bin/SperoCoind"
        extra1 = "-datadir=/coin/data"
        extra2 = "-conf=/coin/sperocoin.conf"
        result = subprocess.run([address,extra1,extra2,"getaccountaddress",user],stdout=subprocess.PIPE)
        clean = (result.stdout.strip()).decode("utf-8")
        bot.send_message(chat_id=update.message.chat_id, text="@{0} your depositing address is: {1}".format(user,clean))

def pay(bot,update):
    user = update.message.from_user.username
    target = update.message.text[5:]
    amount =  target.split(" ")[1]
    target =  target.split(" ")[0]
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        machine = "@SperoCoinWalletBot"
        if target == machine:
            bot.send_message(chat_id=update.message.chat_id, text="HODL.")
        elif "@" in target:
            target = target[1:]
            user = update.message.from_user.username
            core = "/usr/local/bin/SperoCoind"
            extra1 = "-datadir=/coin/data"
            extra2 = "-conf=/coin/sperocoin.conf"
            result = subprocess.run([core,extra1,extra2,"getbalance",user],stdout=subprocess.PIPE)
            balance = float((result.stdout.strip()).decode("utf-8"))
            amount = float(amount)
            if balance < amount:
                bot.send_message(chat_id=update.message.chat_id, text="@{0} you have insufficent funds.".format(user))
            elif target == user:
                bot.send_message(chat_id=update.message.chat_id, text="You can't pay yourself!")
            else:
                balance = str(balance)
                amount = str(amount)
                tx = subprocess.run([core,extra1,extra2,"move",user,target,amount],stdout=subprocess.PIPE)
                bot.send_message(chat_id=update.message.chat_id, text="@{0} paid @{1} of {2} SPERO".format(user, target, amount))
        else:
            bot.send_message(chat_id=update.message.chat_id, text="Error that user is not applicable.")

def funds(bot,update):
    user = update.message.from_user.username
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        core = "/usr/local/bin/SperoCoind"
        extra1 = "-datadir=/coin/data"
        extra2 = "-conf=/coin/sperocoin.conf"
        result = subprocess.run([core,extra1,extra2,"getbalance",user],stdout=subprocess.PIPE)
        clean = (result.stdout.strip()).decode("utf-8")
        balance  = float(clean)
        balance =  str(round(balance,3))
        bot.send_message(chat_id=update.message.chat_id, text="@{0} your current balance is: {1} SPERO ".format(user,balance))

def drawout(bot,update):
    user = update.message.from_user.username
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        target = update.message.text[9:]
        address = target[:35]
        address = ''.join(str(e) for e in address)
        target = target.replace(target[:35], '')
        amount = float(target)
        core = "/usr/local/bin/SperoCoind"
        extra1 = "-datadir=/coin/data"
        extra2 = "-conf=/coin/sperocoin.conf"
        result = subprocess.run([core,extra1,extra2,"getbalance",user],stdout=subprocess.PIPE)
        clean = (result.stdout.strip()).decode("utf-8")
        balance = float(clean)
        if balance < amount:
            bot.send_message(chat_id=update.message.chat_id, text="@{0} you have insufficent funds.".format(user))
        else:
            amount = str(amount)
            tx = subprocess.run([core,extra1,extra2,"sendfrom",user,address,amount],stdout=subprocess.PIPE)
            cleantxid = (tx.stdout.strip()).decode("utf-8")
            txid = str(cleantxid)
            bot.send_message(chat_id=update.message.chat_id, text="@{0} has successfully withdrew to address: {1} of {2} SPERO\n\n TXID: https://explorer.sperocoin.org/tx/{3}" .format(user,address,amount,txid))

def hello(bot,update):
    user = update.message.from_user.username
    bot.send_message(chat_id=update.message.chat_id, text="Hello @{0}, how about buying some SPERO at SPERO EXCHANGE?\n https://exchange.sperocoin.org".format(user))

def rain(bot,update):
  bot.send_message(chat_id=update.message.chat_id, text="Stake for a rainy day!")

def price(bot,update):
    speroCapJson = requests.get('https://api.coingecko.com/api/v3/coins/sperocoin').json()
    mk_cap = speroCapJson ['market_data']['market_cap']['brl']
    pricebrl = speroCapJson ['market_data']['current_price']['brl']
    priceusd = speroCapJson ['market_data']['current_price']['usd']
    pricebtc = speroCapJson ['market_data']['current_price']['btc']
    priceeth = speroCapJson ['market_data']['current_price']['eth']
    update.message.reply_text(" Price: \n Cotação/Price: Coingecko \n SPERO Market Cap: R$:{:.2f}".format(mk_cap)+
"\n Price(BRL):  R${:.3f}".format(pricebrl) + "\n Price(USD):  ${:.3f}".format(priceusd) + "\n Price(BTC):  {:.8f}".format(pricebtc) + "\n Price(ETH):  {:.8f}".format(priceeth))

from telegram.ext import CommandHandler

commands_handler = CommandHandler('commands', commands)
dispatcher.add_handler(commands_handler)

rain_handler = CommandHandler('rain', rain)
dispatcher.add_handler(rain_handler)

hi_handler = CommandHandler('hello', hello)
dispatcher.add_handler(hi_handler)

withdraw_handler = CommandHandler('drawout', drawout)
dispatcher.add_handler(withdraw_handler)

deposit_handler = CommandHandler('recharge', recharge)
dispatcher.add_handler(deposit_handler)

tip_handler = CommandHandler('pay', pay)
dispatcher.add_handler(tip_handler)

balance_handler = CommandHandler('funds', funds)
dispatcher.add_handler(balance_handler)

help_handler = CommandHandler('help', help)
dispatcher.add_handler(help_handler)

price_handler = CommandHandler('price', price)
dispatcher.add_handler(price_handler)

updater.start_polling()
```

<p>For the execution of the code, I ran it on a docker:</p>

```RUN apt update && apt install python3 python3-pip -y
RUN pip3 install beautifulsoup4 \
  && pip3 install requests \
  && pip3 install python-telegram-bot --upgrade
```

答:
This error usually prints what value was not converted:

```<code>>>> float('blah')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: blah
>>>
</code>```

You have conveniently missed that from your question. Please, take a look at the error message and try to include it completely, or, better yet, figure out yourself, why that value was not successfully converted to float.

My suspicion is that the value of clean is '' -- empty string. Which does not look as a float.

Body:
I'm using Python3 in a bot on Telegram, but I'm encountering an error when trying to execute some commands.
The bot is a cryptocurrency wallet, and this bot is connected to a wallet that is running on the same server where the bot is hosted.
The connection is made via RPC commands.
Error follows:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/telegram/ext/dispatcher.py", line 343, in process_update
    handler.handle_update(update, self, check, context)
  File "/usr/local/lib/python3.5/dist-packages/telegram/ext/handler.py", line 122, in handle_update
    return self.callback(dispatcher.bot, update, **optional_args)
  File "command.py", line 86, in funds
    balance  = float(clean)
ValueError: could not convert string to float:

This would be my code:

#-*- coding: utf-8 -*-

import json
import codecs
import requests
from bs4 import BeautifulSoup, SoupStrainer
import re
import subprocess
from telegram.ext.dispatcher import run_async
from telegram.ext import Updater
from html import escape

updater = Updater(token='TOKEN_TELEGRAM')
dispatcher = updater.dispatcher

import logging
logging.basicConfig(filename='log.log',
                    filemode='w',
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.DEBUG)

def commands(bot, update):
    user = update.message.from_user.username
    bot.send_message(chat_id=update.message.chat_id, text=" List of commands: \n "+
        " /hello \n /commands \n /recharge \n /pay \n /drawout \n /funds \n /price \n /help")

def help(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text=" /pay & /drawout have a specfic format use them like so:"+
        "\n Parameters: \n <user> = target user to pay \n <amount> = amount of SperoCoin to utilise \n <address> = SperoCoin address to withdraw to \n \n Tipping format: \n /pay <user> <amount> \n \n Withdrawing format: \n /drawout <address> <amount>")

def recharge(bot, update):
    user = update.message.from_user.username
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        address = "/usr/local/bin/SperoCoind"
        extra1 = "-datadir=/coin/data"
        extra2 = "-conf=/coin/sperocoin.conf"
        result = subprocess.run([address,extra1,extra2,"getaccountaddress",user],stdout=subprocess.PIPE)
        clean = (result.stdout.strip()).decode("utf-8")
        bot.send_message(chat_id=update.message.chat_id, text="@{0} your depositing address is: {1}".format(user,clean))

def pay(bot,update):
    user = update.message.from_user.username
    target = update.message.text[5:]
    amount =  target.split(" ")[1]
    target =  target.split(" ")[0]
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        machine = "@SperoCoinWalletBot"
        if target == machine:
            bot.send_message(chat_id=update.message.chat_id, text="HODL.")
        elif "@" in target:
            target = target[1:]
            user = update.message.from_user.username
            core = "/usr/local/bin/SperoCoind"
            extra1 = "-datadir=/coin/data"
            extra2 = "-conf=/coin/sperocoin.conf"
            result = subprocess.run([core,extra1,extra2,"getbalance",user],stdout=subprocess.PIPE)
            balance = float((result.stdout.strip()).decode("utf-8"))
            amount = float(amount)
            if balance < amount:
                bot.send_message(chat_id=update.message.chat_id, text="@{0} you have insufficent funds.".format(user))
            elif target == user:
                bot.send_message(chat_id=update.message.chat_id, text="You can't pay yourself!")
            else:
                balance = str(balance)
                amount = str(amount)
                tx = subprocess.run([core,extra1,extra2,"move",user,target,amount],stdout=subprocess.PIPE)
                bot.send_message(chat_id=update.message.chat_id, text="@{0} paid @{1} of {2} SPERO".format(user, target, amount))
        else:
            bot.send_message(chat_id=update.message.chat_id, text="Error that user is not applicable.")

def funds(bot,update):
    user = update.message.from_user.username
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        core = "/usr/local/bin/SperoCoind"
        extra1 = "-datadir=/coin/data"
        extra2 = "-conf=/coin/sperocoin.conf"
        result = subprocess.run([core,extra1,extra2,"getbalance",user],stdout=subprocess.PIPE)
        clean = (result.stdout.strip()).decode("utf-8")
        balance  = float(clean)
        balance =  str(round(balance,3))
        bot.send_message(chat_id=update.message.chat_id, text="@{0} your current balance is: {1} SPERO ".format(user,balance))

def drawout(bot,update):
    user = update.message.from_user.username
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        target = update.message.text[9:]
        address = target[:35]
        address = ''.join(str(e) for e in address)
        target = target.replace(target[:35], '')
        amount = float(target)
        core = "/usr/local/bin/SperoCoind"
        extra1 = "-datadir=/coin/data"
        extra2 = "-conf=/coin/sperocoin.conf"
        result = subprocess.run([core,extra1,extra2,"getbalance",user],stdout=subprocess.PIPE)
        clean = (result.stdout.strip()).decode("utf-8")
        balance = float(clean)
        if balance < amount:
            bot.send_message(chat_id=update.message.chat_id, text="@{0} you have insufficent funds.".format(user))
        else:
            amount = str(amount)
            tx = subprocess.run([core,extra1,extra2,"sendfrom",user,address,amount],stdout=subprocess.PIPE)
            cleantxid = (tx.stdout.strip()).decode("utf-8")
            txid = str(cleantxid)
            bot.send_message(chat_id=update.message.chat_id, text="@{0} has successfully withdrew to address: {1} of {2} SPERO\n\n TXID: https://explorer.sperocoin.org/tx/{3}" .format(user,address,amount,txid))

def hello(bot,update):
    user = update.message.from_user.username
    bot.send_message(chat_id=update.message.chat_id, text="Hello @{0}, how about buying some SPERO at SPERO EXCHANGE?\n https://exchange.sperocoin.org".format(user))

def rain(bot,update):
  bot.send_message(chat_id=update.message.chat_id, text="Stake for a rainy day!")

def price(bot,update):
    speroCapJson = requests.get('https://api.coingecko.com/api/v3/coins/sperocoin').json()
    mk_cap = speroCapJson ['market_data']['market_cap']['brl']
    pricebrl = speroCapJson ['market_data']['current_price']['brl']
    priceusd = speroCapJson ['market_data']['current_price']['usd']
    pricebtc = speroCapJson ['market_data']['current_price']['btc']
    priceeth = speroCapJson ['market_data']['current_price']['eth']
    update.message.reply_text(" Price: \n Cotação/Price: Coingecko \n SPERO Market Cap: R$:{:.2f}".format(mk_cap)+
"\n Price(BRL):  R${:.3f}".format(pricebrl) + "\n Price(USD):  ${:.3f}".format(priceusd) + "\n Price(BTC):  {:.8f}".format(pricebtc) + "\n Price(ETH):  {:.8f}".format(priceeth))

from telegram.ext import CommandHandler

commands_handler = CommandHandler('commands', commands)
dispatcher.add_handler(commands_handler)

rain_handler = CommandHandler('rain', rain)
dispatcher.add_handler(rain_handler)

hi_handler = CommandHandler('hello', hello)
dispatcher.add_handler(hi_handler)

withdraw_handler = CommandHandler('drawout', drawout)
dispatcher.add_handler(withdraw_handler)

deposit_handler = CommandHandler('recharge', recharge)
dispatcher.add_handler(deposit_handler)

tip_handler = CommandHandler('pay', pay)
dispatcher.add_handler(tip_handler)

balance_handler = CommandHandler('funds', funds)
dispatcher.add_handler(balance_handler)

help_handler = CommandHandler('help', help)
dispatcher.add_handler(help_handler)

price_handler = CommandHandler('price', price)
dispatcher.add_handler(price_handler)

updater.start_polling()

For the execution of the code, I ran it on a docker:

RUN apt update && apt install python3 python3-pip -y
RUN pip3 install beautifulsoup4 \
  && pip3 install requests \
  && pip3 install python-telegram-bot --upgrade

Body:
This error usually prints what value was not converted:

>>> float('blah')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: blah
>>>

You have conveniently missed that from your question. Please, take a look at the error message and try to include it completely, or, better yet, figure out yourself, why that value was not successfully converted to float.

My suspicion is that the value of clean is '' -- empty string. Which does not look as a float.


问:
how to pass style in div using typescript in react
this is my code i just want to make a custom component in react with typescript like if i want to pass height, width, border Radius and style as extra parameter like if i want more css property then pass style={{display:flex}} but i can't add this with typescript i successfully write in js it works but not familiar with typescript

my interface

```<code>interface BoxProps {
    heights: React.CSSProperties;
    styles?: React.CSSProperties;
    className?: String;
    borderRadius?: React.CSSProperties
    children?: React.ReactElement<any>
}

const Box = ({ id, heights, styles, className, children }: BoxProps) => {
    const Nstyle = { ...styles,height: { heights } }
    return (
        <div
            {...id}
            style={Nstyle}
            className={CN} >
            {children}
        </div >
    );
}
</code>```

please help style shows this error with typescript
The expected type comes from property 'style' which is declared here on type'DetailedHTMLProps, HTMLDivElement>'`

答:
The prop heights needs to be string | number.  The className prop used a capital S for String instead of string.  className={CN} should be className={className} because the variable CN does not exist.

```<code>interface BoxProps {
  heights: string | number;
  styles?: React.CSSProperties;
  className?: string;
  borderRadius?: React.CSSProperties
  children?: React.ReactElement<any>
}

const Box = ({ heights, styles, className, children }: BoxProps) => {
  const Nstyle: React.CSSProperties = { ...styles, height: heights }
  return (
      <div
        style={Nstyle}
        className={className}
      >
          {children}
      </div >
  );
}

</code>```

Body:
this is my code i just want to make a custom component in react with typescript like if i want to pass height, width, border Radius and style as extra parameter like if i want more css property then pass style={{display:flex}} but i can't add this with typescript i successfully write in js it works but not familiar with typescript

my interface

interface BoxProps {
    heights: React.CSSProperties;
    styles?: React.CSSProperties;
    className?: String;
    borderRadius?: React.CSSProperties
    children?: React.ReactElement<any>
}

const Box = ({ id, heights, styles, className, children }: BoxProps) => {
    const Nstyle = { ...styles,height: { heights } }
    return (

            {children}

    );
}

please help style shows this error with typescript
The expected type comes from property 'style' which is declared here on type'DetailedHTMLProps, HTMLDivElement>'`

Body:
The prop heights needs to be string | number.  The className prop used a capital S for String instead of string.  className={CN} should be className={className} because the variable CN does not exist.

interface BoxProps {
  heights: string | number;
  styles?: React.CSSProperties;
  className?: string;
  borderRadius?: React.CSSProperties
  children?: React.ReactElement<any>
}

const Box = ({ heights, styles, className, children }: BoxProps) => {
  const Nstyle: React.CSSProperties = { ...styles, height: heights }
  return (
      <div
        style={Nstyle}
        className={className}
      >
          {children}
      </div >
  );
}


问:
iOS: Sound generation on iPad given Hz parameter?
Is there an API in one of the iOS layers that I can use to generate a tone by just specifying its Hertz. What I´m looking to do is generate a DTMF tone. This link explains how DTMF tones consists of 2 tones:

http://en.wikipedia.org/wiki/Telephone_keypad

Which basically means that I should need playback of 2 tones at the same time...

So, does something like this exist:

SomeCleverPlayerAPI(697, 1336);

If spent the whole morning searching for this, and have found a number of ways to playback a sound file, but nothing on how to generate a specific tone. Does anyone know, please...

答:
Check out the AU (AudioUnit) API. It's pretty low-level, but it can do what you want. A good intro (that probably already gives you what you need) can be found here:

http://cocoawithlove.com/2010/10/ios-tone-generator-introduction-to.html

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Django admin page not showing user models
My admin page is working fine except when logged in it is not showing any user models. It is hindering my work as I cannot manage users.
I have made custom models as shown below.
Database is MySQL.

models.py

```<code>class User(AbstractUser):
    is_customer = models.BooleanField(default=False)
    is_restaurant = models.BooleanField(default=False)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    food_pref = models.CharField(max_length=10, default='veg')

class Restaurant(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    restaurant_name = models.CharField(max_length=100, blank=False)
</code>```

答:
Have You registered them in admin.py?</p>

```<code>from .models import ModelName

admin.site.register(ModelName)
</code>```

Body:
My admin page is working fine except when logged in it is not showing any user models. It is hindering my work as I cannot manage users.
I have made custom models as shown below.
Database is MySQL.

models.py

class User(AbstractUser):
    is_customer = models.BooleanField(default=False)
    is_restaurant = models.BooleanField(default=False)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    food_pref = models.CharField(max_length=10, default='veg')

class Restaurant(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    restaurant_name = models.CharField(max_length=100, blank=False)

Body:
Have You registered them in admin.py?

from .models import ModelName

admin.site.register(ModelName)


问:
on IOS grid-template-rows does nor work correctly with "1fr"
I am facing a strange problem on IOS (chrome, safari):

```<code>.pageContainer {
    width: 100%;
    grid-template-rows: 100px 1fr 100px;
    display: grid;
    height: 100%;
    position: fixed;
    grid-template-areas:
            "header"
            "main"
            "footer"
}
</code>```

It works fine on PC (chrome, android), on Android, On MacOS (Including Safari) BUT on IOS,
grid-template-rows: 100px 1fr 100px just create trouble:
Looks like IOS is unable to handle correctly 1fr and takes the WHOLE screen and not the available space.

On IOS, I must use a fixed value that gives the correct value
like 100px 500px 100px

```<code>header {
    grid-area: header;
    display: flex;
    justify-items: center;
    align-items: center;
    position: static;
}

article {
    grid-area: main;
    height: 100%;
    overflow: auto;
}

footer {
    display: flex;
    grid-area: footer;
    align-items: center;
    width: 100%;
    max-width: 100vw;
    overflow-x: auto;
    overflow-y: hidden;
    position: static;
}
</code>```

My layout has a static header and footer and the article can be scrolled.

答:
Just solved that with minmax

```<code>grid-template-rows: 100px minmax(200px,1fr) 100px;
</code>```

Body:
I am facing a strange problem on IOS (chrome, safari):

.pageContainer {
    width: 100%;
    grid-template-rows: 100px 1fr 100px;
    display: grid;
    height: 100%;
    position: fixed;
    grid-template-areas:
            "header"
            "main"
            "footer"
}

It works fine on PC (chrome, android), on Android, On MacOS (Including Safari) BUT on IOS,
grid-template-rows: 100px 1fr 100px just create trouble:
Looks like IOS is unable to handle correctly 1fr and takes the WHOLE screen and not the available space.

On IOS, I must use a fixed value that gives the correct value
like 100px 500px 100px

header {
    grid-area: header;
    display: flex;
    justify-items: center;
    align-items: center;
    position: static;
}

article {
    grid-area: main;
    height: 100%;
    overflow: auto;
}

footer {
    display: flex;
    grid-area: footer;
    align-items: center;
    width: 100%;
    max-width: 100vw;
    overflow-x: auto;
    overflow-y: hidden;
    position: static;
}

My layout has a static header and footer and the article can be scrolled.

Body:
Just solved that with minmax

grid-template-rows: 100px minmax(200px,1fr) 100px;


问:
How can I get my linkedIn sharing url to work
I am sharing my page "www.mysite.com/detail/?v=2442411"  to linkedIn but I just get a "Oops" on linkedIn.

In code I have it like this:

```<code>string LinkedIn = $"https://www.linkedin.com/shareArticle?mini=true&url={mysiteurlvariable}?v={myidvariable}&title=ThisTitle"
</code>```

It spits out this link:
https://www.linkedin.com/shareArticle/?mini=true&url=www.mysite.com/detail/?v=2442411&title=ThisTitle

When following the link as I say I just get a oops from LinkedIn.
Although when replacing the url with any other url also without a parameter its fine.

It seems like it does not like the ?v={myidvatiable} part

Anyone know of this issue or why this is an issue

答:
You need to do URL-encoding with parameters you are feeding to another URL.  And also, since you have posted your question, the LinkedIn Share URL parameters have changed.  Source: Official Microsoft LinkedIn Share URL Documentation.

So, this is what you should want...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={mysiteurlvariable}%3Fv%3D%7Bmyidvariable%7D%26title%3DThisTitle%22
</code>```

Hope this helps!

Body:
I am sharing my page "www.mysite.com/detail/?v=2442411"  to linkedIn but I just get a "Oops" on linkedIn.

In code I have it like this:

string LinkedIn = $"https://www.linkedin.com/shareArticle?mini=true&url={mysiteurlvariable}?v={myidvariable}&title=ThisTitle"

It spits out this link:
https://www.linkedin.com/shareArticle/?mini=true&url=www.mysite.com/detail/?v=2442411&title=ThisTitle

When following the link as I say I just get a oops from LinkedIn.
Although when replacing the url with any other url also without a parameter its fine.

It seems like it does not like the ?v={myidvatiable} part

Anyone know of this issue or why this is an issue

Body:
You need to do URL-encoding with parameters you are feeding to another URL.  And also, since you have posted your question, the LinkedIn Share URL parameters have changed.  Source: Official Microsoft LinkedIn Share URL Documentation.

So, this is what you should want...

https://www.linkedin.com/sharing/share-offsite/?url={mysiteurlvariable}%3Fv%3D%7Bmyidvariable%7D%26title%3DThisTitle%22

Hope this helps!


问:
How can I set an object to a constant and display the value in react?
This is the app component :

```<code>function App() {
    const [ url, setUrl ] = useState({});
    const fetch = () => {
        axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
            console.log(res);
            setUrl(res.config.url);
        });
    };

    return (
        <div className="App">
            <button onClick={() => fetch()}>Click</button>
            {url.length ? url : null}
        </div>
    );
}
</code>```

This actually works and it displays the url string which is https://jsonplaceholder.typicode.com/posts when I click the button
on the page but What I really want to do is to set the res whole object to the url constant and then display the config.url like this :

```<code>const fetch = () => {
        axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
            setUrl(res);
        });
    };

</code>```

and then :

```<code><button onClick={() => fetch()}>Click</button>
            {url.length ? url.config.url : null}
</code>```

but it doesn't work and it also does not throw an error .

How can I set the whole res object to url constant and then display url.config.url when I click the button ?

答:
You should check length from url.config.url, in url length now is miossing</p>

```<code>{url.config.url.length ? url.config.url : null}
</code>```

Body:
This is the app component :

function App() {
    const [ url, setUrl ] = useState({});
    const fetch = () => {
        axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
            console.log(res);
            setUrl(res.config.url);
        });
    };

    return (

            <button onClick={() => fetch()}>Click</button>
            {url.length ? url : null}

    );
}

This actually works and it displays the url string which is https://jsonplaceholder.typicode.com/posts when I click the button
on the page but What I really want to do is to set the res whole object to the url constant and then display the config.url like this :

const fetch = () => {
        axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
            setUrl(res);
        });
    };

and then :

<button onClick={() => fetch()}>Click</button>
            {url.length ? url.config.url : null}

but it doesn't work and it also does not throw an error .

How can I set the whole res object to url constant and then display url.config.url when I click the button ?

Body:
You should check length from url.config.url, in url length now is miossing

{url.config.url.length ? url.config.url : null}


问:
VideoPlayerPlugin.java uses or overrides a deprecated API
i already used latest version of video_player flutter (video_player: ^0.10.5+1)
but show below warning.

Note: Some input files use or override a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

Note: /Users/pc/Documents/AshishAlagiya/Flutter/Tool/flutter112hotfix5/flutter/.pub-cache/git/plugins-e1e8a04bd104a6a772e6f0e72eaf8615f14c6541/packages/video_player/video_player/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerPlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

答:
I had the same problem and it solved after adding the permission in /android/app/src/main/AndroidManifest.xml :</p>

```<code><uses-permission android:name="android.permission.INTERNET"/>
</code>```

Body:
I had the same problem and it solved after adding the permission in /android/app/src/main/AndroidManifest.xml :

<uses-permission android:name="android.permission.INTERNET"/>


问:
Why cannot I get 2 gigabytes from malloc?
Having this:

```<code>#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define GB (1<<30)
#define N 10000L //number of virtual blocks(arrays)

int main (void) {

    int *ar[N];
    for(int i =0; i<N ; i++)
    {
        ar[i]=malloc(GB); //alloc virtually one GB
        if(!ar[i]){
            printf("done at %i\n",i);
            return 0;
        }
    }
    printf("allocated %li blocks\n",N);

    for(int i =0; i<N ; i++)
    {
        memset(ar[i],2,GB); // get physical gigs for that array
        printf("wrote to %i GB\n",i+1);
    }

    return 0;
}
</code>```

But I will not get even one:

```<code>allocated 10000 blocks //virtual memory (one block==1GB)
wrote to 1 GB //real memory (not really

Command terminated

Press ENTER or type command to continue
</code>```

I know I have at leaset 4 gigs on my machine and I also know OS has some limit it needs to operate, however I cannot get even 2 GB for user space? That is strange. Can someone explain please?

$uname -a:
`4.19.0-9-amd64 #1 SMP Debian 4.19.118-2 (2020-04-29) x86_64 GNU/Linux

EDIT:
It gets stranger:
Now if I run (after an hour from the previous output):

```<code>allocated 10000 blocks
wrote to 1 GB
wrote to 2 GB

Command terminated

Press ENTER or type command to continue
</code>```

so it gets through 2 time in for loop, and allocates 2GB of real memory, but before an hour, I catch only 1GB and something (not full 2GB).

addition info:
$free -h:

```<code>    total        used        free      shared  buff/cache   available
Mem:          3.7Gi       1.1Gi       2.2Gi       236Mi       404Mi       2.2Gi
Swap:            0B          0B          0B
</code>```

How can I take advantage from these information? So it is I said -> I have 4GB (total), but can get 2GB. That is maximum for user space?

答:
Note: This answer does not solve the problem OP was having because it's based on fake code originally in the question, and still present in the question after the first request to correct fake code was made and acted upon. It does explain the question as originally asked.

If the code you posted is accurate now, your problem is that you are attempting to call functions without valid declarations for them (I see no #include directives). This is invalid C and the compiler should warn (or ideally error out) if you do it. Always add -Werror=implicit-function-declaration to get it to do that.

The particular mechanism of your crash is likely this: memset takes a size_t (unsigned long) as its third argument, but without a prototype, the function is being called as if the type of the function matched the argument types you provided (subject to default promotions). This produces undefined behavior. 1<<30 has type int, not unsigned long, and on x86_64 ABI, int is passed in the low 32 bits of a 64-bit register, with arbitrary junk allowed in the upper bits. So rather than passing 1 GB to memset, you're passing some astronomically large number.

Body:
Having this:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define GB (1<<30)
#define N 10000L //number of virtual blocks(arrays)

int main (void) {

    int *ar[N];
    for(int i =0; i<N ; i++)
    {
        ar[i]=malloc(GB); //alloc virtually one GB
        if(!ar[i]){
            printf("done at %i\n",i);
            return 0;
        }
    }
    printf("allocated %li blocks\n",N);

    for(int i =0; i<N ; i++)
    {
        memset(ar[i],2,GB); // get physical gigs for that array
        printf("wrote to %i GB\n",i+1);
    }

    return 0;
}

But I will not get even one:

allocated 10000 blocks //virtual memory (one block==1GB)
wrote to 1 GB //real memory (not really

Command terminated

Press ENTER or type command to continue

I know I have at leaset 4 gigs on my machine and I also know OS has some limit it needs to operate, however I cannot get even 2 GB for user space? That is strange. Can someone explain please?

$uname -a:
`4.19.0-9-amd64 #1 SMP Debian 4.19.118-2 (2020-04-29) x86_64 GNU/Linux

EDIT:
It gets stranger:
Now if I run (after an hour from the previous output):

allocated 10000 blocks
wrote to 1 GB
wrote to 2 GB

Command terminated

Press ENTER or type command to continue

so it gets through 2 time in for loop, and allocates 2GB of real memory, but before an hour, I catch only 1GB and something (not full 2GB).

addition info:
$free -h:

    total        used        free      shared  buff/cache   available
Mem:          3.7Gi       1.1Gi       2.2Gi       236Mi       404Mi       2.2Gi
Swap:            0B          0B          0B

How can I take advantage from these information? So it is I said -> I have 4GB (total), but can get 2GB. That is maximum for user space?


问:
Pandas - Check if row contain specific string and return result in a new column
I have this dataset:

```<code>+-----------------------------------+------------+----------------------+
|               A                   |    B       |   C                  |
+-----------------------------------+------------+----------------------+
| Joseph M. Acaba                   | 2004       |Geology               |
| Loren W. Act                                    Solar Physics         |
| James C. Adamson                  | 1984       |Aerospace Egineerig   |
+-----------------------------------+------------+--------+
</code>```

i would like to check, for each row of column C, if there is the word “Engineering” or “Geology” in the respective phrase. I would like the result to be set in a new column (“D”), as in the example below:

```<code>+----------------------+------------+----------------------+---------+
|               A      |    B       |   C                  | D       |
+----------------------+------------+----------------------+---------+
| Joseph M. Acaba      | 2004       |Geology               |True
| Loren W. Act         |             Solar Physics         |False
| James C. Adamson     | 1984       |Aerospace Egineerig   |True
+-----------------------------------+------------+--------+
</code>```

I tried with :

```<code>check=pd['Undergraduate Major'].str.contains('Engineering'|”Geology”)
print(check)
</code>```

and got the result:

```<code>0      False
1       True
2       True
3      False
4       True
       ...
352     True
353    False
354    False
355     True
356    False
</code>```

But I want the result to become a new column, with only “false” and “true”.

答:
If your dataframe is named df, do:

df['NewColumnName'] = df['Undergraduate Major'].str.contains('Engineering|Geology')
```

I would recommend avoiding using pd as the name of the dataframe because it's generally used for pandas, as in import pandas as pd.

Body:
I have this dataset:

+-----------------------------------+------------+----------------------+
|               A                   |    B       |   C                  |
+-----------------------------------+------------+----------------------+
| Joseph M. Acaba                   | 2004       |Geology               |
| Loren W. Act                                    Solar Physics         |
| James C. Adamson                  | 1984       |Aerospace Egineerig   |
+-----------------------------------+------------+--------+

i would like to check, for each row of column C, if there is the word “Engineering” or “Geology” in the respective phrase. I would like the result to be set in a new column (“D”), as in the example below:

+----------------------+------------+----------------------+---------+
|               A      |    B       |   C                  | D       |
+----------------------+------------+----------------------+---------+
| Joseph M. Acaba      | 2004       |Geology               |True
| Loren W. Act         |             Solar Physics         |False
| James C. Adamson     | 1984       |Aerospace Egineerig   |True
+-----------------------------------+------------+--------+

I tried with :

check=pd['Undergraduate Major'].str.contains('Engineering'|”Geology”)
print(check)

and got the result:

0      False
1       True
2       True
3      False
4       True
       ...
352     True
353    False
354    False
355     True
356    False

But I want the result to become a new column, with only “false” and “true”.

Body:
If your dataframe is named df, do:

df['NewColumnName'] = df['Undergraduate Major'].str.contains('Engineering|Geology')

I would recommend avoiding using pd as the name of the dataframe because it's generally used for pandas, as in import pandas as pd.


问:
Passing ViewModel to Web-Api action
Is it possible to pass an ViewModel object to WebApi controller action instead of separate params?

Instead of using:

```<code>public class ContactsController : ApiController
{
    public IEnumerable<Contact> GetContacts(string p1, string p2)
    {
        // some logic
    }
}
</code>```

I would like to use:

```<code>public class ContactsController : ApiController
{
    public IEnumerable<Contact> GetContacts(TestVM testVM)
    {
        // some logic
    }
}

public class TestVM
{
    public string P1 { get; set; }
    public string P2 { get; set; }
}
</code>```

This doesn't seem to work for me. When I call /api/contacts/?P1=aaa&P2=bbb the testVM object doesn't get populated (null).

Also, I would like the TestVM to have valdiation attribtues defined and use ModelState.IsValid in my API controller.

答:
I know it's kind of late to post another answer but I thought it could be useful for anyone who uses .net core as a web API service</p>

```<code>public IEnumerable<Contact> GetContacts([FromQuery]TestVM testVM)
</code>```

Title: Passing ViewModel to Web-Api action

Body:
Is it possible to pass an ViewModel object to WebApi controller action instead of separate params?

Instead of using:

public class ContactsController : ApiController
{
    public IEnumerable<Contact> GetContacts(string p1, string p2)
    {
        // some logic
    }
}

I would like to use:

public class ContactsController : ApiController
{
    public IEnumerable<Contact> GetContacts(TestVM testVM)
    {
        // some logic
    }
}

public class TestVM
{
    public string P1 { get; set; }
    public string P2 { get; set; }
}

This doesn't seem to work for me. When I call /api/contacts/?P1=aaa&P2=bbb the testVM object doesn't get populated (null).

Also, I would like the TestVM to have valdiation attribtues defined and use ModelState.IsValid in my API controller.

Body:
I know it's kind of late to post another answer but I thought it could be useful for anyone who uses .net core as a web API service

public IEnumerable<Contact> GetContacts([FromQuery]TestVM testVM)


问:
which classes/functions should Helper package typically contain - Selenium & cucumber
I have a Helper package in my selenium framework.

Can anyone help me with what classes or functions typically I should write in this package

Configuration: Selenium & cucumber

答: I typically keep the classes those contain generic things but  will be helpful occassionally. For example, Dictionary that will contain locator details in case you are not using page factory. You can add Thread handling class, wait handling class and loggers/report handing.</p>


问:
Is there a way to automatically check all check boxes in group A by checking another individual check box with DocuSign API
let's say I defined mutilple check boxes with DocuSign eSignature Java SDK, each of the check box been given unique Tab Label,  then group them together in tabs group A and all the check boxes in tabs group A are mandatory (with Validator).

Is there any way that I can define another individual check box (call it B) in the envelope,  by checking the check box B will automaticly check/uncheck all the check boxes in tabs group A by using DocuSign Java SDK or eSignature REST API.

I would appreciate it if any one could provide a solution, thank you^_^.

答:
To the best of my knowledge, no. I would instead suggest playing with Tab Replication feature. It might serve as a good replacement for this requirement.

Here's an example use case...

Let's assume you have a job application that asks the applicant to specify which languages she is familiar with. At the top of the list of languages, there is a checkbox labeled "All". If the user selects this option, all checkboxes next to the individual languages are hidden from view. Otherwise, the user can select the languages that are applicable.

Once the user completes her signing, the business logic of your app can check if that "all" checkbox was selected and interpret it to mean that the user is comfortable with all languages, otherwise, you would check the individual values of the other checkboxes.

Here is how you would build that envelope from scratch: Notice that each checkbox references its parent via conditionalParentLabel. conditionalParentValue": "off"tells DocuSign to hide the children from view if the parent is checked.

```<code>POST /envelopes

{
    "emailSubject": "Please sign this document set",
    "documents": [
        {
            "documentBase64": "JVBERi0xLj...UlRU9GCg==",
            "name": "Test Doc",
            "fileExtension": "pdf",
            "documentId": "1"
        }
    ],
    "recipients": {
        "signers": [
            {
                "email": "test@test.com",
                "name": "Matthew Roknich",
                "recipientId": "1",
                "routingOrder": "1",
                "tabs": {
                    "checkboxTabs": [
                        {
                            "tabLabel": "all",
                            "locked": "false",
                            "xPosition": "100",
                            "yPosition": "100",
                            "documentId": "1",
                            "pageNumber": "1"
                        },
                         {
                            "tabLabel": "english",
                            "locked": "false",
                            "xPosition": "130",
                            "yPosition": "110",
                            "documentId": "1",
                            "pageNumber": "1",
                            "conditionalParentLabel": "all",
                            "conditionalParentValue": "off"
                        },
                         {
                            "tabLabel": "spanish",
                            "locked": "false",
                            "xPosition": "160",
                            "yPosition": "110",
                            "documentId": "1",
                            "pageNumber": "1",
                            "conditionalParentLabel": "all",
                            "conditionalParentValue": "off"
                        },
                         {
                            "tabLabel": "french",
                            "locked": "false",
                            "xPosition": "190",
                            "yPosition": "110",
                            "documentId": "1",
                            "pageNumber": "1",
                            "conditionalParentLabel": "all",
                            "conditionalParentValue": "off"
                        }
                    ]
                }
            }
          ]
    },
  "status": "sent"
}
</code>```

Body:
To the best of my knowledge, no. I would instead suggest playing with Tab Replication feature. It might serve as a good replacement for this requirement.

Here's an example use case...

Let's assume you have a job application that asks the applicant to specify which languages she is familiar with. At the top of the list of languages, there is a checkbox labeled "All". If the user selects this option, all checkboxes next to the individual languages are hidden from view. Otherwise, the user can select the languages that are applicable.

Once the user completes her signing, the business logic of your app can check if that "all" checkbox was selected and interpret it to mean that the user is comfortable with all languages, otherwise, you would check the individual values of the other checkboxes.

Here is how you would build that envelope from scratch: Notice that each checkbox references its parent via conditionalParentLabel. conditionalParentValue": "off"tells DocuSign to hide the children from view if the parent is checked.

POST /envelopes

{
    "emailSubject": "Please sign this document set",
    "documents": [
        {
            "documentBase64": "JVBERi0xLj...UlRU9GCg==",
            "name": "Test Doc",
            "fileExtension": "pdf",
            "documentId": "1"
        }
    ],
    "recipients": {
        "signers": [
            {
                "email": "test@test.com",
                "name": "Matthew Roknich",
                "recipientId": "1",
                "routingOrder": "1",
                "tabs": {
                    "checkboxTabs": [
                        {
                            "tabLabel": "all",
                            "locked": "false",
                            "xPosition": "100",
                            "yPosition": "100",
                            "documentId": "1",
                            "pageNumber": "1"
                        },
                         {
                            "tabLabel": "english",
                            "locked": "false",
                            "xPosition": "130",
                            "yPosition": "110",
                            "documentId": "1",
                            "pageNumber": "1",
                            "conditionalParentLabel": "all",
                            "conditionalParentValue": "off"
                        },
                         {
                            "tabLabel": "spanish",
                            "locked": "false",
                            "xPosition": "160",
                            "yPosition": "110",
                            "documentId": "1",
                            "pageNumber": "1",
                            "conditionalParentLabel": "all",
                            "conditionalParentValue": "off"
                        },
                         {
                            "tabLabel": "french",
                            "locked": "false",
                            "xPosition": "190",
                            "yPosition": "110",
                            "documentId": "1",
                            "pageNumber": "1",
                            "conditionalParentLabel": "all",
                            "conditionalParentValue": "off"
                        }
                    ]
                }
            }
          ]
    },
  "status": "sent"
}


问:
unable to read kafka topic data using spark
I have data like below in one of the topics which I created named "sampleTopic"

```<code>sid,Believer
</code>```

Where the first argument is the username and the second argument is the song name which the user frequently listens. Now, I have started zookeeper, Kafka server, and producer with the topic name as mentioned above. I have entered the above data for that topic using CMD. Now, I want to read the topic in spark perform some aggregation, and write it back to stream. Below is my code:

```<code>package com.sparkKafka
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
object SparkKafkaTopic {
  def main(args: Array[String]) {
    val spark = SparkSession.builder().appName("SparkKafka").master("local[*]").getOrCreate()
    println("hey")
    val df = spark
      .readStream
      .format("kafka")
      .option("kafka.bootstrap.servers", "localhost:9092")
      .option("subscribe", "sampleTopic1")
      .load()
    val query = df.writeStream
      .outputMode("append")
      .format("console")
      .start().awaitTermination()

  }
}
</code>```

However, when I execute the above code it gives :

```<code>    +----+--------------------+------------+---------+------+--------------------+-------------+
| key|               value|       topic|partition|offset|           timestamp|timestampType|
+----+--------------------+------------+---------+------+--------------------+-------------+
|null|[73 69 64 64 68 6...|sampleTopic1|        0|     4|2020-05-31 12:12:...|            0|
+----+--------------------+------------+---------+------+--------------------+-------------+
</code>```

with infinite below looping messages too

```<code>20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
</code>```

I need output something like below:

As modified on the suggestion by Srinivas I got the following output:

Not sure what exactly is wrong over here. Please guide me through it.

答:
spark-sql-kafka jar is missing, which is having the implementation of 'kafka' datasource.

you can add the jar using config option or build fat jar which includes spark-sql-kafka jar. Please use relevant version of jar

```<code>val spark = SparkSession.builder()
  .appName("SparkKafka").master("local[*]")
  .config("spark.jars","/path/to/spark-sql-kafka-xxxxxx.jar")
  .getOrCreate()
</code>```

Body:
I have data like below in one of the topics which I created named "sampleTopic"

sid,Believer

Where the first argument is the username and the second argument is the song name which the user frequently listens. Now, I have started zookeeper, Kafka server, and producer with the topic name as mentioned above. I have entered the above data for that topic using CMD. Now, I want to read the topic in spark perform some aggregation, and write it back to stream. Below is my code:

package com.sparkKafka
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
object SparkKafkaTopic {
  def main(args: Array[String]) {
    val spark = SparkSession.builder().appName("SparkKafka").master("local[*]").getOrCreate()
    println("hey")
    val df = spark
      .readStream
      .format("kafka")
      .option("kafka.bootstrap.servers", "localhost:9092")
      .option("subscribe", "sampleTopic1")
      .load()
    val query = df.writeStream
      .outputMode("append")
      .format("console")
      .start().awaitTermination()

  }
}

However, when I execute the above code it gives :

    +----+--------------------+------------+---------+------+--------------------+-------------+
| key|               value|       topic|partition|offset|           timestamp|timestampType|
+----+--------------------+------------+---------+------+--------------------+-------------+
|null|[73 69 64 64 68 6...|sampleTopic1|        0|     4|2020-05-31 12:12:...|            0|
+----+--------------------+------------+---------+------+--------------------+-------------+

with infinite below looping messages too

20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.

I need output something like below:

As modified on the suggestion by Srinivas I got the following output:

Not sure what exactly is wrong over here. Please guide me through it.

Body:
spark-sql-kafka jar is missing, which is having the implementation of 'kafka' datasource.

you can add the jar using config option or build fat jar which includes spark-sql-kafka jar. Please use relevant version of jar

val spark = SparkSession.builder()
  .appName("SparkKafka").master("local[*]")
  .config("spark.jars","/path/to/spark-sql-kafka-xxxxxx.jar")
  .getOrCreate()


问:
Spotify API queue method returning 503 Service Unavailable error
I'm using Spotify developer API from a webapplication I'm developing in Ruby on Rails.
For that I'm using a gem called rspotify.
I modified it slightly in order to add the capability to queue a song which is offered by the Spotify API.
Here is the API documentation from Spotify Dev:
https://developer.spotify.com/console/post-queue/

Here is the original piece of code from rspotify with all existing (and working) calls (like play a song):
https://github.com/guilhermesad/rspotify/blob/master/lib/rspotify/player.rb

And here is the piece of code I added:

```<code>def queue(device_id = nil, uri)
  url = "me/player/queue?uri=#{uri}"
  url = device_id.nil? ? url : "#{url}?device_id=#{device_id}"

  User.oauth_put(@user.id, url, {})
end
</code>```

Unfortunately, all methods work but not this one.
Here is an example of the call with the error I get (extract of a ruby call in the console):

```<code>> me = RSpotify::User.new(hash)
> player = RSpotify::Player.new(me)
> track = RSpotify::Track.search('Know')[0]
>
> player.play_track(track.uri)
 => nil
> player.queue(track.uri)
warning: Overriding "Content-Type" header "application/json" with "application/x-www-form-urlencoded" due to payload
Traceback (most recent call last):
        1: from (irb):82
RestClient::ServiceUnavailable (503 Service Unavailable)
</code>```

Note that the call to method play_track works fine. Only the player.queue is a problem here.

I hope somebody can help me.

Thanks in advance

答:
Problem is solved.

The issue was coming from the fact that a PUT method was used instead of a POST.
Here is the fixed code:

```<code>def queue(device_id = nil, uri)
  url = "me/player/queue?uri=#{uri}"
  url = device_id.nil? ? url : "#{url}&device_id=#{device_id}"
  User.oauth_post(@user.id, url, {})
end
</code>```

Hope it will save some time to others

Body:
I'm using Spotify developer API from a webapplication I'm developing in Ruby on Rails.
For that I'm using a gem called rspotify.
I modified it slightly in order to add the capability to queue a song which is offered by the Spotify API.
Here is the API documentation from Spotify Dev:
https://developer.spotify.com/console/post-queue/

Here is the original piece of code from rspotify with all existing (and working) calls (like play a song):
https://github.com/guilhermesad/rspotify/blob/master/lib/rspotify/player.rb

And here is the piece of code I added:

def queue(device_id = nil, uri)
  url = "me/player/queue?uri=#{uri}"
  url = device_id.nil? ? url : "#{url}?device_id=#{device_id}"

  User.oauth_put(@user.id, url, {})
end

Unfortunately, all methods work but not this one.
Here is an example of the call with the error I get (extract of a ruby call in the console):

> me = RSpotify::User.new(hash)
> player = RSpotify::Player.new(me)
> track = RSpotify::Track.search('Know')[0]
>
> player.play_track(track.uri)
 => nil
> player.queue(track.uri)
warning: Overriding "Content-Type" header "application/json" with "application/x-www-form-urlencoded" due to payload
Traceback (most recent call last):
        1: from (irb):82
RestClient::ServiceUnavailable (503 Service Unavailable)

Note that the call to method play_track works fine. Only the player.queue is a problem here.

I hope somebody can help me.

Thanks in advance

Body:
Problem is solved.

The issue was coming from the fact that a PUT method was used instead of a POST.
Here is the fixed code:

def queue(device_id = nil, uri)
  url = "me/player/queue?uri=#{uri}"
  url = device_id.nil? ? url : "#{url}&device_id=#{device_id}"
  User.oauth_post(@user.id, url, {})
end

Hope it will save some time to others


问:
How to retrieve data from sqlite database and display in a fragment
I want to display data from my DB into a EditText in my fragment.

Here is my coding:

DBhelper

```<code>public void onCreate(SQLiteDatabase db) {
        db.execSQL("Create table Tenant_login(name text, email text primary key, password text)" );
}
</code>```

Retrive Data

```<code> public Cursor alldata() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor= db.rawQuery("Select * from Tenant_login",null);
        return cursor;
    }
</code>```

Fragment class

```<code>public class profileFragement extends Fragment {

    DatabaseHelper db;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.profile_fragment, container, false);
        EditText et = (EditText) view.findViewById(R.id.text);
        et.setVisibility(view.VISIBLE);

     db = new DatabaseHelper(getActivity());
    Cursor cursor = db.alldata();
      et.setText(""+ cursor.getString(0));
 return view;
    }

}
</code>```

This coding is giving me no results.
Please Help me out.

答:
You must move the cursor's index to the 1st row (if it exists):</p>

```<code>if (cursor.moveToFirst()) {
    et.setText("" + cursor.getString(0));
}
</code>```

Body:
I want to display data from my DB into a EditText in my fragment.

Here is my coding:

DBhelper

public void onCreate(SQLiteDatabase db) {
        db.execSQL("Create table Tenant_login(name text, email text primary key, password text)" );
}

Retrive Data

 public Cursor alldata() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor= db.rawQuery("Select * from Tenant_login",null);
        return cursor;
    }

Fragment class

public class profileFragement extends Fragment {

    DatabaseHelper db;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.profile_fragment, container, false);
        EditText et = (EditText) view.findViewById(R.id.text);
        et.setVisibility(view.VISIBLE);

     db = new DatabaseHelper(getActivity());
    Cursor cursor = db.alldata();
      et.setText(""+ cursor.getString(0));
 return view;
    }

}

This coding is giving me no results.
Please Help me out.

Body:
You must move the cursor's index to the 1st row (if it exists):

if (cursor.moveToFirst()) {
    et.setText("" + cursor.getString(0));
}


问:
Rewrite jQuery function to Vanilla JS and optimize
First I want to apologize, because I am a bit newbie with JS and it's library jQuery. Basically I have written a javascript function that toggles my hamburger menu:

```<code>const menuToggle = document.querySelector('.menu-toggle');
let menuOpen = false;
menuToggle.addEventListener('click', () => {
  if(!menuOpen) {
    menuToggle.classList.add('open');
    menuOpen = true;
  } else {
    menuToggle.classList.remove('open');
    menuOpen = false;
  }
});
</code>```

Now I want to rewrite this jQuery function to Vanilla JS

```<code>$(function() {
  $('.toggle').on('click', function() {
    $('.inner-wrapper').toggleClass('open');
  });
});
</code>```

I tried this, but it is not working:

```<code>var searchElement = document.createElement(".inner-wrapper");
document.querySelector(".toggle").appendChild(searchElement);
searchElement.addEventListener("open", handleClick);
</code>```

I would like to combine both functions if possible. Thanks in advance!

答:
First, this code of yours:

menuToggle.addEventListener('click', () => {
  if(!menuOpen) {
    menuToggle.classList.add('open');
    menuOpen = true;
  } else {
    menuToggle.classList.remove('open');
    menuOpen = false;
  }
});
```

<p>can be simplified to this:</p>

<pre class="lang-js prettyprint-override"><code>menuToggle.addEventListener('click', () => {
  menuToggle.classList.toggle('open');
  menuOpen = !menuOpen;
});
</code>```

Second, the equivalent vanilla JavaScript version of this:

$(function() {
  $('.toggle').on('click', function() {
    $('.inner-wrapper').toggleClass('open');
  });
});
```

<p>is this:</p>

<pre class="lang-js prettyprint-override"><code>document.querySelector('.toggle').addEventListener('click', function () {
  document.querySelector('.inner-wrapper').classList.toggle('open');
});
</code>```

Finally, this code of yours has problems:

var searchElement = document.createElement(".inner-wrapper");
document.querySelector(".toggle").appendChild(searchElement);
searchElement.addEventListener("open", handleClick);
```

<p>There is no HTML element called ".inner-wrapper". You probably wanted to create an element with that class, something like this:</p>

```var searchElement = document.createElement("div"); // or any valid tag name
searchElement.className = 'inner-wrapper';
```

Also, there's no event called "open". You probably want that to be "click", and you probably want to target that to the ".toggle" element (not the '.inner-wrapper' element).

Body:
First I want to apologize, because I am a bit newbie with JS and it's library jQuery. Basically I have written a javascript function that toggles my hamburger menu:

const menuToggle = document.querySelector('.menu-toggle');
let menuOpen = false;
menuToggle.addEventListener('click', () => {
  if(!menuOpen) {
    menuToggle.classList.add('open');
    menuOpen = true;
  } else {
    menuToggle.classList.remove('open');
    menuOpen = false;
  }
});

Now I want to rewrite this jQuery function to Vanilla JS

$(function() {
  $('.toggle').on('click', function() {
    $('.inner-wrapper').toggleClass('open');
  });
});

I tried this, but it is not working:

var searchElement = document.createElement(".inner-wrapper");
document.querySelector(".toggle").appendChild(searchElement);
searchElement.addEventListener("open", handleClick);

I would like to combine both functions if possible. Thanks in advance!

Body:
First, this code of yours:

menuToggle.addEventListener('click', () => {
  if(!menuOpen) {
    menuToggle.classList.add('open');
    menuOpen = true;
  } else {
    menuToggle.classList.remove('open');
    menuOpen = false;
  }
});

can be simplified to this:

menuToggle.addEventListener('click', () => {
  menuToggle.classList.toggle('open');
  menuOpen = !menuOpen;
});

Second, the equivalent vanilla JavaScript version of this:

$(function() {
  $('.toggle').on('click', function() {
    $('.inner-wrapper').toggleClass('open');
  });
});

is this:

document.querySelector('.toggle').addEventListener('click', function () {
  document.querySelector('.inner-wrapper').classList.toggle('open');
});

Finally, this code of yours has problems:

var searchElement = document.createElement(".inner-wrapper");
document.querySelector(".toggle").appendChild(searchElement);
searchElement.addEventListener("open", handleClick);

There is no HTML element called ".inner-wrapper". You probably wanted to create an element with that class, something like this:

var searchElement = document.createElement("div"); // or any valid tag name
searchElement.className = 'inner-wrapper';

Also, there's no event called "open". You probably want that to be "click", and you probably want to target that to the ".toggle" element (not the '.inner-wrapper' element).


问:
sub-group using XSLT
I have a source xml like below. Im trying to convert to a desired format using xslt as shown below

```<code>**Sample XML**

 <table>
    <row>
        <tablename>table1</tablename>
        <columnname>col1</columnname>
        <columnDesc>col1_desc</columnDesc>
        <columnDataType>Number</columnDataType>
        <ultimateSourceTable>sourceTable1</ultimateSourceTable>
    </row>
    <row>
        <tablename>table1</tablename>
        <columnname>col1</columnname>
        <columnDesc>col1_desc</columnDesc>
        <columnDataType>Number</columnDataType>
        <ultimateSourceTable>sourceTable2</ultimateSourceTable>
    </row>
    <row>
        <tablename>table2</tablename>
        <columnname>table2_col1</columnname>
        <columnDesc>table2_col1_desc</columnDesc>
        <columnDataType>String</columnDataType>
        <ultimateSourceTable>sourceTable2</ultimateSourceTable>
    </row>
</table>
</code>```

current output

```<code>   <Prod>
<dataBase>
    <physicalTableName>
        <tableName>table1</tableName>
    </physicalTableName>
    <columnList>
        <name>col1</name>
        <name>col1</name>
        <name>table2_col1</name>
    </columnList>
    <finalSourceList>
        <column>
            <columnName>col1</columnName>
            <ultimateSourceTable>sourceTable1</ultimateSourceTable>
        </column>
        <column>
            <columnName>col1</columnName>
            <ultimateSourceTable>sourceTable2</ultimateSourceTable>
        </column>
    </finalSourceList>
    <physicalTableName>
        <tableName>table2</tableName>
    </physicalTableName>
    <columnList>
        <name>col1</name>
        <name>col1</name>
        <name>table2_col1</name>
    </columnList>
    <finalSourceList>
        <column>
            <columnName>table2_col1</columnName>
            <ultimateSourceTable>sourceTable2</ultimateSourceTable>
        </column>
    </finalSourceList>
</dataBase>
</code>```

Desired output:

```<code><Prod>
    <dataBase>
        <physicalTableName>
            <tableName>table1</tableName>
        </physicalTableName>
        <columnList>
            <name>col1</name>
            <columnDesc>col1_desc</columnDesc>
            <columnDataType>Number</columnDataType>
        </columnList>
        <finalSourceList>
            <column>
                <columnName>col1</columnName>
                <ultimateSourceTable>sourceTable1</ultimateSourceTable>
            </column>
            <column>
                <columnName>col1</columnName>
                <ultimateSourceTable>sourceTable2</ultimateSourceTable>
            </column>
        </finalSourceList>
        <physicalTableName>
            <tableName>table2</tableName>
        </physicalTableName>
        <columnList>
            <name>table2_col1</name>
            <columnDesc>table2_col1_desc</columnDesc>
            <columnDataType>String</columnDataType>
        </columnList>
        <finalSourceList>
            <column>
                <columnName>table2_col1</columnName>
                <ultimateSourceTable>sourceTable2</ultimateSourceTable>
            </column>
        </finalSourceList>
    </dataBase>
</Prod>
</code>```

XSLT:

```<code>      <?xml version="1.0" encoding="UTF-8"?>
        <xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
            <xsl:output method="xml" version="1.0" encoding="UTF-8"
                indent="yes" />
            <xsl:template match="/">
                <Prod>
                    <xsl:apply-templates />
                </Prod>
            </xsl:template>
            <xsl:key name="kElsByGroup" match="row" use="tablename" />
            <xsl:key name="TableColByGroup" match="row" use="concat(tablename,'|',columnname)" />
            <xsl:template match="row">
                <xsl:apply-templates />
            </xsl:template>
            <xsl:template
                match="row[generate-id()=generate-id(key('kElsByGroup',tablename)[1])]">
                <dataBase>
                    <physicalTableName>
                        <tableName>
                            <xsl:value-of select="tablename"></xsl:value-of>
                        </tableName>
                    </physicalTableName>
                    <columnList>
                        <xsl:for-each
                                           select="//row[generate-id()=generate-id(key('TableColByGroup',concat(tablename,'|',columnname))[1])]">
                            <xsl:element name="column">
                                <name>
                                    <xsl:value-of
                                                        select="columnname"></xsl:value-of>
                                </name>
                            </xsl:element>
                        </xsl:for-each>
                    </columnList>
                    <finalSourceList>
                        <xsl:for-each
                                            select="key('kElsByGroup',tablename)">
                            <xsl:element name="column">
                                <columnName>
                                    <xsl:value-of
                                                        select="columnname"></xsl:value-of>
                                </columnName>
                                <sourceTable>
                                    <xsl:value-of
                                                        select="ultimateSourceTable"></xsl:value-of>
                                </sourceTable>
                            </xsl:element>
                        </xsl:for-each>
                    </finalSourceList>
                </dataBase>
            </xsl:template>
            <xsl:template
                match="row[not(generate-id()=generate-id(key('kElsByGroup',tablename)[1]))]" />
        </xsl:stylesheet>
</code>```

So, I basically want to have only unique value in my columnList tag. I'm trying to subgroup using muenchian grouping but, I still 2 entries of col1 in my columnList tag. Can someone help me out?

答:
With a single table element in the source containing rows of different tables it seems you can solve it using modes to process rows twice, once to create the data of a result table and the second time to create the details of each result table:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:output method="xml" indent="yes"/>

  <xsl:key name="table" match="row" use="tablename"/>

  <xsl:key name="col" match="row" use="concat(tablename, '|', columnname)"/>

  <xsl:template match="table">
      <Prod>
          <dataBase>
             <xsl:apply-templates select="row[generate-id() = generate-id(key('table', tablename)[1])]" mode="table"/>
          </dataBase>
      </Prod>
  </xsl:template>

  <xsl:template match="row" mode="table">
      <physicalTableName>
          <xsl:value-of select="tablename"/>
      </physicalTableName>
      <columnList>
          <xsl:apply-templates select="key('table', tablename)[generate-id() = generate-id(key('col', concat(tablename, '|', columnname))[1])]/columnname"/>
      </columnList>
      <finalSourceList>
          <xsl:apply-templates select="key('table', tablename)"/>
      </finalSourceList>
  </xsl:template>

  <xsl:template match="row/columnname">
      <name>
          <xsl:value-of select="."/>
      </name>
  </xsl:template>

  <xsl:template match="row">
      <column>
          <xsl:apply-templates select="*[not(self::tablename)]" mode="source-list"/>
      </column>
  </xsl:template>

  <xsl:template match="row/columnname" mode="source-list">
      <columnName>
          <xsl:value-of select="."/>
      </columnName>
  </xsl:template>

  <xsl:template match="row/ultimateSourceTable" mode="source-list">
      <xsl:copy-of select="."/>
  </xsl:template>

</xsl:stylesheet>
</code>```

https://xsltfiddle.liberty-development.net/naZYrpu/1

Title: sub-group using XSLT

Body:
I have a source xml like below. Im trying to convert to a desired format using xslt as shown below

**Sample XML**

    <row>
        <tablename>table1</tablename>
        <columnname>col1</columnname>
        <columnDesc>col1_desc</columnDesc>
        <columnDataType>Number</columnDataType>
        <ultimateSourceTable>sourceTable1</ultimateSourceTable>
    </row>
    <row>
        <tablename>table1</tablename>
        <columnname>col1</columnname>
        <columnDesc>col1_desc</columnDesc>
        <columnDataType>Number</columnDataType>
        <ultimateSourceTable>sourceTable2</ultimateSourceTable>
    </row>
    <row>
        <tablename>table2</tablename>
        <columnname>table2_col1</columnname>
        <columnDesc>table2_col1_desc</columnDesc>
        <columnDataType>String</columnDataType>
        <ultimateSourceTable>sourceTable2</ultimateSourceTable>
    </row>

current output

   <Prod>
<dataBase>
    <physicalTableName>
        <tableName>table1</tableName>
    </physicalTableName>
    <columnList>
        <name>col1</name>
        <name>col1</name>
        <name>table2_col1</name>
    </columnList>
    <finalSourceList>
        <column>
            <columnName>col1</columnName>
            <ultimateSourceTable>sourceTable1</ultimateSourceTable>
        </column>
        <column>
            <columnName>col1</columnName>
            <ultimateSourceTable>sourceTable2</ultimateSourceTable>
        </column>
    </finalSourceList>
    <physicalTableName>
        <tableName>table2</tableName>
    </physicalTableName>
    <columnList>
        <name>col1</name>
        <name>col1</name>
        <name>table2_col1</name>
    </columnList>
    <finalSourceList>
        <column>
            <columnName>table2_col1</columnName>
            <ultimateSourceTable>sourceTable2</ultimateSourceTable>
        </column>
    </finalSourceList>
</dataBase>

Desired output:

<Prod>
    <dataBase>
        <physicalTableName>
            <tableName>table1</tableName>
        </physicalTableName>
        <columnList>
            <name>col1</name>
            <columnDesc>col1_desc</columnDesc>
            <columnDataType>Number</columnDataType>
        </columnList>
        <finalSourceList>
            <column>
                <columnName>col1</columnName>
                <ultimateSourceTable>sourceTable1</ultimateSourceTable>
            </column>
            <column>
                <columnName>col1</columnName>
                <ultimateSourceTable>sourceTable2</ultimateSourceTable>
            </column>
        </finalSourceList>
        <physicalTableName>
            <tableName>table2</tableName>
        </physicalTableName>
        <columnList>
            <name>table2_col1</name>
            <columnDesc>table2_col1_desc</columnDesc>
            <columnDataType>String</columnDataType>
        </columnList>
        <finalSourceList>
            <column>
                <columnName>table2_col1</columnName>
                <ultimateSourceTable>sourceTable2</ultimateSourceTable>
            </column>
        </finalSourceList>
    </dataBase>
</Prod>

XSLT:

      <?xml version="1.0" encoding="UTF-8"?>
        <xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
            <xsl:output method="xml" version="1.0" encoding="UTF-8"
                indent="yes" />
            <xsl:template match="/">
                <Prod>
                    <xsl:apply-templates />
                </Prod>
            </xsl:template>
            <xsl:key name="kElsByGroup" match="row" use="tablename" />
            <xsl:key name="TableColByGroup" match="row" use="concat(tablename,'|',columnname)" />
            <xsl:template match="row">
                <xsl:apply-templates />
            </xsl:template>
            <xsl:template
                match="row[generate-id()=generate-id(key('kElsByGroup',tablename)[1])]">
                <dataBase>
                    <physicalTableName>
                        <tableName>
                            <xsl:value-of select="tablename"></xsl:value-of>
                        </tableName>
                    </physicalTableName>
                    <columnList>
                        <xsl:for-each
                                           select="//row[generate-id()=generate-id(key('TableColByGroup',concat(tablename,'|',columnname))[1])]">
                            <xsl:element name="column">
                                <name>
                                    <xsl:value-of
                                                        select="columnname"></xsl:value-of>
                                </name>
                            </xsl:element>
                        </xsl:for-each>
                    </columnList>
                    <finalSourceList>
                        <xsl:for-each
                                            select="key('kElsByGroup',tablename)">
                            <xsl:element name="column">
                                <columnName>
                                    <xsl:value-of
                                                        select="columnname"></xsl:value-of>
                                </columnName>
                                <sourceTable>
                                    <xsl:value-of
                                                        select="ultimateSourceTable"></xsl:value-of>
                                </sourceTable>
                            </xsl:element>
                        </xsl:for-each>
                    </finalSourceList>
                </dataBase>
            </xsl:template>
            <xsl:template
                match="row[not(generate-id()=generate-id(key('kElsByGroup',tablename)[1]))]" />
        </xsl:stylesheet>

So, I basically want to have only unique value in my columnList tag. I'm trying to subgroup using muenchian grouping but, I still 2 entries of col1 in my columnList tag. Can someone help me out?

Body:
With a single table element in the source containing rows of different tables it seems you can solve it using modes to process rows twice, once to create the data of a result table and the second time to create the details of each result table:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:output method="xml" indent="yes"/>

  <xsl:key name="table" match="row" use="tablename"/>

  <xsl:key name="col" match="row" use="concat(tablename, '|', columnname)"/>

  <xsl:template match="table">
      <Prod>
          <dataBase>
             <xsl:apply-templates select="row[generate-id() = generate-id(key('table', tablename)[1])]" mode="table"/>
          </dataBase>
      </Prod>
  </xsl:template>

  <xsl:template match="row" mode="table">
      <physicalTableName>
          <xsl:value-of select="tablename"/>
      </physicalTableName>
      <columnList>
          <xsl:apply-templates select="key('table', tablename)[generate-id() = generate-id(key('col', concat(tablename, '|', columnname))[1])]/columnname"/>
      </columnList>
      <finalSourceList>
          <xsl:apply-templates select="key('table', tablename)"/>
      </finalSourceList>
  </xsl:template>

  <xsl:template match="row/columnname">
      <name>
          <xsl:value-of select="."/>
      </name>
  </xsl:template>

  <xsl:template match="row">
      <column>
          <xsl:apply-templates select="*[not(self::tablename)]" mode="source-list"/>
      </column>
  </xsl:template>

  <xsl:template match="row/columnname" mode="source-list">
      <columnName>
          <xsl:value-of select="."/>
      </columnName>
  </xsl:template>

  <xsl:template match="row/ultimateSourceTable" mode="source-list">
      <xsl:copy-of select="."/>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/naZYrpu/1