问:
Unsolvable reason behind Connection Timeout
Server Code

```<code>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using Global;
using System.IO;

namespace Server
{
    class Program
    {
        static List<string> BlackList = new List<string>();
        static List<TcpClient> Clients = new List<TcpClient>();
        static object _lock = new object();
        static BinaryFormatter Formatter = new BinaryFormatter();

        static TcpListener Server;
        static void Main(string[] args)
        {
            Init();
            Console.ReadLine();
        }

        /*
         * Initiate the server and start listening
         */
        static void Init()
        {
            Server = new TcpListener(IPAddress.Any, 7777);
            Server.Start();
            Task.Factory.StartNew(() => Listen());
        }

        /*
         * Listens to new incoming connections
         * Assigns the new client a worker who will listen to it's requests
         * Add the client to the list of active clients
         */
        static void Listen()
        {
            for (;;)
            {
                TcpClient client = Server.AcceptTcpClient();
                lock(_lock)
                    Clients.Add(client);
                Task.Factory.StartNew(() => Work(client));
                Thread.Sleep(100);
            }
        }

        /*
         * Listens to incoming requests from a client and sends a response back if necessary
         * On disconnect remove client from active clients list
         */
        static void Work(TcpClient client)
        {
            while (client.Connected)
            {
                NetworkStream stream = client.GetStream();
                try
                {
                    dynamic request = Formatter.Deserialize(stream);
                    Response response = HandleRequest(request);
                    if(response != null)
                        Formatter.Serialize(stream, response);
                }
                catch(Exception ex)
                {
                    Console.Write(ex.Message);
                }
            }
            lock (_lock)
                Clients.Remove(client);
        }

        /*
         * Handles File Transfer Requests
         */
        static Response HandleRequest(FileTransferRequest request)
        {
            string file = request.File;

            FileTransferResponse response;
            if (File.Exists($"{Environment.CurrentDirectory}\\{file}"))
                response = new FileTransferResponse(File.ReadAllBytes(file));
            else
                response = new FileTransferResponse(null);

            return response;
        }
    }
}
</code>```

Client Code

```<code>using System;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using Global;
using System.IO;

namespace Client
{
    class Program
    {
        static TcpClient Server;
        static void Main(string[] args)
        {
            string file = args[0];
            string output = args[1];
            Init();

            NetworkStream stream = Server.GetStream();
            BinaryFormatter formatter = new BinaryFormatter();

            //Request
            FileTransferRequest request = new FileTransferRequest(file);
            formatter.Serialize(stream, request);

            //Get Response
            FileTransferResponse response = (FileTransferResponse) formatter.Deserialize(stream);

            if (response.File == null)
                Console.Write("File not found");
            else
            {
                File.WriteAllBytes(output, response.File);
                Console.Write("Success");
            }
            Console.ReadLine();
        }
        static void Init()
        {
            try
            {
                Server = new TcpClient("lordfrostbyte.webhop.me", 7777);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                Environment.Exit(-1);
            }
        }
    }
}
</code>```

Global Library Code

```<code>namespace Global
{
    [Serializable]
    public abstract class Request
    {

    }
    [Serializable]
    public class FileTransferRequest : Request
    {
        public string File;
        public FileTransferRequest(string File)
        {
            this.File = File;
        }
    }
    [Serializable]
    public abstract class Response
    {

    }
    [Serializable]
    public class FileTransferResponse : Response
    {
        public byte[] File;
        public FileTransferResponse(byte[] File)
        {
            this.File = File;
        }
    }
}
</code>```

This is my code... It's not working !

But I have configured port forwarding

I have also disabled my firewall

My guess is something is wrong with windows. However I do not want to format my computer in order to solve this. I would much appreciate any input that would lead to solving this issue. I have had this issue for a while and I was wondering if anyone else has had a similar issue and if anyone has ever solved this. At the moment I have no clue how to even troubleshoot this issue. Do note that if I host the server on LAN and connect to LAN it works perfectly.

答: I had to reinstall pcap drivers.</p>

Body:
Server Code

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using Global;
using System.IO;

namespace Server
{
    class Program
    {
        static List<string> BlackList = new List<string>();
        static List<TcpClient> Clients = new List<TcpClient>();
        static object _lock = new object();
        static BinaryFormatter Formatter = new BinaryFormatter();

        static TcpListener Server;
        static void Main(string[] args)
        {
            Init();
            Console.ReadLine();
        }

        /*
         * Initiate the server and start listening
         */
        static void Init()
        {
            Server = new TcpListener(IPAddress.Any, 7777);
            Server.Start();
            Task.Factory.StartNew(() => Listen());
        }

        /*
         * Listens to new incoming connections
         * Assigns the new client a worker who will listen to it's requests
         * Add the client to the list of active clients
         */
        static void Listen()
        {
            for (;;)
            {
                TcpClient client = Server.AcceptTcpClient();
                lock(_lock)
                    Clients.Add(client);
                Task.Factory.StartNew(() => Work(client));
                Thread.Sleep(100);
            }
        }

        /*
         * Listens to incoming requests from a client and sends a response back if necessary
         * On disconnect remove client from active clients list
         */
        static void Work(TcpClient client)
        {
            while (client.Connected)
            {
                NetworkStream stream = client.GetStream();
                try
                {
                    dynamic request = Formatter.Deserialize(stream);
                    Response response = HandleRequest(request);
                    if(response != null)
                        Formatter.Serialize(stream, response);
                }
                catch(Exception ex)
                {
                    Console.Write(ex.Message);
                }
            }
            lock (_lock)
                Clients.Remove(client);
        }

        /*
         * Handles File Transfer Requests
         */
        static Response HandleRequest(FileTransferRequest request)
        {
            string file = request.File;

            FileTransferResponse response;
            if (File.Exists($"{Environment.CurrentDirectory}\\{file}"))
                response = new FileTransferResponse(File.ReadAllBytes(file));
            else
                response = new FileTransferResponse(null);

            return response;
        }
    }
}

Client Code

using System;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using Global;
using System.IO;

namespace Client
{
    class Program
    {
        static TcpClient Server;
        static void Main(string[] args)
        {
            string file = args[0];
            string output = args[1];
            Init();

            NetworkStream stream = Server.GetStream();
            BinaryFormatter formatter = new BinaryFormatter();

            //Request
            FileTransferRequest request = new FileTransferRequest(file);
            formatter.Serialize(stream, request);

            //Get Response
            FileTransferResponse response = (FileTransferResponse) formatter.Deserialize(stream);

            if (response.File == null)
                Console.Write("File not found");
            else
            {
                File.WriteAllBytes(output, response.File);
                Console.Write("Success");
            }
            Console.ReadLine();
        }
        static void Init()
        {
            try
            {
                Server = new TcpClient("lordfrostbyte.webhop.me", 7777);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                Environment.Exit(-1);
            }
        }
    }
}

Global Library Code

namespace Global
{
    [Serializable]
    public abstract class Request
    {

    }
    [Serializable]
    public class FileTransferRequest : Request
    {
        public string File;
        public FileTransferRequest(string File)
        {
            this.File = File;
        }
    }
    [Serializable]
    public abstract class Response
    {

    }
    [Serializable]
    public class FileTransferResponse : Response
    {
        public byte[] File;
        public FileTransferResponse(byte[] File)
        {
            this.File = File;
        }
    }
}

This is my code... It's not working !

But I have configured port forwarding

I have also disabled my firewall

My guess is something is wrong with windows. However I do not want to format my computer in order to solve this. I would much appreciate any input that would lead to solving this issue. I have had this issue for a while and I was wondering if anyone else has had a similar issue and if anyone has ever solved this. At the moment I have no clue how to even troubleshoot this issue. Do note that if I host the server on LAN and connect to LAN it works perfectly.

Body: I had to reinstall pcap drivers.


来源: stackexchange

问:
Blocking current thread until dialog is closed : web application
I'm new to Vaadin and I want to implement this: when a button is clicked a window containing a calendar is opened, and the user should choose a date in the calendar. The user should be blocked until he chooses the date, so I wrote this:

```<code>public class KopivaadincomponentsUI extends UI {

@Override
protected void init(VaadinRequest request) {
    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    setContent(layout);

    Button button = new Button("Click Me");
    button.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {

          DateChooser dateChooser = new DateChooser(new com.kopiright.xkopi.lib.type.Date(2013, 12, 9));
          UI.getCurrent().addWindow(dateChooser);

            synchronized (Lock.getInstance()) {
              while (dateChooser.isVisible()) {
            try {
              Lock.getInstance().wait();
            } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
              }
         }

        }
      });
    layout.addComponent(button);
}
</code>```

Here's the DateChooser—the window containing the calendar:

```<code>public class DateChooser extends Window implements ValueChangeListener{

public DateChooser(Date date){
  this.setModal(true);
  final FormLayout content = new FormLayout();
  calPane = new CalendarPane();
  content.addComponent(calPane);
  this.setContent(content);
  lock =new Lock();

}

/*package*/ class CalendarPane extends InlineDateField {

public CalendarPane() {
  setImmediate(true);
  setResolution(RESOLUTION_DAY);
  setShowISOWeekNumbers(true);
  }

  private static final long serialVersionUID = -3958329773743250969L;
}

private CalendarPane        calPane;
private static final long  serialVersionUID = 1L;

@Override
public void valueChange(ValueChangeEvent event) {
  synchronized(Lock.getInstance()) {
    String date = String.valueOf(event.getProperty().getValue());
    Calendar    cal = Calendar.getInstance(Locale.FRANCE);
    cal.setTime((java.util.Date) event.getProperty().getValue());

     setSelectedDate(new NotNullDate(cal));
     this.close();
    Lock.getInstance().notify();

   }

  }

 }
</code>```

The problem is that when I click the button it waits infinitely.
Any ideas will be appreciated.

答:
In fact Swing has blocking dialogs. The show() method in fact blocks until the user clicks a button and the dialog obtains a result. This is done by show() running its own nested event dispatcher loop as described here: How can Swing dialogs even work?

Unfortunately this is not possible with Vaadin. However, there is a clever technique called Coroutines which allows you to use Vaadin dialogs as if they were blocking: http://mavi.logdown.com/posts/3488105-vaadin-kotlin-coroutines

ContentLicense: CC BY-SA 3.0

Body:
I'm new to Vaadin and I want to implement this: when a button is clicked a window containing a calendar is opened, and the user should choose a date in the calendar. The user should be blocked until he chooses the date, so I wrote this:

public class KopivaadincomponentsUI extends UI {

@Override
protected void init(VaadinRequest request) {
    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    setContent(layout);

    Button button = new Button("Click Me");
    button.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {

          DateChooser dateChooser = new DateChooser(new com.kopiright.xkopi.lib.type.Date(2013, 12, 9));
          UI.getCurrent().addWindow(dateChooser);

            synchronized (Lock.getInstance()) {
              while (dateChooser.isVisible()) {
            try {
              Lock.getInstance().wait();
            } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
              }
         }

        }
      });
    layout.addComponent(button);
}

Here's the DateChooser—the window containing the calendar:

public class DateChooser extends Window implements ValueChangeListener{

public DateChooser(Date date){
  this.setModal(true);
  final FormLayout content = new FormLayout();
  calPane = new CalendarPane();
  content.addComponent(calPane);
  this.setContent(content);
  lock =new Lock();

}

/*package*/ class CalendarPane extends InlineDateField {

public CalendarPane() {
  setImmediate(true);
  setResolution(RESOLUTION_DAY);
  setShowISOWeekNumbers(true);
  }

  private static final long serialVersionUID = -3958329773743250969L;
}

private CalendarPane        calPane;
private static final long  serialVersionUID = 1L;

@Override
public void valueChange(ValueChangeEvent event) {
  synchronized(Lock.getInstance()) {
    String date = String.valueOf(event.getProperty().getValue());
    Calendar    cal = Calendar.getInstance(Locale.FRANCE);
    cal.setTime((java.util.Date) event.getProperty().getValue());

     setSelectedDate(new NotNullDate(cal));
     this.close();
    Lock.getInstance().notify();

   }

  }

 }

The problem is that when I click the button it waits infinitely.
Any ideas will be appreciated.


问:
Requesting administrator privileges in C program?
I'm trying to make a C program that modifies my host file, but I can't just straight up open the file with the program, because Windows blocks it. Is there any way that I can make the program request administrative privileges within the code, or any script I can use to start the program in admin mode? </p>

答:
Right clicking is a solution that allows you to run any program with Administrator privileges. That includes ticking the box in "Properties".

On Windows 7 and later, you can also rename your program so that its name contains setup (like hosts_setup.exe), and it'll automatically be run in Administrator mode (brings up the UAC prompt) if double-clicked in Explorer. Note this only works from double-clicking in Explorer.

<s>You can also take a look at How can I run a child process that requires elevation and wait? . It calls WinAPI and is a fairly native approach.</s> The best solution is to add it in menifest so your program requests Admin at startup.


问:
UnknownHostException on tasktracker in Hadoop cluster
I have set up a pseudo-distributed Hadoop cluster (with jobtracker, a tasktracker, and namenode all on the same box) per tutorial instructions and it's working fine. I am now trying to add in a second node to this cluster as another tasktracker.

When I examine the logs on Node 2, all the logs look fine except for the tasktracker. I'm getting an infinite loop of the error message listed below. It seems that  the Task Tracker is trying to use the hostname SSP-SANDBOX-1.mysite.com rather than the ip address. This hostname is not in /etc/hosts so I'm guessing this is where the problem is coming from. I do not have root access in order to add this to /etc/hosts.

Is there any property or configuration I can change so that it will stop trying to connect using the hostname?

Thanks very much,

```<code>2011-01-18 17:43:22,896 ERROR org.apache.hadoop.mapred.TaskTracker:
Caught exception: java.net.UnknownHostException: unknown host: SSP-SANDBOX-1.mysite.com
        at org.apache.hadoop.ipc.Client$Connection.<init>(Client.java:195)
        at org.apache.hadoop.ipc.Client.getConnection(Client.java:850)
        at org.apache.hadoop.ipc.Client.call(Client.java:720)
        at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:220)
        at $Proxy5.getProtocolVersion(Unknown Source)
        at org.apache.hadoop.ipc.RPC.getProxy(RPC.java:359)
        at org.apache.hadoop.hdfs.DFSClient.createRPCNamenode(DFSClient.java:106)
        at org.apache.hadoop.hdfs.DFSClient.<init>(DFSClient.java:207)
        at org.apache.hadoop.hdfs.DFSClient.<init>(DFSClient.java:170)
        at org.apache.hadoop.hdfs.DistributedFileSystem.initialize(DistributedFileSystem.java:82)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:1378)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:66)
        at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:1390)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:196)
        at org.apache.hadoop.fs.Path.getFileSystem(Path.java:175)
        at org.apache.hadoop.mapred.TaskTracker.offerService(TaskTracker.java:1033)
        at org.apache.hadoop.mapred.TaskTracker.run(TaskTracker.java:1720)
        at org.apache.hadoop.mapred.TaskTracker.main(TaskTracker.java:2833)
</code>```

答:
This blog posting might be helpful:

http://western-skies.blogspot.com/2010/11/fix-for-exceeded-maxfaileduniquefetches.html

The short answer is that Hadoop performs reverse hostname lookups even if you specify IP addresses in your configuration files.  In your environment, in order for you to make Hadoop work, SSP-SANDBOX-1.mysite.com must resolve to the IP address of that machine, and the reverse lookup for that IP address must resolve to SSP-SANDBOX-1.mysite.com.

So you'll need to talk to whoever is administering those machines to either fudge the hosts file or to provide a DNS server that will do the right thing.

ContentLicense: CC BY-SA 2.5

Body:
I have set up a pseudo-distributed Hadoop cluster (with jobtracker, a tasktracker, and namenode all on the same box) per tutorial instructions and it's working fine. I am now trying to add in a second node to this cluster as another tasktracker.

When I examine the logs on Node 2, all the logs look fine except for the tasktracker. I'm getting an infinite loop of the error message listed below. It seems that  the Task Tracker is trying to use the hostname SSP-SANDBOX-1.mysite.com rather than the ip address. This hostname is not in /etc/hosts so I'm guessing this is where the problem is coming from. I do not have root access in order to add this to /etc/hosts.

Is there any property or configuration I can change so that it will stop trying to connect using the hostname?

Thanks very much,

2011-01-18 17:43:22,896 ERROR org.apache.hadoop.mapred.TaskTracker:
Caught exception: java.net.UnknownHostException: unknown host: SSP-SANDBOX-1.mysite.com
        at org.apache.hadoop.ipc.Client$Connection.<init>(Client.java:195)
        at org.apache.hadoop.ipc.Client.getConnection(Client.java:850)
        at org.apache.hadoop.ipc.Client.call(Client.java:720)
        at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:220)
        at $Proxy5.getProtocolVersion(Unknown Source)
        at org.apache.hadoop.ipc.RPC.getProxy(RPC.java:359)
        at org.apache.hadoop.hdfs.DFSClient.createRPCNamenode(DFSClient.java:106)
        at org.apache.hadoop.hdfs.DFSClient.<init>(DFSClient.java:207)
        at org.apache.hadoop.hdfs.DFSClient.<init>(DFSClient.java:170)
        at org.apache.hadoop.hdfs.DistributedFileSystem.initialize(DistributedFileSystem.java:82)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:1378)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:66)
        at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:1390)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:196)
        at org.apache.hadoop.fs.Path.getFileSystem(Path.java:175)
        at org.apache.hadoop.mapred.TaskTracker.offerService(TaskTracker.java:1033)
        at org.apache.hadoop.mapred.TaskTracker.run(TaskTracker.java:1720)
        at org.apache.hadoop.mapred.TaskTracker.main(TaskTracker.java:2833)


问:
Precompressed gzipped files cannot be served by Express possibly because wrong path
I have a React app with a folder structure like this:

```<code>├── index.html
└── app
    ├── server.js
    ├── routes.jsx
    ├── scripts
    │   ├── bundle.js
    │   ├── bundle.js.gz
    │   ├── vendor.js
    │   └── vendor.js.gz
    └── components
        └──  ...
</code>```

I need to serve precompressed files (*.js.gz) when .js files requested but the original .js files are served, instead. This is probably because of a wrong path but I couldn't figure it out.

Here is my server.js file:

```<code>import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { StaticRouter } from 'react-router';
import http from 'http';
import express from 'express';
import fs from 'fs';
import App from '~/routes.jsx';

const index = fs.readFileSync('index.html', 'utf8');
const PORT = process.env.PORT || 8000;

const app = new express();
const server = new http.Server(app);

app.use('/app', express.static('app'));

app.use((request, response) => {
    const context = {};

    const html = ReactDOMServer.renderToString(
        <StaticRouter location={request.url} context={context}>
            <App/>
        </StaticRouter>
    );

    if (context.url) {
        response.writeHead(301, {Location: context.url});
        response.end();
    } else {
        response.write(index.replace(
            /<div id="root"><\/div>/,
            `<div id="root">${html}</div>`
        ));
        response.end();
    }
});

app.get('*.js', function (request, response, next) {
    console.log('js requested');
    request.url = request.url + '.gz';
    response.set('Content-Encoding', 'gzip');
    next();
});

server.listen(PORT);
console.log(`\nApplication available at localhost:${PORT}\n`);
</code>```

答:
Middleware in Express is always invoked in the order you added them. So to load *.js.gz file, you need to move the middleware above the
express.static middleware.

```<code>//...
//load this middleware first
app.get('*.js', function (request, response, next) {
    console.log('js requested');
    request.url = request.url + '.gz';
    response.set('Content-Encoding', 'gzip');
    next();
});
//then load the express.static middleware
app.use('/app', express.static('app'));
//...
</code>```

Body:
I have a React app with a folder structure like this:

├── index.html
└── app
    ├── server.js
    ├── routes.jsx
    ├── scripts
    │   ├── bundle.js
    │   ├── bundle.js.gz
    │   ├── vendor.js
    │   └── vendor.js.gz
    └── components
        └──  ...

I need to serve precompressed files (*.js.gz) when .js files requested but the original .js files are served, instead. This is probably because of a wrong path but I couldn't figure it out.

Here is my server.js file:

import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { StaticRouter } from 'react-router';
import http from 'http';
import express from 'express';
import fs from 'fs';
import App from '~/routes.jsx';

const index = fs.readFileSync('index.html', 'utf8');
const PORT = process.env.PORT || 8000;

const app = new express();
const server = new http.Server(app);

app.use('/app', express.static('app'));

app.use((request, response) => {
    const context = {};

    const html = ReactDOMServer.renderToString(
        <StaticRouter location={request.url} context={context}>
            <App/>
        </StaticRouter>
    );

    if (context.url) {
        response.writeHead(301, {Location: context.url});
        response.end();
    } else {
        response.write(index.replace(
            /
<\/div>/,
            `<div id="root">${html}</div>`
        ));
        response.end();
    }
});

app.get('*.js', function (request, response, next) {
    console.log('js requested');
    request.url = request.url + '.gz';
    response.set('Content-Encoding', 'gzip');
    next();
});

server.listen(PORT);
console.log(`\nApplication available at localhost:${PORT}\n`);

Body:
Middleware in Express is always invoked in the order you added them. So to load *.js.gz file, you need to move the middleware above the
express.static middleware.

//...
//load this middleware first
app.get('*.js', function (request, response, next) {
    console.log('js requested');
    request.url = request.url + '.gz';
    response.set('Content-Encoding', 'gzip');
    next();
});
//then load the express.static middleware
app.use('/app', express.static('app'));
//...


问:
how to use twitter bootstrap javascript component in angularjs
I want to use tootltip of twitter bootstrap in my angularjs web app. when I use them simply in my code and put the jQuery initialization on top of my js file inside document.ready it works perfectly.

```<code>$( document ).ready(function(){
    $(function () {
        $('[data-toggle="tooltip"]').tooltip()
    });
    $('.myslider').myslider();
});

var myapp = angular.module("eplApp",['ui.router']);
</code>```

but when I use them in view by ui-routing. It stops working with no error in console..
i am also using more javascript components like crousel. I would like to know how to intialize/call them in view ad document.ready doesn't work in views.

should I initialize them in my controller.
if yes than how?

答:
If you want to use Bootstrap UI in Angular, it would be a better idea to use Angular Module ui.bootrap found here

While you can always create your own angular directives for bootstrap tooltips, this is a quicker way out.

```<code>var myapp = angular.module("eplApp",['ui.router','ui.bootstrap']);
</code>```

and in your HTML

```<code><button tooltip-placement="{{placement.selected}}" uib-tooltip="On the {{placement.selected}}" type="button" class="btn btn-default">Tooltip text</button>
</code>```

Changing routes using ui.router will not fire $document.ready() again. If the state is loaded after $doucment.ready() is called, your code will not work. If you do not wish to include ui.bootstrap, create a directive and initialize tooltip using $('[data-toggle="tooltip"]').tooltip() in the link function of your directive.

Body:
I want to use tootltip of twitter bootstrap in my angularjs web app. when I use them simply in my code and put the jQuery initialization on top of my js file inside document.ready it works perfectly.

$( document ).ready(function(){
    $(function () {
        $('[data-toggle="tooltip"]').tooltip()
    });
    $('.myslider').myslider();
});

var myapp = angular.module("eplApp",['ui.router']);

but when I use them in view by ui-routing. It stops working with no error in console..
i am also using more javascript components like crousel. I would like to know how to intialize/call them in view ad document.ready doesn't work in views.

should I initialize them in my controller.
if yes than how?

Body:
If you want to use Bootstrap UI in Angular, it would be a better idea to use Angular Module ui.bootrap found here

While you can always create your own angular directives for bootstrap tooltips, this is a quicker way out.

var myapp = angular.module("eplApp",['ui.router','ui.bootstrap']);

and in your HTML

<button tooltip-placement="{{placement.selected}}" uib-tooltip="On the {{placement.selected}}" type="button" class="btn btn-default">Tooltip text</button>

Changing routes using ui.router will not fire $document.ready() again. If the state is loaded after $doucment.ready() is called, your code will not work. If you do not wish to include ui.bootstrap, create a directive and initialize tooltip using $('[data-toggle="tooltip"]').tooltip() in the link function of your directive.


问:
Hardening SpringBoot's embedded Tomcat
New to Tomcat and SpringBoot

I need to make sure the embedded Tomcat in SpringBoot is hardened to a certain level.  I'm using this CIS doc (you'll have to dl the pdf) as a checklist on what we may want to do.  However, the doc is geared toward a "normally installed" Tomcat.  For example, I'm directed to update a file(s) found in $CATALINA_HOME.

Does SpringBoot offer a way to fully control/access it's embedded Tomcat?  If not, is it possible and reasonable to configure Tomcat externally from SpringBoot then override the default SpringBoot Tomcat with my own?  I'm open to other solutions too.

答:
If you have to follow that guide to the letter, the easiest way is going to be packaging the spring boot app as a WAR and deploying it in a regular Tomcat server. This guide explains how to package an app as a war.

Tomcat is a pretty complicated piece of software when you start opening it up. You can write java code that can access Tomcat's configuration and set the config settings yourself. In addition, tomcat is broken up into a number of components, and some of those files you need to modify may be for a component that is not part of spring boot's embedded tomcat.

You can harden spring boot apps, but the job will be easier if you follow the guide.

Title: Hardening SpringBoot's embedded Tomcat


问:
Deleting elements that appeare more than once in the list and leaving only one element
I have a small question.
how can i check if a list has identical elements and if the list has identical elements, how can leave only one of those elements in the list?

For example, i wrote this code:

```<code>def courses_per_student(tuple_lst):
    courses={}
    new_tuple_lst=[]
    for i in range(len(tuple_lst)):
            new_tuple_lst.append((str(tuple_lst[i][0]).lower(),(str(tuple_lst[i][1]).lower())))
    for m in new_tuple_lst:
       if not courses.has_key(m[0]):
            courses[m[0]]=[m[1]]
       else:
           courses[m[0]]=courses[m[0]]+[m[1]]
    return courses
</code>```

which for:   courses_per_student([("Rina", "Math"), ("Yossi", "Chemistry"), ("Riki", "python"), ("Rina", "math"), ("Yossi", "biology")])
returns:
{'rina': ['math', 'math'], 'yossi': ['chemistry', 'biology'], 'riki': ['python']}

I want that 'math' will appere only once in the list.
thankyou

答:
```<code>def uniqode(list):
    demolist = []
    for el in list:
        if el in demolist:
            continue
        demolist.append(el)
    return demolist
</code>```

Body:
I have a small question.
how can i check if a list has identical elements and if the list has identical elements, how can leave only one of those elements in the list?

For example, i wrote this code:

def courses_per_student(tuple_lst):
    courses={}
    new_tuple_lst=[]
    for i in range(len(tuple_lst)):
            new_tuple_lst.append((str(tuple_lst[i][0]).lower(),(str(tuple_lst[i][1]).lower())))
    for m in new_tuple_lst:
       if not courses.has_key(m[0]):
            courses[m[0]]=[m[1]]
       else:
           courses[m[0]]=courses[m[0]]+[m[1]]
    return courses

which for:   courses_per_student([("Rina", "Math"), ("Yossi", "Chemistry"), ("Riki", "python"), ("Rina", "math"), ("Yossi", "biology")])
returns:
{'rina': ['math', 'math'], 'yossi': ['chemistry', 'biology'], 'riki': ['python']}

I want that 'math' will appere only once in the list.
thankyou


问:
Javafx FXML Media Player play same Video in two windows simultaneously
im have a simple Media Player created in Java with Javafx FXML.

Now what i want to achieve, is to play the video also in a second window, sadly ive got no clue how this is done. I searched other posts about the same question but found nothing what would help me.

Here's the code

simplemediaPlayer.java :

```<code>package simplemediaplayer;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

public class simplemediaPlayer extends Application {

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

    Scene scene = new Scene(root);

    stage.setTitle("Media Player");
    scene.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent doubleClicked) {
            if(doubleClicked.getClickCount() == 2) {
                if(stage.isFullScreen()) {
                    stage.setFullScreen(false);
                } else {
                    stage.setFullScreen(true);
                }
            }
        }
    });

    stage.setScene(scene);
    stage.show();

    Parent roota = FXMLLoader.load(getClass().getResource("dualmodeWindow.fxml"));
    Stage stagea = new Stage();
    Scene scenea = new Scene(roota);

    stagea.setTitle("Second Window");

    stagea.setScene(scenea);
    stagea.show();

}

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

}
</code>```

FXMLDocumentController.java :

```<code>package simplemediaplayer;

import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Slider;
import javafx.scene.input.MouseEvent;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.FileChooser;
import javafx.util.Duration;

public class FXMLDocumentController implements Initializable {

private MediaPlayer mediaPlayer;

@FXML
private MediaView mediaView;

private String filePath;

@FXML
private Slider volSlider;

@FXML
private Slider minSlider;

@FXML
private void openvidFile(ActionEvent event) {
    FileChooser fileChooser = new FileChooser();
    FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Select a File (*.mp4)", "*.mp4");
    fileChooser.getExtensionFilters().add(filter);
    File file = fileChooser.showOpenDialog(null);
    filePath = file.toURI().toString();

    if(filePath != null) {
        Media media = new Media(filePath);
        mediaPlayer = new MediaPlayer(media);
        mediaView.setMediaPlayer(mediaPlayer);
        DoubleProperty width = mediaView.fitWidthProperty();
        DoubleProperty height = mediaView.fitHeightProperty();

        width.bind(Bindings.selectDouble(mediaView.sceneProperty(), "width"));
        height.bind(Bindings.selectDouble(mediaView.sceneProperty(), "height"));

        volSlider.setValue(mediaPlayer.getVolume() * 100);
        volSlider.valueProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                mediaPlayer.setVolume(volSlider.getValue()/100);
            }
        });

        mediaPlayer.currentTimeProperty().addListener(new ChangeListener<Duration>() {
            @Override
            public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
                minSlider.setValue(newValue.toSeconds());
            }
        });

        minSlider.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                mediaPlayer.seek(Duration.seconds(minSlider.getValue()));
            }
        });

        mediaPlayer.play();
    }
}

@FXML
private void playVid(ActionEvent event) {
    mediaPlayer.play();
    mediaPlayer.setRate(1);
}

@FXML
private void pauseVid(ActionEvent event) {
    mediaPlayer.pause();
}

@FXML
private void stopVid(ActionEvent event) {
    mediaPlayer.stop();
}

@FXML
private void exitProg(ActionEvent event) {
    System.exit(0);
}
@Override
public void initialize(URL url, ResourceBundle rb) {

}

}
</code>```

FXMLDocument.fxml :

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.media.MediaView?>

 <StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" stylesheets="@style.css" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="simplemediaplayer.FXMLDocumentController">
  <children>
  <MediaView fx:id="mediaView" fitHeight="200.0" fitWidth="200.0" />
  <BorderPane prefHeight="200.0" prefWidth="200.0">
     <top>
        <MenuBar fx:id="topMenu" BorderPane.alignment="CENTER">
          <menus>
            <Menu mnemonicParsing="false" text="File">
              <items>
                <MenuItem mnemonicParsing="false" onAction="#openvidFile" text="Open" />
                    <MenuItem mnemonicParsing="false" onAction="#exitProg" text="Close" />
              </items>
            </Menu>
            <Menu mnemonicParsing="false" text="Edit">
              <items>
                <MenuItem mnemonicParsing="false" text="Delete" />
              </items>
            </Menu>
            <Menu mnemonicParsing="false" text="Help">
              <items>
                <MenuItem mnemonicParsing="false" text="About" />
              </items>
            </Menu>
          </menus>
        </MenuBar>
     </top>
     <bottom>
        <VBox fx:id="botMenu" alignment="BOTTOM_CENTER" prefHeight="84.0" prefWidth="600.0" BorderPane.alignment="CENTER">
           <children>
              <Slider fx:id="minSlider" />
              <HBox alignment="CENTER" prefHeight="57.0" prefWidth="600.0">
                 <children>
                    <Button fx:id="openClick" mnemonicParsing="false" onAction="#openvidFile" text="Open">
                       <HBox.margin>
                          <Insets right="10.0" />
                       </HBox.margin>
                    </Button>
                    <Button fx:id="playClick" mnemonicParsing="false" onAction="#playVid" text="Play">
                       <HBox.margin>
                          <Insets right="10.0" />
                       </HBox.margin>
                    </Button>
                    <Button fx:id="pauseClick" mnemonicParsing="false" onAction="#pauseVid" text="Pause">
                       <HBox.margin>
                          <Insets right="20.0" />
                       </HBox.margin>
                    </Button>
                    <Slider fx:id="volSlider" prefHeight="25.0" prefWidth="140.0" />
                    <Button fx:id="dualmodeButton" mnemonicParsing="false" text="Dual Mode">
                       <HBox.margin>
                          <Insets left="30.0" />
                       </HBox.margin>
                    </Button>
                 </children>
              </HBox>
           </children>
        </VBox>
     </bottom>
  </BorderPane>
 </children>
 </StackPane>
</code>```

and i created a second fxml window which only contains a stackpane and a mediaview.

dualmodeWindow.fxml :

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.media.MediaView?>

<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="simplemediaplayer.FXMLDocumentController">
<children>
  <MediaView fx:id="secmediaView" fitHeight="200.0" fitWidth="200.0" />
</children>
</StackPane>
</code>```

Ive tried to give the mediaView on the second window the same id as the mediaView on the main Window but no video appear on the second window.

Would be nice if someone can help me with this.

答: You need to create a second media player with the same media object, and then set this second media player to the second media view.  According to the documentation, a media player can have only one media object.</p>

Body:
im have a simple Media Player created in Java with Javafx FXML.

Now what i want to achieve, is to play the video also in a second window, sadly ive got no clue how this is done. I searched other posts about the same question but found nothing what would help me.

Here's the code

simplemediaPlayer.java :

package simplemediaplayer;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

public class simplemediaPlayer extends Application {

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

    Scene scene = new Scene(root);

    stage.setTitle("Media Player");
    scene.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent doubleClicked) {
            if(doubleClicked.getClickCount() == 2) {
                if(stage.isFullScreen()) {
                    stage.setFullScreen(false);
                } else {
                    stage.setFullScreen(true);
                }
            }
        }
    });

    stage.setScene(scene);
    stage.show();

    Parent roota = FXMLLoader.load(getClass().getResource("dualmodeWindow.fxml"));
    Stage stagea = new Stage();
    Scene scenea = new Scene(roota);

    stagea.setTitle("Second Window");

    stagea.setScene(scenea);
    stagea.show();

}

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

}

FXMLDocumentController.java :

package simplemediaplayer;

import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Slider;
import javafx.scene.input.MouseEvent;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.FileChooser;
import javafx.util.Duration;

public class FXMLDocumentController implements Initializable {

private MediaPlayer mediaPlayer;

@FXML
private MediaView mediaView;

private String filePath;

@FXML
private Slider volSlider;

@FXML
private Slider minSlider;

@FXML
private void openvidFile(ActionEvent event) {
    FileChooser fileChooser = new FileChooser();
    FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Select a File (*.mp4)", "*.mp4");
    fileChooser.getExtensionFilters().add(filter);
    File file = fileChooser.showOpenDialog(null);
    filePath = file.toURI().toString();

    if(filePath != null) {
        Media media = new Media(filePath);
        mediaPlayer = new MediaPlayer(media);
        mediaView.setMediaPlayer(mediaPlayer);
        DoubleProperty width = mediaView.fitWidthProperty();
        DoubleProperty height = mediaView.fitHeightProperty();

        width.bind(Bindings.selectDouble(mediaView.sceneProperty(), "width"));
        height.bind(Bindings.selectDouble(mediaView.sceneProperty(), "height"));

        volSlider.setValue(mediaPlayer.getVolume() * 100);
        volSlider.valueProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                mediaPlayer.setVolume(volSlider.getValue()/100);
            }
        });

        mediaPlayer.currentTimeProperty().addListener(new ChangeListener<Duration>() {
            @Override
            public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
                minSlider.setValue(newValue.toSeconds());
            }
        });

        minSlider.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                mediaPlayer.seek(Duration.seconds(minSlider.getValue()));
            }
        });

        mediaPlayer.play();
    }
}

@FXML
private void playVid(ActionEvent event) {
    mediaPlayer.play();
    mediaPlayer.setRate(1);
}

@FXML
private void pauseVid(ActionEvent event) {
    mediaPlayer.pause();
}

@FXML
private void stopVid(ActionEvent event) {
    mediaPlayer.stop();
}

@FXML
private void exitProg(ActionEvent event) {
    System.exit(0);
}
@Override
public void initialize(URL url, ResourceBundle rb) {

}

}

FXMLDocument.fxml :

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.media.MediaView?>

 <StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" stylesheets="@style.css" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="simplemediaplayer.FXMLDocumentController">
  <children>
  <MediaView fx:id="mediaView" fitHeight="200.0" fitWidth="200.0" />
  <BorderPane prefHeight="200.0" prefWidth="200.0">
     <top>
        <MenuBar fx:id="topMenu" BorderPane.alignment="CENTER">
          <menus>
            <Menu mnemonicParsing="false" text="File">
              <items>
                <MenuItem mnemonicParsing="false" onAction="#openvidFile" text="Open" />
                    <MenuItem mnemonicParsing="false" onAction="#exitProg" text="Close" />
              </items>
            </Menu>
            <Menu mnemonicParsing="false" text="Edit">
              <items>
                <MenuItem mnemonicParsing="false" text="Delete" />
              </items>
            </Menu>
            <Menu mnemonicParsing="false" text="Help">
              <items>
                <MenuItem mnemonicParsing="false" text="About" />
              </items>
            </Menu>
          </menus>
        </MenuBar>
     </top>
     <bottom>
        <VBox fx:id="botMenu" alignment="BOTTOM_CENTER" prefHeight="84.0" prefWidth="600.0" BorderPane.alignment="CENTER">
           <children>
              <Slider fx:id="minSlider" />
              <HBox alignment="CENTER" prefHeight="57.0" prefWidth="600.0">
                 <children>
                    <Button fx:id="openClick" mnemonicParsing="false" onAction="#openvidFile" text="Open">
                       <HBox.margin>
                          <Insets right="10.0" />
                       </HBox.margin>
                    </Button>
                    <Button fx:id="playClick" mnemonicParsing="false" onAction="#playVid" text="Play">
                       <HBox.margin>
                          <Insets right="10.0" />
                       </HBox.margin>
                    </Button>
                    <Button fx:id="pauseClick" mnemonicParsing="false" onAction="#pauseVid" text="Pause">
                       <HBox.margin>
                          <Insets right="20.0" />
                       </HBox.margin>
                    </Button>
                    <Slider fx:id="volSlider" prefHeight="25.0" prefWidth="140.0" />
                    <Button fx:id="dualmodeButton" mnemonicParsing="false" text="Dual Mode">
                       <HBox.margin>
                          <Insets left="30.0" />
                       </HBox.margin>
                    </Button>
                 </children>
              </HBox>
           </children>
        </VBox>
     </bottom>
  </BorderPane>
 </children>
 </StackPane>

and i created a second fxml window which only contains a stackpane and a mediaview.

dualmodeWindow.fxml :

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.media.MediaView?>

<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="simplemediaplayer.FXMLDocumentController">
<children>
  <MediaView fx:id="secmediaView" fitHeight="200.0" fitWidth="200.0" />
</children>
</StackPane>

Ive tried to give the mediaView on the second window the same id as the mediaView on the main Window but no video appear on the second window.

Would be nice if someone can help me with this.


问:
Laravel - When retrieving the distance when given a user's longitude & latitude, I keep getting the same result on all models. Why?
I have a JSON column in my database that stores longitude and latitude coordinates set up as:

```<code>_geoloc:{lat: 33.6556324, lng: -117.7015161}.
</code>```

I am trying to query the database with a user's longitude & latitude coordinates to retrieve all records that fall within a certain distance. Below is the function that I am using, however all results are returning the same distance of 7797.5012454514 with each model. I would like to pass the $distance parameter as miles.

```<code>protected function get_locations( $latitude, $longitude, $distance = 8000 ) {
    $results= my_table::select( 'my_table.*' )
        ->selectRaw( '(3959 * (acos( cos( radians(?) )
            * cos( radians( "_geoloc->lat" ) )
            * cos( radians( "_geoloc->lng" ) - radians(?))
            + sin( radians( ? ) )
            * sin( radians( "_geoloc->lat" ) ) ) ) )
        AS distance', [ $latitude, $longitude, $latitude ] )
        ->havingRaw( "distance< ?", [ $distance ] )
        ->groupBy( 'first_name' )
        ->get();
    return $results;
}
</code>```

答:
In case someone else comes across the same problem. The solution requires a JSON_EXTRACT to be used in the query along with a $ symbol to tokenize the object.  </p>

```<code>protected function get_locations( $latitude, $longitude, $distance = 20 ) {
    $results = ( new my_table)->having( 'distance', '<', $distance )
                                      ->select( DB::raw( "*,
                 (3959 * ACOS(COS(RADIANS($latitude))
                       * COS(RADIANS(JSON_EXTRACT(`_geoloc`,'$.lat')))
                       * COS(RADIANS($longitude) - RADIANS(JSON_EXTRACT(`_geoloc`,'$.lng')))
                       + SIN(RADIANS($latitude))
                       * SIN(RADIANS(JSON_EXTRACT(`_geoloc`,'$.lat'))))) AS distance" )
                                      )->orderBy( 'distance', 'asc' )
                                      ->get();
    return $results
}
</code>```

Body:
I have a JSON column in my database that stores longitude and latitude coordinates set up as:

_geoloc:{lat: 33.6556324, lng: -117.7015161}.

I am trying to query the database with a user's longitude & latitude coordinates to retrieve all records that fall within a certain distance. Below is the function that I am using, however all results are returning the same distance of 7797.5012454514 with each model. I would like to pass the $distance parameter as miles.

protected function get_locations( $latitude, $longitude, $distance = 8000 ) {
    $results= my_table::select( 'my_table.*' )
        ->selectRaw( '(3959 * (acos( cos( radians(?) )
            * cos( radians( "_geoloc->lat" ) )
            * cos( radians( "_geoloc->lng" ) - radians(?))
            + sin( radians( ? ) )
            * sin( radians( "_geoloc->lat" ) ) ) ) )
        AS distance', [ $latitude, $longitude, $latitude ] )
        ->havingRaw( "distance< ?", [ $distance ] )
        ->groupBy( 'first_name' )
        ->get();
    return $results;
}

Body:
In case someone else comes across the same problem. The solution requires a JSON_EXTRACT to be used in the query along with a $ symbol to tokenize the object.

protected function get_locations( $latitude, $longitude, $distance = 20 ) {
    $results = ( new my_table)->having( 'distance', '<', $distance )
                                      ->select( DB::raw( "*,
                 (3959 * ACOS(COS(RADIANS($latitude))
                       * COS(RADIANS(JSON_EXTRACT(`_geoloc`,'$.lat')))
                       * COS(RADIANS($longitude) - RADIANS(JSON_EXTRACT(`_geoloc`,'$.lng')))
                       + SIN(RADIANS($latitude))
                       * SIN(RADIANS(JSON_EXTRACT(`_geoloc`,'$.lat'))))) AS distance" )
                                      )->orderBy( 'distance', 'asc' )
                                      ->get();
    return $results
}


问:
How to lazy load different routes in Angular5 correctly
I am trying to lazy load a module that has children routes. But so far only the   main component keep loading. Here is my lazy loading routes module.

```<code>export const routes: Routes = [
   {
    path: '',
    component: Notfound404Component, pathMatch: 'prefix',
    children: [
      { path: '', pathMatch: 'full', redirectTo: '404' },
      { path: '404', component: Notfound404Component },
      { path: '403', component: Notfound403Component }
    ]
   }
</code>```

And in my app.routes module I did this :

```<code> { path: 'error/403', loadChildren: './errors/errors.module#ErrorsModule'},
  { path: 'error', loadChildren: './errors/errors.module#ErrorsModule'}
</code>```

Expected behavior is that localhost:4200/error loads the Notfound404Component component and localhost:4200/error/403 loads the Notfound403Component

Unfortunately it only loads the Notfound404Component on both routes.

How can I achieve this?

答:
you must put this line to parent route

```<code>{ path: '', pathMatch: 'full', redirectTo: '/' },
</code>```

and in child route replace

```<code>{ path: '', pathMatch: 'full', redirectTo: '404' },
</code>```

with this

```<code>{ path: '', component: Notfound404Component },
</code>```

Body:
I am trying to lazy load a module that has children routes. But so far only the   main component keep loading. Here is my lazy loading routes module.

export const routes: Routes = [
   {
    path: '',
    component: Notfound404Component, pathMatch: 'prefix',
    children: [
      { path: '', pathMatch: 'full', redirectTo: '404' },
      { path: '404', component: Notfound404Component },
      { path: '403', component: Notfound403Component }
    ]
   }

And in my app.routes module I did this :

 { path: 'error/403', loadChildren: './errors/errors.module#ErrorsModule'},
  { path: 'error', loadChildren: './errors/errors.module#ErrorsModule'}

Expected behavior is that localhost:4200/error loads the Notfound404Component component and localhost:4200/error/403 loads the Notfound403Component

Unfortunately it only loads the Notfound404Component on both routes.

How can I achieve this?

Body:
you must put this line to parent route

{ path: '', pathMatch: 'full', redirectTo: '/' },

and in child route replace

{ path: '', pathMatch: 'full', redirectTo: '404' },

with this

{ path: '', component: Notfound404Component },


问:
removeAll seems to affect its argument
I have written a generic Partition class (a partition is a division of a set into disjoint subsets, called parts). Internally this is a Map<T,Integer> and a Map<Integer,Set<T>>, where the Integers are the labels of the parts. For example partition.getLabel(T t) gives the label of the part that t is in, and partition.move(T t, Integer label) moves t to the partition labelled by label (internally, it updates both the Maps).

But my method for moving a Collection of objects to a new part does not work. It seems that Set.removeAll() is affecting its argument. I think the problem is something like a ConcurrentModificationException, but I can't work it out. Sorry the code is rather long, but I have marked where the problem is (about half-way down), and the output at the bottom should make it clear what the problem is - at the end the partition is in an illegal state.

```<code>    import java.util.*;

    public class Partition<T> {
  private Map<T,Integer> objToLabel = new HashMap<T,Integer>();
     private Map<Integer,Set<T>> labelToObjs =
       new HashMap<Integer,Set<T>>();
     private List<Integer> unusedLabels;
     private int size;  // = number of elements

     public Partition(Collection<T> objects) {
      size = objects.size();
      unusedLabels = new ArrayList<Integer>();
      for (int i = 1; i < size; i++)
       unusedLabels.add(i);
      // Put all the objects in part 0.
      Set<T> part = new HashSet<T>(objects);
      for (T t : objects)
       objToLabel.put(t,0);
      labelToObjs.put(0,part);
     }

     public Integer getLabel(T t) {
      return objToLabel.get(t);
     }
     public Set<T> getPart(Integer label) {
      return labelToObjs.get(label);
     }
     public Set<T> getPart(T t) {
      return getPart(getLabel(t));
     }

     public Integer newPart(T t) {
      // Move t to a new part.
      Integer newLabel = unusedLabels.remove(0);
      labelToObjs.put(newLabel,new HashSet<T>());
      move(t, newLabel);
      return newLabel;
     }
     public Integer newPart(Collection<T> things) {
      // Move things to a new part. (This assumes that
      // they are all in the same part to start with.)
      Integer newLabel = unusedLabels.remove(0);
      labelToObjs.put(newLabel,new HashSet<T>());
      moveAll(things, newLabel);
      return newLabel;
     }
     public void move(T t, Integer label) {
      // Move t to the part "label".
      Integer oldLabel = getLabel(t);
      getPart(oldLabel).remove(t);
      if (getPart(oldLabel).isEmpty())  // if the old part is
       labelToObjs.remove(oldLabel);  // empty, remove it
      getPart(label).add(t);
      objToLabel.put(t,label);
     }
     public void moveAll(Collection<T> things, Integer label) {
      // Move all the things from their current part to label.
      // (This assumes all the things are in the same part.)
      if (things.size()==0)  return;

      T arbitraryThing = new ArrayList<T>(things).get(0);
      Set<T> oldPart = getPart(arbitraryThing);

   // THIS IS WHERE IT SEEMS TO GO WRONG //////////////////////////
      System.out.println(" oldPart = " + oldPart);
      System.out.println(" things = " + things);
      System.out.println("Now doing oldPart.removeAll(things) ...");
      oldPart.removeAll(things);
      System.out.println(" oldPart = " + oldPart);
      System.out.println(" things = " + things);

      if (oldPart.isEmpty())
       labelToObjs.remove(objToLabel.get(arbitraryThing));

      for (T t : things)
       objToLabel.put(t,label);
      getPart(label).addAll(things);
     }

     public String toString() {
      StringBuilder result = new StringBuilder();
      result.append("\nPARTITION OF " + size + " ELEMENTS INTO " +
        labelToObjs.size() + " PART");
      result.append((labelToObjs.size()==1 ? "" : "S") + "\n");
      for (Map.Entry<Integer,Set<T>> mapEntry :
        labelToObjs.entrySet()) {
       result.append("PART " + mapEntry.getKey() + ": ");
       result.append(mapEntry.getValue() + "\n");
      }
      return result.toString();
     }

     public static void main(String[] args) {
      List<String> strings =
        Arrays.asList("zero one two three".split(" "));

      Partition<String> p = new Partition<String>(strings);
      p.newPart(strings.get(3));  // move "three" to a new part
      System.out.println(p);

      System.out.println("Now moving all of three's part to the " +
        "same part as zero.\n");
      Collection<String> oldPart = p.getPart(strings.get(3));
      //oldPart = Arrays.asList(new String[]{"three"});  // works fine!
      p.moveAll(oldPart, p.getLabel(strings.get(0)));
      System.out.println(p);
     }
    }

/* OUTPUT
PARTITION OF 4 ELEMENTS INTO 2 PARTS
PART 0: [two, one, zero]
PART 1: [three]

Now moving all of three's part to the same part as zero.

 oldPart = [three]
 things = [three]
Now doing oldPart.removeAll(things) ...
 oldPart = []
 things = []

PARTITION OF 4 ELEMENTS INTO 1 PART
PART 0: [two, one, zero]
*/
</code>```

答:
Your code is extremely confusing but as far as I can work out, oldPart and things are actually the same object. Set.removeAll() certainly doesn't affect its argument unless it is the same object as it's invoked on:

```<code>public boolean removeAll(Collection<?> c) {
    boolean modified = false;

    if (size() > c.size()) {
        for (Iterator<?> i = c.iterator(); i.hasNext(); )
            modified |= remove(i.next());
    } else {
        for (Iterator<?> i = iterator(); i.hasNext(); ) {
            if (c.contains(i.next())) {
                i.remove();
                modified = true;
            }
        }
    }
    return modified;
}
</code>```

Update:

The easy way to eliminate this is to use a copy of things in the moveAll() method. Indeed such a copy already exists.

```<code>T arbitraryThing = new ArrayList<T>(things).get(0);
</code>```

This line creates but then instantly discards a copy of things. So I'd suggest replacing it with:

```<code>ArrayList<T> thingsToRemove = new ArrayList<T>(things)
T arbitraryThing = thingsToRemove.get(0);
</code>```

And in the rest of the method, replace all references to things to thingsToRemove.

Title: removeAll seems to affect its argument

Body:
I have written a generic Partition class (a partition is a division of a set into disjoint subsets, called parts). Internally this is a Map<T,Integer> and a Map<Integer,Set<T>>, where the Integers are the labels of the parts. For example partition.getLabel(T t) gives the label of the part that t is in, and partition.move(T t, Integer label) moves t to the partition labelled by label (internally, it updates both the Maps).

But my method for moving a Collection of objects to a new part does not work. It seems that Set.removeAll() is affecting its argument. I think the problem is something like a ConcurrentModificationException, but I can't work it out. Sorry the code is rather long, but I have marked where the problem is (about half-way down), and the output at the bottom should make it clear what the problem is - at the end the partition is in an illegal state.

    import java.util.*;

    public class Partition<T> {
  private Map<T,Integer> objToLabel = new HashMap<T,Integer>();
     private Map<Integer,Set<T>> labelToObjs =
       new HashMap<Integer,Set<T>>();
     private List<Integer> unusedLabels;
     private int size;  // = number of elements

     public Partition(Collection<T> objects) {
      size = objects.size();
      unusedLabels = new ArrayList<Integer>();
      for (int i = 1; i < size; i++)
       unusedLabels.add(i);
      // Put all the objects in part 0.
      Set<T> part = new HashSet<T>(objects);
      for (T t : objects)
       objToLabel.put(t,0);
      labelToObjs.put(0,part);
     }

     public Integer getLabel(T t) {
      return objToLabel.get(t);
     }
     public Set<T> getPart(Integer label) {
      return labelToObjs.get(label);
     }
     public Set<T> getPart(T t) {
      return getPart(getLabel(t));
     }

     public Integer newPart(T t) {
      // Move t to a new part.
      Integer newLabel = unusedLabels.remove(0);
      labelToObjs.put(newLabel,new HashSet<T>());
      move(t, newLabel);
      return newLabel;
     }
     public Integer newPart(Collection<T> things) {
      // Move things to a new part. (This assumes that
      // they are all in the same part to start with.)
      Integer newLabel = unusedLabels.remove(0);
      labelToObjs.put(newLabel,new HashSet<T>());
      moveAll(things, newLabel);
      return newLabel;
     }
     public void move(T t, Integer label) {
      // Move t to the part "label".
      Integer oldLabel = getLabel(t);
      getPart(oldLabel).remove(t);
      if (getPart(oldLabel).isEmpty())  // if the old part is
       labelToObjs.remove(oldLabel);  // empty, remove it
      getPart(label).add(t);
      objToLabel.put(t,label);
     }
     public void moveAll(Collection<T> things, Integer label) {
      // Move all the things from their current part to label.
      // (This assumes all the things are in the same part.)
      if (things.size()==0)  return;

      T arbitraryThing = new ArrayList<T>(things).get(0);
      Set<T> oldPart = getPart(arbitraryThing);

   // THIS IS WHERE IT SEEMS TO GO WRONG //////////////////////////
      System.out.println(" oldPart = " + oldPart);
      System.out.println(" things = " + things);
      System.out.println("Now doing oldPart.removeAll(things) ...");
      oldPart.removeAll(things);
      System.out.println(" oldPart = " + oldPart);
      System.out.println(" things = " + things);

      if (oldPart.isEmpty())
       labelToObjs.remove(objToLabel.get(arbitraryThing));

      for (T t : things)
       objToLabel.put(t,label);
      getPart(label).addAll(things);
     }

     public String toString() {
      StringBuilder result = new StringBuilder();
      result.append("\nPARTITION OF " + size + " ELEMENTS INTO " +
        labelToObjs.size() + " PART");
      result.append((labelToObjs.size()==1 ? "" : "S") + "\n");
      for (Map.Entry<Integer,Set<T>> mapEntry :
        labelToObjs.entrySet()) {
       result.append("PART " + mapEntry.getKey() + ": ");
       result.append(mapEntry.getValue() + "\n");
      }
      return result.toString();
     }

     public static void main(String[] args) {
      List<String> strings =
        Arrays.asList("zero one two three".split(" "));

      Partition<String> p = new Partition<String>(strings);
      p.newPart(strings.get(3));  // move "three" to a new part
      System.out.println(p);

      System.out.println("Now moving all of three's part to the " +
        "same part as zero.\n");
      Collection<String> oldPart = p.getPart(strings.get(3));
      //oldPart = Arrays.asList(new String[]{"three"});  // works fine!
      p.moveAll(oldPart, p.getLabel(strings.get(0)));
      System.out.println(p);
     }
    }

/* OUTPUT
PARTITION OF 4 ELEMENTS INTO 2 PARTS
PART 0: [two, one, zero]
PART 1: [three]

Now moving all of three's part to the same part as zero.

 oldPart = [three]
 things = [three]
Now doing oldPart.removeAll(things) ...
 oldPart = []
 things = []

PARTITION OF 4 ELEMENTS INTO 1 PART
PART 0: [two, one, zero]
*/

Body:
Your code is extremely confusing but as far as I can work out, oldPart and things are actually the same object. Set.removeAll() certainly doesn't affect its argument unless it is the same object as it's invoked on:

public boolean removeAll(Collection<?> c) {
    boolean modified = false;

    if (size() > c.size()) {
        for (Iterator<?> i = c.iterator(); i.hasNext(); )
            modified |= remove(i.next());
    } else {
        for (Iterator<?> i = iterator(); i.hasNext(); ) {
            if (c.contains(i.next())) {
                i.remove();
                modified = true;
            }
        }
    }
    return modified;
}

Update:

The easy way to eliminate this is to use a copy of things in the moveAll() method. Indeed such a copy already exists.

T arbitraryThing = new ArrayList<T>(things).get(0);

This line creates but then instantly discards a copy of things. So I'd suggest replacing it with:

ArrayList<T> thingsToRemove = new ArrayList<T>(things)
T arbitraryThing = thingsToRemove.get(0);

And in the rest of the method, replace all references to things to thingsToRemove.


问:
I need help making a random number generator as a lock in a simple game
Basically, I wanted to be able to make a code that would generate a random number and have the user try and guess that number by putting in an input. I thought it would work, but it just runs the else statement everytime even if I do guess the right number.</p>

```<code>import random
def main():
  values = [1, 2, 3, 5, 7, 10]
  a = random.choice(values)
  print (a) ##########To see what the number is#########
  b = input('Enter a number: ')
  if b == a:
    print('You have guessed the number!')
  else:
    print('Try again')
    main()
main()
</code>```

答:
Your if condition is checking a string with an integer. Convert the input number b to int using int(b) before checking or while checking.

```<code>import random
def main():
    values = [1, 2, 3, 5, 7, 10]
    a = random.choice(values)
    print (a) ##########To see what the number is#########
    b = input('Enter a number: ')
    if int(b) == a:
        print('You have guessed the number!')
    else:
        print('Try again')
        main()
main()
</code>```

To know more, you can print the type of a and b inside the function

```<code>print(type(a))
print(type(b))

<class 'int'>
<class 'str'>
</code>```

Updated the indentation of main() to be inside else condition, as per suggestions from @nfnneil.

Body:
Basically, I wanted to be able to make a code that would generate a random number and have the user try and guess that number by putting in an input. I thought it would work, but it just runs the else statement everytime even if I do guess the right number.

import random
def main():
  values = [1, 2, 3, 5, 7, 10]
  a = random.choice(values)
  print (a) ##########To see what the number is#########
  b = input('Enter a number: ')
  if b == a:
    print('You have guessed the number!')
  else:
    print('Try again')
    main()
main()

Body:
Your if condition is checking a string with an integer. Convert the input number b to int using int(b) before checking or while checking.

import random
def main():
    values = [1, 2, 3, 5, 7, 10]
    a = random.choice(values)
    print (a) ##########To see what the number is#########
    b = input('Enter a number: ')
    if int(b) == a:
        print('You have guessed the number!')
    else:
        print('Try again')
        main()
main()

To know more, you can print the type of a and b inside the function

print(type(a))
print(type(b))

<class 'int'>
<class 'str'>

Updated the indentation of main() to be inside else condition, as per suggestions from @nfnneil.


问:
Is there a technical reason why the implementation isn't just impl Foo<T>?
I just learned that structs using generics are declared as struct Foo<T>, and that the implementation is declared as impl<T> Foo<T>. The book explains the discrepancy in the following way:

Note that we have to declare T just after impl in order to use T in the type Point<T>. Declaring T as a generic type after the impl is how Rust knows the type in the angle brackets in Point is a generic type rather than a concrete type.

Again, I'm a newbie, but couldn't the same argument be made for having to declare struct<T> Foo<T> (and possibly even fn<T> foo<T>(bar: T))?

答:
In addition to @dk's answer, I would like to compare how Rust does it to how Haskell does it.

In Haskell, all specific types must start capitalized. Thus, it is illegal to write:

data mytype Var = Constructor {
    myVar :: Var,
    myInt :: Foo
}
```

<p>Instead, Haskell reserves types which start with a lower-cased letter for type variables:</p>

<pre class="lang-haskell prettyprint-override"><code>data MyType var = Constructor {
     myVar :: var
     myInt :: Int
}

instance MyClass (MyType var) where
     ...
</code>```

Here, var is a type variable, MyType is concrete, and Int is concrete.

In my opinion - which you may not share, Rust made the mistake to allow non-capitalized type-identifiers. Thus the language has no other choice but to require you to explicitly say which type identifiers are variables and which are specific. An argument could be made that Rust's explicitness improves readability. The opposite could also be argued.

Rust could of course add a hypothetical feature where you may say:

```<code> impl Foo<#T, T, u32> { .. }
</code>```

Here, the prefix # is taken to mean "This is a type variable", so #T is a type variable, T is specific, and u32 is specific. There is no ambiguity and only local reasoning is required.

With this feature, you may get a little bit less verbosity, but I firmly believe this ship has sailed - adding this feature now will only add another way of doing the same thing for very little gain. The feature would however add the cost of having another feature that the language users must learn.

Body:
In addition to @dk's answer, I would like to compare how Rust does it to how Haskell does it.

In Haskell, all specific types must start capitalized. Thus, it is illegal to write:

data mytype Var = Constructor {
    myVar :: Var,
    myInt :: Foo
}

Instead, Haskell reserves types which start with a lower-cased letter for type variables:

data MyType var = Constructor {
     myVar :: var
     myInt :: Int
}

instance MyClass (MyType var) where
     ...

Here, var is a type variable, MyType is concrete, and Int is concrete.

In my opinion - which you may not share, Rust made the mistake to allow non-capitalized type-identifiers. Thus the language has no other choice but to require you to explicitly say which type identifiers are variables and which are specific. An argument could be made that Rust's explicitness improves readability. The opposite could also be argued.

Rust could of course add a hypothetical feature where you may say:

 impl Foo<#T, T, u32> { .. }

Here, the prefix # is taken to mean "This is a type variable", so #T is a type variable, T is specific, and u32 is specific. There is no ambiguity and only local reasoning is required.

With this feature, you may get a little bit less verbosity, but I firmly believe this ship has sailed - adding this feature now will only add another way of doing the same thing for very little gain. The feature would however add the cost of having another feature that the language users must learn.


问:
Restrict openid-connect userinfo request from unknown source
How to restrict openid-connect request from the unknown source.

If we've Access Token available anyone can request for userinfo (we are saving user information and claims into userinfo) which we want to restrict.

means, the request we should allow from known clients only.

Note: we are using Keycloak as Identity Server

Please help!!

答:
First and foremost, access token must be protected as same as user credentials. What OAuth2.0 framework give us is the ability to replace username/password based authentication/authorization with dynamically generated tokens. Thus these tokens must be protected. That is why TLS is a must for token transmission.

RFC6749 section 10.3 - Access token credentials (as well as any
confidential access token    attributes) MUST be kept confidential in
transit and storage, and    only shared among the authorization
server, the resource servers the    access token is valid for, and the
client to whom the access token is    issued.  Access token
credentials MUST only be transmitted using TLS    as described in
Section 1.6 with server authentication as defined by    [RFC2818].

So if you are worrying over access token misuse, you must first worry about adopting token based communication. Your clients must be secure enough not to misuse the tokens.

Also one other thing you can do is to enable CORS headers to restrict the access to the endpoint. But, this is only after protecting the tokens.!

p.s Alternatively, network configurations can be set to allow only the known/valid IP addresses to communicate to your back end. But that is out of the OIDC protocol.


问:
Function composition, tuples and unpacking
(disclaimed: not a Python kid, so please be gentle)

I am trying to compose functions using the following:

```<code>def compose(*functions):
  return functools.reduce(lambda acc, f: lambda x: acc(f(x)), functions, lambda x: x)
</code>```

which works as expected for scalar functions. I'd like to work with functions returning tuples and others taking multiple arguments, eg.

```<code>def dummy(name):
  return (name, len(name), name.upper())

def transform(name, size, upper):
  return (upper, -size, name)

# What I want to achieve using composition,
# ie. f = compose(transform, dummy)
transform(*dummy('Australia'))
=> ('AUSTRALIA', -9, 'Australia')
</code>```

Since dummy returns a tuple and transform takes three arguments, I need to unpack the value.

How can I achieve this using my compose function above? If I try like this, I get:

```<code>f = compose(transform, dummy)
f('Australia')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in <lambda>
  File "<stdin>", line 2, in <lambda>
TypeError: transform() takes exactly 3 arguments (1 given)
</code>```

Is there a way to change compose such that it will unpack where needed?

答:
The compose function in the answer contributed by Bruno did do the job for functions with multiple arguments but didn't work any more for scalar ones unfortunately.

Using the fact that Python `unpacks' tuples into positional arguments, this is how I solved it:

```<code>import functools

def compose(*functions):
  def pack(x): return x if type(x) is tuple else (x,)

  return functools.reduce(
    lambda acc, f: lambda *y: f(*pack(acc(*pack(y)))), reversed(functions), lambda *x: x)
</code>```

which now works just as expected, eg.

```<code>#########################
# scalar-valued functions
#########################

def a(x): return x + 1
def b(x): return -x

# explicit
> a(b(b(a(15))))
# => 17

# compose
> compose(a, b, b, a)(15)
=> 17

########################
# tuple-valued functions
########################

def dummy(x):
  return (x.upper(), len(x), x)
def trans(a, b, c):
  return (b, c, a)

# explicit
> trans(*dummy('Australia'))
# => ('AUSTRALIA', 9, 'Australia')

# compose
> compose(trans, dummy)('Australia')
# => ('AUSTRALIA', 9, 'Australia')
</code>```

And this also works with multiple arguments:

```<code>def add(x, y): return x + y

# explicit
> b(a(add(5, 3)))
=> -9

# compose
> compose(b, a, add)(5, 3)
=> -9
</code>```

Body:
(disclaimed: not a Python kid, so please be gentle)

I am trying to compose functions using the following:

def compose(*functions):
  return functools.reduce(lambda acc, f: lambda x: acc(f(x)), functions, lambda x: x)

which works as expected for scalar functions. I'd like to work with functions returning tuples and others taking multiple arguments, eg.

def dummy(name):
  return (name, len(name), name.upper())

def transform(name, size, upper):
  return (upper, -size, name)

# What I want to achieve using composition,
# ie. f = compose(transform, dummy)
transform(*dummy('Australia'))
=> ('AUSTRALIA', -9, 'Australia')

Since dummy returns a tuple and transform takes three arguments, I need to unpack the value.

How can I achieve this using my compose function above? If I try like this, I get:

f = compose(transform, dummy)
f('Australia')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in <lambda>
  File "<stdin>", line 2, in <lambda>
TypeError: transform() takes exactly 3 arguments (1 given)

Is there a way to change compose such that it will unpack where needed?

Body:
The compose function in the answer contributed by Bruno did do the job for functions with multiple arguments but didn't work any more for scalar ones unfortunately.

Using the fact that Python `unpacks' tuples into positional arguments, this is how I solved it:

import functools

def compose(*functions):
  def pack(x): return x if type(x) is tuple else (x,)

  return functools.reduce(
    lambda acc, f: lambda *y: f(*pack(acc(*pack(y)))), reversed(functions), lambda *x: x)

which now works just as expected, eg.

#########################
# scalar-valued functions
#########################

def a(x): return x + 1
def b(x): return -x

# explicit
> a(b(b(a(15))))
# => 17

# compose
> compose(a, b, b, a)(15)
=> 17

########################
# tuple-valued functions
########################

def dummy(x):
  return (x.upper(), len(x), x)
def trans(a, b, c):
  return (b, c, a)

# explicit
> trans(*dummy('Australia'))
# => ('AUSTRALIA', 9, 'Australia')

# compose
> compose(trans, dummy)('Australia')
# => ('AUSTRALIA', 9, 'Australia')

And this also works with multiple arguments:

def add(x, y): return x + y

# explicit
> b(a(add(5, 3)))
=> -9

# compose
> compose(b, a, add)(5, 3)
=> -9


问:
Evaluate symbolic matrix in MATLAB
I defined 2 symbolic matrix in MATLAB, for example

```<code>w = sym('w',[10,10])
</code>```

Then I do some operations on it and get function E dependent to symbolic matrix w and v. Now, I want to evaluate E numerically with numerical w and v.

How can I do this?

答:
We can use such code:

```<code> >> w=sym('w',[10 10]);
 >> d=sym('d',[10 1]);
 >> E=W*d + ...(some other operations)
 >> define a numerical matrix f and vector x)
 >> subs(subs(E,w,f),d,x)
</code>```

This code performed in R2014a and had a correct answer.

Title: Evaluate symbolic matrix in MATLAB

Body:
I defined 2 symbolic matrix in MATLAB, for example

w = sym('w',[10,10])

Then I do some operations on it and get function E dependent to symbolic matrix w and v. Now, I want to evaluate E numerically with numerical w and v.

How can I do this?

Body:
We can use such code:

 >> w=sym('w',[10 10]);
 >> d=sym('d',[10 1]);
 >> E=W*d + ...(some other operations)
 >> define a numerical matrix f and vector x)
 >> subs(subs(E,w,f),d,x)

This code performed in R2014a and had a correct answer.


问:
Having trouble using Arraylist.get method and it's showing "Incompatible operand types Object and int"
I was trying to take an unknown number of integers from the user (until the user enters 0), and count the number of occurrences of each of the integers entered. I figured, to count after I'm done taking the integers, I'd have to store them in an array. And I did some research and realized that the only way to create an Array with an unspecified length, ArrayList is the only way. But my this part of the code is showing error:</p>

```<code>import java.util.Scanner;

import java.util.ArrayList;

public class IntegersOccurence {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        System.out.print("Enter the integers between 1 and 100: ");
        ArrayList list = new ArrayList();
        System.out.println(list.get(0));
        //eclipse is showing an error in the line right below
        while (list.get(list.size() - 1) != 0) {
            list.add(input.nextInt());
        }
    }
}
</code>```

答:
Change below line:

```<code>ArrayList list = new ArrayList();
</code>```

To:

```<code>ArrayList<Integer> list = new ArrayList<>();
</code>```

By default the type of your list is Object, by defining the datatype we avoid runtime type errors and the check is being done in compile time.

Body:
I was trying to take an unknown number of integers from the user (until the user enters 0), and count the number of occurrences of each of the integers entered. I figured, to count after I'm done taking the integers, I'd have to store them in an array. And I did some research and realized that the only way to create an Array with an unspecified length, ArrayList is the only way. But my this part of the code is showing error:

import java.util.Scanner;

import java.util.ArrayList;

public class IntegersOccurence {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        System.out.print("Enter the integers between 1 and 100: ");
        ArrayList list = new ArrayList();
        System.out.println(list.get(0));
        //eclipse is showing an error in the line right below
        while (list.get(list.size() - 1) != 0) {
            list.add(input.nextInt());
        }
    }
}

Body:
Change below line:

ArrayList list = new ArrayList();

To:

ArrayList<Integer> list = new ArrayList<>();

By default the type of your list is Object, by defining the datatype we avoid runtime type errors and the check is being done in compile time.