问:
Problem with parsing of UTF-8 encoded xml files in Android 3.1 sdk
Xml parsing api is throwing sax parse exception, If i try to parse a xml file which has attributes at root node.

One thing i have noticed is that, this happens if there is a UTF-8 BOM character at the start of the string, if i remove the BOM character things work fine. This code is working fine on 3.0 sdk and below, i saw this problem only in 3.1

am using following parser:

```<code>    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = docFactory.newDocumentBuilder();

    Document doc = null;
    StringReader sr = new StringReader(xmlString);
    InputSource is = new InputSource(sr);

    doc = builder.parse(is);
</code>```

答:
Thanks evilone,

I have opened a issue with google, and they will be fixing this in their branch.
http://code.google.com/p/android/issues/detail?id=16892

Comments from google developer:

"I've prepared a fix for the root problem in our internal Honeycomb tree. But you don't need the fix for your code. Your parseXml method should just take an InputStream rather than a String. You can pass that directly to the InputSource constructor."

Body:
Xml parsing api is throwing sax parse exception, If i try to parse a xml file which has attributes at root node.

One thing i have noticed is that, this happens if there is a UTF-8 BOM character at the start of the string, if i remove the BOM character things work fine. This code is working fine on 3.0 sdk and below, i saw this problem only in 3.1

am using following parser:

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = docFactory.newDocumentBuilder();

    Document doc = null;
    StringReader sr = new StringReader(xmlString);
    InputSource is = new InputSource(sr);

    doc = builder.parse(is);


来源: stackexchange

问:
Cannot connect to Eclipse Mosquitto broker using Node.js mqtt library
I am running Eclipse Mosquitto on a local docker container on 172.17.0.2:1883

I am able to publish/subscribe using MQTT.fx client but now trying to connect to the broker from node and haven't been able to.

The topic is "sensors"

```<code>CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                            NAMES
e747c86b6ec1        eclipse-mosquitto   "/docker-entrypoint.…"   5 hours ago         Up 5 hours          0.0.0.0:1883->1883/tcp, 0.0.0.0:9001->9001/tcp   adoring_varahamihira
</code>```

When I inspect the IP address

```<code>docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' e747c86b6ec1
172.17.0.2
</code>```

I am trying to use the following node server to connect to my MQTT broker but the 'connect' event never seems to happen.

```<code>// Note: I have an express server running but didn't include
const mqtt = require("mqtt")

var MQTT_TOPIC = "sensors";
var MQTT_ADDR = "mqtt://172.17.0.2";
var MQTT_PORT = 1883;

var client = mqtt.connect(MQTT_ADDR, {
  port: MQTT_PORT,
  clientId: 'bgtestnodejs232323',
  protocolId: 'MQIsdp',
  protocolVersion: 3,
  connectTimeout: 1000,
  debug: true
});

client.on('connect', function () {
  console.log("connected!")
});

client.on('error', function (err) {
  console.log(err)``
  client.end()
})
</code>```

When I run:

```<code>console.log(util.inspect(client))
</code>```

The output is:

```<code>MqttClient {
  options:
   { protocol: 'mqtt',
     slashes: true,
     auth: null,
     host: '172.17.0.2',
     port: 1883,
     hostname: '172.17.0.2',
     hash: null,
     search: null,
     query: [Object: null prototype] {},
     pathname: null,
     path: null,
     href: 'mqtt://172.17.0.2',
     clientId: 'bgtestnodejs232323',
     protocolId: 'MQIsdp',
     protocolVersion: 3,
     connectTimeout: 1000,
     debug: true,
     defaultProtocol: 'mqtt',
     keepalive: 60,
     reschedulePings: true,
     reconnectPeriod: 1000,
     clean: true,
     resubscribe: true,
     customHandleAcks: [Function] },
  streamBuilder: [Function: wrapper],
  outgoingStore: Store { options: { clean: true }, _inflights: Map {} },
  incomingStore: Store { options: { clean: true }, _inflights: Map {} },
  queueQoSZero: true,
  _resubscribeTopics: {},
  messageIdToTopic: {},
  pingTimer: null,
  connected: false,
  disconnecting: false,
  queue: [],
  connackTimer:
   Timeout {
     _called: false,
     _idleTimeout: 1000,
     _idlePrev: [TimersList],
     _idleNext: [TimersList],
     _idleStart: 478,
     _onTimeout: [Function],
     _timerArgs: undefined,
     _repeat: null,
     _destroyed: false,
     [Symbol(unrefed)]: false,
     [Symbol(asyncId)]: 9,
     [Symbol(triggerId)]: 1 },
  reconnectTimer: null,
  _storeProcessing: false,
  _packetIdsDuringStoreProcessing: {},
  nextId: 26898,
  outgoing: {},
  _firstConnection: true,
  _events:
   [Object: null prototype] {
     close: [ [Function], [Function], [Function] ],
     connect: [Function] },
  _eventsCount: 2,
  _maxListeners: undefined,
  stream:
   Socket {
     connecting: true,
     _hadError: false,
     _handle:
      TCP {
        reading: false,
        onread: [Function: onStreamRead],
        onconnection: null,
        [Symbol(owner)]: [Circular] },
     _parent: null,
     _host: null,
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: BufferList { head: null, tail: null, length: 0 },
        length: 0,
        pipes: [Writable],
        pipesCount: 1,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: true,
        needReadable: false,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: true,
        paused: false,
        emitClose: false,
        destroyed: false,
        defaultEncoding: 'utf8',
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: false,
     _events:
      [Object: null prototype] {
        end: [Array],
        data: [Function: ondata],
        error: [Function: nop],
        close: [Function] },
     _eventsCount: 4,
     _maxListeners: 1000,
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 34,
        writing: false,
        corked: 1,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: [Object],
        lastBufferedRequest: [Object],
        pendingcb: 9,
        prefinished: false,
        errorEmitted: false,
        emitClose: false,
        bufferedRequestCount: 9,
        corkedRequestsFree: [Object] },
     writable: true,
     allowHalfOpen: false,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: null,
     _server: null,
     [Symbol(asyncId)]: 5,
     [Symbol(lastWriteQueueSize)]: 0,
     [Symbol(timeout)]: null,
     [Symbol(kBytesRead)]: 0,
     [Symbol(kBytesWritten)]: 0 } }
</code>```

I have been trying the suggestions in this answer: Why is MQTT not connecting with NodeJS?

Thanks for your help!

答:
Port 9001 is the websocket listener

Port 1883 is the native MQTT listener

You are using the mqtt:// schema for your broker URL which indicates the native MQTT protocol, yet you are forcing the use of port 9001.

If you want to use WebSockets then you should change the schema to ws://

If you want to use native MQTT then you need to change the port to 1883

ContentLicense: CC BY-SA 4.0

Body:
I am running Eclipse Mosquitto on a local docker container on 172.17.0.2:1883

I am able to publish/subscribe using MQTT.fx client but now trying to connect to the broker from node and haven't been able to.

The topic is "sensors"

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                            NAMES
e747c86b6ec1        eclipse-mosquitto   "/docker-entrypoint.…"   5 hours ago         Up 5 hours          0.0.0.0:1883->1883/tcp, 0.0.0.0:9001->9001/tcp   adoring_varahamihira

When I inspect the IP address

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' e747c86b6ec1
172.17.0.2

I am trying to use the following node server to connect to my MQTT broker but the 'connect' event never seems to happen.

// Note: I have an express server running but didn't include
const mqtt = require("mqtt")

var MQTT_TOPIC = "sensors";
var MQTT_ADDR = "mqtt://172.17.0.2";
var MQTT_PORT = 1883;

var client = mqtt.connect(MQTT_ADDR, {
  port: MQTT_PORT,
  clientId: 'bgtestnodejs232323',
  protocolId: 'MQIsdp',
  protocolVersion: 3,
  connectTimeout: 1000,
  debug: true
});

client.on('connect', function () {
  console.log("connected!")
});

client.on('error', function (err) {
  console.log(err)``
  client.end()
})

When I run:

console.log(util.inspect(client))

The output is:

MqttClient {
  options:
   { protocol: 'mqtt',
     slashes: true,
     auth: null,
     host: '172.17.0.2',
     port: 1883,
     hostname: '172.17.0.2',
     hash: null,
     search: null,
     query: [Object: null prototype] {},
     pathname: null,
     path: null,
     href: 'mqtt://172.17.0.2',
     clientId: 'bgtestnodejs232323',
     protocolId: 'MQIsdp',
     protocolVersion: 3,
     connectTimeout: 1000,
     debug: true,
     defaultProtocol: 'mqtt',
     keepalive: 60,
     reschedulePings: true,
     reconnectPeriod: 1000,
     clean: true,
     resubscribe: true,
     customHandleAcks: [Function] },
  streamBuilder: [Function: wrapper],
  outgoingStore: Store { options: { clean: true }, _inflights: Map {} },
  incomingStore: Store { options: { clean: true }, _inflights: Map {} },
  queueQoSZero: true,
  _resubscribeTopics: {},
  messageIdToTopic: {},
  pingTimer: null,
  connected: false,
  disconnecting: false,
  queue: [],
  connackTimer:
   Timeout {
     _called: false,
     _idleTimeout: 1000,
     _idlePrev: [TimersList],
     _idleNext: [TimersList],
     _idleStart: 478,
     _onTimeout: [Function],
     _timerArgs: undefined,
     _repeat: null,
     _destroyed: false,
     [Symbol(unrefed)]: false,
     [Symbol(asyncId)]: 9,
     [Symbol(triggerId)]: 1 },
  reconnectTimer: null,
  _storeProcessing: false,
  _packetIdsDuringStoreProcessing: {},
  nextId: 26898,
  outgoing: {},
  _firstConnection: true,
  _events:
   [Object: null prototype] {
     close: [ [Function], [Function], [Function] ],
     connect: [Function] },
  _eventsCount: 2,
  _maxListeners: undefined,
  stream:
   Socket {
     connecting: true,
     _hadError: false,
     _handle:
      TCP {
        reading: false,
        onread: [Function: onStreamRead],
        onconnection: null,
        [Symbol(owner)]: [Circular] },
     _parent: null,
     _host: null,
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: BufferList { head: null, tail: null, length: 0 },
        length: 0,
        pipes: [Writable],
        pipesCount: 1,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: true,
        needReadable: false,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: true,
        paused: false,
        emitClose: false,
        destroyed: false,
        defaultEncoding: 'utf8',
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: false,
     _events:
      [Object: null prototype] {
        end: [Array],
        data: [Function: ondata],
        error: [Function: nop],
        close: [Function] },
     _eventsCount: 4,
     _maxListeners: 1000,
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 34,
        writing: false,
        corked: 1,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: [Object],
        lastBufferedRequest: [Object],
        pendingcb: 9,
        prefinished: false,
        errorEmitted: false,
        emitClose: false,
        bufferedRequestCount: 9,
        corkedRequestsFree: [Object] },
     writable: true,
     allowHalfOpen: false,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: null,
     _server: null,
     [Symbol(asyncId)]: 5,
     [Symbol(lastWriteQueueSize)]: 0,
     [Symbol(timeout)]: null,
     [Symbol(kBytesRead)]: 0,
     [Symbol(kBytesWritten)]: 0 } }

I have been trying the suggestions in this answer: Why is MQTT not connecting with NodeJS?

Thanks for your help!


问:
d3 - problem aligning text with circle center - dominant-baseline not working on Firefox
I am trying to build legend using circle in the following code:

```<code>    gap_between_circles = 5;
    circle_text_gap = 2;
    circle_r = 7;

    index = 0;

    for(key in colors)
    {
        g.append("circle")
        .attr("cx",width)
        .attr("cy",(circle_r*2 +gap_between_circles)* index)
        .attr("r", circle_r)
        .style("fill",colors[key]);

        g.append("text")
        .text(key)
        .attr("x", width + circle_r + circle_text_gap)
        .attr("y", (circle_r*2 +gap_between_circles)* index)
        .attr("dominant-baseline","middle");

        index++;
   }
</code>```

It shows up like this on Firefox:

Notice how the text is not aligned with the center of the circle.
How do I fix this?

Note : the problem doesn't happen on Chrome

答:
I think the issue here is that the dominant-baseline that you chose works well for lower-case letters, but not for upper-case or numbers.

I created a pen here to illustrate (and image below).

For the first two items, the alignment uses the dominant-baseline of middle, but in the third if you use mathematical it lines up nicely.

Body:
I am trying to build legend using circle in the following code:

    gap_between_circles = 5;
    circle_text_gap = 2;
    circle_r = 7;

    index = 0;

    for(key in colors)
    {
        g.append("circle")
        .attr("cx",width)
        .attr("cy",(circle_r*2 +gap_between_circles)* index)
        .attr("r", circle_r)
        .style("fill",colors[key]);

        g.append("text")
        .text(key)
        .attr("x", width + circle_r + circle_text_gap)
        .attr("y", (circle_r*2 +gap_between_circles)* index)
        .attr("dominant-baseline","middle");

        index++;
   }

It shows up like this on Firefox:

Notice how the text is not aligned with the center of the circle.
How do I fix this?

Note : the problem doesn't happen on Chrome


问:
Seeing black bars at the top and bottom of the iPhone X Simulator
Running my App in the iPhone X Simulator (GM Seed) I am noticing two strange effects:

the App does not use the full screen space (top and bottom area is black)

a strange white bar beneath the title bar

Does anybody know what is happening here and how to resolve this? I can't find any new settings in Interface Builder.

答: You may check in project target launch screen file is not set to empty if it is empty it may cause problem.

ContentLicense: CC BY-SA 3.0


问:
Copy items from Source to Destination if they don't already exist
I have a pretty basic powershell copy script that copies items from a source folder to a destination folder. However this is moving way too much data, and I'd like to check if the filename already exists so that file can be ignored. I don't need this as complex as verifying created date/checksum/etc.

Currently it's along the lines of:

```<code>Copy-Item source destination -recurse
Copy-Item source2 destination2 -recurse
</code>```

I'd imagine I need to add the Test-Path cmdlet, but I'm uncertain how to implement it.

答:
Here is a recursive script that syncronizes 2 folders ignoring existing files:

```<code>function Copy-FilesAndFolders([string]$folderFrom, [string]$folderTo) {
    $itensFrom = Get-ChildItem $folderFrom
    foreach ($i in $itensFrom)
    {
        if ($i.PSIsContainer)
        {
            $subFolderFrom = $folderFrom + "\" + $i.BaseName
            $subFolderTo = $folderTo + "\" + $i.BaseName
            Copy-FilesAndFolders $subFolderFrom $subFolderTo | Out-Null
        }
        else
        {
            $from = $folderFrom + "\" + $i.Name
            $to = $folderTo + "\" + $i.Name
            if (!(Test-Path $from)) # only copies non-existing files
            {
                if (!(Test-Path $folderTo)) # if folder doesn't exist, creates it
                {
                    New-Item -ItemType "directory" -Path $folderTo
                }
                Copy-Item $from $folderTo
            }
        }
    }
}
</code>```

To call it:

```<code>Copy-FilesAndFolders "C:\FromFolder" "C:\ToFolder"
</code>```

Body:
I have a pretty basic powershell copy script that copies items from a source folder to a destination folder. However this is moving way too much data, and I'd like to check if the filename already exists so that file can be ignored. I don't need this as complex as verifying created date/checksum/etc.

Currently it's along the lines of:

Copy-Item source destination -recurse
Copy-Item source2 destination2 -recurse

I'd imagine I need to add the Test-Path cmdlet, but I'm uncertain how to implement it.

Body:
Here is a recursive script that syncronizes 2 folders ignoring existing files:

function Copy-FilesAndFolders([string]$folderFrom, [string]$folderTo) {
    $itensFrom = Get-ChildItem $folderFrom
    foreach ($i in $itensFrom)
    {
        if ($i.PSIsContainer)
        {
            $subFolderFrom = $folderFrom + "\" + $i.BaseName
            $subFolderTo = $folderTo + "\" + $i.BaseName
            Copy-FilesAndFolders $subFolderFrom $subFolderTo | Out-Null
        }
        else
        {
            $from = $folderFrom + "\" + $i.Name
            $to = $folderTo + "\" + $i.Name
            if (!(Test-Path $from)) # only copies non-existing files
            {
                if (!(Test-Path $folderTo)) # if folder doesn't exist, creates it
                {
                    New-Item -ItemType "directory" -Path $folderTo
                }
                Copy-Item $from $folderTo
            }
        }
    }
}

To call it:

Copy-FilesAndFolders "C:\FromFolder" "C:\ToFolder"


问:
Let a function accept different types for the same variable?
I have to make a function accept either string or int for the first and second variable its declaring:

```<code>char safe_at(int position, string s){ // example when the first is int and the second is string
    if (position < s.length()){

        return s[position];
    }
    else {
        return ' ';
    }
}

char safe_at(string s, int position){ // example when the first is string and the second is int
    if (position < s.length()){

        return s[position];
    }
    else {
        return ' ';
    }
}
</code>```

I'm not sure you can do it the way I am describing.
My assignment requires me to only use one function, which confuses me.

答:
If you are coming from Python, you have a lot to learn about type-safety (or unlearn about dynamic typing, depending on how you see it ;). A function can only take parameters of fixed type. However, you can overload functions:

Lets assume you have this:

```<code>char safe_at(int position, string s){ // example when the first is int and the second is string
    if (position < s.length()){

        return s[position];
    }
    else {
        return ' ';
    }
}
</code>```

And now you want to enable calling the function with the order of the parameters swapped, then you can provide an overload like this:

```<code>char safe_at(int position, string s) {
    return safe_at(s,position);
}
</code>```

In a nutshell, the function to call is determined by the types of the supplied parameters and we can reuse the implementation. Then

```<code> std::string f{"foo"};
 int x = 42;
 auto c = safe_at(f,x);
 c = safe_at(x,f);
</code>```

..the first call will resolve to a call to safe_at(std::string,int) and the second will call safe_at(int,std::string).

PS Actually your code is fine as is, but of course you want to avoid code duplication.

PPS

My assignment requires me to only use one function, which confuses me.

There must be a small misunderstanding somewhere, because it can be done with a single function, but that wouldn't be trivial and certainly overkill for this situation. Colloquially when talking about "functions" actually a full overload set is considered. Even std::string::length is actually two functions. It has a const and a non-const overload (see here).

PPPS I suppose this is a task given to you. It is not clear why you are supposed to write the fucntion such that the order of parameters can be swapped. Functions that have more than one parameter can be a source of confusion and errors. Consider

```<code>void foo(int x,char z);
</code>```

Then both following ways to call it will compile

```<code>int x = 42;
char y = 0;
foo(x,y);
foo(y,x);
</code>```

Writing parameters in the wrong order can happen by mistake. Writing a fucntion that allows to swap paramters does not really help on that, it rather adds confusion. In my opinion the aim of your taks is rather questionable.

Body:
I have to make a function accept either string or int for the first and second variable its declaring:

char safe_at(int position, string s){ // example when the first is int and the second is string
    if (position < s.length()){

        return s[position];
    }
    else {
        return ' ';
    }
}

char safe_at(string s, int position){ // example when the first is string and the second is int
    if (position < s.length()){

        return s[position];
    }
    else {
        return ' ';
    }
}

I'm not sure you can do it the way I am describing.
My assignment requires me to only use one function, which confuses me.

Body:
If you are coming from Python, you have a lot to learn about type-safety (or unlearn about dynamic typing, depending on how you see it ;). A function can only take parameters of fixed type. However, you can overload functions:

Lets assume you have this:

char safe_at(int position, string s){ // example when the first is int and the second is string
    if (position < s.length()){

        return s[position];
    }
    else {
        return ' ';
    }
}

And now you want to enable calling the function with the order of the parameters swapped, then you can provide an overload like this:

char safe_at(int position, string s) {
    return safe_at(s,position);
}

In a nutshell, the function to call is determined by the types of the supplied parameters and we can reuse the implementation. Then

 std::string f{"foo"};
 int x = 42;
 auto c = safe_at(f,x);
 c = safe_at(x,f);

..the first call will resolve to a call to safe_at(std::string,int) and the second will call safe_at(int,std::string).

PS Actually your code is fine as is, but of course you want to avoid code duplication.

PPS

My assignment requires me to only use one function, which confuses me.

There must be a small misunderstanding somewhere, because it can be done with a single function, but that wouldn't be trivial and certainly overkill for this situation. Colloquially when talking about "functions" actually a full overload set is considered. Even std::string::length is actually two functions. It has a const and a non-const overload (see here).

PPPS I suppose this is a task given to you. It is not clear why you are supposed to write the fucntion such that the order of parameters can be swapped. Functions that have more than one parameter can be a source of confusion and errors. Consider

void foo(int x,char z);

Then both following ways to call it will compile

int x = 42;
char y = 0;
foo(x,y);
foo(y,x);

Writing parameters in the wrong order can happen by mistake. Writing a fucntion that allows to swap paramters does not really help on that, it rather adds confusion. In my opinion the aim of your taks is rather questionable.


问:
How to get difference of time between two datetime columns pandas?
I have two different columns in my dataset,

```<code>       start    end
0   2015-01-01  2017-01-01
1   2015-01-02  2015-06-02
2   2015-01-03  2015-12-03
3   2015-01-04  2020-11-25
4   2015-01-05  2025-07-27
</code>```

I want the difference between start and end in a specific way, here's my desired output.

```<code>year_diff  month_diff
        2           1
        0           6
        0          12
        5          11
       10           7
</code>```

Here the day is not important to me, only month and year. I've tried to period to get diff but it returns just different in months only. how can I achieve my desired output?

```<code>df['end'].dt.to_period('M') - df['start'].dt.to_period('M'))
</code>```

答:
This solution assumes that the number of days that make up a year (365) and a month (30) are constant. If the datetimes are strings, convert them into a datetime object. In a Pandas DataFrame this can be done like so

```<code>def to_datetime(dataframe):
    new_dataframe = pd.DataFrame()
    new_dataframe[0] = pd.to_datetime(dataframe[0], format="%Y-%m-%d")
    new_dataframe[1] = pd.to_datetime(dataframe[1], format="%Y-%m-%d")
    return new_dataframe
</code>```

Next, column 1 can be subtracted from column 0 to give the difference in days. We can divide this number by 365 using the // operator to get the number of whole years. We can get the number of remaining days using the % operator and divide this by 30 using the // operator the get the number of whole months.

```<code>def get_time_diff(dataframe):
    dataframe[2] = dataframe[1] - dataframe[0]
    diff_dataframe = pd.DataFrame(columns=["year_diff", "month_diff"])
    for i in range(0, dataframe.index.stop):
        year_diff = dataframe[2][i].days // 365
        month_diff = (dataframe[2][i].days % 365) // 30
        diff_dataframe.loc[i] = [year_diff, month_diff]

    return diff_dataframe
</code>```

An example output from using these functions would be

```<code>       start        end days_diff year_diff month_diff
0 2019-10-15 2021-08-11  666 days         1         10
1 2020-02-11 2022-10-13  975 days         2          8
2 2018-12-17 2020-09-16  639 days         1          9
3 2017-01-03 2017-01-28   25 days         0          0
4 2019-12-21 2022-03-10  810 days         2          2
5 2018-08-08 2019-05-07  272 days         0          9
6 2017-06-18 2020-08-01 1140 days         3          1
7 2017-11-14 2020-04-17  885 days         2          5
8 2019-08-19 2020-05-10  265 days         0          8
9 2018-05-05 2020-09-08  857 days         2          4
</code>```

Note: This will give the number of whole years and months. Hence, if there is a remainder of 29 days, one day short from a month, this will not be counted.

Body:
I have two different columns in my dataset,

       start    end
0   2015-01-01  2017-01-01
1   2015-01-02  2015-06-02
2   2015-01-03  2015-12-03
3   2015-01-04  2020-11-25
4   2015-01-05  2025-07-27

I want the difference between start and end in a specific way, here's my desired output.

year_diff  month_diff
        2           1
        0           6
        0          12
        5          11
       10           7

Here the day is not important to me, only month and year. I've tried to period to get diff but it returns just different in months only. how can I achieve my desired output?

df['end'].dt.to_period('M') - df['start'].dt.to_period('M'))

Body:
This solution assumes that the number of days that make up a year (365) and a month (30) are constant. If the datetimes are strings, convert them into a datetime object. In a Pandas DataFrame this can be done like so

def to_datetime(dataframe):
    new_dataframe = pd.DataFrame()
    new_dataframe[0] = pd.to_datetime(dataframe[0], format="%Y-%m-%d")
    new_dataframe[1] = pd.to_datetime(dataframe[1], format="%Y-%m-%d")
    return new_dataframe

Next, column 1 can be subtracted from column 0 to give the difference in days. We can divide this number by 365 using the // operator to get the number of whole years. We can get the number of remaining days using the % operator and divide this by 30 using the // operator the get the number of whole months.

def get_time_diff(dataframe):
    dataframe[2] = dataframe[1] - dataframe[0]
    diff_dataframe = pd.DataFrame(columns=["year_diff", "month_diff"])
    for i in range(0, dataframe.index.stop):
        year_diff = dataframe[2][i].days // 365
        month_diff = (dataframe[2][i].days % 365) // 30
        diff_dataframe.loc[i] = [year_diff, month_diff]

    return diff_dataframe

An example output from using these functions would be

       start        end days_diff year_diff month_diff
0 2019-10-15 2021-08-11  666 days         1         10
1 2020-02-11 2022-10-13  975 days         2          8
2 2018-12-17 2020-09-16  639 days         1          9
3 2017-01-03 2017-01-28   25 days         0          0
4 2019-12-21 2022-03-10  810 days         2          2
5 2018-08-08 2019-05-07  272 days         0          9
6 2017-06-18 2020-08-01 1140 days         3          1
7 2017-11-14 2020-04-17  885 days         2          5
8 2019-08-19 2020-05-10  265 days         0          8
9 2018-05-05 2020-09-08  857 days         2          4

Note: This will give the number of whole years and months. Hence, if there is a remainder of 29 days, one day short from a month, this will not be counted.


问:
javascript convert set to comma separated string - IE11
I'm having issues to convert a Set to a comma separated string in IE11, the below works fine in chrome, but IE11 doesn't like Array.from.

```<code>let a = new Set();
a.add("a");
a.add("b");

console.log(Array.from(a).join(","));
</code>```

To get a work around I'm doing:

```<code>let aArray = [];
let pushToArray = function(val) {
  aArray.push(val);
};
a.forEach(pushToArray);

console.log(aArray.toString());
</code>```

Any suggestion on how to do the above better that works in IE11?

答:
It could be better, if you don't even build an array from it, only create the string using concatenation:

let a = new Set();
a.add("a");
a.add("b");

function SetToString(set, delim){
  let str = '';
  set.forEach(function(elem){
    str += elem + delim
  });
  return str
}
console.log(SetToString(a, ','));
```

<p>The only issue with this approach is that it will add a comma at the end as well.</p>

<p>To avoid this, you have two ways:</p>

<ul>
<li><p>Remove the last comma using <code>.slice(0, -1)</code></p>

```let a = new Set();
a.add("a");
a.add("b");

function SetToString(set, delim){
  let str = '';
  set.forEach(function(elem){
    str += elem + delim
  });
  return str.slice(0, -1)
}
console.log(SetToString(a, ','));
```</li>
<li><p>Count elements, and omit comma for the last</p>

```let a = new Set();
a.add("a");
a.add("b");

function SetToString(set, delim){
  let str = '';
  let i = 0;
  let size = set.size;
  set.forEach(function(elem){
    str += elem
    if(i++ < size - 1) str += delim
  });
  return str
}
console.log(SetToString(a, ','));
```

Body:
I'm having issues to convert a Set to a comma separated string in IE11, the below works fine in chrome, but IE11 doesn't like Array.from.

let a = new Set();
a.add("a");
a.add("b");

console.log(Array.from(a).join(","));

To get a work around I'm doing:

let aArray = [];
let pushToArray = function(val) {
  aArray.push(val);
};
a.forEach(pushToArray);

console.log(aArray.toString());

Any suggestion on how to do the above better that works in IE11?

Body:
It could be better, if you don't even build an array from it, only create the string using concatenation:

let a = new Set();
a.add("a");
a.add("b");

function SetToString(set, delim){
  let str = '';
  set.forEach(function(elem){
    str += elem + delim
  });
  return str
}
console.log(SetToString(a, ','));

The only issue with this approach is that it will add a comma at the end as well.

To avoid this, you have two ways:

Remove the last comma using .slice(0, -1)

let a = new Set();
a.add("a");
a.add("b");

function SetToString(set, delim){
  let str = '';
  set.forEach(function(elem){
    str += elem + delim
  });
  return str.slice(0, -1)
}
console.log(SetToString(a, ','));

Count elements, and omit comma for the last

let a = new Set();
a.add("a");
a.add("b");

function SetToString(set, delim){
  let str = '';
  let i = 0;
  let size = set.size;
  set.forEach(function(elem){
    str += elem
    if(i++ < size - 1) str += delim
  });
  return str
}
console.log(SetToString(a, ','));


问:
How to show error message for typing in text box any thing else except number / numeric in angular 8
I have a text box,which only allows to type number,If I try to type alphabet or any special character it should show error below the text box.Once I start typing numeric error should hide.Here I am using reactive form of angular 8. Here is the code below

home.component.html

```<code><form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
            <div class="form-row">
                <div class="form-group col">
                    <label>Title</label>
                    <input type="number" formControlName="title" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.title.errors }"/>

                    <div *ngIf="submitted && f.title.errors" class="invalid-feedback">
                        <div *ngIf="f.title.errors.required">Title is required</div>
                    </div>

                </div>

</div>
<div class="text-center">
                <button class="btn btn-primary mr-1">Register</button>
                <button class="btn btn-secondary" type="reset" >Cancel</button>
            </div>
</form>
</code>```

home.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
declare var $: any;
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
imageSource :any;
 statusdata: any;
closeResult: string;
registerForm: FormGroup;
    submitted = false;

constructor(private modalService: NgbModal,private formBuilder: FormBuilder) {}
  ngOnInit() {
    this.statusdata = [
      { id: 1, name: "cat"},
      { id: 2, name: "arctichare"},
      { id: 3, name: "baboon" },

    ];
    this.registerForm = this.formBuilder.group({
            title: ['', Validators.required]

        });
  }
  get f() { return this.registerForm.controls; }
onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.registerForm.invalid) {
            return;
        }

        // display form values on success
        alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.registerForm.value, null, 4));
    }

}
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UsermanagementComponent } from './usermanagement/usermanagement.component';
import { HomeComponent } from './home/home.component';
import { HeaderComponent } from './shared/header/header.component';
import { LoginComponent } from './login/login.component';
import {HttpModule} from '@angular/http';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
  declarations: [
    AppComponent,
    UsermanagementComponent,
    HomeComponent,
    HeaderComponent,
    LoginComponent
  ],
  imports: [
    NgbModule,
    BrowserModule,
    AppRoutingModule,
    HttpModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
I think you can catch input values with keydown or keyup.

change your input as following:

```<code> <input type="number" formControlName="title" class="form-control"
          #inp (keydown)="checkValue($event, inp.value)"
          [ngClass]="{ 'is-invalid': submitted && f.title.errors }"/>
</code>```

And add following method to your component:

```<code>checkValue(event: KeyboardEvent, val: any) {

    const allowedChars = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "Backspace", "ArrowLeft", "ArrowRight"];
    let isValid: boolean = false;

    for (let i = 0; i < allowedChars.length; i++) {
      if (allowedChars[i] == event.key) {
        isValid = true;
        break;
      }
    }

    if (!isValid) {
      event.preventDefault();
      alert('Enter only number'); // or do smt about your error message
    }else{
        //reset error status here
     }

  }
</code>```

Body:
I have a text box,which only allows to type number,If I try to type alphabet or any special character it should show error below the text box.Once I start typing numeric error should hide.Here I am using reactive form of angular 8. Here is the code below

home.component.html

<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">

                    Title
                    <input type="number" formControlName="title" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.title.errors }"/>

Title is required

                <button class="btn btn-primary mr-1">Register</button>
                <button class="btn btn-secondary" type="reset" >Cancel</button>

</form>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
declare var $: any;
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
imageSource :any;
 statusdata: any;
closeResult: string;
registerForm: FormGroup;
    submitted = false;

constructor(private modalService: NgbModal,private formBuilder: FormBuilder) {}
  ngOnInit() {
    this.statusdata = [
      { id: 1, name: "cat"},
      { id: 2, name: "arctichare"},
      { id: 3, name: "baboon" },

    ];
    this.registerForm = this.formBuilder.group({
            title: ['', Validators.required]

        });
  }
  get f() { return this.registerForm.controls; }
onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.registerForm.invalid) {
            return;
        }

        // display form values on success
        alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.registerForm.value, null, 4));
    }

}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UsermanagementComponent } from './usermanagement/usermanagement.component';
import { HomeComponent } from './home/home.component';
import { HeaderComponent } from './shared/header/header.component';
import { LoginComponent } from './login/login.component';
import {HttpModule} from '@angular/http';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
  declarations: [
    AppComponent,
    UsermanagementComponent,
    HomeComponent,
    HeaderComponent,
    LoginComponent
  ],
  imports: [
    NgbModule,
    BrowserModule,
    AppRoutingModule,
    HttpModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Body:
I think you can catch input values with keydown or keyup.

change your input as following:

 <input type="number" formControlName="title" class="form-control"
          #inp (keydown)="checkValue($event, inp.value)"
          [ngClass]="{ 'is-invalid': submitted && f.title.errors }"/>

And add following method to your component:

checkValue(event: KeyboardEvent, val: any) {

    const allowedChars = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "Backspace", "ArrowLeft", "ArrowRight"];
    let isValid: boolean = false;

    for (let i = 0; i < allowedChars.length; i++) {
      if (allowedChars[i] == event.key) {
        isValid = true;
        break;
      }
    }

    if (!isValid) {
      event.preventDefault();
      alert('Enter only number'); // or do smt about your error message
    }else{
        //reset error status here
     }

  }


问:
How to read one full line, followed by reading only the last five characters?
I am new to Python. I want to read a JSON file from monitoring. The file looks like this

I only want the timestamp, the system name like "test-1" and the numbers from power, disk and CPU.

My script looks like this

```<code>#!/usr/bin/env python3.3

import os
import json

    with open('test.json', 'r') as f:
        distros_dict = json.load(f)

    for distro in distros_dict:
        print(distro['"power [W]"'])
</code>```

Update:
How do i write them to variables?

New Sample Data:

```<code>[
   {
      "Area":"CLOUD",
      "timestamp":"2019-11-06T00:00:00",
      "Systeme":{
         "test-4":{
            "power [W]":181.05,
            "disk [%]":52.28
         },
         "test-1":{
            "power [W]":280.56,
            "disk[%]":6.33,
            "cpu[%]":0.1
         },
         "test-2":{
            "power [W]":271.84,
            "disk[%]":6.52,
            "cpu[%]":0.1
         },
         "test-8":{
            "power [W]":453.56,
            "disk[%]":93.63,
            "cpu[%]":5.04
         }
      }
   }
]
</code>```

The Output variables i want are cpu,power and disk
Instead of printing them to commandline i want write them in the three variables

答:
you can try out this approach. you will need to install pandas for it

pip install pandas

```<code>import json
import pandas as pd
data = json.load(open('data.json'))  // asuming your data is in data.json

new_json=[]
for rec in data:
    new_doc = {}
    for key in rec:
        if type(rec[key]) is str:
            new_doc[key] = rec[key]
        else:
            for key1 in rec[key]:
                if type(rec[key][key1]) is str:
                    new_doc[key+'_'+key1] = rec[key][key1]
                else:
                    for key2 in rec[key][key1]:
                        if type(rec[key][key1][key2]) in [str,float,int]:
                            new_doc[key+'_'+key1+'_'+key2] = rec[key][key1][key2]
                        else:
                            print("don't support more nested json")
    new_json.append(new_doc)

data = pd.DataFrame(new_json)
data.head()  //peak into your new data structure][1]][1]
</code>```

now you will have a well formatted table structure and can do any query on it.
so to get all type-1-power and timestamp simply do

```<code>data[['Systeme_test-1_power [W]','timestamp']]
</code>```

We can do a lot other type of query and graph plotting from here very easily.
Read panda docs for more or comment if you have doubt

Body:
I am new to Python. I want to read a JSON file from monitoring. The file looks like this

I only want the timestamp, the system name like "test-1" and the numbers from power, disk and CPU.

My script looks like this

#!/usr/bin/env python3.3

import os
import json

    with open('test.json', 'r') as f:
        distros_dict = json.load(f)

    for distro in distros_dict:
        print(distro['"power [W]"'])

Update:
How do i write them to variables?

New Sample Data:

[
   {
      "Area":"CLOUD",
      "timestamp":"2019-11-06T00:00:00",
      "Systeme":{
         "test-4":{
            "power [W]":181.05,
            "disk [%]":52.28
         },
         "test-1":{
            "power [W]":280.56,
            "disk[%]":6.33,
            "cpu[%]":0.1
         },
         "test-2":{
            "power [W]":271.84,
            "disk[%]":6.52,
            "cpu[%]":0.1
         },
         "test-8":{
            "power [W]":453.56,
            "disk[%]":93.63,
            "cpu[%]":5.04
         }
      }
   }
]

The Output variables i want are cpu,power and disk
Instead of printing them to commandline i want write them in the three variables

Body:
you can try out this approach. you will need to install pandas for it

pip install pandas

import json
import pandas as pd
data = json.load(open('data.json'))  // asuming your data is in data.json

new_json=[]
for rec in data:
    new_doc = {}
    for key in rec:
        if type(rec[key]) is str:
            new_doc[key] = rec[key]
        else:
            for key1 in rec[key]:
                if type(rec[key][key1]) is str:
                    new_doc[key+'_'+key1] = rec[key][key1]
                else:
                    for key2 in rec[key][key1]:
                        if type(rec[key][key1][key2]) in [str,float,int]:
                            new_doc[key+'_'+key1+'_'+key2] = rec[key][key1][key2]
                        else:
                            print("don't support more nested json")
    new_json.append(new_doc)

data = pd.DataFrame(new_json)
data.head()  //peak into your new data structure][1]][1]

now you will have a well formatted table structure and can do any query on it.
so to get all type-1-power and timestamp simply do

data[['Systeme_test-1_power [W]','timestamp']]

We can do a lot other type of query and graph plotting from here very easily.
Read panda docs for more or comment if you have doubt


问:
Java8: Stream merge two lists
I have two lists

```<code>List1 - (1, 2, 3)
List2 - (4, 5, 6,7, 8)
</code>```

Want to merge both the list as  (1, 4, 2, 5, 3, 6, 7, 8) using java streams

First element from List1, List2 and, Second element from list1, list2 ...so on..if any extra elements remain then place at the end.

答:
```<code>Stream.concat(list1.stream(), list2.stream())
   .collect(Collectors.toList())
</code>```

Title: Java8: Stream merge two lists

Body:
I have two lists

List1 - (1, 2, 3)
List2 - (4, 5, 6,7, 8)

Want to merge both the list as  (1, 4, 2, 5, 3, 6, 7, 8) using java streams

First element from List1, List2 and, Second element from list1, list2 ...so on..if any extra elements remain then place at the end.


问:
Handling Xarray/Dask Memory
I'm trying to use Xarray and Dask to open a multi-file dataset. However, I'm running into memory errors.

I have files that are typically this shape:

```<code> xr.open_dataset("/work/ba0989/a270077/coupled_ice_paper/model_data/coupled/LIG_coupled/outdata/fesom//LIG_coupled_fesom_thetao_19680101.nc")

<xarray.Dataset>
Dimensions:  (depth: 46, nodes_2d: 126859, time: 366)
Coordinates:
  * time     (time) datetime64[ns] 1968-01-02 1968-01-03 ... 1969-01-01
  * depth    (depth) float64 -0.0 10.0 20.0 30.0 ... 5.4e+03 5.65e+03 5.9e+03
Dimensions without coordinates: nodes_2d
Data variables:
    thetao   (time, depth, nodes_3d) float32 ...
Attributes:
    output_schedule:  unit: d first: 1 rate: 1

30 files --> 41.5 GB
</code>```

I also can set up a dask.distributed Client object:

```<code>Client()
<Client: 'tcp://127.0.0.1:43229' processes=8 threads=48, memory=68.72 GB>
</code>```

So, if I suppose there is enough memory for the data to be loaded. However, when I then run xr.open_mfdataset, I very often get these sorts of warnings:

```<code>distributed.worker - WARNING - Memory use is high but worker has no data to store to disk.  Perhaps some other process is leaking memory?  Process memory: 8.25 GB -- Worker memory limit: 8.59 GB
</code>```

I guess there is something I can do with the chunks argument?

Any help would be very appreciated; unfortunately I'm not sure where to begin trying. I could, in principle, open just the first file (they will always have the same shape) to figure out how to ideally rechunk the files.

Thanks!
Paul

答:
Examples of the chunks and parallel keywords to the opening functions, which correspond to how you utilise dask, can be found in this doc section.

That should be all you need!

Title: Handling Xarray/Dask Memory

Body:
I'm trying to use Xarray and Dask to open a multi-file dataset. However, I'm running into memory errors.

I have files that are typically this shape:

 xr.open_dataset("/work/ba0989/a270077/coupled_ice_paper/model_data/coupled/LIG_coupled/outdata/fesom//LIG_coupled_fesom_thetao_19680101.nc")

<xarray.Dataset>
Dimensions:  (depth: 46, nodes_2d: 126859, time: 366)
Coordinates:
  * time     (time) datetime64[ns] 1968-01-02 1968-01-03 ... 1969-01-01
  * depth    (depth) float64 -0.0 10.0 20.0 30.0 ... 5.4e+03 5.65e+03 5.9e+03
Dimensions without coordinates: nodes_2d
Data variables:
    thetao   (time, depth, nodes_3d) float32 ...
Attributes:
    output_schedule:  unit: d first: 1 rate: 1

30 files --> 41.5 GB

I also can set up a dask.distributed Client object:

Client()
<Client: 'tcp://127.0.0.1:43229' processes=8 threads=48, memory=68.72 GB>

So, if I suppose there is enough memory for the data to be loaded. However, when I then run xr.open_mfdataset, I very often get these sorts of warnings:

distributed.worker - WARNING - Memory use is high but worker has no data to store to disk.  Perhaps some other process is leaking memory?  Process memory: 8.25 GB -- Worker memory limit: 8.59 GB

I guess there is something I can do with the chunks argument?

Any help would be very appreciated; unfortunately I'm not sure where to begin trying. I could, in principle, open just the first file (they will always have the same shape) to figure out how to ideally rechunk the files.

Thanks!
Paul


问:
How can I detect a ThreadAbortException in a finally block? (.NET)
I have some critical logic in a finally block (with an empty try block), because I want to guarantee that the code gets executed even if the thread is aborted. However, I'd also like to detect the ThreadAbortException. I've found that wrapping my critical try/finally block in a try/catch does not catch the ThreadAbortException. Is there any way to detect it?</p>

```
try {
    try { }
    finally {
        // critical logic
    }
} catch(Exception ex) {
    // ThreadAbortException is not caught here, but exceptions thrown
    // from within the critical logic are
}
```

答:
Have you tried something like this?</p>

```<code>try {
    try { }
    catch (ThreadAbortException)
    {
      ThreadAbortExceptionBool = true;
    }
    finally {
        // critical logic
        if (ThreadAbortExceptionBool)
          // Whatever
    }
}
catch(Exception ex) {
    // ThreadAbortException is not caught here, but exceptions thrown
    // from within the critical logic are
}
</code>```

OwnerDisplayName: Christopher

Body:
I have some critical logic in a finally block (with an empty try block), because I want to guarantee that the code gets executed even if the thread is aborted. However, I'd also like to detect the ThreadAbortException. I've found that wrapping my critical try/finally block in a try/catch does not catch the ThreadAbortException. Is there any way to detect it?

try {
    try { }
    finally {
        // critical logic
    }
} catch(Exception ex) {
    // ThreadAbortException is not caught here, but exceptions thrown
    // from within the critical logic are
}

Body:
Have you tried something like this?

try {
    try { }
    catch (ThreadAbortException)
    {
      ThreadAbortExceptionBool = true;
    }
    finally {
        // critical logic
        if (ThreadAbortExceptionBool)
          // Whatever
    }
}
catch(Exception ex) {
    // ThreadAbortException is not caught here, but exceptions thrown
    // from within the critical logic are
}

OwnerDisplayName: Jorge Córdoba

ContentLicense: CC BY-SA 2.5


问:
Iphone sdk sample AVCam to drive the following error has occurred
Iphone sdk sample AVCam to drive the following error has occurred.

```<code>warning: Unable to read symbols for /Library/MobileSubstrate/MobileSubstrate.dylib (file not found).
warning: Unable to read symbols for /Library/Frameworks/CydiaSubstrate.framework/Libraries/SubstrateLoader.dylib (file not found).
2011-05-17 14:12:15.927 AVCam[225:607] MS:Notice: Installing: com.224ok.movieplayer [AVCam] (550.58)
2011-05-17 14:12:15.973 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/3GMy3G.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/3GMy3G.dylib (file not found).
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.2 (8H7)/Symbols/usr/lib/libcrypto.0.9.8.dylib (file not found).
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.2 (8H7)/Symbols/usr/lib/libsubstrate.dylib (file not found).
2011-05-17 14:12:16.393 AVCam[225:607] My3G waiting for User Prompt in com.224ok.movieplayer  v4.8..
2011-05-17 14:12:16.408 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/Activator.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/Activator.dylib (file not found).
2011-05-17 14:12:16.823 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/AskToCall.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/AskToCall.dylib (file not found).
MS:Warning: nil class argument
MS:Warning: nil class argument
2011-05-17 14:12:17.084 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/Backgrounder.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/Backgrounder.dylib (file not found).
2011-05-17 14:12:17.300 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/KeyboardFix.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/KeyboardFix.dylib (file not found).
2011-05-17 14:12:17.486 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/Springtomize.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/Springtomize.dylib (file not found).
MS:Warning: nil class argument
/* last message repeated many times */
MS:Warning: nil class argument
2011-05-17 14:12:17.711 AVCam[225:607] [Springtomize]: factor: 0.500000
2011-05-17 14:12:17.716 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/SwipeToMoveCursor.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/SwipeToMoveCursor.dylib (file not found).
MS:Warning: nil class argument
2011-05-17 14:12:17.872 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/WinterBoard.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/WinterBoard.dylib (file not found).
2011-05-17 14:12:18.064 AVCam[225:607] WB:Notice: WinterBoard
MS:Warning: message not found [UIImage defaultDesktopImage]
2011-05-17 14:12:18.104 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/biteSBarClient.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/biteSBarClient.dylib (file not found).
2011-05-17 14:12:18.328 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/libstatusbar.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/libstatusbar.dylib (file not found).
2011-05-17 14:12:18.532 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/sandcastleclient.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/sandcastleclient.dylib (file not found).
Current language:  auto; currently objective-c
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.2 (8H7)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found).
(gdb) continue
Program received signal:  “SIGUSR1”.
warning: Remote failure reply: E37
(gdb) continue
</code>```

I mean why run without modification?

答: The problem here is probably that you're trying to use XCode with a jailbroken iPhone, and XCode is trying (unsuccessfully) to find symbols that aren't there for libraries like CydiaSubstrate. If so, you may have to reinstall iOS and forego jailbreaking to get XCode and your phone to play nice together.

Body:
Iphone sdk sample AVCam to drive the following error has occurred.

warning: Unable to read symbols for /Library/MobileSubstrate/MobileSubstrate.dylib (file not found).
warning: Unable to read symbols for /Library/Frameworks/CydiaSubstrate.framework/Libraries/SubstrateLoader.dylib (file not found).
2011-05-17 14:12:15.927 AVCam[225:607] MS:Notice: Installing: com.224ok.movieplayer [AVCam] (550.58)
2011-05-17 14:12:15.973 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/3GMy3G.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/3GMy3G.dylib (file not found).
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.2 (8H7)/Symbols/usr/lib/libcrypto.0.9.8.dylib (file not found).
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.2 (8H7)/Symbols/usr/lib/libsubstrate.dylib (file not found).
2011-05-17 14:12:16.393 AVCam[225:607] My3G waiting for User Prompt in com.224ok.movieplayer  v4.8..
2011-05-17 14:12:16.408 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/Activator.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/Activator.dylib (file not found).
2011-05-17 14:12:16.823 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/AskToCall.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/AskToCall.dylib (file not found).
MS:Warning: nil class argument
MS:Warning: nil class argument
2011-05-17 14:12:17.084 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/Backgrounder.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/Backgrounder.dylib (file not found).
2011-05-17 14:12:17.300 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/KeyboardFix.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/KeyboardFix.dylib (file not found).
2011-05-17 14:12:17.486 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/Springtomize.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/Springtomize.dylib (file not found).
MS:Warning: nil class argument
/* last message repeated many times */
MS:Warning: nil class argument
2011-05-17 14:12:17.711 AVCam[225:607] [Springtomize]: factor: 0.500000
2011-05-17 14:12:17.716 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/SwipeToMoveCursor.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/SwipeToMoveCursor.dylib (file not found).
MS:Warning: nil class argument
2011-05-17 14:12:17.872 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/WinterBoard.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/WinterBoard.dylib (file not found).
2011-05-17 14:12:18.064 AVCam[225:607] WB:Notice: WinterBoard
MS:Warning: message not found [UIImage defaultDesktopImage]
2011-05-17 14:12:18.104 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/biteSBarClient.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/biteSBarClient.dylib (file not found).
2011-05-17 14:12:18.328 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/libstatusbar.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/libstatusbar.dylib (file not found).
2011-05-17 14:12:18.532 AVCam[225:607] MS:Notice: Loading: /Library/MobileSubstrate/DynamicLibraries/sandcastleclient.dylib
warning: Unable to read symbols for /Library/MobileSubstrate/DynamicLibraries/sandcastleclient.dylib (file not found).
Current language:  auto; currently objective-c
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.2 (8H7)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found).
(gdb) continue
Program received signal:  “SIGUSR1”.
warning: Remote failure reply: E37
(gdb) continue

I mean why run without modification?


问:
I have a vector that has pointers to elements from 2 subtypes accessed via an interface. Can't seem to re-arrange the vector
I'm working on a really over engineered matrix calculator for school and hit a brick wall with the very last function I need. The full version of the transpose() is supposed to re-arrange my matrix and to switch columns and rows around.

I posted this question earlier with a snippet but was asked to write a minimum reproducable sample. This isn't very "minimum" but I tried.

So. I have a std::vector<std::unique_ptr<Interface>> that can hold objects of types Sub1 and Sub2.

In the full version I have a class that bypasses Interface and works fine since it only holds Sub2 objects.

However I can't seem to get it to work when there are multiple types in the vector. Nothing I've tried in the past few hours has done anything.

```<code>#include <iostream>
#include "main.h"
#include <memory>
#include <utility>
#include <vector>
#include <sstream>

//this is the one that won't work
Super Super::transpose() const {
    Super newMatrix = *this;
    int i = 1;
    for(auto& elem : elements){
        *elem = *newMatrix.elements[i];
        i--;
    }
return *this;
}

int main() {
    std::vector<std::unique_ptr<Interface>> newMatrix;
    newMatrix.push_back(std::unique_ptr<Sub1>(new Sub1('x')));
    newMatrix.push_back(std::unique_ptr<Sub2>(new Sub2(1)));
    Super mtx(std::move(newMatrix),2 );
    std::cout << mtx << std::endl;
    mtx.transpose();
    std::cout << mtx;
    return 0;
}

//busywork from here on
Super::Super(std::vector<std::unique_ptr<Interface>> matrix, int pN){
    elements = std::move(matrix);
    n = pN;
}

std::unique_ptr<Interface> Sub1::clone() const {
    char newVal = val;
    return std::unique_ptr<Sub1>(new Sub1(newVal));
}

std::unique_ptr<Interface> Sub2::clone() const {
    int newVal = i;
    return std::unique_ptr<Sub2>(new Sub2(newVal));
}

Sub1::Sub1(char pVal) {
    val = pVal;
}

Sub2::Sub2(int pI) {
    i = pI;
}

std::string Sub1::toString() const {
    std::stringstream ss;
    ss << val;
    return ss.str();
}

std::string Sub2::toString() const {
    std::stringstream ss;
    ss << i;
    return ss.str();
}

std::ostream &operator<<(std::ostream &os, const Super &matrix) {
    os << "[";
    int i = 0;
    for (auto &elem : matrix.elements) {
        os << elem->toString();
        if (i < matrix.n - 1) {
            os << ",";
        }
        i++;
    }
    os << "]";
    return os;
}

Super::Super(const Super &matrix) {
    n = matrix.n;
    for (auto &elem : matrix.elements) {
        std::unique_ptr<Interface> newElem = elem->clone();
        elements.push_back(std::move(newElem));
    }
}
</code>```

And heres the header

```<code>#ifndef EXAMPLE_MAIN_H
#define EXAMPLE_MAIN_H

#include <memory>
#include <vector>

class Interface{
public:
    virtual ~Interface() = default;
    virtual std::unique_ptr<Interface> clone() const = 0;
    virtual std::string toString() const = 0;
};

class Super{
private:
    std::vector<std::unique_ptr<Interface>> elements;
    int n = 2;
public:
    Super(std::vector<std::unique_ptr<Interface>> elements, int n);
    Super(const Super &matrix);
    Super transpose() const;
    friend std::ostream &operator<<(std::ostream &os, const Super &matrix);
};

class Sub1: public Interface{
private:
    char val;
public:
    Sub1(char pVal);
    std::string toString() const override;
    std::unique_ptr<Interface> clone() const override;
};

class Sub2: public Interface{
private:
    int i;
public:
    Sub2(int pI);
    std::string toString() const override;
    std::unique_ptr<Interface> clone() const override;
};

std::ostream &operator<<(std::ostream &os, const Super &matrix);

#endif //EXAMPLE_MAIN_H
</code>```

答:
Your Interface has no virtual assignment operator, so naturally *elem = newMatrix.elements[i]; will not work. I think elem = std::move(newMatrix.elements[i])); should do what you want.

Edit: Sorry, Interface will have a assignment operator, since that will be default created. But it won't be virtual, so the assignment on Interface will do pretty much nothing, since it doesn't call the assignment operators for the child classes. You could write those all, but it seems not really worth the effort.

Body:
I'm working on a really over engineered matrix calculator for school and hit a brick wall with the very last function I need. The full version of the transpose() is supposed to re-arrange my matrix and to switch columns and rows around.

I posted this question earlier with a snippet but was asked to write a minimum reproducable sample. This isn't very "minimum" but I tried.

So. I have a std::vector<std::unique_ptr<Interface>> that can hold objects of types Sub1 and Sub2.

In the full version I have a class that bypasses Interface and works fine since it only holds Sub2 objects.

However I can't seem to get it to work when there are multiple types in the vector. Nothing I've tried in the past few hours has done anything.

#include <iostream>
#include "main.h"
#include <memory>
#include <utility>
#include <vector>
#include <sstream>

//this is the one that won't work
Super Super::transpose() const {
    Super newMatrix = *this;
    int i = 1;
    for(auto& elem : elements){
        *elem = *newMatrix.elements[i];
        i--;
    }
return *this;
}

int main() {
    std::vector<std::unique_ptr<Interface>> newMatrix;
    newMatrix.push_back(std::unique_ptr<Sub1>(new Sub1('x')));
    newMatrix.push_back(std::unique_ptr<Sub2>(new Sub2(1)));
    Super mtx(std::move(newMatrix),2 );
    std::cout << mtx << std::endl;
    mtx.transpose();
    std::cout << mtx;
    return 0;
}

//busywork from here on
Super::Super(std::vector<std::unique_ptr<Interface>> matrix, int pN){
    elements = std::move(matrix);
    n = pN;
}

std::unique_ptr<Interface> Sub1::clone() const {
    char newVal = val;
    return std::unique_ptr<Sub1>(new Sub1(newVal));
}

std::unique_ptr<Interface> Sub2::clone() const {
    int newVal = i;
    return std::unique_ptr<Sub2>(new Sub2(newVal));
}

Sub1::Sub1(char pVal) {
    val = pVal;
}

Sub2::Sub2(int pI) {
    i = pI;
}

std::string Sub1::toString() const {
    std::stringstream ss;
    ss << val;
    return ss.str();
}

std::string Sub2::toString() const {
    std::stringstream ss;
    ss << i;
    return ss.str();
}

std::ostream &operator<<(std::ostream &os, const Super &matrix) {
    os << "[";
    int i = 0;
    for (auto &elem : matrix.elements) {
        os << elem->toString();
        if (i < matrix.n - 1) {
            os << ",";
        }
        i++;
    }
    os << "]";
    return os;
}

Super::Super(const Super &matrix) {
    n = matrix.n;
    for (auto &elem : matrix.elements) {
        std::unique_ptr<Interface> newElem = elem->clone();
        elements.push_back(std::move(newElem));
    }
}

And heres the header

#ifndef EXAMPLE_MAIN_H
#define EXAMPLE_MAIN_H

#include <memory>
#include <vector>

class Interface{
public:
    virtual ~Interface() = default;
    virtual std::unique_ptr<Interface> clone() const = 0;
    virtual std::string toString() const = 0;
};

class Super{
private:
    std::vector<std::unique_ptr<Interface>> elements;
    int n = 2;
public:
    Super(std::vector<std::unique_ptr<Interface>> elements, int n);
    Super(const Super &matrix);
    Super transpose() const;
    friend std::ostream &operator<<(std::ostream &os, const Super &matrix);
};

class Sub1: public Interface{
private:
    char val;
public:
    Sub1(char pVal);
    std::string toString() const override;
    std::unique_ptr<Interface> clone() const override;
};

class Sub2: public Interface{
private:
    int i;
public:
    Sub2(int pI);
    std::string toString() const override;
    std::unique_ptr<Interface> clone() const override;
};

std::ostream &operator<<(std::ostream &os, const Super &matrix);

#endif //EXAMPLE_MAIN_H


问:
Coding data and changing the column names in another columns using codes in R and tidyverse
below, I have demonstrated part of my  data:

```<code>df<-read.table(text=" K G   M
12  2345    Gholi
KAM 2345    KAM
Noghl   1990    KAM
Zae 1990    441
12  2345    441
KAM 1990    12
Noghl   1800    12"

,header=TRUE)
</code>```

I would like to make codes for  K, G and M and starting with 1. We have 4 groups in K, so 1,2,3 and 4. for G, start with 5, so 5, 6 and 7 as we have three subgroups.

Using the following codes, I will get the following table:

```<code>df = lapply(df, function(x) as.integer(as.factor(x)))
data.frame(Map("+", df, cumsum(c(0, head(sapply(df, max), -1)))))
</code>```

I will get the following table:

```<code>KM  KN  KZ
1   7   10
2   7   11
3   6   11
4   6   9
1   7   9
2   6   8
3   5   8
</code>```

Now I want to get the following table:

Group C
K,M 1,8
K,M 2,11
K 3
K 4
G 7
G 6
M 10
M 9```

For example, in Group, Column K (12), M (12,12) goes to Codes 1 and 8, as they coded in KM and KZ and so

答:
After converting all the columns to integer values based on factor route, and adding the max value of previous columns to the current, we pivot to 'long' format with pivot_longer, bind with the original column values reshaped to 'long' format,  grouped by the original value column 'origval', paste the unique elements of other columns

```<code>library(dplyr)
library(tidyr)
df %>%
      mutate_all(~ as.integer(factor(.))) %>%
      mutate(G = max(K) + G, M = max(G) + M) %>%
      pivot_longer(everything()) %>%
      bind_cols(df %>%
                  mutate_all(as.character) %>%
                  pivot_longer(everything(),values_to = 'origvalue') %>%
                  dplyr::select(-name)) %>%
     group_by(origvalue) %>%
     summarise_at(vars(-group_cols()), ~toString(unique(.))) %>%
     dplyr::select(Group = name, C = value)
# A tibble: 9 x 2
#   Group C
#  <chr> <chr>
#1 K, M  1, 8
#2 G     5
#3 G     6
#4 G     7
#5 M     9
#6 M     10
#7 K, M  2, 11
#8 K     3
#9 K     4
</code>```

data

```<code>df <- structure(list(K = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L), .Label = c("12",
"KAM", "Noghl", "Zae"), class = "factor"), G = c(2345L, 2345L,
1990L, 1990L, 2345L, 1990L, 1800L), M = structure(c(3L, 4L, 4L,
2L, 2L, 1L, 1L), .Label = c("12", "441", "Gholi", "KAM"),
class = "factor")), class = "data.frame", row.names = c(NA,
-7L))
</code>```

Body:
below, I have demonstrated part of my  data:

df<-read.table(text=" K G   M
12  2345    Gholi
KAM 2345    KAM
Noghl   1990    KAM
Zae 1990    441
12  2345    441
KAM 1990    12
Noghl   1800    12"

,header=TRUE)

I would like to make codes for  K, G and M and starting with 1. We have 4 groups in K, so 1,2,3 and 4. for G, start with 5, so 5, 6 and 7 as we have three subgroups.

Using the following codes, I will get the following table:

df = lapply(df, function(x) as.integer(as.factor(x)))
data.frame(Map("+", df, cumsum(c(0, head(sapply(df, max), -1)))))

I will get the following table:

KM  KN  KZ
1   7   10
2   7   11
3   6   11
4   6   9
1   7   9
2   6   8
3   5   8

Now I want to get the following table:

Group C
K,M 1,8
K,M 2,11
K 3
K 4
G 7
G 6
M 10
M 9

For example, in Group, Column K (12), M (12,12) goes to Codes 1 and 8, as they coded in KM and KZ and so

Body:
After converting all the columns to integer values based on factor route, and adding the max value of previous columns to the current, we pivot to 'long' format with pivot_longer, bind with the original column values reshaped to 'long' format,  grouped by the original value column 'origval', paste the unique elements of other columns

library(dplyr)
library(tidyr)
df %>%
      mutate_all(~ as.integer(factor(.))) %>%
      mutate(G = max(K) + G, M = max(G) + M) %>%
      pivot_longer(everything()) %>%
      bind_cols(df %>%
                  mutate_all(as.character) %>%
                  pivot_longer(everything(),values_to = 'origvalue') %>%
                  dplyr::select(-name)) %>%
     group_by(origvalue) %>%
     summarise_at(vars(-group_cols()), ~toString(unique(.))) %>%
     dplyr::select(Group = name, C = value)
# A tibble: 9 x 2
#   Group C
#  <chr> <chr>
#1 K, M  1, 8
#2 G     5
#3 G     6
#4 G     7
#5 M     9
#6 M     10
#7 K, M  2, 11
#8 K     3
#9 K     4

data

df <- structure(list(K = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L), .Label = c("12",
"KAM", "Noghl", "Zae"), class = "factor"), G = c(2345L, 2345L,
1990L, 1990L, 2345L, 1990L, 1800L), M = structure(c(3L, 4L, 4L,
2L, 2L, 1L, 1L), .Label = c("12", "441", "Gholi", "KAM"),
class = "factor")), class = "data.frame", row.names = c(NA,
-7L))


问:
wtforms submitting wrong form
I'm making a web-app in Flask and on a page I have a few forms, when I click the submit button for one form (the one called 'UsedBatch'), it ends up submitting it as if it's the other form (the one called 'NewBatch') and I can't see why. The form definitions are shown below:

```<code>class NewBatch(FlaskForm):
    quantity = IntegerField('Number of items:', validators=[DataRequired()])
    date = DateField('Date:', default = date.today(), validators=[DataRequired()])
    submit = SubmitField('Submit')

class UsedBatch(FlaskForm):
    quantity = IntegerField('Number of items used:', validators=[DataRequired()])
    date = DateField('Date:', default = date.today(), validators=[DataRequired()])
    used_by = StringField('Used by:')
    submit = SubmitField('Submit')
</code>```

Before they're run through the template, some attributes of the forms are added and then they are defined as shown:

```<code>for items in items_list:
    setattr(NewBatch, 'item_no', IntegerField(default = items.item_no))
    setattr(UsedBatch, 'item_no', IntegerField(default = items.item_no))
    processed_items_list.append({'item_no':items.item_no, 'quantity':items.quantity, 'items':items.items, 'batch_form':NewBatch(), 'used_form':UsedBatch()})
used_form = UsedBatch()
batch_form = NewBatch()
</code>```

And lastly, the code for the forms in the template is shown below, I iterate through a list (the 'processesd_items_list' shown above_ where each element in the list has an attached form, the iterable in this case is called items. the first form (the UsedBatch) is:

```<code><form method="POST">
    {{ items['used_form'].date.label }}{{ items['used_form'].date(class="uk-input") }}
    {{ items['used_form'].quantity.label }}{{ items['used_form'].quantity(class="uk-input") }}
    {{ items['used_form'].used_by.label }}{{ items['used_form'].used_by(class="uk-input") }}
    {{ items['used_form'].hidden_tag.label }}{{ items['used_form'].hidden_tag() }}
    {{ items['used_form'].submit() }}
</form>
</code>```

and the second form (the NewBatch) is:

```<code><form method="POST">
    {{ items['batch_form'].date.label }}{{ items['batch_form'].date(class="uk-input") }}
    {{ items['batch_form'].quantity.label }}{{ items['batch_form'].quantity(class="uk-input") }}
    {{ items['batch_form'].hidden_tag.label }}{{ items['batch_form'].hidden_tag() }}
    {{ items['batch_form'].submit() }}
</form>
</code>```

Can anyone see why it would submit NewBatch over UsedBatch? When I just add the lines:

```<code>if batch_form.validate_on_submit():
    print('Batch submitted')
if used_form.validate_on_submit():
    print('Usage submitted')
</code>```

It returns "Batch submitted" instead of "Usage submitted" when the UsedBatch form is submitted. Can anyone help point out why? Thanks!

答:
Adding a filter on your POST route should fix it, try the following:

```<code>if batch_form.submit.data and batch_form.validate(): # notice the order
    print('Batch submitted')
if used_form.submit.data and used_form.validate(): # notice the order
    print('Usage submitted')
</code>```

When you call form.validate_on_submit(), it checks if form is submitted by the HTTP method no matter which submit button was clicked. So the little trick above is just add a filter (to check if submit has data, i.e., batch_form.submit.data).

ref: Multiple forms in a single page using flask and WTForms

Title: wtforms submitting wrong form

Body:
I'm making a web-app in Flask and on a page I have a few forms, when I click the submit button for one form (the one called 'UsedBatch'), it ends up submitting it as if it's the other form (the one called 'NewBatch') and I can't see why. The form definitions are shown below:

class NewBatch(FlaskForm):
    quantity = IntegerField('Number of items:', validators=[DataRequired()])
    date = DateField('Date:', default = date.today(), validators=[DataRequired()])
    submit = SubmitField('Submit')

class UsedBatch(FlaskForm):
    quantity = IntegerField('Number of items used:', validators=[DataRequired()])
    date = DateField('Date:', default = date.today(), validators=[DataRequired()])
    used_by = StringField('Used by:')
    submit = SubmitField('Submit')

Before they're run through the template, some attributes of the forms are added and then they are defined as shown:

for items in items_list:
    setattr(NewBatch, 'item_no', IntegerField(default = items.item_no))
    setattr(UsedBatch, 'item_no', IntegerField(default = items.item_no))
    processed_items_list.append({'item_no':items.item_no, 'quantity':items.quantity, 'items':items.items, 'batch_form':NewBatch(), 'used_form':UsedBatch()})
used_form = UsedBatch()
batch_form = NewBatch()

And lastly, the code for the forms in the template is shown below, I iterate through a list (the 'processesd_items_list' shown above_ where each element in the list has an attached form, the iterable in this case is called items. the first form (the UsedBatch) is:

<form method="POST">
    {{ items['used_form'].date.label }}{{ items['used_form'].date(class="uk-input") }}
    {{ items['used_form'].quantity.label }}{{ items['used_form'].quantity(class="uk-input") }}
    {{ items['used_form'].used_by.label }}{{ items['used_form'].used_by(class="uk-input") }}
    {{ items['used_form'].hidden_tag.label }}{{ items['used_form'].hidden_tag() }}
    {{ items['used_form'].submit() }}
</form>

and the second form (the NewBatch) is:

<form method="POST">
    {{ items['batch_form'].date.label }}{{ items['batch_form'].date(class="uk-input") }}
    {{ items['batch_form'].quantity.label }}{{ items['batch_form'].quantity(class="uk-input") }}
    {{ items['batch_form'].hidden_tag.label }}{{ items['batch_form'].hidden_tag() }}
    {{ items['batch_form'].submit() }}
</form>

Can anyone see why it would submit NewBatch over UsedBatch? When I just add the lines:

if batch_form.validate_on_submit():
    print('Batch submitted')
if used_form.validate_on_submit():
    print('Usage submitted')

It returns "Batch submitted" instead of "Usage submitted" when the UsedBatch form is submitted. Can anyone help point out why? Thanks!

Body:
Adding a filter on your POST route should fix it, try the following:

if batch_form.submit.data and batch_form.validate(): # notice the order
    print('Batch submitted')
if used_form.submit.data and used_form.validate(): # notice the order
    print('Usage submitted')

When you call form.validate_on_submit(), it checks if form is submitted by the HTTP method no matter which submit button was clicked. So the little trick above is just add a filter (to check if submit has data, i.e., batch_form.submit.data).

ref: Multiple forms in a single page using flask and WTForms


问:
Display seaborn plots at some point later in code
Let's say at some point in my code, I have following two graphs: i.e. graph_p_changes and graph_p_contrib

```<code>line_grapgh_p_changes = df_p_change[['year','interest accrued', 'trade debts', 'other financial assets']].melt('year', var_name='variables',  value_name='p_changes')
graph_p_changes = sns.factorplot(x="year", y="p_changes", hue='variables', data=line_grapgh_p_changes, height=5, aspect=2)
graph_p_changes.set(xlabel='year', ylabel='percentage change in self value across the years')

line_grapgh_p_contrib = df_p_contrib[['year','interest accrued', 'trade debts', 'other financial assets']].melt('year', var_name='variables',  value_name='p_changes')
graph_p_contrib = sns.factorplot(x="year", y="p_changes", hue='variables', data=line_grapgh_p_contrib, height=5, aspect=2)
graph_p_contrib.set(xlabel='year', ylabel='percentage chnage in contribution to total value')
</code>```

Now at some point later in my code, I just want to display one of the above two graphs. But when I do plt.show(), it displays both of the above graphs in my jupyter notebook. How can I display only one graph at any point in my code.

答:
You'll want to refer to the assigned variable for each plot and then add .fig after that to redisplay it in a Jupyter notebook cell.

Specifically, in your case you'd reference graph_p_changes.fig or graph_p_contrib.fig in a cell and execute that cell to see an individual plot again.

This is similar to how you can show Seaborn's ClusterGrids again, see here. Because the title of your question said 'seaborn plots', I'll add for sake of completeness, this doesn't hold for plots like Seaborn's line plot (lineplot) or  bar plot (barplot) , that produce AxesSubplot objects. There you use .figure, for example ax.figure to recall most of the examples listed on Seaborn's lineplot documentation. (The suggestion of ax.figure assumes you added assigning the plot to a variable named ax, for example using code like ax = sns.lineplot(....)

Example catplots with code

This is using example code from here and seaborn's catplot documentation (see below) to make two plots. If this code was in one cell and then that cell was run, you'd see two plots in the output below it.

import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

titanic = sns.load_dataset("titanic")
exercise = sns.load_dataset("exercise")
g = sns.catplot("alive", col="deck",
                col_wrap=3, data=titanic[titanic.deck.notnull()],
                kind="count", height=2.5, aspect=.8)

another_plot = sns.catplot(x="time", y="pulse", hue="kind", data=exercise)
```

Later, each can be displayed again individually as output of other cells with g.fig or another_plot.fig, depending on which plot you want to show.

Additionaly, I'll suggest to improve your long-term code viability, you may want to move on to using catplot in your plotting calls as that is what factorplot is now called in seaborn. See here where it says "factorplot still exists and will pass its arguments through to catplot() with a warning. It may be removed eventually, but the transition will be as gradual as possible."

UPDATE:

OP commented that what was desired was code allowing interspersed stdout/stderr output with plots at precise points among that stream and not just at the end.

For some reason, Seaborn plots (even simple line plots) don't seem to get 'captured' correctly with io.capture_output(), and so I had to use the %%capture cell magic command in the producing cell and combine the output in a separate cell. However, Plotly plots I tried based on example code are captured by io.capture_output() and allow facile intermixing all in the same cell. This is all illustrated in an example notebook available here; it is best viewed in static form here at nbviewer because nbviewer renders the Plotly plots while GitHub doesn't. The top of that notebook includes a link where you can launch an active Jupyter session where it will run.

Update related to this UPDATE:

In an insightful answer to 'seaborn stop figure from being visualized', ffrosch suggests you "can temporarily disable/enable the inline creation with plt.ioff() and plt.ion()." This may offer yet another way to fine-tune when Seabor plots show among the output and/or offer another way to constrain ouput since %%capture cell magic worked yet io.capture_output() did not. (I have yet to try this.)

Body:
Let's say at some point in my code, I have following two graphs: i.e. graph_p_changes and graph_p_contrib

line_grapgh_p_changes = df_p_change[['year','interest accrued', 'trade debts', 'other financial assets']].melt('year', var_name='variables',  value_name='p_changes')
graph_p_changes = sns.factorplot(x="year", y="p_changes", hue='variables', data=line_grapgh_p_changes, height=5, aspect=2)
graph_p_changes.set(xlabel='year', ylabel='percentage change in self value across the years')

line_grapgh_p_contrib = df_p_contrib[['year','interest accrued', 'trade debts', 'other financial assets']].melt('year', var_name='variables',  value_name='p_changes')
graph_p_contrib = sns.factorplot(x="year", y="p_changes", hue='variables', data=line_grapgh_p_contrib, height=5, aspect=2)
graph_p_contrib.set(xlabel='year', ylabel='percentage chnage in contribution to total value')

Now at some point later in my code, I just want to display one of the above two graphs. But when I do plt.show(), it displays both of the above graphs in my jupyter notebook. How can I display only one graph at any point in my code.

Body:
You'll want to refer to the assigned variable for each plot and then add .fig after that to redisplay it in a Jupyter notebook cell.

Specifically, in your case you'd reference graph_p_changes.fig or graph_p_contrib.fig in a cell and execute that cell to see an individual plot again.

This is similar to how you can show Seaborn's ClusterGrids again, see here. Because the title of your question said 'seaborn plots', I'll add for sake of completeness, this doesn't hold for plots like Seaborn's line plot (lineplot) or  bar plot (barplot) , that produce AxesSubplot objects. There you use .figure, for example ax.figure to recall most of the examples listed on Seaborn's lineplot documentation. (The suggestion of ax.figure assumes you added assigning the plot to a variable named ax, for example using code like ax = sns.lineplot(....)

Example catplots with code

This is using example code from here and seaborn's catplot documentation (see below) to make two plots. If this code was in one cell and then that cell was run, you'd see two plots in the output below it.

import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

titanic = sns.load_dataset("titanic")
exercise = sns.load_dataset("exercise")
g = sns.catplot("alive", col="deck",
                col_wrap=3, data=titanic[titanic.deck.notnull()],
                kind="count", height=2.5, aspect=.8)

another_plot = sns.catplot(x="time", y="pulse", hue="kind", data=exercise)

Later, each can be displayed again individually as output of other cells with g.fig or another_plot.fig, depending on which plot you want to show.

Additionaly, I'll suggest to improve your long-term code viability, you may want to move on to using catplot in your plotting calls as that is what factorplot is now called in seaborn. See here where it says "factorplot still exists and will pass its arguments through to catplot() with a warning. It may be removed eventually, but the transition will be as gradual as possible."

UPDATE:

OP commented that what was desired was code allowing interspersed stdout/stderr output with plots at precise points among that stream and not just at the end.

For some reason, Seaborn plots (even simple line plots) don't seem to get 'captured' correctly with io.capture_output(), and so I had to use the %%capture cell magic command in the producing cell and combine the output in a separate cell. However, Plotly plots I tried based on example code are captured by io.capture_output() and allow facile intermixing all in the same cell. This is all illustrated in an example notebook available here; it is best viewed in static form here at nbviewer because nbviewer renders the Plotly plots while GitHub doesn't. The top of that notebook includes a link where you can launch an active Jupyter session where it will run.

Update related to this UPDATE:

In an insightful answer to 'seaborn stop figure from being visualized', ffrosch suggests you "can temporarily disable/enable the inline creation with plt.ioff() and plt.ion()." This may offer yet another way to fine-tune when Seabor plots show among the output and/or offer another way to constrain ouput since %%capture cell magic worked yet io.capture_output() did not. (I have yet to try this.)


问:
How to call a function from another class React-native
I am trying to call a function from another class it throws an error getValue is not a function. i dont want to use static. I hope  there's a solution for it. here's my code</p>

```<code>import React, { Component } from "react";
import SecondClass from "./main"

export default class A extends Component{
  constructor (props) {
    super(props)

 onPress = ()=>{
   getValue()

 }
}

//SecondClass
export default class SecondClass extends Component{
  constructor (props) {
    super(props)
  }
  getValues = () => {
    alert("Hello")
  }
}
</code>```

答:
You cannot expect that you can simply call some function in another class because you imported that class. The React way of doing this would be to pass the function as a prop if these are parent-child components. If not, I would highly recommend extracting the common function out from both classes and call them separately.

From the comments, other users have also recommended using static function if you absolutely want to couple the function to Second class.

My main objective is when user press the button then it should call the method from another class and return Hello. Then later i want to set some properties which i not possible in static function. So thats why i dont want to use static function

From your sample code it looks like Second is a React component ? If this class was made to encapsulate certain behavior then I would recommend turning it into a plain javascript class and then instantiate/use wherever necessary.

Body:
I am trying to call a function from another class it throws an error getValue is not a function. i dont want to use static. I hope  there's a solution for it. here's my code

import React, { Component } from "react";
import SecondClass from "./main"

export default class A extends Component{
  constructor (props) {
    super(props)

 onPress = ()=>{
   getValue()

 }
}

//SecondClass
export default class SecondClass extends Component{
  constructor (props) {
    super(props)
  }
  getValues = () => {
    alert("Hello")
  }
}


问:
Powershell using windows API to drag drop mouse
I have code that is supposed to do a drag and drop with powershell that I don't understand why it's not working the way I'm hoping for it to work. Details below:

```<code>function Mouse-signature-import(){
    $global:signature=@'
      [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
      public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
'@

    $global:SendMouseClick = Add-Type -memberDefinition $global:signature -name "Win32MouseEventNew" -namespace Win32Functions -passThru
}

function Mouse-Drag($from1,$from2,$to1,$to2){
    Mouse-signature-import
    [System.Windows.Forms.Cursor]::Position = "$from1,$from2"
    $global:SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
    $global:SendMouseClick::mouse_event(0x80000000, 0, 0, 0, 0); Dont know if I need this because drag is not working in all apps
    [System.Windows.Forms.Cursor]::Position = "$to1,$to2"
    $global:SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
    write-host -f yellow -b black "Mouse-Drag" -nonewline; write-host -f Gray " from " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$from1 $from2" -nonewline;write-host -f Magenta "]" -nonewline; write-host -f Gray " to " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$to1 $to2" -nonewline; write-host -f Magenta "]";
}
</code>```

I see the mouse moving and the dragging occurs, I'm using this to select text however. On Mouse-Up, the text becomes no longer highlighted. I need to adjust this code to prevent the mouse-up from unselecting the text I have highlighted in the drag motion. Ideally I will be using sendkeys after this function to do a "^c" to copy most of the time I use this function.

I added this line thinking it would help.

$global:SendMouseClick::mouse_event(0x80000000, 0, 0, 0, 0);

=====================
SOLUTION:

It was the timing as DK suggested. I just addded a sleep before the mouse-up event.

function Mouse-Drag($from1,$from2,$to1,$to2){
    $global:silentMouseFunctions = $true
    Mouse-signature-import

```<code>[System.Windows.Forms.Cursor]::Position = "$from1,$from2"
$global:SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
[System.Windows.Forms.Cursor]::Position = "$to1,$to2"
start-sleep -s 1 # If we do not sleep, then the drag does not work right.
$global:SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);

$global:silentMouseFunctions = $false
write-host -f yellow -b black "Mouse-Drag" -nonewline; write-host -f Gray " from " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$from1 $from2" -nonewline;write-host -f Magenta "]" -nonewline; write-host -f Gray " to " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$to1 $to2" -nonewline; write-host -f Magenta "]";
</code>```

答:
After spending some time to debug the code, it seems that we need to slowly move the cursor for drag-and-drop to work correctly.

Below code is tested for several times for moving an icon on the desktop, it worked just fine on my PC:

```<code>Add-Type @"
    using System;
    using System.Runtime.InteropServices;

    public static class Win32
    {
        [DllImport("user32.dll")]
        static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, int dwExtraInfo);

        [DllImport("user32.dll")]
        public static extern bool SetCursorPos(int x, int y);
    }
"@;

[Win32]::SetCursorPos(25, 25);

[Win32]::mouse_event(0x0002, 0, 0, 0, 0);

for ($i = 0; $i -lt 1000; $i+=100)
{
    [Win32]::SetCursorPos($i, $i);
    Start-Sleep -m 25
}

[Win32]::mouse_event(0x0004, 0, 0, 0, 0);
</code>```

Body:
I have code that is supposed to do a drag and drop with powershell that I don't understand why it's not working the way I'm hoping for it to work. Details below:

function Mouse-signature-import(){
    $global:signature=@'
      [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
      public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
'@

    $global:SendMouseClick = Add-Type -memberDefinition $global:signature -name "Win32MouseEventNew" -namespace Win32Functions -passThru
}

function Mouse-Drag($from1,$from2,$to1,$to2){
    Mouse-signature-import
    [System.Windows.Forms.Cursor]::Position = "$from1,$from2"
    $global:SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
    $global:SendMouseClick::mouse_event(0x80000000, 0, 0, 0, 0); Dont know if I need this because drag is not working in all apps
    [System.Windows.Forms.Cursor]::Position = "$to1,$to2"
    $global:SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
    write-host -f yellow -b black "Mouse-Drag" -nonewline; write-host -f Gray " from " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$from1 $from2" -nonewline;write-host -f Magenta "]" -nonewline; write-host -f Gray " to " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$to1 $to2" -nonewline; write-host -f Magenta "]";
}

I see the mouse moving and the dragging occurs, I'm using this to select text however. On Mouse-Up, the text becomes no longer highlighted. I need to adjust this code to prevent the mouse-up from unselecting the text I have highlighted in the drag motion. Ideally I will be using sendkeys after this function to do a "^c" to copy most of the time I use this function.

I added this line thinking it would help.

$global:SendMouseClick::mouse_event(0x80000000, 0, 0, 0, 0);

=====================
SOLUTION:

It was the timing as DK suggested. I just addded a sleep before the mouse-up event.

function Mouse-Drag($from1,$from2,$to1,$to2){
    $global:silentMouseFunctions = $true
    Mouse-signature-import

[System.Windows.Forms.Cursor]::Position = "$from1,$from2"
$global:SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
[System.Windows.Forms.Cursor]::Position = "$to1,$to2"
start-sleep -s 1 # If we do not sleep, then the drag does not work right.
$global:SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);

$global:silentMouseFunctions = $false
write-host -f yellow -b black "Mouse-Drag" -nonewline; write-host -f Gray " from " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$from1 $from2" -nonewline;write-host -f Magenta "]" -nonewline; write-host -f Gray " to " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$to1 $to2" -nonewline; write-host -f Magenta "]";

Body:
After spending some time to debug the code, it seems that we need to slowly move the cursor for drag-and-drop to work correctly.

Below code is tested for several times for moving an icon on the desktop, it worked just fine on my PC:

Add-Type @"
    using System;
    using System.Runtime.InteropServices;

    public static class Win32
    {
        [DllImport("user32.dll")]
        static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, int dwExtraInfo);

        [DllImport("user32.dll")]
        public static extern bool SetCursorPos(int x, int y);
    }
"@;

[Win32]::SetCursorPos(25, 25);

[Win32]::mouse_event(0x0002, 0, 0, 0, 0);

for ($i = 0; $i -lt 1000; $i+=100)
{
    [Win32]::SetCursorPos($i, $i);
    Start-Sleep -m 25
}

[Win32]::mouse_event(0x0004, 0, 0, 0, 0);