问:
How to fix keyboard from hiding input fields in React Native
I’m setting up a new component,
and the keyboard covers the fields

This is for a new component

```<code><KeyboardAwareScrollView enableOnAndroid={true} extraScrollHeight={50} enableAutomaticScroll={true}>
                    <View style={{ paddingHorizontal: 20 }}>

                        <View>
                            <FloatingLabelInput
                                onRef={(ref) => {
                                    this.inputs['firstName'] = ref
                                }}
                                onSubmitEditing={() => {
                                    this.focusNextField('lastName')
                                }}
                                label={i18n.t('t_driver_registration_first_name_label')}
                                onChangeText={(text) => this.onChangeInputText('firstName', text)}
                                keyboardType='default'
                                maxLength={20}
                                value={form.firstName}
                                labelStyle={Style.inputLabel}
                                basicColor={GStyle.GREEN}
                                inputTextColor={Color(GStyle.BLACK).alpha(.7)}
                                editable={mode !== DriverFormMode.EDIT}
                            />
</code>```

I expect the keyboard will not cover my fields.

答:
Wrap your view in this to scroll automatically on input focus. Do:

```<code><KeyboardAvoidingView style={{ flex: 1, flexDirection: 'column',justifyContent: 'center',}} behavior="padding" enabled   keyboardVerticalOffset={100}>
    <ScrollView>
        <View style={Styles.row}>
                //your view
        </View>
    </ScrollView>
</KeyboardAvoidingView>
</code>```

<View style={Styles.row}> This is just a Stylesheet e.g. Create a new StyleSheet:

```<code>const Styles = StyleSheet.create({
  row: {
    borderRadius: 4,
    borderWidth: 0.5,
    borderColor: '#d6d7da',
  },
  title: {
    fontSize: 19,
    fontWeight: 'bold',
  },
  activeTitle: {
    color: 'red',
  },
});
</code>```

Use a StyleSheet:

```<code><View style={Styles.row}>
  <Text style={[Styles.title, this.props.isActive && styles.activeTitle]} />
</View>
</code>```

Body:
I’m setting up a new component,
and the keyboard covers the fields

This is for a new component

<KeyboardAwareScrollView enableOnAndroid={true} extraScrollHeight={50} enableAutomaticScroll={true}>
                    <View style={{ paddingHorizontal: 20 }}>

                        <View>
                            <FloatingLabelInput
                                onRef={(ref) => {
                                    this.inputs['firstName'] = ref
                                }}
                                onSubmitEditing={() => {
                                    this.focusNextField('lastName')
                                }}
                                label={i18n.t('t_driver_registration_first_name_label')}
                                onChangeText={(text) => this.onChangeInputText('firstName', text)}
                                keyboardType='default'
                                maxLength={20}
                                value={form.firstName}
                                labelStyle={Style.inputLabel}
                                basicColor={GStyle.GREEN}
                                inputTextColor={Color(GStyle.BLACK).alpha(.7)}
                                editable={mode !== DriverFormMode.EDIT}
                            />

I expect the keyboard will not cover my fields.

Body:
Wrap your view in this to scroll automatically on input focus. Do:

<KeyboardAvoidingView style={{ flex: 1, flexDirection: 'column',justifyContent: 'center',}} behavior="padding" enabled   keyboardVerticalOffset={100}>
    <ScrollView>
        <View style={Styles.row}>
                //your view
        </View>
    </ScrollView>
</KeyboardAvoidingView>

<View style={Styles.row}> This is just a Stylesheet e.g. Create a new StyleSheet:

const Styles = StyleSheet.create({
  row: {
    borderRadius: 4,
    borderWidth: 0.5,
    borderColor: '#d6d7da',
  },
  title: {
    fontSize: 19,
    fontWeight: 'bold',
  },
  activeTitle: {
    color: 'red',
  },
});

Use a StyleSheet:

<View style={Styles.row}>
  <Text style={[Styles.title, this.props.isActive && styles.activeTitle]} />
</View>


来源: stackexchange

问:
Readiness probe failed: HTTP probe failed with statuscode: 503 in ISTIO
I have deployed istio service mesh in my AKS cluster. i have ui and backend services both configured in istio for service communication. i am able to invoke backend service through istio, and no problem in accessing my backend services.

But i am facing issue in test-ui pod, when i see pod status

```<code>NAME                                  READY   STATUS    RESTARTS   AGE
Test-api-deployment-59f6c6f67-ml4xm   2/2     Running   0          3d21h
Test-ui-deployment-b54fd89b-2ndsv     1/2     Running   0          52m
</code>```

In above status, my ui pod , one of my istio container is not in ready state to serve my request.. when i looked into the container state, i get below error..

```<code>Warning  Unhealthy  2m24s (x299 over 12m)  kubelet, aks-wmsdevk8s-25812762-4
Readiness probe failed: HTTP probe failed with statuscode: 503
</code>```

i see it an open issue issue in github.. is there any workaround for this...

EDIT

my istio version

version.BuildInfo{Version:"1.1.5",
  GitRevision:"9b6d31b74d1c0cc9358cc82d395b53f71393326b", User:"root",
  Host:"3e29fde4-6c3f-11e9-b00d-0a580a2c0205", GolangVersion:"go1.10.4",
  DockerHub:"docker.io/istio", BuildStatus:"Clean",
  GitTag:"1.1.4-10-g9b6d31b"}

```<code>istio proxy version -   Image:         docker.io/istio/proxyv2:1.1.2
</code>```

答:
In my case, I tested on OpenShift 3.11 with ServiceMesh TP 0.10 and used ovs-multitenant(SDN plugin) so inter-projects communications were blocked. I had same problem and set netid of istio-system namespace to "0", then problem was solved.
Check network communications between your application's namespace and namespace which has istio-sidecar-injector. </p>

ContentLicense: CC BY-SA 4.0

Body:
I have deployed istio service mesh in my AKS cluster. i have ui and backend services both configured in istio for service communication. i am able to invoke backend service through istio, and no problem in accessing my backend services.

But i am facing issue in test-ui pod, when i see pod status

NAME                                  READY   STATUS    RESTARTS   AGE
Test-api-deployment-59f6c6f67-ml4xm   2/2     Running   0          3d21h
Test-ui-deployment-b54fd89b-2ndsv     1/2     Running   0          52m

In above status, my ui pod , one of my istio container is not in ready state to serve my request.. when i looked into the container state, i get below error..

Warning  Unhealthy  2m24s (x299 over 12m)  kubelet, aks-wmsdevk8s-25812762-4
Readiness probe failed: HTTP probe failed with statuscode: 503

i see it an open issue issue in github.. is there any workaround for this...

EDIT

my istio version

version.BuildInfo{Version:"1.1.5",
  GitRevision:"9b6d31b74d1c0cc9358cc82d395b53f71393326b", User:"root",
  Host:"3e29fde4-6c3f-11e9-b00d-0a580a2c0205", GolangVersion:"go1.10.4",
  DockerHub:"docker.io/istio", BuildStatus:"Clean",
  GitTag:"1.1.4-10-g9b6d31b"}

istio proxy version -   Image:         docker.io/istio/proxyv2:1.1.2


问:
Is there a reason why not to use link-time optimization (LTO)?
GCC, MSVC, LLVM, and probably other toolchains have support for link-time (whole program) optimization to allow optimization of calls among compilation units.

Is there a reason not to enable this option when compiling production software?

答:
Apart from to this,

Consider a typical example from embedded system,

```<code>void function1(void) { /*Do something*/} //located at address 0x1000
void function2(void) { /*Do something*/} //located at address 0x1100
void function3(void) { /*Do something*/} //located at address 0x1200
</code>```

With predefined addressed functions can be called through relative addresses like below,

```<code> (*0x1000)(); //expected to call function2
 (*0x1100)(); //expected to call function2
 (*0x1200)(); //expected to call function3
</code>```

LTO can lead to unexpected behavior.

updated:

In automotive embedded SW development,Multiple parts of SW are compiled and flashed on to a separate sections.
Boot-loader, Application/s, Application-Configurations are independently flash-able units. Boot-loader has special capabilities to update Application and Application-configuration. At every power-on cycle boot-loader ensures the SW application and application-configuration's compatibility and consistence via Hard-coded location for SW-Versions and CRC and many more parameters. Linker-definition files are used to hard-code the variable location and some function location.

Body:
Apart from to this,

Consider a typical example from embedded system,

void function1(void) { /*Do something*/} //located at address 0x1000
void function2(void) { /*Do something*/} //located at address 0x1100
void function3(void) { /*Do something*/} //located at address 0x1200

With predefined addressed functions can be called through relative addresses like below,

 (*0x1000)(); //expected to call function2
 (*0x1100)(); //expected to call function2
 (*0x1200)(); //expected to call function3

LTO can lead to unexpected behavior.

updated:

In automotive embedded SW development,Multiple parts of SW are compiled and flashed on to a separate sections.
Boot-loader, Application/s, Application-Configurations are independently flash-able units. Boot-loader has special capabilities to update Application and Application-configuration. At every power-on cycle boot-loader ensures the SW application and application-configuration's compatibility and consistence via Hard-coded location for SW-Versions and CRC and many more parameters. Linker-definition files are used to hard-code the variable location and some function location.


问:
Uncaught TypeError: Cannot read property 'class function' of undefined in reactjs
Error: Uncaught TypeError: Cannot read property 'manageChange' of undefined

I have bound the method to "this" as well. I have even tried the arrow function format to define "manageChange". It still does not work.

Please help out with identifying the issue?
Code:

```<code> class App extends React.Component {
  constructor() {
    super();
    this.state = { todos: TodoData };
    this.manageChange = this.manageChange.bind(this);
  }

  manageChange(id) {
    console.log(id);
  }

  render() {
    const todoItems = this.state.todos.map(function (item) {
      return (<TodoItem key={item.id} items={item}
        handleChange={this.manageChange} />);
    }
    );
    return
    (
      <div className="app">
        {todoItems}
      </div>
    );
  }
}
</code>```

答:
The error is not in the definition of your manageChange function. It is instead in the below code

```<code>const todoItems=this.state.todos.map(function(item)
                {
                   return (<TodoItem key={item.id} items={item}
                    handleChange={this.manageChange}/>);
                }
                );
</code>```

You should change it to below and use arrow function instead like this

```<code>const todoItems=this.state.todos.map((item) =>
                {
                   return (<TodoItem key={item.id} items={item}
                    handleChange={this.manageChange}/>);
                }
                );
</code>```

Please note the difference in arrow function and normal function. The reference in the arrow functions is passed down to the children.

So when you define it like this; this keyword is passed as an reference of the class to this.manageChange and is not undefined.

Body:
Error: Uncaught TypeError: Cannot read property 'manageChange' of undefined

I have bound the method to "this" as well. I have even tried the arrow function format to define "manageChange". It still does not work.

Please help out with identifying the issue?
Code:

 class App extends React.Component {
  constructor() {
    super();
    this.state = { todos: TodoData };
    this.manageChange = this.manageChange.bind(this);
  }

  manageChange(id) {
    console.log(id);
  }

  render() {
    const todoItems = this.state.todos.map(function (item) {
      return (<TodoItem key={item.id} items={item}
        handleChange={this.manageChange} />);
    }
    );
    return
    (

        {todoItems}

    );
  }
}

Body:
The error is not in the definition of your manageChange function. It is instead in the below code

const todoItems=this.state.todos.map(function(item)
                {
                   return (<TodoItem key={item.id} items={item}
                    handleChange={this.manageChange}/>);
                }
                );

You should change it to below and use arrow function instead like this

const todoItems=this.state.todos.map((item) =>
                {
                   return (<TodoItem key={item.id} items={item}
                    handleChange={this.manageChange}/>);
                }
                );

Please note the difference in arrow function and normal function. The reference in the arrow functions is passed down to the children.

So when you define it like this; this keyword is passed as an reference of the class to this.manageChange and is not undefined.


问:
Kubernetes not pulling image from private registry
I am trying to deploy an image from my private registry (harbor) to my Kubernetes environment. The registry was set up successfully and already contains my image.

To give context this is my deployment file:

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    name: sps-app
  name: sps-app
spec:
  replicas: 1
  template:
    metadata:
      labels:
        name: sps-app
    spec:
      containers:
      - image: repo-harbor.test.com/sps_project/spsapp:23
        env:
        - name: MONGODB_URL
          value: "mongodb://mongo.default.svc.cluster.local:27017/user"
        name: sps-app
        ports:
        - containerPort: 4000
          name: sps-app
      imagePullSecrets:
      - name: harbor
</code>```

I already had create my harbor secret using the below command

```<code>kubectl create secret docker-registry harbor \
--docker-server=https://repo-harbor.test.com \
--docker-username=admin \
--docker-password='xxxxxx!'
</code>```

However, when I do a kubectl apply -f of my deployment, it always goes into an image pull backoff.

Upon further investigation, I checked the logs of the pod and it states there is a x509 certification error.

Kubernetes events:

```<code>Events:
  Type     Reason          Age              From                                           Message
  ----     ------          ----             ----                                           -------
  Normal   Scheduled       3m               default-scheduler                              Successfully assigned default/private-image-test-1 to df56bd02-5e0e-4644-a565-c233ac2404fe
  Normal   Pulling         2m (x3 over 3m)  kubelet, df56bd02-5e0e-4644-a565-c233ac2404fe  pulling image "jur01-harbor.acepod.com/sps_project/spsapp:2"
  Warning  Failed          2m (x3 over 3m)  kubelet, df56bd02-5e0e-4644-a565-c233ac2404fe  Failed to pull image "jur01-harbor.acepod.com/sps_project/spsapp:2": rpc error: code = Unknown desc = Error response from daemon: Get https://jur01-harbor.acepod.com/v2/: x509: certificate signed by unknown authority
  Warning  Failed          2m (x3 over 3m)  kubelet, df56bd02-5e0e-4644-a565-c233ac2404fe  Error: ErrImagePull
  Warning  Failed          2m (x4 over 3m)  kubelet, df56bd02-5e0e-4644-a565-c233ac2404fe  Error: ImagePullBackOff
  Normal   SandboxChanged  2m (x7 over 3m)  kubelet, df56bd02-5e0e-4644-a565-c233ac2404fe  Pod sandbox changed, it will be killed and re-created.
  Normal   BackOff         2m (x5 over 3m)  kubelet, df56bd02-5e0e-4644-a565-c233ac2404fe  Back-off pulling image "jur01-harbor.acepod.com/sps_project/spsapp:2"
</code>```

At this point, I'm not sure how to resolve this. Would anyone how to resolve this?

答:
Root cause

The image registry at jur01-harbor.acepod.com uses a self-signed certificate, which Docker does not trust.

Solution

Copy the custom CA certificate presented by that image registry to all your Kubernetes nodes', in a directory called /etc/docker/certs.d/jur01-harbor.acepod.com/.

Reference: Docker docs / Test an insecure registry.

Body:
I am trying to deploy an image from my private registry (harbor) to my Kubernetes environment. The registry was set up successfully and already contains my image.

To give context this is my deployment file:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    name: sps-app
  name: sps-app
spec:
  replicas: 1
  template:
    metadata:
      labels:
        name: sps-app
    spec:
      containers:
      - image: repo-harbor.test.com/sps_project/spsapp:23
        env:
        - name: MONGODB_URL
          value: "mongodb://mongo.default.svc.cluster.local:27017/user"
        name: sps-app
        ports:
        - containerPort: 4000
          name: sps-app
      imagePullSecrets:
      - name: harbor

I already had create my harbor secret using the below command

kubectl create secret docker-registry harbor \
--docker-server=https://repo-harbor.test.com \
--docker-username=admin \
--docker-password='xxxxxx!'

However, when I do a kubectl apply -f of my deployment, it always goes into an image pull backoff.

Upon further investigation, I checked the logs of the pod and it states there is a x509 certification error.

Kubernetes events:

Events:
  Type     Reason          Age              From                                           Message
  ----     ------          ----             ----                                           -------
  Normal   Scheduled       3m               default-scheduler                              Successfully assigned default/private-image-test-1 to df56bd02-5e0e-4644-a565-c233ac2404fe
  Normal   Pulling         2m (x3 over 3m)  kubelet, df56bd02-5e0e-4644-a565-c233ac2404fe  pulling image "jur01-harbor.acepod.com/sps_project/spsapp:2"
  Warning  Failed          2m (x3 over 3m)  kubelet, df56bd02-5e0e-4644-a565-c233ac2404fe  Failed to pull image "jur01-harbor.acepod.com/sps_project/spsapp:2": rpc error: code = Unknown desc = Error response from daemon: Get https://jur01-harbor.acepod.com/v2/: x509: certificate signed by unknown authority
  Warning  Failed          2m (x3 over 3m)  kubelet, df56bd02-5e0e-4644-a565-c233ac2404fe  Error: ErrImagePull
  Warning  Failed          2m (x4 over 3m)  kubelet, df56bd02-5e0e-4644-a565-c233ac2404fe  Error: ImagePullBackOff
  Normal   SandboxChanged  2m (x7 over 3m)  kubelet, df56bd02-5e0e-4644-a565-c233ac2404fe  Pod sandbox changed, it will be killed and re-created.
  Normal   BackOff         2m (x5 over 3m)  kubelet, df56bd02-5e0e-4644-a565-c233ac2404fe  Back-off pulling image "jur01-harbor.acepod.com/sps_project/spsapp:2"

At this point, I'm not sure how to resolve this. Would anyone how to resolve this?


问:
Spring @cacheable how to refresh cache 12am?
I would like to refresh the cache everyday 12am or the cache expired at 12am. I had check the available methods in net.sf.ehcache.config.CacheConfiguration, but these methods i.e. timeToIdleSeconds, timeToLiveSeconds seem like not what I want. May I know how to achieve this?

Edit 1:

Here is how I use @Cacheable.

```<code>@Override
@Cacheable(value = "cacheName")
public Object retrieveConfigurations() {
    ...
}
</code>```

答:
You can use @Scheduled:

```<code>@Scheduled(cron = "<cron expression>")
@CacheEvict(value = "<cache name>")
public void clearCache() {
}

</code>```

Body:
I would like to refresh the cache everyday 12am or the cache expired at 12am. I had check the available methods in net.sf.ehcache.config.CacheConfiguration, but these methods i.e. timeToIdleSeconds, timeToLiveSeconds seem like not what I want. May I know how to achieve this?

Edit 1:

Here is how I use @Cacheable.

@Override
@Cacheable(value = "cacheName")
public Object retrieveConfigurations() {
    ...
}

Body:
You can use @Scheduled:

@Scheduled(cron = "<cron expression>")
@CacheEvict(value = "<cache name>")
public void clearCache() {
}


问:
How to do case insensitive string comparison?
How do I perform case insensitive string comparison in JavaScript?</p>

答:
Convert both to lower string (only once for performance reasons) and compare them with inline ternary operator:</p>
```<code>function strcasecmp(s1,s2){
    s1=(s1+'').toLowerCase();
    s2=(s2+'').toLowerCase();
    return s1>s2?1:(s1<s2?-1:0);
}
</code>```

Body:
Convert both to lower string (only once for performance reasons) and compare them with inline ternary operator:

function strcasecmp(s1,s2){
    s1=(s1+'').toLowerCase();
    s2=(s2+'').toLowerCase();
    return s1>s2?1:(s1<s2?-1:0);
}


问:
Obtaining a powerset of a set in Java
The powerset of {1, 2, 3} is:

{{}, {2}, {3}, {2, 3}, {1, 2}, {1, 3}, {1, 2, 3}, {1}}

Let's say I have a Set in Java:

```<code>Set<Integer> mySet = new HashSet<Integer>();
mySet.add(1);
mySet.add(2);
mySet.add(3);
Set<Set<Integer>> powerSet = getPowerset(mySet);
</code>```

How do I write the function getPowerset, with the best possible order of complexity?
(I think it might be O(2^n).)

答:
I was looking for a solution that wasn't as huge as the ones posted here. This targets Java 7, so it will require a handful of pastes for versions 5 and 6.

```<code>Set<Set<Object>> powerSetofNodes(Set<Object> orig) {
    Set<Set<Object>> powerSet = new HashSet<>(),
        runSet = new HashSet<>(),
        thisSet = new HashSet<>();

    while (powerSet.size() < (Math.pow(2, orig.size())-1)) {
        if (powerSet.isEmpty()) {
            for (Object o : orig) {
                Set<Object> s = new TreeSet<>();
                s.add(o);
                runSet.add(s);
                powerSet.add(s);
            }
            continue;
        }
        for (Object o : orig) {
            for (Set<Object> s : runSet) {
                Set<Object> s2 = new TreeSet<>();
                s2.addAll(s);
                s2.add(o);
                powerSet.add(s2);
                thisSet.add(s2);
            }
        }
        runSet.clear();
        runSet.addAll(thisSet);
        thisSet.clear();
    }
    powerSet.add(new TreeSet());
    return powerSet;
</code>```

Here's some example code to test:

```<code>Set<Object> hs = new HashSet<>();
hs.add(1);
hs.add(2);
hs.add(3);
hs.add(4);
for(Set<Object> s : powerSetofNodes(hs)) {
    System.out.println(Arrays.toString(s.toArray()));
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Obtaining a powerset of a set in Java

Body:
The powerset of {1, 2, 3} is:

{{}, {2}, {3}, {2, 3}, {1, 2}, {1, 3}, {1, 2, 3}, {1}}

Let's say I have a Set in Java:

Set<Integer> mySet = new HashSet<Integer>();
mySet.add(1);
mySet.add(2);
mySet.add(3);
Set<Set<Integer>> powerSet = getPowerset(mySet);

How do I write the function getPowerset, with the best possible order of complexity?
(I think it might be O(2^n).)

Body:
I was looking for a solution that wasn't as huge as the ones posted here. This targets Java 7, so it will require a handful of pastes for versions 5 and 6.

Set<Set<Object>> powerSetofNodes(Set<Object> orig) {
    Set<Set<Object>> powerSet = new HashSet<>(),
        runSet = new HashSet<>(),
        thisSet = new HashSet<>();

    while (powerSet.size() < (Math.pow(2, orig.size())-1)) {
        if (powerSet.isEmpty()) {
            for (Object o : orig) {
                Set<Object> s = new TreeSet<>();
                s.add(o);
                runSet.add(s);
                powerSet.add(s);
            }
            continue;
        }
        for (Object o : orig) {
            for (Set<Object> s : runSet) {
                Set<Object> s2 = new TreeSet<>();
                s2.addAll(s);
                s2.add(o);
                powerSet.add(s2);
                thisSet.add(s2);
            }
        }
        runSet.clear();
        runSet.addAll(thisSet);
        thisSet.clear();
    }
    powerSet.add(new TreeSet());
    return powerSet;

Here's some example code to test:

Set<Object> hs = new HashSet<>();
hs.add(1);
hs.add(2);
hs.add(3);
hs.add(4);
for(Set<Object> s : powerSetofNodes(hs)) {
    System.out.println(Arrays.toString(s.toArray()));
}


问:
MySQL load and delete on same PHP page
I am trying to load data from MySQL and then display the results. I would like be able to delete the associated record as well.

```<code><?php
include 'conn.php';

$sql = "SELECT * FROM Reviews LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<h1> " . $row["rTitle"]. " </h1>" . $row["rText"]. "<br> <a href="delete.php?id={$row['id']}">Delete</a>";
}
} else {
echo "0 results";
}

$id = $_GET['rID'];
mysql_query("DELETE FROM Reviews WHERE id = {$id}");

$conn->close();

?>
</code>```

I have a problem with this line:

```<code>echo "<h1> " . $row["rTitle"]. " </h1>" . $row["rText"]. "<br> <a href="delete.php?id={$row['id']}">Delete</a>";
</code>```

Error: syntax error, unexpected 'delete' (T_STRING), expecting ',' or ';

What am I doing wrong? Thank you.

Title: MySQL load and delete on same PHP page

Body:
I am trying to load data from MySQL and then display the results. I would like be able to delete the associated record as well.

<?php
include 'conn.php';

$sql = "SELECT * FROM Reviews LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
 " . $row["rTitle"]. "
" . $row["rText"]. "
 Delete";
}
} else {
echo "0 results";
}

$id = $_GET['rID'];
mysql_query("DELETE FROM Reviews WHERE id = {$id}");

$conn->close();

?>

I have a problem with this line:

echo "
 " . $row["rTitle"]. "
" . $row["rText"]. "
 Delete";

Error: syntax error, unexpected 'delete' (T_STRING), expecting ',' or ';

What am I doing wrong? Thank you.

Body: echo '<h1>'.$row["rTitle"].'</h1>'.$row["rText"].'<br><a href="delete.php?id='.$row['id'].'">Delete</a>';


问:
How do I add image overlays to an MKMapView?
----------UPDATED------------

original question at the bottom

I've gotten pretty far, and I have this now:

```<code>class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet var mapView: MKMapView!

    var locationManager: CLLocationManager!
    var mapOverlay: MKOverlay!

    override func viewDidLoad() {
        super.viewDidLoad()

        var points = [CLLocationCoordinate2D(latitude: -29.8122, longitude: 148.6351),
                      CLLocationCoordinate2D(latitude: -27.9307, longitude: 148.6351),
                      CLLocationCoordinate2D(latitude: -27.9307, longitude: 150.9909),
                      CLLocationCoordinate2D(latitude: -29.8122, longitude: 150.9909)]
        let tile = MKPolygon(coordinates: &points, count: points.count)
        tile.title = "zurich"
        mapView.addOverlay(tile)

        //Setup our Location Manager
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()

        //Setup our Map View
        mapView.delegate = self
        mapView.mapType = MKMapType.satellite
        mapView.showsUserLocation = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // mapView delegate function
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolygonRenderer(overlay: overlay)
        renderer.fillColor = UIColor.red
        return renderer
    }
}

</code>```

I now need to know how to replace the renderer.fillColor = UIColor.red with something that will display my image.
Thanks once again

----- original question ------

So, I'm new to Swift and MapKit and I want to add a simple image overlay on top of an MKMapView. I've found a few answers, but they're all confusing, and they are all for Swift 3 and earlier.

I've found that a delegate for the map view is needed, is that a file?
I have already created a map view using the main view controller.

This is what I've done so far (this is in the ViewController.swift file):

```<code>import UIKit
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate
{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    }

    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib

        let location = CLLocationCoordinate2D(latitude: 47.457925,
                                              longitude: 8.548466)

        let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
        let region = MKCoordinateRegion(center: location, span: span)
        mapView.setRegion(region, animated: true)

    }

}

</code>```

Thank you and I hope you can help!

答:
There are a lot of way to embed image into your maps.

Annotation Views

Callouts

Custom Map Tile

Explain your need more, and maybe we can help better to how to get there.

You are adding overlay over the map. We want to change with specific map tile.

```<code>func createLocalUrl(forImageNamed name: String) -> URL? {

    let fileManager = FileManager.default
    let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
    let url = cacheDirectory.appendingPathComponent("\(name).png")

    guard fileManager.fileExists(atPath: url.path) else {
        guard
            let image = UIImage(named: name),
            let data = image.pngData()
            else { return nil }

        fileManager.createFile(atPath: url.path, contents: data, attributes: nil)
        return url
    }

    return url
}

func setupTiles() {
    let url = createLocalUrl(forImageNamed: "yourImageName")
    let template = url?.absoluteString
    let overlay = MKTileOverlay(urlTemplate: template)
    overlay.canReplaceMapContent = true
    self.tileOverlay = overlay
    mapView.addOverlay(overlay)
    self.tileRenderer = MKTileOverlayRenderer(tileOverlay: overlay)
}

func isInDesiredArea(middlePoint: MKMapPoint) -> Bool {

    //mapView has convert function which converts CGPoint ->
    //CLLocationCoordinate2D and vice versa Use this function and,
    //Your polygon has boundingMapRect which has contains function.
    //Also your map has func mapView(_ mapView: MKMapView,
    //regionDidChangeAnimated animated: Bool) which runs whenever region changes..
    return myBoundsPolygon.boundingMapRect.hasContain(middlePoint)

}

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
 //Convert middle point of your view to CLLocationCoordinate2D
 //Convert your coordinate to MKMapPoint
 if isInDesiredArea(middlePoint: point) {
     setupTiles()
 }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    ....
if overlay is MKTileOverlay {
    return tileRenderer
}
</code>```

Body:
----------UPDATED------------

original question at the bottom

I've gotten pretty far, and I have this now:

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet var mapView: MKMapView!

    var locationManager: CLLocationManager!
    var mapOverlay: MKOverlay!

    override func viewDidLoad() {
        super.viewDidLoad()

        var points = [CLLocationCoordinate2D(latitude: -29.8122, longitude: 148.6351),
                      CLLocationCoordinate2D(latitude: -27.9307, longitude: 148.6351),
                      CLLocationCoordinate2D(latitude: -27.9307, longitude: 150.9909),
                      CLLocationCoordinate2D(latitude: -29.8122, longitude: 150.9909)]
        let tile = MKPolygon(coordinates: &points, count: points.count)
        tile.title = "zurich"
        mapView.addOverlay(tile)

        //Setup our Location Manager
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()

        //Setup our Map View
        mapView.delegate = self
        mapView.mapType = MKMapType.satellite
        mapView.showsUserLocation = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // mapView delegate function
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolygonRenderer(overlay: overlay)
        renderer.fillColor = UIColor.red
        return renderer
    }
}

I now need to know how to replace the renderer.fillColor = UIColor.red with something that will display my image.
Thanks once again

----- original question ------

So, I'm new to Swift and MapKit and I want to add a simple image overlay on top of an MKMapView. I've found a few answers, but they're all confusing, and they are all for Swift 3 and earlier.

I've found that a delegate for the map view is needed, is that a file?
I have already created a map view using the main view controller.

This is what I've done so far (this is in the ViewController.swift file):

import UIKit
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate
{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    }

    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib

        let location = CLLocationCoordinate2D(latitude: 47.457925,
                                              longitude: 8.548466)

        let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
        let region = MKCoordinateRegion(center: location, span: span)
        mapView.setRegion(region, animated: true)

    }

}

Thank you and I hope you can help!

Body:
There are a lot of way to embed image into your maps.

Annotation Views

Callouts

Custom Map Tile

Explain your need more, and maybe we can help better to how to get there.

You are adding overlay over the map. We want to change with specific map tile.

func createLocalUrl(forImageNamed name: String) -> URL? {

    let fileManager = FileManager.default
    let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
    let url = cacheDirectory.appendingPathComponent("\(name).png")

    guard fileManager.fileExists(atPath: url.path) else {
        guard
            let image = UIImage(named: name),
            let data = image.pngData()
            else { return nil }

        fileManager.createFile(atPath: url.path, contents: data, attributes: nil)
        return url
    }

    return url
}

func setupTiles() {
    let url = createLocalUrl(forImageNamed: "yourImageName")
    let template = url?.absoluteString
    let overlay = MKTileOverlay(urlTemplate: template)
    overlay.canReplaceMapContent = true
    self.tileOverlay = overlay
    mapView.addOverlay(overlay)
    self.tileRenderer = MKTileOverlayRenderer(tileOverlay: overlay)
}

func isInDesiredArea(middlePoint: MKMapPoint) -> Bool {

    //mapView has convert function which converts CGPoint ->
    //CLLocationCoordinate2D and vice versa Use this function and,
    //Your polygon has boundingMapRect which has contains function.
    //Also your map has func mapView(_ mapView: MKMapView,
    //regionDidChangeAnimated animated: Bool) which runs whenever region changes..
    return myBoundsPolygon.boundingMapRect.hasContain(middlePoint)

}

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
 //Convert middle point of your view to CLLocationCoordinate2D
 //Convert your coordinate to MKMapPoint
 if isInDesiredArea(middlePoint: point) {
     setupTiles()
 }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    ....
if overlay is MKTileOverlay {
    return tileRenderer
}


问:
Should we modify a function signature for unit testing?
Suppose we have a function add() as below:

```<code>void add(int a, int b) {
    int sum=a+b;
    cout<<sum;
    sendSumToStorage(sum);
}
</code>```

This simple function adds to input values, prints the sum to the console and also sends it to some external storage (say, a file).  This is how we ideally want it in the application (meaning, we don't want it to return anything).

For purposes of unit testing, is it valid (from a design perspective) if we modify the function signature so that it returns the sum?  We could then have a test like:

```<code>bool checkAdd() {
    int res=add(3, 4);
    if(res==7) return true;
    else return false;
}
</code>```

Better yet, is this (returning a value) the only way we could unit test it?  Is there some valid way in which we could unit test the add() function without changing the function signature?

答:
Changing the design of code to improve testability is very common and generally considered as a good practice.  Obviously, not all such changes are necessarily real improvements - sometimes better solutions exist.

In your case, the code is difficult to test because it combines computations (the addition) with interactions with depended-on components (output and storing data).  In your case (as Andrei has pointed out) the function also violates the SRP, but mixing computations and interactions generally makes testing more difficult, even in cases where the SRP is not violated.

I understand, you would change the function such that it will return the computed value in addition to printing it and writing it to the storage.  This will allow you to test the computational part of the function.  The function will then, however, only be partially tested.  And, the purpose of the function will be further obfuscated.

If instead you split the function into one function doing the computation and one doing the interactions, you can thoroughly test the first with unit-testing, and use integration-testing for the other.  Again, the usefulness of this approach is independent of whether the code violates the SRP or not.

Body:
Suppose we have a function add() as below:

void add(int a, int b) {
    int sum=a+b;
    cout<<sum;
    sendSumToStorage(sum);
}

This simple function adds to input values, prints the sum to the console and also sends it to some external storage (say, a file).  This is how we ideally want it in the application (meaning, we don't want it to return anything).

For purposes of unit testing, is it valid (from a design perspective) if we modify the function signature so that it returns the sum?  We could then have a test like:

bool checkAdd() {
    int res=add(3, 4);
    if(res==7) return true;
    else return false;
}

Better yet, is this (returning a value) the only way we could unit test it?  Is there some valid way in which we could unit test the add() function without changing the function signature?


问:
JQuery full calendar, how to change view
I am using JQuery Full Calendar in my application, but I need slightly different view,
that is - in month view don't show tasks, just color days which have events associated to different color than days with no events. Then when user clicks this day in month view - a day view for this day is opened showing all the events.

Is it possible to make such adjustment?
Thank you kindly.

答:
http://webdesignandseo.net/jquery/datepicker/

You can actually do this in the normal jQuery DatePicker if you wanted that instead (go to March to see events and click for an alert). I don't know much about how the Full Calendar Plugin works but there might be something in the documentation that will help:

http://arshaw.com/fullcalendar/docs/


问:
Debug output in tests
How do I output some information in Postman tests?

```<code>console.log(tv4.error);
tests["Valid Data1"] = tv4.validate(data1, schema);
</code>```

console.log() seems to be working but I want to output my info into the same panel where my assertions go (for easier correlation):

答:
Now You have got sth called "Postman Console" To run it please type CTRL + ALT + C
For mor info see here: https://blog.getpostman.com/2016/08/26/the-postman-console/</p>

Title: Debug output in tests

Body:
How do I output some information in Postman tests?

console.log(tv4.error);
tests["Valid Data1"] = tv4.validate(data1, schema);

console.log() seems to be working but I want to output my info into the same panel where my assertions go (for easier correlation):


问:
Return different datatypes in a method in java
I have a very silly question in java. I have a main method which in turns calls a method passing one string value. But in return I need to get 3 string values. Can someone please assist?

In main method, I pass only one string value and it has to return 3 string or may be at times 2 string and one int.

```<code>public static void main(String[] args) {
        List <String> ls= cusmethod("string1");
        ls.get(0); //get string A
}

Private static string cusmethod(String test)
{
    String A = "A"+test;
    String B = "B"+test;
    String C = "C"+test;

    // Need to return all these 3 string to main method.
    return A , B, C;
}
</code>```

The method should return the 3 string values to the main method. Please advise how to achieve this. I am not sure how to return these strings to main method and how to retrieve these string in main

答:
and it has to return 3 strings or may be at times 2 strings and one int

In Java you can use Object type to represent any object, for example:

```<code>public void foo(Object obj){
    if(obj instanceof String){  // obj is a String
        System.out.println("Hello, " + (String) obj);
    }
    else if(obj instanceof Integer) {  // obj is an integer value
        // Integer is an object analog of int, because int is a primitive type
        int my_int = (Integer) obj;  // but we can implicitly convert Integer to int
        System.out.println("I doubled your integer: " + my_int * 2);
    }

}

// somewhere
foo("Steve");  // Hello, Steve
foo(2);  // I doubled your integer: 4
</code>```

So in your case you can return List of Objects:

```<code>private static List<Object> cusmethod(String test)
{
    List<String> list = new ArrayList<>();
    if(test.equals("return 3 strings")){
        list.add("A" + test);
        list.add("B" + test);
        list.add("C" + test);
    }
    else if(test.equals("return 2 strings and an int")){
        list.add("A" + test);
        list.add("B" + test);
        list.add(12345);
    }
    return list;
}

public static void main(String[] args) {
    List <Object> ls = cusmethod("string1");
    String s = (String) ls.get(0); //get string A
    int x = (Integer) ls.get(2);
}
</code>```

Body:
I have a very silly question in java. I have a main method which in turns calls a method passing one string value. But in return I need to get 3 string values. Can someone please assist?

In main method, I pass only one string value and it has to return 3 string or may be at times 2 string and one int.

public static void main(String[] args) {
        List <String> ls= cusmethod("string1");
        ls.get(0); //get string A
}

Private static string cusmethod(String test)
{
    String A = "A"+test;
    String B = "B"+test;
    String C = "C"+test;

    // Need to return all these 3 string to main method.
    return A , B, C;
}

The method should return the 3 string values to the main method. Please advise how to achieve this. I am not sure how to return these strings to main method and how to retrieve these string in main

Body:
and it has to return 3 strings or may be at times 2 strings and one int

In Java you can use Object type to represent any object, for example:

public void foo(Object obj){
    if(obj instanceof String){  // obj is a String
        System.out.println("Hello, " + (String) obj);
    }
    else if(obj instanceof Integer) {  // obj is an integer value
        // Integer is an object analog of int, because int is a primitive type
        int my_int = (Integer) obj;  // but we can implicitly convert Integer to int
        System.out.println("I doubled your integer: " + my_int * 2);
    }

}

// somewhere
foo("Steve");  // Hello, Steve
foo(2);  // I doubled your integer: 4

So in your case you can return List of Objects:

private static List<Object> cusmethod(String test)
{
    List<String> list = new ArrayList<>();
    if(test.equals("return 3 strings")){
        list.add("A" + test);
        list.add("B" + test);
        list.add("C" + test);
    }
    else if(test.equals("return 2 strings and an int")){
        list.add("A" + test);
        list.add("B" + test);
        list.add(12345);
    }
    return list;
}

public static void main(String[] args) {
    List <Object> ls = cusmethod("string1");
    String s = (String) ls.get(0); //get string A
    int x = (Integer) ls.get(2);
}


问:
How to get the range of a non blank cell in google script
I´m trying to get the values of the rows that don't have a blank cell in column K.

```<code>  var spreadsheet = SpreadsheetApp.getActive();
  var bigrange = spreadsheet.getSheetByName('sheet').getRange("K2:K").getValues();
//  var smallrange= bigrange .filter(String);

  for (var i=0; i < smallrange.length; i++) {

var calId = spreadsheet.getSheetByName('sheet').getRange("M" + [i+ 2]).getValue();

}
</code>```

The code above works if I don't use the .filter(String). But since my data is big and most of range K2:K is blank, I think I should use the .filter(String).

What is the best way of getting the range of the few cells in K2:K that are not blank?

答:
How about this answer?

Pattern 1:

The sheet name is sheet. In this sheet, you want to retrieve the ranges when the cell of column "K" is empty.

If my understanding is correct, how about this modification?

Modified script:

In this modified script, at first, the values are retrieved from "K2:K". Then, the ranges are retrieved from the values.

```<code>var sheetName = "sheet"; // Please set the sheet name here.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName);
var values = sheet.getRange("K2:K").getValues();
var ranges = values.map(function(e, i) {return e[0] ? sheetName + "!K" + (i + 2) : ""}).filter(String);
Logger.log(ranges)
</code>```

Pattern 2:

The sheet name is sheet. In this sheet, you want to retrieve the values of the column "M" when the cell of column "K" is empty.

From your question and script, I also understood like above. If my understanding is correct, how about this modification?

Modified script:

In this modified script, at first, the values are retrieved from "A2:M". Then, the values of the column "M" when the column "K" is empty are retrieved.

```<code>var sheetName = "sheet"; // Please set the sheet name here.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName);
var values = sheet.getRange("A2:M").getValues();
var res = values.map(function(e) {return e[10] ? e[12] : ""}).filter(String);
Logger.log(res)
</code>```

Note:

In both modified scripts, from your script, it supposes that you want to retrieve the values from one sheet which is sheet.

References:

filter()

map()

If I misunderstood your question and this was not the result you want, I apologize.

Body:
I´m trying to get the values of the rows that don't have a blank cell in column K.

  var spreadsheet = SpreadsheetApp.getActive();
  var bigrange = spreadsheet.getSheetByName('sheet').getRange("K2:K").getValues();
//  var smallrange= bigrange .filter(String);

  for (var i=0; i < smallrange.length; i++) {

var calId = spreadsheet.getSheetByName('sheet').getRange("M" + [i+ 2]).getValue();

}

The code above works if I don't use the .filter(String). But since my data is big and most of range K2:K is blank, I think I should use the .filter(String).

What is the best way of getting the range of the few cells in K2:K that are not blank?

Body:
How about this answer?

Pattern 1:

The sheet name is sheet. In this sheet, you want to retrieve the ranges when the cell of column "K" is empty.

If my understanding is correct, how about this modification?

Modified script:

In this modified script, at first, the values are retrieved from "K2:K". Then, the ranges are retrieved from the values.

var sheetName = "sheet"; // Please set the sheet name here.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName);
var values = sheet.getRange("K2:K").getValues();
var ranges = values.map(function(e, i) {return e[0] ? sheetName + "!K" + (i + 2) : ""}).filter(String);
Logger.log(ranges)

Pattern 2:

The sheet name is sheet. In this sheet, you want to retrieve the values of the column "M" when the cell of column "K" is empty.

From your question and script, I also understood like above. If my understanding is correct, how about this modification?

Modified script:

In this modified script, at first, the values are retrieved from "A2:M". Then, the values of the column "M" when the column "K" is empty are retrieved.

var sheetName = "sheet"; // Please set the sheet name here.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName);
var values = sheet.getRange("A2:M").getValues();
var res = values.map(function(e) {return e[10] ? e[12] : ""}).filter(String);
Logger.log(res)

Note:

In both modified scripts, from your script, it supposes that you want to retrieve the values from one sheet which is sheet.

References:

filter()

map()

If I misunderstood your question and this was not the result you want, I apologize.


问:
how to get unidentified network adaptor name with batch

I already knew how to get all network adaptors names, but I can't tell the difference between normally using and not identified

By using
netsh interface ip show interfaces
or other commands ,you may get all adaptors names.

答:
The necessary information can be obtained using the Win32_NetworkAdapter class.
For example:

```<code>Get-CimInstance -ClassName Win32_NetworkAdapter -Filter @'
NetConnectionID = "Local Area Connection" AND
NetConnectionStatus=2 AND NetEnabled = True AND PhysicalAdapter = True
'@ | Format-List *
</code>```

The Get-WmiObject cmdlet can also be used, but starting in PowerShell 3.0,  it has been superseded by Get-CimInstance.
Starting with Windows 8, you can use the Get-NetAdapter cmdlet.

Body:
The necessary information can be obtained using the Win32_NetworkAdapter class.
For example:

Get-CimInstance -ClassName Win32_NetworkAdapter -Filter @'
NetConnectionID = "Local Area Connection" AND
NetConnectionStatus=2 AND NetEnabled = True AND PhysicalAdapter = True
'@ | Format-List *

The Get-WmiObject cmdlet can also be used, but starting in PowerShell 3.0,  it has been superseded by Get-CimInstance.
Starting with Windows 8, you can use the Get-NetAdapter cmdlet.


问:
AWS Glue Crawler Unable to Classify CSV files
I'm unable to get the default crawler classifier, nor a custom classifier to work against many of my CSV files.  The classification is listed as 'UNKNOWN'. I've tried re-running existing classifiers, as well as creating new ones.  Is anyone aware of a specific configuration for a custom classifier for CSV files that works for files of any size?

I'm also unable to find any errors specific to this issue in the logs.

Although I have seen reference to issues for JSON files over 1MB in size, I can't find anything detailing this same issue for CSV files, nor a solution to the problem.

AWS crawler could not classify the file type stores in S3 if its size >1MB

AWS Glue Crawler Classifies json file as UNKNOWN

答:
Default CSV classifiers supported by Glue Crawler:

CSV    -  Checks for the following delimiters: comma (,), pipe (|), tab
  (\t), semicolon (;), and Ctrl-A (\u0001). Ctrl-A is the Unicode
  control character for Start Of Heading.

If you have any other delimiter, then it will not work with default CSV classfier. In that case you will have to write grok pattern.


问:
How to write code to help garbage collector
On interview I got a question - "How to help garbage collector when writing code?".

In my opinion GC works really good and we don't need to use anything more than basic good code practices, later added that closing resources in finally clause help GC for sure but generally got suprised with such question.

Is there a good reply? Do we need to do something incredible to help garbage collector?

答:
The Garbage Collector is a "task" that periodically scans your objects to detect what is not in use (in reality it is a mechanism to emulate a machine with an infinite memory).

For this reason, when you are holding a reference to an object instance you no longer need, you must set it to null in order to let the Garbage Collector know that you are no longer interested in that instance (and possibly its descendants).

This does not mean that you have to set every variable to null after use, but you have to watch for fields.
As Java does not have a dispose pattern (see here for more information), you have to design your APIs to mimic it: when you are finished using an object instance which holds a reference you want to free, you have to add an appropriate method to perform such action.

Consider the following example:

```<code>class MyClass1
{
    int Field1;
    int Field2;
    int Field3;
    int Field4;
}

class MyClass2
{
    private MyClass1 m_MyReference;

    public MyClass2()
    {
        m_MyReference = new MyClass1();
    }

    public void DoSomething()
    {
        // do something here that uses m_MyReference.
    }
}
</code>```

If an instance of MyClass2 is held but some other reachable instance of your program (e.g. a singleton, or some instance currently in the stack), you will never release the memory associated to MyClass1 as it is still referenced by m_MyReference.

Is this bad? It depends on that MyClass2 and MyClass1 are truly doing.

If you know that MyClass2 could have a very long lifespan and you want to retain the reference to MyClass2 but to release the memory associated to MyClass1, you have to do something similar to the code below:

```<code>class MyClass2
{
    private MyClass1 m_MyReference;

    public MyClass2()
    {
        m_MyReference = new MyClass1();
    }

    public void DoSomething()
    {
        // do something here that uses m_MyReference.
    }

    public void Dispose()
    {
        m_MyReference = null;
    }

}
</code>```

This way you expose to the caller a way to signal that you are no longer holding a reference to instances you do not need.

Remember that simply assigning null to a variable or field, does not automatically release the memory. The Garbage Collector is asynchronous and runs when it decides so.
Hope to have given the idea without going too deeper.

Body:
The Garbage Collector is a "task" that periodically scans your objects to detect what is not in use (in reality it is a mechanism to emulate a machine with an infinite memory).

For this reason, when you are holding a reference to an object instance you no longer need, you must set it to null in order to let the Garbage Collector know that you are no longer interested in that instance (and possibly its descendants).

This does not mean that you have to set every variable to null after use, but you have to watch for fields.
As Java does not have a dispose pattern (see here for more information), you have to design your APIs to mimic it: when you are finished using an object instance which holds a reference you want to free, you have to add an appropriate method to perform such action.

Consider the following example:

class MyClass1
{
    int Field1;
    int Field2;
    int Field3;
    int Field4;
}

class MyClass2
{
    private MyClass1 m_MyReference;

    public MyClass2()
    {
        m_MyReference = new MyClass1();
    }

    public void DoSomething()
    {
        // do something here that uses m_MyReference.
    }
}

If an instance of MyClass2 is held but some other reachable instance of your program (e.g. a singleton, or some instance currently in the stack), you will never release the memory associated to MyClass1 as it is still referenced by m_MyReference.

Is this bad? It depends on that MyClass2 and MyClass1 are truly doing.

If you know that MyClass2 could have a very long lifespan and you want to retain the reference to MyClass2 but to release the memory associated to MyClass1, you have to do something similar to the code below:

class MyClass2
{
    private MyClass1 m_MyReference;

    public MyClass2()
    {
        m_MyReference = new MyClass1();
    }

    public void DoSomething()
    {
        // do something here that uses m_MyReference.
    }

    public void Dispose()
    {
        m_MyReference = null;
    }

}

This way you expose to the caller a way to signal that you are no longer holding a reference to instances you do not need.

Remember that simply assigning null to a variable or field, does not automatically release the memory. The Garbage Collector is asynchronous and runs when it decides so.
Hope to have given the idea without going too deeper.


问:
Why my code is not able to convert each item of list from string to integer?
I am stuck on a problem due to a small portion of my code. I can't find why that portion of code is not working properly.

By debugging each portion of my code, I found which lines are causing unexpected results. I have written that lines below. I have defined the list here so that I do not have to copy my full code.

```<code>list1=["-7","-7","-6"]

for test in list1:

    test=int(test)

print( type( list1[0] ) )
</code>```

I expected type to be int but output is coming as str instead.

答:
You forgot about appending the transformed value:</p>

```<code>list1 = ["-7","-7","-6"]
list2 = [] # store integers
for test in list1:
    test = int(test)
    list2.append(test) # store transformed values

print(type(list2[0]))
</code>```

Body:
I am stuck on a problem due to a small portion of my code. I can't find why that portion of code is not working properly.

By debugging each portion of my code, I found which lines are causing unexpected results. I have written that lines below. I have defined the list here so that I do not have to copy my full code.

list1=["-7","-7","-6"]

for test in list1:

    test=int(test)

print( type( list1[0] ) )

I expected type to be int but output is coming as str instead.

Body:
You forgot about appending the transformed value:

list1 = ["-7","-7","-6"]
list2 = [] # store integers
for test in list1:
    test = int(test)
    list2.append(test) # store transformed values

print(type(list2[0]))


问:
React unable to find component
I'm trying to create a React App.. largely my attempts so far are based on the default application from create-react-app. Here's my App.js:

```<code>import React from 'react';
import './App.css';
import './Components/MyComponent';

function App() {
  return (
    <div className="App">
      <MyComponent/>
    </div>
  );
}

export default App;
</code>```

MyComponent is defined here:

```<code>import React from 'react';
import img from './Assets/img.png';
import imgComponent from './MyImage';

class MyComponent extends React.Component {
    render() {
      return
        <div>
            <imgComponent imageProp={img} />

        </div>
    }
}

export default MyComponent;
</code>```

When I run this, I get the error:

```<code>./src/App.js
  Line 8:  'MyComponent' is not defined  react/jsx-no-undef
</code>```

Please could someone tell me why I'm getting this error? I was under the impression that a combination of the import in App.js and the export default in MyComponent was all that was needed to use the component.

答:
When we are doing export default Mycomponent, we are exposing the Mycomponent module to other modules. But we require a local name to access the contents. For a default export, it doesn't have to be the same as export. A simple import statement should look like import name from 'module'.
In your case, it will be

import MyComponent from './Components/MyComponent'.

Title: React unable to find component

Body:
I'm trying to create a React App.. largely my attempts so far are based on the default application from create-react-app. Here's my App.js:

import React from 'react';
import './App.css';
import './Components/MyComponent';

function App() {
  return (

      <MyComponent/>

  );
}

export default App;

MyComponent is defined here:

import React from 'react';
import img from './Assets/img.png';
import imgComponent from './MyImage';

class MyComponent extends React.Component {
    render() {
      return

            <imgComponent imageProp={img} />

    }
}

export default MyComponent;

When I run this, I get the error:

./src/App.js
  Line 8:  'MyComponent' is not defined  react/jsx-no-undef

Please could someone tell me why I'm getting this error? I was under the impression that a combination of the import in App.js and the export default in MyComponent was all that was needed to use the component.


问:
Echo an Array and make the content look pretty on the page
I am trying to echo out my array on each line, not bunched together.

I have tried
, this only show's on the front end, but when you look at HTML code. Its still clumped together.

```<code>$arrays = [];

$arrays[] = "Good";
$arrays[] = "Bad";

foreach ($arrays as $array){
    echo $array;
}
</code>```

Result:

GoodBad

Want Result:

Good

Bad

答: Try echo "```; var_dump($arrays); echo "```;

Body:
I am trying to echo out my array on each line, not bunched together.

I have tried
, this only show's on the front end, but when you look at HTML code. Its still clumped together.

$arrays = [];

$arrays[] = "Good";
$arrays[] = "Bad";

foreach ($arrays as $array){
    echo $array;
}

Result:

GoodBad

Want Result:

Good

Bad

Body: Try echo "<pre>; var_dump($arrays); echo "</pre>;


问:
Limiting a doctrine query with a fetch-joined collection?
I have a doctrine query that returns blog posts and their comments:

```<code>SELECT b, c FROM BlogPost b LEFT JOIN b.comments c
</code>```

I would like to limit the results to 10 blog posts. According to the DQL documentation, setMaxResults() doesn't work correctly on queries that fetch-join a collection (comments in this case):

If your query contains a fetch-joined
  collection specifying the result limit
  methods are not working as you would
  expect. Set Max Results restricts the
  number of database result rows,
  however in the case of fetch-joined
  collections one root entity might
  appear in many rows, effectively
  hydrating less than the specified
  number of results.

How would I properly limit a doctrine query that contains a fetch-joined collection (in this case, limit the results to 10 blog posts)?

答:
Did the same with a querybuilder and it works. Maybe something else is the problem?</p>

```<code>$qb->add('select', 'b, c, ch, g')
   ->add('from', 'Broadcast b')
   ->add('groupBy', 'b.title')
   ->add('where', 'b.imageBig != \'\'')
   ->add('orderBy', 'b.starttime ASC')
   ->setMaxResults(10)
   ->leftJoin('b.category', 'c')
   ->leftJoin('b.channel', 'ch')
   ->leftJoin('b.genre', 'g')
</code>```

Body:
I have a doctrine query that returns blog posts and their comments:

SELECT b, c FROM BlogPost b LEFT JOIN b.comments c

I would like to limit the results to 10 blog posts. According to the DQL documentation, setMaxResults() doesn't work correctly on queries that fetch-join a collection (comments in this case):

If your query contains a fetch-joined
  collection specifying the result limit
  methods are not working as you would
  expect. Set Max Results restricts the
  number of database result rows,
  however in the case of fetch-joined
  collections one root entity might
  appear in many rows, effectively
  hydrating less than the specified
  number of results.

How would I properly limit a doctrine query that contains a fetch-joined collection (in this case, limit the results to 10 blog posts)?

Body:
Did the same with a querybuilder and it works. Maybe something else is the problem?

$qb->add('select', 'b, c, ch, g')
   ->add('from', 'Broadcast b')
   ->add('groupBy', 'b.title')
   ->add('where', 'b.imageBig != \'\'')
   ->add('orderBy', 'b.starttime ASC')
   ->setMaxResults(10)
   ->leftJoin('b.category', 'c')
   ->leftJoin('b.channel', 'ch')
   ->leftJoin('b.genre', 'g')


问:
ReactNative: Component inline and for navigation
I am beginning with ReactNative and try to get a component I can navigate to as well as use inline.

MyComp is the component. In Home I try to navigate to MyComp by a button as well as have it inline with .

App.js

```<code>import React from 'react';
import { StyleSheet, Text, View, Button, Alert, Image} from 'react-native';
import {createStackNavigator, createAppContainer} from 'react-navigation';
import Home from "./Home";
import MyComp from "./MyComp";

const navi = createStackNavigator({
    Home: {screen: Home},
    MyComp: {screen: MyComp}
});

const App = createAppContainer (navi);
export default App;
</code>```

Home.js

```<code>import React from 'react';
import {StyleSheet, Text, View, Button, Alert} from 'react-native';
import {navigate} from 'react-navigation';
import {MyComp} from "./MyComp";

export default class Home extends React.Component
{
    static navigationOptions = {title: 'At Home'};

    render()
    {
        return (
            <View style={{ alignItems: 'center', justifyContent: 'center', flex: 1}}>
            <Button
                title={"Goto MyComp"}
                onPress={() => this.props.navigation.navigate('MyComp')}/>

            <MyComp/>   {/* Compiler Error */}

            </View>
        );
  }
}
</code>```

MyComp.js

```<code>import React from 'react';
import {Text, View, Button} from 'react-native';

export default class MyComp extends React.Component
{
    render()
    {
        return (
            <View>
            <Text>Here I am</Text>
            </View>
    );
  }
}
</code>```

But the inline produces an error.

Invariant Violation: Invariant Violation: Element type is invalid:
  expected a string (for built-in components) or a class/function (for
  composite components) but got: undefined. You likely forgot to export
  your component from the file it's defined in, or you might have mixed
  up default and named imports.

Check the render method of Home.

I am not sure whats the problem here. Is it not possible to use a component in both ways?

答:
remove brackets when u import component in home screen

change
 import {MyComp} from "./MyComp";

to
 import MyComp from "./MyComp";

Body:
I am beginning with ReactNative and try to get a component I can navigate to as well as use inline.

MyComp is the component. In Home I try to navigate to MyComp by a button as well as have it inline with .

App.js

import React from 'react';
import { StyleSheet, Text, View, Button, Alert, Image} from 'react-native';
import {createStackNavigator, createAppContainer} from 'react-navigation';
import Home from "./Home";
import MyComp from "./MyComp";

const navi = createStackNavigator({
    Home: {screen: Home},
    MyComp: {screen: MyComp}
});

const App = createAppContainer (navi);
export default App;

Home.js

import React from 'react';
import {StyleSheet, Text, View, Button, Alert} from 'react-native';
import {navigate} from 'react-navigation';
import {MyComp} from "./MyComp";

export default class Home extends React.Component
{
    static navigationOptions = {title: 'At Home'};

    render()
    {
        return (
            <View style={{ alignItems: 'center', justifyContent: 'center', flex: 1}}>
            <Button
                title={"Goto MyComp"}
                onPress={() => this.props.navigation.navigate('MyComp')}/>

            <MyComp/>   {/* Compiler Error */}

            </View>
        );
  }
}

MyComp.js

import React from 'react';
import {Text, View, Button} from 'react-native';

export default class MyComp extends React.Component
{
    render()
    {
        return (
            <View>
            <Text>Here I am</Text>
            </View>
    );
  }
}

But the inline produces an error.

Invariant Violation: Invariant Violation: Element type is invalid:
  expected a string (for built-in components) or a class/function (for
  composite components) but got: undefined. You likely forgot to export
  your component from the file it's defined in, or you might have mixed
  up default and named imports.

Check the render method of Home.

I am not sure whats the problem here. Is it not possible to use a component in both ways?


问:
ToStringBuilder doesn't print contents of nested objects
I am cuurently using apache commons API (commmons-lang.jar) to print an object values as shown below:

```<code>ToStringBuilder.reflectionToString(object,ToStringStyle.MULTI_LINE_STYLE))
</code>```

But this code does not print value if the object has a getter method which returns another object.

For example I have Person object it has a getter method which returns Address object. Using the above code, it just prints Address object name. I am looking for printing Address object values also. If I a pass person.getAddress() to above code it prints that but I want to see everything when I pass person object.

Any suggestions?

答:
Since version 3.2 of Apache Commons Lang, you can use a RecursiveToStringStyle to achieve exactly what you want.

Either:

```<code>ToStringBuilder.reflectionToString(object, new RecursiveToStringStyle());
</code>```

or

```<code>ToStringBuilder.reflectionToString(object, new MultilineRecursiveToStringStyle());
</code>```

MultilineRecursiveToStringStyle is available since version 3.4

Body:
I am cuurently using apache commons API (commmons-lang.jar) to print an object values as shown below:

ToStringBuilder.reflectionToString(object,ToStringStyle.MULTI_LINE_STYLE))

But this code does not print value if the object has a getter method which returns another object.

For example I have Person object it has a getter method which returns Address object. Using the above code, it just prints Address object name. I am looking for printing Address object values also. If I a pass person.getAddress() to above code it prints that but I want to see everything when I pass person object.

Any suggestions?

Body:
Since version 3.2 of Apache Commons Lang, you can use a RecursiveToStringStyle to achieve exactly what you want.

Either:

ToStringBuilder.reflectionToString(object, new RecursiveToStringStyle());

or

ToStringBuilder.reflectionToString(object, new MultilineRecursiveToStringStyle());

MultilineRecursiveToStringStyle is available since version 3.4


问:
Flexible date/time parsing in Go (Adding default values in parsing)
Further to this question, I want to parse a date/time passed on the command line to a Go program. At the moment, I use the flag package to populate a string variable ts and then the following code:

```<code>if ts == "" {
    config.Until = time.Now()
} else {
    const layout = "2006-01-02T15:04:05"
    if config.Until, err = time.Parse(layout, ts); err != nil {
        log.Errorf("Could not parse %s as a time string: %s. Using current date/time instead.", ts, err.Error())
        config.Until = time.Now()
    }
}
</code>```

This works OK, provided the user passes exactly the right format - e.g. 2019-05-20T09:07:33 or some such.

However, what I would like, if possible, is the flexibility to pass e.g. 2019-05-20T09:07 or 2019-05-20T09 or maybe even 2019-05-20 and have the hours, minutes and seconds default to 0 where appropriate.

Is there a sane1 way to do this?

  1 not requiring me to essentially write my own parser

UPDATE

I've kind of got a solution to this, although it's not particularly elegant, it does appear to work for most of the cases I am likely to encounter.

```<code>package main

import (
    "fmt"
    "time"
)

func main() {

    const layout = "2006-01-02T15:04:05"
    var l string
    var input string

    for _, input = range []string{"2019-05-30", "2019-05-30T16", "2019-05-30T16:04", "2019-05-30T16:04:34",
                                "This won't work", "This is extravagantly long and won't work either"} {
        if len(input) < len(layout) {
            l = layout[:len(input)]
        } else {
            l = layout
        }
        if d, err := time.Parse(l, input); err != nil {
            fmt.Printf("Error %s\n", err.Error())
        } else {
            fmt.Printf("Layout %-20s gives time %v\n", l, d)
        }
    }
}
</code>```

答:
I think this library is what you are looking for https://github.com/araddon/dateparse

Parse many date strings without knowing the format in advance. Uses a scanner to read bytes and use a state machine to find format.

```<code>t, err := dateparse.ParseAny("3/1/2014")
</code>```

Body:
Further to this question, I want to parse a date/time passed on the command line to a Go program. At the moment, I use the flag package to populate a string variable ts and then the following code:

if ts == "" {
    config.Until = time.Now()
} else {
    const layout = "2006-01-02T15:04:05"
    if config.Until, err = time.Parse(layout, ts); err != nil {
        log.Errorf("Could not parse %s as a time string: %s. Using current date/time instead.", ts, err.Error())
        config.Until = time.Now()
    }
}

This works OK, provided the user passes exactly the right format - e.g. 2019-05-20T09:07:33 or some such.

However, what I would like, if possible, is the flexibility to pass e.g. 2019-05-20T09:07 or 2019-05-20T09 or maybe even 2019-05-20 and have the hours, minutes and seconds default to 0 where appropriate.

Is there a sane1 way to do this?

  1 not requiring me to essentially write my own parser

UPDATE

I've kind of got a solution to this, although it's not particularly elegant, it does appear to work for most of the cases I am likely to encounter.

package main

import (
    "fmt"
    "time"
)

func main() {

    const layout = "2006-01-02T15:04:05"
    var l string
    var input string

    for _, input = range []string{"2019-05-30", "2019-05-30T16", "2019-05-30T16:04", "2019-05-30T16:04:34",
                                "This won't work", "This is extravagantly long and won't work either"} {
        if len(input) < len(layout) {
            l = layout[:len(input)]
        } else {
            l = layout
        }
        if d, err := time.Parse(l, input); err != nil {
            fmt.Printf("Error %s\n", err.Error())
        } else {
            fmt.Printf("Layout %-20s gives time %v\n", l, d)
        }
    }
}

Body:
I think this library is what you are looking for https://github.com/araddon/dateparse

Parse many date strings without knowing the format in advance. Uses a scanner to read bytes and use a state machine to find format.

t, err := dateparse.ParseAny("3/1/2014")


问:
why is this node.js application throwing ENOENT error?
```<code>res.sendFile(path.join(
__dirname, '..', 'client', 'views', 'index.html'));
</code>```

this line of code generates a 404 error ENOENT: no such file or directory, stat '/Users/[username]/workspace/client/views/index.html'

for the following folder structure

workspace/

⠀⠀webapp/

⠀⠀⠀⠀client/

⠀⠀⠀⠀⠀⠀views/

⠀⠀⠀⠀⠀⠀⠀index.html

⠀⠀⠀⠀server/

⠀⠀⠀⠀⠀⠀routes/

⠀⠀⠀⠀⠀⠀⠀⠀index.js

答:
seems the path "/Users/[username]/workspace/client/views/index.html'" has a missing '⠀webapp/' in between workspace and client.

By default the server looks for the files which are present in views folder with its default configuration settings in Express, If you want to change it you can use the method set() to redefine express's default settings.

```<code> var express = require('express');
 var path = require('path');
 var app = express();

 app.set('views', path.join(__dirname, '/ViewDirectorypath'));
</code>```

Body:
res.sendFile(path.join(
__dirname, '..', 'client', 'views', 'index.html'));

this line of code generates a 404 error ENOENT: no such file or directory, stat '/Users/[username]/workspace/client/views/index.html'

for the following folder structure

workspace/

⠀⠀webapp/

⠀⠀⠀⠀client/

⠀⠀⠀⠀⠀⠀views/

⠀⠀⠀⠀⠀⠀⠀index.html

⠀⠀⠀⠀server/

⠀⠀⠀⠀⠀⠀routes/

⠀⠀⠀⠀⠀⠀⠀⠀index.js

Body:
seems the path "/Users/[username]/workspace/client/views/index.html'" has a missing '⠀webapp/' in between workspace and client.

By default the server looks for the files which are present in views folder with its default configuration settings in Express, If you want to change it you can use the method set() to redefine express's default settings.

 var express = require('express');
 var path = require('path');
 var app = express();

 app.set('views', path.join(__dirname, '/ViewDirectorypath'));


问:
Angular how to check if this page is accessed by a user and to block access for another user?
I have a page with some data on it.

```<code><p-table [value]="mnos" [(contextMenuSelection)]="selectmno"
[contextMenu]="cm"  >
 <ng-template pTemplate="header"  >
  <tr>
      <th >ID</th>
      <th>Name</th>
  </tr>
  </ng-template>
  <ng-template pTemplate="body" let-mno>
      <tr [pContextMenuRow]="rowData"     (click)="test($event,mno)">
          <td>{{mno.id}}</td>
      <td>{{mno.name}}</td>
  </tr>
  </ng-template>
</p-table>
<p-contextMenu #cm [model]="items"></p-contextMenu>
</code>```

On click on table it will redirect to another page http://localhost:4200/test . How can I block access to a user if someone already was redirected to this page. Like if I'm already on page http://localhost:4200/test another user that will click on table will be announced that this page is busy.

This is my onClick:

```<code>test(event, mno){
console.log("On click",event,mno);
this.router.navigate(['/test']);

}
</code>```

答:
Following the conversation in the comments you could do the following.

Assuming you have the following files.

test.component.ts

```<code>....
@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent {
}
</code>```

app.routing.ts

```<code>...
export const router: Routes = [
  {path: 'test', component: TestComponent}
];
....
</code>```

You want to somehow check if there's already an active session on the test page.
This is a perfect use case for a route guard, at least I'm convinced.

You can create a route guard that will perform a API call that checks if there's already an active session on the test page. You will need to add some more logic of course, but that'll be the next steps..

check-active-session.guard.ts

```<code>....
@Injectable()
export class CheckActiveSessionGuard implements CanActivate {
  constructor(private api: ApiService,
              private router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.apiService.activeTestSession().pipe(map(x => {
      // x will be the response from the API
      // Let's pretend it is returning a boolean.
      // It will be true when there's already an active session and false if there's no active session
      // true means user should not pass (because of an active session), false means a user can pass
      if (!x) {
        // No active session, user can pass
        return true;
      } else {
        // Already an active sesssion, user should be redirected
        this.router.navigate(['busy']);
        return false;
      }
    }));
  }
}
</code>```

api.service.ts

```<code>...
public activeTestSession(): Observable<boolean> {
        return this.httpClient.get<any>('api' + '/is_there_already_an_active_session, { observe: 'body', responseType: 'json' });
    }
...
</code>```

Then add the guard to the canActivate property in the routing:

app.routing.ts (New)

```<code>...
export const router: Routes = [
  {path: 'test', component: TestComponent, canActivate: [CheckActiveSessionGuard]}
];
....
</code>```

Think this is the minimum implementation of how you can do that.

I can imagine you can create a user session (when the user visits your site, just once) and sending along this session id along with api call, to be able to expand the functionality.

Body:
I have a page with some data on it.

 <ng-template pTemplate="header"  >

      ID
      Name

  </ng-template>
  <ng-template pTemplate="body" let-mno>

          {{mno.id}}
      {{mno.name}}

  </ng-template>

On click on table it will redirect to another page http://localhost:4200/test . How can I block access to a user if someone already was redirected to this page. Like if I'm already on page http://localhost:4200/test another user that will click on table will be announced that this page is busy.

This is my onClick:

test(event, mno){
console.log("On click",event,mno);
this.router.navigate(['/test']);

}

Body:
Following the conversation in the comments you could do the following.

Assuming you have the following files.

test.component.ts

....
@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent {
}

app.routing.ts

...
export const router: Routes = [
  {path: 'test', component: TestComponent}
];
....

You want to somehow check if there's already an active session on the test page.
This is a perfect use case for a route guard, at least I'm convinced.

You can create a route guard that will perform a API call that checks if there's already an active session on the test page. You will need to add some more logic of course, but that'll be the next steps..

check-active-session.guard.ts

....
@Injectable()
export class CheckActiveSessionGuard implements CanActivate {
  constructor(private api: ApiService,
              private router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.apiService.activeTestSession().pipe(map(x => {
      // x will be the response from the API
      // Let's pretend it is returning a boolean.
      // It will be true when there's already an active session and false if there's no active session
      // true means user should not pass (because of an active session), false means a user can pass
      if (!x) {
        // No active session, user can pass
        return true;
      } else {
        // Already an active sesssion, user should be redirected
        this.router.navigate(['busy']);
        return false;
      }
    }));
  }
}

api.service.ts

...
public activeTestSession(): Observable<boolean> {
        return this.httpClient.get<any>('api' + '/is_there_already_an_active_session, { observe: 'body', responseType: 'json' });
    }
...

Then add the guard to the canActivate property in the routing:

app.routing.ts (New)

...
export const router: Routes = [
  {path: 'test', component: TestComponent, canActivate: [CheckActiveSessionGuard]}
];
....

Think this is the minimum implementation of how you can do that.

I can imagine you can create a user session (when the user visits your site, just once) and sending along this session id along with api call, to be able to expand the functionality.


问:
pimp up a plain jar to be a maven jar with internal pom.xml for Artifactory
I need to use a xyz.jar wich was generated with ant. Hence, the transitive dependencies are missing. So I had the idea, to modify the xyz.jar to add the internal META-INF/maven/groupId/artifactId/pom.xml and pom.properties files.

When I deployed it to Artifactory, it ignored them and generated it's own pom.xml without dependencies.

What has one to do, Artifactory deploys the pom.xml lying about in the same folder as the xyz.jar file?

Lost way too much time on this allready...

答:
It might be a better idea to add it's dependencies to your pom instead of rigging a third-party library to use maven.

That being said, make sure your pom.xml is valid XML (most modern IDEs can validate xml for  you) and make sure your properties file includes version, group id, and artifact id.

Artifactory has changed the way that it handles POM generation in different versions, so, depending on your version, you may have some sort of generate pom option that you have to turn off on deploy. I think they have a deploy time pom editor or something like that in the newer versions.


问:
Django 'model' object is not iterable
I have a table which shows me the employees registered. I want to generate a simple HTML page according to their DB which includes their name, id, designation, etc.

To do so, I pass an id to the view so it can get the respective user's details and show me. Everything works fine until the error occurs object is not iterable. Here is my code below.

report.html

{% if emp_item %}
 {% for some in emp_item %}
    <title> {{ some.employee_name }} Report</title>

{{ some.employee_name }}

        {{some.id}}
        {{some.Annual_leave}}
        {{some.Sick_leave}}
        {{some.allowed}}

{% endfor %}

No User

{% else %}
{% endif %}

```
<p><code>views.py</code></p>
<pre class="lang-py prettyprint-override"><code>@staff_member_required  # for admin login required
def report(request, id):
    emp_item = Employee.objects.get(id=id)
    context = {'emp_item': emp_item}
    return render(request, 'projectfiles/report.html', context)
</code>```

urls.py

    url(r'^(?i)Rejectleaves/$', views.rejected_leave_show,
        name='Reject_show'),  # user leaves

    url(r'^(?i)report/(?P<id>\d+)$', views.report,
        name='Report'),  # user Report
```
<p><code>models.py</code></p>
<pre class="lang-py prettyprint-override"><code>class Employee(models.Model):

    allowed = models.BooleanField(default=True)
    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 5)
    employee_department = models.CharField(max_length = 5)
    Annual_leave = models.PositiveSmallIntegerField(default=5)
    Sick_leave = models.PositiveSmallIntegerField(default=5)
</code>```

I want to see each individual user's data according to the process they have made.

答:
Change Employee.objects.get(id=id) to Employee.objects.filter(id=id)

"filter() will always give you a QuerySet" - it's iterable

get() - return single object and it's not iterable

Title: Django 'model' object is not iterable

Body:
I have a table which shows me the employees registered. I want to generate a simple HTML page according to their DB which includes their name, id, designation, etc.

To do so, I pass an id to the view so it can get the respective user's details and show me. Everything works fine until the error occurs object is not iterable. Here is my code below.

report.html

{% if emp_item %}
 {% for some in emp_item %}
    <title> {{ some.employee_name }} Report</title>

{{ some.employee_name }}

        {{some.id}}
        {{some.Annual_leave}}
        {{some.Sick_leave}}
        {{some.allowed}}

{% endfor %}

No User

{% else %}
{% endif %}

views.py

@staff_member_required  # for admin login required
def report(request, id):
    emp_item = Employee.objects.get(id=id)
    context = {'emp_item': emp_item}
    return render(request, 'projectfiles/report.html', context)

urls.py

    url(r'^(?i)Rejectleaves/$', views.rejected_leave_show,
        name='Reject_show'),  # user leaves

    url(r'^(?i)report/(?P<id>\d+)$', views.report,
        name='Report'),  # user Report

models.py

class Employee(models.Model):

    allowed = models.BooleanField(default=True)
    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 5)
    employee_department = models.CharField(max_length = 5)
    Annual_leave = models.PositiveSmallIntegerField(default=5)
    Sick_leave = models.PositiveSmallIntegerField(default=5)

I want to see each individual user's data according to the process they have made.


问:
I need delete two " " with sed command
I need to delete "" in file

```<code>"CITFFUSKD-E0"
</code>```

I have tried sed 's/\"//.

Result is:

```<code>CITFFUSKD-E0"
</code>```

How I can delete both ?

Also I need to delete everything behind first word but input can be this one:

```<code>"CITFFUSKD-E0"
"CITFFUSKD_E0"
"CITFFUSKD E0"
</code>```

Result I want it:

```<code>CITFFUSKD
</code>```

答:
Could you please try following.</p>

```<code>awk 'match($0,/[a-zA-Z]+[^a-zA-Z]*/){val=substr($0,RSTART,RLENGTH);gsub(/[^a-zA-Z]+/,"",val);print val}' Input_file
</code>```

Title: I need delete two " " with sed command

Body:
I need to delete "" in file

"CITFFUSKD-E0"

I have tried sed 's/\"//.

Result is:

CITFFUSKD-E0"

How I can delete both ?

Also I need to delete everything behind first word but input can be this one:

"CITFFUSKD-E0"
"CITFFUSKD_E0"
"CITFFUSKD E0"

Result I want it:

CITFFUSKD

Body:
Could you please try following.

awk 'match($0,/[a-zA-Z]+[^a-zA-Z]*/){val=substr($0,RSTART,RLENGTH);gsub(/[^a-zA-Z]+/,"",val);print val}' Input_file


问:
Shell driver install with `ACCEPT_EULA=Y` error
As described here, I am trying to install the following driver in shell, using this code (modified from the original slightly):

```<code>curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
curl https://packages.microsoft.com/config/debian/8/prod.list | sudo tee /etc/apt/sources.list.d/mssql-release.list
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install msodbcsql17
</code>```

But I get an error on the last command:

```<code>sudo: sorry, you are not allowed to set the following environment variables: ACCEPT_EULA
</code>```

After searching, I can't seem to find this exact error anywhere else.

One solution is to run the last command without ACCEPT_EULA=Y as sudo apt-get install msodbcsql17. And then to enter Y at the prompt. This indeed works but I would like to run the above installation for other users without need of their input.

Is there a way to resolve the above error so I can use ACCEPT_EULA=Y, or

alternatively is there a simple way to enter the Y response for the EULA
automatically so the end user never needs to take any action?

Thank you in advance.

答:
I don't have enough rep to post a comment.
But I was doing the same install for pyodbc inside a python:3 docker container.
In the dockerfile the following command works:

ACCEPT_EULA=Y apt-get install -y msodbcsql17

(I was after this particular driver #17.)

Reading: https://github.com/microsoft/mssql-docker/blob/master/oss-drivers/pyodbc/Dockerfile can help see the environment set up from a base ubuntu (ubuntu:16.04) box.

Also check up on: https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-2017
for microsoft first hand docs.

Body:
As described here, I am trying to install the following driver in shell, using this code (modified from the original slightly):

curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
curl https://packages.microsoft.com/config/debian/8/prod.list | sudo tee /etc/apt/sources.list.d/mssql-release.list
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install msodbcsql17

But I get an error on the last command:

sudo: sorry, you are not allowed to set the following environment variables: ACCEPT_EULA

After searching, I can't seem to find this exact error anywhere else.

One solution is to run the last command without ACCEPT_EULA=Y as sudo apt-get install msodbcsql17. And then to enter Y at the prompt. This indeed works but I would like to run the above installation for other users without need of their input.

Is there a way to resolve the above error so I can use ACCEPT_EULA=Y, or

alternatively is there a simple way to enter the Y response for the EULA
automatically so the end user never needs to take any action?

Thank you in advance.


问:
React Native 'Modal' Component Not Covering Entire Screen on Android when using Full Screen Theme
The title says it all. I've edited the styles.xml file (/projectname/android/app/src/res/values/styles.xml) to contain the following:

<resources>

</resources>```

This code successfully makes the app fullscreen, removing the Android status bar. However, if I launch a React Native 'Modal' component the modal only extends as far to the top as where the edge of the status bar would have been, leaving a gap the size of a status bar. How would I modify the modal to extend all the way to the top?

Here's a screenshot of the open modal with the gap:

答:
I had tried to use native Android code to hide the StatusBar for a single component it works in other component but when I used it in modal, it just didn't work.

Then, I tried to remove the modal view and use react-navigation's StackNavigator to navigate to a specific path and handle the back button using BackHandler component and it worked.

Body:
The title says it all. I've edited the styles.xml file (/projectname/android/app/src/res/values/styles.xml) to contain the following:

<resources>

</resources>

This code successfully makes the app fullscreen, removing the Android status bar. However, if I launch a React Native 'Modal' component the modal only extends as far to the top as where the edge of the status bar would have been, leaving a gap the size of a status bar. How would I modify the modal to extend all the way to the top?

Here's a screenshot of the open modal with the gap:


问:
cant able to find the right xpath for active element
i am not able to find the active xpath (the fare bundle which are displayed only on flight selection page ) for the fare bundle in flight selection page .
i have tried all , when i have been trying i am getting the total counts of webelement (fare bundle) which is included both active and inactive . this is causing me problem to select the active xpath .when i am running the loop , the moment the loop point out to inactive (the webelement which is not pointing any farebundle in UI but shown in developer tool) , it is getting failed as that webelemet is not displayed on UI . need your help/

```<code>xpath :

<div class="colRadio">::before
<input type="radio" name="flightItineraryGroupId[0]_01" value="12" id="flightSelectGr_0_12" onclick="selectFareFamily(0, 1, 'AN'); fareFamiliesFlightSelection.selectFlight(this); reloadItinerarySummaryInfo(this, false)" class="" aria-labelledby="flightSelectGr_0_12Label  idFFTitleAN idFlightNumber2">
</code>```

Note :
    here only below html are constane and all rest are change based on

selected fare bundle

```<code> <div class="colRadio">::before
</code>```

i have tried
//div[@class="colRadio"] and it is showing all webelement including inactive which is not displayed on UI .

```<code> For (i=1;i<=count,i++)driver.findElement(By.xpath("(//input[@type=\"radio\"])["+i+"]")).click();
</code>```

Expected : i want xpath which is only pointing web element present in Ui
Actual: when i am running loop the loop is getting failed when it click on the web element which is not displayed in UI which is inactibe

```<code> For (i=1;i<=count,i++)driver.findElement(By.xpath("(//input[@type=\"radio\"])["+i+"]")).click();
</code>```

Note: i want only active xpath count

答:
Get all radio buttons into a List of WebElements like:

```<code>List<WebElement> allRadioButtons = driver.findElements(By.xpath("//input[@type='radio']"));
</code>```

hint: you can use single quote marks ' in your XPath queries for better readability as you won't have to escape double quotation marks  " with a backslash \

Filter out only those which are currently visible:

```<code>List<WebElement> visibleRadioButtons = allRadioButtons
        .stream()
        .filter(WebElement::isDisplayed)
        .collect(Collectors.toList());
</code>```

That's it, now visibleRadioButtons list will contain only those buttons which are currently displayed and can be interacted with.

Body:
i am not able to find the active xpath (the fare bundle which are displayed only on flight selection page ) for the fare bundle in flight selection page .
i have tried all , when i have been trying i am getting the total counts of webelement (fare bundle) which is included both active and inactive . this is causing me problem to select the active xpath .when i am running the loop , the moment the loop point out to inactive (the webelement which is not pointing any farebundle in UI but shown in developer tool) , it is getting failed as that webelemet is not displayed on UI . need your help/

xpath :

::before
<input type="radio" name="flightItineraryGroupId[0]_01" value="12" id="flightSelectGr_0_12" onclick="selectFareFamily(0, 1, 'AN'); fareFamiliesFlightSelection.selectFlight(this); reloadItinerarySummaryInfo(this, false)" class="" aria-labelledby="flightSelectGr_0_12Label  idFFTitleAN idFlightNumber2">

Note :
    here only below html are constane and all rest are change based on

selected fare bundle

::before

i have tried
//div[@class="colRadio"] and it is showing all webelement including inactive which is not displayed on UI .

 For (i=1;i<=count,i++)driver.findElement(By.xpath("(//input[@type=\"radio\"])["+i+"]")).click();

Expected : i want xpath which is only pointing web element present in Ui
Actual: when i am running loop the loop is getting failed when it click on the web element which is not displayed in UI which is inactibe

 For (i=1;i<=count,i++)driver.findElement(By.xpath("(//input[@type=\"radio\"])["+i+"]")).click();

Note: i want only active xpath count

Body:
Get all radio buttons into a List of WebElements like:

List<WebElement> allRadioButtons = driver.findElements(By.xpath("//input[@type='radio']"));

hint: you can use single quote marks ' in your XPath queries for better readability as you won't have to escape double quotation marks  " with a backslash \

Filter out only those which are currently visible:

List<WebElement> visibleRadioButtons = allRadioButtons
        .stream()
        .filter(WebElement::isDisplayed)
        .collect(Collectors.toList());

That's it, now visibleRadioButtons list will contain only those buttons which are currently displayed and can be interacted with.