问:
Error 415 Web service Rest with Spring
i'm having a problem with my service. I'm trying to send the datas to the database. However, i'm receiving this message:

Error 415

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

I'm using Postman to sendo the code below:

Postman

Controller:

```<code>package br.com.standard.controller;

import java.util.List;
import br.com.standard.bean.Client;
import br.com.standard.service.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ClientController {

        @Autowired
        ClientService clientService;

        @RequestMapping(value = "/addClient", method = RequestMethod.POST, headers = "Accept=application/json")
        public void addClient(@RequestBody Client client) {
            clientService.addClient(client);

        }

}
</code>```

Model

```<code>import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="client")
public class Client {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int id;

    @Column(name="name")
    String nome;

    public Client() {
        super();
    }

    public Client(int id, String nome) {
        super();
        this.id = id;
        this.nome = nome;
    }

    public long getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

}
</code>```

I know that it probably is a simple question, but i tried a lot of ways without success.

Thanks in advance.

答:
Two (alternative) solution proposals:

Be sure to send the header: Accept=application/json! (with your client.)

...or change headers = "Accept=application/json" to
consumes = org.springframework.http.MediaType.APPLICATION_JSON (leaving everything else as is)

Title: Error 415 Web service Rest with Spring

Body:
i'm having a problem with my service. I'm trying to send the datas to the database. However, i'm receiving this message:

Error 415

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

I'm using Postman to sendo the code below:

Postman

Controller:

package br.com.standard.controller;

import java.util.List;
import br.com.standard.bean.Client;
import br.com.standard.service.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ClientController {

        @Autowired
        ClientService clientService;

        @RequestMapping(value = "/addClient", method = RequestMethod.POST, headers = "Accept=application/json")
        public void addClient(@RequestBody Client client) {
            clientService.addClient(client);

        }

}

Model

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="client")
public class Client {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int id;

    @Column(name="name")
    String nome;

    public Client() {
        super();
    }

    public Client(int id, String nome) {
        super();
        this.id = id;
        this.nome = nome;
    }

    public long getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

}

I know that it probably is a simple question, but i tried a lot of ways without success.

Thanks in advance.


来源: stackexchange

问:
Conditionally replace elements of a vector based on an index
It's best explained with an example.

I have a vector, or column from data.frame named vec:

```<code>vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)
</code>```

I would like a vectorized process (not a for loop) to change the three trailing NA when a 1 is observed.

The end vector would be:

```<code>c(NA, NA, 1, 1, 1, 1, NA, 1, 1, 1, 1, NA, NA, NA)
</code>```

If we had:

```<code>vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)
</code>```

The end vector would look like:

```<code>c(NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA)
</code>```

A very badly written solution is:

```<code>vec2 <- vec
for(i in index(v)){
  if(!is.na(v[i])) vec2[i] <- 1
  if(i>3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
    if(!is.na(vec[i-3])) vec2[i] <- 1
  }
  if(i==3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
  }
  if(i==2){
    if(!is.na(vec[i-1])) vec2[i] <- 1
  }
}
</code>```

答:
With sapply, any, and is.na:

```<code>output <- sapply(1:length(vec),function(i){any(!is.na(vec[max(0,i-3):i]))})
output[output] <- 1
output[output==0] <- NA
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It's best explained with an example.

I have a vector, or column from data.frame named vec:

vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)

I would like a vectorized process (not a for loop) to change the three trailing NA when a 1 is observed.

The end vector would be:

c(NA, NA, 1, 1, 1, 1, NA, 1, 1, 1, 1, NA, NA, NA)

If we had:

vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)

The end vector would look like:

c(NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA)

A very badly written solution is:

vec2 <- vec
for(i in index(v)){
  if(!is.na(v[i])) vec2[i] <- 1
  if(i>3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
    if(!is.na(vec[i-3])) vec2[i] <- 1
  }
  if(i==3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
  }
  if(i==2){
    if(!is.na(vec[i-1])) vec2[i] <- 1
  }
}

Body:
With sapply, any, and is.na:

output <- sapply(1:length(vec),function(i){any(!is.na(vec[max(0,i-3):i]))})
output[output] <- 1
output[output==0] <- NA


问:
CSS Grid vertical columns with infinite rows
I have a list of items of unknown length (from a CMS). I want to display them in 2 vertical columns reading down. e.g.

```
1 4
2 5
3 6

etc...
```

I am trying to achieve this with CSS grid, however, it doesn't seem possible unless you set the number of rows up front. I have tried grid-auto-flow: column as per https://gridbyexample.com/examples/example18/ but this just adds additional columns when it gets to the end.

I feel like this should be possible with grid, but I can't find a way. Anyone have any ideas?

P.S. Please don't suggest CSS text columns.

答:
Without knowing the exact amount of items this is not possible with CSS grid alone.

The only way to get around this limitation is to add a class to your second half of the items.

body {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow: row dense;

  /* extra styles */
  grid-gap: 0.5rem;
}

span {
  grid-column-start: 1;

  /* extra styles */
  background-color: #def;
  padding: 0.5rem;
}

.second-half {
  grid-column-start: 2;

  /* extra styles */
  background-color: #abc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span class="second-half">5</span>
<span class="second-half">6</span>
<span class="second-half">7</span></code>```

Body:
I have a list of items of unknown length (from a CMS). I want to display them in 2 vertical columns reading down. e.g.

1 4
2 5
3 6

etc...

I am trying to achieve this with CSS grid, however, it doesn't seem possible unless you set the number of rows up front. I have tried grid-auto-flow: column as per https://gridbyexample.com/examples/example18/ but this just adds additional columns when it gets to the end.

I feel like this should be possible with grid, but I can't find a way. Anyone have any ideas?

P.S. Please don't suggest CSS text columns.

Body:
Without knowing the exact amount of items this is not possible with CSS grid alone.

The only way to get around this limitation is to add a class to your second half of the items.

body {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow: row dense;

  /* extra styles */
  grid-gap: 0.5rem;
}

span {
  grid-column-start: 1;

  /* extra styles */
  background-color: #def;
  padding: 0.5rem;
}

.second-half {
  grid-column-start: 2;

  /* extra styles */
  background-color: #abc;
}

<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span class="second-half">5</span>
<span class="second-half">6</span>
<span class="second-half">7</span>


问:
How to pause background music when app is running in background
I created a game.I added some background music to the app and now I want to pause the music when the app is exited using home button and the song should resume when it is opened from the multitasking.</p>

```<code>package tssll8.coloursmash;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
Import android.os.IBinder;

/**
 * Created by ciddarth on 04/07/17.
 */

public class bgmusic extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {

    return null;
}
@Override
public void onCreate() {
    super.onCreate();
    player = MediaPlayer.create(this, R.raw.bg);
    player.setLooping(true); // Set looping
    player.setVolume(100,100);

}
public int onStartCommand(Intent intent, int flags, int startId) {
    player.start();
    return 1;
}

public void onStart(Intent intent, int startId) {
    // TO DO
}
public IBinder onUnBind(Intent arg0) {
    // TO DO Auto-generated method
    return null;
}

public void onStop() {

}
public void onPause() {

}
@Override
public void onDestroy() {
    player.stop();
    player.release();
}

@Override
public void onLowMemory() {

}
}
</code>```

答:
Mediaplayer has a pause() method: MediaPlayer#pause()

so you could call that in the on pause which gets triggered by pressing the home button, like so

```<code>public void onPause() {
    player.pause();
}
</code>```

and resume it in onResume like this:

```<code>public void onResume() {
    player.play();
}
</code>```

Body:
I created a game.I added some background music to the app and now I want to pause the music when the app is exited using home button and the song should resume when it is opened from the multitasking.

package tssll8.coloursmash;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
Import android.os.IBinder;

/**
 * Created by ciddarth on 04/07/17.
 */

public class bgmusic extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {

    return null;
}
@Override
public void onCreate() {
    super.onCreate();
    player = MediaPlayer.create(this, R.raw.bg);
    player.setLooping(true); // Set looping
    player.setVolume(100,100);

}
public int onStartCommand(Intent intent, int flags, int startId) {
    player.start();
    return 1;
}

public void onStart(Intent intent, int startId) {
    // TO DO
}
public IBinder onUnBind(Intent arg0) {
    // TO DO Auto-generated method
    return null;
}

public void onStop() {

}
public void onPause() {

}
@Override
public void onDestroy() {
    player.stop();
    player.release();
}

@Override
public void onLowMemory() {

}
}

Body:
Mediaplayer has a pause() method: MediaPlayer#pause()

so you could call that in the on pause which gets triggered by pressing the home button, like so

public void onPause() {
    player.pause();
}

and resume it in onResume like this:

public void onResume() {
    player.play();
}


问:
ASP.Net httpruntime executionTimeout not working (and yes debug=false)
We just recently noticed that executionTimeout has stopped working on our website.  It was definitely working ~last year ... hard to say when it stopped.

We are currently running on:

Windows-2008x64

IIS7

32bit binaries

Managed Pipeline Mode = classic

Framework version = v2.0

Web.Config has

```<code><compilation defaultLanguage="vb" debug="false" batch="true">
<httpRuntime executionTimeout="90" />
</code>```

Any hints on why we are seeing Timetaken all the way up to ~20 minutes.  Would compilation options for DebugType (full vs pdbonly) have any effect?

```<code>datetime       timetaken httpmethod Status  Sent    Received<BR>
12/19/10 0:10  901338    POST       302 456 24273<BR>
12/19/10 0:18  1817446   POST       302 0   114236<BR>
12/19/10 0:16  246923    POST       400 0   28512<BR>
12/19/10 0:12  220450    POST       302 0   65227<BR>
12/19/10 0:22  400150    GET        200 180835  416<BR>
12/19/10 0:20  335455    POST       400 0   36135<BR>
12/19/10 0:57  213210    POST       302 0   51558<BR>
12/19/10 0:48  352742    POST       302 438 25802<BR>
12/19/10 0:37  958660    POST       400 0   24558<BR>
12/19/10 0:06  202025    POST       302 0   58349<BR>
</code>```

答:
Execution timeout and time-taken time two different things.  Although, the size of the discrepancy is troubling.

time-taken includes all of the network time in the request/response (under certain conditions.).  The network transfer time easily outstrips the amount of time a request really takes.  Though, normally, I'm used to just seconds of difference not minutes.

Execution timeout refers only to the amount of time the worker process spent processing the request; which is just a subset of time-taken.  It only applies if the debug attribute is set to false; which it looks like you have.

Of course, assuming the first request you listed took the full 90 seconds of allowed time out, that still leaves 13.5 minutes left in the time-taken window to transfer essentially 24k of data.  That sounds like a serious network issue.

So, either you have a serious transport issue or there is another web.config file somewhere in the tree where the requests are being processed that either sets debug to true or increases the execution timeout to something astronomical.

Another possibility is that the page itself has either the debug attribute set or it's own timeout values.

Body:
We just recently noticed that executionTimeout has stopped working on our website.  It was definitely working ~last year ... hard to say when it stopped.

We are currently running on:

Windows-2008x64

IIS7

32bit binaries

Managed Pipeline Mode = classic

Framework version = v2.0

Web.Config has

<compilation defaultLanguage="vb" debug="false" batch="true">
<httpRuntime executionTimeout="90" />

Any hints on why we are seeing Timetaken all the way up to ~20 minutes.  Would compilation options for DebugType (full vs pdbonly) have any effect?

datetime       timetaken httpmethod Status  Sent    Received

12/19/10 0:10  901338    POST       302 456 24273

12/19/10 0:18  1817446   POST       302 0   114236

12/19/10 0:16  246923    POST       400 0   28512

12/19/10 0:12  220450    POST       302 0   65227

12/19/10 0:22  400150    GET        200 180835  416

12/19/10 0:20  335455    POST       400 0   36135

12/19/10 0:57  213210    POST       302 0   51558

12/19/10 0:48  352742    POST       302 438 25802

12/19/10 0:37  958660    POST       400 0   24558

12/19/10 0:06  202025    POST       302 0   58349

ContentLicense: CC BY-SA 4.0


问:
VScode will not auto push when I commit changes
I can commit loads of changes, but nothing gets to github.

Its only when I manually click the PUSH function from the menu that it pushes to github.

How can I get it to do this automatically when I commit?

These are my VS GIT settings:

```<code> // Whether git is enabled
  "git.enabled": true,

  // Path to the git executable
  "git.path": null,

  // Whether auto refreshing is enabled
  "git.autorefresh": true,

  // Whether auto fetching is enabled
  "git.autofetch": true,

  // Confirm before synchronizing git repositories
  "git.confirmSync": true,

  // Controls the git badge counter. `all` counts all changes. `tracked` counts only the tracked changes. `off` turns it off.
  "git.countBadge": "all",

  // Controls what type of branches are listed when running `Checkout to...`. `all` shows all refs, `local` shows only the local branchs, `tags` shows only tags and `remote` shows only remote branches.
  "git.checkoutType": "all",

  // Ignores the legacy Git warning
  "git.ignoreLegacyWarning": false,

  // Ignores the warning when there are too many changes in a repository
  "git.ignoreLimitWarning": false,

  // The default location where to clone a git repository
  "git.defaultCloneDirectory": null,

  // Commit all changes when there are not staged changes.
  "git.enableSmartCommit": false,
</code>```

答:
According to this issue on GitHub, this feature does not exist and is not planned to be added.

They suggest using Git hooks to achieve this behavior.

Something like this:

```<code>#!/usr/bin/env bash

branch_name=`git symbolic-ref --short HEAD`
retcode=$?

# Only push if branch_name was found (my be empty if in detached head state)
if [ $retcode = 0 ] ; then
    #Only push if branch_name is master
    if [[ $branch_name = "master" ]] ; then
        echo
        echo "**** Pushing current branch $branch_name to origin ****"
        echo
        git push origin $branch_name;
    fi
fi
</code>```

You can check this answer for more details and options.

Body:
I can commit loads of changes, but nothing gets to github.

Its only when I manually click the PUSH function from the menu that it pushes to github.

How can I get it to do this automatically when I commit?

These are my VS GIT settings:

 // Whether git is enabled
  "git.enabled": true,

  // Path to the git executable
  "git.path": null,

  // Whether auto refreshing is enabled
  "git.autorefresh": true,

  // Whether auto fetching is enabled
  "git.autofetch": true,

  // Confirm before synchronizing git repositories
  "git.confirmSync": true,

  // Controls the git badge counter. `all` counts all changes. `tracked` counts only the tracked changes. `off` turns it off.
  "git.countBadge": "all",

  // Controls what type of branches are listed when running `Checkout to...`. `all` shows all refs, `local` shows only the local branchs, `tags` shows only tags and `remote` shows only remote branches.
  "git.checkoutType": "all",

  // Ignores the legacy Git warning
  "git.ignoreLegacyWarning": false,

  // Ignores the warning when there are too many changes in a repository
  "git.ignoreLimitWarning": false,

  // The default location where to clone a git repository
  "git.defaultCloneDirectory": null,

  // Commit all changes when there are not staged changes.
  "git.enableSmartCommit": false,

Body:
According to this issue on GitHub, this feature does not exist and is not planned to be added.

They suggest using Git hooks to achieve this behavior.

Something like this:

#!/usr/bin/env bash

branch_name=`git symbolic-ref --short HEAD`
retcode=$?

# Only push if branch_name was found (my be empty if in detached head state)
if [ $retcode = 0 ] ; then
    #Only push if branch_name is master
    if [[ $branch_name = "master" ]] ; then
        echo
        echo "**** Pushing current branch $branch_name to origin ****"
        echo
        git push origin $branch_name;
    fi
fi

You can check this answer for more details and options.


问:
How to list table foreign keys
Is there a way using SQL to list all foreign keys for a given table? I know the table name / schema and I can plug that in.</p>

答:
Note: Do not forget column's order while reading constraint columns!</p>

```<code>SELECT conname, attname
  FROM pg_catalog.pg_constraint c
  JOIN pg_catalog.pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY (c.conkey)
 WHERE attrelid = 'schema.table_name'::regclass
 ORDER BY conname, array_position(c.conkey, a.attnum)
</code>```

Title: How to list table foreign keys

Body:
Note: Do not forget column's order while reading constraint columns!

SELECT conname, attname
  FROM pg_catalog.pg_constraint c
  JOIN pg_catalog.pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY (c.conkey)
 WHERE attrelid = 'schema.table_name'::regclass
 ORDER BY conname, array_position(c.conkey, a.attnum)


问:
List WPA supplicant network properties using dbus-cpp
When trying to list network properties - https://w1.fi/wpa_supplicant/devel/dbus.html#dbus_network using dbus-cpp I get a number of errors about missing operator== for core::dbus::types::Variant

```<code>/usr/include/core/dbus/impl/object.h:185:17:   required from ‘std::shared_ptr<core::dbus::Property<PropertyDescription> > core::dbus::Object::get_property() [with PropertyDescription = fi::w1::wpa_supplicant1::Network::Properties::Propertiez]’ /home/martin/ClionProjects/ang-wifi-controller/src/wpasupplicantclient.cpp:149:118:   required from here /usr/include/c++/6/bits/stl_pair.h:364:51: error: no match for ‘operator==’ (operand types are ‘const core::dbus::types::Variant’ and ‘const core::dbus::types::Variant’)
 { return __x.first == __y.first && __x.second == __y.second; }
</code>```

My code is based on dbus-cpp examples and http://quaintous.com/2015/08/30/cpp11-dbus/, but they only offer limited assistance.
The code representing Properties property is as follows:

```<code>namespace fi {
namespace w1 {
struct wpa_supplicant1 {
struct Network {
    struct Properties {
        struct Propertiez {
            inline static std::string name() { return "Properties"; };
            typedef Network Interface;
            typedef std::map<std::string, core::dbus::types::Variant> ValueType;
            static const bool readable = true;
            static const bool writable = true;
        };
    };
};
</code>```

And the offending line in .cpp is networkProxy->get_property<fi::w1::wpa_supplicant1::Network::Properties::Propertiez>();

I found that this question has already been asked at https://answers.launchpad.net/ubuntu/+source/dbus-cpp/+question/593271, but nobody offered any advice. Going through the code of packages listed by apt-cache rdepends libdbus-cpp5 also yielded no results.
I tried messing with the ValueType but it all resulted in runtime errors as the expected result probably truly is the map. It honestly seems like a bug in the library to me, but since this must be an obvious use case I am trying to find the mistake in my usage of the library. So what am I doing wrong?

Edit: Since I did not get any response, I am including minimal sample.

```<code>#include <core/dbus/bus.h>
#include <core/dbus/object.h>
#include <core/dbus/property.h>
#include <core/dbus/service.h>
#include <core/dbus/result.h>
#include <core/dbus/asio/executor.h>
#include <core/dbus/interfaces/properties.h>
#include <core/dbus/types/stl/string.h>
#include <core/dbus/types/stl/tuple.h>
#include <core/dbus/types/stl/vector.h>
#include <core/dbus/types/struct.h>
#include <core/dbus/types/variant.h>

using namespace std::chrono_literals;
using DBusDict = std::map<std::string, core::dbus::types::Variant>;

namespace fi {
namespace w1 {
struct wpa_supplicant1
{
    struct GetInterface {
        typedef wpa_supplicant1 Interface;
        static const std::string &name()
        {
            static const std::string s("GetInterface");
            return s;
        }
        inline static const std::chrono::milliseconds default_timeout() { return 1s; }
    };
    struct Iface
    {
        struct AddNetwork {
            typedef Iface Interface;
            static const std::string &name()
            {
                static const std::string s("AddNetwork");
                return s;
            }
            inline static const std::chrono::milliseconds default_timeout() { return 1s; }
        };
        struct Properties
        {
            struct Networks
            {
                inline static std::string name()
                { return "Networks"; };
                typedef Iface Interface;
                typedef std::vector<core::dbus::types::ObjectPath> ValueType;
                static const bool readable = true;
                static const bool writable = false;
            };
        };
    };
    struct Network
    {
        struct Properties
        {
            struct Propertiez
            {
                inline static std::string name()
                { return "Properties"; };
                typedef Network Interface;
                typedef DBusDict ValueType;
                static const bool readable = true;
                static const bool writable = true;
            };
        };
    };
};
};
};

namespace core {
namespace dbus {
namespace traits {
template <> struct Service<fi::w1::wpa_supplicant1> {
    inline static const std::string &interface_name()
    {
        static const std::string s("fi.w1.wpa_supplicant1");
        return s;
    }
};

template <> struct Service<fi::w1::wpa_supplicant1::Iface> {
    inline static const std::string &interface_name()
    {
        static const std::string s("fi.w1.wpa_supplicant1.Interface");
        return s;
    }
};
template <> struct Service<fi::w1::wpa_supplicant1::Network> {
    inline static const std::string &interface_name()
    {
        static const std::string s("fi.w1.wpa_supplicant1.Network");
        return s;
    }
};
}
}
}

int main()
{
    //bus
    auto systemBus = std::make_shared<core::dbus::Bus>(core::dbus::WellKnownBus::system);
    systemBus->install_executor(core::dbus::asio::make_executor(systemBus));
    auto busThread = std::thread(std::bind(&core::dbus::Bus::run, systemBus));

    //service
    auto wpaService = core::dbus::Service::use_service<fi::w1::wpa_supplicant1>(systemBus);
    auto wpaObjectPath = core::dbus::types::ObjectPath("/fi/w1/wpa_supplicant1");
    auto wpaRootProxy = wpaService->object_for_path(wpaObjectPath);

    //iface
    auto ifacePath = wpaRootProxy->transact_method<fi::w1::wpa_supplicant1::GetInterface,
                                             core::dbus::types::ObjectPath,
                                             std::string>("wlan0"); //change this to your own wireless interface
    auto wpaIfaceProxy = wpaService->object_for_path(ifacePath.value());
    auto networkPaths = wpaIfaceProxy->get_property<fi::w1::wpa_supplicant1::Iface::Properties::Networks>();

    //network
    std::string ssid("network");
    std::string password("password");
    DBusDict args = {
        {"ssid", core::dbus::types::Variant::encode(ssid)},
        {"psk", core::dbus::types::Variant::encode(password)},
    };

    auto networkPath = wpaIfaceProxy->transact_method<fi::w1::wpa_supplicant1::Iface::AddNetwork,
                                                        core::dbus::types::ObjectPath,
                                                        DBusDict>(args);
    auto networkProxy = wpaService->object_for_path(networkPath.value());

    //get properties - uncomment line below to get compiler errors
    //auto netProps = networkProxy->get_property<fi::w1::wpa_supplicant1::Network::Properties::Propertiez>();

    while (true) {
        continue;
    }
}
</code>```

Compile using: g++ $(pkg-config --cflags dbus-1 dbus-cpp) ./main.cpp $(pkg-config --libs dbus-1 dbus-cpp) -lpthread

答:
As the documentation for fi.w1.wpa_supplicant1.Network.Properties.Properties says:

[...] All values are string type, e.g., frequency is "2437", not 2437.

So try to define DBusDict as follow:

```<code>using DBusDict = std::map<std::string, std::string>;
</code>```

Body:
When trying to list network properties - https://w1.fi/wpa_supplicant/devel/dbus.html#dbus_network using dbus-cpp I get a number of errors about missing operator== for core::dbus::types::Variant

/usr/include/core/dbus/impl/object.h:185:17:   required from ‘std::shared_ptr<core::dbus::Property<PropertyDescription> > core::dbus::Object::get_property() [with PropertyDescription = fi::w1::wpa_supplicant1::Network::Properties::Propertiez]’ /home/martin/ClionProjects/ang-wifi-controller/src/wpasupplicantclient.cpp:149:118:   required from here /usr/include/c++/6/bits/stl_pair.h:364:51: error: no match for ‘operator==’ (operand types are ‘const core::dbus::types::Variant’ and ‘const core::dbus::types::Variant’)
 { return __x.first == __y.first && __x.second == __y.second; }

My code is based on dbus-cpp examples and http://quaintous.com/2015/08/30/cpp11-dbus/, but they only offer limited assistance.
The code representing Properties property is as follows:

namespace fi {
namespace w1 {
struct wpa_supplicant1 {
struct Network {
    struct Properties {
        struct Propertiez {
            inline static std::string name() { return "Properties"; };
            typedef Network Interface;
            typedef std::map<std::string, core::dbus::types::Variant> ValueType;
            static const bool readable = true;
            static const bool writable = true;
        };
    };
};

And the offending line in .cpp is networkProxy->get_property<fi::w1::wpa_supplicant1::Network::Properties::Propertiez>();

I found that this question has already been asked at https://answers.launchpad.net/ubuntu/+source/dbus-cpp/+question/593271, but nobody offered any advice. Going through the code of packages listed by apt-cache rdepends libdbus-cpp5 also yielded no results.
I tried messing with the ValueType but it all resulted in runtime errors as the expected result probably truly is the map. It honestly seems like a bug in the library to me, but since this must be an obvious use case I am trying to find the mistake in my usage of the library. So what am I doing wrong?

Edit: Since I did not get any response, I am including minimal sample.

#include <core/dbus/bus.h>
#include <core/dbus/object.h>
#include <core/dbus/property.h>
#include <core/dbus/service.h>
#include <core/dbus/result.h>
#include <core/dbus/asio/executor.h>
#include <core/dbus/interfaces/properties.h>
#include <core/dbus/types/stl/string.h>
#include <core/dbus/types/stl/tuple.h>
#include <core/dbus/types/stl/vector.h>
#include <core/dbus/types/struct.h>
#include <core/dbus/types/variant.h>

using namespace std::chrono_literals;
using DBusDict = std::map<std::string, core::dbus::types::Variant>;

namespace fi {
namespace w1 {
struct wpa_supplicant1
{
    struct GetInterface {
        typedef wpa_supplicant1 Interface;
        static const std::string &name()
        {
            static const std::string s("GetInterface");
            return s;
        }
        inline static const std::chrono::milliseconds default_timeout() { return 1s; }
    };
    struct Iface
    {
        struct AddNetwork {
            typedef Iface Interface;
            static const std::string &name()
            {
                static const std::string s("AddNetwork");
                return s;
            }
            inline static const std::chrono::milliseconds default_timeout() { return 1s; }
        };
        struct Properties
        {
            struct Networks
            {
                inline static std::string name()
                { return "Networks"; };
                typedef Iface Interface;
                typedef std::vector<core::dbus::types::ObjectPath> ValueType;
                static const bool readable = true;
                static const bool writable = false;
            };
        };
    };
    struct Network
    {
        struct Properties
        {
            struct Propertiez
            {
                inline static std::string name()
                { return "Properties"; };
                typedef Network Interface;
                typedef DBusDict ValueType;
                static const bool readable = true;
                static const bool writable = true;
            };
        };
    };
};
};
};

namespace core {
namespace dbus {
namespace traits {
template <> struct Service<fi::w1::wpa_supplicant1> {
    inline static const std::string &interface_name()
    {
        static const std::string s("fi.w1.wpa_supplicant1");
        return s;
    }
};

template <> struct Service<fi::w1::wpa_supplicant1::Iface> {
    inline static const std::string &interface_name()
    {
        static const std::string s("fi.w1.wpa_supplicant1.Interface");
        return s;
    }
};
template <> struct Service<fi::w1::wpa_supplicant1::Network> {
    inline static const std::string &interface_name()
    {
        static const std::string s("fi.w1.wpa_supplicant1.Network");
        return s;
    }
};
}
}
}

int main()
{
    //bus
    auto systemBus = std::make_shared<core::dbus::Bus>(core::dbus::WellKnownBus::system);
    systemBus->install_executor(core::dbus::asio::make_executor(systemBus));
    auto busThread = std::thread(std::bind(&core::dbus::Bus::run, systemBus));

    //service
    auto wpaService = core::dbus::Service::use_service<fi::w1::wpa_supplicant1>(systemBus);
    auto wpaObjectPath = core::dbus::types::ObjectPath("/fi/w1/wpa_supplicant1");
    auto wpaRootProxy = wpaService->object_for_path(wpaObjectPath);

    //iface
    auto ifacePath = wpaRootProxy->transact_method<fi::w1::wpa_supplicant1::GetInterface,
                                             core::dbus::types::ObjectPath,
                                             std::string>("wlan0"); //change this to your own wireless interface
    auto wpaIfaceProxy = wpaService->object_for_path(ifacePath.value());
    auto networkPaths = wpaIfaceProxy->get_property<fi::w1::wpa_supplicant1::Iface::Properties::Networks>();

    //network
    std::string ssid("network");
    std::string password("password");
    DBusDict args = {
        {"ssid", core::dbus::types::Variant::encode(ssid)},
        {"psk", core::dbus::types::Variant::encode(password)},
    };

    auto networkPath = wpaIfaceProxy->transact_method<fi::w1::wpa_supplicant1::Iface::AddNetwork,
                                                        core::dbus::types::ObjectPath,
                                                        DBusDict>(args);
    auto networkProxy = wpaService->object_for_path(networkPath.value());

    //get properties - uncomment line below to get compiler errors
    //auto netProps = networkProxy->get_property<fi::w1::wpa_supplicant1::Network::Properties::Propertiez>();

    while (true) {
        continue;
    }
}

Compile using: g++ $(pkg-config --cflags dbus-1 dbus-cpp) ./main.cpp $(pkg-config --libs dbus-1 dbus-cpp) -lpthread

Body:
As the documentation for fi.w1.wpa_supplicant1.Network.Properties.Properties says:

[...] All values are string type, e.g., frequency is "2437", not 2437.

So try to define DBusDict as follow:

using DBusDict = std::map<std::string, std::string>;


问:
Find several groups of ocurrences in String with regex Scala
I have a String like this:

```<code>val rawData = "askljdld<a>content to extract</a>lkdsjkdj<a>more content to extract</a>sdkdljk
</code>```

and I want to extract the content between the tags

I've tried this, but the end part of the regex is not working as I expected:

```<code>val regex = "<a>(.*)</a>".r
for(m <- regex.findAllIn(rawData)){
      println(m)
    }
</code>```

the output is:

```<code><a>content to extract</a>lkdsjkdj<a>more content to extract</a>
</code>```

I understand what's happening: the regex finds the first  and the last .
How can I have an iterator with the two entries?

```<code><a>content to extract</a>
<a>more content to extract</a>
</code>```

thanks in advance

答:
All is very simple: "(.*?)"

.*? - means anything until something. In your case until

Body:
I have a String like this:

val rawData = "askljdldcontent to extractlkdsjkdjmore content to extractsdkdljk

and I want to extract the content between the tags

I've tried this, but the end part of the regex is not working as I expected:

val regex = "(.*)".r
for(m <- regex.findAllIn(rawData)){
      println(m)
    }

the output is:

content to extractlkdsjkdjmore content to extract

I understand what's happening: the regex finds the first  and the last .
How can I have an iterator with the two entries?

content to extract
more content to extract

thanks in advance

Body:
All is very simple: "<a>(.*?)</a>"

.*? - means anything until something. In your case until </a>


问:
Why there are only two panels now? [Info] [Build Settings]
There are only two panels in my App Info

Before this, I have opened it in Xcode 9 beta2, and now I'm in Xcode 8.3.3. Why there are only two panels left?

答:
You have selected the project and not your build target.

Make sure you have the target list visible.


问:
TPL DataFlow confusion around pipelines - should I create a new pipeline for each data call? How can I track data that's flowing through?
I'm struggling with how to apply TPL DataFlow to my application.

I've got a bunch of parallel data operations I want to track and manage, previously I was just using Tasks, but I'm trying to implement DataFlow to give me more control.

I'm composing a pipeline of tasks to say get the data and process it, here's an example of a pipeline to get data, process data, and log it as complete:

```<code>TransformBlock<string, string> loadDataFromFile = new TransformBlock<string, string>(filename =>
{
    // read the data file (takes a long time!)
    Console.WriteLine("Loading from " + filename);
    Thread.Sleep(2000);

    // return our result, for now just use the filename
    return filename + "_data";
});

TransformBlock<string, string> prodcessData = new TransformBlock<string, string>(data =>
{
    // process the data
    Console.WriteLine("Processiong data " + data);
    Thread.Sleep(2000);

    // return our result, for now just use the data string
    return data + "_processed";
});

TransformBlock<string, string> logProcessComplete= new TransformBlock<string, string>(data =>
{
    // Doesn't do anything to the data, just performs an 'action' (but still passses the data long, unlike ActionBlock)
    Console.WriteLine("Result " + data + " complete");
    return data;
});
</code>```

I'm linking them together like this:

```<code>// create a pipeline
loadDataFromFile.LinkTo(prodcessData);
prodcessData.LinkTo(logProcessComplete);
</code>```

I've been trying to follow this tutorial.

My confusion is that in the tutorial this pipeline seems to be a 'fire once' operation. It creates the pipeline and fires it off once, and it completes. This seems counter to how the Dataflow library seems designed, I've read:

The usual way of using TPL Dataflow is to create all the blocks, link
  them together, and then start putting data in one end.

From "Concurrency in C# Cookbook" by Stephen Cleary.

But I'm not sure how to track the data after I've put said data 'in one end'. I need to be able to get the processed data from multiple parts of the program, say the user presses two buttons, one to get the data from "File1" and do something with it, one to get the data from "File2", I'd need something like this I think:

```<code>public async Task loadFile1ButtonPress()
{
    loadDataFromFile.Post("File1");
    var data = await logProcessComplete.ReceiveAsync();
    Console.WriteLine($"Got data1: {data}");
}

public async Task loadFile2ButtonPress()
{
    loadDataFromFile.Post("File2");
    var data = await logProcessComplete.ReceiveAsync();
    Console.WriteLine($"Got data2: {data}");
}
</code>```

If these are performed 'synchronously' it works just fine, as there's only one piece of information flowing through the pipeline:

```<code>Console.WriteLine("waiting for File 1");
await loadFile1ButtonPress();
Console.WriteLine("waiting for File 2");
await loadFile2ButtonPress();
Console.WriteLine("Done");
</code>```

Produces the expected output:

```<code>waiting for File 1
Loading from File1
Processiong data File1_data
Result File1_data_processed complete
Got data1: File1_data_processed
waiting for File 2
Loading from File2
Processiong data File2_data
Result File2_data_processed complete
Got data2: File2_data_processed
Done
</code>```

This makes sense to me, it's just doing them one at a time:

However, the point is I want to run these operations in parallel and asynchronously. If I simulate this (say, the user pressing both 'buttons' in quick succession) with:

```<code>Console.WriteLine("waiting");
await Task.WhenAll(loadFile1ButtonPress(), loadFile2ButtonPress());
Console.WriteLine("Done");
</code>```

Does this work if the second operation takes longer than the first?

I was expecting both to return the first data however (Originally this didn't
work but it was a bug I've fixed - it does return the correct items now).

I was thinking I could link an ActionBlock<string> to perform the action with the data, something like:

```<code>public async Task loadFile1ButtonPress()
{
    loadDataFromFile.Post("File1");
    // instead of var data = await logProcessComplete.ReceiveAsync();

    logProcessComplete.LinkTo(new ActionBlock<string>(data =>
    {
        Console.WriteLine($"Got data1: {data}");
    }));
}
</code>```

But this is changing the pipeline completely, now loadFile2ButtonPress won't work at all as it's using that pipeline.

Can I create multiple pipelines with the same Blocks? Or should I be creating a whole new pipeline (and new blocks) for each 'operation' (that seems to defeat the point of using the Dataflow library at all)

Not sure if this is best place for Stackoverflow or something like Codereview? Might be a bit subjective.

答:
If you need some events to happen after some data has been processed, you should make your last block AsObservable, and add some small code with Rx.Net:

```<code>var subscription = logProcessComplete.AsObservable();
subscription.Subscribe(i => Console.WriteLine(i));
</code>```

As been said in comments, you can link your blocks to more than one block, with a predicate. Note, that in that case, message will be delivered only to first matching block. You also may create a BroadcastBlock, which delivers a copy of the message to each linked block.

Make sure that unwanted by every other block messages are linked to NullTarget, as in other case they will stay in your pipeline forever, and will stop your completion.

Check that your pipeline correctly handles completion, as in case of multiple links the completion also being propagated only to the first linked block.

Body:
I'm struggling with how to apply TPL DataFlow to my application.

I've got a bunch of parallel data operations I want to track and manage, previously I was just using Tasks, but I'm trying to implement DataFlow to give me more control.

I'm composing a pipeline of tasks to say get the data and process it, here's an example of a pipeline to get data, process data, and log it as complete:

TransformBlock<string, string> loadDataFromFile = new TransformBlock<string, string>(filename =>
{
    // read the data file (takes a long time!)
    Console.WriteLine("Loading from " + filename);
    Thread.Sleep(2000);

    // return our result, for now just use the filename
    return filename + "_data";
});

TransformBlock<string, string> prodcessData = new TransformBlock<string, string>(data =>
{
    // process the data
    Console.WriteLine("Processiong data " + data);
    Thread.Sleep(2000);

    // return our result, for now just use the data string
    return data + "_processed";
});

TransformBlock<string, string> logProcessComplete= new TransformBlock<string, string>(data =>
{
    // Doesn't do anything to the data, just performs an 'action' (but still passses the data long, unlike ActionBlock)
    Console.WriteLine("Result " + data + " complete");
    return data;
});

I'm linking them together like this:

// create a pipeline
loadDataFromFile.LinkTo(prodcessData);
prodcessData.LinkTo(logProcessComplete);

I've been trying to follow this tutorial.

My confusion is that in the tutorial this pipeline seems to be a 'fire once' operation. It creates the pipeline and fires it off once, and it completes. This seems counter to how the Dataflow library seems designed, I've read:

The usual way of using TPL Dataflow is to create all the blocks, link
  them together, and then start putting data in one end.

From "Concurrency in C# Cookbook" by Stephen Cleary.

But I'm not sure how to track the data after I've put said data 'in one end'. I need to be able to get the processed data from multiple parts of the program, say the user presses two buttons, one to get the data from "File1" and do something with it, one to get the data from "File2", I'd need something like this I think:

public async Task loadFile1ButtonPress()
{
    loadDataFromFile.Post("File1");
    var data = await logProcessComplete.ReceiveAsync();
    Console.WriteLine($"Got data1: {data}");
}

public async Task loadFile2ButtonPress()
{
    loadDataFromFile.Post("File2");
    var data = await logProcessComplete.ReceiveAsync();
    Console.WriteLine($"Got data2: {data}");
}

If these are performed 'synchronously' it works just fine, as there's only one piece of information flowing through the pipeline:

Console.WriteLine("waiting for File 1");
await loadFile1ButtonPress();
Console.WriteLine("waiting for File 2");
await loadFile2ButtonPress();
Console.WriteLine("Done");

Produces the expected output:

waiting for File 1
Loading from File1
Processiong data File1_data
Result File1_data_processed complete
Got data1: File1_data_processed
waiting for File 2
Loading from File2
Processiong data File2_data
Result File2_data_processed complete
Got data2: File2_data_processed
Done

This makes sense to me, it's just doing them one at a time:

However, the point is I want to run these operations in parallel and asynchronously. If I simulate this (say, the user pressing both 'buttons' in quick succession) with:

Console.WriteLine("waiting");
await Task.WhenAll(loadFile1ButtonPress(), loadFile2ButtonPress());
Console.WriteLine("Done");

Does this work if the second operation takes longer than the first?

I was expecting both to return the first data however (Originally this didn't
work but it was a bug I've fixed - it does return the correct items now).

I was thinking I could link an ActionBlock<string> to perform the action with the data, something like:

public async Task loadFile1ButtonPress()
{
    loadDataFromFile.Post("File1");
    // instead of var data = await logProcessComplete.ReceiveAsync();

    logProcessComplete.LinkTo(new ActionBlock<string>(data =>
    {
        Console.WriteLine($"Got data1: {data}");
    }));
}

But this is changing the pipeline completely, now loadFile2ButtonPress won't work at all as it's using that pipeline.

Can I create multiple pipelines with the same Blocks? Or should I be creating a whole new pipeline (and new blocks) for each 'operation' (that seems to defeat the point of using the Dataflow library at all)

Not sure if this is best place for Stackoverflow or something like Codereview? Might be a bit subjective.

Body:
If you need some events to happen after some data has been processed, you should make your last block AsObservable, and add some small code with Rx.Net:

var subscription = logProcessComplete.AsObservable();
subscription.Subscribe(i => Console.WriteLine(i));

As been said in comments, you can link your blocks to more than one block, with a predicate. Note, that in that case, message will be delivered only to first matching block. You also may create a BroadcastBlock, which delivers a copy of the message to each linked block.

Make sure that unwanted by every other block messages are linked to NullTarget, as in other case they will stay in your pipeline forever, and will stop your completion.

Check that your pipeline correctly handles completion, as in case of multiple links the completion also being propagated only to the first linked block.


问:
How can the User Interface know which commands is allowed to perform against an Aggregate Root?
The UI is decoupled from the domain, but the UI should try its best to never allow the user to issue commands that are sure to fail.
Consider the following example (pseudo-code):

```<code>DiscussionController
    @Security(is_logged)
    @Method('POST')
    @Route('addPost')
    addPostToDiscussionAction(request)
        discussionService.postToDiscussion(
            new PostToDiscussionCommand(request.discussionId, session.myUserId, request.bodyText)
        )

    @Method('GET')
    @Route('showDiscussion/{discussionId}')
    showDiscussionAction(request)
        discussionWithAllThePosts = discussionFinder.findById(request.discussionId)

        canAddPostToThisDiscussion = ???

        // render the discussion to the user, and use `canAddPostToThisDiscussion` to show/hide the form
        // from which the user can send a request to `addPostToDiscussionAction`.
        renderDiscussion(discussionWithAllThePosts, canAddPostToThisDiscussion)

PostToDiscussionCommand
    constructor(discussionId, authorId, bodyText)

DiscussionApplicationService
    postToDiscussion(command)
        discussion = discussionRepository.get(command.discussionId)
        author = collaboratorService.authorFrom(discussion.Id, command.authorId)
        post = discussion.createPost(postRepository.nextIdentity(), author, command.bodyText)
        postRepository.add(post)

DiscussionAggregate
    // originalPoster is the Author that started the discussion
    constructor(discussionId, originalPoster)

    // if the discussion is closed, you can't create a post.
    // *unless* if you're the author (OP) that started the discussion
    createPost(postId, author, bodyText)
        if (this.close && !this.originalPoster.equals(author))
            throw "Discussion is closed."

        return new Post(this.discussionId, postId, author, bodyText)

    close()
        if (this.close)
            throw "Discussion already closed."

        this.close = true

    isClosed()
        return this.close
</code>```

The user goes to /showDiscussion/123 and he see the discussion with the <form> from which he can submit a new post, but only if the discussion is not closed or the current user is who started that discussion.

Or, the user goes to /showDiscussion/123 where it's presented as a REST-as-in-HATEOAS API. A hypermedia link to /addPost will be provided, only if the discussion is not closed or the authenticated user is who started that discussion.

How can I provide that knowledge into the UI?

I could code that into the read model,

```<code>canAddPostToThisDiscussion = !discussionWithAllThePosts.discussion.isClosed
    && discussionWithAllThePosts.discussion.originalPoster.id == session.currentUserId
</code>```

but then I need to maintain that logic and keep it in sync with the write model. This is a fairly simple example, but as the states transitions of an aggregate become more complex, it may become really hard to do. I'd like to image my aggregates as state machines, with their workflows (like the RESTBucks example). But I don't like the idea to move that business logic outside my domain model, and put it in a service that both the read side and write side can use.

Maybe this isn't the best example, but as an aggregate root is basically a consistency boundary, we know that we need to prevent invalid state transitions in its life cycle, and in each transitions to a new state some operations may become illegal and vice versa. So, how can the user interface know what is allowed or not? What are my alternative? How should I approach to this problem? Do you have any example to provide?

答:
I find it is rare that authorization is actually part of the domain. If it isn't, it makes sense to move that logic out into its own service which the UI and the domain can make use of.

I like to build up a set of rules using the specification pattern. I find it to be a fairly elegant way to build up the rules.

This also plays very well in a CQRS context as you can run each command through the 'rules engine' before they get issued to your AR's. If you push queries through a message routeing system you can do the same for queries. I've had a lot of success with this approach.

Body:
The UI is decoupled from the domain, but the UI should try its best to never allow the user to issue commands that are sure to fail.
Consider the following example (pseudo-code):

DiscussionController
    @Security(is_logged)
    @Method('POST')
    @Route('addPost')
    addPostToDiscussionAction(request)
        discussionService.postToDiscussion(
            new PostToDiscussionCommand(request.discussionId, session.myUserId, request.bodyText)
        )

    @Method('GET')
    @Route('showDiscussion/{discussionId}')
    showDiscussionAction(request)
        discussionWithAllThePosts = discussionFinder.findById(request.discussionId)

        canAddPostToThisDiscussion = ???

        // render the discussion to the user, and use `canAddPostToThisDiscussion` to show/hide the form
        // from which the user can send a request to `addPostToDiscussionAction`.
        renderDiscussion(discussionWithAllThePosts, canAddPostToThisDiscussion)

PostToDiscussionCommand
    constructor(discussionId, authorId, bodyText)

DiscussionApplicationService
    postToDiscussion(command)
        discussion = discussionRepository.get(command.discussionId)
        author = collaboratorService.authorFrom(discussion.Id, command.authorId)
        post = discussion.createPost(postRepository.nextIdentity(), author, command.bodyText)
        postRepository.add(post)

DiscussionAggregate
    // originalPoster is the Author that started the discussion
    constructor(discussionId, originalPoster)

    // if the discussion is closed, you can't create a post.
    // *unless* if you're the author (OP) that started the discussion
    createPost(postId, author, bodyText)
        if (this.close && !this.originalPoster.equals(author))
            throw "Discussion is closed."

        return new Post(this.discussionId, postId, author, bodyText)

    close()
        if (this.close)
            throw "Discussion already closed."

        this.close = true

    isClosed()
        return this.close

The user goes to /showDiscussion/123 and he see the discussion with the <form> from which he can submit a new post, but only if the discussion is not closed or the current user is who started that discussion.

Or, the user goes to /showDiscussion/123 where it's presented as a REST-as-in-HATEOAS API. A hypermedia link to /addPost will be provided, only if the discussion is not closed or the authenticated user is who started that discussion.

How can I provide that knowledge into the UI?

I could code that into the read model,

canAddPostToThisDiscussion = !discussionWithAllThePosts.discussion.isClosed
    && discussionWithAllThePosts.discussion.originalPoster.id == session.currentUserId

but then I need to maintain that logic and keep it in sync with the write model. This is a fairly simple example, but as the states transitions of an aggregate become more complex, it may become really hard to do. I'd like to image my aggregates as state machines, with their workflows (like the RESTBucks example). But I don't like the idea to move that business logic outside my domain model, and put it in a service that both the read side and write side can use.

Maybe this isn't the best example, but as an aggregate root is basically a consistency boundary, we know that we need to prevent invalid state transitions in its life cycle, and in each transitions to a new state some operations may become illegal and vice versa. So, how can the user interface know what is allowed or not? What are my alternative? How should I approach to this problem? Do you have any example to provide?


问:
Gradle dependencies to add gif library
I am using the  these dependencies:

```<code>  compile 'com.felipecsl:gifimageview:2.1.0'
  compile 'commons-io:commons-io:2.4'
</code>```

But it couldn't resolve the first one. I'm using Android Studio 2.3.2.

答:
try this library </p>

```<code>compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.0'
</code>```

<p>and this is the xml </p>

```<code> <pl.droidsonroids.gif.GifImageView
                android:scaleType="centerCrop"
                android:src="@drawable/gif1"
                android:layout_width="150dp"
                android:layout_height="150dp" />
</code>```

Title: Gradle dependencies to add gif library

Body:
I am using the  these dependencies:

  compile 'com.felipecsl:gifimageview:2.1.0'
  compile 'commons-io:commons-io:2.4'

But it couldn't resolve the first one. I'm using Android Studio 2.3.2.

Body:
try this library

compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.0'

and this is the xml

 <pl.droidsonroids.gif.GifImageView
                android:scaleType="centerCrop"
                android:src="@drawable/gif1"
                android:layout_width="150dp"
                android:layout_height="150dp" />


问:
Accessing labels, textboxes and lauching views from TableViewDatSource
Just new to Monotouch! :D Very glad with it but still in the discovery phase... Hehehe...

I was wondering if i can see/change my labels from within my Table View, for example, in the Main.cs, please take a look:

```<code>public partial class AppDelegate : UIApplicationDelegate

{

     public override bool FinishedLaunching (UIApplication app, NSDictionary options)

     {

          //Do something in here (load my view or any other thing...)

     }

     public class TableViewDataSourceClientes : UITableViewSource

     {

          //Why can't I access my labels inside this class?

     }

}
</code>```

So, my question is pretty much it. Why i can access my labels and views and textboxes and etc. inside FinishedLauching and not in TableViewDataSourceClientes? ANd how can I achieve this?

My objective is to create a method inside of TableViewDataSourceClientes called RowSelected and change a label text when I select a row.

答: You cannot access your outlets/labels in the TableViewDataSourceClientes class because they are instance properties on your AppDelegate class.  You can get at the AppDelegate from anywhere with UIApplication.SharedApplication.Delegate, you'll need to cast it to your AppDelegate type tho, and then expose the fields / properties you want as public members.</p>

Body:
Just new to Monotouch! :D Very glad with it but still in the discovery phase... Hehehe...

I was wondering if i can see/change my labels from within my Table View, for example, in the Main.cs, please take a look:

public partial class AppDelegate : UIApplicationDelegate

{

     public override bool FinishedLaunching (UIApplication app, NSDictionary options)

     {

          //Do something in here (load my view or any other thing...)

     }

     public class TableViewDataSourceClientes : UITableViewSource

     {

          //Why can't I access my labels inside this class?

     }

}

So, my question is pretty much it. Why i can access my labels and views and textboxes and etc. inside FinishedLauching and not in TableViewDataSourceClientes? ANd how can I achieve this?

My objective is to create a method inside of TableViewDataSourceClientes called RowSelected and change a label text when I select a row.

ContentLicense: CC BY-SA 2.5


问:
What difference does .AsNoTracking() make?
I have a question regarding the .AsNoTracking() extension, as this is all quite new and quite confusing.

I'm using a per-request context for a website.

A lot of my entities don't change so don't need to be tracked, but I have the following scenario where I'm unsure of what's going to the database, or even whether it makes a difference in this case.

This example is what I'm currently doing:

```<code>context.Set<User>().AsNoTracking()
// Step 1) Get user
context.Set<User>()
// Step 2) Update user
</code>```

This is the same as above but removing the .AsNoTracking() from Step 1:

```<code>context.Set<User>();
// Step 1) Get user
context.Set<User>()
// Step 2) Update user
</code>```

The Steps 1 & 2 use the same context but occur at different times. What I can't work out is whether there is any difference. As Step 2 is an update I'm guessing both will hit the database twice anyway.

Can anyone tell me what the difference is?

答:
If you have something else altering the DB (say another process) and need to ensure you see these changes, use AsNoTracking(), otherwise EF may give you the last copy that your context had instead, hence it being good to usually use a new context every query:

http://codethug.com/2016/02/19/Entity-Framework-Cache-Busting/

Body:
I have a question regarding the .AsNoTracking() extension, as this is all quite new and quite confusing.

I'm using a per-request context for a website.

A lot of my entities don't change so don't need to be tracked, but I have the following scenario where I'm unsure of what's going to the database, or even whether it makes a difference in this case.

This example is what I'm currently doing:

context.Set<User>().AsNoTracking()
// Step 1) Get user
context.Set<User>()
// Step 2) Update user

This is the same as above but removing the .AsNoTracking() from Step 1:

context.Set<User>();
// Step 1) Get user
context.Set<User>()
// Step 2) Update user

The Steps 1 & 2 use the same context but occur at different times. What I can't work out is whether there is any difference. As Step 2 is an update I'm guessing both will hit the database twice anyway.

Can anyone tell me what the difference is?


问:
Outlook Email and ICS format -- Strange behavior
To begin, I will set the scenario.  I am using the biweekly library to create a VEvent and an ICalendar.  Everything is working fine (code below).  I can successfully send a calendar invite to Google and the appropriate 'Accept, Decline, Add to Calendar' options are available.

When I send the same message to Outlook, I do not receive the correct invite. The message is formatted in such a way that it expects the recipient to send the invite - not be invited, nor add to his/her calendar.

The framework:

Java
 - JavaMailSender
 - Spring Boot
 - biweekly

The code is operational.  The issue in is the difference in which Outlook handles the calendar invite.

Here is the Java code...

```<code>@Service
public class CalendarEvent {

private JavaMailSender javaMailSender;

@Autowired
public CalendarEvent(JavaMailSender javaMailSender) {
    this.javaMailSender = javaMailSender;
}

public void createCal() throws MessagingException, ParseException, IOException {

    ICalendar ical = new ICalendar();

    VEvent event = new VEvent();

    Attendee attendee = new Attendee("Juniper", "blank@blank.com");
    attendee.setRsvp(true);
    attendee.setRole(Role.ATTENDEE);
    attendee.setParticipationStatus(ParticipationStatus.NEEDS_ACTION);
    attendee.setParticipationLevel(ParticipationLevel.REQUIRED);

    event.addAttendee(attendee);

    event.setSummary("hello");

    DateTime dt = new DateTime(2016, 12, 28, 12, 0);
    DateTime et = new DateTime(2016, 12, 28, 13, 30);
    Date starts = (Date) dt.toDate();
    Date ends = (Date) et.toDate();

    DateStart thisStart = new DateStart(starts, true);
    DateEnd dateEnd = new DateEnd(ends, true);

    event.setDateStart(thisStart);
    event.setDateEnd(dateEnd);

    Duration reminder = new Duration.Builder().minutes(15).build();
    Trigger trigger = new Trigger(reminder, Related.START);
    Action action = new Action("DISPLAY");
    VAlarm valarm = new VAlarm(action, trigger);
    event.addAlarm(valarm);

    Duration duration = new Duration.Builder().hours(1).build();
    event.setDuration(duration);

    event.setUid("555xxx");
    event.setOrganizer("blank@blank.com");
    event.setLocation("Small");

    ical.addEvent(event);

    String str = Biweekly.write(ical).go();

    MimeMessage message = javaMailSender.createMimeMessage();
    message.addHeaderLine("charset=UTF-8");
    message.addHeaderLine("component=VEVENT");
    message.addHeaderLine("method=REQUEST");

    message.setFrom("blank@blank.com");
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("blank@blank.com"));
    message.setSubject("You're Invited to a Meeting");

    // Create the message part
    BodyPart messageBodyPart = new MimeBodyPart();

    // Fill the message
    messageBodyPart.setHeader("Content-Class", "urn:content-classes:calendarmessage");
    messageBodyPart.setHeader("Content-ID", "calendar_message");
    messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(str, "text/calendar")));// very important

    Multipart multipart = new MimeMultipart();

    multipart.addBodyPart(messageBodyPart);

    message.setContent(multipart);

    javaMailSender.send(message);

}
</code>```

}

Here is the ICS...

```<code>BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Michael Angstadt//biweekly 0.6.0//EN BEGIN:VEVENT
DTSTAMP:20161223T203840Z ATTENDEE;RSVP=TRUE;ROLE=REQ-
PARTICIPANT;PARTSTAT=NEEDS-ACTION;CN=Juniper:mail
 to:blank@blank.com
SUMMARY:hello
DTSTART:20161228T170000Z
DTEND:20161228T183000Z
DURATION:PT1H
UID:555****
ORGANIZER:mailto:blank@blank.com
LOCATION:Small
BEGIN:VALARM
ACTION:DISPLAY
TRIGGER;RELATED=START:PT15M
END:VALARM
END:VEVENT
END:VCALENDAR
</code>```

Here is the Opened Outlook Email (notice how it is a composed message)...

Here is the Opened Gmail Email...

I have found the documentation to be limited and was hoping somebody may have/is encountered/ecountering the same issue.  Thanks for reading.

答: I had the same problem. Adding ical.setMethod("REQUEST"); solved it for me.

Body:
To begin, I will set the scenario.  I am using the biweekly library to create a VEvent and an ICalendar.  Everything is working fine (code below).  I can successfully send a calendar invite to Google and the appropriate 'Accept, Decline, Add to Calendar' options are available.

When I send the same message to Outlook, I do not receive the correct invite. The message is formatted in such a way that it expects the recipient to send the invite - not be invited, nor add to his/her calendar.

The framework:

Java
 - JavaMailSender
 - Spring Boot
 - biweekly

The code is operational.  The issue in is the difference in which Outlook handles the calendar invite.

Here is the Java code...

@Service
public class CalendarEvent {

private JavaMailSender javaMailSender;

@Autowired
public CalendarEvent(JavaMailSender javaMailSender) {
    this.javaMailSender = javaMailSender;
}

public void createCal() throws MessagingException, ParseException, IOException {

    ICalendar ical = new ICalendar();

    VEvent event = new VEvent();

    Attendee attendee = new Attendee("Juniper", "blank@blank.com");
    attendee.setRsvp(true);
    attendee.setRole(Role.ATTENDEE);
    attendee.setParticipationStatus(ParticipationStatus.NEEDS_ACTION);
    attendee.setParticipationLevel(ParticipationLevel.REQUIRED);

    event.addAttendee(attendee);

    event.setSummary("hello");

    DateTime dt = new DateTime(2016, 12, 28, 12, 0);
    DateTime et = new DateTime(2016, 12, 28, 13, 30);
    Date starts = (Date) dt.toDate();
    Date ends = (Date) et.toDate();

    DateStart thisStart = new DateStart(starts, true);
    DateEnd dateEnd = new DateEnd(ends, true);

    event.setDateStart(thisStart);
    event.setDateEnd(dateEnd);

    Duration reminder = new Duration.Builder().minutes(15).build();
    Trigger trigger = new Trigger(reminder, Related.START);
    Action action = new Action("DISPLAY");
    VAlarm valarm = new VAlarm(action, trigger);
    event.addAlarm(valarm);

    Duration duration = new Duration.Builder().hours(1).build();
    event.setDuration(duration);

    event.setUid("555xxx");
    event.setOrganizer("blank@blank.com");
    event.setLocation("Small");

    ical.addEvent(event);

    String str = Biweekly.write(ical).go();

    MimeMessage message = javaMailSender.createMimeMessage();
    message.addHeaderLine("charset=UTF-8");
    message.addHeaderLine("component=VEVENT");
    message.addHeaderLine("method=REQUEST");

    message.setFrom("blank@blank.com");
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("blank@blank.com"));
    message.setSubject("You're Invited to a Meeting");

    // Create the message part
    BodyPart messageBodyPart = new MimeBodyPart();

    // Fill the message
    messageBodyPart.setHeader("Content-Class", "urn:content-classes:calendarmessage");
    messageBodyPart.setHeader("Content-ID", "calendar_message");
    messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(str, "text/calendar")));// very important

    Multipart multipart = new MimeMultipart();

    multipart.addBodyPart(messageBodyPart);

    message.setContent(multipart);

    javaMailSender.send(message);

}

}

Here is the ICS...

BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Michael Angstadt//biweekly 0.6.0//EN BEGIN:VEVENT
DTSTAMP:20161223T203840Z ATTENDEE;RSVP=TRUE;ROLE=REQ-
PARTICIPANT;PARTSTAT=NEEDS-ACTION;CN=Juniper:mail
 to:blank@blank.com
SUMMARY:hello
DTSTART:20161228T170000Z
DTEND:20161228T183000Z
DURATION:PT1H
UID:555****
ORGANIZER:mailto:blank@blank.com
LOCATION:Small
BEGIN:VALARM
ACTION:DISPLAY
TRIGGER;RELATED=START:PT15M
END:VALARM
END:VEVENT
END:VCALENDAR

Here is the Opened Outlook Email (notice how it is a composed message)...

Here is the Opened Gmail Email...

I have found the documentation to be limited and was hoping somebody may have/is encountered/ecountering the same issue.  Thanks for reading.


问:
Detect another host with the same MAC address
How can I detect if another host is using the same MAC address as the current host, e.g. because the other host is spoofing?

I'm working in an embedded environment, so looking for answers on a protocol level, rather than “use such and such a tool”.

Edit: RARP does not solve this problem. For RARP to get any reply at all, there has to be at least one host on the segment which supports RARP. Since RARP is obsolete, modern operating systems don't support it. Furthermore, all RARP can do is tell you your own IP address - the response won't be any different if there’s another host on the segment with the same MAC, unless that host has itself used a different IP address.

答:
You could send an ARP request for each possible ip in the subnet.
Of course the source address of the ARP request must be ff:ff:ff:ff:ff:ff, otherwise you might not see the response.

I forged a packet like this with bittwiste and replayed it with PReplay and all the hosts on the network got the response. (I don't know if these forged ARP packets are legal or not... some OSes might ignore them)

Here is what the forged package looked like:

Here is what the reply looked like:

If you watch the responses and see your MAC address in one of the packets (in the red rectangle) , than someone has the same MAC address as you do...

Unfortuantely I couldn't test the theory fully because none of my (Windows) machines care about me trying to set the nic's MAC address...

OwnerDisplayName: Daniel Cassidy

LastEditorDisplayName: Daniel Cassidy

OwnerDisplayName: Kalmi


问:
Search for key inside dictionary and print values- Javascript
I have a dictionary that looks a little like this:

```<code>var index = {
  "Italian": [
    {
      "name": "Il Brigante",
      "rating": "5.0"
    },
    {
      "name": "Giardino Doro Ristorante",
      "rating": "5.0"
    }
  ],
  "Mexican": [
    {
      "name": "Cosme",
      "rating": "5.0"
    }
  ]
}
</code>```

I also have a search bar that people can enter queries into. What I want to do is take the query and search for it inside index.

Example: search = "italian", results = {"name": "Il Brigante", "rating": "5.0"}, {"name": "Giardino Doro Ristorante", "rating": "5.0"}

Is that kind of search possible? Any help would be appreciated. Thanks so much in advance. Happy 4th!

Cheers,
Theoi

答:
You can try following

var index = {
  "Italian": [{
      "name": "Il Brigante",
      "rating": "5.0"
    },
    {
      "name": "Giardino Doro Ristorante",
      "rating": "5.0"
    }
  ],
  "Mexican": [{
    "name": "Cosme",
    "rating": "5.0"
  }]
};

var search = "italian";

var results = Object.keys(index).reduce(function(a, b) {
  if (b.toLowerCase() === search.toLowerCase()) {
    return a.concat(index[b]);
  }
  return a;
}, []);

console.log(results);```
</div>
</div>
</p>

<p><strong>May Be a Requirement Later!</strong></p>

<p>In case you want to for the partial match, you just need to replace </p>

```if (b.toLowerCase() === search.toLowerCase()) {
```

<p>with </p>

```if(b.toLowerCase().indexOf(search.toLowerCase()) !== -1) {
```

For tweaking - plunker

Body:
I have a dictionary that looks a little like this:

var index = {
  "Italian": [
    {
      "name": "Il Brigante",
      "rating": "5.0"
    },
    {
      "name": "Giardino Doro Ristorante",
      "rating": "5.0"
    }
  ],
  "Mexican": [
    {
      "name": "Cosme",
      "rating": "5.0"
    }
  ]
}

I also have a search bar that people can enter queries into. What I want to do is take the query and search for it inside index.

Example: search = "italian", results = {"name": "Il Brigante", "rating": "5.0"}, {"name": "Giardino Doro Ristorante", "rating": "5.0"}

Is that kind of search possible? Any help would be appreciated. Thanks so much in advance. Happy 4th!

Cheers,
Theoi

Body:
You can try following

var index = {
  "Italian": [{
      "name": "Il Brigante",
      "rating": "5.0"
    },
    {
      "name": "Giardino Doro Ristorante",
      "rating": "5.0"
    }
  ],
  "Mexican": [{
    "name": "Cosme",
    "rating": "5.0"
  }]
};

var search = "italian";

var results = Object.keys(index).reduce(function(a, b) {
  if (b.toLowerCase() === search.toLowerCase()) {
    return a.concat(index[b]);
  }
  return a;
}, []);

console.log(results);

May Be a Requirement Later!

In case you want to for the partial match, you just need to replace

if (b.toLowerCase() === search.toLowerCase()) {

with

if(b.toLowerCase().indexOf(search.toLowerCase()) !== -1) {

For tweaking - plunker


问:
How do I apply a wholesale group price with the Extended Pricing Module?
When using the Extended pricing module I add the following to my YML file.

```<code>Product:
  extensions:
    - HasGroupPricing
HasGroupPricing:
  price_levels:
    wholesale: WholesalePrice
  field_labels:
    WholesalePrice: 'Price for wholesale customers'
</code>```

I have a wholesale group and the fields show up in the CMS for setting a price, but nothing happens on the front end.

答:
The key for the price_levels has to exactly match the Code of the group in the CMS. The Code of a group will only be set with the initial write, so renaming a group later on won't change its group-code!

That being said, you should inspect the Group Table in your Database and look at the Code column. Identify the group you want to apply the WholesalePrice to and ensure that the key matches the Code of that group…

Example: You have a Group that is called "My Wholesale Group", the Code of said group is my-group (you'd have to look this up in the Database). You'd then have to change your YML to read:

```<code>HasGroupPricing:
  price_levels:
    # Here's where we change the key to match the Group Code
    my-group: WholesalePrice
  field_labels:
    WholesalePrice: 'Price for wholesale customers'
</code>```

Body:
When using the Extended pricing module I add the following to my YML file.

Product:
  extensions:
    - HasGroupPricing
HasGroupPricing:
  price_levels:
    wholesale: WholesalePrice
  field_labels:
    WholesalePrice: 'Price for wholesale customers'

I have a wholesale group and the fields show up in the CMS for setting a price, but nothing happens on the front end.

Body:
The key for the price_levels has to exactly match the Code of the group in the CMS. The Code of a group will only be set with the initial write, so renaming a group later on won't change its group-code!

That being said, you should inspect the Group Table in your Database and look at the Code column. Identify the group you want to apply the WholesalePrice to and ensure that the key matches the Code of that group…

Example: You have a Group that is called "My Wholesale Group", the Code of said group is my-group (you'd have to look this up in the Database). You'd then have to change your YML to read:

HasGroupPricing:
  price_levels:
    # Here's where we change the key to match the Group Code
    my-group: WholesalePrice
  field_labels:
    WholesalePrice: 'Price for wholesale customers'


问:
Firebase Query.Once failed on Firefox and Google Chrome console, but not it JS Bin website
I have a problem with firebase, it read data using 'once', but it shows me Uncaught Error: Query.once failed: Was called with 1 argument. Expects at least 2 on Firefox console and Google Chrome, but the source code on JS Bin there's no error.
I got the code from here : https://stackoverflow.com/a/35526844/6780268
I copy the code in bracket, i try 2 different firebase.js, but still show me nothing.

```<code>var ref = new Firebase('https://stackoverflow.firebaseio.com/35526205');
        ref.child('Highscore').once('value').then(function(snapshot) {
            console.log(snapshot.val());
        });
</code>```

Is this normal? And how to fix this problem?
Sorry for my bad english.

答:
You're likely using a different/newer version of Firebase than the one in the jsbin in the link.

In newer versions of Firebase, you get a reference to the same database location with:

```<code>firebase.initializeApp({ databaseURL: "https://stackoverflow.firebaseio.com" });
var ref = firebase.database().ref("35526205");
</code>```

I recommend reading the Firebase documentation, the migration guide, and the web codelab.

Body:
I have a problem with firebase, it read data using 'once', but it shows me Uncaught Error: Query.once failed: Was called with 1 argument. Expects at least 2 on Firefox console and Google Chrome, but the source code on JS Bin there's no error.
I got the code from here : https://stackoverflow.com/a/35526844/6780268
I copy the code in bracket, i try 2 different firebase.js, but still show me nothing.

var ref = new Firebase('https://stackoverflow.firebaseio.com/35526205');
        ref.child('Highscore').once('value').then(function(snapshot) {
            console.log(snapshot.val());
        });

Is this normal? And how to fix this problem?
Sorry for my bad english.

Body:
You're likely using a different/newer version of Firebase than the one in the jsbin in the link.

In newer versions of Firebase, you get a reference to the same database location with:

firebase.initializeApp({ databaseURL: "https://stackoverflow.firebaseio.com" });
var ref = firebase.database().ref("35526205");

I recommend reading the Firebase documentation, the migration guide, and the web codelab.


问:
unwanted keys in JSON object
hi i am creating a JSON object after executing a loop. the problem is the JSON object have additional keys. i don't want that keys. that keys are generated by me. for arraigning the json according my requirement. this is code i am using for create my JSON object

```<code> var bankdata = data;
    var updatebankdata = {}
    for (var key in bankdata) {
        var id = +key.substr(key.length - 1);

        if (isNaN(id)) {
            updatebankdata[0] = updatebankdata[0] || {};
            updatebankdata[0][key] = bankdata[key];
        } else {
            var uniqid=$("#bankaccount"+id).attr("uniq_id");
            updatebankdata[id] = updatebankdata[id] || {};
            var field = key.substring(0, key.length - 1);
            updatebankdata[id][field] = bankdata[key];
            updatebankdata[id]["uniquid"] = uniquid;
        }
    }
    return updatebankdata;
}
</code>```

my bank data is like

{bankname1: "new", micrcode1: "mkkk", comments1: "commentsfvfdv", bankname2: "bankfgname", micrcode2: "micrfgcode"…}

i want to change it into  like this way

[{bankname1: "new", micrcode1: "mkkk", comments1:
  "commentsfvfdv"},{bankname2: "bankfgname", micrcode2: "micrfgcode"}]

but still it getting like this .its not good

{"0":{bankname1: "new", micrcode1: "mkkk", comments1:

"commentsfvfdv"},"1":{bankname2: "bankfgname", micrcode2: "micrfgcode"}

what is the mistake in my code?

答:
You need to use an array instead of an object. Like so:

```<code>   function func(data) {
       var bankdata = data;
       var updatebankdata = [];  // ARRAY instead of Object
       for (var key in bankdata) {
           var id = +key.substr(key.length - 1);

           if (isNaN(id)) {
               updatebankdata[0] = updatebankdata[0] || {};
               updatebankdata[0][key] = bankdata[key];
           } else {
               var uniqid=$("#bankaccount"+id).attr("uniq_id");
               updatebankdata[id] = updatebankdata[id] || {};
               var field = key.substring(0, key.length - 1);
               updatebankdata[id][field] = bankdata[key];
               updatebankdata[id]["uniquid"] = uniqid;  // CHANGED to "uniqid" to match variable declaration above, not the key on the left is still "uniquid"
           }
       }
       return updatebankdata;
   }
</code>```

Then you can get result like:

```<code>JSON.stringify(func({name: 'someval', val: 123}));
"[{"name":"someval","val":123}]"
</code>```

Title: unwanted keys in JSON object

Body:
hi i am creating a JSON object after executing a loop. the problem is the JSON object have additional keys. i don't want that keys. that keys are generated by me. for arraigning the json according my requirement. this is code i am using for create my JSON object

 var bankdata = data;
    var updatebankdata = {}
    for (var key in bankdata) {
        var id = +key.substr(key.length - 1);

        if (isNaN(id)) {
            updatebankdata[0] = updatebankdata[0] || {};
            updatebankdata[0][key] = bankdata[key];
        } else {
            var uniqid=$("#bankaccount"+id).attr("uniq_id");
            updatebankdata[id] = updatebankdata[id] || {};
            var field = key.substring(0, key.length - 1);
            updatebankdata[id][field] = bankdata[key];
            updatebankdata[id]["uniquid"] = uniquid;
        }
    }
    return updatebankdata;
}

my bank data is like

{bankname1: "new", micrcode1: "mkkk", comments1: "commentsfvfdv", bankname2: "bankfgname", micrcode2: "micrfgcode"…}

i want to change it into  like this way

[{bankname1: "new", micrcode1: "mkkk", comments1:
  "commentsfvfdv"},{bankname2: "bankfgname", micrcode2: "micrfgcode"}]

but still it getting like this .its not good

{"0":{bankname1: "new", micrcode1: "mkkk", comments1:

"commentsfvfdv"},"1":{bankname2: "bankfgname", micrcode2: "micrfgcode"}

what is the mistake in my code?

Body:
You need to use an array instead of an object. Like so:

   function func(data) {
       var bankdata = data;
       var updatebankdata = [];  // ARRAY instead of Object
       for (var key in bankdata) {
           var id = +key.substr(key.length - 1);

           if (isNaN(id)) {
               updatebankdata[0] = updatebankdata[0] || {};
               updatebankdata[0][key] = bankdata[key];
           } else {
               var uniqid=$("#bankaccount"+id).attr("uniq_id");
               updatebankdata[id] = updatebankdata[id] || {};
               var field = key.substring(0, key.length - 1);
               updatebankdata[id][field] = bankdata[key];
               updatebankdata[id]["uniquid"] = uniqid;  // CHANGED to "uniqid" to match variable declaration above, not the key on the left is still "uniquid"
           }
       }
       return updatebankdata;
   }

Then you can get result like:

JSON.stringify(func({name: 'someval', val: 123}));
"[{"name":"someval","val":123}]"


问:
Conditionally replace elements of a vector based on an index
It's best explained with an example.

I have a vector, or column from data.frame named vec:

```<code>vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)
</code>```

I would like a vectorized process (not a for loop) to change the three trailing NA when a 1 is observed.

The end vector would be:

```<code>c(NA, NA, 1, 1, 1, 1, NA, 1, 1, 1, 1, NA, NA, NA)
</code>```

If we had:

```<code>vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)
</code>```

The end vector would look like:

```<code>c(NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA)
</code>```

A very badly written solution is:

```<code>vec2 <- vec
for(i in index(v)){
  if(!is.na(v[i])) vec2[i] <- 1
  if(i>3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
    if(!is.na(vec[i-3])) vec2[i] <- 1
  }
  if(i==3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
  }
  if(i==2){
    if(!is.na(vec[i-1])) vec2[i] <- 1
  }
}
</code>```

答:
How about this:

```<code>r <- which(vec==1)
vec[c(mapply(seq, r, r+3))] <- 1
</code>```

Examples:

```<code>vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)
#[1] NA NA  1  1  1  1 NA  1  1  1  1 NA NA NA

vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)
#[1] NA NA  1  1  1  1  1  1  1  1  1 NA NA NA
</code>```

Body:
It's best explained with an example.

I have a vector, or column from data.frame named vec:

vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)

I would like a vectorized process (not a for loop) to change the three trailing NA when a 1 is observed.

The end vector would be:

c(NA, NA, 1, 1, 1, 1, NA, 1, 1, 1, 1, NA, NA, NA)

If we had:

vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)

The end vector would look like:

c(NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA)

A very badly written solution is:

vec2 <- vec
for(i in index(v)){
  if(!is.na(v[i])) vec2[i] <- 1
  if(i>3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
    if(!is.na(vec[i-3])) vec2[i] <- 1
  }
  if(i==3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
  }
  if(i==2){
    if(!is.na(vec[i-1])) vec2[i] <- 1
  }
}

Body:
How about this:

r <- which(vec==1)
vec[c(mapply(seq, r, r+3))] <- 1

Examples:

vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)
#[1] NA NA  1  1  1  1 NA  1  1  1  1 NA NA NA

vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)
#[1] NA NA  1  1  1  1  1  1  1  1  1 NA NA NA


问:
No return after executing passwd command using ssh in script
I have one script which reads hosts IP from /etc/hosts file, do ssh and update the passwords there for the given user. However, the script is closed after setting password for the first host and not able to set password for rest of the hosts. Please find below files-

/etc/hosts file-

172.x.x.x  host1

    172.x.x.x  host2

    172.x.x.x  host3

Script I am using is as-

```<code>key=$1
user=$2
password=$3
filename='/etc/hosts'
while IFS= read -r line; do
   IFS=' ' read -r -a array <<< $line
   ssh -i $key centos@${array[0]} "echo "$password" | sudo passwd $user --stdin"
done <$filename
</code>```

Script is simple. but it is getting closed after setting password for host1 from file. Does anyone has any idea, what I am missing?

答:
What is happening is that ssh is swallowing all of the standard input. The way to avoid that in general is to use a different file descriptor for your input, for example:

```<code>while IFS= read -u 9 -r line
do
    […]
done 9< "$filename"
</code>```

However, this approach to changing authentication is really quite insecure, and I would strongly recommend moving to using public keys instead.

Body:
I have one script which reads hosts IP from /etc/hosts file, do ssh and update the passwords there for the given user. However, the script is closed after setting password for the first host and not able to set password for rest of the hosts. Please find below files-

/etc/hosts file-

172.x.x.x  host1

    172.x.x.x  host2

    172.x.x.x  host3

Script I am using is as-

key=$1
user=$2
password=$3
filename='/etc/hosts'
while IFS= read -r line; do
   IFS=' ' read -r -a array <<< $line
   ssh -i $key centos@${array[0]} "echo "$password" | sudo passwd $user --stdin"
done <$filename

Script is simple. but it is getting closed after setting password for host1 from file. Does anyone has any idea, what I am missing?

Body:
What is happening is that ssh is swallowing all of the standard input. The way to avoid that in general is to use a different file descriptor for your input, for example:

while IFS= read -u 9 -r line
do
    […]
done 9< "$filename"

However, this approach to changing authentication is really quite insecure, and I would strongly recommend moving to using public keys instead.


问:
Sending many requests from Node.js to an API causes error
I have more than 2000 user in my database , when I try to broadcast a message to all users, it barely sends about 200 request then my server stops and I get an error as below :

```<code>{ Error: connect ETIMEDOUT 31.13.88.4:443
at Object.exports._errnoException (util.js:1026:11)
at exports._exceptionWithHostPort (util.js:1049:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect,
address: '31.13.88.4',
port: 443 }
</code>```

Sometimes I get another error that says :

```<code>Error!: Error: socket hang up
</code>```

This is my request :

```<code>function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: '#####' },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      if (messageId) {
        console.log("Successfully sent message with id %s to recipient %s",
          messageId, recipientId);
      } else {
      console.log("Successfully called Send API for recipient %s",
        recipientId);
      }
    } else {
      console.error("Failed calling Send API");
      console.log(error)
    }
  });
}
</code>```

I have tried

setTimeout to make the the API calling wait for a while:

```<code> setTimeout(function(){callSendAPI(data)},200);
</code>```

Can anyone help if he/she faced a similar error ?

EDITED

I'm using Messenger Platform which support high rate of calls to the Send API and it is not limited with 200 calls .

答:
It sounds like you are hitting a rate limit.

From the Facebook documentation:

Your app can make 200 calls per hour per user in aggregate.

You can check the dashboard to see if you are hitting the rate limiting in these cases.

Body:
I have more than 2000 user in my database , when I try to broadcast a message to all users, it barely sends about 200 request then my server stops and I get an error as below :

{ Error: connect ETIMEDOUT 31.13.88.4:443
at Object.exports._errnoException (util.js:1026:11)
at exports._exceptionWithHostPort (util.js:1049:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect,
address: '31.13.88.4',
port: 443 }

Sometimes I get another error that says :

Error!: Error: socket hang up

This is my request :

function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: '#####' },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      if (messageId) {
        console.log("Successfully sent message with id %s to recipient %s",
          messageId, recipientId);
      } else {
      console.log("Successfully called Send API for recipient %s",
        recipientId);
      }
    } else {
      console.error("Failed calling Send API");
      console.log(error)
    }
  });
}

I have tried

setTimeout to make the the API calling wait for a while:

 setTimeout(function(){callSendAPI(data)},200);

Can anyone help if he/she faced a similar error ?

EDITED

I'm using Messenger Platform which support high rate of calls to the Send API and it is not limited with 200 calls .


问:
Dictionary in python with order I set at start
I'm making dictionary:

```<code>d = {"server":"mpilgrim", "database":"master"}
d['mynewkey'] = 'mynewvalue'
</code>```

But when I display it I saw that this dict is reversed.

```<code>print(d)

{'mynewkey': 'mynewvalue', 'database': 'master', 'server': 'mpilgrim'}
</code>```

How to reverse it back?

Or if it is true that dictionary is not sortable what I must to use to have collection where the order of that informations matters?

答: Dictionary are unordered (the order is deterministic, but depends on a handful of factors you don't even think of and shouldn't care about - hash of the keys, order of insertion, collisions, etc). In Python 2.7+, use collections.OrderedDict. If you must use an older version, there are various implementations google can point you to.

Body:
I'm making dictionary:

d = {"server":"mpilgrim", "database":"master"}
d['mynewkey'] = 'mynewvalue'

But when I display it I saw that this dict is reversed.

print(d)

{'mynewkey': 'mynewvalue', 'database': 'master', 'server': 'mpilgrim'}

How to reverse it back?

Or if it is true that dictionary is not sortable what I must to use to have collection where the order of that informations matters?


问:
Laravel: customize or extend notifications - database model
IMHO, the current Database channel for saving notifications in Laravel is really bad design:

You can't use foreign key cascades on items for cleaning up notifications of a deleted item for example

Searching custom attributes in the data column (casted to Array) is not optimal

How would you go about extending the DatabaseNotification Model in vendor package?

I would like to add columns event_id, question_id, user_id (the user that created the notification) etc... to the default laravel notifications table

How do you override the send function to include more columns?

In:

```<code>vendor/laravel/framework/src/Illuminate/Notifications/Channels/DatabaseChannel.php
</code>```

The code:

```<code>class DatabaseChannel
{
 /**
  * Send the given notification.
  *
  * @param  mixed  $notifiable
  * @param  \Illuminate\Notifications\Notification  $notification
  * @return \Illuminate\Database\Eloquent\Model
  */
 public function send($notifiable, Notification $notification)
 {
    return $notifiable->routeNotificationFor('database')->create([
        'id' => $notification->id,
        'type' => get_class($notification),

      \\I want to add these
        'user_id' => \Auth::user()->id,
        'event_id' => $notification->type =='event' ? $notification->id : null,
        'question_id' => $notification->type =='question' ? $notification->id : null,
      \\End adding new columns

        'data' => $this->getData($notifiable, $notification),
        'read_at' => null,
    ]);
 }
}
</code>```

答:
I solved a similar problem by customizing notification class:

create the class for this action:

```<code>artisan make:notification NewQuestion
</code>```

inside it:

```<code>public function __construct($user,$question)
    {
        $this->user=$user;
        $this->question=$question;
    }

...

    public function toDatabase($notifiable){
        $data=[
            'question'=>$this->(array)$this->question->getAttributes(),
            'user'=>$this->(array)$this->user->getAttributes()
        ];

        return $data;
    }
</code>```

then you can access proper data in view or controller like this:

```<code>@if($notification->type=='App\Notifications\UserRegistered')
<a href="{!!route('question.show',$notification->data['question']['id'])!!}">New question from {{$notification->data['user']['name']}}</a>
@endif
</code>```

Body:
IMHO, the current Database channel for saving notifications in Laravel is really bad design:

You can't use foreign key cascades on items for cleaning up notifications of a deleted item for example

Searching custom attributes in the data column (casted to Array) is not optimal

How would you go about extending the DatabaseNotification Model in vendor package?

I would like to add columns event_id, question_id, user_id (the user that created the notification) etc... to the default laravel notifications table

How do you override the send function to include more columns?

In:

vendor/laravel/framework/src/Illuminate/Notifications/Channels/DatabaseChannel.php

The code:

class DatabaseChannel
{
 /**
  * Send the given notification.
  *
  * @param  mixed  $notifiable
  * @param  \Illuminate\Notifications\Notification  $notification
  * @return \Illuminate\Database\Eloquent\Model
  */
 public function send($notifiable, Notification $notification)
 {
    return $notifiable->routeNotificationFor('database')->create([
        'id' => $notification->id,
        'type' => get_class($notification),

      \\I want to add these
        'user_id' => \Auth::user()->id,
        'event_id' => $notification->type =='event' ? $notification->id : null,
        'question_id' => $notification->type =='question' ? $notification->id : null,
      \\End adding new columns

        'data' => $this->getData($notifiable, $notification),
        'read_at' => null,
    ]);
 }
}

Body:
I solved a similar problem by customizing notification class:

create the class for this action:

artisan make:notification NewQuestion

inside it:

public function __construct($user,$question)
    {
        $this->user=$user;
        $this->question=$question;
    }

...

    public function toDatabase($notifiable){
        $data=[
            'question'=>$this->(array)$this->question->getAttributes(),
            'user'=>$this->(array)$this->user->getAttributes()
        ];

        return $data;
    }

then you can access proper data in view or controller like this:

@if($notification->type=='App\Notifications\UserRegistered')
<a href="{!!route('question.show',$notification->data['question']['id'])!!}">New question from {{$notification->data['user']['name']}}</a>
@endif