问:
When I try to play my Music Discord Bot it doesn't play music
When I try to play my Music Discord Bot it doesn't play music. It uses ytdl-core and ffmpeg
My code is:

```<code>const Discord = require('discord.js');
const bot = new Discord.Client

const ytdl = require("ytdl-core")

const token = 'API TOKEN'

const PREFIX = '?';

var version = '1.2';

var servers = {};

bot.on('ready', () =>{
    console.log('This bot is online!' + version);
})

bot.on('message', message => {

    let args = message.content.substring(PREFIX.length).split(" ");

    switch(args[0]){
        case 'play':

            function play(connection, message){
                var server = servers[message.guild.id];

                server.dispatcher = connection.play(ytdl(server.queue[0], {filter: "audioonly"}))

                server.queue.shift();

                server.dispatcher.on("end", function(){
                    if(server.queue[0]){
                        play(connection, message);
                    }else {
                        connection.disconnect();
                    }
                });

            }

            if(!args[1]){
                message.channel.send("You need to provide a link!")
                return;
            }

            if(!message.member.voice.channel){
               message.channel.send("You must be in a Voice Channel to play the bot!")
               return;
            }

            if(!servers[message.guild.id]) servers[message.guild.id] = {
                queue: []
            }

            var server = servers[message.guild.id];

            server.queue.push(args[1]);

            if(!message.guild.voice) message.member.voice.channel.join().then(function(connection){
                play(connection, message);
            })

        break;
    }

    });

    bot.login(token);
</code>```

Whenever I try to play a song this error happens:

(node:5180) UnhandledPromiseRejectionWarning: Error: FFmpeg/avconv not
found!
at Function.getInfo (C:\Users\picar\Desktop\DiscordMusicBot\node_modules\prism-media\src\core\FFmpeg.js:130:11)
at Function.create (C:\Users\picar\Desktop\DiscordMusicBot\node_modules\prism-media\src\core\FFmpeg.js:143:38)
at new FFmpeg (C:\Users\picar\Desktop\DiscordMusicBot\node_modules\prism-media\src\core\FFmpeg.js:44:27)
at AudioPlayer.playUnknown (C:\Users\picar\Desktop\DiscordMusicBot\node_modules\discord.js\src\client\voice\player\BasePlayer.js:47:20)
at VoiceConnection.play (C:\Users\picar\Desktop\DiscordMusicBot\node_modules\discord.js\src\client\voice\util\PlayInterface.js:71:28)
at play (C:\Users\picar\Desktop\DiscordMusicBot\index.js:29:48)
at C:\Users\picar\Desktop\DiscordMusicBot\index.js:66:17
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:5180) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was
not handled with .catch(). To terminate the node process on unhandled
promise rejection, use the CLI flag --unhandled-rejections=strict
(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1)
(node:5180) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are
not handled will terminate the Node.js process with a non-zero exit
code

Please help.

答:
Have you installed FFmpeg ? Or ffmpeg-static ?

Try doing npm i ffmpeg ffmpeg-static, it should update everything, let us know if it changes anything !

Also try to install npm i @discordjs/opus since it is required to play audio in Discord :)

Body:
When I try to play my Music Discord Bot it doesn't play music. It uses ytdl-core and ffmpeg
My code is:

const Discord = require('discord.js');
const bot = new Discord.Client

const ytdl = require("ytdl-core")

const token = 'API TOKEN'

const PREFIX = '?';

var version = '1.2';

var servers = {};

bot.on('ready', () =>{
    console.log('This bot is online!' + version);
})

bot.on('message', message => {

    let args = message.content.substring(PREFIX.length).split(" ");

    switch(args[0]){
        case 'play':

            function play(connection, message){
                var server = servers[message.guild.id];

                server.dispatcher = connection.play(ytdl(server.queue[0], {filter: "audioonly"}))

                server.queue.shift();

                server.dispatcher.on("end", function(){
                    if(server.queue[0]){
                        play(connection, message);
                    }else {
                        connection.disconnect();
                    }
                });

            }

            if(!args[1]){
                message.channel.send("You need to provide a link!")
                return;
            }

            if(!message.member.voice.channel){
               message.channel.send("You must be in a Voice Channel to play the bot!")
               return;
            }

            if(!servers[message.guild.id]) servers[message.guild.id] = {
                queue: []
            }

            var server = servers[message.guild.id];

            server.queue.push(args[1]);

            if(!message.guild.voice) message.member.voice.channel.join().then(function(connection){
                play(connection, message);
            })

        break;
    }

    });

    bot.login(token);

Whenever I try to play a song this error happens:

(node:5180) UnhandledPromiseRejectionWarning: Error: FFmpeg/avconv not
found!
at Function.getInfo (C:\Users\picar\Desktop\DiscordMusicBot\node_modules\prism-media\src\core\FFmpeg.js:130:11)
at Function.create (C:\Users\picar\Desktop\DiscordMusicBot\node_modules\prism-media\src\core\FFmpeg.js:143:38)
at new FFmpeg (C:\Users\picar\Desktop\DiscordMusicBot\node_modules\prism-media\src\core\FFmpeg.js:44:27)
at AudioPlayer.playUnknown (C:\Users\picar\Desktop\DiscordMusicBot\node_modules\discord.js\src\client\voice\player\BasePlayer.js:47:20)
at VoiceConnection.play (C:\Users\picar\Desktop\DiscordMusicBot\node_modules\discord.js\src\client\voice\util\PlayInterface.js:71:28)
at play (C:\Users\picar\Desktop\DiscordMusicBot\index.js:29:48)
at C:\Users\picar\Desktop\DiscordMusicBot\index.js:66:17
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:5180) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was
not handled with .catch(). To terminate the node process on unhandled
promise rejection, use the CLI flag --unhandled-rejections=strict
(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1)
(node:5180) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are
not handled will terminate the Node.js process with a non-zero exit
code

Please help.


来源: stackexchange

问:
Flutter BottomNavigationBarItem.icon to use BottomNavigationBar.iconSize
I want to use custom Widget (not Icon/ImageIcon) for the bottom navigation bar icons, but how do I make them follow iconSize?

```<code>BottomNavigationBar(
  iconSize: 24, // Currently ignored...
  items: _menu(theme),
  ...
)

List<BottomNavigationBarItem> _menu(ThemeData theme) => _items
  .map((i) => BottomNavigationBarItem(
        icon: CustomWidget(), // ...by CustomWidget
        ...
      ))
  .toList();
</code>```

Documentation for BottomNavigationBarItem.icon:

Typically the icon is an Icon or an ImageIcon widget. If another type of widget is provided then it should configure itself to match the current IconTheme size and color.

What does it mean?

答: The simple way is set the size as a const, and use this const in the widgets

ContentLicense: CC BY-SA 4.0

Body:
I want to use custom Widget (not Icon/ImageIcon) for the bottom navigation bar icons, but how do I make them follow iconSize?

BottomNavigationBar(
  iconSize: 24, // Currently ignored...
  items: _menu(theme),
  ...
)

List<BottomNavigationBarItem> _menu(ThemeData theme) => _items
  .map((i) => BottomNavigationBarItem(
        icon: CustomWidget(), // ...by CustomWidget
        ...
      ))
  .toList();

Documentation for BottomNavigationBarItem.icon:

Typically the icon is an Icon or an ImageIcon widget. If another type of widget is provided then it should configure itself to match the current IconTheme size and color.

What does it mean?


问:
How can I update the numberOfRowsInSection and how do I show all added values in this tableView?
I am trying to send values from one view controller - NewZoomAddressViewController to another one - Add_EditAddressViewController. I am sending the values to an array in the second view controller (addressArray).

Here is the first view controller:

```<code>class NewZoomAddressViewController: UIViewController {

@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var addressLabel: UILabel!
var addressArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    print("in Zoom map VC")
    mapView.delegate = self
    addressLabel.text = "\(self.sublocalityName!) \(localityName!) \(self.zipName!)"

}
@IBAction func confirmBtn(_ sender: Any) {
    let viewController = storyboard?.instantiateViewController(withIdentifier: "Add_EditAddressViewController") as! Add_EditAddressViewController
    addressArray.append("\(sublocalityName ?? "") \(zipName ?? "") \(localityName ?? "")")
    viewController.addressArray = addressArray
    navigationController?.pushViewController(viewController, animated: true)
}
}
</code>```

Then here I am adding values to addressArray from NewZoomAddressViewController like below:

```<code>class Add_EditAddressViewController: UIViewController,DataEnteredDelegate {
@IBOutlet var addressEDITTableview: UITableView!

  var addressArray = [String]()
override func viewDidLoad() {
    super.viewDidLoad()
    addressEDITTableview.register(UINib(nibName: "EditAddressTableViewCell", bundle: nil), forCellReuseIdentifier: "EditAddressTableViewCell")
    addressEDITTableview.reloadData()

}
}
extension Add_EditAddressViewController : UITableViewDelegate,UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return addressArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: EditAddressTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EditAddressTableViewCell") as! EditAddressTableViewCell
    cell.nameHeader.text = "header"
    cell.addressLabel.text = addressArray[indexPath.row]//"\(city) \(pincode) \(locality)"

    return cell
}
}
</code>```

However, in the table view I am only getting one row. The first time, the single row is okay, but if I add another address - the row is replaced with the new address, and I am no longer getting the old address. How do I show all of the added addresses in the table view?

答:
Update: Try out the following code on your Xcode-playground and play around with it to see how it works and try to implement the same logic in your code.

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {
    var array = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton(type: .contactAdd)
        button.center = view.center
        button.addTarget(self, action: #selector(add), for: .touchUpInside)
        view.addSubview(button)
    }
    @objc func add() {
        array.append("New element \(array.count)")
        let controller = TableViewController()
        controller.array = array
        present(controller, animated: true)
    }
}
class TableViewController: UITableViewController {
    var array = [String]()
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        array.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = array[indexPath.row]
        return cell
    }
}

PlaygroundPage.current.setLiveView(ViewController())
```

<p>Store the array outside the function scope and keep adding new elements to the same array instead of a new instance.</p>

<p>In InitialViewController with button action:</p>

<pre class="lang-swift prettyprint-override"><code>var addressArray = [String]()

@IBAction func confirmBtn(_ sender: Any) {
    let viewController = storyboard?.instantiateViewController(withIdentifier: "Add_EditAddressViewController") as! Add_EditAddressViewController
    addressArray.append("\(sublocalityName ?? "") \(zipName ?? "") \(localityName ?? "")")
    viewController.addressArray = addressArray
    navigationController?.pushViewController(viewController, animated: true)
}
</code>```

In Add_EditAddressViewController:

class Add_EditAddressViewController: UIViewController {
    var addressArray = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
        addressEDITTableview.reloadData()
    }
}

extension Add_EditAddressViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return addressArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: EditAddressTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EditAddressTableViewCell") as! EditAddressTableViewCell
        cell.nameHeader.text = "header"
        cell.addressLabel.text = addressArray[indexPath.row]
        return cell
    }
}
```

Body:
I am trying to send values from one view controller - NewZoomAddressViewController to another one - Add_EditAddressViewController. I am sending the values to an array in the second view controller (addressArray).

Here is the first view controller:

class NewZoomAddressViewController: UIViewController {

@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var addressLabel: UILabel!
var addressArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    print("in Zoom map VC")
    mapView.delegate = self
    addressLabel.text = "\(self.sublocalityName!) \(localityName!) \(self.zipName!)"

}
@IBAction func confirmBtn(_ sender: Any) {
    let viewController = storyboard?.instantiateViewController(withIdentifier: "Add_EditAddressViewController") as! Add_EditAddressViewController
    addressArray.append("\(sublocalityName ?? "") \(zipName ?? "") \(localityName ?? "")")
    viewController.addressArray = addressArray
    navigationController?.pushViewController(viewController, animated: true)
}
}

Then here I am adding values to addressArray from NewZoomAddressViewController like below:

class Add_EditAddressViewController: UIViewController,DataEnteredDelegate {
@IBOutlet var addressEDITTableview: UITableView!

  var addressArray = [String]()
override func viewDidLoad() {
    super.viewDidLoad()
    addressEDITTableview.register(UINib(nibName: "EditAddressTableViewCell", bundle: nil), forCellReuseIdentifier: "EditAddressTableViewCell")
    addressEDITTableview.reloadData()

}
}
extension Add_EditAddressViewController : UITableViewDelegate,UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return addressArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: EditAddressTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EditAddressTableViewCell") as! EditAddressTableViewCell
    cell.nameHeader.text = "header"
    cell.addressLabel.text = addressArray[indexPath.row]//"\(city) \(pincode) \(locality)"

    return cell
}
}

However, in the table view I am only getting one row. The first time, the single row is okay, but if I add another address - the row is replaced with the new address, and I am no longer getting the old address. How do I show all of the added addresses in the table view?

Body:
Update: Try out the following code on your Xcode-playground and play around with it to see how it works and try to implement the same logic in your code.

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {
    var array = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton(type: .contactAdd)
        button.center = view.center
        button.addTarget(self, action: #selector(add), for: .touchUpInside)
        view.addSubview(button)
    }
    @objc func add() {
        array.append("New element \(array.count)")
        let controller = TableViewController()
        controller.array = array
        present(controller, animated: true)
    }
}
class TableViewController: UITableViewController {
    var array = [String]()
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        array.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = array[indexPath.row]
        return cell
    }
}

PlaygroundPage.current.setLiveView(ViewController())

Store the array outside the function scope and keep adding new elements to the same array instead of a new instance.

In InitialViewController with button action:

var addressArray = [String]()

@IBAction func confirmBtn(_ sender: Any) {
    let viewController = storyboard?.instantiateViewController(withIdentifier: "Add_EditAddressViewController") as! Add_EditAddressViewController
    addressArray.append("\(sublocalityName ?? "") \(zipName ?? "") \(localityName ?? "")")
    viewController.addressArray = addressArray
    navigationController?.pushViewController(viewController, animated: true)
}

In Add_EditAddressViewController:

class Add_EditAddressViewController: UIViewController {
    var addressArray = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
        addressEDITTableview.reloadData()
    }
}

extension Add_EditAddressViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return addressArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: EditAddressTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EditAddressTableViewCell") as! EditAddressTableViewCell
        cell.nameHeader.text = "header"
        cell.addressLabel.text = addressArray[indexPath.row]
        return cell
    }
}


问:
Commons File Upload Not Working In Servlet
I have a servlet which is meant to handle the upload of a very large file. I am trying to use commons fileupload to handle it. Currently, the file I am attempting to upload is 287MB.

I set up the FileItemFactory and ServletFileUpload, then set a very large max file size on the ServletFileUpload.

Unfortunately, when I attempt to create a FileItemIterator, nothing happens. The form is set with the correct action, multipart encoding, and for the POST method.

Can anyone assist? doPost() of the servlet is posted below:

```<code>@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // ensure that the form is multipart encoded since we are uploading a file
    if (!ServletFileUpload.isMultipartContent(req)) {
        //throw new FileUploadException("Request was not multipart");
        log.debug("Request was not multipart. Returning from call");
    }

    // create a list to hold all of the files
    List<File> fileList = new ArrayList<File>();
    try {
        // setup the factories and file upload stuff
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(999999999);

        // create a file item iterator to cycle through all of the files in the req. There SHOULD only be one, though
        FileItemIterator iterator = upload.getItemIterator(req);

        // iterate through the file items and create a file item stream to output the file
        while (iterator.hasNext()) {

            // get the file item stream from the iterator
            FileItemStream fileItemStream = iterator.next();

            // Use the Special InputStream type, passing it the stream and the length of the file
            InputStream inputStream = new UploadProgressInputStream(fileItemStream.openStream(), req.getContentLength());

            // create a File from the file name
            String fileName = fileItemStream.getName();  // this only returns the filename, not the full path
            File file = new File(tempDirectory, fileName);

            // add the file to the list
            fileList.add(file);

            // Use commons-io Streams to copy from the inputstrea to a brand-new file
            Streams.copy(inputStream, new FileOutputStream(file), true);

            // close the inputstream
            inputStream.close();

        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // now that we've save the file, we can process it.
    if (fileList.size() == 0) {
        log.debug("No File in the file list. returning.");
        return;
    }

    for (File file : fileList) {

        String fileName = file.getName();
        BufferedReader reader = new BufferedReader(new FileReader(fileName));

        String line = reader.readLine();
        List<Feature> featureList = new ArrayList<Feature>(); // arraylist may not be the best choice since I don't know how many features I'm importing
        while (!line.isEmpty()) {
            String[] splitLine = line.split("|");
            Feature feature = new Feature();
            feature.setId(Integer.parseInt(splitLine[0]));
            feature.setName(splitLine[1]);
            feature.setFeatureClass(splitLine[2]);
            feature.setLat(Double.parseDouble(splitLine[9]));
            feature.setLng(Double.parseDouble(splitLine[10]));
            featureList.add(feature);

            line = reader.readLine();
        }

        file.delete();   // todo: check this to ensure it won't blow up the code since we're iterating in a for each
        reader.close();  // todo: need this in a finally block somewhere to ensure this always happens.

        try {
            featureService.persistList(featureList);
        } catch (ServiceException e) {
            log.debug("Caught Service Exception in FeatureUploadService.", e);

        }
    }
}
</code>```

答: It was an incredibly stupid problem. I left the name attribute off of the FileUpload entry in the GWT UiBinder. Thanks for all of the help from everyone.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a servlet which is meant to handle the upload of a very large file. I am trying to use commons fileupload to handle it. Currently, the file I am attempting to upload is 287MB.

I set up the FileItemFactory and ServletFileUpload, then set a very large max file size on the ServletFileUpload.

Unfortunately, when I attempt to create a FileItemIterator, nothing happens. The form is set with the correct action, multipart encoding, and for the POST method.

Can anyone assist? doPost() of the servlet is posted below:

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // ensure that the form is multipart encoded since we are uploading a file
    if (!ServletFileUpload.isMultipartContent(req)) {
        //throw new FileUploadException("Request was not multipart");
        log.debug("Request was not multipart. Returning from call");
    }

    // create a list to hold all of the files
    List<File> fileList = new ArrayList<File>();
    try {
        // setup the factories and file upload stuff
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(999999999);

        // create a file item iterator to cycle through all of the files in the req. There SHOULD only be one, though
        FileItemIterator iterator = upload.getItemIterator(req);

        // iterate through the file items and create a file item stream to output the file
        while (iterator.hasNext()) {

            // get the file item stream from the iterator
            FileItemStream fileItemStream = iterator.next();

            // Use the Special InputStream type, passing it the stream and the length of the file
            InputStream inputStream = new UploadProgressInputStream(fileItemStream.openStream(), req.getContentLength());

            // create a File from the file name
            String fileName = fileItemStream.getName();  // this only returns the filename, not the full path
            File file = new File(tempDirectory, fileName);

            // add the file to the list
            fileList.add(file);

            // Use commons-io Streams to copy from the inputstrea to a brand-new file
            Streams.copy(inputStream, new FileOutputStream(file), true);

            // close the inputstream
            inputStream.close();

        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // now that we've save the file, we can process it.
    if (fileList.size() == 0) {
        log.debug("No File in the file list. returning.");
        return;
    }

    for (File file : fileList) {

        String fileName = file.getName();
        BufferedReader reader = new BufferedReader(new FileReader(fileName));

        String line = reader.readLine();
        List<Feature> featureList = new ArrayList<Feature>(); // arraylist may not be the best choice since I don't know how many features I'm importing
        while (!line.isEmpty()) {
            String[] splitLine = line.split("|");
            Feature feature = new Feature();
            feature.setId(Integer.parseInt(splitLine[0]));
            feature.setName(splitLine[1]);
            feature.setFeatureClass(splitLine[2]);
            feature.setLat(Double.parseDouble(splitLine[9]));
            feature.setLng(Double.parseDouble(splitLine[10]));
            featureList.add(feature);

            line = reader.readLine();
        }

        file.delete();   // todo: check this to ensure it won't blow up the code since we're iterating in a for each
        reader.close();  // todo: need this in a finally block somewhere to ensure this always happens.

        try {
            featureService.persistList(featureList);
        } catch (ServiceException e) {
            log.debug("Caught Service Exception in FeatureUploadService.", e);

        }
    }
}


问:
.NET Framework And .NET Standard Dependency Problem
I have a .NET Framework 4.7.2 console application, a .NET standard 2.0 business layer and a .NET standard 2.0 data access layer.

When I am trying to access data access layer from console application through the business layer, I am getting errors that say dependency not found. These dependencies are added to the data access layer and these are not related to console application like Dapper, OracleManagedDataAcess etc. If I added these libraries to the console application, it works. But I don't understand why do I have to add data access related libraries to the console application.

By the way if I switch the console application to .NET Core, it works as expected. But my console application has to be .NET framework. Any ideas?

答:
I have found the answer in another post:

Copy all dependencies from .Net Standard libraries to .Net Framework Console application

Adding below line in the first "PropertyGroup" tag of the .net framework console application's ".csproj" file solved my problem.

```<code><RestoreProjectStyle>PackageReference</RestoreProjectStyle>
</code>```

Body:
I have found the answer in another post:

Copy all dependencies from .Net Standard libraries to .Net Framework Console application

Adding below line in the first "PropertyGroup" tag of the .net framework console application's ".csproj" file solved my problem.

<RestoreProjectStyle>PackageReference</RestoreProjectStyle>


问:
MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client
I can't make a simple connection to the server for some reason. I install the newest MySQL Community 8.0 database along with Node.JS with default settings.

This is my node.js code

```<code>    var mysql = require('mysql');

    var con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "password",
      insecureAuth : true
    });

    con.connect(function(err) {
      if (err) throw err;
      console.log("Connected!");
    });
</code>```

Below is the error found in Command Prompt:

```<code>C:\Users\mysql-test>node app.js
    C:\Users\mysql-test\node_modules\mysql\lib\protocol\Parse
    r.js:80
            throw err; // Rethrow non-MySQL errors
            ^

Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
    at Handshake.Sequence._packetToError (C:\Users\mysql-
test\node_modules\mysql\lib\protocol\sequences\Sequence.js:52:14)
    at Handshake.ErrorPacket (C:\Users\mysql-test\node_mo
dules\mysql\lib\protocol\sequences\Handshake.js:130:18)
    at Protocol._parsePacket (C:\Users\mysql-test\node_mo
dules\mysql\lib\protocol\Protocol.js:279:23)
    at Parser.write (C:\Users\mysql-test\node_modules\mys
ql\lib\protocol\Parser.js:76:12)
    at Protocol.write (C:\Users\mysql-test\node_modules\m
ysql\lib\protocol\Protocol.js:39:16)
    at Socket.<anonymous> (C:\Users\mysql-test\node_modul
es\mysql\lib\Connection.js:103:28)
    at Socket.emit (events.js:159:13)
    at addChunk (_stream_readable.js:265:12)
    at readableAddChunk (_stream_readable.js:252:11)
    at Socket.Readable.push (_stream_readable.js:209:10)
    --------------------
    at Protocol._enqueue (C:\Users\mysql-test\node_module
s\mysql\lib\protocol\Protocol.js:145:48)
    at Protocol.handshake (C:\Users\mysql-test\node_modul
es\mysql\lib\protocol\Protocol.js:52:23)
    at Connection.connect (C:\Users\mysql-test\node_modul
es\mysql\lib\Connection.js:130:18)
    at Object.<anonymous> (C:\Users\mysql-test\server.js:
11:5)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
</code>```

I've read up on some things such as:
https://dev.mysql.com/doc/refman/5.5/en/old-client.html
https://github.com/mysqljs/mysql/issues/1507

But I am still not sure how to fix my problem.

答:
Downgrading might not be a good option as:

Its upgraded for a reason (To provide better authentication).

You might not have enough permissions to make such changes.

You can use mysql2 package in place of mysql. Its mostly API compatible with mysqljs.
Also, it has promises support.

Use it like:
const mysql = require('mysql2/promise') (for promise based methods)

You can read more about mysql2 here: https://www.npmjs.com/package/mysql2

Body:
I can't make a simple connection to the server for some reason. I install the newest MySQL Community 8.0 database along with Node.JS with default settings.

This is my node.js code

    var mysql = require('mysql');

    var con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "password",
      insecureAuth : true
    });

    con.connect(function(err) {
      if (err) throw err;
      console.log("Connected!");
    });

Below is the error found in Command Prompt:

C:\Users\mysql-test>node app.js
    C:\Users\mysql-test\node_modules\mysql\lib\protocol\Parse
    r.js:80
            throw err; // Rethrow non-MySQL errors
            ^

Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
    at Handshake.Sequence._packetToError (C:\Users\mysql-
test\node_modules\mysql\lib\protocol\sequences\Sequence.js:52:14)
    at Handshake.ErrorPacket (C:\Users\mysql-test\node_mo
dules\mysql\lib\protocol\sequences\Handshake.js:130:18)
    at Protocol._parsePacket (C:\Users\mysql-test\node_mo
dules\mysql\lib\protocol\Protocol.js:279:23)
    at Parser.write (C:\Users\mysql-test\node_modules\mys
ql\lib\protocol\Parser.js:76:12)
    at Protocol.write (C:\Users\mysql-test\node_modules\m
ysql\lib\protocol\Protocol.js:39:16)
    at Socket.<anonymous> (C:\Users\mysql-test\node_modul
es\mysql\lib\Connection.js:103:28)
    at Socket.emit (events.js:159:13)
    at addChunk (_stream_readable.js:265:12)
    at readableAddChunk (_stream_readable.js:252:11)
    at Socket.Readable.push (_stream_readable.js:209:10)
    --------------------
    at Protocol._enqueue (C:\Users\mysql-test\node_module
s\mysql\lib\protocol\Protocol.js:145:48)
    at Protocol.handshake (C:\Users\mysql-test\node_modul
es\mysql\lib\protocol\Protocol.js:52:23)
    at Connection.connect (C:\Users\mysql-test\node_modul
es\mysql\lib\Connection.js:130:18)
    at Object.<anonymous> (C:\Users\mysql-test\server.js:
11:5)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)

I've read up on some things such as:
https://dev.mysql.com/doc/refman/5.5/en/old-client.html
https://github.com/mysqljs/mysql/issues/1507

But I am still not sure how to fix my problem.


问:
Load *.dylib or *.so into the V8 Javascript runtime?
While not specifically related to Frida's use of V8, I was reading this Frida release page and noticed it made the following reference:

Short of writing the whole agent in C, one could go ahead and build a
  native library, and load it using Module.load(). This works but means
  it has to be compiled for every single architecture, deployed to the
  target, etc.

The comment by Ole alludes to this being possible, though I can't find any references other than the NodeJS C++ Addons features that are, of course, specific to NodeJS (though NodeJS does use V8).

tl;dr
How does one load a generic object such that all of its exported functions are callable from Javascript? Is this possible?

答:
I was misinterpreting the context of the comment in the original link, it seems. I was under the impression that Module.load was a v8-ism, while it in fact appears to be a Frida-API.

https://frida.re/docs/javascript-api/#module

I figured this out about the time I was writing code to use Module.getExportByName to just pass the addresses of dlopen and dlsym to the entry of my CModule code.


问:
Forward locking a downloaded file
I am interested in forward locking a downloaded file (an image, or a video, etc.). Is there any way to do this?

As far as I can tell packages can be forward locked, but their resources remain public. Is there a way to forward lock a specific file I've downloaded to the Android?

答:
This depends.

In order to do that, you need to use a DRM forward lock.

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

http://answers.yahoo.com/question/index?qid=20091231141343AAx7cVS

But doing so isn't quite simple.

Also, if you are an app developer you can download files to a private folder. This should be reasonably safe but I think that people with rooted devices could see the files if they wanted to. Also, be sure to use a secure connection (https) otherwise people could intercept the traffic and reconstruct the file! DRM already addresses this issue.

Title: Forward locking a downloaded file


问:
I'm trying to create a guessing game but it won't work
I'm trying to create a guessing game where you have to guess a number between 1 and 10, however if you enter 0 then it quits the program. I managed to get it to work (minus the quit part) so I tried adding the next step, the quit feature. I'd assume based off the order of the else if that first if you get the correct number then it says "you won the game", which is what happens, however if the answer is wrong it just quits. I'm trying to get it to only quit if the user types in 0 but it quits no matter what number you type in (as long as it's not the right one) I've spent hours and hours trying different things but nothing seems to work. Here's the code:</p>

```<code>public static void main(String[] args) {
    int secretNumber;
    int guess;
    secretNumber = (int) (Math.random() * 9 + 1);

    Scanner keyboard = new Scanner(System.in);
    System.out.print("Guess a number between 1 and 10: ");

    guess = keyboard.nextInt();

    if (guess == secretNumber)

        System.out.println("You won the game");

    else if (guess == 0)

        System.exit(0);

    else

        System.out.println("Invalid guess!");
}
</code>```

答:
Here this function is not recursively running. So it runs only one time and quits. Change your code as follows and try it.</p>

```<code>public static void main(String[] args) {
    guessingGame();
}

public static void guessingGame() {

    int secretNumber;
    int guess;
    secretNumber = (int) (Math.random() * 9 + 1);

    Scanner keyboard = new Scanner(System.in);
    System.out.print("Guess a number between 1 and 10: ");

    guess = keyboard.nextInt();

    if (guess == secretNumber) {

        System.out.println("You won the game");
        guessingGame();
    }
    else if (guess == 0)

        System.exit(0);

    else {

        System.out.println("Invalid guess!");
        guessingGame();
    }
}
</code>```

Body:
I'm trying to create a guessing game where you have to guess a number between 1 and 10, however if you enter 0 then it quits the program. I managed to get it to work (minus the quit part) so I tried adding the next step, the quit feature. I'd assume based off the order of the else if that first if you get the correct number then it says "you won the game", which is what happens, however if the answer is wrong it just quits. I'm trying to get it to only quit if the user types in 0 but it quits no matter what number you type in (as long as it's not the right one) I've spent hours and hours trying different things but nothing seems to work. Here's the code:

public static void main(String[] args) {
    int secretNumber;
    int guess;
    secretNumber = (int) (Math.random() * 9 + 1);

    Scanner keyboard = new Scanner(System.in);
    System.out.print("Guess a number between 1 and 10: ");

    guess = keyboard.nextInt();

    if (guess == secretNumber)

        System.out.println("You won the game");

    else if (guess == 0)

        System.exit(0);

    else

        System.out.println("Invalid guess!");
}

Body:
Here this function is not recursively running. So it runs only one time and quits. Change your code as follows and try it.

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

public static void guessingGame() {

    int secretNumber;
    int guess;
    secretNumber = (int) (Math.random() * 9 + 1);

    Scanner keyboard = new Scanner(System.in);
    System.out.print("Guess a number between 1 and 10: ");

    guess = keyboard.nextInt();

    if (guess == secretNumber) {

        System.out.println("You won the game");
        guessingGame();
    }
    else if (guess == 0)

        System.exit(0);

    else {

        System.out.println("Invalid guess!");
        guessingGame();
    }
}


问:
How to remove CODE parameter from AZURE function API url?
I am new in AZURE. I have created multiple functions in AZURE with API URL. Some function contains API URL with CODE parameter and some are without CODE parameter.
Can any one let me know how to remove the CODE parameter from the API URL?
e.g

```<code>1) With paramter: API_URL?code=oxwOFsfARhzBZpworHGR9cKeN/Mns0L6s4daqQuJft8ui84yYdbOfQ==
2) Without parameter: API_URL
</code>```

Thanks

答:
Check out Azure Function Proxies - https://learn.microsoft.com/en-us/azure/azure-functions/functions-proxies

That should help with presenting a "friendly URL".

Body:
I am new in AZURE. I have created multiple functions in AZURE with API URL. Some function contains API URL with CODE parameter and some are without CODE parameter.
Can any one let me know how to remove the CODE parameter from the API URL?
e.g

1) With paramter: API_URL?code=oxwOFsfARhzBZpworHGR9cKeN/Mns0L6s4daqQuJft8ui84yYdbOfQ==
2) Without parameter: API_URL

Thanks


问:
Flexbox align several items to left, several to the center and several to the right - order should be changeable
I need a CSS solution for the following case:

I have a header with several children, say four. Not all four children have an equal width. Items are by default aligned to the left. I use margin-left and/or margin-right auto to align items to the center/right. I change the order of the items with the CSS order property.

Now I want to align items to the left, center and right of the container. The order of the children should change on viewports (using @media queries).

How do I center an unspecified number of items to the left, to the center and to the right, in different viewport widths?

My (simplified) HTML

```<code><div class="header-container">

 <div class="first-child">
 </div>
 <div class="second-child">
 </div>
 <div class="third-child">
 </div>
 <div class="fourth-child">
 </div>

</div>
</code>```

I've also put my simplified situation in this JSFiddle.

Concrete example of look with viewports

```<code>@media (max-width: 799px) {*

 left: first-child and second-child

 center: third-child

 right: fourth-child

}

@media (max-width: 800px) and (max-width: 1319px) {

 left: third-child

 center: first-child and second-child

 right: fourth-child

}

@media (min-width: 1320px) {

 left: first-child

 center: third-child

 right: second-child

 fourth-child - display: none;

}
</code>```

答:
Firstly you will have to group childs that are for example in the middle:

```<code><div class="grouped-items">
  <div class="second-child">
  </div>
  <div class="third-child">
  </div>
</div>
</code>```

After that, you will have three groups of items or separate items. Use justify-content: space-between

It would look like this (open in full page to see best result):

.header-container {
  width: 100%;
  height: 68px;
  background-color: white;
  display: flex;
  justify-content: space-between;
}

/* Set display: flex so they will act same as if they weren't in another div */

.grouped-items {
  display: flex;
}

.first-child {
  width: 60px;
  height: 100%;
  background-color: red;
}

.second-child {
  width: 80px;
  height: 100%;
  background-color: green;
}

.third-child {
  width: 50px;
  height: 100%;
  background-color: blue;
}

.fourth-child {
  width: 100px;
  height: 100%;
  background-color: black;
}

@media (max-width: 799px) {
  .grouped-items {
    order: 1;
  }
  .third-child {
    order: 2;
  }
  .fourth-child {
    order: 3;
  }
}

@media (min-width: 800px) and (max-width: 1319px) {
  .grouped-items {
    order: 2;
  }
  .third-child {
    order: 1;
  }
  .fourth-child {
    order: 3;
  }
}

@media (min-width: 1320px) {
  .fourth-child {
    display: none;
  }

  .grouped-items {
    order: 2;
  }
  .third-child {
    order: 1;
  }
}

body {
  background-color: grey;
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header-container">

  <div class="grouped-items">
    <div class="first-child">
    </div>
    <div class="second-child">
    </div>
  </div>

  <div class="third-child">
  </div>

  <div class="fourth-child">
  </div>

</div></code>```

To change order on media, just use order

Body:
I need a CSS solution for the following case:

I have a header with several children, say four. Not all four children have an equal width. Items are by default aligned to the left. I use margin-left and/or margin-right auto to align items to the center/right. I change the order of the items with the CSS order property.

Now I want to align items to the left, center and right of the container. The order of the children should change on viewports (using @media queries).

How do I center an unspecified number of items to the left, to the center and to the right, in different viewport widths?

My (simplified) HTML

I've also put my simplified situation in this JSFiddle.

Concrete example of look with viewports

@media (max-width: 799px) {*

 left: first-child and second-child

 center: third-child

 right: fourth-child

}

@media (max-width: 800px) and (max-width: 1319px) {

 left: third-child

 center: first-child and second-child

 right: fourth-child

}

@media (min-width: 1320px) {

 left: first-child

 center: third-child

 right: second-child

 fourth-child - display: none;

}

Body:
Firstly you will have to group childs that are for example in the middle:

<div class="grouped-items">
  <div class="second-child">
  </div>
  <div class="third-child">
  </div>
</div>

After that, you will have three groups of items or separate items. Use justify-content: space-between

It would look like this (open in full page to see best result):

.header-container {
  width: 100%;
  height: 68px;
  background-color: white;
  display: flex;
  justify-content: space-between;
}

/* Set display: flex so they will act same as if they weren't in another div */

.grouped-items {
  display: flex;
}

.first-child {
  width: 60px;
  height: 100%;
  background-color: red;
}

.second-child {
  width: 80px;
  height: 100%;
  background-color: green;
}

.third-child {
  width: 50px;
  height: 100%;
  background-color: blue;
}

.fourth-child {
  width: 100px;
  height: 100%;
  background-color: black;
}

@media (max-width: 799px) {
  .grouped-items {
    order: 1;
  }
  .third-child {
    order: 2;
  }
  .fourth-child {
    order: 3;
  }
}

@media (min-width: 800px) and (max-width: 1319px) {
  .grouped-items {
    order: 2;
  }
  .third-child {
    order: 1;
  }
  .fourth-child {
    order: 3;
  }
}

@media (min-width: 1320px) {
  .fourth-child {
    display: none;
  }

  .grouped-items {
    order: 2;
  }
  .third-child {
    order: 1;
  }
}

body {
  background-color: grey;
  margin: 0;
}

<div class="header-container">

  <div class="grouped-items">
    <div class="first-child">
    </div>
    <div class="second-child">
    </div>
  </div>

  <div class="third-child">
  </div>

  <div class="fourth-child">
  </div>

</div>

To change order on media, just use order


问:
Delay in playing audio (mp3) in iOS 13 safari/chrome browser
Is there a way to reduce (get rid of) the delay in playing audio (mp3) in iOS 13 safari/chrome browser?  I have tried setting preload to "none" and also to "auto" but it doesn't seem to work in anyway. I'm using react h5 audio player.</p>

答:
Try add:

```<code>const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();
</code>```

source: https://stackoverflow.com/a/54119854/2364154 l

Body:
Try add:

const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();

source: https://stackoverflow.com/a/54119854/2364154 l


问:
How does this pointer-based strcat work in C?
I have some basic experience with C, but it usually takes me a little while to figure out how to implement something; using pointers and such is still a bit of a mystery to me.

Then I see an example like strcat implementation and I can't follow along. Would someone mind kindly explaining this to a C newcomer?

```<code>char *
my_strcat(char *dest, const char *src)
{
    char *rdest = dest;

    while (*dest)
      dest++;
    while (*dest++ = *src++)
      ;
    return rdest;
}
</code>```

When I read that, I think "rdest = ?, maybe real destination". So set a pointer to the original destination. Then "while (*dest) dest++;", what is that doing? Same with the next line. I don't follow.

Is it using any additional memory to the original two parts (src and dest)? Like in JS, if you concatenate 2 strings, it creates memory for a third string that combines the two, so you have double the memory. How is this avoided in this C implementation (if it is)?

答:
string is just an array (buffer) of chars. Basically, an array of 8-bit unsigned ints. And the last element in the array is '\0'. The actual array can be much bigger than the string occupying it, and strcat indeed requires that the dest is big enough to contain both the dest string and the source strings together. strcat is not a ready-to-use method like in higher level languages. It's use case looks like this:

char* buffer = malloc(strlen(string1) + strlen(string2) +1) Create a buffer that's big enough to contain both strings.

strpy(buffer, string1) Copy the first string to the buffer

strcat(buffer, string2) Append the second string to the buffer where the first string ends.

++ and -- operators allow a pointer to serve as enumerator. Think of those as .next() and .prev(). The caveat here is that they return (or accept) the value BEFORE moving the enumerator. This is critical here, this basically is what allows C to be so hard ;) If you want to recreate this in higher level, it'll be getAndNext() and setAndNext()

* is an accessor, working both ways, so it's enumerator's getValue() and setValue().

First block just skips the dest buffer until it reaches the end of the string in it - but NOT the end of the buffer.

```<code>while (*dest)
    dest.next();
</code>```

in pseudo-code is:

```<code>while (dest.get() != '\0')
    dest.next();
</code>```

That's because \0 is a real zero in the int meaning, and int zero is false in boolean meaning. Anything non-zero is true. That means -1, 42 and 'A' are just as true as 1. So in C we just skip the != 0 which is as pointless as writing != false in a language that has real booleans.

```<code>while (*dest++ = *src++)
  ;
</code>```

Can be restated as:

```<code>while (dest.setAndNext(src.getAndNext()) != '\0')
</code>```

or without the compounding:

```<code>char value;
do
{
    dest.set(src.get());
    value = src.get();
    src.next();
    dst.next();
}
while (value != '\0');
</code>```

That's because in C an assignment has a value. So (*dest++ = *src++) ultimately returns the character that had been copied. It's like an inline function that copies, advances and then returns what was copied.

A pointer can legally point beyond the array. It's like enumerator that had reached the end and there is nothing more. The big difference is that a high-level enumerator can and will tell you that (via an exception), while a pointer will keep going even though it doesn't make any sense anymore. That's why both src and dest pointers are ++ed one time too many, but we don't care because we've took care to never use them after that.

rdest is simply saved position of where the buffer started. We can't return dest, because that enumerator had been used up and now it's at the end of the string, while we need to return the beginning. "r" probably stands for "return", because the whole point of this variable is to be returned.

Body:
I have some basic experience with C, but it usually takes me a little while to figure out how to implement something; using pointers and such is still a bit of a mystery to me.

Then I see an example like strcat implementation and I can't follow along. Would someone mind kindly explaining this to a C newcomer?

char *
my_strcat(char *dest, const char *src)
{
    char *rdest = dest;

    while (*dest)
      dest++;
    while (*dest++ = *src++)
      ;
    return rdest;
}

When I read that, I think "rdest = ?, maybe real destination". So set a pointer to the original destination. Then "while (*dest) dest++;", what is that doing? Same with the next line. I don't follow.

Is it using any additional memory to the original two parts (src and dest)? Like in JS, if you concatenate 2 strings, it creates memory for a third string that combines the two, so you have double the memory. How is this avoided in this C implementation (if it is)?

Body:
string is just an array (buffer) of chars. Basically, an array of 8-bit unsigned ints. And the last element in the array is '\0'. The actual array can be much bigger than the string occupying it, and strcat indeed requires that the dest is big enough to contain both the dest string and the source strings together. strcat is not a ready-to-use method like in higher level languages. It's use case looks like this:

char* buffer = malloc(strlen(string1) + strlen(string2) +1) Create a buffer that's big enough to contain both strings.

strpy(buffer, string1) Copy the first string to the buffer

strcat(buffer, string2) Append the second string to the buffer where the first string ends.

++ and -- operators allow a pointer to serve as enumerator. Think of those as .next() and .prev(). The caveat here is that they return (or accept) the value BEFORE moving the enumerator. This is critical here, this basically is what allows C to be so hard ;) If you want to recreate this in higher level, it'll be getAndNext() and setAndNext()

* is an accessor, working both ways, so it's enumerator's getValue() and setValue().

First block just skips the dest buffer until it reaches the end of the string in it - but NOT the end of the buffer.

while (*dest)
    dest.next();

in pseudo-code is:

while (dest.get() != '\0')
    dest.next();

That's because \0 is a real zero in the int meaning, and int zero is false in boolean meaning. Anything non-zero is true. That means -1, 42 and 'A' are just as true as 1. So in C we just skip the != 0 which is as pointless as writing != false in a language that has real booleans.

while (*dest++ = *src++)
  ;

Can be restated as:

while (dest.setAndNext(src.getAndNext()) != '\0')

or without the compounding:

char value;
do
{
    dest.set(src.get());
    value = src.get();
    src.next();
    dst.next();
}
while (value != '\0');

That's because in C an assignment has a value. So (*dest++ = *src++) ultimately returns the character that had been copied. It's like an inline function that copies, advances and then returns what was copied.

A pointer can legally point beyond the array. It's like enumerator that had reached the end and there is nothing more. The big difference is that a high-level enumerator can and will tell you that (via an exception), while a pointer will keep going even though it doesn't make any sense anymore. That's why both src and dest pointers are ++ed one time too many, but we don't care because we've took care to never use them after that.

rdest is simply saved position of where the buffer started. We can't return dest, because that enumerator had been used up and now it's at the end of the string, while we need to return the beginning. "r" probably stands for "return", because the whole point of this variable is to be returned.


问:
CSL file not applied everywhere when having two bibliographies
Following this answer about having two bibliographies in an R Markdown document, I just saw that CSL files are not applied everywhere.

Indeed, in the example below:

```<code>---
title: "Cite R packages"
author: ''
date: ""
output:
  pdf_document:
    pandoc_args: --lua-filter=multiple-bibliographies.lua
bibliography_software: packages.bib
bibliography_normal: test.bib
csl: anabases.csl
---

This is a citation of a paper: @mayer2011.
This is a citation of an R package @R-dplyr
And another @R-knitr

# Bibliography{-}
\setlength{\parindent}{-0.2in}
\setlength{\leftskip}{0.2in}
\noindent
<div id = "refs_normal"></div>
\setlength{\parindent}{0in}
\setlength{\leftskip}{0in}
\setlength{\parskip}{0pt}

# Software used{-}
\setlength{\parindent}{-0.2in}
\setlength{\leftskip}{0.2in}
\noindent
<div id = "refs_software"></div>
\setlength{\parindent}{0in}
\setlength{\leftskip}{0in}
\setlength{\parskip}{0pt}

```{r cite-packages, echo=FALSE}

packages_used <- c("dplyr", "ggplot2", "knitr")

knitr::write_bib(packages_used, file = "packages.bib", tweak = TRUE)

```
</code>```

To prevent having a post too long, see here for the contents of multiple-bibliographies.lua and test.bib (packages.bib is created at the end of the .Rmd file).

In this example, I use anabases.csl just because it is easy to see if the csl file was applied or not. You can see what it looks like and download it here. The problem is this R Markdown file applies csl on the citations in text but not on the bibliographies. In the picture below, you can see that capitals are applied on the citations in text but not in the bibliographies, whereas it should be the case.

Why is that? How can I apply csl everywhere in the document?

I think this has to be done in the .lua file but not sure at all.

Also asked on RStudio Community

答:
The solution can be found in the comments of this answer. The only thing to do is to replace:

```<code>local tmp_meta = pandoc.Meta{bibliography = doc_meta['bibliography' .. name]}
</code>```

by

```<code>local tmp_meta = pandoc.Meta{bibliography = doc_meta['bibliography' .. name], csl = doc_meta.csl}
</code>```

in multiple-bibliographies.lua

Body:
Following this answer about having two bibliographies in an R Markdown document, I just saw that CSL files are not applied everywhere.

Indeed, in the example below:

---
title: "Cite R packages"
author: ''
date: ""
output:
  pdf_document:
    pandoc_args: --lua-filter=multiple-bibliographies.lua
bibliography_software: packages.bib
bibliography_normal: test.bib
csl: anabases.csl
---

This is a citation of a paper: @mayer2011.
This is a citation of an R package @R-dplyr
And another @R-knitr

# Bibliography{-}
\setlength{\parindent}{-0.2in}
\setlength{\leftskip}{0.2in}
\noindent

\setlength{\parindent}{0in}
\setlength{\leftskip}{0in}
\setlength{\parskip}{0pt}

# Software used{-}
\setlength{\parindent}{-0.2in}
\setlength{\leftskip}{0.2in}
\noindent

\setlength{\parindent}{0in}
\setlength{\leftskip}{0in}
\setlength{\parskip}{0pt}

```{r cite-packages, echo=FALSE}

packages_used <- c("dplyr", "ggplot2", "knitr")

knitr::write_bib(packages_used, file = "packages.bib", tweak = TRUE)

```

To prevent having a post too long, see here for the contents of multiple-bibliographies.lua and test.bib (packages.bib is created at the end of the .Rmd file).

In this example, I use anabases.csl just because it is easy to see if the csl file was applied or not. You can see what it looks like and download it here. The problem is this R Markdown file applies csl on the citations in text but not on the bibliographies. In the picture below, you can see that capitals are applied on the citations in text but not in the bibliographies, whereas it should be the case.

Why is that? How can I apply csl everywhere in the document?

I think this has to be done in the .lua file but not sure at all.

Also asked on RStudio Community

Body:
The solution can be found in the comments of this answer. The only thing to do is to replace:

local tmp_meta = pandoc.Meta{bibliography = doc_meta['bibliography' .. name]}

by

local tmp_meta = pandoc.Meta{bibliography = doc_meta['bibliography' .. name], csl = doc_meta.csl}

in multiple-bibliographies.lua


问:
How can I adjust DIV width to contents
I have a div element with style attached:

```<code>.mypost {
    border: 1px solid Peru;
    font-family: arial;
    margin: auto;
    min-width: 700px;
    width: 700px;
}
</code>```

I am diplaying WordPress post contents inside the DIV block but for simplicity let assume that there is only one  inside the DIV. I want my div to be minimum 700 px wide and adjust the width if image is wider than 700 px.

What are my options to achieve that? Please advice.

UPDATE

See my Fiddle
http://jsfiddle.net/cpt_comic/4qjXv/

答:
You could try using float:left; or display:inline-block;.

Both of these will change the element's behaviour from defaulting to 100% width to defaulting to the natural width of its contents.

However, note that they'll also both have an impact on the layout of the surrounding elements as well. I would suggest that inline-block will have less of an impact though, so probably best to try that first.

Title: How can I adjust DIV width to contents

Body:
I have a div element with style attached:

.mypost {
    border: 1px solid Peru;
    font-family: arial;
    margin: auto;
    min-width: 700px;
    width: 700px;
}

I am diplaying WordPress post contents inside the DIV block but for simplicity let assume that there is only one  inside the DIV. I want my div to be minimum 700 px wide and adjust the width if image is wider than 700 px.

What are my options to achieve that? Please advice.

UPDATE

See my Fiddle
http://jsfiddle.net/cpt_comic/4qjXv/


问:
Required property doesn't work for array of ObjectId type in mongoose
I have the following schema and model for mongoose:

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    username: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    first_name: String,
    second_name: String,
    roles: { type: [{ type: Schema.Types.ObjectId, ref: 'Role' }], required: true }
});

userSchema.virtual('fullName').get(function() {
    return `${this.first_name} ${this.second_name}`;
});

module.exports = mongoose.model('User', userSchema);
</code>```

I can't get required to work for arrays of ObjectId, when I create an object without the roles field and save it mongoose doesn't throw and error. What am I doing wrong here?

答:
In mongoose V4 the required on the array worked as you wanted.

But in V5 this behavior has been changed.

In mongoose 5 the required validator only verifies if the value is an
  array. That is, it will not fail for empty arrays as it would in
  mongoose 4.

But you can use the validate function to make it work. Returning false or throwing an error means validation failed.

So if you want to validation to fail when the array is null or empty, you can use the following validate function.

```<code>validate: v !== null && v.length > 0
</code>```

Test:

const validate = (v) => {
  return v !== null && v.length > 0;
};

const res1 = validate(null);
console.log(res1); // FALSE  => Validation fails

const res2 = validate([]);
console.log(res2); //FALSE  => Validation fails

const res3 = validate([1, 2]);
console.log(res3); //TRUE
```

Body:
I have the following schema and model for mongoose:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    username: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    first_name: String,
    second_name: String,
    roles: { type: [{ type: Schema.Types.ObjectId, ref: 'Role' }], required: true }
});

userSchema.virtual('fullName').get(function() {
    return `${this.first_name} ${this.second_name}`;
});

module.exports = mongoose.model('User', userSchema);

I can't get required to work for arrays of ObjectId, when I create an object without the roles field and save it mongoose doesn't throw and error. What am I doing wrong here?

Body:
In mongoose V4 the required on the array worked as you wanted.

But in V5 this behavior has been changed.

In mongoose 5 the required validator only verifies if the value is an
  array. That is, it will not fail for empty arrays as it would in
  mongoose 4.

But you can use the validate function to make it work. Returning false or throwing an error means validation failed.

So if you want to validation to fail when the array is null or empty, you can use the following validate function.

validate: v !== null && v.length > 0

Test:

const validate = (v) => {
  return v !== null && v.length > 0;
};

const res1 = validate(null);
console.log(res1); // FALSE  => Validation fails

const res2 = validate([]);
console.log(res2); //FALSE  => Validation fails

const res3 = validate([1, 2]);
console.log(res3); //TRUE


问:
Hide iframe but somehow disengage it
I am creating a website which hosts 360 panaramic photography. I am creating basically a slideshow of 360's using an iframe with tiled thumbnails. When the user clicks on a tile it loads that 360 into the iframe through JS by changing the src value of the iframe.

My issue is bandwidth, If I use the method of loading the src value into the iframe then every time this occurs, it seems to reload the content - looking at my network tab in my browser this does seem to be the case, I can see the image files being reloaded for a second time if the user re-views a tile/iframe.

My other option would be to have multiple iframes and just hide or show them based on which tile was clicked. Maybe using 'display:none'?

However would this then create the issue of multiple 360 panoramic photos running at the same time and being taxing on the users computer/ graphics card? Or would display:none then disengage the iframe from creating work for the graphics card?

Is there anyway to tell whether the iframe has been disengaged when hidden and is no longer taxing the users computer?

And if it is, then is there a way around this somehow? Can an iframe be disengaged so that it isn't running so to speak but it can still be made visible to the user again without reloading the content again.

Thanks, I hope this makes sense.

答:
I think your problem can be solved using two things: Lazy Loading and Visibility.

You can achieve the lazy loading either the native way

```<code><iframe src="your-360-image" loading="lazy"></iframe>
</code>```

or using one of the libraries that does it for you, Iframely and lazyframe are good ones.

You can set the all the iframes to start loading in the background when the user is near them, so by the time the user clicks the tile, it's already loaded.

Regarding that the browser reloads the images, that might be because you set display to none, or even remove the element completely from the DOM. You might just want to hide it by setting the visibility to hidden, this should not re-load it again.

Title: Hide iframe but somehow disengage it

Body:
I think your problem can be solved using two things: Lazy Loading and Visibility.

You can achieve the lazy loading either the native way

<iframe src="your-360-image" loading="lazy"></iframe>

or using one of the libraries that does it for you, Iframely and lazyframe are good ones.

You can set the all the iframes to start loading in the background when the user is near them, so by the time the user clicks the tile, it's already loaded.

Regarding that the browser reloads the images, that might be because you set display to none, or even remove the element completely from the DOM. You might just want to hide it by setting the visibility to hidden, this should not re-load it again.


问:
Casting to unsigned without specifying a type
```<code>#include <stdio.h>

int main(){
  ssize_t a= -1;
  size_t b = (unsigned)a;
  return 0;
}
</code>```

a is 8 bytes all set to 1, however b becomes a 4 byte number when casted to unsigned without doing a proper (unsigned size_t), why is that? why doesn't it turn into an 8 byte unsigned variable?

答:
The C standard sheds some light on this:

In § 6.7.2p2, Type specifiers, "- unsigned, or unsigned int" are in the same list entry, because they are equivalent type specifiers.

Body:
#include <stdio.h>

int main(){
  ssize_t a= -1;
  size_t b = (unsigned)a;
  return 0;
}

a is 8 bytes all set to 1, however b becomes a 4 byte number when casted to unsigned without doing a proper (unsigned size_t), why is that? why doesn't it turn into an 8 byte unsigned variable?


问:
Find the closest pair of points in a given set of points
Q) Find the closest pair of points in a given set of points.

Expected time complexity: O(nlog2(n)) / O(nlog(n))

i was reading up this problem from here. However i am unable to understand a few things:

what do we achieve by sorting points by Y which are already sorted by X?

when we take a point as mid from one of the halves, dont we miss out on a few cases?
i.e. how does taking a mid point ensure that the strip formed
includes all the points that are candidates for a distance less than the distance returned by the two recursive calls?

even if the above point is proved, shouldnt we take the mid point of both halves i.e. m of left half and (m+1) of right half?

答:
2) You use the x coordinate of the mid point to find a line that splits the points in half.  The recursive calls compare all pairs that don't cross that line, so all that remains is to compare pairs that do cross the line.  If two points are less than d apart, and they're on either side of the line, then they must both be less than d away from the line.

3) Well, that will be done in the recursive calls.  I don't know what else you could mean.

1) The points in the strip are separated out and sorted.  Then, given one point in the strip, all the points with y coordinate within d are in a contiguous region around it.  These are the only other points you need to compare it with, and the sorting makes it quick and easy to find these points.  The magic of this algorithm is that the number of possible points in any such region is strictly limited to a constant value.  This follows from the fact (established by the recursive calls) that no pair of points on either side of the line are closer than d.


问:
What data strucutre does *mutableSetOf()* return in Kotlin?
Is it implemented as a HashSet, linked HashSet or binary search tree?

I know it is hidden for encapsulation, but I need to estimate the asymptotic runtime.

答:
Looking up the implementation in my kotlin stdlib installation:

```<code>public inline fun <T> mutableSetOf(): MutableSet<T> = LinkedHashSet()
</code>```

Body:
Looking up the implementation in my kotlin stdlib installation:

public inline fun <T> mutableSetOf(): MutableSet<T> = LinkedHashSet()


问:
How to access section property inside a delegate of DelegateModel
Consider following code:

```<code>import QtQuick 2.0
import QtQuick.Window 2.14
import QtQml.Models 2.2

Window {
    width: 200
    height: 100
    visible: true
    DelegateModel {
        id: visualModel
        model: ListModel {
            ListElement {
                name: "Apple"
            }
            ListElement {
                name: "Orange"
            }
        }
        delegate: Rectangle {
            height: 25
            width: 100
            Text {
                text: "Name: " + name + " Current section: <insert current section here>"  ; // How to get section here
            }
        }
    }

    ListView {
        anchors.fill: parent
        model: visualModel
        section.property: "name"
        section.criteria: ViewSection.FullString
        section.delegate: Text {
            text: section
        }
    }
}
</code>```

here I needed to access attached section property from ListView inside visualModel's delegate, but I can't seem to get it, I tried different combinations like directly accessing it or through model's property but nothing seems to work, any help would be really appreciated

答:
This can be done using https://doc.qt.io/qt-5/qtqml-syntax-objectattributes.html#a-note-about-accessing-attached-properties-and-signal-handlers

basically you have to use this syntax -> <delegate root item>.ListView.section

so above working code will look like this

```<code>import QtQuick 2.0
import QtQuick.Window 2.14
import QtQml.Models 2.2

Window {
    width: 200
    height: 100
    visible: true
    DelegateModel {
        id: visualModel
        model: ListModel {
            ListElement {
                name: "Apple"
            }
            ListElement {
                name: "Orange"
            }
        }
        delegate: Rectangle {
            id: root
            height: 25
            width: 100
            Text {
                text: "Name: " + name + " Current section: " + root.ListView.section  ;
            }
        }
    }

    ListView {
        anchors.fill: parent
        model: visualModel
        section.property: "name"
        section.criteria: ViewSection.FullString
        section.delegate: Text {
            text: section
        }
    }
}
</code>```

Body:
Consider following code:

import QtQuick 2.0
import QtQuick.Window 2.14
import QtQml.Models 2.2

Window {
    width: 200
    height: 100
    visible: true
    DelegateModel {
        id: visualModel
        model: ListModel {
            ListElement {
                name: "Apple"
            }
            ListElement {
                name: "Orange"
            }
        }
        delegate: Rectangle {
            height: 25
            width: 100
            Text {
                text: "Name: " + name + " Current section: <insert current section here>"  ; // How to get section here
            }
        }
    }

    ListView {
        anchors.fill: parent
        model: visualModel
        section.property: "name"
        section.criteria: ViewSection.FullString
        section.delegate: Text {
            text: section
        }
    }
}

here I needed to access attached section property from ListView inside visualModel's delegate, but I can't seem to get it, I tried different combinations like directly accessing it or through model's property but nothing seems to work, any help would be really appreciated

Body:
This can be done using https://doc.qt.io/qt-5/qtqml-syntax-objectattributes.html#a-note-about-accessing-attached-properties-and-signal-handlers

basically you have to use this syntax -> <delegate root item>.ListView.section

so above working code will look like this

import QtQuick 2.0
import QtQuick.Window 2.14
import QtQml.Models 2.2

Window {
    width: 200
    height: 100
    visible: true
    DelegateModel {
        id: visualModel
        model: ListModel {
            ListElement {
                name: "Apple"
            }
            ListElement {
                name: "Orange"
            }
        }
        delegate: Rectangle {
            id: root
            height: 25
            width: 100
            Text {
                text: "Name: " + name + " Current section: " + root.ListView.section  ;
            }
        }
    }

    ListView {
        anchors.fill: parent
        model: visualModel
        section.property: "name"
        section.criteria: ViewSection.FullString
        section.delegate: Text {
            text: section
        }
    }
}


问:
Is it possible to use both an external css stylesheet / js file and an external svg file?
I want to use external css / js files in altering an external svg file, however, upon "importing" the svg file into the html, its "subtags" such as path are not imported, and therefore the css and js cannot alter it.

```<code><!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <object data="map.svg" type="image/svg+xml"></object>
                <script src="map.js"></script>
    </body>
</html>
</code>```

I have seen multiple proposed solutions that I do not see functioning. If anyone could explain these or propose their own I would be thankful.

Inline svg [My map file has over 3000 lines of code, and would be difficult to read the html]

Have a seperate stylesheet for map.svg [I can't seem to have this work]

Have inline css for map.svg [I would like if the files could be separated and I don't see the equivalent for js]

Have a javascript injection [I can't seem to have this work, and I believe this just uses a javascript file to dynamically add the path elements from the svg file, I would be willing to have a separate js file or incorporate it into my html js file, and prefer this method]

Thanks in advance!

答:
If the SVG has the same host as a document you can use getSVGDocument to get SVG document from JavaScript

    <object id="map" data="js.svg" type="image/svg+xml"></object>

```

Body:
I want to use external css / js files in altering an external svg file, however, upon "importing" the svg file into the html, its "subtags" such as path are not imported, and therefore the css and js cannot alter it.

<!DOCTYPE html>

        <link rel="stylesheet" href="style.css">

        <object data="map.svg" type="image/svg+xml"></object>

I have seen multiple proposed solutions that I do not see functioning. If anyone could explain these or propose their own I would be thankful.

Inline svg [My map file has over 3000 lines of code, and would be difficult to read the html]

Have a seperate stylesheet for map.svg [I can't seem to have this work]

Have inline css for map.svg [I would like if the files could be separated and I don't see the equivalent for js]

Have a javascript injection [I can't seem to have this work, and I believe this just uses a javascript file to dynamically add the path elements from the svg file, I would be willing to have a separate js file or incorporate it into my html js file, and prefer this method]

Thanks in advance!

Body:
If the SVG has the same host as a document you can use getSVGDocument to get SVG document from JavaScript

    <object id="map" data="js.svg" type="image/svg+xml"></object>
    <script>
      const mapObject = document.getElementById("map");
      mapObject.addEventListener("load", () => {
        mapObject
          .getSVGDocument()
          .querySelector("path")
          .setAttribute("fill", "red");
      });
    </script>


问:
Function not call when button click
i have create a UIBUtton

```<code>editButton = [[UIButton alloc]initWithFrame:CGRectMake(width, -4, 30, 30)];
        [editButton setImage:[UIImage imageNamed:@"DeleteButton.jpg"] forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
        editButton.hidden = YES;
        [editButton setTag:tag];
        [backView addSubview:editButton];
</code>```

But control not jump to its definition where i check if button give its tag value on click or not.

-

```<code>(void)deleteObjectViewImage
{

    NSInteger index = editButton.tag;
    editButton.hidden = YES;
}
</code>```

Can anyone tell me why it not work please.

答:
For getting Tag Value you have to write this code in Button Click event...

```<code> -(IBAction)deleteObjectViewImage:(id)sender
 {
      UIButton *btn = (UIButton *)sender;
      NSLog(@"%d",btn.tag);
 }
</code>```

Don't remove colon from

```<code> [editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
</code>```

Title: Function not call when button click

Body:
i have create a UIBUtton

editButton = [[UIButton alloc]initWithFrame:CGRectMake(width, -4, 30, 30)];
        [editButton setImage:[UIImage imageNamed:@"DeleteButton.jpg"] forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
        editButton.hidden = YES;
        [editButton setTag:tag];
        [backView addSubview:editButton];

But control not jump to its definition where i check if button give its tag value on click or not.

-

(void)deleteObjectViewImage
{

    NSInteger index = editButton.tag;
    editButton.hidden = YES;
}

Can anyone tell me why it not work please.

Body:
For getting Tag Value you have to write this code in Button Click event...

 -(IBAction)deleteObjectViewImage:(id)sender
 {
      UIButton *btn = (UIButton *)sender;
      NSLog(@"%d",btn.tag);
 }

Don't remove colon from

 [editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];