问:
Can't find a method declared in other java file
I'm Building a todo app, I declared methods in separate java file and when I wanna access them in another java file they are saying 'can't resolve the method'

You can see the whole project at https://github.com/RamcharanS/MyTODO_Be_Productive

Please Help me with this and if possible please check and give a small review on my code

Java file of Methods

```<code>package com.example.mytodo;

public class my_todo {
    String titledoes;
    String datedoes;
    String descdoes;
    String keydoes;

    public my_todo() {
    }

    public my_todo(String titledoes, String datedoes, String descdoes, String keydoes) {
        this.titledoes = titledoes;
        this.datedoes = datedoes;
        this.descdoes = descdoes;
        this.keydoes = keydoes;
    }

    public String getKeydoes() {
        return keydoes;
    }

    public void setKeydoes(String keydoes) {
        this.keydoes = keydoes;
    }

    public String getTitledoes() {
        return titledoes;
    }

    public void setTitledoes(String titledoes) {
        this.titledoes = titledoes;
    }

    public String getDatedoes() {
        return datedoes;
    }

    public void setDatedoes(String datedoes) {
        this.datedoes = datedoes;
    }

    public String getDescdoes() {
        return descdoes;
    }

    public void setDescdoes(String descdoes) {
        this.descdoes = descdoes;
    }
}

</code>```

This is the Java file Giving me Error
Method : getTitledoes() getDescdoes() getDatedoes()

```<code>package com.example.mytodo;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.mytodo.R;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class DoesAdapter extends RecyclerView.Adapter<DoesAdapter.MyViewHolder>{

    Context context;
    ArrayList myDoes;

    public DoesAdapter(Context c, ArrayList p) {
        context = c;
        myDoes = p;
    }

    @NonNull
    @Override
    public  MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i){
    return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.new_todo, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i){
        MyViewHolder.titledoes.setText(myDoes.get(i).getTitledoes());
        MyViewHolder.descdoes.setText(myDoes.get(i).getDescdoes());
        MyViewHolder.datedoes.setText(myDoes.get(i).getDatedoes());
    }

    @Override
    public int getItemCount(){
        return myDoes.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView titledoes, descdoes, datedoes;

        public MyViewHolder(@NonNull View itemView){
            super(itemView);
            titledoes = (TextView) itemView.findViewById(R.id.titledoes);
            descdoes = (TextView) itemView.findViewById(R.id.descdoes);
            datedoes = (TextView) itemView.findViewById(R.id.datedoes);
        }
    }

}

</code>```

答:
Cause for your problem is that you are using ArrayList without specifying generic type, this means that when you get element from list it will be Object and not my_todo, you can simply fix this problem by adding generic type which you want list to be:

change ArrayList myDoes; to List<my_todo> myDoes;

and constructor parameter to List<my_todo> p.

Note that I have used List instead of ArrayList, because it is more abstract type, its best practice to always use most abstract type that is possible in given situation.

UPDATE:

I would gladly explain you how generics work but that would result in quite long answer, seeing that you are beginner I would suggest to find some Java book or online course, most of those cover generics, how they work and how to use them, also you can read this tutorial from Oracle itself

Body:
I'm Building a todo app, I declared methods in separate java file and when I wanna access them in another java file they are saying 'can't resolve the method'

You can see the whole project at https://github.com/RamcharanS/MyTODO_Be_Productive

Please Help me with this and if possible please check and give a small review on my code

Java file of Methods

package com.example.mytodo;

public class my_todo {
    String titledoes;
    String datedoes;
    String descdoes;
    String keydoes;

    public my_todo() {
    }

    public my_todo(String titledoes, String datedoes, String descdoes, String keydoes) {
        this.titledoes = titledoes;
        this.datedoes = datedoes;
        this.descdoes = descdoes;
        this.keydoes = keydoes;
    }

    public String getKeydoes() {
        return keydoes;
    }

    public void setKeydoes(String keydoes) {
        this.keydoes = keydoes;
    }

    public String getTitledoes() {
        return titledoes;
    }

    public void setTitledoes(String titledoes) {
        this.titledoes = titledoes;
    }

    public String getDatedoes() {
        return datedoes;
    }

    public void setDatedoes(String datedoes) {
        this.datedoes = datedoes;
    }

    public String getDescdoes() {
        return descdoes;
    }

    public void setDescdoes(String descdoes) {
        this.descdoes = descdoes;
    }
}

This is the Java file Giving me Error
Method : getTitledoes() getDescdoes() getDatedoes()

package com.example.mytodo;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.mytodo.R;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class DoesAdapter extends RecyclerView.Adapter<DoesAdapter.MyViewHolder>{

    Context context;
    ArrayList myDoes;

    public DoesAdapter(Context c, ArrayList p) {
        context = c;
        myDoes = p;
    }

    @NonNull
    @Override
    public  MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i){
    return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.new_todo, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i){
        MyViewHolder.titledoes.setText(myDoes.get(i).getTitledoes());
        MyViewHolder.descdoes.setText(myDoes.get(i).getDescdoes());
        MyViewHolder.datedoes.setText(myDoes.get(i).getDatedoes());
    }

    @Override
    public int getItemCount(){
        return myDoes.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView titledoes, descdoes, datedoes;

        public MyViewHolder(@NonNull View itemView){
            super(itemView);
            titledoes = (TextView) itemView.findViewById(R.id.titledoes);
            descdoes = (TextView) itemView.findViewById(R.id.descdoes);
            datedoes = (TextView) itemView.findViewById(R.id.datedoes);
        }
    }

}


来源: stackexchange

问:
Sending email from own server to the internets
I have set up an email server on my host. It's basically a SMTP server that listens on port 25.

```<code>const recvServer = new SMTPServer({
  requireTLS: true,
  authOptional: true,
  logger: true,
  onConnect(session, callback) {
    return callback();
  },

  onMailFrom(address, session, callback) {
    console.log('from', address, session);
    return callback();
  },

  onData(stream, session, callback) {
    console.log('new msg');
    let message = '';
    stream.on('data', chunk => {
      message += chunk;
    });

    stream.on('end', () => {

      callback(null, 'Message queued');
      simpleParser(message)
        .then(parsed => {
          console.log(parsed);
          // here I wish to forward the message to outside gmail addresses
        })
        .catch(err => {
          console.log(ee)
        });

    });
  }
});

recvServer.listen(25);

recvServer.on('error', err => {
  console.log(err.message);
});
</code>```

It works fine for receiving emails from outside, like gmail etc.

But I want to be able to send emails outside also, or forward emails that I receive to some gmail addresses.

I know that I can do that using Gmail SMTP servers, but then I need an gmail account and password.

I want to be able to send email with my own server, just like yahoo sends mail to gmail using their own server not gmail accounts :)

答:
You need a MTA (Mail Transfer Agent) in order to send an email.

So the popular options is: Postfix, here a guid how to setup postfix on ubuntu: https://help.ubuntu.com/community/Postfix

Or you can spin up a docker container like: https://hub.docker.com/r/bytemark/smtp/

Then you can use nodemailer to send emails through postfix or docker instance.

And if you want there is a full stack docker image all batteries included: https://github.com/tomav/docker-mailserver

ContentLicense: CC BY-SA 4.0

Body:
I have set up an email server on my host. It's basically a SMTP server that listens on port 25.

const recvServer = new SMTPServer({
  requireTLS: true,
  authOptional: true,
  logger: true,
  onConnect(session, callback) {
    return callback();
  },

  onMailFrom(address, session, callback) {
    console.log('from', address, session);
    return callback();
  },

  onData(stream, session, callback) {
    console.log('new msg');
    let message = '';
    stream.on('data', chunk => {
      message += chunk;
    });

    stream.on('end', () => {

      callback(null, 'Message queued');
      simpleParser(message)
        .then(parsed => {
          console.log(parsed);
          // here I wish to forward the message to outside gmail addresses
        })
        .catch(err => {
          console.log(ee)
        });

    });
  }
});

recvServer.listen(25);

recvServer.on('error', err => {
  console.log(err.message);
});

It works fine for receiving emails from outside, like gmail etc.

But I want to be able to send emails outside also, or forward emails that I receive to some gmail addresses.

I know that I can do that using Gmail SMTP servers, but then I need an gmail account and password.

I want to be able to send email with my own server, just like yahoo sends mail to gmail using their own server not gmail accounts :)


问:
Question about condition check in linklist
If head is a struct type pointer, pointing to the first node in link list then what does while(head) means? Does While loop runs till the head is not equal to NULL? Also what does if(!head) means while checking the condition</p>

答:
If head is a struct type pointer, pointing to the first node in link list then what does while(head) means?

to have

```<code>while(head)
</code>```

is like to have

```<code>while(head != NULL)
</code>```

Does While loop runs till the head is not equal to NULL?

yes (supposing there is nothing allowing to go out of the loop in its body)

Also what does if(!head) means while checking the condition

to have

```<code> if(!head)
</code>```

is like to have

```<code>if(head == NULL)
</code>```

Body:
If head is a struct type pointer, pointing to the first node in link list then what does while(head) means?

to have

while(head)

is like to have

while(head != NULL)

Does While loop runs till the head is not equal to NULL?

yes (supposing there is nothing allowing to go out of the loop in its body)

Also what does if(!head) means while checking the condition

to have

 if(!head)

is like to have

if(head == NULL)


问:
Rails 5.2.3 / Heroku - Why is it not possible to run postgres in production mode with squlite3 in development mode?
I'm using Rails 5.2.3 and I'm getting an application error when I try to view my production app on Heroku pipeline & the following errors when:

I run heroku logs I get: heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"

I run heroku run rails console I get: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile. (LoadError)

I run heroku run rails db:migrate I get: LoadError: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile.

I want to use sqlite3 for development and postgres for production, so why do I need to make the sqlite3 gemfile available in production mode?

Here's my gemfile:

```<code>group :development do
  gem 'sqlite3'
end

group :production do
  gem 'pg'
end
</code>```

Here's my database.yml:

```<code>default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3
</code>```

答:
Your problem is this part:

```<code>production:
  <<: *default
  database: db/production.sqlite3
</code>```

Currently your production is still trying to use sqlite, as this expands to

```<code>production:
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000
  database: db/production.sqlite3
</code>```

And obviously db/production.sqlite3 also suggests a sqlite database

Instead change this section to

```<code>production:
  adapter: postgresql
  host: [your db host]
  database: [your database]
  username: [your username]
  password: [your password]
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000
</code>```

All that being said PostgreSQL is free and you really should not develop again sqlite if you will be deploying to PostgreSQL.

SQLite is great for a proof of concept because it is quick to scale up and easy to tear down with no real external dependencies but if you want to actually build an application and deploy it somewhere you should really be using a production ready database.

Heroku DB config

Heroku Getting started Rails 5

Body:
I'm using Rails 5.2.3 and I'm getting an application error when I try to view my production app on Heroku pipeline & the following errors when:

I run heroku logs I get: heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"

I run heroku run rails console I get: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile. (LoadError)

I run heroku run rails db:migrate I get: LoadError: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile.

I want to use sqlite3 for development and postgres for production, so why do I need to make the sqlite3 gemfile available in production mode?

Here's my gemfile:

group :development do
  gem 'sqlite3'
end

group :production do
  gem 'pg'
end

Here's my database.yml:

default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3

Body:
Your problem is this part:

production:
  <<: *default
  database: db/production.sqlite3

Currently your production is still trying to use sqlite, as this expands to

production:
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000
  database: db/production.sqlite3

And obviously db/production.sqlite3 also suggests a sqlite database

Instead change this section to

production:
  adapter: postgresql
  host: [your db host]
  database: [your database]
  username: [your username]
  password: [your password]
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

All that being said PostgreSQL is free and you really should not develop again sqlite if you will be deploying to PostgreSQL.

SQLite is great for a proof of concept because it is quick to scale up and easy to tear down with no real external dependencies but if you want to actually build an application and deploy it somewhere you should really be using a production ready database.

Heroku DB config

Heroku Getting started Rails 5


问:
apache POI java.lang.NoClassDefFoundError: org/apache/commons/compress/archivers/zip/ZipFile
I try to make word document using Apache POI 4.0.0, but i get error

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError:
    org/apache/commons/compress/archivers/zip/ZipFile     at
    org.apache.poi.openxml4j.opc.OPCPackage.create(OPCPackage.java:365)
      at
    org.apache.poi.xwpf.usermodel.XWPFDocument.newPackage(XWPFDocument.java:158)
      at
    org.apache.poi.xwpf.usermodel.XWPFDocument.(XWPFDocument.java:149)
      at model.Model_dokumen.Cetak(Model_dokumen.java:32)     at
    view.Frame_surat.cetak_dan_simpanActionPerformed(Frame_surat.java:414)
      at view.Frame_surat.access$400(Frame_surat.java:23)     at
    view.Frame_surat$5.actionPerformed(Frame_surat.java:211)  at
    javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
      at
    javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
      at
    javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
      at
    javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
      at
    javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
      at java.awt.Component.processMouseEvent(Component.java:6533)    at
    javax.swing.JComponent.processMouseEvent(JComponent.java:3324)    at
    java.awt.Component.processEvent(Component.java:6298)  at
    java.awt.Container.processEvent(Container.java:2238)  at
    java.awt.Component.dispatchEventImpl(Component.java:4889)     at
    java.awt.Container.dispatchEventImpl(Container.java:2296)     at
    java.awt.Component.dispatchEvent(Component.java:4711)     at
    java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4897)
      at
    java.awt.LightweightDispatcher.processMouseEvent(Container.java:4534)
      at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4475)
      at java.awt.Container.dispatchEventImpl(Container.java:2282)    at
    java.awt.Window.dispatchEventImpl(Window.java:2746)   at
    java.awt.Component.dispatchEvent(Component.java:4711)     at
    java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)    at
    java.awt.EventQueue.access$500(EventQueue.java:97)    at
    java.awt.EventQueue$3.run(EventQueue.java:709)    at
    java.awt.EventQueue$3.run(EventQueue.java:703)    at
    java.security.AccessController.doPrivileged(Native Method)    at
    java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
      at
    java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
      at java.awt.EventQueue$4.run(EventQueue.java:733)   at
    java.awt.EventQueue$4.run(EventQueue.java:731)    at
    java.security.AccessController.doPrivileged(Native Method)    at
    java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
      at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)   at
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
      at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
      at
    java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
      at
    java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
      at
    java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
      at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
    Caused by: java.lang.ClassNotFoundException:
    org.apache.commons.compress.archivers.zip.ZipFile     at
    java.net.URLClassLoader.findClass(URLClassLoader.java:381)    at
    java.lang.ClassLoader.loadClass(ClassLoader.java:424)     at
    sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)     at
    java.lang.ClassLoader.loadClass(ClassLoader.java:357)     ... 43 more
    Blockquote

i following tutorial from this site : tutorials point , and i had trying any solutions from blog, forum, etc. but nothing works for me.
This is my code :

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import view.Frame_surat;

/**
 *
 * @author nasution
 */
public class Model_dokumen {

    public void Cetak(Frame_surat fs) throws Exception {
        try {
            XWPFDocument document = new XWPFDocument();
//            XWPFDocument document = new XWPFDocument();//blank document
            //membuat paragraf

             //membuat dokumen surat keluar
            try (FileOutputStream outputStream = new FileOutputStream(new File("Surat_keluar.docx"))) {
                //membuat paragraf
                XWPFParagraph paragraf = document.createParagraph();
                XWPFRun run = paragraf.createRun();
                run.setText("ini adalah halaman dokumen yg baru saja dibuat menggunakan POI");
                document.write(outputStream);
            }
            JOptionPane.showMessageDialog(null, "Surat keluar berhasil dibuat");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Model_dokumen.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Model_dokumen.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
</code>```

答:
For poi-4.1.0 I had to add these to the classpath:
    dom4j-1.6.jar
    xmlbeans-3.1.0.jar
    commons-collections4-4.3.jar
    commons-compress-1.18.jar
Only then did this work for Excel.xlsx File:</p>

```<code>ExcelWBook = new XSSFWorkbook(ExcelFile);
</code>```

Body:
I try to make word document using Apache POI 4.0.0, but i get error

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError:
    org/apache/commons/compress/archivers/zip/ZipFile     at
    org.apache.poi.openxml4j.opc.OPCPackage.create(OPCPackage.java:365)
      at
    org.apache.poi.xwpf.usermodel.XWPFDocument.newPackage(XWPFDocument.java:158)
      at
    org.apache.poi.xwpf.usermodel.XWPFDocument.(XWPFDocument.java:149)
      at model.Model_dokumen.Cetak(Model_dokumen.java:32)     at
    view.Frame_surat.cetak_dan_simpanActionPerformed(Frame_surat.java:414)
      at view.Frame_surat.access$400(Frame_surat.java:23)     at
    view.Frame_surat$5.actionPerformed(Frame_surat.java:211)  at
    javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
      at
    javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
      at
    javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
      at
    javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
      at
    javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
      at java.awt.Component.processMouseEvent(Component.java:6533)    at
    javax.swing.JComponent.processMouseEvent(JComponent.java:3324)    at
    java.awt.Component.processEvent(Component.java:6298)  at
    java.awt.Container.processEvent(Container.java:2238)  at
    java.awt.Component.dispatchEventImpl(Component.java:4889)     at
    java.awt.Container.dispatchEventImpl(Container.java:2296)     at
    java.awt.Component.dispatchEvent(Component.java:4711)     at
    java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4897)
      at
    java.awt.LightweightDispatcher.processMouseEvent(Container.java:4534)
      at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4475)
      at java.awt.Container.dispatchEventImpl(Container.java:2282)    at
    java.awt.Window.dispatchEventImpl(Window.java:2746)   at
    java.awt.Component.dispatchEvent(Component.java:4711)     at
    java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)    at
    java.awt.EventQueue.access$500(EventQueue.java:97)    at
    java.awt.EventQueue$3.run(EventQueue.java:709)    at
    java.awt.EventQueue$3.run(EventQueue.java:703)    at
    java.security.AccessController.doPrivileged(Native Method)    at
    java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
      at
    java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
      at java.awt.EventQueue$4.run(EventQueue.java:733)   at
    java.awt.EventQueue$4.run(EventQueue.java:731)    at
    java.security.AccessController.doPrivileged(Native Method)    at
    java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
      at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)   at
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
      at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
      at
    java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
      at
    java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
      at
    java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
      at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
    Caused by: java.lang.ClassNotFoundException:
    org.apache.commons.compress.archivers.zip.ZipFile     at
    java.net.URLClassLoader.findClass(URLClassLoader.java:381)    at
    java.lang.ClassLoader.loadClass(ClassLoader.java:424)     at
    sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)     at
    java.lang.ClassLoader.loadClass(ClassLoader.java:357)     ... 43 more
    Blockquote

i following tutorial from this site : tutorials point , and i had trying any solutions from blog, forum, etc. but nothing works for me.
This is my code :

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import view.Frame_surat;

/**
 *
 * @author nasution
 */
public class Model_dokumen {

    public void Cetak(Frame_surat fs) throws Exception {
        try {
            XWPFDocument document = new XWPFDocument();
//            XWPFDocument document = new XWPFDocument();//blank document
            //membuat paragraf

             //membuat dokumen surat keluar
            try (FileOutputStream outputStream = new FileOutputStream(new File("Surat_keluar.docx"))) {
                //membuat paragraf
                XWPFParagraph paragraf = document.createParagraph();
                XWPFRun run = paragraf.createRun();
                run.setText("ini adalah halaman dokumen yg baru saja dibuat menggunakan POI");
                document.write(outputStream);
            }
            JOptionPane.showMessageDialog(null, "Surat keluar berhasil dibuat");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Model_dokumen.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Model_dokumen.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Body:
For poi-4.1.0 I had to add these to the classpath:
    dom4j-1.6.jar
    xmlbeans-3.1.0.jar
    commons-collections4-4.3.jar
    commons-compress-1.18.jar
Only then did this work for Excel.xlsx File:

ExcelWBook = new XSSFWorkbook(ExcelFile);


问:
Create select based on specific column data - using javascript
I am creating a table where in it has too many data and I want to put select option and just filter it, I already got the filter thing in the table  using select, my question is how can I not manually add options to the select?
for example I have a column of dates containing 5 - 01-12-19 , 2 - 01-13-19 and 10 - 01-14-19 the said dates need to be the one in the options, and should only display 3 dates which is 01-12-19,01-13-19,01-14-19, the thing with manually adding options is not the best option because the column of dates are updated day by day.

<select>
  <option></option>
</select>

      Name
      Dates

      A
      01-12-19

      Jas
      01-12-19

      sam
      01-12-19

      James
      01-12-19

      luke
      01-13-19

      lucas
      01-13-19

      laus
      01-13-19

      cals
      01-13-19

      miya
      01-14-19

      lesley
      01-14-19

```

I expect that using javascript the options will automatically fillout by the available dates but will only display in option as one even if there are 10 dates that are the same.

答:
Assuming you're just trying to populate your select option with one of the columns then filter the below table every-time it changes, something like this will work.

const table = document.getElementById('myTable');
const trs = table.querySelectorAll('tbody tr');
const getAllDatesInTable = () => {
  const table = document.getElementById('myTable');
  const trs = table.querySelectorAll('tbody tr');
  const dates = [];
  trs.forEach( tr => {
    const date = tr.querySelector('td:last-child').innerText;
    if (!dates.includes(date)) {
      dates.push(date);
    }
  });

  return dates;
};

const dates = getAllDatesInTable();
const select = document.getElementById('dateFilter');
select.innerHTML = dates.map( d => `<option value=${d}>${d}</option>`);
select.onchange = (e) => {
  const selection = e.target.value;

  trs.forEach( tr => {
    tr.style.display = '';
    const date = tr.querySelector('td:last-child').innerText;
    if (date !== selection) {
      tr.style.display = 'none';
    }
  });
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="dateFilter">
  <option></option>
</select>
<table border="2" id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Dates</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A</td>
      <td>01-12-19</td>
    </tr>
    <tr>
      <td>Jas</td>
      <td>01-12-19</td>
    </tr>
    <tr>
      <td>sam</td>
      <td>01-12-19</td>
    </tr>
    <tr>
      <td>James</td>
      <td>01-12-19</td>
    </tr>
    <tr>
      <td>luke</td>
      <td>01-13-19</td>
    </tr>
    <tr>
      <td>lucas</td>
      <td>01-13-19</td>
    </tr>
    <tr>
      <td>laus</td>
      <td>01-13-19</td>
    </tr>
    <tr>
      <td>cals</td>
      <td>01-13-19</td>
    </tr>
    <tr>
      <td>miya</td>
      <td>01-14-19</td>
    </tr><tr>
      <td>lesley</td>
      <td>01-14-19</td>
    </tr>
  </tbody>
</table></code>```

Body:
I am creating a table where in it has too many data and I want to put select option and just filter it, I already got the filter thing in the table  using select, my question is how can I not manually add options to the select?
for example I have a column of dates containing 5 - 01-12-19 , 2 - 01-13-19 and 10 - 01-14-19 the said dates need to be the one in the options, and should only display 3 dates which is 01-12-19,01-13-19,01-14-19, the thing with manually adding options is not the best option because the column of dates are updated day by day.

<select>
  <option></option>
</select>

      Name
      Dates

      A
      01-12-19

      Jas
      01-12-19

      sam
      01-12-19

      James
      01-12-19

      luke
      01-13-19

      lucas
      01-13-19

      laus
      01-13-19

      cals
      01-13-19

      miya
      01-14-19

      lesley
      01-14-19

I expect that using javascript the options will automatically fillout by the available dates but will only display in option as one even if there are 10 dates that are the same.

Body:
Assuming you're just trying to populate your select option with one of the columns then filter the below table every-time it changes, something like this will work.

const table = document.getElementById('myTable');
const trs = table.querySelectorAll('tbody tr');
const getAllDatesInTable = () => {
  const table = document.getElementById('myTable');
  const trs = table.querySelectorAll('tbody tr');
  const dates = [];
  trs.forEach( tr => {
    const date = tr.querySelector('td:last-child').innerText;
    if (!dates.includes(date)) {
      dates.push(date);
    }
  });

  return dates;
};

const dates = getAllDatesInTable();
const select = document.getElementById('dateFilter');
select.innerHTML = dates.map( d => `<option value=${d}>${d}</option>`);
select.onchange = (e) => {
  const selection = e.target.value;

  trs.forEach( tr => {
    tr.style.display = '';
    const date = tr.querySelector('td:last-child').innerText;
    if (date !== selection) {
      tr.style.display = 'none';
    }
  });
};

<select id="dateFilter">
  <option></option>
</select>
<table border="2" id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Dates</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A</td>
      <td>01-12-19</td>
    </tr>
    <tr>
      <td>Jas</td>
      <td>01-12-19</td>
    </tr>
    <tr>
      <td>sam</td>
      <td>01-12-19</td>
    </tr>
    <tr>
      <td>James</td>
      <td>01-12-19</td>
    </tr>
    <tr>
      <td>luke</td>
      <td>01-13-19</td>
    </tr>
    <tr>
      <td>lucas</td>
      <td>01-13-19</td>
    </tr>
    <tr>
      <td>laus</td>
      <td>01-13-19</td>
    </tr>
    <tr>
      <td>cals</td>
      <td>01-13-19</td>
    </tr>
    <tr>
      <td>miya</td>
      <td>01-14-19</td>
    </tr><tr>
      <td>lesley</td>
      <td>01-14-19</td>
    </tr>
  </tbody>
</table>


问:
/bin/sh: 1: arm-linux-gnueabihf-strip: not found
I am trying to compile FFmpeg for opencv-xilinx but i get an error like this

/bin/sh: 1: arm-linux-gnueabihf-strip: not found
  ffbuild/library.mak:101: recipe for target
  'install-libavdevice-shared' failed make: ***
  [install-libavdevice-shared] Error 127

What can i do any thoughts

before i make install i get a warning.

```<code>WARNING: arm-Linux-gnueabihf-pkg-config not found, library detection may fail.
</code>```

Maybe it helps.

答:
The binutils-arm-linux-gnueabi package solved the issue for me, run the following command:

sudo apt-get install binutils-arm-linux-gnueabi

ContentLicense: CC BY-SA 3.0

Body:
I am trying to compile FFmpeg for opencv-xilinx but i get an error like this

/bin/sh: 1: arm-linux-gnueabihf-strip: not found
  ffbuild/library.mak:101: recipe for target
  'install-libavdevice-shared' failed make: ***
  [install-libavdevice-shared] Error 127

What can i do any thoughts

before i make install i get a warning.

WARNING: arm-Linux-gnueabihf-pkg-config not found, library detection may fail.

Maybe it helps.


问:
Python dictionary or json to PHP Arrary
I've seen multiple threads converting python dictionaries to json but nothing showing how to save a python dictionary or a json array to a PHP array. I have inherited a PHP array file that needs to be modified. I was able to do this thru the help of another thread or two. I know am able to open the existing php array file, make needed changes and store to a python dictionary. I have saved it to a json array file but need to get it to the original format as shown below in order for existing scripts to have access to the data.

```<code><?php
error_reporting(0);
$items=array (
0 =>
array (
'name' => 'Ted',
'size' => 'Large',
'sleeve' => 'Short',
'color' => 'Red',
),

);
$unObiect->items = $items;
$json = json_encode($unObiect);
echo($json);
?>
</code>```

Currently using :

```<code>with open('data.json', 'w') as outfile:
        json.dump(r, outfile, sort_keys=True, indent=4, ensure_ascii=False)
</code>```

Where the r is the python dictionary. The result of this array looks like:

```<code>{
    "items": [
        {
            "name": 'Ted',
            "size": 'Large',
            "sleeve": 'Short,
            "color":  'Red',
        },
</code>```

Is there a way to retain the php array style with either the dictionary or the json array?

The reference duplicate is not the same. I do not wish to parse a json with PHP, I want to use Python to save to PHP array.

EDIT:
Ignore all references to JSON in this thread. I only wish to save a Python dictionary to a PHP array in the format shown.

答:
If your Python is producing the following JSON:

```<code>{
    "items": [
        {
            "name": 'Ted',
            "size": 'Large',
            "sleeve": 'Short,
            "color":  'Red',
        },
</code>```

and you wish to access that data in PHP then you need json_decode():

```<code>$items = json_decode( file_get_contents( '/path/to/my/python/file.json' ), true )[ 'items' ];
</code>```

Title: Python dictionary or json to PHP Arrary

Body:
I've seen multiple threads converting python dictionaries to json but nothing showing how to save a python dictionary or a json array to a PHP array. I have inherited a PHP array file that needs to be modified. I was able to do this thru the help of another thread or two. I know am able to open the existing php array file, make needed changes and store to a python dictionary. I have saved it to a json array file but need to get it to the original format as shown below in order for existing scripts to have access to the data.

<?php
error_reporting(0);
$items=array (
0 =>
array (
'name' => 'Ted',
'size' => 'Large',
'sleeve' => 'Short',
'color' => 'Red',
),

);
$unObiect->items = $items;
$json = json_encode($unObiect);
echo($json);
?>

Currently using :

with open('data.json', 'w') as outfile:
        json.dump(r, outfile, sort_keys=True, indent=4, ensure_ascii=False)

Where the r is the python dictionary. The result of this array looks like:

{
    "items": [
        {
            "name": 'Ted',
            "size": 'Large',
            "sleeve": 'Short,
            "color":  'Red',
        },

Is there a way to retain the php array style with either the dictionary or the json array?

The reference duplicate is not the same. I do not wish to parse a json with PHP, I want to use Python to save to PHP array.

EDIT:
Ignore all references to JSON in this thread. I only wish to save a Python dictionary to a PHP array in the format shown.

Body:
If your Python is producing the following JSON:

{
    "items": [
        {
            "name": 'Ted',
            "size": 'Large',
            "sleeve": 'Short,
            "color":  'Red',
        },

and you wish to access that data in PHP then you need json_decode():

$items = json_decode( file_get_contents( '/path/to/my/python/file.json' ), true )[ 'items' ];


问:
getting error "Expected false to be true"
i have function called sunset that copies the existing array sunsetColors by reference and then changes the first element to "blue". sunset should return the copy of the array.</p>

```<code>
function sunset(){
  let clone =sunsetColors;
clone.splice(0,0,"blue");
  return clone;
}
sunset()
</code>```

答:
This does not copy the array.

let clone =sunsetColors;

At the end of that statement, clone and sunsetColors are both pointing to the same array.

To copy the array, try something such as

let clone = [...sunsetColors];

Or you could copy the array this way

let clone = sunsetColors.slice();

Body:
i have function called sunset that copies the existing array sunsetColors by reference and then changes the first element to "blue". sunset should return the copy of the array.

function sunset(){
  let clone =sunsetColors;
clone.splice(0,0,"blue");
  return clone;
}
sunset()


问:
What is the difference between an abstract class and typescript interface?
I'm new to programming. and can't understand the difference between the abstract class and typescript interface?</p>

答:
One of the main differences is that an interface is just there to tell you the "shape" of your data.  An interface generates no JavaScript code at all.  See the code vs. the generated JS code here

An abstract class is defined as:

Abstract classes are base classes from which other classes may be derived. They may not be instantiated directly. Unlike an interface, an abstract class may contain implementation details for its members. The abstract keyword is used to define abstract classes as well as abstract methods within an abstract class.

via: https://www.typescriptlang.org/docs/handbook/classes.html

With a regular class, you can create a new instance of it like this

class MyClass {
    constructor() {}
}

var a = new MyClass();
```

<p>So that means you can't <code>new</code> an abstract class, you get an error</p>

<pre class="lang-js prettyprint-override"><code>abstract class MyAbstractClass {
    constructor() {}
}

var a = new MyAbstractClass();  //error! "Cannot create an instance of an abstract class.
"
</code>```

Abstract classes are meant to use as a "base class", like this:

abstract class Animal {
    constructor(public legs: number, public sound: string) {
        console.log(`I have ${this.legs} legs and I say "${this.sound}"!`)
    }
}

class Dog extends Animal {
    constructor() {
        super(4, 'bark');
    }
}

class Cat extends Animal {
    constructor() {
        super(4, 'meow');
    }
}

var a = new Dog();//Logs: I have 4 legs and I say "bark"!
var b = new Cat();//Logs: I have 4 legs and I say "meow"!
```

Body:
One of the main differences is that an interface is just there to tell you the "shape" of your data.  An interface generates no JavaScript code at all.  See the code vs. the generated JS code here

An abstract class is defined as:

Abstract classes are base classes from which other classes may be derived. They may not be instantiated directly. Unlike an interface, an abstract class may contain implementation details for its members. The abstract keyword is used to define abstract classes as well as abstract methods within an abstract class.

via: https://www.typescriptlang.org/docs/handbook/classes.html

With a regular class, you can create a new instance of it like this

class MyClass {
    constructor() {}
}

var a = new MyClass();

So that means you can't new an abstract class, you get an error

abstract class MyAbstractClass {
    constructor() {}
}

var a = new MyAbstractClass();  //error! "Cannot create an instance of an abstract class.
"

Abstract classes are meant to use as a "base class", like this:

abstract class Animal {
    constructor(public legs: number, public sound: string) {
        console.log(`I have ${this.legs} legs and I say "${this.sound}"!`)
    }
}

class Dog extends Animal {
    constructor() {
        super(4, 'bark');
    }
}

class Cat extends Animal {
    constructor() {
        super(4, 'meow');
    }
}

var a = new Dog();//Logs: I have 4 legs and I say "bark"!
var b = new Cat();//Logs: I have 4 legs and I say "meow"!


问:
Scala Dependencies
I just downloaded scala and trying to use the IntelliJ IDEA CE and having a number of dependency issues. I have been solving some of the dependancy issues by doing the following. Here is an example.

```<code>libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % "test"
</code>```

was wondering what the correct way to add all of these dependencies is? I am also unsure about how to check the dependency tree before trying to run the file. I apologize if this is a straightforward question just want to make sure that I am adding the dependencies correctly since in the past (using other programming languages) badly adding dependencies has come back to haunt me.

```<code>{file:/Users/user1/IdeaProjects/Hello/}hello/testOnly demo.HelloTest
[info] Updating ...
[warn]  module not found: org.scalatest#scalatest_3.10;3.1.0
[warn] ==== local: tried
[warn]   /Users/user1/.ivy2/local/org.scalatest/scalatest_3.10/3.1.0/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/scalatest/scalatest_3.10/3.1.0/scalatest_3.10-3.1.0.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /Users/user1/.sbt/preloaded/org.scalatest/scalatest_3.10/3.1.0/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////Users/user1/.sbt/preloaded/org/scalatest/scalatest_3.10/3.1.0/scalatest_3.10-3.1.0.pom
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.scalatest#scalatest_3.10;3.1.0: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn]  Note: Unresolved dependencies path:
[warn]      org.scalatest:scalatest_3.10:3.1.0 (/Users/user1/IdeaProjects/Hello/build.sbt#L7-8)
[warn]        +- default:hello_2.12:0.1
[error] sbt.librarymanagement.ResolveException: unresolved dependency: org.scalatest#scalatest_3.10;3.1.0: not found
[error]     at sbt.internal.librarymanagement.IvyActions$.resolveAndRetrieve(IvyActions.scala:332)
[error]     at sbt.internal.librarymanagement.IvyActions$.$anonfun$updateEither$1(IvyActions.scala:208)
[error]     at sbt.internal.librarymanagement.IvySbt$Module.$anonfun$withModule$1(Ivy.scala:239)
[error]     at sbt.internal.librarymanagement.IvySbt.$anonfun$withIvy$1(Ivy.scala:204)
[error]     at sbt.internal.librarymanagement.IvySbt.sbt$internal$librarymanagement$IvySbt$$action$1(Ivy.scala:70)
[error]     at sbt.internal.librarymanagement.IvySbt$$anon$3.call(Ivy.scala:77)
[error]     at xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:95)
[error]     at xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:80)
[error]     at xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:99)
[error]     at xsbt.boot.Using$.withResource(Using.scala:10)
[error]     at xsbt.boot.Using$.apply(Using.scala:9)
[error]     at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:60)
[error]     at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:50)
[error]     at xsbt.boot.Locks$.apply0(Locks.scala:31)
[error]     at xsbt.boot.Locks$.apply(Locks.scala:28)
[error]     at sbt.internal.librarymanagement.IvySbt.withDefaultLogger(Ivy.scala:77)
[error]     at sbt.internal.librarymanagement.IvySbt.withIvy(Ivy.scala:199)
[error]     at sbt.internal.librarymanagement.IvySbt.withIvy(Ivy.scala:196)
[error]     at sbt.internal.librarymanagement.IvySbt$Module.withModule(Ivy.scala:238)
[error]     at sbt.internal.librarymanagement.IvyActions$.updateEither(IvyActions.scala:193)
[error]     at sbt.librarymanagement.ivy.IvyDependencyResolution.update(IvyDependencyResolution.scala:20)
[error]     at sbt.librarymanagement.DependencyResolution.update(DependencyResolution.scala:56)
[error]     at sbt.internal.LibraryManagement$.resolve$1(LibraryManagement.scala:45)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$12(LibraryManagement.scala:93)
[error]     at sbt.util.Tracked$.$anonfun$lastOutput$1(Tracked.scala:68)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$19(LibraryManagement.scala:106)
[error]     at scala.util.control.Exception$Catch.apply(Exception.scala:224)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$11(LibraryManagement.scala:106)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$11$adapted(LibraryManagement.scala:89)
[error]     at sbt.util.Tracked$.$anonfun$inputChanged$1(Tracked.scala:149)
[error]     at sbt.internal.LibraryManagement$.cachedUpdate(LibraryManagement.scala:120)
[error]     at sbt.Classpaths$.$anonfun$updateTask$5(Defaults.scala:2561)
[error]     at scala.Function1.$anonfun$compose$1(Function1.scala:44)
[error]     at sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:40)
[error]     at sbt.std.Transform$$anon$4.work(System.scala:67)
[error]     at sbt.Execute.$anonfun$submit$2(Execute.scala:269)
[error]     at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)
[error]     at sbt.Execute.work(Execute.scala:278)
[error]     at sbt.Execute.$anonfun$submit$1(Execute.scala:269)
[error]     at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:178)
[error]     at sbt.CompletionService$$anon$2.call(CompletionService.scala:37)
[error]     at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
[error]     at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
[error]     at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
[error]     at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
[error]     at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
[error]     at java.base/java.lang.Thread.run(Thread.java:835)
[error] (update) sbt.librarymanagement.ResolveException: unresolved dependency: org.scalatest#scalatest_3.10;3.1.0: not found
[error] Total time: 2 s, completed May 31, 2019, 2:29:57 PM
</code>```

Thank you so much for your help. To reiterate what is the most correct way to download and manage Scale/IntelliJ IDEA CE dependencies?

答: add a new plugin addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.9.2") . then you can sbt dependencyTree

Title: Scala Dependencies

Body:
I just downloaded scala and trying to use the IntelliJ IDEA CE and having a number of dependency issues. I have been solving some of the dependancy issues by doing the following. Here is an example.

libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % "test"

was wondering what the correct way to add all of these dependencies is? I am also unsure about how to check the dependency tree before trying to run the file. I apologize if this is a straightforward question just want to make sure that I am adding the dependencies correctly since in the past (using other programming languages) badly adding dependencies has come back to haunt me.

{file:/Users/user1/IdeaProjects/Hello/}hello/testOnly demo.HelloTest
[info] Updating ...
[warn]  module not found: org.scalatest#scalatest_3.10;3.1.0
[warn] ==== local: tried
[warn]   /Users/user1/.ivy2/local/org.scalatest/scalatest_3.10/3.1.0/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/scalatest/scalatest_3.10/3.1.0/scalatest_3.10-3.1.0.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /Users/user1/.sbt/preloaded/org.scalatest/scalatest_3.10/3.1.0/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////Users/user1/.sbt/preloaded/org/scalatest/scalatest_3.10/3.1.0/scalatest_3.10-3.1.0.pom
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.scalatest#scalatest_3.10;3.1.0: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn]  Note: Unresolved dependencies path:
[warn]      org.scalatest:scalatest_3.10:3.1.0 (/Users/user1/IdeaProjects/Hello/build.sbt#L7-8)
[warn]        +- default:hello_2.12:0.1
[error] sbt.librarymanagement.ResolveException: unresolved dependency: org.scalatest#scalatest_3.10;3.1.0: not found
[error]     at sbt.internal.librarymanagement.IvyActions$.resolveAndRetrieve(IvyActions.scala:332)
[error]     at sbt.internal.librarymanagement.IvyActions$.$anonfun$updateEither$1(IvyActions.scala:208)
[error]     at sbt.internal.librarymanagement.IvySbt$Module.$anonfun$withModule$1(Ivy.scala:239)
[error]     at sbt.internal.librarymanagement.IvySbt.$anonfun$withIvy$1(Ivy.scala:204)
[error]     at sbt.internal.librarymanagement.IvySbt.sbt$internal$librarymanagement$IvySbt$$action$1(Ivy.scala:70)
[error]     at sbt.internal.librarymanagement.IvySbt$$anon$3.call(Ivy.scala:77)
[error]     at xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:95)
[error]     at xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:80)
[error]     at xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:99)
[error]     at xsbt.boot.Using$.withResource(Using.scala:10)
[error]     at xsbt.boot.Using$.apply(Using.scala:9)
[error]     at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:60)
[error]     at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:50)
[error]     at xsbt.boot.Locks$.apply0(Locks.scala:31)
[error]     at xsbt.boot.Locks$.apply(Locks.scala:28)
[error]     at sbt.internal.librarymanagement.IvySbt.withDefaultLogger(Ivy.scala:77)
[error]     at sbt.internal.librarymanagement.IvySbt.withIvy(Ivy.scala:199)
[error]     at sbt.internal.librarymanagement.IvySbt.withIvy(Ivy.scala:196)
[error]     at sbt.internal.librarymanagement.IvySbt$Module.withModule(Ivy.scala:238)
[error]     at sbt.internal.librarymanagement.IvyActions$.updateEither(IvyActions.scala:193)
[error]     at sbt.librarymanagement.ivy.IvyDependencyResolution.update(IvyDependencyResolution.scala:20)
[error]     at sbt.librarymanagement.DependencyResolution.update(DependencyResolution.scala:56)
[error]     at sbt.internal.LibraryManagement$.resolve$1(LibraryManagement.scala:45)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$12(LibraryManagement.scala:93)
[error]     at sbt.util.Tracked$.$anonfun$lastOutput$1(Tracked.scala:68)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$19(LibraryManagement.scala:106)
[error]     at scala.util.control.Exception$Catch.apply(Exception.scala:224)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$11(LibraryManagement.scala:106)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$11$adapted(LibraryManagement.scala:89)
[error]     at sbt.util.Tracked$.$anonfun$inputChanged$1(Tracked.scala:149)
[error]     at sbt.internal.LibraryManagement$.cachedUpdate(LibraryManagement.scala:120)
[error]     at sbt.Classpaths$.$anonfun$updateTask$5(Defaults.scala:2561)
[error]     at scala.Function1.$anonfun$compose$1(Function1.scala:44)
[error]     at sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:40)
[error]     at sbt.std.Transform$$anon$4.work(System.scala:67)
[error]     at sbt.Execute.$anonfun$submit$2(Execute.scala:269)
[error]     at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)
[error]     at sbt.Execute.work(Execute.scala:278)
[error]     at sbt.Execute.$anonfun$submit$1(Execute.scala:269)
[error]     at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:178)
[error]     at sbt.CompletionService$$anon$2.call(CompletionService.scala:37)
[error]     at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
[error]     at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
[error]     at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
[error]     at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
[error]     at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
[error]     at java.base/java.lang.Thread.run(Thread.java:835)
[error] (update) sbt.librarymanagement.ResolveException: unresolved dependency: org.scalatest#scalatest_3.10;3.1.0: not found
[error] Total time: 2 s, completed May 31, 2019, 2:29:57 PM

Thank you so much for your help. To reiterate what is the most correct way to download and manage Scale/IntelliJ IDEA CE dependencies?


问:
Comparing objects based on the values of multiple fields using Comparator
How can I improve the comparator for objects by several fields? The comparator must sort user by last name or first name if last name doesn't exist. And if there are no last name and first name sort by username. But these users must be at the end of the list.

```<code>public static Comparator<UserConfigurationDto> BY_LASTNAME =  (u1, u2) -> {
        // if users have only username compare them
        if((u1.getLastName().isEmpty() && u1.getFirstName().isEmpty())
                && (u2.getLastName().isEmpty() && u2.getFirstName().isEmpty())){
            return u1.getUsername().compareToIgnoreCase(u2.getUsername());
        }
        //if user doesnt have firstName and LastName drop them at the end
        if(u1.getLastName().isEmpty() && u1.getFirstName().isEmpty()){
            return 1000000 + getWeight(u1.getUsername());
        }
        if(u2.getLastName().isEmpty() && u2.getFirstName().isEmpty()){
            return -1000000 + getWeight(u2.getUsername());
        }
      String s1 = u1.getLastName().isEmpty() ? u1.getFirstName() : u1.getLastName();
      String s2 = u2.getLastName().isEmpty() ? u2.getFirstName() : u2.getLastName();
      return s1.compareToIgnoreCase(s2);
    };
}
private static int getWeight(String s){
    return s.codePoints().sum();
}
</code>```

Does anybody have an idea how to improve this? I try to use Comparator.comparing and Comparator.thenComparing but they produce an incorrect result

答:
1) return 1000000 + getWeight(u1.getUsername()); and                 return -1000000 + getWeight(u2.getUsername()); are not required. return 1 and return -1 is clearer and produces the same result if you refer to the CompareTo() javadoc :

Compares this object with the specified object for order. Returns a
  negative integer, zero, or a positive integer as this object is less
  than, equal to, or greater than the specified object

2) You don't chain the field comparisons but you have 3 ways of sorting according to the state of the compared objects.  So the fact that the code be a bit verbose to define each case is finally normal.

You could all the same reduce it with an extract method as you duplicate a lot of user.getLastName().isEmpty() invocations.

For example :

```<code>public static Comparator<UserConfigurationDto> BY_LASTNAME =  (u1, u2) -> {

        // first case
        if( u1.isLastAndFirstNameEmpty() && u2.isLastAndFirstNameEmpty()){
            return u1.getUsername().compareToIgnoreCase(u2.getUsername());
        }
        // second case
        if(u1.isLastAndFirstNameEmpty()){
            return 1;
        }
        else if(u2.isLastAndFirstNameEmpty()){
            return -1;
        }
        // third case
        String s1 = u1.getLastName().isEmpty() ? u1.getFirstName() : u1.getLastName();
        String s2 = u2.getLastName().isEmpty() ? u2.getFirstName() : u2.getLastName();
        return s1.compareToIgnoreCase(s2);
    };
</code>```

Body:
How can I improve the comparator for objects by several fields? The comparator must sort user by last name or first name if last name doesn't exist. And if there are no last name and first name sort by username. But these users must be at the end of the list.

public static Comparator<UserConfigurationDto> BY_LASTNAME =  (u1, u2) -> {
        // if users have only username compare them
        if((u1.getLastName().isEmpty() && u1.getFirstName().isEmpty())
                && (u2.getLastName().isEmpty() && u2.getFirstName().isEmpty())){
            return u1.getUsername().compareToIgnoreCase(u2.getUsername());
        }
        //if user doesnt have firstName and LastName drop them at the end
        if(u1.getLastName().isEmpty() && u1.getFirstName().isEmpty()){
            return 1000000 + getWeight(u1.getUsername());
        }
        if(u2.getLastName().isEmpty() && u2.getFirstName().isEmpty()){
            return -1000000 + getWeight(u2.getUsername());
        }
      String s1 = u1.getLastName().isEmpty() ? u1.getFirstName() : u1.getLastName();
      String s2 = u2.getLastName().isEmpty() ? u2.getFirstName() : u2.getLastName();
      return s1.compareToIgnoreCase(s2);
    };
}
private static int getWeight(String s){
    return s.codePoints().sum();
}

Does anybody have an idea how to improve this? I try to use Comparator.comparing and Comparator.thenComparing but they produce an incorrect result

Body:
1) return 1000000 + getWeight(u1.getUsername()); and                 return -1000000 + getWeight(u2.getUsername()); are not required. return 1 and return -1 is clearer and produces the same result if you refer to the CompareTo() javadoc :

Compares this object with the specified object for order. Returns a
  negative integer, zero, or a positive integer as this object is less
  than, equal to, or greater than the specified object

2) You don't chain the field comparisons but you have 3 ways of sorting according to the state of the compared objects.  So the fact that the code be a bit verbose to define each case is finally normal.

You could all the same reduce it with an extract method as you duplicate a lot of user.getLastName().isEmpty() invocations.

For example :

public static Comparator<UserConfigurationDto> BY_LASTNAME =  (u1, u2) -> {

        // first case
        if( u1.isLastAndFirstNameEmpty() && u2.isLastAndFirstNameEmpty()){
            return u1.getUsername().compareToIgnoreCase(u2.getUsername());
        }
        // second case
        if(u1.isLastAndFirstNameEmpty()){
            return 1;
        }
        else if(u2.isLastAndFirstNameEmpty()){
            return -1;
        }
        // third case
        String s1 = u1.getLastName().isEmpty() ? u1.getFirstName() : u1.getLastName();
        String s2 = u2.getLastName().isEmpty() ? u2.getFirstName() : u2.getLastName();
        return s1.compareToIgnoreCase(s2);
    };


问:
Jqvmap how to make svg resize with the div and zoom buttons work
I am trying to make a simple website where you can see a map and click on the different countries.

I use bootstrap for the look and want to use jqvmap for the map.

I have read that it can be tricky to make the map adjust dynamically to the resize of a window but I really need to make it work. For now I managed to make the dimensions of the
 adapt to the size of the window but I don't know how to make the svg adapt as well. It may be linked, the zoom in and out button do not work either even with enableZoom: true parameter.

When I look at the console I have the errors bellow but I found no solution when searching them on internet:

```<code>Error: <g> attribute transform: Expected number, "…le(0) translate(Infinity, 0)".
</code>```

and

```<code>Error: <g> attribute transform: Expected number, "scale(NaN) translate(0…".
</code>```

They are pretty similar and I guess they are coming from the same issue.

This tag <g transform="scale(NaN) translate(NaN, NaN)"> is the direct child of the <svg> tag. I have tried to use jQuery to modify this attribute and make wild guesses but I guessed wrong.

Here is my code :

```<code>    <head>
    .
    .
    .
        <script type="text/javascript">
            var ratio=0.60;
            $(document).ready(function() {
                $('#vmapWorld').vectorMap({
                    map: 'world_en',
                    backgroundColor: null,
                    color: '#ffffff',
                    hoverOpacity: 0.7,
                    selectedColor: '#666666',
                    enableZoom: true
                });
                $("#vmapWorld > svg").css("height", $(this).width()*ratio);
            });
            $(window).resize(function(){
                $("#vmapWorld > svg").css("height", $(this).width()*ratio);
            });
        </script>
    </head>
    <body style="background-color: #a5bfdd">
        <div class="container-fluid" id="vmapWorld" style="background-color: #16982a">
        </div>
    </body>
</code>```

Any help is welcomed.

答:
Try specifying both the width and the height for your container-fluid element.

I've seen the same issue, and by specifying those, the error went away. It seems you can't use a element without those to store your map, as it would be considered infinite. I haven't looked deeper onto the code to see why this happens, but if someone else faces this issue, let me know how it goes.

Hope this helps.

Body:
I am trying to make a simple website where you can see a map and click on the different countries.

I use bootstrap for the look and want to use jqvmap for the map.

I have read that it can be tricky to make the map adjust dynamically to the resize of a window but I really need to make it work. For now I managed to make the dimensions of the
 adapt to the size of the window but I don't know how to make the svg adapt as well. It may be linked, the zoom in and out button do not work either even with enableZoom: true parameter.

When I look at the console I have the errors bellow but I found no solution when searching them on internet:

Error: <g> attribute transform: Expected number, "…le(0) translate(Infinity, 0)".

and

Error: <g> attribute transform: Expected number, "scale(NaN) translate(0…".

They are pretty similar and I guess they are coming from the same issue.

This tag <g transform="scale(NaN) translate(NaN, NaN)"> is the direct child of the <svg> tag. I have tried to use jQuery to modify this attribute and make wild guesses but I guessed wrong.

Here is my code :

    .
    .
    .

Any help is welcomed.


问:
TargetFolderName with space character (char)
I'm using visual studio templates in order to build a custom visual studio template project. I'm trying to create a folder with a name «External Models» that has space char but the visual studio is creating a folder with the name «External%20Models» replacing the space by %20.

Follows my .vstemplate file:

```<code><VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">

<TemplateData>
   ...
</TemplateData>

<TemplateContent>

  <Project TargetFileName="Product.Models.csproj" File="Product.Models.csproj" ReplaceParameters="true">

    ...

    <Folder Name="GeneratedCode" TargetFolderName="GeneratedCode">
        ...
    </Folder>
    <Folder Name="External Models" TargetFolderName="External Models">
      <Folder Name="CorePatterns" TargetFolderName="CorePatterns">
        ...
      </Folder>
    </Folder>
  </Project>
</TemplateContent>

<WizardExtension>
    ...
</WizardExtension>
</code>```

And the content of the .vsix files generated:

答:
I changed from this:

```<code><Folder Name="External Models" TargetFolderName="External Models">
  <Folder Name="CorePatterns" TargetFolderName="CorePatterns">
        ...
  </Folder>
</Folder>
</code>```

To this, and start to work.

```<code><Folder Name="ExternalModels" TargetFolderName="External Models">
  <Folder Name="CorePatterns" TargetFolderName="CorePatterns">
        ...
  </Folder>
</Folder>
</code>```

Explanation:

It does not matter which folders are generated to create the .vsix installer. What is matter is TargetFolderName="External Models" tag name which will generate the project folder (during the Visual Studio->File->Create new project). By changing the Name="External Models" to Name="ExternalModels" and, in the template project that generate the .vsix, change the name of the folder "External Models" to "ExternalModels" everithing will work fine.

Body:
I'm using visual studio templates in order to build a custom visual studio template project. I'm trying to create a folder with a name «External Models» that has space char but the visual studio is creating a folder with the name «External%20Models» replacing the space by %20.

Follows my .vstemplate file:

<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">

<TemplateData>
   ...
</TemplateData>

<TemplateContent>

  <Project TargetFileName="Product.Models.csproj" File="Product.Models.csproj" ReplaceParameters="true">

    ...

    <Folder Name="GeneratedCode" TargetFolderName="GeneratedCode">
        ...
    </Folder>
    <Folder Name="External Models" TargetFolderName="External Models">
      <Folder Name="CorePatterns" TargetFolderName="CorePatterns">
        ...
      </Folder>
    </Folder>
  </Project>
</TemplateContent>

<WizardExtension>
    ...
</WizardExtension>

And the content of the .vsix files generated:

Body:
I changed from this:

<Folder Name="External Models" TargetFolderName="External Models">
  <Folder Name="CorePatterns" TargetFolderName="CorePatterns">
        ...
  </Folder>
</Folder>

To this, and start to work.

<Folder Name="ExternalModels" TargetFolderName="External Models">
  <Folder Name="CorePatterns" TargetFolderName="CorePatterns">
        ...
  </Folder>
</Folder>

Explanation:

It does not matter which folders are generated to create the .vsix installer. What is matter is TargetFolderName="External Models" tag name which will generate the project folder (during the Visual Studio->File->Create new project). By changing the Name="External Models" to Name="ExternalModels" and, in the template project that generate the .vsix, change the name of the folder "External Models" to "ExternalModels" everithing will work fine.


问:
How to activate a wookbook named in a different module
I call module2 from module1 where I name a workbook "x" in module2. But later when I try "x.Activate" in module1 I get an error "Run-time error '424': Object required"

I have a rather lengthy module that I would like to organize by breaking it up into multiple modules. So far I have created a module called "INPUTS" in this module I have a "Sub RT_CMM_DATA_COMPILER_INPUTS()" presumably in the future I will have other Subs in this module "Sub RT_Some_Other_Project_INPUTS()" I name a workbook in "Sub RT_CMM_DATA_COMPILER_INPUTS()" and try to activate that workbook by name in a separate module called sandbox. But it displays an error.

```<code>'RT_Sandbox Module
Sub sandbox()

    Call RT_CMM_DATA_COMPILER_INPUTS

    wkbwatchFolders_table.Activate
    lastShtRow = LASTSHEETROW(ActiveSheet)

    MsgBox lastShtRow

End Sub

'Inputs module
Sub RT_CMM_DATA_COMPILER_INPUTS()

    watchFolders_filePath = "D:\RT_CMM_Data_File_Paths.xlsx"
    Set wkbwatchFolders_table = Workbooks.Open(Filename:=watchFolders_filePath)

End Sub
</code>```

Am I going about this attempt to organize my code completely wrong? Should I be using class modules for this instead? Or is it just some syntax I am missing?

答:
The critical part you're missing is Option Explicit at the top of every module.

With that option, code will refuse to compile until all variables are explicitly declared.

Without it, watchFolders_filePath is an undeclared variable in both  procedures, and in the scope where it is read but not assigned, its data type is Variant/Empty.

Rubberduck (free, open-source VBIDE add-in project that I manage) can help locate and fix these issues (and others) in your code:

OptionExplicit inspection

UnassignedVariableUsage inspection

UndeclaredVariable inspection

VariableNotAssigned inspection

VariableNotUsed inspection

As for your code, you don't need any global variables. Avoid global variables whenever possible. Use functions (and parameters) instead:

```<code>Function RT_CMM_DATA_COMPILER_INPUTS() As Workbook
    Dim watchFolders_filePath As String
    watchFolders_filePath = "D:\RT_CMM_Data_File_Paths.xlsx"
    Set RT_CMM_DATA_COMPILER_INPUTS = Workbooks.Open(Filename:=watchFolders_filePath)
End Function
</code>```

```<code>Sub sandbox()

    Dim wb As Workbook
    Set wb = RT_CMM_DATA_COMPILER_INPUTS
    wb.Activate
    lastShtRow = LASTSHEETROW(wb.ActiveSheet)

    MsgBox lastShtRow

End Sub
</code>```

Body:
I call module2 from module1 where I name a workbook "x" in module2. But later when I try "x.Activate" in module1 I get an error "Run-time error '424': Object required"

I have a rather lengthy module that I would like to organize by breaking it up into multiple modules. So far I have created a module called "INPUTS" in this module I have a "Sub RT_CMM_DATA_COMPILER_INPUTS()" presumably in the future I will have other Subs in this module "Sub RT_Some_Other_Project_INPUTS()" I name a workbook in "Sub RT_CMM_DATA_COMPILER_INPUTS()" and try to activate that workbook by name in a separate module called sandbox. But it displays an error.

'RT_Sandbox Module
Sub sandbox()

    Call RT_CMM_DATA_COMPILER_INPUTS

    wkbwatchFolders_table.Activate
    lastShtRow = LASTSHEETROW(ActiveSheet)

    MsgBox lastShtRow

End Sub

'Inputs module
Sub RT_CMM_DATA_COMPILER_INPUTS()

    watchFolders_filePath = "D:\RT_CMM_Data_File_Paths.xlsx"
    Set wkbwatchFolders_table = Workbooks.Open(Filename:=watchFolders_filePath)

End Sub

Am I going about this attempt to organize my code completely wrong? Should I be using class modules for this instead? Or is it just some syntax I am missing?

Body:
The critical part you're missing is Option Explicit at the top of every module.

With that option, code will refuse to compile until all variables are explicitly declared.

Without it, watchFolders_filePath is an undeclared variable in both  procedures, and in the scope where it is read but not assigned, its data type is Variant/Empty.

Rubberduck (free, open-source VBIDE add-in project that I manage) can help locate and fix these issues (and others) in your code:

OptionExplicit inspection

UnassignedVariableUsage inspection

UndeclaredVariable inspection

VariableNotAssigned inspection

VariableNotUsed inspection

As for your code, you don't need any global variables. Avoid global variables whenever possible. Use functions (and parameters) instead:

Function RT_CMM_DATA_COMPILER_INPUTS() As Workbook
    Dim watchFolders_filePath As String
    watchFolders_filePath = "D:\RT_CMM_Data_File_Paths.xlsx"
    Set RT_CMM_DATA_COMPILER_INPUTS = Workbooks.Open(Filename:=watchFolders_filePath)
End Function

Sub sandbox()

    Dim wb As Workbook
    Set wb = RT_CMM_DATA_COMPILER_INPUTS
    wb.Activate
    lastShtRow = LASTSHEETROW(wb.ActiveSheet)

    MsgBox lastShtRow

End Sub


问:
Routing - WebAPI and MVC in one project
I have 2 controllers. Both dealing with Bar (a child of Foo).

One of them is for MVC which returns views.

```<code>[Route("Foo/Bar")]
public class FooBarController : ControllerBase
{
    public IActionResult Index()
    {
        // ...
    }

    public IActionResult SomeAction()
    {
        // ...
    }
}
</code>```

One of them is for the API, which exists under a folder of "api".

```<code>[Route("api/Foo/Bar")]
[ApiController]
public class FooBarAPIController : ControllerBase
{
    //
}
</code>```

Without adding the following line to the FooBarController class, I can access the API controller (for example: /api/foo/bar/{id}), and the MVC controller (for example: /FooBar/SomeAction)

[Route("Foo/Bar")]

But when I do, routing is messed up and I get the following error trying to access /Foo/Bar/SomeAction

AmbiguousMatchException: The request matched multiple endpoints. Matches:

Controllers.MVC.FooBarController.Index

Controllers.MVC.FooBarController.SomeAction

答:
For your API controller, I recommend changing Route to RoutePrefix["api"], this way all of your api methods would then contain just the route (hopefully a different name than what you have for your Home Controller.

```<code>[RoutePrefix("api")]
public class MyApiController : ApiController
{
    [HttpGet, Route("foo/bar")]
    public IHttpActionResult GetSomething()
    {
        //do something when routing to /api/foo/bar
    }

    [HttpPost, Route("foobar/foobar")]
    public IHttpActionResult GetSomething()
    {
        //do something when routing to /api/foobar/foobar
    }
}
</code>```

Same advice goes to your HomeController (if you really want to add a route to it, and every method within that class will be routed according to their method name eg. Index)

```<code>[RoutePrefix("foo/bar")]
public class MyController : BaseController
{
    public IActionResult Index()
    {
        return View(); //or something
    }

    public IHttpActionResult Contact()
    {
        return View(); //or something
    }
}
</code>```

Title: Routing - WebAPI and MVC in one project

Body:
I have 2 controllers. Both dealing with Bar (a child of Foo).

One of them is for MVC which returns views.

[Route("Foo/Bar")]
public class FooBarController : ControllerBase
{
    public IActionResult Index()
    {
        // ...
    }

    public IActionResult SomeAction()
    {
        // ...
    }
}

One of them is for the API, which exists under a folder of "api".

[Route("api/Foo/Bar")]
[ApiController]
public class FooBarAPIController : ControllerBase
{
    //
}

Without adding the following line to the FooBarController class, I can access the API controller (for example: /api/foo/bar/{id}), and the MVC controller (for example: /FooBar/SomeAction)

[Route("Foo/Bar")]

But when I do, routing is messed up and I get the following error trying to access /Foo/Bar/SomeAction

AmbiguousMatchException: The request matched multiple endpoints. Matches:

Controllers.MVC.FooBarController.Index

Controllers.MVC.FooBarController.SomeAction

Body:
For your API controller, I recommend changing Route to RoutePrefix["api"], this way all of your api methods would then contain just the route (hopefully a different name than what you have for your Home Controller.

[RoutePrefix("api")]
public class MyApiController : ApiController
{
    [HttpGet, Route("foo/bar")]
    public IHttpActionResult GetSomething()
    {
        //do something when routing to /api/foo/bar
    }

    [HttpPost, Route("foobar/foobar")]
    public IHttpActionResult GetSomething()
    {
        //do something when routing to /api/foobar/foobar
    }
}

Same advice goes to your HomeController (if you really want to add a route to it, and every method within that class will be routed according to their method name eg. Index)

[RoutePrefix("foo/bar")]
public class MyController : BaseController
{
    public IActionResult Index()
    {
        return View(); //or something
    }

    public IHttpActionResult Contact()
    {
        return View(); //or something
    }
}


问:
Getting erros about Build CSS when i try to build my project
Evey time i run build i get these errors on this project i am using material kit and its dependencies may be one of the dependencies are old someone please help I have been on this for days and I am feeling really defeated. I have installed react-scripts and ran react-scripts Build but to no avail

```<code>npm ERR! missing script: build-css
npm ERR!
npm ERR! Did you mean this?
npm ERR!     build

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2019-05-31T00_03_48_444Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! material-kit-react@1.4.0 build: `npm run build-css && react-scripts build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the material-kit-react@1.4.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2019-05-31T00_03_48_505Z-debug.log
</code>```

I would like to run npm run build-css but i dont want to break y code

Packages.json file---!

```<code> {
      "name": "material-kit-react",
      "version": "1.4.0",
      "description": "Material Kit React. Coded by Creative Tim",
      "private": true,
      "main": "dist/index.js",
      "dependencies": {
        "@material-ui/core": "3.9.2",
        "@material-ui/icons": "3.0.2",
        "classnames": "2.2.6",
        "history": "4.7.2",
        "moment": "2.24.0",
        "node-sass": "4.11.0",
        "nouislider": "13.1.0",
        "prop-types": "15.7.1",
        "react": "16.8.1",
        "react-datetime": "2.16.3",
        "react-dom": "16.8.1",
        "react-router-dom": "4.3.1",
        "react-scripts": "2.1.5",
        "react-slick": "0.23.2",
        "react-swipeable-views": "0.13.1"
      },
      "devDependencies": {
        "@babel/cli": "7.2.3",
        "@babel/plugin-proposal-class-properties": "7.3.0",
        "@babel/preset-env": "7.3.1",
        "@babel/preset-react": "7.0.0"
      },
      "optionalDependencies": {
        "eslint-config-prettier": "4.0.0",
        "eslint-plugin-prettier": "3.0.1"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "npm run build-css && react-scripts build",
        "test": "react-scripts test --env=jsdom",
        "eject": "react-scripts eject",
        "lint:check": "eslint . --ext=js,jsx;  exit 0",
        "lint:fix": "eslint . --ext=js,jsx --fix;  exit 0",
        "install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && npm install && npm start",
        "build-package-css": "node-sass src/assets/scss/material-kit-react.scss dist/material-kit-react.css",
        "build-package": "npm run build-package-css && babel src --out-dir dist",
        "compile-sass": "node-sass src/assets/scss/material-kit-react.scss src/assets/css/material-kit-react.css",
        "minify-sass": "node-sass src/assets/scss/material-kit-react.scss src/assets/css/material-kit-react.min.css --output-style compressed",
        "map-sass": "node-sass src/assets/scss/material-kit-react.scss src/assets/css/material-kit-react.css --source-map true"
      },
      "browserslist": [
        ">0.2%",
        "not dead",
        "not ie <= 11",
        "not op_mini all"
      ]
    }
</code>```

I expect my build folder to be built

答:
To solve this, change the build script to:

```<code>"build": "react-scripts build"
</code>```

Reference: https://github.com/creativetimofficial/material-kit-react/issues/52

Body:
Evey time i run build i get these errors on this project i am using material kit and its dependencies may be one of the dependencies are old someone please help I have been on this for days and I am feeling really defeated. I have installed react-scripts and ran react-scripts Build but to no avail

npm ERR! missing script: build-css
npm ERR!
npm ERR! Did you mean this?
npm ERR!     build

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2019-05-31T00_03_48_444Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! material-kit-react@1.4.0 build: `npm run build-css && react-scripts build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the material-kit-react@1.4.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2019-05-31T00_03_48_505Z-debug.log

I would like to run npm run build-css but i dont want to break y code

Packages.json file---!

 {
      "name": "material-kit-react",
      "version": "1.4.0",
      "description": "Material Kit React. Coded by Creative Tim",
      "private": true,
      "main": "dist/index.js",
      "dependencies": {
        "@material-ui/core": "3.9.2",
        "@material-ui/icons": "3.0.2",
        "classnames": "2.2.6",
        "history": "4.7.2",
        "moment": "2.24.0",
        "node-sass": "4.11.0",
        "nouislider": "13.1.0",
        "prop-types": "15.7.1",
        "react": "16.8.1",
        "react-datetime": "2.16.3",
        "react-dom": "16.8.1",
        "react-router-dom": "4.3.1",
        "react-scripts": "2.1.5",
        "react-slick": "0.23.2",
        "react-swipeable-views": "0.13.1"
      },
      "devDependencies": {
        "@babel/cli": "7.2.3",
        "@babel/plugin-proposal-class-properties": "7.3.0",
        "@babel/preset-env": "7.3.1",
        "@babel/preset-react": "7.0.0"
      },
      "optionalDependencies": {
        "eslint-config-prettier": "4.0.0",
        "eslint-plugin-prettier": "3.0.1"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "npm run build-css && react-scripts build",
        "test": "react-scripts test --env=jsdom",
        "eject": "react-scripts eject",
        "lint:check": "eslint . --ext=js,jsx;  exit 0",
        "lint:fix": "eslint . --ext=js,jsx --fix;  exit 0",
        "install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && npm install && npm start",
        "build-package-css": "node-sass src/assets/scss/material-kit-react.scss dist/material-kit-react.css",
        "build-package": "npm run build-package-css && babel src --out-dir dist",
        "compile-sass": "node-sass src/assets/scss/material-kit-react.scss src/assets/css/material-kit-react.css",
        "minify-sass": "node-sass src/assets/scss/material-kit-react.scss src/assets/css/material-kit-react.min.css --output-style compressed",
        "map-sass": "node-sass src/assets/scss/material-kit-react.scss src/assets/css/material-kit-react.css --source-map true"
      },
      "browserslist": [
        ">0.2%",
        "not dead",
        "not ie <= 11",
        "not op_mini all"
      ]
    }

I expect my build folder to be built

Body:
To solve this, change the build script to:

"build": "react-scripts build"

Reference: https://github.com/creativetimofficial/material-kit-react/issues/52


答:
Where you're going wrong is trying to apply the idea of a "weight". When dealing with Comparators in Java, the only values that matter coming out of the function are 0, greater than 0, and less than 0.

Something like this seems to work:

```<code>public static final Comparator<UserConfgurationDto> BY_LASTNAME = ( u1, u2 ) ->
{
    boolean u1hasName = !u1.getLastName().isEmpty() || !u1.getFirstName().isEmpty();
    boolean u2hasName = !u2.getLastName().isEmpty() || !u2.getFirstName().isEmpty();

    if ( u1hasName && !u2hasName )
    {
        // u1 < u2
        return -1;
    }
    else if ( !u1hasName && u2hasName )
    {
        // u2 < u1
        return 1;
    }
    else if ( u1hasName && u2hasName )
    {
        String s1 = u1.getLastName().isEmpty() ? u1.getFirstName() : u1.getLastName();
        String s2 = u2.getLastName().isEmpty() ? u2.getFirstName() : u2.getLastName();

        return s1.compareToIgnoreCase( s2 );
    }
    else
    {
        return u1.getUsername().compareToIgnoreCase( u2.getUsername() );
    }
};
</code>```

Title: Comparing objects based on the values of multiple fields using Comparator

Body:
Where you're going wrong is trying to apply the idea of a "weight". When dealing with Comparators in Java, the only values that matter coming out of the function are 0, greater than 0, and less than 0.

Something like this seems to work:

public static final Comparator<UserConfgurationDto> BY_LASTNAME = ( u1, u2 ) ->
{
    boolean u1hasName = !u1.getLastName().isEmpty() || !u1.getFirstName().isEmpty();
    boolean u2hasName = !u2.getLastName().isEmpty() || !u2.getFirstName().isEmpty();

    if ( u1hasName && !u2hasName )
    {
        // u1 < u2
        return -1;
    }
    else if ( !u1hasName && u2hasName )
    {
        // u2 < u1
        return 1;
    }
    else if ( u1hasName && u2hasName )
    {
        String s1 = u1.getLastName().isEmpty() ? u1.getFirstName() : u1.getLastName();
        String s2 = u2.getLastName().isEmpty() ? u2.getFirstName() : u2.getLastName();

        return s1.compareToIgnoreCase( s2 );
    }
    else
    {
        return u1.getUsername().compareToIgnoreCase( u2.getUsername() );
    }
};


问:
Find and print num of solutions to x1+x2+x3=num
I need to write a recusive function that recive an integer num and returns the number of solutions to the equation :x1 + x2 + x3 = num, where x1,x2,x3 are numbers between 1-10, the method should print all solutions.

For example if num=3 then the method will print 1+1+1 and will return 1.

if num=5 the method will return 6 and will print:

```<code>1 + 1 + 3
1 + 2 + 2
1 + 3 + 1
2 + 1 + 2
2 + 2 + 1
3 + 1 + 1
</code>```

if num<3 or num>30 the method will return 0.

The method should be recursive without using loops. Global variables are not allowed. Lists are also not allowed.

Here my code, it works fine but it also prints duplicates, for num=5 it prints:

```<code>3 + 1 + 1
2 + 2 + 1
2 + 1 + 2
2 + 2 + 1
1 + 3 + 1
1 + 2 + 2
2 + 1 + 2
1 + 2 + 2
1 + 1 + 3
</code>```

Here is my code:

```<code>public static void main(String[] args) {
    System.out.println("num of solutions: "+solutions(5));

}

public static int solutions(int num)
{

    if (num < 3 || num > 30)
        return 0;

    return solutions(num, 1, 1, 1);
}
private static int solutions(int num, int x1, int x2, int x3)
{
    if (x1 < 1 || x1 > 10 || x2 < 1 || x2 > 10||x3 < 1 || x3 > 10)
        return 0;
    if (x1 + x2 + x3 > num)
        return 0;
    if (x1 + x2 + x3 == num)
    {
        System.out.println(x1 + " + " + x2 + " + " + x3);
        return 1;
    }
    return solutions(num, x1 + 1, x2, x3) + solutions(num, x1, x2 + 1, x3) + solutions(num, x1, x2, x3 + 1);

}
</code>```

How do I get the desired output without duplicates?

答:
The reason why you're getting duplicates is that both solutions(1,2,1) and solutions(2,1,1) will lead you to 2 + 2 + 1.

The trivial way of not getting duplicate for three digits is count up from 111 to 10,10,10 as if it was a decimal integer:

```<code>private static int solutions(int num, int x1, int x2, int x3)
{
  if (x1 > 10 || x1 > num)
    return 0;
  if (x2 > 10 || x1+x2 > num)
    return solutions(num, x1+1, 1, 1);
  if (x3 > 10 || x1+x2+x3 > num)
    return solutions(num, x1, x2+1, 1);

  int me = 0;
  if (x1+x2+x3 == num) {
    System.out.printf("%d + %d + %d\n", x1, x2, x3);
    me=1;
  }
  return me + solutions(num, x1, x2, x3+1);
}
</code>```

This mimics your approach of searching through the full space with pruning, but a more efficient solution could just search through x1 and x2 and set x3=num-x1-x2.

Body:
I need to write a recusive function that recive an integer num and returns the number of solutions to the equation :x1 + x2 + x3 = num, where x1,x2,x3 are numbers between 1-10, the method should print all solutions.

For example if num=3 then the method will print 1+1+1 and will return 1.

if num=5 the method will return 6 and will print:

1 + 1 + 3
1 + 2 + 2
1 + 3 + 1
2 + 1 + 2
2 + 2 + 1
3 + 1 + 1

if num<3 or num>30 the method will return 0.

The method should be recursive without using loops. Global variables are not allowed. Lists are also not allowed.

Here my code, it works fine but it also prints duplicates, for num=5 it prints:

3 + 1 + 1
2 + 2 + 1
2 + 1 + 2
2 + 2 + 1
1 + 3 + 1
1 + 2 + 2
2 + 1 + 2
1 + 2 + 2
1 + 1 + 3

Here is my code:

public static void main(String[] args) {
    System.out.println("num of solutions: "+solutions(5));

}

public static int solutions(int num)
{

    if (num < 3 || num > 30)
        return 0;

    return solutions(num, 1, 1, 1);
}
private static int solutions(int num, int x1, int x2, int x3)
{
    if (x1 < 1 || x1 > 10 || x2 < 1 || x2 > 10||x3 < 1 || x3 > 10)
        return 0;
    if (x1 + x2 + x3 > num)
        return 0;
    if (x1 + x2 + x3 == num)
    {
        System.out.println(x1 + " + " + x2 + " + " + x3);
        return 1;
    }
    return solutions(num, x1 + 1, x2, x3) + solutions(num, x1, x2 + 1, x3) + solutions(num, x1, x2, x3 + 1);

}

How do I get the desired output without duplicates?

Body:
The reason why you're getting duplicates is that both solutions(1,2,1) and solutions(2,1,1) will lead you to 2 + 2 + 1.

The trivial way of not getting duplicate for three digits is count up from 111 to 10,10,10 as if it was a decimal integer:

private static int solutions(int num, int x1, int x2, int x3)
{
  if (x1 > 10 || x1 > num)
    return 0;
  if (x2 > 10 || x1+x2 > num)
    return solutions(num, x1+1, 1, 1);
  if (x3 > 10 || x1+x2+x3 > num)
    return solutions(num, x1, x2+1, 1);

  int me = 0;
  if (x1+x2+x3 == num) {
    System.out.printf("%d + %d + %d\n", x1, x2, x3);
    me=1;
  }
  return me + solutions(num, x1, x2, x3+1);
}

This mimics your approach of searching through the full space with pruning, but a more efficient solution could just search through x1 and x2 and set x3=num-x1-x2.


问:
awk ignore quoted delimiters `echo 'a "b1 b2" c'| awk '{print $2}'`
The following will output "b1 as it recognizes the quoted space as a field delimiter. How do I tell awk to ignore quoted delimiters so that this would output b1 b2 or "b1 b2"

echo 'a "b1 b2" c'| awk '{print $2}'
```

I see the following two related posts, but I'm having trouble getting the solutions to work. I was hoping to find a simple solution. Field parsing is awk's specialty, right?

awk ignore delimiter inside single quote within a parenthesis
What's the most robust way to efficiently parse CSV using awk?

答:
With gawk (GNU awk) you can use the FPAT special variable to define how a field looks like instead of being limited to specify a delimiter:

```<code>echo 'a "b1 b2" c'| gawk '{print $2}' FPAT='("[^"]+")|[^[:blank:]]+'
</code>```

Here we say: A field is either a " followed by non " chars and a closing " -> ("[^"]+")
... or | a sequence of non-blank chars -> [^[:blank:]]+

These regexes will be evaluated in order, therefore a field enclosed in "" has precedence over the second pattern, the sequence of non blank chars (awk's default).

See GNU awk manual: Defining fields by content

Body:
The following will output "b1 as it recognizes the quoted space as a field delimiter. How do I tell awk to ignore quoted delimiters so that this would output b1 b2 or "b1 b2"

echo 'a "b1 b2" c'| awk '{print $2}'

I see the following two related posts, but I'm having trouble getting the solutions to work. I was hoping to find a simple solution. Field parsing is awk's specialty, right?

awk ignore delimiter inside single quote within a parenthesis
What's the most robust way to efficiently parse CSV using awk?

Body:
With gawk (GNU awk) you can use the FPAT special variable to define how a field looks like instead of being limited to specify a delimiter:

echo 'a "b1 b2" c'| gawk '{print $2}' FPAT='("[^"]+")|[^[:blank:]]+'

Here we say: A field is either a " followed by non " chars and a closing " -> ("[^"]+")
... or | a sequence of non-blank chars -> [^[:blank:]]+

These regexes will be evaluated in order, therefore a field enclosed in "" has precedence over the second pattern, the sequence of non blank chars (awk's default).

See GNU awk manual: Defining fields by content


问:
Google OAuth 2 authorization - Error: redirect_uri_mismatch
On the website https://code.google.com/apis/console I have registered my application, set up generated Client ID: and Client Secret to my app and tried to log in with Google.
Unfortunately, I got the error message:

```<code>Error: redirect_uri_mismatch
The redirect URI in the request: http://127.0.0.1:3000/auth/google_oauth2/callback did not match a registered redirect URI

scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email
response_type=code
redirect_uri=http://127.0.0.1:3000/auth/google_oauth2/callback
access_type=offline
approval_prompt=force
client_id=generated_id
</code>```

What does mean this message, and how can I fix it?
I use the gem omniauth-google-oauth2.

答:
I had this problem using Meteor and Ngrok, while trying to login with Google.
I put the Ngrok URL in the Google Developer Console as redirect URLs, and went to the Ngrok URL page. The thing was that I didn't use Meteor's ROOT_URL when executing the app, so any redirect would go to localhost:3000 insted of the Ngrok URL.
Just fixed it by adding the Ngrok URL as ROOT_URL on Meteor's configuration or by exporting it before executing the app on the terminal like: export ROOT_URL=https://my_ngrok_url

Body:
On the website https://code.google.com/apis/console I have registered my application, set up generated Client ID: and Client Secret to my app and tried to log in with Google.
Unfortunately, I got the error message:

Error: redirect_uri_mismatch
The redirect URI in the request: http://127.0.0.1:3000/auth/google_oauth2/callback did not match a registered redirect URI

scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email
response_type=code
redirect_uri=http://127.0.0.1:3000/auth/google_oauth2/callback
access_type=offline
approval_prompt=force
client_id=generated_id

What does mean this message, and how can I fix it?
I use the gem omniauth-google-oauth2.