问:
how to split an XML file into multiple XML files using java
I'm using XML files in Java for the first time and i need some help. I am trying to split an XML file to multiple XML files using Java

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<products>
    <product>
        <description>Sony 54.6" (Diag) Xbr Hx929 Internet Tv</description>
        <gtin>00027242816657</gtin>
        <price>2999.99</price>
        <orderId>2343</orderId>
        <supplier>Sony</supplier>
    </product>
    <product>
        <description>Apple iPad 2 with Wi-Fi 16GB - iOS 5 - Black
        </description>
        <gtin>00885909464517</gtin>
        <price>399.0</price>
        <orderId>2343</orderId>
        <supplier>Apple</supplier>
    </product>
    <product>
        <description>Sony NWZ-E464 8GB E Series Walkman Video MP3 Player Blue
        </description>
        <gtin>00027242831438</gtin>
        <price>91.99</price>
        <orderId>2343</orderId>
        <supplier>Sony</supplier>
    </product>
    <product>
        <description>Apple MacBook Air A 11.6" Mac OS X v10.7 Lion MacBook
        </description>
        <gtin>00885909464043</gtin>
        <price>1149.0</price>
        <orderId>2344</orderId>
        <supplier>Apple</supplier>
    </product>
    <product>
        <description>Panasonic TC-L47E50 47" Smart TV Viera E50 Series LED
            HDTV</description>
        <gtin>00885170076471</gtin>
        <price>999.99</price>
        <orderId>2344</orderId>
        <supplier>Panasonic</supplier>
    </product>
</products>
</code>```

and I'm trying to get three XML documents like:

```<code> <?xml version="1.0" encoding="UTF-8"?>
<products>
        <product>
            <description>Sony 54.6" (Diag) Xbr Hx929 Internet Tv</description>
            <gtin>00027242816657</gtin>
            <price currency="USD">2999.99</price>
            <orderid>2343</orderid>
        </product>
        <product>
            <description>Sony NWZ-E464 8GB E Series Walkman Video MP3 Player Blue</description>
            <gtin>00027242831438</gtin>
            <price currency="USD">91.99</price>
            <orderid>2343</orderid>
        </product>
</products>
</code>```

one for each supplier. How can I receive it? Any help on this will be great.

答:
Consider this xml

```<code><?xml version="1.0"?>
<SSNExportDocument xmlns="urn:com:ssn:schema:export:SSNExportFormat.xsd" Version="0.1" DocumentID="b482350d-62bb-41be-b792-8a9fe3884601-1" ExportID="b482350d-62bb-41be-b792-8a9fe3884601" JobID="464" RunID="3532468" CreationTime="2019-04-16T02:20:01.332-04:00" StartTime="2019-04-15T20:20:00.000-04:00" EndTime="2019-04-16T02:20:00.000-04:00">
    <MeterData MeterName="MUNI1-11459398" UtilDeviceID="11459398" MacID="00:12:01:fae:fe:00:d5:fc">
        <RegisterData StartTime="2019-04-15T20:00:00.000-04:00" EndTime="2019-04-15T20:00:00.000-04:00" NumberReads="1">
            <RegisterRead ReadTime="2019-04-15T20:00:00.000-04:00" GatewayCollectedTime="2019-04-16T01:40:06.214-04:00" RegisterReadSource="REG_SRC_TYPE_EO_CURR_READ" Season="-1">
                <Tier Number="0">
                    <Register Number="1" Summation="5949.1000" SummationUOM="GAL"/>
                </Tier>
            </RegisterRead>
        </RegisterData>
    </MeterData>
    <MeterData MeterName="MUNI4-11460365" UtilDeviceID="11460365" MacID="00:11:01:bc:fe:00:d3:f9">
        <RegisterData StartTime="2019-04-15T20:00:00.000-04:00" EndTime="2019-04-15T20:00:00.000-04:00" NumberReads="1">
            <RegisterRead ReadTime="2019-04-15T20:00:00.000-04:00" GatewayCollectedTime="2019-04-16T01:40:11.082-04:00" RegisterReadSource="REG_SRC_TYPE_EO_CURR_READ" Season="-1">
                <Tier Number="0">
                    <Register Number="1" Summation="136349.9000" SummationUOM="GAL"/>
                </Tier>
            </RegisterRead>
        </RegisterData>
    </MeterData>
</code>```

We can use JAXB which converts your xml tags to objects. Then we can play around with them.

```<code>File xmlFile = new File("input.xml");
jaxbContext = JAXBContext.newInstance(SSNExportDocument.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
SSNExportDocument ssnExpDoc = (SSNExportDocument) jaxbUnmarshaller.unmarshal(xmlFile);
MeterData mD = new MeterData();
Map<String, List<MeterData>> meterMapper = new HashMap<String, List<MeterData>>(); // Phantom Reference

for (MeterData mData : ssnExpDoc.getMeterData()) {
            String meterFullName = mData.getMeterName();
            String[] splitMeterName = meterFullName.split("-");
            List<MeterData> _meterDataList = meterMapper.get(splitMeterName[0]);// o(1)
            if (_meterDataList == null) {
                _meterDataList = new ArrayList<>();
                _meterDataList.add(mData);
                meterMapper.put(splitMeterName[0], _meterDataList);
                _meterDataList = null;
            } else {
                _meterDataList.add(mData);
            }
        }
</code>```

meterMapper contains tag names against list of objects

Then Marshall the contents using

```<code>       JAXBContext jaxbContext = JAXBContext.newInstance(SSNExportDocument.class);

        // Create Marshaller
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // Required formatting??
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        //jaxbMarshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);

        // Print XML String to Console

        StringWriter sw = new StringWriter();

        // Write XML to StringWriter
        jaxbMarshaller.marshal(employee, sw);

        // Verify XML Content
        String xmlContent = sw.toString();
        System.out.println(xmlContent);
</code>```

Body:
I'm using XML files in Java for the first time and i need some help. I am trying to split an XML file to multiple XML files using Java

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<products>
    <product>
        <description>Sony 54.6" (Diag) Xbr Hx929 Internet Tv</description>
        <gtin>00027242816657</gtin>
        <price>2999.99</price>
        <orderId>2343</orderId>
        <supplier>Sony</supplier>
    </product>
    <product>
        <description>Apple iPad 2 with Wi-Fi 16GB - iOS 5 - Black
        </description>
        <gtin>00885909464517</gtin>
        <price>399.0</price>
        <orderId>2343</orderId>
        <supplier>Apple</supplier>
    </product>
    <product>
        <description>Sony NWZ-E464 8GB E Series Walkman Video MP3 Player Blue
        </description>
        <gtin>00027242831438</gtin>
        <price>91.99</price>
        <orderId>2343</orderId>
        <supplier>Sony</supplier>
    </product>
    <product>
        <description>Apple MacBook Air A 11.6" Mac OS X v10.7 Lion MacBook
        </description>
        <gtin>00885909464043</gtin>
        <price>1149.0</price>
        <orderId>2344</orderId>
        <supplier>Apple</supplier>
    </product>
    <product>
        <description>Panasonic TC-L47E50 47" Smart TV Viera E50 Series LED
            HDTV</description>
        <gtin>00885170076471</gtin>
        <price>999.99</price>
        <orderId>2344</orderId>
        <supplier>Panasonic</supplier>
    </product>
</products>

and I'm trying to get three XML documents like:

 <?xml version="1.0" encoding="UTF-8"?>
<products>
        <product>
            <description>Sony 54.6" (Diag) Xbr Hx929 Internet Tv</description>
            <gtin>00027242816657</gtin>
            <price currency="USD">2999.99</price>
            <orderid>2343</orderid>
        </product>
        <product>
            <description>Sony NWZ-E464 8GB E Series Walkman Video MP3 Player Blue</description>
            <gtin>00027242831438</gtin>
            <price currency="USD">91.99</price>
            <orderid>2343</orderid>
        </product>
</products>

one for each supplier. How can I receive it? Any help on this will be great.

Body:
Consider this xml

<?xml version="1.0"?>
<SSNExportDocument xmlns="urn:com:ssn:schema:export:SSNExportFormat.xsd" Version="0.1" DocumentID="b482350d-62bb-41be-b792-8a9fe3884601-1" ExportID="b482350d-62bb-41be-b792-8a9fe3884601" JobID="464" RunID="3532468" CreationTime="2019-04-16T02:20:01.332-04:00" StartTime="2019-04-15T20:20:00.000-04:00" EndTime="2019-04-16T02:20:00.000-04:00">
    <MeterData MeterName="MUNI1-11459398" UtilDeviceID="11459398" MacID="00:12:01:fae:fe:00:d5:fc">
        <RegisterData StartTime="2019-04-15T20:00:00.000-04:00" EndTime="2019-04-15T20:00:00.000-04:00" NumberReads="1">
            <RegisterRead ReadTime="2019-04-15T20:00:00.000-04:00" GatewayCollectedTime="2019-04-16T01:40:06.214-04:00" RegisterReadSource="REG_SRC_TYPE_EO_CURR_READ" Season="-1">
                <Tier Number="0">
                    <Register Number="1" Summation="5949.1000" SummationUOM="GAL"/>
                </Tier>
            </RegisterRead>
        </RegisterData>
    </MeterData>
    <MeterData MeterName="MUNI4-11460365" UtilDeviceID="11460365" MacID="00:11:01:bc:fe:00:d3:f9">
        <RegisterData StartTime="2019-04-15T20:00:00.000-04:00" EndTime="2019-04-15T20:00:00.000-04:00" NumberReads="1">
            <RegisterRead ReadTime="2019-04-15T20:00:00.000-04:00" GatewayCollectedTime="2019-04-16T01:40:11.082-04:00" RegisterReadSource="REG_SRC_TYPE_EO_CURR_READ" Season="-1">
                <Tier Number="0">
                    <Register Number="1" Summation="136349.9000" SummationUOM="GAL"/>
                </Tier>
            </RegisterRead>
        </RegisterData>
    </MeterData>

We can use JAXB which converts your xml tags to objects. Then we can play around with them.

File xmlFile = new File("input.xml");
jaxbContext = JAXBContext.newInstance(SSNExportDocument.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
SSNExportDocument ssnExpDoc = (SSNExportDocument) jaxbUnmarshaller.unmarshal(xmlFile);
MeterData mD = new MeterData();
Map<String, List<MeterData>> meterMapper = new HashMap<String, List<MeterData>>(); // Phantom Reference

for (MeterData mData : ssnExpDoc.getMeterData()) {
            String meterFullName = mData.getMeterName();
            String[] splitMeterName = meterFullName.split("-");
            List<MeterData> _meterDataList = meterMapper.get(splitMeterName[0]);// o(1)
            if (_meterDataList == null) {
                _meterDataList = new ArrayList<>();
                _meterDataList.add(mData);
                meterMapper.put(splitMeterName[0], _meterDataList);
                _meterDataList = null;
            } else {
                _meterDataList.add(mData);
            }
        }

meterMapper contains tag names against list of objects

Then Marshall the contents using

       JAXBContext jaxbContext = JAXBContext.newInstance(SSNExportDocument.class);

        // Create Marshaller
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // Required formatting??
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        //jaxbMarshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);

        // Print XML String to Console

        StringWriter sw = new StringWriter();

        // Write XML to StringWriter
        jaxbMarshaller.marshal(employee, sw);

        // Verify XML Content
        String xmlContent = sw.toString();
        System.out.println(xmlContent);


来源: stackexchange

问:
How to add a fixed View above the Sticky Header RecyclerView in Android Studio?
I implemented the Sticky Header successfully with the 'Flexible Adapter', and I want to place an EditText in between Toolbar and Sticky Header. But, now the header disappearing under the EditText while scrolling. Please help me for keeping Section Headers Sticky below the EditText.....

mylayout.xml is like this:

```<code>android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:layout_marginTop="?attr/actionBarSize">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:clipToPadding="false">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#F6FAFD">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"
            android:layout_marginRight="50dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:padding="10dp"
            android:background="@drawable/shape_white"
            android:text="000000"
            android:textSize="25sp"/>
    </FrameLayout>

    <include layout="@layout/my_recyclerview"/>

</LinearLayout>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    android:src="@drawable/ic_add_white_24dp" />
</code>```

This one I want to have

But now, the Section Header goes under the EditText

答:
I have removed your FrameLayout inside LinearLayout and added EditText directly inside LinearLayout. FrameLayout was needed there. here is my xml.

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="?attr/actionBarSize"
    android:clipToPadding="false">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:orientation="vertical">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"
            android:layout_marginTop="10dp"
            android:layout_marginRight="50dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/shape_white"
            android:padding="10dp"
            android:text="000000"
            android:textSize="25sp" />

        <include layout="@layout/my_recyclerview"/>

    </LinearLayout>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="16dp"
        android:src="@drawable/ic_add_white_24dp" />

</FrameLayout>
</code>```

Please check and let me know does it work for you or not?

ContentLicense: CC BY-SA 4.0

Body:
I implemented the Sticky Header successfully with the 'Flexible Adapter', and I want to place an EditText in between Toolbar and Sticky Header. But, now the header disappearing under the EditText while scrolling. Please help me for keeping Section Headers Sticky below the EditText.....

mylayout.xml is like this:

android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:layout_marginTop="?attr/actionBarSize">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:clipToPadding="false">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#F6FAFD">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"
            android:layout_marginRight="50dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:padding="10dp"
            android:background="@drawable/shape_white"
            android:text="000000"
            android:textSize="25sp"/>
    </FrameLayout>

    <include layout="@layout/my_recyclerview"/>

</LinearLayout>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    android:src="@drawable/ic_add_white_24dp" />

This one I want to have

But now, the Section Header goes under the EditText

Body:
I have removed your FrameLayout inside LinearLayout and added EditText directly inside LinearLayout. FrameLayout was needed there. here is my xml.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="?attr/actionBarSize"
    android:clipToPadding="false">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:orientation="vertical">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"
            android:layout_marginTop="10dp"
            android:layout_marginRight="50dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/shape_white"
            android:padding="10dp"
            android:text="000000"
            android:textSize="25sp" />

        <include layout="@layout/my_recyclerview"/>

    </LinearLayout>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="16dp"
        android:src="@drawable/ic_add_white_24dp" />

</FrameLayout>

Please check and let me know does it work for you or not?


问:
How to set Zookeeper IP address in ConsumerGroup instead of Kafka-Host IP address?
I have to set zookeeper IP address in ConsumerGroup instead of Kafka-Host IP address. Because I have set replication factor as 3 and 3 brokers were created. So, if one host fails then the another one can take over.

When I tried to put zookeeper IP address instead of Kafka-Host IP address in ConsumerGroup, it doesn't receive any messages which were sent from Producer API.

```<code>var kafka = require('kafka-node')
var ConsumerGroup = kafka.ConsumerGroup

function createConsumerGroup () {
  var options = {
    kafkaHost: '127.0.0.1:9092',
    batch: undefined,
    ssl: true,
    groupId: 'demoExample',
    protocol: ['roundrobin'],
    encoding: 'utf8',
    fromOffset: 'latest',
    commitOffsetsOnFirstJoin: true,
    outOfRangeOffset: 'earliest',
    onRebalance: (isAlreadyMember, callback) => { callback(); }
  }

  var consumerGroup = new ConsumerGroup(Object.assign({ id: 'demo-' + process.pid }, options), 'example')

  consumerGroup.on('message', function (message) {
    message.value = JSON.parse(message.value)
    console.log('Message Received')
  })
}
</code>```

I want that, if I pass zookeeper IP address in ConsumerGroup rather then Kafka-Host IP address, it should receive messages which were sent from Producer API on "example" topic. And if one broker fails then it should receive messages from another broker. As replication factor is set to 3 and 3 brokers were created.

答:
The new consumer API introduced in Kafka 0.9, does not require a connection with Zookeeper. Group balancing is now handled by Kafka itself. Therefore, you have to provide Kafka Host(s) instead of Zookeeper Host(s).

The blog post from Confluent should shed some more light:

At the time of the 0.8.2 release of Apache Kafka, which released the
  redesigned producer client, we had promised to redesign the consumer
  client as well. And we kept our promise: the 0.9 release introduces
  beta support for the newly redesigned consumer client. At a high
  level, the primary difference in the new consumer is that it removes
  the distinction between the “high-level” ZooKeeper-based consumer and
  the “low-level” SimpleConsumer APIs, and instead offers a unified
  consumer API.

This new consumer is implemented using a powerful new server-side
  facility that makes group management a first-class part of Kafka’s
  protocols. This has several advantages. First it allows for a much
  more scalable group facility, which allows the consumer clients to be
  much simpler and thinner and allows for larger groups with far faster
  rebalancing. This facility is available to all clients; work is
  already nearing completion to use it in the C client, librdkafka. This
  same facility turns out to be broadly useful for managing distributed
  producing and consuming of data in Kafka; it is the basis for Kafka
  Connect as well as several upcoming projects. Finally this completes a
  series of projects done in the last few years to fully decouple Kafka
  clients from Zookeeper, thus entirely removing the consumer client’s
  dependency on ZooKeeper. Zookeeper is still used by Kafka, but it is
  an implementation detail of the broker–clients that use this new
  facility have no need to connect to Zookeeper at all. This has a
  number of operational benefits since clients are now always working
  through the security and quota mechanisms the broker provides. This
  significantly simplifies the consumer and opens the door for
  first-class non-Java implementations of the consumer API to emerge
  over time.

Body:
I have to set zookeeper IP address in ConsumerGroup instead of Kafka-Host IP address. Because I have set replication factor as 3 and 3 brokers were created. So, if one host fails then the another one can take over.

When I tried to put zookeeper IP address instead of Kafka-Host IP address in ConsumerGroup, it doesn't receive any messages which were sent from Producer API.

var kafka = require('kafka-node')
var ConsumerGroup = kafka.ConsumerGroup

function createConsumerGroup () {
  var options = {
    kafkaHost: '127.0.0.1:9092',
    batch: undefined,
    ssl: true,
    groupId: 'demoExample',
    protocol: ['roundrobin'],
    encoding: 'utf8',
    fromOffset: 'latest',
    commitOffsetsOnFirstJoin: true,
    outOfRangeOffset: 'earliest',
    onRebalance: (isAlreadyMember, callback) => { callback(); }
  }

  var consumerGroup = new ConsumerGroup(Object.assign({ id: 'demo-' + process.pid }, options), 'example')

  consumerGroup.on('message', function (message) {
    message.value = JSON.parse(message.value)
    console.log('Message Received')
  })
}

I want that, if I pass zookeeper IP address in ConsumerGroup rather then Kafka-Host IP address, it should receive messages which were sent from Producer API on "example" topic. And if one broker fails then it should receive messages from another broker. As replication factor is set to 3 and 3 brokers were created.


问:
Service account fails to delete resources, even though it should have rights to do so
I have a service account monitoring:prometheus-operator-operator with a clusterrolebinding to to this clusterrole:

```<code>Name:         prometheus-operator-operator
Labels:       app=prometheus-operator-operator
              chart=prometheus-operator-5.7.0
              heritage=Tiller
              release=prometheus-operator
Annotations:  <none>
PolicyRule:
  Resources                                       Non-Resource URLs  Resource Names  Verbs
  ---------                                       -----------------  --------------  -----
  configmaps                                      []                 []              [*]
  secrets                                         []                 []              [*]
  customresourcedefinitions.apiextensions.k8s.io  []                 []              [*]
  statefulsets.apps                               []                 []              [*]
  alertmanagers.monitoring.coreos.com/finalizers  []                 []              [*]
  alertmanagers.monitoring.coreos.com             []                 []              [*]
  prometheuses.monitoring.coreos.com/finalizers   []                 []              [*]
  prometheuses.monitoring.coreos.com              []                 []              [*]
  prometheusrules.monitoring.coreos.com           []                 []              [*]
  servicemonitors.monitoring.coreos.com           []                 []              [*]
  endpoints                                       []                 []              [get create update]
  services                                        []                 []              [get create update]
  namespaces                                      []                 []              [get list watch]
  pods                                            []                 []              [list delete]
  nodes                                           []                 []              [list watch]
</code>```

Now, I am attempting to run this

```<code>curl -ik -X DELETE \
  -H "Authorization: Bearer <SERVICE_ACCOUNT_TOKEN>" \
  https://kubernetes.default.svc/apis/monitoring.coreos.com/v1/monitoring/prometheusrules/zalenium
</code>```

from within a pod in the cluster to delete a PrometheusRule.

My request however is not successful and being rejected with a 403:

```<code>{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {},
  "status": "Failure",
  "message": "monitoring.monitoring.coreos.com \"prometheusrules\" is forbidden: User \"system:serviceaccount:monitoring:prometheus-operator-operator\" cannot delete resource \"monitoring/zalenium\" in API group \"monitoring.coreos.com\" at the cluster scope",
  "reason": "Forbidden",
  "details": {
    "name": "prometheusrules",
    "group": "monitoring.coreos.com",
    "kind": "monitoring"
  },
  "code": 403
}
</code>```

Am I wrong believing that the service account in my monitoring namespace should be able to delete PrometheusRule on the cluster level?

To me everything looks correct and I don't understand why I get a Forbidden response.

答:
you forgot to put namespace in the URI

```<code>
curl -ik -X DELETE \
  -H "Authorization: Bearer <SERVICE_ACCOUNT_TOKEN>" \
  https://kubernetes.default.svc/apis/monitoring.coreos.com/v1/namespaces/monitoring/prometheusrules/zalenium

</code>```

with the following command you can verify the if you are allowed to take action X with the resoucres Y

kubectl auth can-i delete prometheusrules --as system:serviceaccount:monitoring:prometheus-operator-operator -n monitoring

With the -v flag you can increase the verbosity of the request which also provides a request in curl form.

Body:
I have a service account monitoring:prometheus-operator-operator with a clusterrolebinding to to this clusterrole:

Name:         prometheus-operator-operator
Labels:       app=prometheus-operator-operator
              chart=prometheus-operator-5.7.0
              heritage=Tiller
              release=prometheus-operator
Annotations:  <none>
PolicyRule:
  Resources                                       Non-Resource URLs  Resource Names  Verbs
  ---------                                       -----------------  --------------  -----
  configmaps                                      []                 []              [*]
  secrets                                         []                 []              [*]
  customresourcedefinitions.apiextensions.k8s.io  []                 []              [*]
  statefulsets.apps                               []                 []              [*]
  alertmanagers.monitoring.coreos.com/finalizers  []                 []              [*]
  alertmanagers.monitoring.coreos.com             []                 []              [*]
  prometheuses.monitoring.coreos.com/finalizers   []                 []              [*]
  prometheuses.monitoring.coreos.com              []                 []              [*]
  prometheusrules.monitoring.coreos.com           []                 []              [*]
  servicemonitors.monitoring.coreos.com           []                 []              [*]
  endpoints                                       []                 []              [get create update]
  services                                        []                 []              [get create update]
  namespaces                                      []                 []              [get list watch]
  pods                                            []                 []              [list delete]
  nodes                                           []                 []              [list watch]

Now, I am attempting to run this

curl -ik -X DELETE \
  -H "Authorization: Bearer <SERVICE_ACCOUNT_TOKEN>" \
  https://kubernetes.default.svc/apis/monitoring.coreos.com/v1/monitoring/prometheusrules/zalenium

from within a pod in the cluster to delete a PrometheusRule.

My request however is not successful and being rejected with a 403:

{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {},
  "status": "Failure",
  "message": "monitoring.monitoring.coreos.com \"prometheusrules\" is forbidden: User \"system:serviceaccount:monitoring:prometheus-operator-operator\" cannot delete resource \"monitoring/zalenium\" in API group \"monitoring.coreos.com\" at the cluster scope",
  "reason": "Forbidden",
  "details": {
    "name": "prometheusrules",
    "group": "monitoring.coreos.com",
    "kind": "monitoring"
  },
  "code": 403
}

Am I wrong believing that the service account in my monitoring namespace should be able to delete PrometheusRule on the cluster level?

To me everything looks correct and I don't understand why I get a Forbidden response.

Body:
you forgot to put namespace in the URI

curl -ik -X DELETE \
  -H "Authorization: Bearer <SERVICE_ACCOUNT_TOKEN>" \
  https://kubernetes.default.svc/apis/monitoring.coreos.com/v1/namespaces/monitoring/prometheusrules/zalenium

with the following command you can verify the if you are allowed to take action X with the resoucres Y

kubectl auth can-i delete prometheusrules --as system:serviceaccount:monitoring:prometheus-operator-operator -n monitoring

With the -v flag you can increase the verbosity of the request which also provides a request in curl form.


问:
Bootstrap collapse scroll to bottom issue
I have a bootstrap collapse panel. In there I have placed toggle link bottom of the content so it will go down and up when click that link.

The problem

I have a long list of content. I need to move users to top when they click toggle. But in here, when I expand the menu and click collapse, it will go all the way to bottom of the page. Instead of I need to move users to the top of the page. I tried to set offset top but no luck.

Any idea?

My Jquery

```<code>$('html,body').animate({
     scrollTop: $(".collapsed").offset().top
 },500);
</code>```

jsfiddle

答:
if I correctly understood, you need to scroll top when collapse area is hidden, try to use this. The collapse has hide.bs.collapse event that fires immediately when the hide method has been called, default interval for the collapse is 350ms, as you won't see the end of your site, scroll interval should be less than the default.

Sorry for my bad english...

Update

I re-read all comments, your problem is that you try to scroll to toggle button instead collapse area, you scroll to the button when area not closed and it is on the bottom, just scroll to panel-collapse....

$(document).ready(function() {
  $('.panel-collapse').on('hide.bs.collapse show.bs.collapse', function(e) {
   $('html, body').animate({
      scrollTop: $(e.target).offset().top - 20
    }, 150);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
  <div class="col-md-6 col-sm-6 col-xs-6">
    <div class="panel-group" id="accordion">
  <div class="panel panel-default" id="panel1">

    <div id="collapseOne" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
         <p>Cras eleifend feugiat lectus ac lobortis. Ut vestibulum nulla odio, ut vulputate urna euismod et. Duis elementum nulla quis nulla fringilla dignissim. Fusce vitae turpis leo. Integer tincidunt sapien id sem feugiat, et vulputate dolor varius. Sed et pharetra orci. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
    <p>
      Proin ac ultrices tellus, vel scelerisque tellus. Donec porttitor pharetra congue. Donec ultrices ligula in felis varius, in maximus nibh ornare. Sed augue felis, interdum in cursus ornare, porta rutrum turpis. Aliquam rutrum massa id dui cursus, non imperdiet ligula viverra. In convallis placerat lectus, at sollicitudin lectus interdum vitae. Proin cursus tempor eros, eget ultrices nisi feugiat at. Praesent scelerisque felis id nisi tempus aliquet. Vivamus vehicula, augue at ultricies viverra, arcu quam pretium lectus, nec accumsan est dolor vel quam. Aenean scelerisque sodales libero, at elementum lorem mollis id.
    </p>
    <p>Mauris vel laoreet ante. Maecenas ut gravida tellus, eu egestas nisi. Nam elementum lacus nec odio ultrices, quis viverra massa congue. Nunc rutrum orci ac luctus aliquam. Vivamus et lorem laoreet erat condimentum feugiat imperdiet ac orci. Praesent faucibus lacus et nibh vestibulum dapibus vitae maximus lorem. Donec vulputate, sem vel posuere dictum, arcu lacus faucibus ante, sit amet luctus nulla nisi eu diam. Phasellus sit amet augue eu nisi auctor tincidunt. Vivamus tristique sem dignissim risus interdum, vel commodo tellus maximus. Vestibulum scelerisque mi finibus nibh sollicitudin sollicitudin. Sed porttitor diam tortor, id vestibulum neque vulputate semper. Cras scelerisque laoreet diam viverra rutrum. Vivamus a imperdiet tellus. Etiam aliquet eros luctus auctor condimentum. Nulla lacinia est sit amet vulputate fringilla. Phasellus fringilla nulla lectus.</p>
      </div>
    </div>
    <div class="panel-heading">
      <h4 class="panel-title">

          Collapsible Group Item #1

      </h4>
    </div>
  </div>
  <div class="panel panel-default" id="panel1">

    <div id="collapseTwo" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
         <p>Cras eleifend feugiat lectus ac lobortis. Ut vestibulum nulla odio, ut vulputate urna euismod et. Duis elementum nulla quis nulla fringilla dignissim. Fusce vitae turpis leo. Integer tincidunt sapien id sem feugiat, et vulputate dolor varius. Sed et pharetra orci. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
    <p>
      Proin ac ultrices tellus, vel scelerisque tellus. Donec porttitor pharetra congue. Donec ultrices ligula in felis varius, in maximus nibh ornare. Sed augue felis, interdum in cursus ornare, porta rutrum turpis. Aliquam rutrum massa id dui cursus, non imperdiet ligula viverra. In convallis placerat lectus, at sollicitudin lectus interdum vitae. Proin cursus tempor eros, eget ultrices nisi feugiat at. Praesent scelerisque felis id nisi tempus aliquet. Vivamus vehicula, augue at ultricies viverra, arcu quam pretium lectus, nec accumsan est dolor vel quam. Aenean scelerisque sodales libero, at elementum lorem mollis id.
    </p>
    <p>Mauris vel laoreet ante. Maecenas ut gravida tellus, eu egestas nisi. Nam elementum lacus nec odio ultrices, quis viverra massa congue. Nunc rutrum orci ac luctus aliquam. Vivamus et lorem laoreet erat condimentum feugiat imperdiet ac orci. Praesent faucibus lacus et nibh vestibulum dapibus vitae maximus lorem. Donec vulputate, sem vel posuere dictum, arcu lacus faucibus ante, sit amet luctus nulla nisi eu diam. Phasellus sit amet augue eu nisi auctor tincidunt. Vivamus tristique sem dignissim risus interdum, vel commodo tellus maximus. Vestibulum scelerisque mi finibus nibh sollicitudin sollicitudin. Sed porttitor diam tortor, id vestibulum neque vulputate semper. Cras scelerisque laoreet diam viverra rutrum. Vivamus a imperdiet tellus. Etiam aliquet eros luctus auctor condimentum. Nulla lacinia est sit amet vulputate fringilla. Phasellus fringilla nulla lectus.</p>
      </div>
    </div>
    <div class="panel-heading">
      <h4 class="panel-title">

          Collapsible Group Item #1

      </h4>
    </div>
  </div>
  <div class="panel panel-default" id="panel1">

    <div id="collapseThree" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
         <p>Cras eleifend feugiat lectus ac lobortis. Ut vestibulum nulla odio, ut vulputate urna euismod et. Duis elementum nulla quis nulla fringilla dignissim. Fusce vitae turpis leo. Integer tincidunt sapien id sem feugiat, et vulputate dolor varius. Sed et pharetra orci. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
    <p>
      Proin ac ultrices tellus, vel scelerisque tellus. Donec porttitor pharetra congue. Donec ultrices ligula in felis varius, in maximus nibh ornare. Sed augue felis, interdum in cursus ornare, porta rutrum turpis. Aliquam rutrum massa id dui cursus, non imperdiet ligula viverra. In convallis placerat lectus, at sollicitudin lectus interdum vitae. Proin cursus tempor eros, eget ultrices nisi feugiat at. Praesent scelerisque felis id nisi tempus aliquet. Vivamus vehicula, augue at ultricies viverra, arcu quam pretium lectus, nec accumsan est dolor vel quam. Aenean scelerisque sodales libero, at elementum lorem mollis id.
    </p>
    <p>Mauris vel laoreet ante. Maecenas ut gravida tellus, eu egestas nisi. Nam elementum lacus nec odio ultrices, quis viverra massa congue. Nunc rutrum orci ac luctus aliquam. Vivamus et lorem laoreet erat condimentum feugiat imperdiet ac orci. Praesent faucibus lacus et nibh vestibulum dapibus vitae maximus lorem. Donec vulputate, sem vel posuere dictum, arcu lacus faucibus ante, sit amet luctus nulla nisi eu diam. Phasellus sit amet augue eu nisi auctor tincidunt. Vivamus tristique sem dignissim risus interdum, vel commodo tellus maximus. Vestibulum scelerisque mi finibus nibh sollicitudin sollicitudin. Sed porttitor diam tortor, id vestibulum neque vulputate semper. Cras scelerisque laoreet diam viverra rutrum. Vivamus a imperdiet tellus. Etiam aliquet eros luctus auctor condimentum. Nulla lacinia est sit amet vulputate fringilla. Phasellus fringilla nulla lectus.</p>
      </div>
    </div>
    <div class="panel-heading">
      <h4 class="panel-title">

          Collapsible Group Item #1

      </h4>
    </div>
  </div>
  </div>
  <br>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse in elementum sapien. Etiam non tellus ut diam sagittis ultricies. Sed ornare quis ex ut ornare. Duis at fermentum purus, et ultricies ex. Sed id porta metus. Nunc posuere, ex at maximus ullamcorper, arcu orci tempus justo, id efficitur massa erat et ipsum. Maecenas pharetra et est quis varius. Donec id tincidunt erat, ac bibendum lorem. Fusce pellentesque, leo ac molestie lacinia, neque leo elementum velit, vitae porta lectus justo quis nisi. Cras quis sem accumsan, faucibus ligula in, vehicula erat. Maecenas semper eros ultrices sem ultrices, a po</p>
 </div>

 <!-- dib -->
  <div class="col-md-6 col-sm-6 col-xs-6">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse in elementum sapien. Etiam non tellus ut diam sagittis ultricies. Sed ornare quis ex ut ornare. Duis at fermentum purus, et ultricies ex. Sed id porta metus. Nunc posuere, ex at maximus ullamcorper, arcu orci tempus justo, id efficitur massa erat et ipsum. Maecenas pharetra et est quis varius. Donec id tincidunt erat, ac bibendum lorem. Fusce pellentesque, leo ac molestie lacinia, neque leo elementum velit, vitae porta lectus justo quis nisi. Cras quis sem accumsan, faucibus ligula in, vehicula erat. Maecenas semper eros ultrices sem ultrices, a posuere urna posuere.</p>

  </div>
</div>
<br><br><br><br><br><br><br><br>
<!-- roew -->
<div class="row">
  <div class="col-md-12">
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse in elementum sapien. Etiam non tellus ut diam sagittis ultricies. Sed ornare quis ex ut ornare. Duis at fermentum purus, et ultricies ex. Sed id porta metus. Nunc posuere, ex at maximus ullamcorper, arcu orci tempus justo, id efficitur massa erat et ipsum. Maecenas pharetra et est quis varius. Donec id tincidunt erat, ac bibendum lorem. Fusce pellentesque, leo ac molestie lacinia, neque leo elementum velit, vitae porta lectus justo quis nisi. Cras quis sem accumsan, faucibus ligula in, vehicula erat. Maecenas semper eros ultrices sem ultrices, a posuere urna posuere.</p>
  </div>
</div>
</div></code>```

Body:
I have a bootstrap collapse panel. In there I have placed toggle link bottom of the content so it will go down and up when click that link.

The problem

I have a long list of content. I need to move users to top when they click toggle. But in here, when I expand the menu and click collapse, it will go all the way to bottom of the page. Instead of I need to move users to the top of the page. I tried to set offset top but no luck.

Any idea?

My Jquery

$('html,body').animate({
     scrollTop: $(".collapsed").offset().top
 },500);

jsfiddle

Body:
if I correctly understood, you need to scroll top when collapse area is hidden, try to use this. The collapse has hide.bs.collapse event that fires immediately when the hide method has been called, default interval for the collapse is 350ms, as you won't see the end of your site, scroll interval should be less than the default.

Sorry for my bad english...

Update

I re-read all comments, your problem is that you try to scroll to toggle button instead collapse area, you scroll to the button when area not closed and it is on the bottom, just scroll to panel-collapse....

$(document).ready(function() {
  $('.panel-collapse').on('hide.bs.collapse show.bs.collapse', function(e) {
   $('html, body').animate({
      scrollTop: $(e.target).offset().top - 20
    }, 150);
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
  <div class="col-md-6 col-sm-6 col-xs-6">
    <div class="panel-group" id="accordion">
  <div class="panel panel-default" id="panel1">

    <div id="collapseOne" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
         <p>Cras eleifend feugiat lectus ac lobortis. Ut vestibulum nulla odio, ut vulputate urna euismod et. Duis elementum nulla quis nulla fringilla dignissim. Fusce vitae turpis leo. Integer tincidunt sapien id sem feugiat, et vulputate dolor varius. Sed et pharetra orci. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
    <p>
      Proin ac ultrices tellus, vel scelerisque tellus. Donec porttitor pharetra congue. Donec ultrices ligula in felis varius, in maximus nibh ornare. Sed augue felis, interdum in cursus ornare, porta rutrum turpis. Aliquam rutrum massa id dui cursus, non imperdiet ligula viverra. In convallis placerat lectus, at sollicitudin lectus interdum vitae. Proin cursus tempor eros, eget ultrices nisi feugiat at. Praesent scelerisque felis id nisi tempus aliquet. Vivamus vehicula, augue at ultricies viverra, arcu quam pretium lectus, nec accumsan est dolor vel quam. Aenean scelerisque sodales libero, at elementum lorem mollis id.
    </p>
    <p>Mauris vel laoreet ante. Maecenas ut gravida tellus, eu egestas nisi. Nam elementum lacus nec odio ultrices, quis viverra massa congue. Nunc rutrum orci ac luctus aliquam. Vivamus et lorem laoreet erat condimentum feugiat imperdiet ac orci. Praesent faucibus lacus et nibh vestibulum dapibus vitae maximus lorem. Donec vulputate, sem vel posuere dictum, arcu lacus faucibus ante, sit amet luctus nulla nisi eu diam. Phasellus sit amet augue eu nisi auctor tincidunt. Vivamus tristique sem dignissim risus interdum, vel commodo tellus maximus. Vestibulum scelerisque mi finibus nibh sollicitudin sollicitudin. Sed porttitor diam tortor, id vestibulum neque vulputate semper. Cras scelerisque laoreet diam viverra rutrum. Vivamus a imperdiet tellus. Etiam aliquet eros luctus auctor condimentum. Nulla lacinia est sit amet vulputate fringilla. Phasellus fringilla nulla lectus.</p>
      </div>
    </div>
    <div class="panel-heading">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
          Collapsible Group Item #1
        </a>
      </h4>
    </div>
  </div>
  <div class="panel panel-default" id="panel1">

    <div id="collapseTwo" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
         <p>Cras eleifend feugiat lectus ac lobortis. Ut vestibulum nulla odio, ut vulputate urna euismod et. Duis elementum nulla quis nulla fringilla dignissim. Fusce vitae turpis leo. Integer tincidunt sapien id sem feugiat, et vulputate dolor varius. Sed et pharetra orci. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
    <p>
      Proin ac ultrices tellus, vel scelerisque tellus. Donec porttitor pharetra congue. Donec ultrices ligula in felis varius, in maximus nibh ornare. Sed augue felis, interdum in cursus ornare, porta rutrum turpis. Aliquam rutrum massa id dui cursus, non imperdiet ligula viverra. In convallis placerat lectus, at sollicitudin lectus interdum vitae. Proin cursus tempor eros, eget ultrices nisi feugiat at. Praesent scelerisque felis id nisi tempus aliquet. Vivamus vehicula, augue at ultricies viverra, arcu quam pretium lectus, nec accumsan est dolor vel quam. Aenean scelerisque sodales libero, at elementum lorem mollis id.
    </p>
    <p>Mauris vel laoreet ante. Maecenas ut gravida tellus, eu egestas nisi. Nam elementum lacus nec odio ultrices, quis viverra massa congue. Nunc rutrum orci ac luctus aliquam. Vivamus et lorem laoreet erat condimentum feugiat imperdiet ac orci. Praesent faucibus lacus et nibh vestibulum dapibus vitae maximus lorem. Donec vulputate, sem vel posuere dictum, arcu lacus faucibus ante, sit amet luctus nulla nisi eu diam. Phasellus sit amet augue eu nisi auctor tincidunt. Vivamus tristique sem dignissim risus interdum, vel commodo tellus maximus. Vestibulum scelerisque mi finibus nibh sollicitudin sollicitudin. Sed porttitor diam tortor, id vestibulum neque vulputate semper. Cras scelerisque laoreet diam viverra rutrum. Vivamus a imperdiet tellus. Etiam aliquet eros luctus auctor condimentum. Nulla lacinia est sit amet vulputate fringilla. Phasellus fringilla nulla lectus.</p>
      </div>
    </div>
    <div class="panel-heading">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
          Collapsible Group Item #1
        </a>
      </h4>
    </div>
  </div>
  <div class="panel panel-default" id="panel1">

    <div id="collapseThree" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
         <p>Cras eleifend feugiat lectus ac lobortis. Ut vestibulum nulla odio, ut vulputate urna euismod et. Duis elementum nulla quis nulla fringilla dignissim. Fusce vitae turpis leo. Integer tincidunt sapien id sem feugiat, et vulputate dolor varius. Sed et pharetra orci. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
    <p>
      Proin ac ultrices tellus, vel scelerisque tellus. Donec porttitor pharetra congue. Donec ultrices ligula in felis varius, in maximus nibh ornare. Sed augue felis, interdum in cursus ornare, porta rutrum turpis. Aliquam rutrum massa id dui cursus, non imperdiet ligula viverra. In convallis placerat lectus, at sollicitudin lectus interdum vitae. Proin cursus tempor eros, eget ultrices nisi feugiat at. Praesent scelerisque felis id nisi tempus aliquet. Vivamus vehicula, augue at ultricies viverra, arcu quam pretium lectus, nec accumsan est dolor vel quam. Aenean scelerisque sodales libero, at elementum lorem mollis id.
    </p>
    <p>Mauris vel laoreet ante. Maecenas ut gravida tellus, eu egestas nisi. Nam elementum lacus nec odio ultrices, quis viverra massa congue. Nunc rutrum orci ac luctus aliquam. Vivamus et lorem laoreet erat condimentum feugiat imperdiet ac orci. Praesent faucibus lacus et nibh vestibulum dapibus vitae maximus lorem. Donec vulputate, sem vel posuere dictum, arcu lacus faucibus ante, sit amet luctus nulla nisi eu diam. Phasellus sit amet augue eu nisi auctor tincidunt. Vivamus tristique sem dignissim risus interdum, vel commodo tellus maximus. Vestibulum scelerisque mi finibus nibh sollicitudin sollicitudin. Sed porttitor diam tortor, id vestibulum neque vulputate semper. Cras scelerisque laoreet diam viverra rutrum. Vivamus a imperdiet tellus. Etiam aliquet eros luctus auctor condimentum. Nulla lacinia est sit amet vulputate fringilla. Phasellus fringilla nulla lectus.</p>
      </div>
    </div>
    <div class="panel-heading">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
          Collapsible Group Item #1
        </a>
      </h4>
    </div>
  </div>
  </div>
  <br>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse in elementum sapien. Etiam non tellus ut diam sagittis ultricies. Sed ornare quis ex ut ornare. Duis at fermentum purus, et ultricies ex. Sed id porta metus. Nunc posuere, ex at maximus ullamcorper, arcu orci tempus justo, id efficitur massa erat et ipsum. Maecenas pharetra et est quis varius. Donec id tincidunt erat, ac bibendum lorem. Fusce pellentesque, leo ac molestie lacinia, neque leo elementum velit, vitae porta lectus justo quis nisi. Cras quis sem accumsan, faucibus ligula in, vehicula erat. Maecenas semper eros ultrices sem ultrices, a po</p>
 </div>

 <!-- dib -->
  <div class="col-md-6 col-sm-6 col-xs-6">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse in elementum sapien. Etiam non tellus ut diam sagittis ultricies. Sed ornare quis ex ut ornare. Duis at fermentum purus, et ultricies ex. Sed id porta metus. Nunc posuere, ex at maximus ullamcorper, arcu orci tempus justo, id efficitur massa erat et ipsum. Maecenas pharetra et est quis varius. Donec id tincidunt erat, ac bibendum lorem. Fusce pellentesque, leo ac molestie lacinia, neque leo elementum velit, vitae porta lectus justo quis nisi. Cras quis sem accumsan, faucibus ligula in, vehicula erat. Maecenas semper eros ultrices sem ultrices, a posuere urna posuere.</p>

  </div>
</div>
<br><br><br><br><br><br><br><br>
<!-- roew -->
<div class="row">
  <div class="col-md-12">
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse in elementum sapien. Etiam non tellus ut diam sagittis ultricies. Sed ornare quis ex ut ornare. Duis at fermentum purus, et ultricies ex. Sed id porta metus. Nunc posuere, ex at maximus ullamcorper, arcu orci tempus justo, id efficitur massa erat et ipsum. Maecenas pharetra et est quis varius. Donec id tincidunt erat, ac bibendum lorem. Fusce pellentesque, leo ac molestie lacinia, neque leo elementum velit, vitae porta lectus justo quis nisi. Cras quis sem accumsan, faucibus ligula in, vehicula erat. Maecenas semper eros ultrices sem ultrices, a posuere urna posuere.</p>
  </div>
</div>
</div>


问:
My floating icon goes behind contents of my website
I am trying to add a floating icon in my website. The code I used is
html

```<code><a href="#" class="floata">
<i class="fa fa-plus my-floata"></i>
</a>
</code>```

css

```<code>.floata{
    position:fixed;
    width:60px;
    height:60px;
    bottom:40px;
    right:40px;
    background-color:#0C9;
    color:#FFF;
    border-radius:50px;
    text-align:center;
    box-shadow: 2px 2px 3px #999;
}

.my-floata{
    margin-top:22px;
}
</code>```

In mobile and sometimes in pc it shows behind website content in my site at https://demo.justinechacko.in/

答:
Look at z-index, this is for specifying the layer on which the node is drawn.

At your homepage, 3 was needed to be over the pictures:

.floata {
  z-index: 3;
}
```

Body:
I am trying to add a floating icon in my website. The code I used is
html

css

.floata{
    position:fixed;
    width:60px;
    height:60px;
    bottom:40px;
    right:40px;
    background-color:#0C9;
    color:#FFF;
    border-radius:50px;
    text-align:center;
    box-shadow: 2px 2px 3px #999;
}

.my-floata{
    margin-top:22px;
}

In mobile and sometimes in pc it shows behind website content in my site at https://demo.justinechacko.in/


问:
Gcloud kubernetes cluster access to internet
A Pod in gcloud kubernetes cluster is not accessible from the internet. Access from kubernetes or cloud shell works fine.

There a serveral ways to make a pod accessible from outside kubernetes cluster. I have tried three different ways.

My kubernetes cluster is not private, means that the command

```<code>kubectl get nodes - o wide
</code>```

has an external ip address. The ip is reachable from outside the gc project.

I created a pod with a Pod yaml, not with a deploymentConfig. Pod has two container Ports:

```<code>ports:
  - containerPort: 8500
  - containerPort: 8501
</code>```

Pod is running Ports are open inside the container. Now I have created services in different ways.

Creating different services. Service and pod are connected over selector

```<code>app=myapp
</code>```

1 NodePort: Using the external ip address from kubernetes cluster. I created a service from type NodePort. Accesss should work over clusterIP:

2 LoadBalancer: Creating a service from type Loadbalanacer creates an external ip address for the service.

```<code>kubectl get service -o wide

kubectl expose pod myapp --port 8500 --target-port=8500 --type=Loadbalancer
</code>```

I got a second external ip address. Access from out side over "ip-address:port" did not work

3 HostPort: The container port will be exposed to the external network at :, where the hostIP is the IP address of the Kubernetes node where the container is running and the hostPort is the port requested by the user.

Using this tutorial: http://alesnosek.com/blog/2017/02/14/accessing-kubernetes-pods-from-outside-of-the-cluster/

The only thing worked for me was to use Port 80. I used Port 80 for rest endpoint, but I have 2 endpoints rest and grpc and both should be provided.

Overall I created firewall rules for the ports I used:

```<code>gcloud compute firewall-rules create MY-RULE \
  --allow tcp:8500-8501
</code>```

Nothing worked for me. Now I believe that I am missing something.

答:
Let's focus on the second option you tried (expose app via LoadBalancer):

I'm assuming you are using GKE (Google Kubernetes Engine)

First of all I can see you have a typo in your 'expose' command (service types are case sensitive):

change:

```<code>--type=Loadbalancer
</code>```

to:

```<code>--type=LoadBalancer
</code>```

You are not doing anything wrong, so exposing HTTP(s) service should work, please verify quickly if your Kubernetes cluster is fully functional with following commands:

```<code>kubectl create ns demo
kubectl -n demo run myapp --generator=run-pod/v1 --image=nginx
kubectl -n demo expose pod myapp --port 8500 --target-port=80 --type=LoadBalancer
</code>```

and try to reach app on <EXTERNAL-IP>:<8500>

for grpc-services the things are getting more difficult, please follow this tutorial on how to do this on GKE.

Body:
A Pod in gcloud kubernetes cluster is not accessible from the internet. Access from kubernetes or cloud shell works fine.

There a serveral ways to make a pod accessible from outside kubernetes cluster. I have tried three different ways.

My kubernetes cluster is not private, means that the command

kubectl get nodes - o wide

has an external ip address. The ip is reachable from outside the gc project.

I created a pod with a Pod yaml, not with a deploymentConfig. Pod has two container Ports:

ports:
  - containerPort: 8500
  - containerPort: 8501

Pod is running Ports are open inside the container. Now I have created services in different ways.

Creating different services. Service and pod are connected over selector

app=myapp

1 NodePort: Using the external ip address from kubernetes cluster. I created a service from type NodePort. Accesss should work over clusterIP:

2 LoadBalancer: Creating a service from type Loadbalanacer creates an external ip address for the service.

kubectl get service -o wide

kubectl expose pod myapp --port 8500 --target-port=8500 --type=Loadbalancer

I got a second external ip address. Access from out side over "ip-address:port" did not work

3 HostPort: The container port will be exposed to the external network at :, where the hostIP is the IP address of the Kubernetes node where the container is running and the hostPort is the port requested by the user.

Using this tutorial: http://alesnosek.com/blog/2017/02/14/accessing-kubernetes-pods-from-outside-of-the-cluster/

The only thing worked for me was to use Port 80. I used Port 80 for rest endpoint, but I have 2 endpoints rest and grpc and both should be provided.

Overall I created firewall rules for the ports I used:

gcloud compute firewall-rules create MY-RULE \
  --allow tcp:8500-8501

Nothing worked for me. Now I believe that I am missing something.

Body:
Let's focus on the second option you tried (expose app via LoadBalancer):

I'm assuming you are using GKE (Google Kubernetes Engine)

First of all I can see you have a typo in your 'expose' command (service types are case sensitive):

change:

--type=Loadbalancer

to:

--type=LoadBalancer

You are not doing anything wrong, so exposing HTTP(s) service should work, please verify quickly if your Kubernetes cluster is fully functional with following commands:

kubectl create ns demo
kubectl -n demo run myapp --generator=run-pod/v1 --image=nginx
kubectl -n demo expose pod myapp --port 8500 --target-port=80 --type=LoadBalancer

and try to reach app on <EXTERNAL-IP>:<8500>

for grpc-services the things are getting more difficult, please follow this tutorial on how to do this on GKE.


问:
convert a key value pair into 2 different objects
Let me explain here

```<code>let obj = {manager:XYZ}
//output:[{position:"manager",name:"XYZ"}]
</code>```

you can also use lodash to find the solution

答:
Using Object.entries, map and some destructuring you can come to a simple solution:

let obj = { manager: "XYZ" };

console.log(
  Object.entries(obj).map(([position, name]) => ({ position, name }))
);```

Body:
Let me explain here

let obj = {manager:XYZ}
//output:[{position:"manager",name:"XYZ"}]

you can also use lodash to find the solution


问:
Failed to lookup view "home/index" in views directory "/app/views"
I am trying to publish my project to heroku to make it run in the cloud. Locally it works on port 5000, and i can get every view. When i upload it to heroku, i get the following error when i try to reach the home page: Failed to lookup view "home/index" in views directory "/app/views"

I already tried to do the following:

```<code>app.set('views', __dirname + '/views');
app.set('view engine', 'ejs'); // set up ejs for templating
</code>```

I also looked on the internet for other solutions, but nothing seems to fix my problem.

My route looks like this:

views/home/index.ejs

The code that looks for the file is:

```<code>        app.get('/', function (req, res) {
            res.render('home/index.ejs'); // load the index.ejs file
        });
</code>```

The expected output is that my heroku is working fine without making big changes, so it can both work on heroku and locally. At the moment heroku is giving back the above error.

答:
It is because Heroku can't find the sub-folder home inside the views folder.  This is very likely because you might have written the folder as 'Home' instead of 'home'.  To find out, do a heroku run bash and then run ls.  This will list the folders inside the /app folder.  Once inside the working directory, you should see the views folder.  do a cd views and you will have the list of all the folders.  There you should find the home folder.  If you find a Views instead of views or Home instead or no home at all, then that is where the error comes from since in heroku, folder and file paths are case sensitive (in local it is not and that is why you don't run into the same error in localhost port 5000).

Once you fix the folder and file names to the appropriate case, do a push on Heroku and it should work.  Also be careful to test again to see if in heroku run bash it worked, and the cd home works.  If it doesn't then you need to delete the home folder, push into Heroku and then repaste the home folder and do the push (because of cache) and then it should work.

Body:
I am trying to publish my project to heroku to make it run in the cloud. Locally it works on port 5000, and i can get every view. When i upload it to heroku, i get the following error when i try to reach the home page: Failed to lookup view "home/index" in views directory "/app/views"

I already tried to do the following:

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs'); // set up ejs for templating

I also looked on the internet for other solutions, but nothing seems to fix my problem.

My route looks like this:

views/home/index.ejs

The code that looks for the file is:

        app.get('/', function (req, res) {
            res.render('home/index.ejs'); // load the index.ejs file
        });

The expected output is that my heroku is working fine without making big changes, so it can both work on heroku and locally. At the moment heroku is giving back the above error.


问:
Why can't I delete this cookie?
From PHP, I'm having trouble getting the browser to delete a cookie. To chase down the problem, I have created a simple test page that just does this:

```<code>// Set cookie named MrPants with value foo to expire at end of session
setcookie("MrPants", "foo", 0);
</code>```

After loading that page, I see the cookie in my Firefox cookies menu. So far, so good.

Then I follow example #2 here to delete a cookie:

```<code>// Set that cookie's expires time in the past
setcookie("MrPants", "", time() - 3600);
</code>```

This has no effect. I have tried specifying the path, too; no change.

In Firebug, I see the following in the response headers:

```<code>Set-Cookie ZDEDebuggerPresent=php,phtml,php3; path=/
MrPants=deleted; expires=Tue, 25-Aug-2009 15:27:46 GMT; path=/some/path
</code>```

What am I missing here?

答: Check the domain. You can have multiple cookies with the same name and different domains (e.g. one is set on home.foo.com another on the root .foo.com). Deleting one doesn't delete the other.</p>

ContentLicense: CC BY-SA 2.5

Title: Why can't I delete this cookie?

Body:
From PHP, I'm having trouble getting the browser to delete a cookie. To chase down the problem, I have created a simple test page that just does this:

// Set cookie named MrPants with value foo to expire at end of session
setcookie("MrPants", "foo", 0);

After loading that page, I see the cookie in my Firefox cookies menu. So far, so good.

Then I follow example #2 here to delete a cookie:

// Set that cookie's expires time in the past
setcookie("MrPants", "", time() - 3600);

This has no effect. I have tried specifying the path, too; no change.

In Firebug, I see the following in the response headers:

Set-Cookie ZDEDebuggerPresent=php,phtml,php3; path=/
MrPants=deleted; expires=Tue, 25-Aug-2009 15:27:46 GMT; path=/some/path

What am I missing here?

ContentLicense: CC BY-SA 3.0


问:
How to import csv replace characters and export csv that is saved in blob in powershell
I am very new to powershell. I am trying to replace characters in a csv that is saved in blob storage. Take the file from one folder, do the replace and save in another.

I have 2 sets of code, one for replacing the characters and one for creating blob context. However, I am unsure how to put them together to perform the task. Meaning what do I use instead of 'import-csv' and 'set-content' and how do I tell it to do this for each file in the folder? Any advice would be appreciated.

```<code>$dest = "C:\test\Test - Copy\"

Function RemoveStripScrape ($CsvFileName, $csvLoc)
{
    $CsvFile = $csvLoc + $CsvFileName + ".csv"
    $ExportLoc = $csvLoc + $CsvFileName + ".csv"

    $Csv = Import-Csv $CsvFile

    $regex = '(?<!"),|,(?!")'
    $regex1 = '(?<!\r)\n'

    $Csv | Select-Object * |ConvertTo-Csv -NoTypeInformation | %{$_ -replace $regex,' '} |%{$_ -replace $regex1, ' '} | Set-Content $ExportLoc
    }

$ens = Get-ChildItem $dest -Recurse -include Let*.csv
foreach($e in $ens)
{
    $e.Basename
    RemoveStripScrape -CsvFileName $e.BaseName -csvLoc $dest
}
</code>```

get context:

```<code>$azurepw = ConvertTo-SecureString "xyz" -AsplainText -Force
$cred = New-Object -typename pscredential -argumentlist "xyz@xyz.com",$azurepw
Login-AzureRmAccount -credential $cred | Out-Null

$resourcegroup = "xyz"
$storageaccountname = "xyz"

$storageaccountkey = `
    (Get-AzureRmStorageAccountKey `
    -ResourceGroupName $resourcegroup `
    -Name $storageaccountname).Value[0]

$sourceContext = New-AzureStorageContext $storageaccountname $storageaccountkey
$container = "xyz"

$FileDate = $($(Get-Date).ToString('yyyyMMdd'))
$SourceFileName = "*activity*.csv"
$SinkFileName = "processed_$($FileDate).csv"
$BlobSourceFileNamePath = "Data/Revenue/Archive/CorethreeNew/$($SourceFileName)"
$BlobSinkFileNamePath = "Data/Revenue/Archive/CorethreeNew/Processed/$($SinkFileName)"
#$BlobArchiveSinkFileNamePath = "Data/Revenue/Archive/CorethreeNew/Archive/$($SinkFileName)"
</code>```

答:
solved it this way:
    #Getting files from local directory to perform replace
        $ent = Get-ChildItem -Path $afLocalPath2  -Recurse -include aircoach.csv

```<code>#Importing csv and replacing regex for each file in the local store and saving it in
local Processed folder
foreach($e in $ent)
{
     $FileName = $e.Name
     $CsvFile = "$($afLocalPath2)$($FileName)"
     $Csv = Import-Csv $CsvFile

     $Csv | Select-Object * |ConvertTo-Csv -NoTypeInformation | %{$_ -replace $regex,' '} |%{$_ -replace $regex1, ' '} |%{$_ -replace $regex2, ' '} | %{$_ -replace $regex3, ''}| Set-Content "$($ExportLoc)$($FileName)" -Force

   #Uploading the updated files from local Processed directory to blob
   Set-AzureStorageBlobContent -Context $sourceContext -Container $container -File "$($ExportLoc)$($FileName)" -Blob "$($BlobSinkFileNamePath)$($FileName)" -Force

}
</code>```

Body:
I am very new to powershell. I am trying to replace characters in a csv that is saved in blob storage. Take the file from one folder, do the replace and save in another.

I have 2 sets of code, one for replacing the characters and one for creating blob context. However, I am unsure how to put them together to perform the task. Meaning what do I use instead of 'import-csv' and 'set-content' and how do I tell it to do this for each file in the folder? Any advice would be appreciated.

$dest = "C:\test\Test - Copy\"

Function RemoveStripScrape ($CsvFileName, $csvLoc)
{
    $CsvFile = $csvLoc + $CsvFileName + ".csv"
    $ExportLoc = $csvLoc + $CsvFileName + ".csv"

    $Csv = Import-Csv $CsvFile

    $regex = '(?<!"),|,(?!")'
    $regex1 = '(?<!\r)\n'

    $Csv | Select-Object * |ConvertTo-Csv -NoTypeInformation | %{$_ -replace $regex,' '} |%{$_ -replace $regex1, ' '} | Set-Content $ExportLoc
    }

$ens = Get-ChildItem $dest -Recurse -include Let*.csv
foreach($e in $ens)
{
    $e.Basename
    RemoveStripScrape -CsvFileName $e.BaseName -csvLoc $dest
}

get context:

$azurepw = ConvertTo-SecureString "xyz" -AsplainText -Force
$cred = New-Object -typename pscredential -argumentlist "xyz@xyz.com",$azurepw
Login-AzureRmAccount -credential $cred | Out-Null

$resourcegroup = "xyz"
$storageaccountname = "xyz"

$storageaccountkey = `
    (Get-AzureRmStorageAccountKey `
    -ResourceGroupName $resourcegroup `
    -Name $storageaccountname).Value[0]

$sourceContext = New-AzureStorageContext $storageaccountname $storageaccountkey
$container = "xyz"

$FileDate = $($(Get-Date).ToString('yyyyMMdd'))
$SourceFileName = "*activity*.csv"
$SinkFileName = "processed_$($FileDate).csv"
$BlobSourceFileNamePath = "Data/Revenue/Archive/CorethreeNew/$($SourceFileName)"
$BlobSinkFileNamePath = "Data/Revenue/Archive/CorethreeNew/Processed/$($SinkFileName)"
#$BlobArchiveSinkFileNamePath = "Data/Revenue/Archive/CorethreeNew/Archive/$($SinkFileName)"

Body:
solved it this way:
    #Getting files from local directory to perform replace
        $ent = Get-ChildItem -Path $afLocalPath2  -Recurse -include aircoach.csv

#Importing csv and replacing regex for each file in the local store and saving it in
local Processed folder
foreach($e in $ent)
{
     $FileName = $e.Name
     $CsvFile = "$($afLocalPath2)$($FileName)"
     $Csv = Import-Csv $CsvFile

     $Csv | Select-Object * |ConvertTo-Csv -NoTypeInformation | %{$_ -replace $regex,' '} |%{$_ -replace $regex1, ' '} |%{$_ -replace $regex2, ' '} | %{$_ -replace $regex3, ''}| Set-Content "$($ExportLoc)$($FileName)" -Force

   #Uploading the updated files from local Processed directory to blob
   Set-AzureStorageBlobContent -Context $sourceContext -Container $container -File "$($ExportLoc)$($FileName)" -Blob "$($BlobSinkFileNamePath)$($FileName)" -Force

}


问:
JavaScript Error in Microsoft Edge with Telerik RadDatePicker in ASP.NET UpdatePanel
Telerik RadDatePicker inside ASP.NET UpdatePanel in Microsoft Edge browser throws JavaScript error when doing a post-back.
The error: "Unable to get property 'length' of undefined or null reference".

The RadDatePicker must be inside an UpdatePanel for the error to be thrown, and this ONLY happens in Microsoft Edge browser, all other browsers have no error.

Microsoft Edge version: 44.17763.1.0

Telerik Controls: Telerik.Web.UI, Version=2019.1.409.45

Any ideas how to fix this, or a work-around?

Here is my code:

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="EdgeDatePickerIssue.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Default</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager" runat="server" ScriptMode="Release" />

        <asp:UpdatePanel runat="server" ID="upPanel">
            <ContentTemplate>
                <label>Select Date:</label>
                <telerik:RadDatePicker ID="dpStartDate" runat="server"
                    AutoPostBack="true"
                    OnSelectedDateChanged="dpStartDate_SelectedDateChanged" />

                <telerik:RadButton ID="btnSave" runat="server"
                    Text="Save" OnClick="btnSave_Click" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>
</code>```

Here is a screen-shot of the error:
Screen-shot Error in Edge

答:
The problem is fixed in R2 2019.
Another way to solve it is setting the RadDatePicker's RenderMode property to Lightweight.</p>

Body:
Telerik RadDatePicker inside ASP.NET UpdatePanel in Microsoft Edge browser throws JavaScript error when doing a post-back.
The error: "Unable to get property 'length' of undefined or null reference".

The RadDatePicker must be inside an UpdatePanel for the error to be thrown, and this ONLY happens in Microsoft Edge browser, all other browsers have no error.

Microsoft Edge version: 44.17763.1.0

Telerik Controls: Telerik.Web.UI, Version=2019.1.409.45

Any ideas how to fix this, or a work-around?

Here is my code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="EdgeDatePickerIssue.Default" %>

<!DOCTYPE html>

    <title>Default</title>

    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager" runat="server" ScriptMode="Release" />

        <asp:UpdatePanel runat="server" ID="upPanel">
            <ContentTemplate>
                Select Date:
                <telerik:RadDatePicker ID="dpStartDate" runat="server"
                    AutoPostBack="true"
                    OnSelectedDateChanged="dpStartDate_SelectedDateChanged" />

                <telerik:RadButton ID="btnSave" runat="server"
                    Text="Save" OnClick="btnSave_Click" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>

Here is a screen-shot of the error:
Screen-shot Error in Edge


问:
Insert if not exists, if exists update
I'm getting usersfrom this API.

https://redmine-mock-api.herokuapp.com/api/v1/users

There are 100 in total (100 different ids). I added them to my mongodb database using mongoose but the problem is that it's always adding (i already have 5000 users (50 times repeated 100 users)

I want to add if the id does not exist or update if it exists.

What am I doing wrong? users is the array of users from the API

```<code> db.collection("users").insertMany(users, function (error, response) {
                        if (error) throw error;
                        console.log("Number of users inserted: " + response.insertedCount);
                        db.close();
                    });
</code>```

答:
try following format</p>

```<code>db.collection.update({'_id': Id}, //Find with the unique identifier
                     {//put whatever you want to insert},
                     {upsert: true}
                    )
</code>```

Title: Insert if not exists, if exists update

Body:
I'm getting usersfrom this API.

https://redmine-mock-api.herokuapp.com/api/v1/users

There are 100 in total (100 different ids). I added them to my mongodb database using mongoose but the problem is that it's always adding (i already have 5000 users (50 times repeated 100 users)

I want to add if the id does not exist or update if it exists.

What am I doing wrong? users is the array of users from the API

 db.collection("users").insertMany(users, function (error, response) {
                        if (error) throw error;
                        console.log("Number of users inserted: " + response.insertedCount);
                        db.close();
                    });

Body:
try following format

db.collection.update({'_id': Id}, //Find with the unique identifier
                     {//put whatever you want to insert},
                     {upsert: true}
                    )


问:
How to push app in background and launch from same screen in Appium with selenium
Is there any way to do the following process in android Automation using Appium with android driver?

Press home button from some specific screen.
Put app in background.
Open the app from same screen after some time interval.

Please help if anybody knows.

答:
This will navigate to the Gmail App while executing your Appium script. You Just Change the package name & activity of your app.</p>

```<code>Activity activity = new Activity("com.google.android.gm", "com.google.android.gm.ConversationListActivityGmail");
activity.setStopApp(false);
((AndroidDriver<MobileElement>) driver).startActivity(activity);
</code>```

Body:
This will navigate to the Gmail App while executing your Appium script. You Just Change the package name & activity of your app.

Activity activity = new Activity("com.google.android.gm", "com.google.android.gm.ConversationListActivityGmail");
activity.setStopApp(false);
((AndroidDriver<MobileElement>) driver).startActivity(activity);


问:
Form input realtime feedback
I'm constructing a form with an input field for a username. I want to restrict the username to a pretty small range of characters using regex, changing the color of the text from red to green based on the validity of the input compared to the regex as the user types.

So far it isn't picking up any characters that aren't valid despite positive testing of the regex.

https://regex101.com/r/XPFy6c/1/

```<code>/^[A-Z0-9 -]+$/igm
</code>```

Here's the code, with a JSFiddle here.

const form = document.querySelector('form');
const input = document.querySelector('input');

const check = /^[A-Z0-9 -]+$/ig;

form.addEventListener("input", e => {
    const checkName = check.test(input.value);
    if(!check) {
        input.classList.add('invalid-name');
        input.classList.remove('valid-name');
    } else {
        input.classList.add('valid-name');
        input.classList.remove('invalid-name');
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.invalid-name {
  color: red;
}

.valid-name {
  color: green;
}</code>```

<form id="form">
    <input class="col-12 edit-name-field" id="name" name="edit-name" maxlength="12" autocomplete="off">
</form>```

Update: Although this question is solved, if you try the code you will notice that there remains an issue with the regex alternating true/false. The solution to this problem is here.

答:
I think you need to use the checkName variable</p>

```<code>    const checkName = check.test(input.value);
    if(!checkName)
</code>```

Title: Form input realtime feedback

Body:
I'm constructing a form with an input field for a username. I want to restrict the username to a pretty small range of characters using regex, changing the color of the text from red to green based on the validity of the input compared to the regex as the user types.

So far it isn't picking up any characters that aren't valid despite positive testing of the regex.

https://regex101.com/r/XPFy6c/1/

/^[A-Z0-9 -]+$/igm

Here's the code, with a JSFiddle here.

const form = document.querySelector('form');
const input = document.querySelector('input');

const check = /^[A-Z0-9 -]+$/ig;

form.addEventListener("input", e => {
    const checkName = check.test(input.value);
    if(!check) {
        input.classList.add('invalid-name');
        input.classList.remove('valid-name');
    } else {
        input.classList.add('valid-name');
        input.classList.remove('invalid-name');
    }
})

.invalid-name {
  color: red;
}

.valid-name {
  color: green;
}

<form id="form">
    <input class="col-12 edit-name-field" id="name" name="edit-name" maxlength="12" autocomplete="off">
</form>

Update: Although this question is solved, if you try the code you will notice that there remains an issue with the regex alternating true/false. The solution to this problem is here.

Body:
I think you need to use the checkName variable

    const checkName = check.test(input.value);
    if(!checkName)


问:
[PHP][LARAVEL] "Class 'App\User' not found" but there is clearly 'use App\User;' in the code
I'm using some very simple code in "api.php" in Laravel and this error is driving me nuts.

Code:

```<code><?php

use Illuminate\Http\Request;
use App\User;

// list new user
Route::get('users', function() {
    // If the Content-Type and Accept headers are set to 'application/json',
    // this will return a JSON structure. This will be cleaned up later.
    return User::all();
});

// create new user
Route::post('users/add', function(Request $request) {
    return User::create($request->all);
});
</code>```

Error:

Class 'App\User' not found

How is this even possible?

答: Make sure you run composer update, then composer dumpautoload

Body:
I'm using some very simple code in "api.php" in Laravel and this error is driving me nuts.

Code:

<?php

use Illuminate\Http\Request;
use App\User;

// list new user
Route::get('users', function() {
    // If the Content-Type and Accept headers are set to 'application/json',
    // this will return a JSON structure. This will be cleaned up later.
    return User::all();
});

// create new user
Route::post('users/add', function(Request $request) {
    return User::create($request->all);
});

Error:

Class 'App\User' not found

How is this even possible?


问:
How does impersonation and security permissions in tSQLt tests work?
I have a tSQLt test which I expect to fail but it runs with success. When I run the code outside the procedure, it fails as expected, but when executing the test with Run, no error occurs.

I have read the question tSQLt Testing SQL Server security permissions but the accepted answer does not solve my problem.

My test looks like this:

    CREATE PROCEDURE TestSecurity.[test AFDK_Reader cannot read from AWS schema]
    AS
    BEGIN
        --EXEC tSQLt.ExpectException
        EXECUTE AS USER = 'AFDK_Reader'

        select *
        from sys.user_token

        SELECT * FROM fn_my_permissions('AWS', 'SCHEMA')
        ORDER BY subentity_name, permission_name ;

        SELECT *
        FROM [AWS].[ADRESSEPUNKT_HISTORIK]
        REVERT
    END
```

The role has granted select permissions on the AFDK schema only and that is the only database role membership the SQL user has.

The AFDK_Reader has no permissions to read from the AWS schema.

Can anybody tell me how to get on with my debugging? Thanks in advance.

答:
EXECUTE AS... REVERT commands don't behave in the way you are expecting inside a stored procedure. This is a general feature of stored procedure security in SQL Server; one common use of stored procedures is to abstract permissions. The MS docs page Customizing Permissions with Impersonation in SQL Server says:

SQL Server does not check the permissions of the caller if the stored
  procedure and tables have the same owner.

and that's effectively what's happening here. Even though the EXECUTE AS changes the security context, that security context isn't checked inside the stored procedure.

The docs page also says:

However, ownership chaining doesn't work if objects have different
  owners or in the case of dynamic SQL.

One way to get the behaviour you're expecting would be to run the SELECT statement from inside a dynamic SQL statement, which means that the active security context is tested against the table permissions:

```<code>CREATE PROCEDURE TestSecurity.[test AFDK_Reader cannot read from AWS schema]
AS
BEGIN
    EXEC tSQLt.ExpectException
    EXECUTE AS USER = 'AFDK_Reader'

    EXEC ('SELECT * FROM [AWS].[ADRESSEPUNKT_HISTORIK]')
    REVERT
END
</code>```

A alternative (better?) solution might be to use the built-in permission functions to test permissions settings through metadata. Here's one way, still using EXECUTE AS... REVERT and sys.fn_my_permission:

```<code>CREATE PROCEDURE TestSecurity.[test AFDK_Reader cannot read from AWS schema]
AS
BEGIN
    EXECUTE AS USER = 'AFDK_Reader'
    DECLARE @permissionCount int = (SELECT COUNT(*) FROM sys.fn_my_permissions('[AWS].[ADRESSEPUNKT_HISTORIK]', 'OBJECT') WHERE permission_name = 'SELECT' AND subentity_name = '')
    REVERT
    EXEC tSQLt.AssertEquals 0, @permissionCount
END
</code>```

Body:
I have a tSQLt test which I expect to fail but it runs with success. When I run the code outside the procedure, it fails as expected, but when executing the test with Run, no error occurs.

I have read the question tSQLt Testing SQL Server security permissions but the accepted answer does not solve my problem.

My test looks like this:

    CREATE PROCEDURE TestSecurity.[test AFDK_Reader cannot read from AWS schema]
    AS
    BEGIN
        --EXEC tSQLt.ExpectException
        EXECUTE AS USER = 'AFDK_Reader'

        select *
        from sys.user_token

        SELECT * FROM fn_my_permissions('AWS', 'SCHEMA')
        ORDER BY subentity_name, permission_name ;

        SELECT *
        FROM [AWS].[ADRESSEPUNKT_HISTORIK]
        REVERT
    END

The role has granted select permissions on the AFDK schema only and that is the only database role membership the SQL user has.

The AFDK_Reader has no permissions to read from the AWS schema.

Can anybody tell me how to get on with my debugging? Thanks in advance.

Body:
EXECUTE AS... REVERT commands don't behave in the way you are expecting inside a stored procedure. This is a general feature of stored procedure security in SQL Server; one common use of stored procedures is to abstract permissions. The MS docs page Customizing Permissions with Impersonation in SQL Server says:

SQL Server does not check the permissions of the caller if the stored
  procedure and tables have the same owner.

and that's effectively what's happening here. Even though the EXECUTE AS changes the security context, that security context isn't checked inside the stored procedure.

The docs page also says:

However, ownership chaining doesn't work if objects have different
  owners or in the case of dynamic SQL.

One way to get the behaviour you're expecting would be to run the SELECT statement from inside a dynamic SQL statement, which means that the active security context is tested against the table permissions:

CREATE PROCEDURE TestSecurity.[test AFDK_Reader cannot read from AWS schema]
AS
BEGIN
    EXEC tSQLt.ExpectException
    EXECUTE AS USER = 'AFDK_Reader'

    EXEC ('SELECT * FROM [AWS].[ADRESSEPUNKT_HISTORIK]')
    REVERT
END

A alternative (better?) solution might be to use the built-in permission functions to test permissions settings through metadata. Here's one way, still using EXECUTE AS... REVERT and sys.fn_my_permission:

CREATE PROCEDURE TestSecurity.[test AFDK_Reader cannot read from AWS schema]
AS
BEGIN
    EXECUTE AS USER = 'AFDK_Reader'
    DECLARE @permissionCount int = (SELECT COUNT(*) FROM sys.fn_my_permissions('[AWS].[ADRESSEPUNKT_HISTORIK]', 'OBJECT') WHERE permission_name = 'SELECT' AND subentity_name = '')
    REVERT
    EXEC tSQLt.AssertEquals 0, @permissionCount
END


问:
Issues "getting started" with Blazor
I'm trying to "get started" with Blazorfollowing Microsoft's guidelines,

I've installed the .NET Core 3.0 Preview SDK as indicated,
but then I try to run the command

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview5-19227-01

respectively from terminal and powershell both as admin and not,
getting this error:

Did you mean to run dotnet SDK commands? Please install dotnet SDK from:...

I proceeded anyway installing Visual Studio Preview (with Blazor Extension)

to be able to run the command form the Visual studio terminal,
but I'm simply getting this error:

Command "dotnet" is not valid.

Looks like doesn't recognize the installed SDK (3.0 or previous),

any idea how can I solve the issue? thanks in advance

答:
I imagine if you've got multiple of the same executable in your path then it can't resolve which one you're trying to call.

Try manually using the full path to the .NET Core 3.0 SDK dotnet.exe in a command line e.g.
"C:\Program Files\dotnet\dotnet.exe" new -i Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview5-19227-01 (you can use dotnet --version to find the version of the exe if you're unsure which is which)

Title: Issues "getting started" with Blazor


问:
p5js - Animating lines with 3 different positions
In my project i have 2 lines.
Each line changes position when you click on the screen.
The position of each line always falls randomly in thirds of the screen width.
I accomplished the clicks and the random position in thirds.

Now i would like the lines to animate to the new position on mousePress but i don’t know how to go about it. i’m wondering if a have to rebuild in another way.

can someone guide me? :slight_smile:

https://editor.p5js.org/antoniofrom1984/sketches/8n9le2Wvh

```<code>function setup(){
  createCanvas(windowWidth, windowHeight);
}

function draw(){
  noLoop();
  background(backcolor);
}

function mousePressed(){
  loop();
  var h = height;
  var w = width;
  var thirdsH = [h/3, h/2, h/1.5 ];
  var thirdsV = [w/3, w/2, w/1.5];

  var randomthirdsH = random(thirdsH);
  var randomthirdsV = random(thirdsV);
  strokeWeight(2);
  stroke(linecolor);
  line(0, randomthirdsH, w, randomthirdsH);
  line(randomthirdsV, 0 ,randomthirdsV, h);

  print(randomthirdsH);
}
</code>```

答:
I assume you mean that the splitting of the canvas happens at the point where you click, something like this:

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

var backcolor = "rgb(194, 24, 91)";
var linecolor = "rgb(240, 98, 146)";
var h;
var w;
var thirdsH;
var thirdsV;
var randomthirdsH;
var randomthirdsV;

function setup(){
  createCanvas(windowWidth, windowHeight);
}

function draw(){
  noLoop();
  background(backcolor);
}

function mousePressed(){
  loop();
  var h = height;
  var w = width;
  var thirdsH = [h/3, h/2, h/1.5 ];
  var thirdsV = [w/3, w/2, w/1.5];

  var randomthirdsH = mouseY;
  var randomthirdsV = mouseX;
  strokeWeight(2);
  stroke(linecolor);
  line(0, randomthirdsH, w, randomthirdsH);
  line(randomthirdsV, 0 ,randomthirdsV, h);

  print(randomthirdsH);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script></code>```

The key thing here being:

```<code> var randomthirdsH = mouseY;
 var randomthirdsV = mouseX;
</code>```

In the mousePressed() handler.

Body:
In my project i have 2 lines.
Each line changes position when you click on the screen.
The position of each line always falls randomly in thirds of the screen width.
I accomplished the clicks and the random position in thirds.

Now i would like the lines to animate to the new position on mousePress but i don’t know how to go about it. i’m wondering if a have to rebuild in another way.

can someone guide me? :slight_smile:

https://editor.p5js.org/antoniofrom1984/sketches/8n9le2Wvh

function setup(){
  createCanvas(windowWidth, windowHeight);
}

function draw(){
  noLoop();
  background(backcolor);
}

function mousePressed(){
  loop();
  var h = height;
  var w = width;
  var thirdsH = [h/3, h/2, h/1.5 ];
  var thirdsV = [w/3, w/2, w/1.5];

  var randomthirdsH = random(thirdsH);
  var randomthirdsV = random(thirdsV);
  strokeWeight(2);
  stroke(linecolor);
  line(0, randomthirdsH, w, randomthirdsH);
  line(randomthirdsV, 0 ,randomthirdsV, h);

  print(randomthirdsH);
}

Body:
I assume you mean that the splitting of the canvas happens at the point where you click, something like this:

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

var backcolor = "rgb(194, 24, 91)";
var linecolor = "rgb(240, 98, 146)";
var h;
var w;
var thirdsH;
var thirdsV;
var randomthirdsH;
var randomthirdsV;

function setup(){
  createCanvas(windowWidth, windowHeight);
}

function draw(){
  noLoop();
  background(backcolor);
}

function mousePressed(){
  loop();
  var h = height;
  var w = width;
  var thirdsH = [h/3, h/2, h/1.5 ];
  var thirdsV = [w/3, w/2, w/1.5];

  var randomthirdsH = mouseY;
  var randomthirdsV = mouseX;
  strokeWeight(2);
  stroke(linecolor);
  line(0, randomthirdsH, w, randomthirdsH);
  line(randomthirdsV, 0 ,randomthirdsV, h);

  print(randomthirdsH);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>

The key thing here being:

 var randomthirdsH = mouseY;
 var randomthirdsV = mouseX;

In the mousePressed() handler.


问:
Literal notation for Dictionary in C#?
I currently have a WebSocket between JavaScript and a server programmed in C#. In JavaScript, I can pass data easily using an associative array:

```<code>var data = {'test': 'val',
            'test2': 'val2'};
</code>```

To represent this data object on the server side, I use a Dictionary<string, string>, but this is more 'typing-expensive' than in JavaScript:

```<code>Dictionary<string, string> data = new Dictionary<string,string>();
data.Add("test", "val");
data.Add("test2", "val2");
</code>```

Is there some kind of literal notation for associative arrays / Dictionarys in C#?

答:
Use Dictionary Literals (C#9 proposal) [rejected] or the new syntax (beginning with C#9)

C#9 introduces a simpler syntax to create initialized Dictionary<TKey,TValue> objects without having to specify either the Dictionary type name or the type parameters. The type parameters for the dictionary are inferred using the existing rules used for array type inference.

```<code>// C# 1..8
var x = new Dictionary <string,int> () { { "foo", 4 }, { "bar", 5 }};
// C# 9
var x = ["foo":4, "bar": 5];
</code>```

This synthax makes the work with dictionaries in C# simpler and removing the redundant code.

You can follow the issue on GitHub (and here is the milestone for C#9).

Edit: This proposal is currently rejected:

[...] We think there are a number of interesting use cases around initializing data, particularly for things like immutable dictionaries. We don't find the existing syntax for initializing a dictionary that onerous, nor do we see it as a frequent pattern in code that would benefit much from a language feature. We thing that the general area of initializing data should be looked at again after we do records and withers. [...]

current milestone:

Note that beginning with C# 9.0, constructor invocation expressions are target-typed. That is, if a target type of an expression is known, you can omit a type name, as the following example shows:

```<code>Dictionary<int, List<int>> lookup = new()
{
    [1] = new() {1, 2, 3},
    [2] = new() {5, 8, 3},
    [5] = new() {1, 0, 4}
};
</code>```

As the preceding example shows, you always use parentheses in a target-typed new expression.

If a target type of a new expression is unknown (for example, when you use the var keyword), you must specify a type name.

MSDN

Title: Literal notation for Dictionary in C#?

Body:
I currently have a WebSocket between JavaScript and a server programmed in C#. In JavaScript, I can pass data easily using an associative array:

var data = {'test': 'val',
            'test2': 'val2'};

To represent this data object on the server side, I use a Dictionary<string, string>, but this is more 'typing-expensive' than in JavaScript:

Dictionary<string, string> data = new Dictionary<string,string>();
data.Add("test", "val");
data.Add("test2", "val2");

Is there some kind of literal notation for associative arrays / Dictionarys in C#?

Body:
Use Dictionary Literals (C#9 proposal) [rejected] or the new syntax (beginning with C#9)

C#9 introduces a simpler syntax to create initialized Dictionary<TKey,TValue> objects without having to specify either the Dictionary type name or the type parameters. The type parameters for the dictionary are inferred using the existing rules used for array type inference.

// C# 1..8
var x = new Dictionary <string,int> () { { "foo", 4 }, { "bar", 5 }};
// C# 9
var x = ["foo":4, "bar": 5];

This synthax makes the work with dictionaries in C# simpler and removing the redundant code.

You can follow the issue on GitHub (and here is the milestone for C#9).

Edit: This proposal is currently rejected:

[...] We think there are a number of interesting use cases around initializing data, particularly for things like immutable dictionaries. We don't find the existing syntax for initializing a dictionary that onerous, nor do we see it as a frequent pattern in code that would benefit much from a language feature. We thing that the general area of initializing data should be looked at again after we do records and withers. [...]

current milestone:

Note that beginning with C# 9.0, constructor invocation expressions are target-typed. That is, if a target type of an expression is known, you can omit a type name, as the following example shows:

Dictionary<int, List<int>> lookup = new()
{
    [1] = new() {1, 2, 3},
    [2] = new() {5, 8, 3},
    [5] = new() {1, 0, 4}
};

As the preceding example shows, you always use parentheses in a target-typed new expression.

If a target type of a new expression is unknown (for example, when you use the var keyword), you must specify a type name.

MSDN