问:
Setting up Traefik with Cloudflare
I am trying to setup traefik using a combination of this guide, and the code found here.

I am using docker-compose with Unraid, so far I have the following code:

traefik.toml:

```<code>debug = false

logLevel = "ERROR"
defaultEntryPoints = ["https","http"]

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
    entryPoint = "https"
  [entryPoints.https]
  address = ":443"
  [entryPoints.https.tls]

[retry]

[acme]
email = "user@domain.com"
storage = "acme.json"
entryPoint = "https"
#OnHostRule = true
#onDemand = true
[acme.dnsChallenge]
  provider = "cloudflare"
[[acme.domains]]
   main = "domain.name"
[[acme.domains]]
   main = "*.domain.name"
</code>```

docker-compose.yml:

```<code>services:

  traefik:
    image: traefik:latest
    command: --web --docker --docker.watch --docker.domain=${DOMAIN} \
             --docker.exposedbydefault=false --acme.domains=${DOMAIN}
    container_name: traefik
    hostname: traefik
    networks:
      br0:
        ipv4_address: 192.168.1.253
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ${CONFIG}/traefik/acme.json:/acme.json
      - ${CONFIG}/traefik/traefik.toml:/etc/traefik/traefik.toml
      - ${CONFIG}/traefik/.htpasswd:/etc/traefik/.htpasswd:ro
    environment:
      - CF_API_EMAIL=user@domain.com
      - CF_API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXX
    labels:
      traefik.enable: "true"
      traefik.frontend.rule: "Host:monitor.${DOMAIN}"
      traefik.port: "8080"
      traefik.frontend.auth.basic: "${HTPASSWD}"
      com.ouroboros.enable: "true"
    restart: unless-stopped

  ouroboros:
    image: pyouroboros/ouroboros
    container_name: ouroboros
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - PGID
      - PUID
      - TZ
      - CLEANUP=true
      - INTERVAL=86400  # 24hrs
      - SELF_UPDATE=true
      - LABELS_ONLY=true
    restart: unless-stopped

  plex:
    image: linuxserver/plex
    container_name: plex
    hostname: plex
    networks:
      br0:
        ipv4_address: 192.168.1.252
    volumes:
      - ${CONFIG}/plex:/config
      - ${DATA}/TV:/media/tv
      - ${DATA}/Movies:/media/movies
      - ${DATA}/Music:/media/music
      - ${DATA}/Anime:/media/anime
    environment:
      - PGID
      - PUID
      - TZ
      - VERSION=latest
    labels:
      traefik.enable: "true"
      traefik.port: "32400"
      traefik.frontend.rule: "Host:plex.${DOMAIN}"
      com.ouroboros.enable: "true"
    restart: unless-stopped

  plexpy:
    image: linuxserver/tautulli:latest
    container_name: tautulli
    hostname: tautulli
    networks:
      br0:
        ipv4_address: 192.168.1.251
    volumes:
      - ${CONFIG}/plexpy:/config
      - ${CONFIG}/plex/Library/Application Support/Plex Media Server/Logs:/logs:ro
    environment:
      - PGID
      - PUID
      - TZ
    labels:
      traefik.enable: "true"
      traefik.port: "8181"
      traefik.frontend.rule: "Host:tautulli.${DOMAIN}"
      traefik.frontend.auth.basic: "${HTPASSWD}"
      com.ouroboros.enable: "true"
    restart: unless-stopped

  heimdall:
    image: duhio/heimdall-https:latest
    container_name: heimdall
    hostname: heimdall
    networks:
      br0:
        ipv4_address: 192.168.1.250
    volumes:
      - ${CONFIG}/heimdall:/config
    environment:
      - PGID
      - PUID
      - TZ
    labels:
      traefik.enable: "true"
      traefik.port: "80"
      traefik.frontend.rule: "Host:${DOMAIN}"
      traefik.frontend.auth.basic: "${HTPASSWD}"
      com.ouroboros.enable: "true"
    restart: unless-stopped

  ombi:
    image: linuxserver/ombi
    container_name: ombi
    hostname: ombi
    networks:
      br0:
        ipv4_address: 192.168.1.249
    volumes:
      - ${CONFIG}/ombi:/config
    environment:
      - PGID
      - PUID
      - TZ
    labels:
      traefik.enable: "true"
      traefik.port: "3579"
      traefik.frontend.rule: "Host:ombi.${DOMAIN}"
      com.ouroboros.enable: "true"
    restart: unless-stopped

# br0 is an existing Unraid macvlan
networks:
  br0:
    external: true
</code>```

When I used OnHostRule = true I could get plex.domain.name working with https but none of the other subdomains.

UPDATE: I have concluded that the issue is that the wildcard domains not working, after talking to a redditor he was not sure that the wildcards would work when manually specifying the network in the docker-compose.yml with static IP's, so far I have been unable to confirm this.

Digging further I think this may be an issue at the Cloudflare level, source here and report here.

答:
Edit: This configuration is now out of date for Traefik 2.0 and beyond

I have wildcards working with Cloudflare. Here is my configuration:

Part of my traefik.toml file

```<code>[acme]
  acmeLogging = true
  email = "me@email.com"
  storage = "/acme.json"
  onHostRule = true
  entryPoint = "https"
  [acme.dnsChallenge]
    provider = "cloudflare"

  [[acme.domains]]
    main = "sub.domain.com"
  [[acme.domains]]
    main = "*.sub.domain.com"
</code>```

And then in my docker-compose.yml file from which I start my traefik service, I specify an env file:

```<code>env_file: ./traefik.env
</code>```

In this file I have the following environment variables:

```<code>CLOUDFLARE_EMAIL=value1
CLOUDFLARE_API_KEY=value2
CF_API_EMAIL=value1
CF_API_KEY=value2
</code>```

I hope from my examples you'll have something to experiment with and find success!

I heavily recommend adding debug=true in your traefik.toml file as it will display logs which indicate whether or not the cloudflare setup was successful and for which domains.

Title: Setting up Traefik with Cloudflare

Body:
I am trying to setup traefik using a combination of this guide, and the code found here.

I am using docker-compose with Unraid, so far I have the following code:

traefik.toml:

debug = false

logLevel = "ERROR"
defaultEntryPoints = ["https","http"]

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
    entryPoint = "https"
  [entryPoints.https]
  address = ":443"
  [entryPoints.https.tls]

[retry]

[acme]
email = "user@domain.com"
storage = "acme.json"
entryPoint = "https"
#OnHostRule = true
#onDemand = true
[acme.dnsChallenge]
  provider = "cloudflare"
[[acme.domains]]
   main = "domain.name"
[[acme.domains]]
   main = "*.domain.name"

docker-compose.yml:

services:

  traefik:
    image: traefik:latest
    command: --web --docker --docker.watch --docker.domain=${DOMAIN} \
             --docker.exposedbydefault=false --acme.domains=${DOMAIN}
    container_name: traefik
    hostname: traefik
    networks:
      br0:
        ipv4_address: 192.168.1.253
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ${CONFIG}/traefik/acme.json:/acme.json
      - ${CONFIG}/traefik/traefik.toml:/etc/traefik/traefik.toml
      - ${CONFIG}/traefik/.htpasswd:/etc/traefik/.htpasswd:ro
    environment:
      - CF_API_EMAIL=user@domain.com
      - CF_API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXX
    labels:
      traefik.enable: "true"
      traefik.frontend.rule: "Host:monitor.${DOMAIN}"
      traefik.port: "8080"
      traefik.frontend.auth.basic: "${HTPASSWD}"
      com.ouroboros.enable: "true"
    restart: unless-stopped

  ouroboros:
    image: pyouroboros/ouroboros
    container_name: ouroboros
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - PGID
      - PUID
      - TZ
      - CLEANUP=true
      - INTERVAL=86400  # 24hrs
      - SELF_UPDATE=true
      - LABELS_ONLY=true
    restart: unless-stopped

  plex:
    image: linuxserver/plex
    container_name: plex
    hostname: plex
    networks:
      br0:
        ipv4_address: 192.168.1.252
    volumes:
      - ${CONFIG}/plex:/config
      - ${DATA}/TV:/media/tv
      - ${DATA}/Movies:/media/movies
      - ${DATA}/Music:/media/music
      - ${DATA}/Anime:/media/anime
    environment:
      - PGID
      - PUID
      - TZ
      - VERSION=latest
    labels:
      traefik.enable: "true"
      traefik.port: "32400"
      traefik.frontend.rule: "Host:plex.${DOMAIN}"
      com.ouroboros.enable: "true"
    restart: unless-stopped

  plexpy:
    image: linuxserver/tautulli:latest
    container_name: tautulli
    hostname: tautulli
    networks:
      br0:
        ipv4_address: 192.168.1.251
    volumes:
      - ${CONFIG}/plexpy:/config
      - ${CONFIG}/plex/Library/Application Support/Plex Media Server/Logs:/logs:ro
    environment:
      - PGID
      - PUID
      - TZ
    labels:
      traefik.enable: "true"
      traefik.port: "8181"
      traefik.frontend.rule: "Host:tautulli.${DOMAIN}"
      traefik.frontend.auth.basic: "${HTPASSWD}"
      com.ouroboros.enable: "true"
    restart: unless-stopped

  heimdall:
    image: duhio/heimdall-https:latest
    container_name: heimdall
    hostname: heimdall
    networks:
      br0:
        ipv4_address: 192.168.1.250
    volumes:
      - ${CONFIG}/heimdall:/config
    environment:
      - PGID
      - PUID
      - TZ
    labels:
      traefik.enable: "true"
      traefik.port: "80"
      traefik.frontend.rule: "Host:${DOMAIN}"
      traefik.frontend.auth.basic: "${HTPASSWD}"
      com.ouroboros.enable: "true"
    restart: unless-stopped

  ombi:
    image: linuxserver/ombi
    container_name: ombi
    hostname: ombi
    networks:
      br0:
        ipv4_address: 192.168.1.249
    volumes:
      - ${CONFIG}/ombi:/config
    environment:
      - PGID
      - PUID
      - TZ
    labels:
      traefik.enable: "true"
      traefik.port: "3579"
      traefik.frontend.rule: "Host:ombi.${DOMAIN}"
      com.ouroboros.enable: "true"
    restart: unless-stopped

# br0 is an existing Unraid macvlan
networks:
  br0:
    external: true

When I used OnHostRule = true I could get plex.domain.name working with https but none of the other subdomains.

UPDATE: I have concluded that the issue is that the wildcard domains not working, after talking to a redditor he was not sure that the wildcards would work when manually specifying the network in the docker-compose.yml with static IP's, so far I have been unable to confirm this.

Digging further I think this may be an issue at the Cloudflare level, source here and report here.

Body:
Edit: This configuration is now out of date for Traefik 2.0 and beyond

I have wildcards working with Cloudflare. Here is my configuration:

Part of my traefik.toml file

[acme]
  acmeLogging = true
  email = "me@email.com"
  storage = "/acme.json"
  onHostRule = true
  entryPoint = "https"
  [acme.dnsChallenge]
    provider = "cloudflare"

  [[acme.domains]]
    main = "sub.domain.com"
  [[acme.domains]]
    main = "*.sub.domain.com"

And then in my docker-compose.yml file from which I start my traefik service, I specify an env file:

env_file: ./traefik.env

In this file I have the following environment variables:

CLOUDFLARE_EMAIL=value1
CLOUDFLARE_API_KEY=value2
CF_API_EMAIL=value1
CF_API_KEY=value2

I hope from my examples you'll have something to experiment with and find success!

I heavily recommend adding debug=true in your traefik.toml file as it will display logs which indicate whether or not the cloudflare setup was successful and for which domains.


来源: stackexchange

问:
Predict the next location based on the previous days data using lstm
Based on the 10 days of the data I need to predict the 11th-day location of the user. Example of my input is in this link

The dataset contains:
200,000 users with  1550 random location points and 10days of history for each user

```<code>from datetime import datetime
from random import seed

import pandas as pd

seed(150)

df = pd.read_csv('input.csv', delimiter=';')
df = df.iloc[:-1,:]
df = df.drop(columns='tslot')

def normalize_cols(df, cols):
for col in df.columns:
print(col, df[col].max(), df[col].min())
df[col] = (df[col] - df[col].min())/(df[col].max() - df[col].min())
return df

df = normalize_cols(df, ['slot', 'location', 'user'])
df.to_csv('cleaned_data.csv', index=False)
</code>```

```<code>from keras.models import Sequential, load_model
from keras.layers import Dense, LSTM, Dropout
from matplotlib import pyplot
import numpy as np
import pandas as pd
df = pd.read_csv('cleaned_data.csv')
train_x = df[['slot', 'user']].copy()
train_y = df[['tower']].copy().values
train_x = train_x.values.reshape((train_x.shape[0], 1, train_x.shape[1]))
model = Sequential()
model.add(LSTM(50, input_shape=(train_x.shape[1], train_x.shape[2])))
model.add(Dropout(0.5))
model.add(Dense(40))
model.add(Dropout(0.3))
model.add(Dense(20))
model.add(Dropout(0.2))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
history = model.fit(train_x, train_y, epochs=100, batch_size=25,  verbose=2, shuffle=True)
model.save('5g_tower.h5')
del model
model = load_model('5g_tower.h5')
## Prediction
def get_tower_number(model, slot, user):
## normalize input slot, tower, user
slot = ((slot - 0)*1.0) / ((95.0 - 0.0)*1.0)
user = ((user - 1)*1.0) / ((2.0 - 1.0)*1.0)

## get a slot for next 15 mins
res = model.predict(np.array([[[slot, user]]]))

## de-normalize that tower
return int(res[0][0] * ((1354.0 - 9.0)*1.0) + 9.0)

print(get_tower_number(model, 4, 1))
</code>```

But failed to predict the location of the user for the 11th day. The output I got is wrong compared to the required output.
The example of the output is given in this link. How to implement individual model rather than the global model in this system?
The example output should be the 11th day:

```<code>     User   location   slot
      1        145       0

      1         94       95
      2         562       0

      2         583       95
</code>```

The actual dataset contains a total of 350,000 users

答:
Just looking at the model implementation, you're missing activation function for every Dense block, so keras is applying linear activation.
You can modify that using:</p>

```<code>model.add(Activation('relu'))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Based on the 10 days of the data I need to predict the 11th-day location of the user. Example of my input is in this link

The dataset contains:
200,000 users with  1550 random location points and 10days of history for each user

from datetime import datetime
from random import seed

import pandas as pd

seed(150)

df = pd.read_csv('input.csv', delimiter=';')
df = df.iloc[:-1,:]
df = df.drop(columns='tslot')

def normalize_cols(df, cols):
for col in df.columns:
print(col, df[col].max(), df[col].min())
df[col] = (df[col] - df[col].min())/(df[col].max() - df[col].min())
return df

df = normalize_cols(df, ['slot', 'location', 'user'])
df.to_csv('cleaned_data.csv', index=False)

from keras.models import Sequential, load_model
from keras.layers import Dense, LSTM, Dropout
from matplotlib import pyplot
import numpy as np
import pandas as pd
df = pd.read_csv('cleaned_data.csv')
train_x = df[['slot', 'user']].copy()
train_y = df[['tower']].copy().values
train_x = train_x.values.reshape((train_x.shape[0], 1, train_x.shape[1]))
model = Sequential()
model.add(LSTM(50, input_shape=(train_x.shape[1], train_x.shape[2])))
model.add(Dropout(0.5))
model.add(Dense(40))
model.add(Dropout(0.3))
model.add(Dense(20))
model.add(Dropout(0.2))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
history = model.fit(train_x, train_y, epochs=100, batch_size=25,  verbose=2, shuffle=True)
model.save('5g_tower.h5')
del model
model = load_model('5g_tower.h5')
## Prediction
def get_tower_number(model, slot, user):
## normalize input slot, tower, user
slot = ((slot - 0)*1.0) / ((95.0 - 0.0)*1.0)
user = ((user - 1)*1.0) / ((2.0 - 1.0)*1.0)

## get a slot for next 15 mins
res = model.predict(np.array([[[slot, user]]]))

## de-normalize that tower
return int(res[0][0] * ((1354.0 - 9.0)*1.0) + 9.0)

print(get_tower_number(model, 4, 1))

But failed to predict the location of the user for the 11th day. The output I got is wrong compared to the required output.
The example of the output is given in this link. How to implement individual model rather than the global model in this system?
The example output should be the 11th day:

     User   location   slot
      1        145       0

      1         94       95
      2         562       0

      2         583       95

The actual dataset contains a total of 350,000 users

Body:
Just looking at the model implementation, you're missing activation function for every Dense block, so keras is applying linear activation.
You can modify that using:

model.add(Activation('relu'))


问:
Redirect user after 60 seconds of idling/inactivity?
How can I use JavaScript on my site to redirect the user to a /logout page after 60 seconds of inactivity?

I know setting a timer or using a meta refresh tag is straightforward: but I only want to redirect inactive users, not disrupt someone's active session/usage.

Is this possible with JavaScript?

答:
I belive you are looking for something like this:

http://paulirish.com/2009/jquery-idletimer-plugin/

If you were to code that yourself, you would need to capture mouse and keyboard events and restart your timer after any of these events. If the timer ever reaches the threshold or counts down to 0 from the threshold you can reset the URL of the page.

ContentLicense: CC BY-SA 3.0


问:
Javascript program to automate task
I am trying to automate a tedious task we do at my current job. We have a website we use to process customer orders and every day, we have to print out papers and force orders over so they can be processed.

I had done it before using Python and the Selenium Webdriver but that stopped working because they upgraded the PCs (and I would like to try utilizing Javascript instead now since it's built into the web browsers (was previously running the script off a flash drive that had python installed on it). I've figured out most of the basic stuff, but I'm having trouble finding answers to how this can be done.

I need to be able to run the script easily (not just me but my coworkers as well when I'm not there and they're all not very knowledgeable in this stuff).

Is it possible to actually write a Javascript script that can be run and automate this task? The website does require us to login. With Pytbon, I used a GUI form where the user would type in their username, password, and a day of the week and it would take those values and just login and navigate the pages, "clicking" everything for us and printing. Would prefer to be able to do it in Internet Explorer because that's what the website we use is optimized for (chrome has weird side effects when the paperwork is printed).

Thanks to anyone who can give me some advice, suggestions, or even links to other resources that could help.

答:
You could use Node.js and the selenium webdriver module with promises get this done.

https://www.npmjs.com/package/selenium-webdriver

You could create this in a way where all you have to do is run the command and the program will be automated with feedback.

Title: Javascript program to automate task


问:
Why map re rendering on marker click event?
I have google map with multiple markers with the cluster. Upon marker click, I am showing info window, but when I click on marker whole of the map marker and cluster are re-rendered, which makes the page slow and annoying.

Following is my code:

```<code>import React, { Component } from "react";
import axios from "axios";
import { compose, withProps, withHandlers, withStateHandlers } from "recompose";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  InfoWindow
} from "react-google-maps";
const {
  MarkerClusterer
} = require("react-google-maps/lib/components/addons/MarkerClusterer");

const MapWithAMarkerClusterer = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=API&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `90vh` }} />,
    mapElement: <div style={{ height: `100%` }} />
  }),
  withStateHandlers(
    { InfoWindowobject: null },
    {
      setInfoWindow: () => value => ({ InfoWindowobject: value })
    }
  ),
  withStateHandlers(
    { isOpen: false },
    {
      onToggleOpen: ({ isOpen }) => () => ({
        isOpen: !isOpen
      })
    }
  ),
  withHandlers({
    onMarkerClustererClick: () => markerClusterer => {
      const clickedMarkers = markerClusterer.getMarkers();
    },
    onMarkerClick: props => markerss => {
      const { setInfoWindow, onToggleOpen } = props;

      axios({
        url: "API",
        method: "POST",

      }).then(res => {

        setInfoWindow(res.data);
        onToggleOpen();
      });
    }
  }),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap
    defaultZoom={5}
    defaultCenter={{ lat: 22.845625996700075, lng: 78.9629 }}
  >
    <MarkerClusterer
      onClick={props.onMarkerClustererClick}
      minimumClusterSize={10}
      averageCenter
      styles={[
        {
          textColor: "white",
          url: imgmapcluster,
          height: 68,
          lineHeight: 3,
          width: 70
        }
      ]}
      enableRetinaIcons
      gridSize={60}
    >
      {props.markers.map((marker, index) => (
        <Marker
          key={index}
          icon={user}
          onClick={props.onMarkerClick.bind(props, marker)}
          position={{ lat: marker.latitude, lng: marker.longitude }}
        />
      ))}
      {props.isOpen && props.InfoWindowobject !== null && (
        <InfoWindow
          position={{
            lat: props.InfoWindowobject.latitude,
            lng: props.InfoWindowobject.longitude
          }}
          onCloseClick={props.onToggleOpen}
        >
          {props.InfoWindowobject !== null && (
            <div className="infobox clearfix" style={{ fontFamily: "Gotham" }}>
              <div className="header clearfix">
                <h3>
                  {props.InfoWindowobject.name},{" "}
                  <small>{props.InfoWindowobject.contactNo}</small>
                </h3>
              </div>

            </div>
          )}
        </InfoWindow>
      )}
    </MarkerClusterer>
  </GoogleMap>
));

class DemoApp extends React.PureComponent {
  componentWillMount() {
    this.setState({ markers: [], isOpen: false, InfoWindowobject: {} });
  }

  componentDidMount() {
    axios({
      url: "API",

    }).then(res => {
      this.setState({ markers: res.data.data.list });
    });
  }

  render() {
    return (
      <MapWithAMarkerClusterer
        markers={this.state.markers}
        isOpen={this.state.isOpen}
        InfoWindowobject={this.state.InfoWindowobject}
      />
    );
  }
}
</code>```

Reference:
https://tomchentw.github.io/react-google-maps/#markerclusterer

答:
This is an expected behavior since re-render happens on every state change.
To prevent re-render you could consider to  wrap MarkerClusterer component  with shouldUpdate higher-order component to let React know whether a component should be affected by change state or not  as demonstrated below:

```<code>const MyMarkerClusterer = shouldUpdate(checkPropsChange)(props => {
  const {onMarkerClick,markers,...clusterProps}  = props;
  return (
    <MarkerClusterer
    {...clusterProps}
    >
      {markers.map(marker => (
        <Marker
          key={marker.photo_id}
          position={{ lat: marker.latitude, lng: marker.longitude }}
          onClick={onMarkerClick.bind(this, marker)}
        />
      ))}
    </MarkerClusterer>
  );
});
</code>```

where

```<code>const checkPropsChange = (props, nextProps) => {
  return nextProps.markers.length !== props.markers.length; //re-render only if markers prop changed
};
</code>```

Here is a  demo

Body:
I have google map with multiple markers with the cluster. Upon marker click, I am showing info window, but when I click on marker whole of the map marker and cluster are re-rendered, which makes the page slow and annoying.

Following is my code:

import React, { Component } from "react";
import axios from "axios";
import { compose, withProps, withHandlers, withStateHandlers } from "recompose";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  InfoWindow
} from "react-google-maps";
const {
  MarkerClusterer
} = require("react-google-maps/lib/components/addons/MarkerClusterer");

const MapWithAMarkerClusterer = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=API&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `90vh` }} />,
    mapElement: <div style={{ height: `100%` }} />
  }),
  withStateHandlers(
    { InfoWindowobject: null },
    {
      setInfoWindow: () => value => ({ InfoWindowobject: value })
    }
  ),
  withStateHandlers(
    { isOpen: false },
    {
      onToggleOpen: ({ isOpen }) => () => ({
        isOpen: !isOpen
      })
    }
  ),
  withHandlers({
    onMarkerClustererClick: () => markerClusterer => {
      const clickedMarkers = markerClusterer.getMarkers();
    },
    onMarkerClick: props => markerss => {
      const { setInfoWindow, onToggleOpen } = props;

      axios({
        url: "API",
        method: "POST",

      }).then(res => {

        setInfoWindow(res.data);
        onToggleOpen();
      });
    }
  }),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap
    defaultZoom={5}
    defaultCenter={{ lat: 22.845625996700075, lng: 78.9629 }}
  >
    <MarkerClusterer
      onClick={props.onMarkerClustererClick}
      minimumClusterSize={10}
      averageCenter
      styles={[
        {
          textColor: "white",
          url: imgmapcluster,
          height: 68,
          lineHeight: 3,
          width: 70
        }
      ]}
      enableRetinaIcons
      gridSize={60}
    >
      {props.markers.map((marker, index) => (
        <Marker
          key={index}
          icon={user}
          onClick={props.onMarkerClick.bind(props, marker)}
          position={{ lat: marker.latitude, lng: marker.longitude }}
        />
      ))}
      {props.isOpen && props.InfoWindowobject !== null && (
        <InfoWindow
          position={{
            lat: props.InfoWindowobject.latitude,
            lng: props.InfoWindowobject.longitude
          }}
          onCloseClick={props.onToggleOpen}
        >
          {props.InfoWindowobject !== null && (

                  {props.InfoWindowobject.name},{" "}
                  {props.InfoWindowobject.contactNo}

          )}
        </InfoWindow>
      )}
    </MarkerClusterer>
  </GoogleMap>
));

class DemoApp extends React.PureComponent {
  componentWillMount() {
    this.setState({ markers: [], isOpen: false, InfoWindowobject: {} });
  }

  componentDidMount() {
    axios({
      url: "API",

    }).then(res => {
      this.setState({ markers: res.data.data.list });
    });
  }

  render() {
    return (
      <MapWithAMarkerClusterer
        markers={this.state.markers}
        isOpen={this.state.isOpen}
        InfoWindowobject={this.state.InfoWindowobject}
      />
    );
  }
}

Reference:
https://tomchentw.github.io/react-google-maps/#markerclusterer

Body:
This is an expected behavior since re-render happens on every state change.
To prevent re-render you could consider to  wrap MarkerClusterer component  with shouldUpdate higher-order component to let React know whether a component should be affected by change state or not  as demonstrated below:

const MyMarkerClusterer = shouldUpdate(checkPropsChange)(props => {
  const {onMarkerClick,markers,...clusterProps}  = props;
  return (
    <MarkerClusterer
    {...clusterProps}
    >
      {markers.map(marker => (
        <Marker
          key={marker.photo_id}
          position={{ lat: marker.latitude, lng: marker.longitude }}
          onClick={onMarkerClick.bind(this, marker)}
        />
      ))}
    </MarkerClusterer>
  );
});

where

const checkPropsChange = (props, nextProps) => {
  return nextProps.markers.length !== props.markers.length; //re-render only if markers prop changed
};

Here is a  demo


问:
How to identify and save anonymous user choices in django?
I have a quiz app for students. Right now students have to first resister on the platform then they choose course and relevant quizzes appear before them.
But what I want is : Students don't have to register first. They can choose course and then take one quiz then I will prompt them for a registration. What I want; when they register I can save data such as their course to a anonymous user (which they chose before registration) and link that to the account that will be created after they register.
So how I can I know what course did they choose before registration and how to link it to the user after they register?
Preferably through django rest framework as we an android app.</p>

答:
You could create a 'fake' user based on the session key.  Something like

```<code>    if not self.request.user.is_authenticated():
        #create anonymous user
        self.request.session.save()
        username = str(self.request.session.session_key) + '@dummy.com'
        try:
            user = MyUser.objects.create_user(username, is_fake=True)
        except:
            user = MyUser.objects.get(email=username)
        login(self.request, user)
</code>```

Then if you have a username of this format you know they're not a real user and offer the normal options around login etc.

Body:
You could create a 'fake' user based on the session key.  Something like

    if not self.request.user.is_authenticated():
        #create anonymous user
        self.request.session.save()
        username = str(self.request.session.session_key) + '@dummy.com'
        try:
            user = MyUser.objects.create_user(username, is_fake=True)
        except:
            user = MyUser.objects.get(email=username)
        login(self.request, user)

Then if you have a username of this format you know they're not a real user and offer the normal options around login etc.


问:
How to receive the vlan header/l2 header using a ICMPv6 socket
In my ND daemon, i am using rbos_socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6); to receive ICMPv6 header for receiving NS and other ND messages (l3 messages).
With this option kernel will strip the l2 header (with VLAN information). which option should I use to avoid this stripping?

My intent is to receive ICMPv6 message with VLAN information.

Already tried using the following:
1) rbos_socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
2) rbos_socket(AF_INET6, SOCK_RAW, PROTO_ND)

My expectation is to receive ICMPv6 message with l2 information (specifically VLAN header).

答: You cannot get the first VLAN tag like this. It does get stripped from the packet, but it is available out-of-band in the tp_vlan_tci and tp_vlan_tpid members, see linux/if_packet.h (assuming this is on Linux).


问:
Point-Triangle Collision Detection in 3D
How do I correct for floating point error in the following physical simulation:

Original point (x, y, z),

Desired point (x', y', z') after forces are applied.

Two triangles (A, B, C) and (B, C, D), who share edge BC

I am using this method for collision detection:

```<code>For each Triangle
    If the original point is in front of the current triangle, and the desired point is behind the desired triangle:
        Calculate the intersection point of the ray (original-desired) and the plane (triangle's normal).
        If the intersection point is inside the triangle edges (!)
            Respond to the collision.
        End If
    End If
Next Triangle
</code>```

The problem I am having is that sometimes the point falls into the grey area of floating point math where it is so close to the line BC that it fails to collide with either triangle, even though technically it should always collide with one or the other since they share an edge.  When this happens the point passes right between the two edge sharing triangles.  I have marked one line of the code with (!) because I believe that's where I should be making a change.

One idea that works in very limited situations is to skip the edge testing.  Effectively turning the triangles into planes.  This only works when my meshes are convex hulls, but I plan to create convex shapes.

I am specifically using the dot product and triangle normals for all of my front-back testing.

答:
This is an inevitable problem when shooting a single ray against some geometry with edges and vertices. It's amazing how physical simulations seem to seek out the smallest of numerical inaccuracies!

Some of the explanations and solutions proposed by other respondents will not work. In particular:

Numerical inaccuracy really can cause a ray to "fall through the gap". The problem is that we intersect the ray with the plane ABC (getting the point P, say) before testing against line BC. Then we intersect the ray with plane BCD (getting the point Q, say) before testing against line BC. P and Q are both represented by the closest floating-point approximation; there's no reason to expect that these exactly lie on the planes that they are supposed to lie on, and so every possibility that you can have both P to the left of BC and Q to the right of BC.

Using less-than-or-equal test won't help; it's inaccuracy in the intersection of the ray and the plane that's the trouble.

Square roots are not the issue; you can do all of the necessary computations using dot products and floating-point division.

Here are some genuine solutions:

For convex meshes, you can just test against all the planes and ignore the edges and vertices, as you say (thus avoiding the issue entirely).

Don't intersect the ray with each triangle in turn. Instead, use the scalar triple product. (This method makes the exact same sequence of computations for the ray and the edge BC when considering each triangle, ensuring that any numerical inaccuracy is at least consistent between the two triangles.)

For non-convex meshes, give the edges and vertices some width. That is, place a small sphere at each vertex in the mesh, and place a thin cylinder along each edge of the mesh. Intersect the ray with these spheres and cylinders as well as with the triangles. These additional geometric figures stop the ray passing through edges and vertices of the mesh.

Let me strongly recommend the book Real-Time Collision Detection by Christer Ericson. There's a discussion of this exact problem on pages 446–448, and an explanation of the scalar triple product approach to intersecting a ray with a triangle on pages 184–188.

OwnerDisplayName: Martin

ContentLicense: CC BY-SA 2.5

Body:
How do I correct for floating point error in the following physical simulation:

Original point (x, y, z),

Desired point (x', y', z') after forces are applied.

Two triangles (A, B, C) and (B, C, D), who share edge BC

I am using this method for collision detection:

For each Triangle
    If the original point is in front of the current triangle, and the desired point is behind the desired triangle:
        Calculate the intersection point of the ray (original-desired) and the plane (triangle's normal).
        If the intersection point is inside the triangle edges (!)
            Respond to the collision.
        End If
    End If
Next Triangle

The problem I am having is that sometimes the point falls into the grey area of floating point math where it is so close to the line BC that it fails to collide with either triangle, even though technically it should always collide with one or the other since they share an edge.  When this happens the point passes right between the two edge sharing triangles.  I have marked one line of the code with (!) because I believe that's where I should be making a change.

One idea that works in very limited situations is to skip the edge testing.  Effectively turning the triangles into planes.  This only works when my meshes are convex hulls, but I plan to create convex shapes.

I am specifically using the dot product and triangle normals for all of my front-back testing.

LastEditorDisplayName: Oli

LastEditorDisplayName: Gareth Rees


问:
The given path's format is not supported - Using time data
I trying to save some data to a text file inside a folder:

I have tried to change dd-MM-yyyy-hhmm To dd-MM-yyyy-hh:mm, and I tried to use the debugger to check where is the problem but I couldn't find anything.

Code:

```<code>public static string Folder(string mode)
{
    string str = DateTime.Now.ToString("dd-MM-yyyy-hhmm - ");
    Directory.CreateDirectory(str + mode);
    return str + mode;
}
</code>```

The resulting behaviour should be similar to, the user saves the data, it will create a new folder with this name.

For example:

(example - http - 26-5-2019-1514), inside the folder - Results.txt

答:
You should check input for invalid characters

for windows - \/:*?"<>|

for linux /

or maybe prefer other way and define allowed characters for your case
my suggestion is 0-9a-zA-Z-._

Example of cleanup process

```<code>  var invalidCharacters = new string[] {"\\", "/", ":", " *", "?", "<", ">", "|"};

  var temp = a.Split(invalidCharacters, StringSplitOptions.RemoveEmptyEntries);
  a = String.Join("", temp);
</code>```

Body:
I trying to save some data to a text file inside a folder:

I have tried to change dd-MM-yyyy-hhmm To dd-MM-yyyy-hh:mm, and I tried to use the debugger to check where is the problem but I couldn't find anything.

Code:

public static string Folder(string mode)
{
    string str = DateTime.Now.ToString("dd-MM-yyyy-hhmm - ");
    Directory.CreateDirectory(str + mode);
    return str + mode;
}

The resulting behaviour should be similar to, the user saves the data, it will create a new folder with this name.

For example:

(example - http - 26-5-2019-1514), inside the folder - Results.txt

Body:
You should check input for invalid characters

for windows - \/:*?"<>|

for linux /

or maybe prefer other way and define allowed characters for your case
my suggestion is 0-9a-zA-Z-._

Example of cleanup process

  var invalidCharacters = new string[] {"\\", "/", ":", " *", "?", "<", ">", "|"};

  var temp = a.Split(invalidCharacters, StringSplitOptions.RemoveEmptyEntries);
  a = String.Join("", temp);


问:
How to detect duplicate request in method post with same time
I using spring boot and create api with method look like below:

```<code>@RestController
@RequestMapping("/api/products/")
@Api(value = "ProductControllerApi",produces = MediaType.APPLICATION_JSON_VALUE)
public class ProductController {
  @PostMapping
    public ResponseEntity<ProductDto> createProduct(@RequestBody Product product) {
        URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(product.getId()).toUri();
        return ResponseEntity.created(location).body(productService.createProduct(product));
    }
}
</code>```

But when user using device call my method(/api/products/) with same time, it duplicate create with same data. Example: When use create user look like
{
   "name": "Samsung"
   "cost": "26$"
}

it create two record in database with same data. How to detect duplicate data from different source(example : user using two mobile and call same time with same method and create same data). How to avoid it and if it call same time with same data it only insert one record to database

答: This isn't a problem for Spring Boot but rather for your persistence layer. The best practice is for your DB tables to modeled in such a way that two identical requests would create exactly the same primary key. Then your application code would deal with any exception from the DB layer at transaction commit time. </p>

Body:
I using spring boot and create api with method look like below:

@RestController
@RequestMapping("/api/products/")
@Api(value = "ProductControllerApi",produces = MediaType.APPLICATION_JSON_VALUE)
public class ProductController {
  @PostMapping
    public ResponseEntity<ProductDto> createProduct(@RequestBody Product product) {
        URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(product.getId()).toUri();
        return ResponseEntity.created(location).body(productService.createProduct(product));
    }
}

But when user using device call my method(/api/products/) with same time, it duplicate create with same data. Example: When use create user look like
{
   "name": "Samsung"
   "cost": "26$"
}

it create two record in database with same data. How to detect duplicate data from different source(example : user using two mobile and call same time with same method and create same data). How to avoid it and if it call same time with same data it only insert one record to database


问:
Creating project in vue taking time
I typed vue create "project name" and it is installing packages for some long time.

there is no error messages it just keeps on installing packages

答: I have encountered significant speed issues with vue-cli it definitely slows down your computer. Try closing everything except your terminal and see if that helps. The next step would be to free up memory by killing unneeded processes. </p>

Title: Creating project in vue taking time


问:
JavasScript wait for web element to be visible and click it
I'm trying to automate some tasks with JavaScript. Website is being generated so I cannot use CSS selectors as they change with every website refresh. It is not shown in the example but it is possible to manipulate buttons with their text content (which CSS, sadly, cannot get).

I have figured out (thanks to StackOverflow) how to click web element by its Xpath but still don't know how to tell JS to wait until it is present.

Code for clicking element (working):

```<code>var xPathRes = document.evaluate ('//*[@id="tsf"]/div[2]/div/div[3]/center/input[1]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
xPathRes.singleNodeValue.click();
</code>```

Attempt to wait for element to be present and then click it (not working):

```<code>var selector = "//*[@id='tsf']/div[2]/div/div[3]/center/input[1]";
var time = 500;
    if(document.evaluate (selector, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)) {
        selector.singleNodeValue.click();
        return;
        }
    else {
        setTimeout(function() {
        waitForElementToDisplay(selector, time);
        }, time);
    }
</code>```

As you can see code in the example is Google.com search button.

I have always used Python Selenium to do such things but in this case I really cannot.

PS. I suck at JS as it is evident from posted code.

Thank you for trying to help!

EDIT:

Following @folo code I wrote something like this:

```<code>var element = '//*[@id="tsf"]/div[2]/div/div[3]/center/input[1]';
(function checkIfElemExists() {
   if (!document.evaluate (element, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)) {
     console.log('nope')
     window.requestAnimationFrame(checkIfElemExists);
   } else {
     console.log('okay i exist now! lets do something.')
   }
 })()
</code>```

The problem is that it always returns "Okay i exist now!). Even when i run it on a website that does not contain this element.

答:
The button will only be present when the page (DOM) is completely loaded. In javascript you can use the 'onload'-event:

```<code>window.onload = function () {
   //Code to execute when page is loaded.
}
</code>```

Or via JQuery:

```<code>$( document ).ready(function() {
    //Code to execute when page is loaded.
});
</code>```

I hope this is what you are looking for.

Body:
I'm trying to automate some tasks with JavaScript. Website is being generated so I cannot use CSS selectors as they change with every website refresh. It is not shown in the example but it is possible to manipulate buttons with their text content (which CSS, sadly, cannot get).

I have figured out (thanks to StackOverflow) how to click web element by its Xpath but still don't know how to tell JS to wait until it is present.

Code for clicking element (working):

var xPathRes = document.evaluate ('//*[@id="tsf"]/div[2]/div/div[3]/center/input[1]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
xPathRes.singleNodeValue.click();

Attempt to wait for element to be present and then click it (not working):

var selector = "//*[@id='tsf']/div[2]/div/div[3]/center/input[1]";
var time = 500;
    if(document.evaluate (selector, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)) {
        selector.singleNodeValue.click();
        return;
        }
    else {
        setTimeout(function() {
        waitForElementToDisplay(selector, time);
        }, time);
    }

As you can see code in the example is Google.com search button.

I have always used Python Selenium to do such things but in this case I really cannot.

PS. I suck at JS as it is evident from posted code.

Thank you for trying to help!

EDIT:

Following @folo code I wrote something like this:

var element = '//*[@id="tsf"]/div[2]/div/div[3]/center/input[1]';
(function checkIfElemExists() {
   if (!document.evaluate (element, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)) {
     console.log('nope')
     window.requestAnimationFrame(checkIfElemExists);
   } else {
     console.log('okay i exist now! lets do something.')
   }
 })()

The problem is that it always returns "Okay i exist now!). Even when i run it on a website that does not contain this element.

Body:
The button will only be present when the page (DOM) is completely loaded. In javascript you can use the 'onload'-event:

window.onload = function () {
   //Code to execute when page is loaded.
}

Or via JQuery:

$( document ).ready(function() {
    //Code to execute when page is loaded.
});

I hope this is what you are looking for.


问:
Spring WebClient: How to stream large byte[] to file?
It seems like it the Spring RestTemplate isn't able to stream a response directly to file without buffering it all in memory. What is the proper to achieve this using the newer Spring 5 WebClient?

```<code>WebClient client = WebClient.create("https://example.com");
client.get().uri(".../{name}", name).accept(MediaType.APPLICATION_OCTET_STREAM)
                    ....?
</code>```

I see people have found a few workarounds/hacks to this issue with RestTemplate, but I am more interested in doing it the proper way with the WebClient.

There are many examples of using RestTemplate to download binary data but almost all of them load the byte[] into memory.

答:
I'm not sure if you have access to RestTemplate in your current usage of spring, but this one have worked for me.

RestTemplate restTemplate // = ...;

RequestCallback requestCallback = request -> request.getHeaders()
        .setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));

// Streams the response
ResponseExtractor<Void> responseExtractor = response -> {
    // Here I write the response to a file but do what you like
    Path path = Paths.get("http://some/path");
    Files.copy(response.getBody(), path);
    return null;
};
restTemplate.execute(URI.create("www.something.com"), HttpMethod.GET, requestCallback, responseExtractor);

```

Body:
It seems like it the Spring RestTemplate isn't able to stream a response directly to file without buffering it all in memory. What is the proper to achieve this using the newer Spring 5 WebClient?

WebClient client = WebClient.create("https://example.com");
client.get().uri(".../{name}", name).accept(MediaType.APPLICATION_OCTET_STREAM)
                    ....?

I see people have found a few workarounds/hacks to this issue with RestTemplate, but I am more interested in doing it the proper way with the WebClient.

There are many examples of using RestTemplate to download binary data but almost all of them load the byte[] into memory.


问:
How to fill column background color for pdfmake with fillColor?
Is there any option to fill column background color with fillColor: '#dedede' ?
fillColor works in tablecell very well at the same time it doesn't work for column :(

<button onclick="print()" style="display:block; margin: 10px auto;padding: 20px 50px;">Print</button>

```

答:
Use a table to wrap your content

Setup a table with one cell and no border and use the fillColor to set the background.

var docDefinition = {
  content: [
  {
    table: {
      headerRows: 0,
      body: [
        [{
            // Choose your color
            fillColor: '#bada55',
            // Remove distasteful border
            border: [false, false, false, false],

            // Columns/Whatever goes here
            columns: [{
              // auto-sized columns have their widths based on their content
              width: 'auto',
              text: 'First column',
              fontSize: 30,
              fillColor: '#dedede'
            }, {
              // star-sized columns fill the remaining space
              // if there's more than one star-column, available width is divided equally
              width: '*',
              text: 'Second column'
            }, {
              // fixed width
              width: 100,
              text: 'Third column'
            }, {
              // percentage width
              width: '10%',
              text: 'Last column'
            }],
            // optional space between columns
            columnGap: 10
          },
          'This paragraph goes below all columns and has full width'
        ]

        }],
      ]
    }
  },
};
```

This takes me back to the years where the internet was styled using tables.
If nothing else supports fill color property wrap it in what does support it; a table.

Body:
Use a table to wrap your content

Setup a table with one cell and no border and use the fillColor to set the background.

var docDefinition = {
  content: [
  {
    table: {
      headerRows: 0,
      body: [
        [{
            // Choose your color
            fillColor: '#bada55',
            // Remove distasteful border
            border: [false, false, false, false],

            // Columns/Whatever goes here
            columns: [{
              // auto-sized columns have their widths based on their content
              width: 'auto',
              text: 'First column',
              fontSize: 30,
              fillColor: '#dedede'
            }, {
              // star-sized columns fill the remaining space
              // if there's more than one star-column, available width is divided equally
              width: '*',
              text: 'Second column'
            }, {
              // fixed width
              width: 100,
              text: 'Third column'
            }, {
              // percentage width
              width: '10%',
              text: 'Last column'
            }],
            // optional space between columns
            columnGap: 10
          },
          'This paragraph goes below all columns and has full width'
        ]

        }],
      ]
    }
  },
};

This takes me back to the years where the internet was styled using tables.
If nothing else supports fill color property wrap it in what does support it; a table.


问:
How should weights be optimized with gradient descent algorithm in order to work?
I have a neural network in visual studio. for the loss function I am using a basic cost function (pred-target)**2 and after I finish an epoch I optimize the parameter functions afterwards, but the algorithm doesn't work.

No matter what is my network configuration, the predictions are not write (it is the same output for all the inputs) and the loss function is not optimized. It stays the same through all the epochs.

```<code>void calc_lyr(int x, int y, int idx, float target) // thus function calculates the neuron value based on the previous layer
{
    if (x == -1 || y == 0) // if its the first layer, get the data from input nodes
    {
        for (int i = 0; i < neurons[y]; i++)
        {
            float sum = 0;

            for (int j = 0; j < inputTypes.Count; j++)
            {
                sum += weights[x+1][j][i] * training_test[idx][j];
            }
            sum = relu(sum);
            vals[y+1][i] = sum;

        }
    }
    else
    {
        for(int i = 0; i < neurons[y]; i++)
        {
            float sum = 0;

            for(int j = 0; j < neurons[x]; j++)
            {
                sum += weights[x+1][j][i] * vals[x+1][j] + biases[y][i];
            }
            sum = relu(sum);
            vals[y+1][i] = sum;
        }
    }
}

void train()
{
    log("Proces de antrenare inceput ----------------- " + DateTime.Now.ToString());

    vals = new List<List<float>>();
    weights = new List<List<List<float>>>();
    biases = new List<List<float>>();

    Random randB = new Random(DateTime.Now.Millisecond);
    Random randW = new Random(DateTime.Now.Millisecond);

    for (int i = 0; i <= nrLayers; i++)
    {
        progressEpochs.Value =(int)(((float)i * (float)nrLayers) / 100.0f);

        vals.Add(new List<float>());

        weights.Add(new List<List<float>>());
        if (i == 0)
        {
            for (int j = 0; j < inputTypes.Count; j++)
            {
                vals[i].Add(0);
            }
        }
        else
        {
            biases.Add(new List<float>());

            for (int j = 0; j < neurons[i-1]; j++)
            {
                vals[i].Add(0);

                float valB = (float)randB.NextDouble();
                biases[i-1].Add(valB - ((int)valB));
            }
        }
    }

    float valLB = (float)randB.NextDouble();

    biases.Add(new List<float>());
    biases[nrLayers].Add(valLB - ((int)valLB));

    for (int i = 0; i <= nrLayers; i++)
    {
        if (i == 0)
        {
            for (int j = 0; j < inputTypes.Count; j++)
            {
                weights[i].Add(new List<float>());

                for (int x = 0; x < neurons[i]; x++)
                {
                    float valW = (float)randW.NextDouble();
                    weights[i][j].Add(valW);
                }
            }
        }
        else if (i == nrLayers)
        {
            for (int j = 0; j < neurons[i-1]; j++) {
                weights[i].Add(new List<float>());
                weights[i][j].Add(0);
            }
        }
        else
        {
            for (int j = 0; j < neurons[i - 1]; j++)
            {
                weights[i].Add(new List<float>());

                for (int x = 0; x < neurons[i]; x++)
                {
                    float valW = (float)randW.NextDouble();
                    weights[i][j].Add(valW);
                }
            }
        }
    }

    Random rand = new Random(DateTime.Now.Millisecond);
    log("\n\n");
    for (int i = 0; i < epochs; i++)
    {
        log("Epoch " + (i + 1).ToString() + " inceput ---> " + DateTime.Now.ToString());
        int idx = rand.Next() % training_test.Count;

        float target = outputsPossible.IndexOf(training_labels[idx]);

        for (int j = 0; j < nrLayers; j++)
        {
            calc_lyr(j - 1, j, idx, target);
        }

        float total_val = 0;

        for(int x = 0; x < neurons[nrLayers - 1]; x++)
        {
            float val = relu(weights[nrLayers][x][0] * vals[nrLayers][x] + biases[nrLayers][0]);
            total_val += val;
        }

        total_val = sigmoid(total_val);

        float cost_res = cost(total_val, target);

        log("Epoch " + (i+1).ToString() + " terminat ----- " + DateTime.Now.ToString() + "\n");
        log("Eroare epoch ---> " + (cost_res<1?"0":"") + cost_res.ToString("##.##") + "\n\n\n");

        float cost_der = cost_d(total_val, target);

        for (int a = 0; a < weights.Count; a++)
        {
            for (int b = 0; b < weights[a].Count; b++)
            {
                for (int c = 0; c < weights[a][b].Count; c++)
                {
                    weights[a][b][c]-=cost_der*learning_rate * sigmoid_d(weights[a][b][c]);
                }
            }
        }

        for (int a = 0; a < nrLayers; a++)
        {
            for (int b = 0; b < neurons[a]; b++)
            {
                biases[a][b] -= cost_der * learning_rate;
            }
        }

    }
    hasTrained = true;
    testBut.Enabled = hasTrained;
    MessageBox.Show("Antrenament complet!");

    SavePrompt sp = new SavePrompt();
    sp.Show();
}

</code>```

How can it be changed to optimize the weights, biases and loss function? For now, when I try to debug, the weights are changing, but it is the same value for the loss function.

答: I solved it by using AForge.NET: link</p>

Body:
I have a neural network in visual studio. for the loss function I am using a basic cost function (pred-target)**2 and after I finish an epoch I optimize the parameter functions afterwards, but the algorithm doesn't work.

No matter what is my network configuration, the predictions are not write (it is the same output for all the inputs) and the loss function is not optimized. It stays the same through all the epochs.

void calc_lyr(int x, int y, int idx, float target) // thus function calculates the neuron value based on the previous layer
{
    if (x == -1 || y == 0) // if its the first layer, get the data from input nodes
    {
        for (int i = 0; i < neurons[y]; i++)
        {
            float sum = 0;

            for (int j = 0; j < inputTypes.Count; j++)
            {
                sum += weights[x+1][j][i] * training_test[idx][j];
            }
            sum = relu(sum);
            vals[y+1][i] = sum;

        }
    }
    else
    {
        for(int i = 0; i < neurons[y]; i++)
        {
            float sum = 0;

            for(int j = 0; j < neurons[x]; j++)
            {
                sum += weights[x+1][j][i] * vals[x+1][j] + biases[y][i];
            }
            sum = relu(sum);
            vals[y+1][i] = sum;
        }
    }
}

void train()
{
    log("Proces de antrenare inceput ----------------- " + DateTime.Now.ToString());

    vals = new List<List<float>>();
    weights = new List<List<List<float>>>();
    biases = new List<List<float>>();

    Random randB = new Random(DateTime.Now.Millisecond);
    Random randW = new Random(DateTime.Now.Millisecond);

    for (int i = 0; i <= nrLayers; i++)
    {
        progressEpochs.Value =(int)(((float)i * (float)nrLayers) / 100.0f);

        vals.Add(new List<float>());

        weights.Add(new List<List<float>>());
        if (i == 0)
        {
            for (int j = 0; j < inputTypes.Count; j++)
            {
                vals[i].Add(0);
            }
        }
        else
        {
            biases.Add(new List<float>());

            for (int j = 0; j < neurons[i-1]; j++)
            {
                vals[i].Add(0);

                float valB = (float)randB.NextDouble();
                biases[i-1].Add(valB - ((int)valB));
            }
        }
    }

    float valLB = (float)randB.NextDouble();

    biases.Add(new List<float>());
    biases[nrLayers].Add(valLB - ((int)valLB));

    for (int i = 0; i <= nrLayers; i++)
    {
        if (i == 0)
        {
            for (int j = 0; j < inputTypes.Count; j++)
            {
                weights[i].Add(new List<float>());

                for (int x = 0; x < neurons[i]; x++)
                {
                    float valW = (float)randW.NextDouble();
                    weights[i][j].Add(valW);
                }
            }
        }
        else if (i == nrLayers)
        {
            for (int j = 0; j < neurons[i-1]; j++) {
                weights[i].Add(new List<float>());
                weights[i][j].Add(0);
            }
        }
        else
        {
            for (int j = 0; j < neurons[i - 1]; j++)
            {
                weights[i].Add(new List<float>());

                for (int x = 0; x < neurons[i]; x++)
                {
                    float valW = (float)randW.NextDouble();
                    weights[i][j].Add(valW);
                }
            }
        }
    }

    Random rand = new Random(DateTime.Now.Millisecond);
    log("\n\n");
    for (int i = 0; i < epochs; i++)
    {
        log("Epoch " + (i + 1).ToString() + " inceput ---> " + DateTime.Now.ToString());
        int idx = rand.Next() % training_test.Count;

        float target = outputsPossible.IndexOf(training_labels[idx]);

        for (int j = 0; j < nrLayers; j++)
        {
            calc_lyr(j - 1, j, idx, target);
        }

        float total_val = 0;

        for(int x = 0; x < neurons[nrLayers - 1]; x++)
        {
            float val = relu(weights[nrLayers][x][0] * vals[nrLayers][x] + biases[nrLayers][0]);
            total_val += val;
        }

        total_val = sigmoid(total_val);

        float cost_res = cost(total_val, target);

        log("Epoch " + (i+1).ToString() + " terminat ----- " + DateTime.Now.ToString() + "\n");
        log("Eroare epoch ---> " + (cost_res<1?"0":"") + cost_res.ToString("##.##") + "\n\n\n");

        float cost_der = cost_d(total_val, target);

        for (int a = 0; a < weights.Count; a++)
        {
            for (int b = 0; b < weights[a].Count; b++)
            {
                for (int c = 0; c < weights[a][b].Count; c++)
                {
                    weights[a][b][c]-=cost_der*learning_rate * sigmoid_d(weights[a][b][c]);
                }
            }
        }

        for (int a = 0; a < nrLayers; a++)
        {
            for (int b = 0; b < neurons[a]; b++)
            {
                biases[a][b] -= cost_der * learning_rate;
            }
        }

    }
    hasTrained = true;
    testBut.Enabled = hasTrained;
    MessageBox.Show("Antrenament complet!");

    SavePrompt sp = new SavePrompt();
    sp.Show();
}

How can it be changed to optimize the weights, biases and loss function? For now, when I try to debug, the weights are changing, but it is the same value for the loss function.

Body: I solved it by using AForge.NET: link


问:
Is there a way to beautify curl command in Vscode?
I've a complex curl command that I want to analyze but it's all minfied into one line. Is there a formatter that would beautify it?</p>

答: shell-format can format bash files. Assuming you put that curl command to be part of a bash script, it should work.


问:
module.exports that include all functions in a single line
This is a follow-up question to In Node.js, how do I "include" functions from my other files?

I would like to include an external js file that contains common functions for a node.js app.

From one of the answers in In Node.js, how do I "include" functions from my other files?, this can be done by

```<code>// tools.js
// ========
module.exports = {
  foo: function () {
    // whatever
  },
  bar: function () {
    // whatever
  }
};

var zemba = function () {
}
</code>```

It is inconvenient to export each and every function. Is it possible to have a one-liner that exports all functions? Something that looks like this;

```<code>module.exports = 'all functions';
</code>```

It is so much more convenient this way. It is also less buggy in case one forgets to export certain functions later.

If not a one-liner, are there simpler alternatives that make coding more convenient? I just want to include an external js file made up of common functions conveniently. Something like include <stdio.h> in C/C++.

答:
If you use ES6 you can do something like that:

function bar() {
   //bar
}

function foo() {
   //foo
}

export default { bar, foo };```

Body:
This is a follow-up question to In Node.js, how do I "include" functions from my other files?

I would like to include an external js file that contains common functions for a node.js app.

From one of the answers in In Node.js, how do I "include" functions from my other files?, this can be done by

// tools.js
// ========
module.exports = {
  foo: function () {
    // whatever
  },
  bar: function () {
    // whatever
  }
};

var zemba = function () {
}

It is inconvenient to export each and every function. Is it possible to have a one-liner that exports all functions? Something that looks like this;

module.exports = 'all functions';

It is so much more convenient this way. It is also less buggy in case one forgets to export certain functions later.

If not a one-liner, are there simpler alternatives that make coding more convenient? I just want to include an external js file made up of common functions conveniently. Something like include <stdio.h> in C/C++.


问:
Xcode 10.2.1 is not supporting ios 12.3.1 for deployment/testing purpose?
when I'm trying to deploy/test my app in a real device, I'm facing the issue. The error is in the image attached.

This is the error :

My Xcode version is 10.2.1

My IOS software version is 12.3.1

答:
Your device iOS version maybe higher than what your current xCode version can handle, thus when you try to test it has an error.

Check that you are running the latest version of xCode.

If iOS software version 12.3.1 is a beta version, you'll need to download and use the Beta version of xCode.


问:
Python Function does not return value
I'm working in Python and I wrote this simple function.  I'm getting anything returned.

```<code>def add(a, b):
    total = a + b
    return total

add(6, 3)
</code>```

I've tried installing and uninstalling the latest version.

答:
In REPL like Python interpreter or IPython, the output is evaluated and displayed in the next line when the function which returns a value is run

```<code>In [9]: def add(a, b):
   ...:     total = a + b
   ...:     return total
   ...:

In [10]: add(6,3)
Out[10]: 9
</code>```

But same doesn't happen when you run it via an IDE say PyCharm in which case you need to explicitly print the output by print

```<code>def add(a, b):
    total = a + b
    return total

print(add(6,3))
</code>```

Output then will be 9

Title: Python Function does not return value

Body:
I'm working in Python and I wrote this simple function.  I'm getting anything returned.

def add(a, b):
    total = a + b
    return total

add(6, 3)

I've tried installing and uninstalling the latest version.

Body:
In REPL like Python interpreter or IPython, the output is evaluated and displayed in the next line when the function which returns a value is run

In [9]: def add(a, b):
   ...:     total = a + b
   ...:     return total
   ...:

In [10]: add(6,3)
Out[10]: 9

But same doesn't happen when you run it via an IDE say PyCharm in which case you need to explicitly print the output by print

def add(a, b):
    total = a + b
    return total

print(add(6,3))

Output then will be 9


问:
Clip element with circles, Erase portion of div, Hole Punch Effect
I have this card layout Codepen card layout

 in which I would like to create a "hole punch effect". Where the card is missing semi-circle bits from either side, and the blurred background shows through in the background.

I have tried using pseudo elements on the card element itself and making it inherit the background to give the illusion of negative space. As well as using clip-path, but that seems to do the inverse operation of what I want. I want to keep most of the card, and just erase a portion of it. Not sure what to call this or how to search for it, any and all suggestions are much appreciated!

答:
it's a little late, but i'd like to share this solution with you:

.shape {
  width: 275px;
  height: 300px;
  position: relative;
  background-color: transparent;
}

.shape-left, .shape-right {
  width: 50%;
  height: 100%;
  position: absolute;
  overflow: hidden;
}

.circle {
    position: absolute;
    box-sizing: content-box;
    width: 50px;
    height: 50px;
    border-radius: 100%;
    border: 100vh solid white;
    top: 50%;
}

.shape-left {
  left: 0;
}

.shape-left .circle {
  left: 0;
  transform: translate(-50%, -50%);
}

.shape-right {
  right: 0;
}

.shape-right .circle {
  right: 0;
  transform: translate(50%, -50%);
}

body {
  background-image: url(https://images.pexels.com/photos/2318554/pexels-photo-2318554.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940);
  background-size: cover;
  background-position: 50% 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="shape">
  <div class="shape-left"><div class="circle"></div></div>
  <div class="shape-right"><div class="circle"></div></div>
</div></code>```

so basically what i did is the following:

create the rectangle without background

create a 'left' and a 'right' child element without background and hidden overflow both filling one half of your rectangle

give both children an element without background

style the element as a circle

align the circles inside the 'left' and 'right' element to the position you like the rectangle being 'clipped'

give the circles an oversized border (so it fills out the whole parent element) and a border color of your choice

tada **
if it is hard to understand, change the size of the border on the .circle element. this will help to understand.

Body:
it's a little late, but i'd like to share this solution with you:

.shape {
  width: 275px;
  height: 300px;
  position: relative;
  background-color: transparent;
}

.shape-left, .shape-right {
  width: 50%;
  height: 100%;
  position: absolute;
  overflow: hidden;
}

.circle {
    position: absolute;
    box-sizing: content-box;
    width: 50px;
    height: 50px;
    border-radius: 100%;
    border: 100vh solid white;
    top: 50%;
}

.shape-left {
  left: 0;
}

.shape-left .circle {
  left: 0;
  transform: translate(-50%, -50%);
}

.shape-right {
  right: 0;
}

.shape-right .circle {
  right: 0;
  transform: translate(50%, -50%);
}

body {
  background-image: url(https://images.pexels.com/photos/2318554/pexels-photo-2318554.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940);
  background-size: cover;
  background-position: 50% 50%;
}

<div class="shape">
  <div class="shape-left"><div class="circle"></div></div>
  <div class="shape-right"><div class="circle"></div></div>
</div>

so basically what i did is the following:

create the rectangle without background

create a 'left' and a 'right' child element without background and hidden overflow both filling one half of your rectangle

give both children an element without background

style the element as a circle

align the circles inside the 'left' and 'right' element to the position you like the rectangle being 'clipped'

give the circles an oversized border (so it fills out the whole parent element) and a border color of your choice

tada **
if it is hard to understand, change the size of the border on the .circle element. this will help to understand.


问:
Eliminate QWebChannel property notifier signal warnings
I'm using QWebEngineView with QWebChannel, similar to this:

```<code>class AppView(QWebEngineView):
    def __init__(self):
        QWebEngineView.__init__(self)
        self.ch = QWebChannel(self.page())
        self.page().setWebChannel(self.ch)
</code>```

Then I call:

```<code>self.ch.registerObject('app',self)
</code>```

and everything runs correctly. However, I then get log-spam like this:

...

  Property 'title'' of object 'AppView' has no notify signal and is not constant, value updates in HTML will be broken!

  Property 'url'' of object 'AppView' has no notify signal and is not constant, value updates in HTML will be broken!

  Property 'selectedText'' of object 'AppView' has no notify signal and is not constant, value updates in HTML will be broken!

  Property 'hasSelection'' of object 'AppView' has no notify signal and is not constant, value updates in HTML will be broken!

  Property 'zoomFactor'' of object 'AppView' has no notify signal and is not constant, value updates in HTML will be broken!

  ...

These seem to be the properties of the derived QWebEngineView class that have been pulled in. Is there a way to correctly derive this, or does the whole structure need to change so that I'm not pulling in QWebEngineView?

AppView has other signals and slots needed in the JS code.

答:
Disable all qt warnings:

```<code>QtCore.qInstallMessageHandler(lambda x,y,z: None)
</code>```

Feed your custom handler-function inside for detail filtration

Body:
I'm using QWebEngineView with QWebChannel, similar to this:

class AppView(QWebEngineView):
    def __init__(self):
        QWebEngineView.__init__(self)
        self.ch = QWebChannel(self.page())
        self.page().setWebChannel(self.ch)

Then I call:

self.ch.registerObject('app',self)

and everything runs correctly. However, I then get log-spam like this:

...

  Property 'title'' of object 'AppView' has no notify signal and is not constant, value updates in HTML will be broken!

  Property 'url'' of object 'AppView' has no notify signal and is not constant, value updates in HTML will be broken!

  Property 'selectedText'' of object 'AppView' has no notify signal and is not constant, value updates in HTML will be broken!

  Property 'hasSelection'' of object 'AppView' has no notify signal and is not constant, value updates in HTML will be broken!

  Property 'zoomFactor'' of object 'AppView' has no notify signal and is not constant, value updates in HTML will be broken!

  ...

These seem to be the properties of the derived QWebEngineView class that have been pulled in. Is there a way to correctly derive this, or does the whole structure need to change so that I'm not pulling in QWebEngineView?

AppView has other signals and slots needed in the JS code.

Body:
Disable all qt warnings:

QtCore.qInstallMessageHandler(lambda x,y,z: None)

Feed your custom handler-function inside for detail filtration


答:
It's returned and then discarded because the returned value is not used anywhere. If you want to see it printed, then print it:</p>

```<code>print(add(6,3))
</code>```

Title: Python Function does not return value

Body:
It's returned and then discarded because the returned value is not used anywhere. If you want to see it printed, then print it:

print(add(6,3))


问:
How to fix 'ValueError: math domain error' in python?
I am trying to write a program which calculates formula y=√x*x + 3*x - 500,
Interval is [x1;x2] and f.e x1=15, x2=25.

I tried to use Exception Handling but it didn't help.
And the code I try to use now gives me: ValueError: math domain error

```<code>import math

x1 = int(input("Enter first number:"))
x2 = int(input("Enter second number:"))
print(" x", "   y")
for x in range(x1, x2):
    formula = math.sqrt(x * x + 3 * x - 500)
    if formula < 0:
        print("square root cant be negative")
    print(x, round(formula, 2))
</code>```

The output should look like this:

```<code>x   y
15 ***
16 ***
17 ***
18 ***
19 ***
20 ***
21 2.00
22 7.07
23 9.90
24 12.17
25 14.14
</code>```

答: You have to check whether the expression is < 0 before you take the square root. Otherwise you take the sqrt of a negative number which gives you a domain error.

Body:
I am trying to write a program which calculates formula y=√x*x + 3*x - 500,
Interval is [x1;x2] and f.e x1=15, x2=25.

I tried to use Exception Handling but it didn't help.
And the code I try to use now gives me: ValueError: math domain error

import math

x1 = int(input("Enter first number:"))
x2 = int(input("Enter second number:"))
print(" x", "   y")
for x in range(x1, x2):
    formula = math.sqrt(x * x + 3 * x - 500)
    if formula < 0:
        print("square root cant be negative")
    print(x, round(formula, 2))

The output should look like this:

x   y
15 ***
16 ***
17 ***
18 ***
19 ***
20 ***
21 2.00
22 7.07
23 9.90
24 12.17
25 14.14


问:
c#.net function
```<code>namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
    }
}
</code>```

is my code...am getting error like.....Error Type or namespace definition, or end-of-file expected

..hw can i over come this error

答:
Try this:

```<code>namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The answer: " + AddNumbers(40, 2));
        }

        public static int AddNumbers(int number1, int number2)
        {
            int result = number1 + number2;
            return result;
        }
    }
}
</code>```

You nested the functions instead of making them functions of the same class.

Title: c#.net function

Body:
namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
    }
}

is my code...am getting error like.....Error Type or namespace definition, or end-of-file expected

..hw can i over come this error

Body:
Try this:

namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The answer: " + AddNumbers(40, 2));
        }

        public static int AddNumbers(int number1, int number2)
        {
            int result = number1 + number2;
            return result;
        }
    }
}

You nested the functions instead of making them functions of the same class.


问:
Insert and delete in a transaction always block the rows?
I have this table:

```<code>TableAB
{
    IDA;
    IDB;
}
</code>```

And I want to ensure that always I have the pair (ID1, ID2) and (ID2, ID1). So I am trying to use this to scripts:

To insert:

```<code>begin tran
insert into tablaAB (IDTablaA, IDTablaB) VALUES(1,2);
insert into tablaAB (IDTablaA, IDTablaB) VALUES(2,1);
commit
</code>```

To delete:

```<code>begin tran
delete tablaAB where IDTablaA = 1 and IDTablaB = 2
delete tablaAB where IDTablaA = 2 and IDTablaB = 1;
commit
</code>```

I am using two instance of Microsoft Management Studio, to run both queries, and in most of the cases, it works, I get the two rows or any of them. But sometimes, I get only one of them.

The steps are:

run the query to delete (1,2).

run the query to add (1,2).

In most of the cases, it is block until the transaction to delete both rows finishes, but in some case it can pass to the next line, to insert the second row. If this happens, then I don't have a coherence data.

But I don't know if it is because I make some mistakes in the test or in same rare cases the first query is not blocked as I expect.

Really in all cases the first insert should be block if the first delete is done?

The table is empty. So it seems that the row is blocked when I try to delete and it doesn't allow to insert the row, but I don't know if really can be some rare situations in which the row is not blocked.

Thanks.

答:
```<code>But I don't know if it is because I make some mistakes in the test or in same rare cases the first query is not blocked as I expect.

Really in all cases the first insert should be block if the first delete is done?
</code>```

It seems you are running using the READ COMMITTED isolation level. In this case, no lock is held by the DELETE session when no rows qualify so the INSERT session can proceed to insert rows. This becomes a race condition where you may end up with zero, one, or two rows. Consider this sequence that results in one row:

```<code>--session 1:
begin tran;
delete TableAB where IDTablaA = 1 and IDTablaB = 2;
--no row deleted, no lock held

--session 2:
begin tran
insert into TableAB (IDTablaA, IDTablaB) VALUES(1,2);
--row inserted, lock held
insert into TableAB (IDTablaA, IDTablaB) VALUES(2,1);
--row inserted, lock held
commit;
-- inserts committed and locks released

--session 1:
delete TableAB where IDTablaA = 2 and IDTablaB = 1;
--row deleted, lock held
commit;
--deleted committed, lock released
</code>```

If you instead use the SERIALIZABLE isolation level, the DELETE statement will hold a lock (table lock in this case due to no indexes) and block the insert session. A less restrictive key range lock will be held with an index on the column used to locate rows to be deleted.

Note that SERIALIZABLE is it is more prone to deadlocks than less restrictive isolation levels.

Body:
I have this table:

TableAB
{
    IDA;
    IDB;
}

And I want to ensure that always I have the pair (ID1, ID2) and (ID2, ID1). So I am trying to use this to scripts:

To insert:

begin tran
insert into tablaAB (IDTablaA, IDTablaB) VALUES(1,2);
insert into tablaAB (IDTablaA, IDTablaB) VALUES(2,1);
commit

To delete:

begin tran
delete tablaAB where IDTablaA = 1 and IDTablaB = 2
delete tablaAB where IDTablaA = 2 and IDTablaB = 1;
commit

I am using two instance of Microsoft Management Studio, to run both queries, and in most of the cases, it works, I get the two rows or any of them. But sometimes, I get only one of them.

The steps are:

run the query to delete (1,2).

run the query to add (1,2).

In most of the cases, it is block until the transaction to delete both rows finishes, but in some case it can pass to the next line, to insert the second row. If this happens, then I don't have a coherence data.

But I don't know if it is because I make some mistakes in the test or in same rare cases the first query is not blocked as I expect.

Really in all cases the first insert should be block if the first delete is done?

The table is empty. So it seems that the row is blocked when I try to delete and it doesn't allow to insert the row, but I don't know if really can be some rare situations in which the row is not blocked.

Thanks.

Body:
But I don't know if it is because I make some mistakes in the test or in same rare cases the first query is not blocked as I expect.

Really in all cases the first insert should be block if the first delete is done?

It seems you are running using the READ COMMITTED isolation level. In this case, no lock is held by the DELETE session when no rows qualify so the INSERT session can proceed to insert rows. This becomes a race condition where you may end up with zero, one, or two rows. Consider this sequence that results in one row:

--session 1:
begin tran;
delete TableAB where IDTablaA = 1 and IDTablaB = 2;
--no row deleted, no lock held

--session 2:
begin tran
insert into TableAB (IDTablaA, IDTablaB) VALUES(1,2);
--row inserted, lock held
insert into TableAB (IDTablaA, IDTablaB) VALUES(2,1);
--row inserted, lock held
commit;
-- inserts committed and locks released

--session 1:
delete TableAB where IDTablaA = 2 and IDTablaB = 1;
--row deleted, lock held
commit;
--deleted committed, lock released

If you instead use the SERIALIZABLE isolation level, the DELETE statement will hold a lock (table lock in this case due to no indexes) and block the insert session. A less restrictive key range lock will be held with an index on the column used to locate rows to be deleted.

Note that SERIALIZABLE is it is more prone to deadlocks than less restrictive isolation levels.


问:
for i in range(0,x+1) for j in range(0,y+1) for k in range(0,z+1) if((i+j+k))!=n print([[i,j,k]]).what is wrong with this code?
You are given three integers X,Y,Z and  representing the dimensions of a cuboid along with an integer N . You have to print a list of all possible coordinates given by (I,J,K) on a 3D grid where the sum (I+J+K)of is not equal to N . Here is my code for this question.,

```<code>x = int(input())
y = int(input())
z = int(input())
n = int(input())

for i in range(0,x+1)
for j in range(0,y+1)
for k in range(0,z+1)
if((i+j+k))!=n
print([[i,j,k]])
</code>```

this code is showing compiling error.please let me know my error and how to rectify it.

答:
You should check the syntax of python.

```<code>for i in range(0,x+1):
</code>```

You forgot the :

And make sure it's well idented:

```<code>x = int(input())
y = int(input())
z = int(input())
n = int(input())

for i in range(0,x+1):
    for j in range(0,y+1):
        for k in range(0,z+1):
            if((i+j+k)!=n):  //and you forgot the ")" as well
                print([[i,j,k]])
</code>```

Body:
You are given three integers X,Y,Z and  representing the dimensions of a cuboid along with an integer N . You have to print a list of all possible coordinates given by (I,J,K) on a 3D grid where the sum (I+J+K)of is not equal to N . Here is my code for this question.,

x = int(input())
y = int(input())
z = int(input())
n = int(input())

for i in range(0,x+1)
for j in range(0,y+1)
for k in range(0,z+1)
if((i+j+k))!=n
print([[i,j,k]])

this code is showing compiling error.please let me know my error and how to rectify it.

Body:
You should check the syntax of python.

for i in range(0,x+1):

You forgot the :

And make sure it's well idented:

x = int(input())
y = int(input())
z = int(input())
n = int(input())

for i in range(0,x+1):
    for j in range(0,y+1):
        for k in range(0,z+1):
            if((i+j+k)!=n):  //and you forgot the ")" as well
                print([[i,j,k]])


问:
How to use JSON with difficult objects
I have problem with dynamic JSON data. I don't know how to put it into my JAVA class. I need "routes" data. But i don't know what i should do with this ""2019-05-27": {...".

It is part of JSON file...

```<code>{
  "2019-05-26": {
    "lastUpdate": "2019-05-26 06:05:02",
    "routes": [
      {
        "routeId": 107,
        "agencyId": 18
      },
      {
        "routeId": 222,
        "agencyId": 22
      }
    ]
  },
  "2019-05-27": {
    "lastUpdate": "2019-05-27 06:05:02",
    "routes": [
      {
        "routeId": 33,
        "agencyId": 14
      },
      {
        "routeId": 345,
        "agencyId": 2232
      }
    ]
  }
}
</code>```

The code below doesn't work. It is not Map<String,Map<String, String>>. I think it is -

```<code>Gson gson = new Gson();

    Type mapType = new TypeToken<Map<String,Map<String, String>>>() {}.getType();
    Map<String,Map<String, String>> map = null;
    try {
        map = gson.fromJson(new FileReader("routes.json"), mapType);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
</code>```

What should I do to take this data ?

答:
Please check this line :

```<code>json = Files.lines(Paths.get("routes.json")).collect(Collectors.joining());
</code>```

this line may store null value and that's why you are getting a java.lang.NullPointerException.

Please check this by debugging. I think you will get the solution.

Title: How to use JSON with difficult objects

Body:
I have problem with dynamic JSON data. I don't know how to put it into my JAVA class. I need "routes" data. But i don't know what i should do with this ""2019-05-27": {...".

It is part of JSON file...

{
  "2019-05-26": {
    "lastUpdate": "2019-05-26 06:05:02",
    "routes": [
      {
        "routeId": 107,
        "agencyId": 18
      },
      {
        "routeId": 222,
        "agencyId": 22
      }
    ]
  },
  "2019-05-27": {
    "lastUpdate": "2019-05-27 06:05:02",
    "routes": [
      {
        "routeId": 33,
        "agencyId": 14
      },
      {
        "routeId": 345,
        "agencyId": 2232
      }
    ]
  }
}

The code below doesn't work. It is not Map<String,Map<String, String>>. I think it is -

Gson gson = new Gson();

    Type mapType = new TypeToken<Map<String,Map<String, String>>>() {}.getType();
    Map<String,Map<String, String>> map = null;
    try {
        map = gson.fromJson(new FileReader("routes.json"), mapType);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

What should I do to take this data ?

Body:
Please check this line :

json = Files.lines(Paths.get("routes.json")).collect(Collectors.joining());

this line may store null value and that's why you are getting a java.lang.NullPointerException.

Please check this by debugging. I think you will get the solution.


答:
```<code>import math
x1 = int(input("Enter first number:"))
x2 = int(input("Enter second number:"))
print(" x", "   y")
for x in range(x1, x2+1):
    formula = x * x + 3 * x - 500
    if formula < 0:
        print (x, "***")
    else:
        formula = math.sqrt(formula)
        print(x, round(formula, 2))
</code>```

Title: How to fix 'ValueError: math domain error' in python?


问:
Replace header of one column by file name
I have about 100 comma-separated text files with eight columns.

Example of two file names:

```<code>sample1_sorted_count_clean.csv
sample2_sorted_count_clean.csv
</code>```

Example of file content:

```<code>Domain,Phylum,Class,Order,Family,Genus,Species,Count
Bacteria,Proteobacteria,Alphaproteobacteria,Sphingomonadales,Sphingomonadaceae,Zymomonas,Zymomonas mobilis,0.0
Bacteria,Bacteroidetes,Flavobacteria,Flavobacteriales,Flavobacteriaceae,Zunongwangia,Zunongwangia profunda,0.0
</code>```

For each file, I would like to replace the column header "Count" by sample ID, which is contained in the first part of the file name (sample1, sample2)

In the end, the header should then look like this:

```<code>Domain,Phylum,Class,Order,Family,Genus,Species,sample1
</code>```

If I use my code, the header looks like this:

```<code>Domain,Phylum,Class,Order,Family,Genus,Species,${f%_clean.csv}
</code>```

```<code>for f in *_clean.csv; do echo ${f}; sed -e "1s/Domain,Phylum,Class,Order,Family,Genus,Species,RPMM/Domain,Phylum,Class,Order,Family,Genus,Species,${f%_clean.csv}/" ${f} > ${f%_clean.csv}_clean2.csv; done
</code>```

I also tried:

```<code>for f in *_clean.csv; do gawk -F"," '{$NF=","FILENAME}1' ${f}  > t && mv t ${f%_clean.csv}_clean2.csv; done
</code>```

In this case, "count" is replaced by the entire file name, but each row of the column contains file name now. The count values are no longer present. This is not what I want.

Do you have any ideas on what else I may try?
Thank you very much in advance!

Anna

答:
If you are ok with awk, could you please try following.

```<code>awk 'BEGIN{FS=OFS=","} FNR==1{var=FILENAME;sub(/_.*/,"",var);$NF=var} 1' *.csv
</code>```

EDIT: Since OP is asking that after 2nd underscore everything should be removed in file's name then try following.

```<code>awk 'BEGIN{FS=OFS=","} FNR==1{split(FILENAME,array,"_");$NF=array[1]"_"array[2]} 1' *.csv
</code>```

Explanation: Adding explanation for above code here.

```<code>awk '                              ##Starting awk program from here.
BEGIN{                             ##Starting BEGIN section of code from here, which will be executed before Input_file(s) are being read.
  FS=OFS=","                       ##Setting FS and OFS as comma here for all files all lines.
}                                  ##Closing BEGIN section here.
FNR==1{                            ##Checking condition if FNR==1 which means very first line is being read for Input_file then do following.
  split(FILENAME,array,"_")        ##Using split of awk out of box function by splitting FILENAME(which contains file name in it) into an array named array with delimiter _ here.
  $NF=array[1]"_"array[2]          ##Setting last field value to array 1st element underscore and then array 2nd element value in it.
}                                  ##Closing FNR==1 condition BLOCK here.
1                                  ##Mentioning 1 will print the rest of the lines for current Input_file.
' *.csv                            ##Passing all *.csv files to awk program here.
</code>```

Body:
I have about 100 comma-separated text files with eight columns.

Example of two file names:

sample1_sorted_count_clean.csv
sample2_sorted_count_clean.csv

Example of file content:

Domain,Phylum,Class,Order,Family,Genus,Species,Count
Bacteria,Proteobacteria,Alphaproteobacteria,Sphingomonadales,Sphingomonadaceae,Zymomonas,Zymomonas mobilis,0.0
Bacteria,Bacteroidetes,Flavobacteria,Flavobacteriales,Flavobacteriaceae,Zunongwangia,Zunongwangia profunda,0.0

For each file, I would like to replace the column header "Count" by sample ID, which is contained in the first part of the file name (sample1, sample2)

In the end, the header should then look like this:

Domain,Phylum,Class,Order,Family,Genus,Species,sample1

If I use my code, the header looks like this:

Domain,Phylum,Class,Order,Family,Genus,Species,${f%_clean.csv}

for f in *_clean.csv; do echo ${f}; sed -e "1s/Domain,Phylum,Class,Order,Family,Genus,Species,RPMM/Domain,Phylum,Class,Order,Family,Genus,Species,${f%_clean.csv}/" ${f} > ${f%_clean.csv}_clean2.csv; done

I also tried:

for f in *_clean.csv; do gawk -F"," '{$NF=","FILENAME}1' ${f}  > t && mv t ${f%_clean.csv}_clean2.csv; done

In this case, "count" is replaced by the entire file name, but each row of the column contains file name now. The count values are no longer present. This is not what I want.

Do you have any ideas on what else I may try?
Thank you very much in advance!

Anna

Body:
If you are ok with awk, could you please try following.

awk 'BEGIN{FS=OFS=","} FNR==1{var=FILENAME;sub(/_.*/,"",var);$NF=var} 1' *.csv

EDIT: Since OP is asking that after 2nd underscore everything should be removed in file's name then try following.

awk 'BEGIN{FS=OFS=","} FNR==1{split(FILENAME,array,"_");$NF=array[1]"_"array[2]} 1' *.csv

Explanation: Adding explanation for above code here.

awk '                              ##Starting awk program from here.
BEGIN{                             ##Starting BEGIN section of code from here, which will be executed before Input_file(s) are being read.
  FS=OFS=","                       ##Setting FS and OFS as comma here for all files all lines.
}                                  ##Closing BEGIN section here.
FNR==1{                            ##Checking condition if FNR==1 which means very first line is being read for Input_file then do following.
  split(FILENAME,array,"_")        ##Using split of awk out of box function by splitting FILENAME(which contains file name in it) into an array named array with delimiter _ here.
  $NF=array[1]"_"array[2]          ##Setting last field value to array 1st element underscore and then array 2nd element value in it.
}                                  ##Closing FNR==1 condition BLOCK here.
1                                  ##Mentioning 1 will print the rest of the lines for current Input_file.
' *.csv                            ##Passing all *.csv files to awk program here.


答:
Try to print the result:</p>

```<code>def add(a, b):
    total = a + b
    return total

print(add(6, 3))
</code>```

Title: Python Function does not return value

Body:
I'm working in Python and I wrote this simple function.  I'm getting anything returned.

def add(a, b):
    total = a + b
    return total

add(6, 3)

I've tried installing and uninstalling the latest version.

Body:
Try to print the result:

def add(a, b):
    total = a + b
    return total

print(add(6, 3))


问:
Excel stealing keyboard focus from VCL Form (in AddIn)
I have an Excel AddIn written in Delphi that has a VCL form with a TMemo on it.
When I try to enter text into the Memo the input goes to Excel instead.

When I start the form modal (ShowModal), all works fine but obviously it's not possible to work with the main excel window and the addin's window concurrently.

The issue seems to be the exact similar to this question: Modeless form cannot receive keyboard input in Excel Add-in developed by Delphi

This answer suggests to handle WM_PARENTNOTIFY so I tried the following:

```<code>TMyForm = class(TForm)
...
 procedure OnParentNotify(var Msg: TMessage); message WM_PARENTNOTIFY;
</code>```

And in that procedure tried things like SetFocus, WinApi.Windows.SetFocus(self.Handle), SetForeGroundWindows, SetActiveWindow but that doesn't appear to work.

Other suggestions I've read is to run the UI in a different thread (which is of course not possible with VCL) and to install a keyboard hook with SetWindowsHookEx. Obviously that will give us keypress events but not sure what to do with those.

I am not using 3rd party tooling such as Add-In Express but just implementing IDTExtensibility2.

EDIT: more research suggests that Office uses an interface called IMsoComponent and and IMsoComponentManager as a way of tracking the active component in the application. Visual Studio uses these as IOleComponent and IOleComponentManager.

This link and this one suggest to register a new empty IOleComponent/IMsoComponent.

EDIT: MCVE can be fetched here, it's the smallest possible Excel AddIn code that will launch a VCL Form with a TEdit on it. The edit looses keyboard focus as soon as a worksheet is active.

答:
I was having the same kind of problem. I am also implementing IDTExtensibility2 but as I am doing it on C++ I already managed to run the UI on a different thread. But anyway I was not fully happy with this solution. I would still have this problem if I wanted to use a VBA Userform as a TaskPane Window. I did try but as (I guess, didn´t check) the VBA userform will run on the native Excel Thread, just calling it on a different thread (to use as a TaskPane window) just marshalled it, didn´t mean that it was created on a different thread, so as I did try, there was this kind of problem.

I too did read and try to to handle WM_PARENTNOTIFY messages with SetFocus.. on my window but didn´t work.

This both interfaces IOleComponent and IOleComponentManager were new to me. Didn´t find the header files, but could write and implement from the descriptions at the link you shared.

How it worked for me was to register my IOleComponent  implementation on every WM_SETCURSOR e  WM_IME_SETCONTEXT at my Form Window. (I am not sure if this is exactly the best messages, but did work for me)  and Revoke the component on every click back at EXCEL7 window.

The MSOCRINFO options I used to register was msocrfPreTranslateKey and msocadvfModal.

Hope that with this answer I will not receive tons of criticism.  I know that it is a very specific issue, the question was with a -1 status when I read it, but was exactly what I needed to finish with this point. So I am just trying to be honest and share back something.

Body:
I have an Excel AddIn written in Delphi that has a VCL form with a TMemo on it.
When I try to enter text into the Memo the input goes to Excel instead.

When I start the form modal (ShowModal), all works fine but obviously it's not possible to work with the main excel window and the addin's window concurrently.

The issue seems to be the exact similar to this question: Modeless form cannot receive keyboard input in Excel Add-in developed by Delphi

This answer suggests to handle WM_PARENTNOTIFY so I tried the following:

TMyForm = class(TForm)
...
 procedure OnParentNotify(var Msg: TMessage); message WM_PARENTNOTIFY;

And in that procedure tried things like SetFocus, WinApi.Windows.SetFocus(self.Handle), SetForeGroundWindows, SetActiveWindow but that doesn't appear to work.

Other suggestions I've read is to run the UI in a different thread (which is of course not possible with VCL) and to install a keyboard hook with SetWindowsHookEx. Obviously that will give us keypress events but not sure what to do with those.

I am not using 3rd party tooling such as Add-In Express but just implementing IDTExtensibility2.

EDIT: more research suggests that Office uses an interface called IMsoComponent and and IMsoComponentManager as a way of tracking the active component in the application. Visual Studio uses these as IOleComponent and IOleComponentManager.

This link and this one suggest to register a new empty IOleComponent/IMsoComponent.

EDIT: MCVE can be fetched here, it's the smallest possible Excel AddIn code that will launch a VCL Form with a TEdit on it. The edit looses keyboard focus as soon as a worksheet is active.