问:
Open popup on marker hover
I need to implement a function that can open a popup with some information by hover on a marker placed in the map.
I'm using openlayers 6 I tried to follow the example in the openlayers documentation but it doesn't work.
This is how I create a point:

```<code>var lonLat = ol.proj.fromLonLat([Lon, Lat])
  var layer = new ol.layer.Vector({
    source: new ol.source.Vector({
      features: [
        new ol.Feature({
          geometry: new ol.geom.Point(lonLat)
        })
      ]
    }),
    style: new ol.style.Style({
      image: new ol.style.Icon({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        src: pinPath,
        scale: 1
      })
    })
  });
  layer.set("layerId", "Point");
  if (this.map) {
    this.map.addLayer(layer);
    this.map.getView().animate({ zoom: Zoom, center: lonLat });

  }
</code>```

How can I do?

答:
Do you have any relevant code, how you try to achieve this at the moment?

EDIT:

Here is a working proof of concept (btw. this is how you can turn your layer on and off).

https://jsfiddle.net/ckxmueqb/7/

Complete example code:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <style>
        .map {
            height: 100%;
            width: 100%;
        }
        html, body {height:100%}

    </style>
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/build/ol.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.5.0/css/ol.css">
</head>
<body>
<button onClick=switchLayer();>switch Layer</button>
<div id="map" class="map">
</div>

<div id="popup">
  <span>Hello there</span>
</div>

<script type="text/javascript">

let map;
let vectorSource;
let vectorLayer;

document.addEventListener("DOMContentLoaded", function() {
    drawMap();
});

function drawMap() {

    const container = document.getElementById('popup');
    const popupOverlay = new ol.Overlay({
        element: container,
        autoPan: {
            animation: {
                duration: 250,
            },
        },
    });

    const iconFeature = new ol.Feature({
        geometry: new ol.geom.Point([809549.1064227211, 6908390.40501351]),
    });

    const osm = new ol.layer.Tile({
        source: new ol.source.OSM({}),
    });

    vectorSource = new ol.source.Vector({
        features: [
            iconFeature,
        ],
    });

    vectorLayer = new ol.layer.Vector({
        source: vectorSource,
    });

    map = new ol.Map({
        target: 'map',
        layers: [
            osm,
            vectorLayer,
        ],
        view: new ol.View(),
    });

    map.addOverlay(popupOverlay);

    map.on('pointermove', function(e) {
        const pixel = map.getEventPixel(e.originalEvent);
        const hit = map.hasFeatureAtPixel(pixel);
        if (hit) {
            //How to get all features you hover on.
            //const featureArray = map.getFeaturesAtPixel(pixel);

            popupOverlay.element.hidden = false;
            popupOverlay.setPosition(e.coordinate);
        } else {
            popupOverlay.element.hidden = true;
        }
    });

    map.getView().fit(vectorSource.getExtent(), map.getSize());
}

function switchLayer() {
    vectorLayer.setVisible(!vectorLayer.getVisible());
}

</script>
</body>
</html>
</code>```

Title: Open popup on marker hover

Body:
I need to implement a function that can open a popup with some information by hover on a marker placed in the map.
I'm using openlayers 6 I tried to follow the example in the openlayers documentation but it doesn't work.
This is how I create a point:

var lonLat = ol.proj.fromLonLat([Lon, Lat])
  var layer = new ol.layer.Vector({
    source: new ol.source.Vector({
      features: [
        new ol.Feature({
          geometry: new ol.geom.Point(lonLat)
        })
      ]
    }),
    style: new ol.style.Style({
      image: new ol.style.Icon({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        src: pinPath,
        scale: 1
      })
    })
  });
  layer.set("layerId", "Point");
  if (this.map) {
    this.map.addLayer(layer);
    this.map.getView().animate({ zoom: Zoom, center: lonLat });

  }

How can I do?

Body:
Do you have any relevant code, how you try to achieve this at the moment?

EDIT:

Here is a working proof of concept (btw. this is how you can turn your layer on and off).

https://jsfiddle.net/ckxmueqb/7/

Complete example code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <style>
        .map {
            height: 100%;
            width: 100%;
        }
        html, body {height:100%}

    </style>
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/build/ol.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.5.0/css/ol.css">
</head>
<body>
<button onClick=switchLayer();>switch Layer</button>
<div id="map" class="map">
</div>

<div id="popup">
  <span>Hello there</span>
</div>

<script type="text/javascript">

let map;
let vectorSource;
let vectorLayer;

document.addEventListener("DOMContentLoaded", function() {
    drawMap();
});

function drawMap() {

    const container = document.getElementById('popup');
    const popupOverlay = new ol.Overlay({
        element: container,
        autoPan: {
            animation: {
                duration: 250,
            },
        },
    });

    const iconFeature = new ol.Feature({
        geometry: new ol.geom.Point([809549.1064227211, 6908390.40501351]),
    });

    const osm = new ol.layer.Tile({
        source: new ol.source.OSM({}),
    });

    vectorSource = new ol.source.Vector({
        features: [
            iconFeature,
        ],
    });

    vectorLayer = new ol.layer.Vector({
        source: vectorSource,
    });

    map = new ol.Map({
        target: 'map',
        layers: [
            osm,
            vectorLayer,
        ],
        view: new ol.View(),
    });

    map.addOverlay(popupOverlay);

    map.on('pointermove', function(e) {
        const pixel = map.getEventPixel(e.originalEvent);
        const hit = map.hasFeatureAtPixel(pixel);
        if (hit) {
            //How to get all features you hover on.
            //const featureArray = map.getFeaturesAtPixel(pixel);

            popupOverlay.element.hidden = false;
            popupOverlay.setPosition(e.coordinate);
        } else {
            popupOverlay.element.hidden = true;
        }
    });

    map.getView().fit(vectorSource.getExtent(), map.getSize());
}

function switchLayer() {
    vectorLayer.setVisible(!vectorLayer.getVisible());
}

</script>
</body>
</html>


来源: stackexchange

问:
Adding Segment Analytics to VueJS
I am trying to add Segment-Analytics to a VueJS app but currently, no data is being sent. I think the issue is where I am including Segment's snippet. I have so far pasted into the  tag of public.html, but I have seen other methods. I am trying to figure out the best way to do this.

here are my package.json dependencies including vue-segment-analytics:

```<code> "dependencies": {
    "axios": "^0.19.0",
    "babel-plugin-transform-remove-console": "^6.9.4",
    "bootstrap-vue": "^2.0.0-rc.28",
    "connect-history-api-fallback": "^1.6.0",
    "core-js": "^2.6.5",
    "epic-spinners": "^1.1.0",
    "force-secure-express": "^1.0.1",
    "jquery": "^1.9.1",
    "lodash-for-vue": "^1.0.3",
    "moment-strftime": "^0.5.0",
    "register-service-worker": "^1.6.2",
    "vee-validate": "^2.0.0-rc.27",
    "vue": "^2.6.10",
    "vue-axios": "^2.1.4",
    "vue-router": "^3.0.3",
    "vue-segment-analytics": "^0.3.2",
    "vue-snotify": "^3.2.1",
    "vue-sweet-calendar": "^0.3.1",
    "vuex": "^3.0.1"
</code>```

I have added the Segment code snippet in the  tag in public/index.html.

and in my components, I have, eg:

```<code>mounted() {
    this.getPosts();
    window.analytics.page('Home') // from segment.io docs
  },
</code>```

Segment is telling me that no data is being sent.

答: Here's a medium post I wrote out of frustration on how to setup Vue 3 + Segment + Amplitude

ContentLicense: CC BY-SA 4.0

Title: Adding Segment Analytics to VueJS

Body:
I am trying to add Segment-Analytics to a VueJS app but currently, no data is being sent. I think the issue is where I am including Segment's snippet. I have so far pasted into the  tag of public.html, but I have seen other methods. I am trying to figure out the best way to do this.

here are my package.json dependencies including vue-segment-analytics:

 "dependencies": {
    "axios": "^0.19.0",
    "babel-plugin-transform-remove-console": "^6.9.4",
    "bootstrap-vue": "^2.0.0-rc.28",
    "connect-history-api-fallback": "^1.6.0",
    "core-js": "^2.6.5",
    "epic-spinners": "^1.1.0",
    "force-secure-express": "^1.0.1",
    "jquery": "^1.9.1",
    "lodash-for-vue": "^1.0.3",
    "moment-strftime": "^0.5.0",
    "register-service-worker": "^1.6.2",
    "vee-validate": "^2.0.0-rc.27",
    "vue": "^2.6.10",
    "vue-axios": "^2.1.4",
    "vue-router": "^3.0.3",
    "vue-segment-analytics": "^0.3.2",
    "vue-snotify": "^3.2.1",
    "vue-sweet-calendar": "^0.3.1",
    "vuex": "^3.0.1"

I have added the Segment code snippet in the  tag in public/index.html.

and in my components, I have, eg:

mounted() {
    this.getPosts();
    window.analytics.page('Home') // from segment.io docs
  },

Segment is telling me that no data is being sent.


问:
Cancelling/Exiting Photo Library in Android using react-native-image-crop-picker
In my React Native app, I use the react-native-image-crop-picker package to have access to user's photo library.

It works nicely but if the user has no images in his/her photo library, I want to give the user a way to cancel out or exit it. How do I do that? Currently in Android, I click the element e.g. button or menu item to access user's photo library but then I get stuck there -- see image below:

And if I use gestures to get back to my app, I get the following warning.

Possible Unhandled Promise Rejection

My code is pretty basic at this point. When the user presses a button, I call this function which invokes the image picker:

pickImage() {

```<code>  ImagePicker.openPicker({
     width: 400,
     height: 250,
     cropping: true
  }).then(image => {
     onFilePicked(image);
  });
</code>```

}

Basically, I just need to give the user a way to cancel out of picking an image from the photo gallery. I'd appreciate some pointers on this. Thanks!

答:
The npm package react-native-image-crop-picker is the most used library in react-native to choose Images and videos across the platforms.

It opens a default native Intent from which we can select media files from the gallery, We are not able to customize the view of it as its pure native intent is available into the native device.

And the error message Possible Unhandled Promise Rejection We get is the default error from the library, when the user goes back into our app without selecting a single image or video.

To handle the error message we have to wrap our code inside to try and catch it.

For Ex:

```<code>ImagePicker.openPicker({
     width: 400,
     height: 250,
     cropping: true
  }).then(image => {
     onFilePicked(image);
  }).catch(err => {
     console.log('Error : ', err.message)
  });

// - OR -

try {
    const imagePickerRes = await ImagePicker.openPicker({
        width: 400,
        height: 250,
        cropping: true
    })
    console.log('imagePicker Result : ', imagePickerRes)
} catch (err) {
    console.log('Error : ', err.message)
}
</code>```

Body:
In my React Native app, I use the react-native-image-crop-picker package to have access to user's photo library.

It works nicely but if the user has no images in his/her photo library, I want to give the user a way to cancel out or exit it. How do I do that? Currently in Android, I click the element e.g. button or menu item to access user's photo library but then I get stuck there -- see image below:

And if I use gestures to get back to my app, I get the following warning.

Possible Unhandled Promise Rejection

My code is pretty basic at this point. When the user presses a button, I call this function which invokes the image picker:

pickImage() {

  ImagePicker.openPicker({
     width: 400,
     height: 250,
     cropping: true
  }).then(image => {
     onFilePicked(image);
  });

}

Basically, I just need to give the user a way to cancel out of picking an image from the photo gallery. I'd appreciate some pointers on this. Thanks!

Body:
The npm package react-native-image-crop-picker is the most used library in react-native to choose Images and videos across the platforms.

It opens a default native Intent from which we can select media files from the gallery, We are not able to customize the view of it as its pure native intent is available into the native device.

And the error message Possible Unhandled Promise Rejection We get is the default error from the library, when the user goes back into our app without selecting a single image or video.

To handle the error message we have to wrap our code inside to try and catch it.

For Ex:

ImagePicker.openPicker({
     width: 400,
     height: 250,
     cropping: true
  }).then(image => {
     onFilePicked(image);
  }).catch(err => {
     console.log('Error : ', err.message)
  });

// - OR -

try {
    const imagePickerRes = await ImagePicker.openPicker({
        width: 400,
        height: 250,
        cropping: true
    })
    console.log('imagePicker Result : ', imagePickerRes)
} catch (err) {
    console.log('Error : ', err.message)
}


问:
getting exception: No bean named 'springSecurityFilterChain' is defined
I am learning spring security from reference material. release 3.1.2.RELEASE. As stated in that I have configured security:http tag like this

security-context.xml

```<code><security:http auto-config="true">
        <security:intercept-url pattern="/**" access="ROLE_USER"/>
    </security:http>
</code>```

web.xml

```<code><context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:*-context.xml</param-value>
  </context-param>

  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>security</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>security</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</code>```

security-servlet.xml

```<code><context:component-scan base-package="com.pokuri.security.mvc.controllers"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/page/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</code>```

But I am getting this exception when I start the application. If I remove security configuration my spring web application working fine. I went through the same kind of questions in stackoverflow. But no luck.

答:
For those who learning spring without xml may be this helps.

I faced the same exception when learning the spring without xml.

Found that i have register the spring security filter by extending the class AbstractSecurityWebApplicationInitializer but did not configure the spring security.
To configure the spring security i added below code and it works.

```<code>@Configuration
@EnableWebSecurity
public class SpringSecurityConfigInitializer extends
WebSecurityConfigurerAdapter {

@Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
    UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication().withUser(users.username("test").
password("test123").roles("EMPLOYEE"));
 }

 }
</code>```

Above is just sample for my case but the exception was due to the missing configuration.

ContentLicense: CC BY-SA 3.0

Body:
I am learning spring security from reference material. release 3.1.2.RELEASE. As stated in that I have configured security:http tag like this

security-context.xml

<security:http auto-config="true">
        <security:intercept-url pattern="/**" access="ROLE_USER"/>
    </security:http>

web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:*-context.xml</param-value>
  </context-param>

  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>security</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>security</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

security-servlet.xml

<context:component-scan base-package="com.pokuri.security.mvc.controllers"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/page/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

But I am getting this exception when I start the application. If I remove security configuration my spring web application working fine. I went through the same kind of questions in stackoverflow. But no luck.

Body:
For those who learning spring without xml may be this helps.

I faced the same exception when learning the spring without xml.

Found that i have register the spring security filter by extending the class AbstractSecurityWebApplicationInitializer but did not configure the spring security.
To configure the spring security i added below code and it works.

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigInitializer extends
WebSecurityConfigurerAdapter {

@Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
    UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication().withUser(users.username("test").
password("test123").roles("EMPLOYEE"));
 }

 }

Above is just sample for my case but the exception was due to the missing configuration.


问:
In Core Data, how sort an NSFetchRequest depending on the sum of an attribute of a child entity? (SwiftUI)
I am building an iOS app in SwiftUI for which I have a Core Data model with two entities:

CategoryEntity with attribute: name (String)

ExpenseEntity with attributes: name (String) and amount (Double)

There is a To-many relationship between CategoryEntity and ExpenseEntity (A category can have many expenses).

I’m fetching the categories and showing them in a list together with the sum of the expenses for each category as follows: Link to app screenshot

I would like to add a sort to the fetch request so the categories appear in order depending on the total amount of their expenses. In the example of the previous picture, the order of appearance that I would like to get would be: Tech, Clothes, Food and Transport. I don’t know how to approach this problem. Any suggestions?

In my current implementation of the request, the sorted is done alphabetically:

    // My current implementation for fetching the categories
    func fetchCategories() {
        let request = NSFetchRequest<CategoryEntity>(entityName: "CategoryEntity")

        let sort = NSSortDescriptor(keyPath: \CategoryEntity.name, ascending: true)
        request.sortDescriptors = [sort]

        do {
            fetchedCategories = try manager.context.fetch(request)
        } catch let error {
            print("Error fetching. \(error.localizedDescription)")
        }
    }
```

答:
You don't have to make another FetchRequest, you can just sort in a computed property like this:
(I assume your fetched results come into a var called fetchedCategories.)

```<code>var sortedCategories: [CategoryEntity] {
    return fetchedCategories.sorted(by: { cat1, cat2 in
        cat1.expensesArray.reduce(0, { $0 + $1.amount }) >
        cat2.expensesArray.reduce(0, { $0 + $1.amount })
    })
}
</code>```

So this sorts the fetchedCategories array by a comparing rule, that looks at the sum of all cat1.expenses and compares it with the sum of cat2.expenses. The >says we want the large sums first.

You put the computed var directly in the View where you use it!

And where you used fetchedCategories before in your view (e.g. a ForEach), you now use sortedCategories.

This will update in the same way as the fetched results do.

Body:
You don't have to make another FetchRequest, you can just sort in a computed property like this:
(I assume your fetched results come into a var called fetchedCategories.)

var sortedCategories: [CategoryEntity] {
    return fetchedCategories.sorted(by: { cat1, cat2 in
        cat1.expensesArray.reduce(0, { $0 + $1.amount }) >
        cat2.expensesArray.reduce(0, { $0 + $1.amount })
    })
}

So this sorts the fetchedCategories array by a comparing rule, that looks at the sum of all cat1.expenses and compares it with the sum of cat2.expenses. The >says we want the large sums first.

You put the computed var directly in the View where you use it!

And where you used fetchedCategories before in your view (e.g. a ForEach), you now use sortedCategories.

This will update in the same way as the fetched results do.


问:
Is there a simpler way to get an attribute's frontend value?
I have an array of attribute codes which I need to get the values of:

```<code>$attributes = array(
    'Category'           => 'type',
    'Manufacturer'       => 'brand',
    'Title'              => 'meta_title',
    'Description'        => 'description',
    'Product Link'       => 'url_path',
    'Price'              => 'price',
    'Product-image link' => 'image',
    'SKU'                => 'sku',
    'Stock'              => 'qty',
    'Condition'          => 'condition',
    'Shipping cost'      => 'delivery_cost');
</code>```

After iterating through a product collection I get the frontend values of the attributes like so:

```<code>$attributeId = Mage::getResourceModel('eav/entity_attribute')
    ->getIdByCode('catalog_product', $attribute_code);
$attribute = Mage::getModel('catalog/resource_eav_attribute')
    ->load($attributeId);
$value = $attribute->getFrontend()->getValue($product);
</code>```

Simply using $product->getDate($attribute) won't work with dropdowns and multi-selects, it just returns their id and not their frontend value.

While the code above works, it seems to be a long way around getting the value, but more importantly it runs quite slow. Is there a faster/more sensible way to get the frontend values for product attributes?

Edit

I now have the following (after dealing with special cases like image and qty) which is a bit easier on the eyes and does seem to run quicker (although I don't know why):

```<code>$inputType = $product->getResource()
                     ->getAttribute($attribute_code)
                     ->getFrontend()
                     ->getInputType();

switch ($inputType) {
case 'multiselect':
case 'select':
case 'dropdown':
    $value = $product->getAttributeText($attribute_code);
    if (is_array($value)) {
        $value = implode(', ', $value);
    }
    break;
default:
    $value = $product->getData($attribute_code);
    break;
}

$attributesRow[] = $value;
</code>```

If anyone can improve this (make it simpler/more efficient), please post an answer.

答:
For dropdowns and multiselects and only with products (this isn't a general EAV trick) you can use getAttributeText().

```<code>$value = $product->getAttributeText($attribute_code);
</code>```

Body:
I have an array of attribute codes which I need to get the values of:

$attributes = array(
    'Category'           => 'type',
    'Manufacturer'       => 'brand',
    'Title'              => 'meta_title',
    'Description'        => 'description',
    'Product Link'       => 'url_path',
    'Price'              => 'price',
    'Product-image link' => 'image',
    'SKU'                => 'sku',
    'Stock'              => 'qty',
    'Condition'          => 'condition',
    'Shipping cost'      => 'delivery_cost');

After iterating through a product collection I get the frontend values of the attributes like so:

$attributeId = Mage::getResourceModel('eav/entity_attribute')
    ->getIdByCode('catalog_product', $attribute_code);
$attribute = Mage::getModel('catalog/resource_eav_attribute')
    ->load($attributeId);
$value = $attribute->getFrontend()->getValue($product);

Simply using $product->getDate($attribute) won't work with dropdowns and multi-selects, it just returns their id and not their frontend value.

While the code above works, it seems to be a long way around getting the value, but more importantly it runs quite slow. Is there a faster/more sensible way to get the frontend values for product attributes?

Edit

I now have the following (after dealing with special cases like image and qty) which is a bit easier on the eyes and does seem to run quicker (although I don't know why):

$inputType = $product->getResource()
                     ->getAttribute($attribute_code)
                     ->getFrontend()
                     ->getInputType();

switch ($inputType) {
case 'multiselect':
case 'select':
case 'dropdown':
    $value = $product->getAttributeText($attribute_code);
    if (is_array($value)) {
        $value = implode(', ', $value);
    }
    break;
default:
    $value = $product->getData($attribute_code);
    break;
}

$attributesRow[] = $value;

If anyone can improve this (make it simpler/more efficient), please post an answer.

Body:
For dropdowns and multiselects and only with products (this isn't a general EAV trick) you can use getAttributeText().

$value = $product->getAttributeText($attribute_code);


问:
How to switch elements in data.frame according to size?
I am looking for an R function that allows swapping two elements in a data frame under a certain constraint.

For example:

If I have a dataframe (5rows, 5cols) and I want that all elements in column 2 that are greater than the corresponding elements in column 3 to be swapped. As a result, all the elements of column 2 greater than those of column 3 would move to column 3 and vice-versa.

Your help is much appreciated.

答:
In base R, this may done by changing the order of column index/names  while specifying the row index

```<code>i1 <- with(dat, V1 > V2)
dat[i1, 1:2] <- dat[i1, 2:1]
</code>```

data

```<code>dat <- structure(list(V1 = c(1L, 5L, 1L, 9L, 10L), V2 = c(4L, 2L, 10L,
1L, 8L), V3 = c(7L, 4L, 9L, 5L, 4L), V4 = c(10L, 2L, 3L, 9L,
9L), V5 = c(4L, 5L, 5L, 4L, 2L)), class = "data.frame", row.names = c(NA,
-5L))
</code>```

Body:
In base R, this may done by changing the order of column index/names  while specifying the row index

i1 <- with(dat, V1 > V2)
dat[i1, 1:2] <- dat[i1, 2:1]

data

dat <- structure(list(V1 = c(1L, 5L, 1L, 9L, 10L), V2 = c(4L, 2L, 10L,
1L, 8L), V3 = c(7L, 4L, 9L, 5L, 4L), V4 = c(10L, 2L, 3L, 9L,
9L), V5 = c(4L, 5L, 5L, 4L, 2L)), class = "data.frame", row.names = c(NA,
-5L))


问:
How to in React Component constructor set this state
I still learn much React JavaScript and now I can't understand how to create this initial state.

In the constructor here in the code I want to add to state by running this line:

```<code>    this.state = CsvViewer.parse(props.data);
</code>```

And direct after I want to add more state variables like this:

```<code>    this.state = {
        filters: {},
        sortColumn: null,
        sortDirection: null,
    };
</code>```

The problem now is that state does not contain the first call to CsvViewer. How can I add to state both the call to CsvViewer and the other state variables?

Code:

```<code>    class CsvViewer extends Component {
        static parse(data) {
            const rows = [];
            const columns = [];

            new CSV(data).forEach(array => {
                if (columns.length < 1) {
                    array.forEach((cell, idx) => {
                        columns.push({
                            key: `key-${idx}`,
                            name: cell,
                            resizable: true,
                            sortable: true,
                            filterable: true,
                        });
                    });
                } else {
                    const row = {};
                    array.forEach((cell, idx) => {
                        row[`key-${idx}`] = cell;
                    });
                    rows.push(row);
                }
            });
            return { rows, columns };
        }

        constructor(props) {
            super();
            this.state = CsvViewer.parse(props.data);
            this.state = {
                filters: {},
                sortColumn: null,
                sortDirection: null,
            };
        }

    UNSAFE_componentWillReceiveProps(nextProps) {
        // TODO
        this.setState(CsvViewer.parse(nextProps.data));
    }

    handleGridSort = (sortColumn, sortDirection) => {
        // this.setState({ sortColumn, sortDirection });
    };

    render() {
        const { rows, columns } = this.state;
        const { height } = this.props;
        return (
            <ReactDataGrid
                enableCellAutoFocus={false}
                columns={columns}
                rowsCount={rows ? rows.length: 0}
                rowGetter={i => rows[i]}
                minHeight={height || 650}
                onGridSort={this.handleGridSort}
            />
        );
    }
}

export default CsvViewer;
</code>```

答:
There's a few options for adding properties to an object. Here's the one i would usually do, using spread syntax. It will create a shallow copy of the object returned by parse, and add in the extra properties you define:

```<code>this.state = {
  ...CsvViewer.parse(props.data),
  filters: {},
  sortColumn: null,
  sortDirection: null,
}
</code>```

Object.assign can be used to do something similar:

```<code>this.state = Object.assign({}, CsvViewer.parse(props.data), {
  filters: {},
  sortColumn: null,
  sortDirection: null,
});
</code>```

Or you could just add the individual properties one at a time:

```<code>this.state = CsvViewer.parse(props.data);
this.state.filters = {};
this.state.sortColumn = null;
this.state.sortDirection = null;
</code>```

Body:
I still learn much React JavaScript and now I can't understand how to create this initial state.

In the constructor here in the code I want to add to state by running this line:

    this.state = CsvViewer.parse(props.data);

And direct after I want to add more state variables like this:

    this.state = {
        filters: {},
        sortColumn: null,
        sortDirection: null,
    };

The problem now is that state does not contain the first call to CsvViewer. How can I add to state both the call to CsvViewer and the other state variables?

Code:

    class CsvViewer extends Component {
        static parse(data) {
            const rows = [];
            const columns = [];

            new CSV(data).forEach(array => {
                if (columns.length < 1) {
                    array.forEach((cell, idx) => {
                        columns.push({
                            key: `key-${idx}`,
                            name: cell,
                            resizable: true,
                            sortable: true,
                            filterable: true,
                        });
                    });
                } else {
                    const row = {};
                    array.forEach((cell, idx) => {
                        row[`key-${idx}`] = cell;
                    });
                    rows.push(row);
                }
            });
            return { rows, columns };
        }

        constructor(props) {
            super();
            this.state = CsvViewer.parse(props.data);
            this.state = {
                filters: {},
                sortColumn: null,
                sortDirection: null,
            };
        }

    UNSAFE_componentWillReceiveProps(nextProps) {
        // TODO
        this.setState(CsvViewer.parse(nextProps.data));
    }

    handleGridSort = (sortColumn, sortDirection) => {
        // this.setState({ sortColumn, sortDirection });
    };

    render() {
        const { rows, columns } = this.state;
        const { height } = this.props;
        return (
            <ReactDataGrid
                enableCellAutoFocus={false}
                columns={columns}
                rowsCount={rows ? rows.length: 0}
                rowGetter={i => rows[i]}
                minHeight={height || 650}
                onGridSort={this.handleGridSort}
            />
        );
    }
}

export default CsvViewer;

Body:
There's a few options for adding properties to an object. Here's the one i would usually do, using spread syntax. It will create a shallow copy of the object returned by parse, and add in the extra properties you define:

this.state = {
  ...CsvViewer.parse(props.data),
  filters: {},
  sortColumn: null,
  sortDirection: null,
}

Object.assign can be used to do something similar:

this.state = Object.assign({}, CsvViewer.parse(props.data), {
  filters: {},
  sortColumn: null,
  sortDirection: null,
});

Or you could just add the individual properties one at a time:

this.state = CsvViewer.parse(props.data);
this.state.filters = {};
this.state.sortColumn = null;
this.state.sortDirection = null;


问:
Efficiently store an N-dimensional array of mostly zeros in Matlab
I implemented a finite differences algorithm to solve a PDE.

The grid is a structured 2D domain of size [Nx, Nz], solved Nt times.

I pre-allocate the object containing all solutions:

```<code>sol = zeros(Nx, Nz, Nt, 'single') ;
</code>```

This becomes very easily too large and I get a 'out of memory' error.
Unfortunately sparse doesn't work for N-dimensional arrays.

For the sake of the question it's not important to know the values, it goes without saying that the RAM usage grows exponentially with decreasing the grid spacing and increasing the simulation time.

I am aware that I do not need to store each time instant for the purpose of the advancement of the solution. It would be sufficient to just store the previous two time steps. However, for post-processing reasons I need to access the solution at all time-steps (or at least at a submultiple of the total number).It might help to specify that, even after the solution, the grid remains predominantly populated by zeros.

Am I fighting a lost battle or is there a more efficient way to proceed (other type of objects, vectorization...)?

Thank you.

答: You can create a a cell array of sparse matrices to store the results. However computations can be performed on full matrices if working with a full matrix is faster than sparse matrix and convert the full matrix to sparse matrix and place it in the cell.</p>

Body:
I implemented a finite differences algorithm to solve a PDE.

The grid is a structured 2D domain of size [Nx, Nz], solved Nt times.

I pre-allocate the object containing all solutions:

sol = zeros(Nx, Nz, Nt, 'single') ;

This becomes very easily too large and I get a 'out of memory' error.
Unfortunately sparse doesn't work for N-dimensional arrays.

For the sake of the question it's not important to know the values, it goes without saying that the RAM usage grows exponentially with decreasing the grid spacing and increasing the simulation time.

I am aware that I do not need to store each time instant for the purpose of the advancement of the solution. It would be sufficient to just store the previous two time steps. However, for post-processing reasons I need to access the solution at all time-steps (or at least at a submultiple of the total number).It might help to specify that, even after the solution, the grid remains predominantly populated by zeros.

Am I fighting a lost battle or is there a more efficient way to proceed (other type of objects, vectorization...)?

Thank you.


问:
Adding extra information in sales_flat_quote and sales_flat_order_item tables
I am just getting to grips with magento and i am trying to work out how to do the following.

This is what i have currently

When a customer loads the onepage.phtml file an include is made to a script that checks the items in the basket and calls an api which generates a unique order url for the customer.

This is what i need to do

I then need to store this unique order url in the database sales_flat_order table. The reason i need to do this is i have an observer i have created which once the order is paid . A second api call is made which passes this unique_order_url back to finalise the order and complete payment.

So to summarise i need to pass this unique_order_url that is generated as part of onepage.phtml so that it is included in the database once an order is placed.

I have created the coloumn in sales_flat_order as a varchar but i am struggling on where to go from here

Any help / advice would be much appreciated

答:
If I were you, I would NOT change the default magento schema! What happens when you have to update your magento install? Trouble! Instead I would add 1:1 related tables for magento tables where you want to store additional information.

Furthermore I would NOT change the original code either. Same reason. Instead I would extend the respective class and add the additional functionality there!

Your main question: Override the method that stores the order and add a query that saves the url to your extended table.


问:
What languages are supported for nltk.word_tokenize and nltk.pos_tag
I need to conduct name entity extraction for text in multiple languages: spanish, portuguese, greek, czech, chinese.

Is there somewhere a list of all supported languages for these two functions? And is there a method to use other corpora so that these languages can be included?

答:
The list of the languages supported by the NLTK tokenizer is as follows:

'czech'

'danish'

'dutch'

'english'

'estonian'

'finnish'

'french'

'german'

'greek'

'italian'

'norwegian'

'polish'

'portuguese'

'russian'

'slovene',

'spanish'

'swedish'

'turkish'

It corresponds to the pickles stored in C:\Users\XXX\AppData\Roaming\nltk_data\tokenizers\punkt (in Windows). This is what you enter with the key 'language' when tokenizing, e.g.

```<code>nltk.word_tokenize(text, language='italian')
</code>```

Body:
The list of the languages supported by the NLTK tokenizer is as follows:

'czech'

'danish'

'dutch'

'english'

'estonian'

'finnish'

'french'

'german'

'greek'

'italian'

'norwegian'

'polish'

'portuguese'

'russian'

'slovene',

'spanish'

'swedish'

'turkish'

It corresponds to the pickles stored in C:\Users\XXX\AppData\Roaming\nltk_data\tokenizers\punkt (in Windows). This is what you enter with the key 'language' when tokenizing, e.g.

nltk.word_tokenize(text, language='italian')


问:
SQL Script for Employee/manager Mismatch
We have a Employee table, and I read the contents of it to build a treeview control for employee hierarchy.
The table structure is
1.FirstName
2.lastName
3.EmpNumber
4.Begindate
5.LastDateOfEmployement
6.ManagerId

Each employee reports to a managerId. When an Employee leaves the org the "lastdateofEmployement" is updated.
We have a script to populate the treeview control of all employees , who has LastDateOfemployement as NUll. That works fine.
However HR sometimes forgets to update the ManagerId of an employee, whose manager leaves the organization.
So when our script runs, the treeview fails to populate.

Can someone PLEASE help me write a script where , if an employee A leaves an organization, anyone reporting to him/her, should have their managerID updated to A's Managerid.

Emp A
Emp B
Emp C

C Reports to B , and B reports to A.
If B leaves the org (LastDateofEmployement is Not Null), the manager ID of C should be updated to A's Empnumber.

Please help!

答:
I'm assuming that managerID is the EmpNumber.

If this is the case you can try to join the table with itself for the update:

```<code>UPDATE lostEmployee
SET ManagerId = goneManager.ManagerId
FROM Employees lostEmployee
INNER JOIN Employees goneManager ON lostEmployee.ManagerId = goneManager.EmpNumber
WHERE goneManager.LastDateOfEmployement IS NOT NULL
</code>```

Check this for a running example: DB Fiddle

Body:
I'm assuming that managerID is the EmpNumber.

If this is the case you can try to join the table with itself for the update:

UPDATE lostEmployee
SET ManagerId = goneManager.ManagerId
FROM Employees lostEmployee
INNER JOIN Employees goneManager ON lostEmployee.ManagerId = goneManager.EmpNumber
WHERE goneManager.LastDateOfEmployement IS NOT NULL

Check this for a running example: DB Fiddle


问:
Add background image in SVG
I need to add background image in svg. But I'm getting only black rectangle box, the image is not displaying. How to add the background image?

This is my code:

```<code><style>
    path {
        fill: none;
        stroke: #000;
        stroke-width: 3px;
        stroke-linejoin: round;
        stroke-linecap: round;
    }
</style>

<svg width="1000" height="700">
    <!-- <rect fill="#fff" width="100%" height="100%"></rect> -->

    <defs>
        <pattern id="img1" patternUnits="userSpaceOnUse" x="0" y="0" width="1000" height="700">
            <image xlink:href="home/nayana/Documents/Text Editor Files/abstract-hd.jpg" width="600" height="450" />
        </pattern>
    </defs>
    <path d="M5,5 l0,680 l980,0 l0,-680 l-980,0 fill="url(#img1)" />
</svg>
</code>```

Thanks in advance

答: Simplest use nowadays is plain <image href="bgnd.png"/>. This also can take x, y, width, height. https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image

Title: Add background image in SVG

Body:
I need to add background image in svg. But I'm getting only black rectangle box, the image is not displaying. How to add the background image?

This is my code:

<svg width="1000" height="700">

    <defs>
        <pattern id="img1" patternUnits="userSpaceOnUse" x="0" y="0" width="1000" height="700">
            <image xlink:href="home/nayana/Documents/Text Editor Files/abstract-hd.jpg" width="600" height="450" />
        </pattern>
    </defs>
    <path d="M5,5 l0,680 l980,0 l0,-680 l-980,0 fill="url(#img1)" />
</svg>

Thanks in advance


问:
How to find current_streaks in BQ SQL
Looking for the best way to find all current streaks of today in BigQuery ( so essentially the answer must be row_number() based but otherwise any flavor SQL should do..).

```<code> created_at  | user_id
-------------+---------
  2022-02-10 | 1
  2022-02-09 | 1
  2022-02-08 | 1
  2022-02-10 | 2
  2022-01-20 | 3
</code>```

Desired result only showing User_ID of the Streaker and their # of days Streaked

```<code> user_id  | streak
----------+---------
     1    |    3
     2    |    1
</code>```

UserID: 2 is ignored because it's streak did not make it to today

答:
You can add a condition outside the streak-identification code, which validates the existence of current_date() in the streak set and only display the valid streaks (i.e. ones which connect to today's date):

```<code>select user_id, array_length(array_agg(distinct created_at)) as streak from (
   select
      user_id,
      created_at,
      date_sub(created_at, interval rnk day) as grp from (
         select
            user_id,
            date(created_at) as created_at,
            dense_rank() over (partition by user_id order by created_at) as rnk
         from table
      )
   )
group by user_id, grp
having current_date() in unnest( array_agg(distinct created_at))
</code>```

Title: How to find current_streaks in BQ SQL

Body:
Looking for the best way to find all current streaks of today in BigQuery ( so essentially the answer must be row_number() based but otherwise any flavor SQL should do..).

 created_at  | user_id
-------------+---------
  2022-02-10 | 1
  2022-02-09 | 1
  2022-02-08 | 1
  2022-02-10 | 2
  2022-01-20 | 3

Desired result only showing User_ID of the Streaker and their # of days Streaked

 user_id  | streak
----------+---------
     1    |    3
     2    |    1

UserID: 2 is ignored because it's streak did not make it to today

Body:
You can add a condition outside the streak-identification code, which validates the existence of current_date() in the streak set and only display the valid streaks (i.e. ones which connect to today's date):

select user_id, array_length(array_agg(distinct created_at)) as streak from (
   select
      user_id,
      created_at,
      date_sub(created_at, interval rnk day) as grp from (
         select
            user_id,
            date(created_at) as created_at,
            dense_rank() over (partition by user_id order by created_at) as rnk
         from table
      )
   )
group by user_id, grp
having current_date() in unnest( array_agg(distinct created_at))


问:
Keep selected column as DataFrame instead of Series
When selecting a single column from a pandas DataFrame(say df.iloc[:, 0], df['A'], or df.A, etc), the resulting vector is automatically converted to a Series instead of a single-column DataFrame. However, I am writing some functions that takes a DataFrame as an input argument. Therefore, I prefer to deal with single-column DataFrame instead of Series so that the function can assume say df.columns is accessible. Right now I have to explicitly convert the Series into a DataFrame by using something like pd.DataFrame(df.iloc[:, 0]). This doesn't seem like the most clean method. Is there a more elegant way to index from a DataFrame directly so that the result is a single-column DataFrame instead of Series?

答:
(Talking about pandas 1.3.4)

I'd like to add a little more context to the answers involving .to_frame(). If you select a single row of a data frame and execute .to_frame() on that, then the index will be made up of the original column names and you'll get numeric column names. You can just tack on a .T to the end to transpose that back into the original data frame's format (see below).

import pandas as pd
print(pd.__version__)  #1.3.4

df = pd.DataFrame({
    "col1": ["a", "b", "c"],
    "col2": [1, 2, 3]
})

# series
df.loc[0, ["col1", "col2"]]

# dataframe (column names are along the index; not what I wanted)
df.loc[0, ["col1", "col2"]].to_frame()
    #       0
    # col1  a
    # col2  1

# looks like an actual single-row dataframe.
# To me, this is the true answer to the question
# because the output matches the format of the
# original dataframe.
df.loc[0, ["col1", "col2"]].to_frame().T
    #   col1 col2
    # 0    a    1

# this works really well with .to_dict(orient="records") which is
# what I'm ultimately after by selecting a single row
df.loc[0, ["col1", "col2"]].to_frame().T.to_dict(orient="records")
    # [{'col1': 'a', 'col2': 1}]

```


问:
how to turn off Cyclomatic complexity for where is too high
I have a where method in model that's throwing lint error. The whole code in model is just a test code at this moment and will be refactored later on. So i want to turn off this lint error for now.

UPDATE:
Here's the method i am getting lint error at

```<code>def self.where(start_date, end_date, customer_id, type, location, is_registered)
  filtered_data = if start_date && end_date
                     customers.select do |e|
                       e[:startDateTime].to_datetime >= start_date.to_datetime &&
                         e[:endDateTime].to_datetime <= end_date.to_datetime
                     end
                   elsif start_date
                     customers.select {|e| e[:startDateTime].to_datetime >= start_date.to_datetime }
                   elsif end_date
                     customers.select {|e| e[:endDateTime].to_datetime <= end_date.to_datetime }
                   else
                     customers
                   end

  if !is_registered.nil? # is_registered is true or false
    filtered_data = customers.select { |e| e[:isRegistered].to_s == is_registered }
  end
  # Check if hash presents and check if the keys have valid values.
  if customer_id || type || location
    hash = { customerId: customer_id.to_i, type: type, location: location }
    # delete if type, location or customer_id is nil.
    hash = hash.delete_if { |_k, v| v.nil? || v == 0 }
    keys = hash.keys
    filtered_data = filtered_data.select { |h| h.select { |k| keys.include?(k) } == hash }
  else
    filtered_data
  end

  filtered_data.map do |slot|
    mock_customer(slot[:id], slot[:customerId], slot[:name], slot[:startDateTime],
               slot[:endDateTime], slot[:location], slot[:status])
  end
end
</code>```

I tried adding # rubocop:disable Metrics/AbcSize in model but didnt help.

答:
This works for me</p>
```<code># rubocop:disable Style/CyclomaticComplexity
yor code
# rubocop:enable Style/CyclomaticComplexity
</code>```

Body:
I have a where method in model that's throwing lint error. The whole code in model is just a test code at this moment and will be refactored later on. So i want to turn off this lint error for now.

UPDATE:
Here's the method i am getting lint error at

def self.where(start_date, end_date, customer_id, type, location, is_registered)
  filtered_data = if start_date && end_date
                     customers.select do |e|
                       e[:startDateTime].to_datetime >= start_date.to_datetime &&
                         e[:endDateTime].to_datetime <= end_date.to_datetime
                     end
                   elsif start_date
                     customers.select {|e| e[:startDateTime].to_datetime >= start_date.to_datetime }
                   elsif end_date
                     customers.select {|e| e[:endDateTime].to_datetime <= end_date.to_datetime }
                   else
                     customers
                   end

  if !is_registered.nil? # is_registered is true or false
    filtered_data = customers.select { |e| e[:isRegistered].to_s == is_registered }
  end
  # Check if hash presents and check if the keys have valid values.
  if customer_id || type || location
    hash = { customerId: customer_id.to_i, type: type, location: location }
    # delete if type, location or customer_id is nil.
    hash = hash.delete_if { |_k, v| v.nil? || v == 0 }
    keys = hash.keys
    filtered_data = filtered_data.select { |h| h.select { |k| keys.include?(k) } == hash }
  else
    filtered_data
  end

  filtered_data.map do |slot|
    mock_customer(slot[:id], slot[:customerId], slot[:name], slot[:startDateTime],
               slot[:endDateTime], slot[:location], slot[:status])
  end
end

I tried adding # rubocop:disable Metrics/AbcSize in model but didnt help.

Body:
This works for me

# rubocop:disable Style/CyclomaticComplexity
yor code
# rubocop:enable Style/CyclomaticComplexity


答:
One approach would be to include a derived attribute in your CategoryEntity model description which keeps the totals for you. For example, to sum the relevant values from the amount column within an expenses relation:

That attribute should be updated whenever you save your managed object context. You'll then be able to sort it just as you would any other attribute, without the performance cost of calculating the expense sum for each category whenever you sort.

Note that this option only really works if you don't have to do any filtering on expenses; for example, if you're looking at sorting based on expenses just in 2022, but your core data store also has seconds in 2021, the derived attribute might not give you the sort order you want.

Title: In Core Data, how sort an NSFetchRequest depending on the sum of an attribute of a child entity? (SwiftUI)

Body:
I am building an iOS app in SwiftUI for which I have a Core Data model with two entities:

CategoryEntity with attribute: name (String)

ExpenseEntity with attributes: name (String) and amount (Double)

There is a To-many relationship between CategoryEntity and ExpenseEntity (A category can have many expenses).

I’m fetching the categories and showing them in a list together with the sum of the expenses for each category as follows: Link to app screenshot

I would like to add a sort to the fetch request so the categories appear in order depending on the total amount of their expenses. In the example of the previous picture, the order of appearance that I would like to get would be: Tech, Clothes, Food and Transport. I don’t know how to approach this problem. Any suggestions?

In my current implementation of the request, the sorted is done alphabetically:

    // My current implementation for fetching the categories
    func fetchCategories() {
        let request = NSFetchRequest<CategoryEntity>(entityName: "CategoryEntity")

        let sort = NSSortDescriptor(keyPath: \CategoryEntity.name, ascending: true)
        request.sortDescriptors = [sort]

        do {
            fetchedCategories = try manager.context.fetch(request)
        } catch let error {
            print("Error fetching. \(error.localizedDescription)")
        }
    }


问:
C# Cosmos DB ReadItemAsync Partition Key multiple values
I have a container that has a partition key made up of two fields. Neither of them is 'id'. In this example it is FormId and Version.

I am calling a function that uses ReadItemAsync to return a single document from the container. I'd like to include the Partition Key parameter as the data in the container is set to get very large and I'd rather not have the query run cross partition based solely on the id value. However, when I make the call I can't figure out how to structure the Partition Key value.

```<code>
    public async Task<dynamic> GetItemAsync(string id, string? partitionId, string containerName)
    {
        try
        {
            Container container = _client.GetContainer(_databaseName, containerName);
            ItemResponse<dynamic> response;

            if (partitionId == null)
                response = await container.ReadItemAsync<dynamic>(id, PartitionKey.None);
            else
                response = await container.ReadItemAsync<dynamic>(id, new PartitionKey(partitionId));

            return response.Resource;
        }
        catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
        {
            return null;
        }
    }

</code>```

When I call with the function with the id Guid and null as the partition key, the function works fine. When I pass in a string representing the Partition Key in any of the following ways I get no data found:

```<code>    formId + "." + version
    formId + "/" + version
    formId + "\\" + version
</code>```

How should the partition key parameter be structured when it is made up of more than one field?

Edit 1: Example of the document instance:

```<code>
    {
        "formID": "e8493c8b-6736-4360-b781-5d94e93fe545",
        "version": "1",
        "id": "71d7458d-b71c-467e-b5b9-2b646dbd5435",
        "_rid": "QMgvAKsrCcABAAAAAAAAAA==",
        "_self": "dbs/QMgvAA==/colls/QMgvAKsrCcA=/docs/QMgvAKsrCcABAAAAAAAAAA==/",
        "_etag": "\"5f019a17-0000-1100-0000-6205202f0000\"",
        "_attachments": "attachments/",
        "_ts": 1644503087
    }

</code>```

The Partition Key is set as \formId.version.

答:
Based on the comments and the new information, the problem is casing on the attribute name.

/formId.version as Partition key definition means your documents should have this format:

```<code>{
    "formId": {
        "version": "some value"
    },
    "id": "the id"
}
</code>```

The "dot" is saying that formId is actually an object and inside there should be a version property.

To read such a document, you would do:

container.ReadItem<dynamic>("the id", new PartitionKey("some value"))

The document example you provide has formID which means it really has no Partition Key value. Furthermore, the other problem is, even if the casing matched, you are using a string value, not a nested JSON object with a version property.

It seems that you would need to have /formID as the Partition Key Definition to fit the code and document you are sharing.

Body:
I have a container that has a partition key made up of two fields. Neither of them is 'id'. In this example it is FormId and Version.

I am calling a function that uses ReadItemAsync to return a single document from the container. I'd like to include the Partition Key parameter as the data in the container is set to get very large and I'd rather not have the query run cross partition based solely on the id value. However, when I make the call I can't figure out how to structure the Partition Key value.

    public async Task<dynamic> GetItemAsync(string id, string? partitionId, string containerName)
    {
        try
        {
            Container container = _client.GetContainer(_databaseName, containerName);
            ItemResponse<dynamic> response;

            if (partitionId == null)
                response = await container.ReadItemAsync<dynamic>(id, PartitionKey.None);
            else
                response = await container.ReadItemAsync<dynamic>(id, new PartitionKey(partitionId));

            return response.Resource;
        }
        catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
        {
            return null;
        }
    }

When I call with the function with the id Guid and null as the partition key, the function works fine. When I pass in a string representing the Partition Key in any of the following ways I get no data found:

    formId + "." + version
    formId + "/" + version
    formId + "\\" + version

How should the partition key parameter be structured when it is made up of more than one field?

Edit 1: Example of the document instance:

    {
        "formID": "e8493c8b-6736-4360-b781-5d94e93fe545",
        "version": "1",
        "id": "71d7458d-b71c-467e-b5b9-2b646dbd5435",
        "_rid": "QMgvAKsrCcABAAAAAAAAAA==",
        "_self": "dbs/QMgvAA==/colls/QMgvAKsrCcA=/docs/QMgvAKsrCcABAAAAAAAAAA==/",
        "_etag": "\"5f019a17-0000-1100-0000-6205202f0000\"",
        "_attachments": "attachments/",
        "_ts": 1644503087
    }

The Partition Key is set as \formId.version.

Body:
Based on the comments and the new information, the problem is casing on the attribute name.

/formId.version as Partition key definition means your documents should have this format:

{
    "formId": {
        "version": "some value"
    },
    "id": "the id"
}

The "dot" is saying that formId is actually an object and inside there should be a version property.

To read such a document, you would do:

container.ReadItem<dynamic>("the id", new PartitionKey("some value"))

The document example you provide has formID which means it really has no Partition Key value. Furthermore, the other problem is, even if the casing matched, you are using a string value, not a nested JSON object with a version property.

It seems that you would need to have /formID as the Partition Key Definition to fit the code and document you are sharing.


问:
Trying to generate a word document in a .NET Windows Service
In a Windows Service I'm trying to convert a document from word to pdf.

The code used is pretty simple:

```<code>/// <summary>
/// Generate a PDF document from a Word document.
/// </summary>
/// <param name="inputFile">Path to the input Word document</param>
/// <param name="outputFile">Path to the output PDF document</param>
/// <returns>Exception string in case of error. Empty string if ok.</returns>
private string DocToPDF(string inputFile, string outputFile)
{
    try
    {
        object inputfileName = inputFile;
        object outputfileName = outputFile;
        object fileFormat = WdSaveFormat.wdFormatDocument;
        object lockComments = false;
        object passWord = Missing.Value;
        object addToRecentFiles = false;
        object writePassword = Missing.Value;
        object readOnlyRecommended = false;
        object embedTruetypeFonts = false;
        object saveNativePictureFormat = true;
        object saveFormsData = false;
        object saveAsAOCELetter = false;
        object newTemplate = false;
        object docType = WdNewDocumentType.wdNewBlankDocument; //Missing.Value;
        object beVisisble = true;

        MWordApp.Visible = MWordVisible;
        Document wordDoc = MWordApp.Documents.Add(ref inputfileName, ref newTemplate, ref
                                                  docType, ref beVisisble);
        wordDoc.SaveAs(ref outputfileName, ref fileFormat, ref lockComments, ref passWord, ref
                       addToRecentFiles,
                       ref writePassword, ref readOnlyRecommended, ref embedTruetypeFonts, ref
                       saveNativePictureFormat,
                       ref saveFormsData, ref saveAsAOCELetter);
        return "";
    }
    catch (Exception ex)
    {
        return ex.ToString();
    }
}
</code>```

When the code is triggered I get the following error:

System.Runtime.InteropServices.COMException (0x800A13E9): Word has encountered a problem.
at Microsoft.Office.Interop.Word.Documents.Add(Object& Template, Object& NewTemplate, Object& DocumentType, Object& Visible)
at DocService.Listener.DocToPDF(String inputFile, String outputFile) in E:\Projects\DocService\DocService\DocService.cs:line 77

I looked up the error and found a couple of work arounds (like placing a folder "Desktop" in "C:\Windows\SysWOW64\config\systemprofile") but nothing worked.

Now, the service itself is pretty ancient. The service was originally written to run on 32-bit Windows with Office 2010 32 bit.

I'm currently trying to run it on 64-bit Windows Server 2016 with Office 365 64-bit

I'll be trying to rebuild the entire application in 64 bit, to see if that makes a difference. (just realized the problem might be simply the office version being in 64 bit rather than 32 bit)

Does anybody here have any idea what else it might be?

答: The problem turned out to be caused by the user the service was running on. Needed to use an interactive user, and I got past the error.</p>

Body:
In a Windows Service I'm trying to convert a document from word to pdf.

The code used is pretty simple:

///
/// Generate a PDF document from a Word document.
///
/// <param name="inputFile">Path to the input Word document</param>
/// <param name="outputFile">Path to the output PDF document</param>
/// <returns>Exception string in case of error. Empty string if ok.</returns>
private string DocToPDF(string inputFile, string outputFile)
{
    try
    {
        object inputfileName = inputFile;
        object outputfileName = outputFile;
        object fileFormat = WdSaveFormat.wdFormatDocument;
        object lockComments = false;
        object passWord = Missing.Value;
        object addToRecentFiles = false;
        object writePassword = Missing.Value;
        object readOnlyRecommended = false;
        object embedTruetypeFonts = false;
        object saveNativePictureFormat = true;
        object saveFormsData = false;
        object saveAsAOCELetter = false;
        object newTemplate = false;
        object docType = WdNewDocumentType.wdNewBlankDocument; //Missing.Value;
        object beVisisble = true;

        MWordApp.Visible = MWordVisible;
        Document wordDoc = MWordApp.Documents.Add(ref inputfileName, ref newTemplate, ref
                                                  docType, ref beVisisble);
        wordDoc.SaveAs(ref outputfileName, ref fileFormat, ref lockComments, ref passWord, ref
                       addToRecentFiles,
                       ref writePassword, ref readOnlyRecommended, ref embedTruetypeFonts, ref
                       saveNativePictureFormat,
                       ref saveFormsData, ref saveAsAOCELetter);
        return "";
    }
    catch (Exception ex)
    {
        return ex.ToString();
    }
}

When the code is triggered I get the following error:

System.Runtime.InteropServices.COMException (0x800A13E9): Word has encountered a problem.
at Microsoft.Office.Interop.Word.Documents.Add(Object& Template, Object& NewTemplate, Object& DocumentType, Object& Visible)
at DocService.Listener.DocToPDF(String inputFile, String outputFile) in E:\Projects\DocService\DocService\DocService.cs:line 77

I looked up the error and found a couple of work arounds (like placing a folder "Desktop" in "C:\Windows\SysWOW64\config\systemprofile") but nothing worked.

Now, the service itself is pretty ancient. The service was originally written to run on 32-bit Windows with Office 2010 32 bit.

I'm currently trying to run it on 64-bit Windows Server 2016 with Office 365 64-bit

I'll be trying to rebuild the entire application in 64 bit, to see if that makes a difference. (just realized the problem might be simply the office version being in 64 bit rather than 32 bit)

Does anybody here have any idea what else it might be?


问:
Create a dictionary with comprehension
Can I use list comprehension syntax to create a dictionary?

For example, by iterating over pairs of keys and values:

```<code>d = {... for k, v in zip(keys, values)}
</code>```

答:
this approach uses iteration over the given date using a for loop.

```<code>Syntax: {key: value for (key, value) in data}
</code>```

Eg:

```<code># create a list comprehension with country and code:
    Country_code = [('China', 86), ('USA', 1),
            ('Ghana', 233), ('Uk', 44)]

# use iterable method to show results
{key: value for (key, value) in Country_code}
</code>```

Title: Create a dictionary with comprehension

Body:
Can I use list comprehension syntax to create a dictionary?

For example, by iterating over pairs of keys and values:

d = {... for k, v in zip(keys, values)}

Body:
this approach uses iteration over the given date using a for loop.

Syntax: {key: value for (key, value) in data}

Eg:

# create a list comprehension with country and code:
    Country_code = [('China', 86), ('USA', 1),
            ('Ghana', 233), ('Uk', 44)]

# use iterable method to show results
{key: value for (key, value) in Country_code}


问:
ERROR [internal] load metadata for docker.io/library/python.alpine3.8:latest
I am new to Docker and learning how to creating an image in container but I am having this error  ERROR [internal] load metadata for docker.io/library/python.alpine3.8.3:latest

Please someone help me to fix this error!

```<code>FROM python.alpine3.8
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPOSE 5000
CMD python
</code>```

The above is the code of Dockerfile

答:
change docker daemon.json "buildkit" on the last line to FALSE, like so:

```<code>  {
        "builder": { "gc": { "defaultKeepStorage": "20GB", "enabled": true } },
        "experimental": false,
        "features": { "buildkit": false }
    }
</code>```

Body:
I am new to Docker and learning how to creating an image in container but I am having this error  ERROR [internal] load metadata for docker.io/library/python.alpine3.8.3:latest

Please someone help me to fix this error!

FROM python.alpine3.8
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPOSE 5000
CMD python

The above is the code of Dockerfile

Body:
change docker daemon.json "buildkit" on the last line to FALSE, like so:

  {
        "builder": { "gc": { "defaultKeepStorage": "20GB", "enabled": true } },
        "experimental": false,
        "features": { "buildkit": false }
    }


问:
Yaml frontmatter not parsing as documented
I have yaml frontmatter installed in a php/Laravel project, but I cannot get it to work as documentend.

I made a testfile test.html:

```<code>---
title: Example
---
Lorem ipsum.
</code>```

Then I try to parse with yaml:

```<code>$document = YamlFrontMatter::parse(file_get_contents('test.html'));

dd($document->title);
</code>```

The result:

```<code>Spatie\YamlFrontMatter\Document {#280 ▼
  #matter: []
  #body: "--- title: Example --- Lorem ipsum."
}
</code>```

While matter should be:

```<code>['title' => 'Example']
</code>```

What am I doing wrong?

Kind regards

Hubert

答:
First your test.html file move to resources folder now follow this code

```<code>$document = YamlFrontMatter::parseFile(resource_path('test.html'));

dd($document->title);
</code>```

I hope you this solution is work.

Body:
I have yaml frontmatter installed in a php/Laravel project, but I cannot get it to work as documentend.

I made a testfile test.html:

---
title: Example
---
Lorem ipsum.

Then I try to parse with yaml:

$document = YamlFrontMatter::parse(file_get_contents('test.html'));

dd($document->title);

The result:

Spatie\YamlFrontMatter\Document {#280 ▼
  #matter: []
  #body: "--- title: Example --- Lorem ipsum."
}

While matter should be:

['title' => 'Example']

What am I doing wrong?

Kind regards

Hubert

Body:
First your test.html file move to resources folder now follow this code

$document = YamlFrontMatter::parseFile(resource_path('test.html'));

dd($document->title);

I hope you this solution is work.


问:
M4 "No such file or directory".Bison
This is my code in file skener.y

```<code> %{
#include <stdio.h>
%}
%token T_Int
%%

exp:      T_Int           { $$ = $1;         }
| exp exp '+'     { $$ = $1 + $2;    }
| exp exp '-'     { $$ = $1 - $2;    }
| exp exp '*'     { $$ = $1 * $2;    }
| exp exp '/'     { $$ = $1 / $2;    }

;
%%
</code>```

When I compile it with comand "bison -d skener.y" I get error "m4: No such file or directory.". Of course I am located in working folder when typing command in prompt. I dont know what is it about?

答:
Moved the Folder from

```<code>C:\Program Files(x86)\GnuWin32
</code>```

to

```<code>C:\GnuWin32
</code>```

then, added PATH values to both user variables and system variables as:

```<code>C:\GnuWin32\bin
</code>```

Title: M4 "No such file or directory".Bison

Body:
This is my code in file skener.y

 %{
#include <stdio.h>
%}
%token T_Int
%%

exp:      T_Int           { $$ = $1;         }
| exp exp '+'     { $$ = $1 + $2;    }
| exp exp '-'     { $$ = $1 - $2;    }
| exp exp '*'     { $$ = $1 * $2;    }
| exp exp '/'     { $$ = $1 / $2;    }

;
%%

When I compile it with comand "bison -d skener.y" I get error "m4: No such file or directory.". Of course I am located in working folder when typing command in prompt. I dont know what is it about?

Body:
Moved the Folder from

C:\Program Files(x86)\GnuWin32

to

C:\GnuWin32

then, added PATH values to both user variables and system variables as:

C:\GnuWin32\bin


问:
How to retrieve Contact name and phone number in Android
I'm trying to retrieve contact list with there name and phone numbers. I try following code:

```<code> // Get a cursor over every contact.
    Cursor cursor = getContentResolver().query(People.CONTENT_URI,
                                               null, null, null, null);
    // Let the activity manage the cursor lifecycle.
    startManagingCursor(cursor);
    // Use the convenience properties to get the index of the columns
    int nameIdx = cursor.getColumnIndexOrThrow(People.NAME);

    int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER);
    String[] result = new String[cursor.getCount()];
    if (cursor.moveToFirst())
      do {
        // Extract the name.
        String name = cursor.getString(nameIdx);
        // Extract the phone number.
        String phone = cursor.getString(phoneIdx);
        result[cursor.getPosition()] = name + "-" +" "+  phone;
      } while(cursor.moveToNext());
</code>```

This code should return an array with the all contacts name and its phone number but this only returns name of the contact and returns NULL in phone number,

Example Output:

```<code> John - null
</code>```

答:
Try the below code. </p>

```<code>Cursor managedCursor = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
 new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, null, null,  Phone.DISPLAY_NAME + " ASC");
</code>```

Body:
I'm trying to retrieve contact list with there name and phone numbers. I try following code:

 // Get a cursor over every contact.
    Cursor cursor = getContentResolver().query(People.CONTENT_URI,
                                               null, null, null, null);
    // Let the activity manage the cursor lifecycle.
    startManagingCursor(cursor);
    // Use the convenience properties to get the index of the columns
    int nameIdx = cursor.getColumnIndexOrThrow(People.NAME);

    int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER);
    String[] result = new String[cursor.getCount()];
    if (cursor.moveToFirst())
      do {
        // Extract the name.
        String name = cursor.getString(nameIdx);
        // Extract the phone number.
        String phone = cursor.getString(phoneIdx);
        result[cursor.getPosition()] = name + "-" +" "+  phone;
      } while(cursor.moveToNext());

This code should return an array with the all contacts name and its phone number but this only returns name of the contact and returns NULL in phone number,

Example Output:

 John - null

Body:
Try the below code.

Cursor managedCursor = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
 new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, null, null,  Phone.DISPLAY_NAME + " ASC");


问:
How do you plot density curves on top of the data to show distribution in R
I am looking to plot the density curves within the distribution of my data. I have heard (not not expert) on something called lognormal distribution?
My data is the following:

```<code>data<- data.frame(
      Day=c(1,2,3,4,5,6,7,8,9,10),
      Variable=c(3,5,20,10,8,18,23,21,16,12))

ggplot(data)  +
  geom_bar(aes(y=Variable, x=Day),stat="identity", colour="black")+
  labs(title= "",x="",y=expression('Variable'))+  theme_classic()
</code>```

And would like something like this:

答:
I am assuming here that your data are frequencies, therefore in order to
simplify subsequent operations, first transform them into a vector of single observations.

library(ggplot2)
library(tidyr)
library(dplyr)

long <- with(data, rep(Day, times = Variable))

long[1:20]

[1] 1 1 1 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3
```
<p>Now using <code>ggplot</code> you can plot the histogram and density estimate:</p>
<pre class="lang-r prettyprint-override"><code>data.frame(Day = long) |>
  ggplot() +
  geom_bar(aes(x = Day), stat = "count") +
  geom_density(aes(x = Day, after_stat(count)))
</code>```

To fit a mixture of two gaussian distributions (as in the reference example), you can use mclust. Note that this is shown only as an example and it is probably not the best way to treat your data. Here, the parameter G specifies the number of models:

library(mclust)
fit <- densityMclust(long, G = 2)
```
<p>Next, the data are prepared for plotting using ggplot in several steps:</p>
<ul>
<li>the density estimates are produced for both gaussian models in a suitable range of <code>x</code> using <code>predict</code></li>
<li>the density values are scaled to match the proportion of observations predicted to be in either model</li>
<li>the dataframe is rearranged pivoting on the <code>x</code></li>
</ul>
<pre class="lang-r prettyprint-override"><code>x <- seq(0, max(long) + 1, by = 0.1)

dens <- predict(fit, x, what = "cdens") |>
  apply(1, function(z) z*table(fit$classification)) |>
  t() |>
  data.frame() |>
  cbind(x = x) |>
  pivot_longer(cols = c(X1, X2),
               names_to = "K",
               values_to = "y")
</code>```

Finally, the densities are layered upon the barplot, by specifying in geom_line that the source of data is dens:

data.frame(Day = long) |>
  ggplot() +
  geom_bar(aes(x = Day), stat = "count") +
  geom_line(data = dens,
            aes(x = x, y = y, color = K))
```

Body:
I am looking to plot the density curves within the distribution of my data. I have heard (not not expert) on something called lognormal distribution?
My data is the following:

data<- data.frame(
      Day=c(1,2,3,4,5,6,7,8,9,10),
      Variable=c(3,5,20,10,8,18,23,21,16,12))

ggplot(data)  +
  geom_bar(aes(y=Variable, x=Day),stat="identity", colour="black")+
  labs(title= "",x="",y=expression('Variable'))+  theme_classic()

And would like something like this:

Body:
I am assuming here that your data are frequencies, therefore in order to
simplify subsequent operations, first transform them into a vector of single observations.

library(ggplot2)
library(tidyr)
library(dplyr)

long <- with(data, rep(Day, times = Variable))

long[1:20]

[1] 1 1 1 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3

Now using ggplot you can plot the histogram and density estimate:

data.frame(Day = long) |>
  ggplot() +
  geom_bar(aes(x = Day), stat = "count") +
  geom_density(aes(x = Day, after_stat(count)))

To fit a mixture of two gaussian distributions (as in the reference example), you can use mclust. Note that this is shown only as an example and it is probably not the best way to treat your data. Here, the parameter G specifies the number of models:

library(mclust)
fit <- densityMclust(long, G = 2)

Next, the data are prepared for plotting using ggplot in several steps:

the density estimates are produced for both gaussian models in a suitable range of x using predict

the density values are scaled to match the proportion of observations predicted to be in either model

the dataframe is rearranged pivoting on the x

x <- seq(0, max(long) + 1, by = 0.1)

dens <- predict(fit, x, what = "cdens") |>
  apply(1, function(z) z*table(fit$classification)) |>
  t() |>
  data.frame() |>
  cbind(x = x) |>
  pivot_longer(cols = c(X1, X2),
               names_to = "K",
               values_to = "y")

Finally, the densities are layered upon the barplot, by specifying in geom_line that the source of data is dens:

data.frame(Day = long) |>
  ggplot() +
  geom_bar(aes(x = Day), stat = "count") +
  geom_line(data = dens,
            aes(x = x, y = y, color = K))


问:
Ruby Watir Gem Won't See Updated Div
I have a scrape on a JS driven HTML page that updates found products on the same page.  I want to grab the products and parse them out.  I want to then move onto the next page, which I have already managed using Watir.  The problem is that Watir cannot see the first page's items.  Each item is formatted in the HTML below.  Here is my code after, then the result:

```<code>## HTML
<div data-jplist-item="" class="itemSpace">
  <div class="itemContainer">
    <a href="/en/Products/All/Tipless Chine" target="_blank" title="Click here to learn more about this product">
    <div class="name itemName">(1711) Red Chine, Tips Removed<span style="display:none;">boat part, DELTAUPDATE</span></div>
    <div class="saleDiscount" style="display:none;">25.575</div>
    <div class="itemNo" style="display:none;">1711</div>
    <div class="saleNote">SALE</div></a>
  </div>
</div>

## code
##### a is the browser
item = a.div(class: "itemSpace")
ap item.inspect
puts item.class
puts
item2 = a.div(class: "itemContainer")
ap item2.inspect
puts item2.class

## result
"#<Watir::Div: located: false; {:class=>\"itemSpace\", :tag_name=>\"div\"}>"
Watir::Div

"#<Watir::Div: located: false; {:class=>\"itemContainer\", :tag_name=>\"div\"}>"
Watir::Div
</code>```

As you can see, the div is not located.  I'm under the impression Watir manages JS returns, so i don't know why it isn't visible.

Anybody know what I'm doing wrong?  Different gem (Ferrum) needs to be used?

答:
The located: false does not mean that Watir cannot see the element or that the element does not exist. It just means that the Watir has not tried to find the element yet. Once you perform an action on the element, then it will be located: true.

For example, if you inspected the class attribute (rather than the object's class), the :located will change to true.

```<code>item = a.div(class: "itemSpace")
p item.inspect
#=> "#<Watir::Div: located: false; {:class=>\"itemSpace\", :tag_name=>\"div\"}>"
p item.class_name   # note that this is #class_name not #class
#=> "itemSpace"
p item.inspect
#=> "#<Watir::Div: located: true; {:class=>\"itemSpace\", :tag_name=>\"div\"}>"
</code>```

As to why Watir no longer sees the first page of results, that would depend on what happens to them when loading the second page of results. If the first page of results is removed from the page (ie user can no longer see them), then Watir would not be able to see it either. You'd want to capture the first page of results before going to the next page.

Title: Ruby Watir Gem Won't See Updated Div

Body:
I have a scrape on a JS driven HTML page that updates found products on the same page.  I want to grab the products and parse them out.  I want to then move onto the next page, which I have already managed using Watir.  The problem is that Watir cannot see the first page's items.  Each item is formatted in the HTML below.  Here is my code after, then the result:

## HTML

(1711) Red Chine, Tips Removedboat part, DELTAUPDATE

25.575

1711

SALE

## code
##### a is the browser
item = a.div(class: "itemSpace")
ap item.inspect
puts item.class
puts
item2 = a.div(class: "itemContainer")
ap item2.inspect
puts item2.class

## result
"#<Watir::Div: located: false; {:class=>\"itemSpace\", :tag_name=>\"div\"}>"
Watir::Div

"#<Watir::Div: located: false; {:class=>\"itemContainer\", :tag_name=>\"div\"}>"
Watir::Div

As you can see, the div is not located.  I'm under the impression Watir manages JS returns, so i don't know why it isn't visible.

Anybody know what I'm doing wrong?  Different gem (Ferrum) needs to be used?

Body:
The located: false does not mean that Watir cannot see the element or that the element does not exist. It just means that the Watir has not tried to find the element yet. Once you perform an action on the element, then it will be located: true.

For example, if you inspected the class attribute (rather than the object's class), the :located will change to true.

item = a.div(class: "itemSpace")
p item.inspect
#=> "#<Watir::Div: located: false; {:class=>\"itemSpace\", :tag_name=>\"div\"}>"
p item.class_name   # note that this is #class_name not #class
#=> "itemSpace"
p item.inspect
#=> "#<Watir::Div: located: true; {:class=>\"itemSpace\", :tag_name=>\"div\"}>"

As to why Watir no longer sees the first page of results, that would depend on what happens to them when loading the second page of results. If the first page of results is removed from the page (ie user can no longer see them), then Watir would not be able to see it either. You'd want to capture the first page of results before going to the next page.


问:
How to change the number of size categories in seaborn scatterplot
I tried hard to look through all the documentation and examples but I am not able to figure it out. How do I change the number of categories = the number of size bubbles, and their boundaries in seaborn scatterplot? The sizes parameter doesn't help here.

It always gives me 6 of them regardless of what I try (here 8, 16, ..., 48):

import seaborn as sns

tips = sns.load_dataset("tips")

sns.scatterplot(data=tips, x="total_bill", y="tip", size="total_bill")
```
<p><img src="https://i.stack.imgur.com/SbXMA.png" alt="tips" /></p>
<p>or</p>
<pre class="lang-py prettyprint-override"><code>penguins = sns.load_dataset("penguins")

sns.scatterplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", size="body_mass_g")
</code>```

And how do I change their boundaries? Ie. if I want to have 10, 20, 30, 40, 50 in the first case or 3000, 4000, 5000, 6000 in the second?

I know that going around and creating another column in the dataframe works but that is not wanted (adds unnecessary columns and even if I do it on the fly, it's just not what I am looking for).

Workaround:

def myfunc(mass):
    if mass <3500:
        return 3000
    elif mass <4500:
        return 4000
    elif mass <5500:
        return 5000
    return 6000

penguins["mass"] = penguins.apply(lambda x: myfunc(x['body_mass_g']), axis=1)

sns.scatterplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", size="mass")
```

答:
I don't think seaborn has a fine-grained control, it just tries to come up with something that works a bit intuitively for many situations, but not for all.  The legend='full' parameter shows all values of the size column, but that can be too overwhelming.

The suggestion to create a new column with binned sizes has the drawback that this will also change the sizes used in the scatterplot.

An approach could be to create your own custom legend. Note that when the legend also contains other elements, this approach needs to be adapted a bit.

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

tips = sns.load_dataset("tips")

ax = sns.scatterplot(data=tips, x="total_bill", y="tip", size="total_bill", legend='full')
handles, labels = ax.get_legend_handles_labels()
labels = np.array([float(l) for l in labels])
desired_labels = [10, 20, 30, 40, 50]
desired_handles = [handles[np.argmin(np.abs(labels - d))] for d in desired_labels]
ax.legend(handles=desired_handles, labels=desired_labels, title=ax.legend_.get_title().get_text())
plt.show()
```
<p><img src="https://i.stack.imgur.com/L71Gk.png" alt="seaborn scatterplot with adjusted sizes in legend" /></p>
<p>The code can be wrapped into a function, and e.g. applied to the penguins:</p>
<pre class="lang-py prettyprint-override"><code>from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np

def sizes_legend(desired_sizes, ax=None):
    ax = ax or plt.gca()
    handles, labels = ax.get_legend_handles_labels()
    labels = np.array([float(l) for l in labels])
    desired_handles = [handles[np.argmin(np.abs(labels - d))] for d in desired_sizes]
    ax.legend(handles=desired_handles, labels=desired_sizes, title=ax.legend_.get_title().get_text())

penguins = sns.load_dataset("penguins")
ax = sns.scatterplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", size="body_mass_g", legend='full')
sizes_legend([3000, 4000, 5000, 6000], ax)
plt.show()
</code>```

Body:
I tried hard to look through all the documentation and examples but I am not able to figure it out. How do I change the number of categories = the number of size bubbles, and their boundaries in seaborn scatterplot? The sizes parameter doesn't help here.

It always gives me 6 of them regardless of what I try (here 8, 16, ..., 48):

import seaborn as sns

tips = sns.load_dataset("tips")

sns.scatterplot(data=tips, x="total_bill", y="tip", size="total_bill")

or

penguins = sns.load_dataset("penguins")

sns.scatterplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", size="body_mass_g")

And how do I change their boundaries? Ie. if I want to have 10, 20, 30, 40, 50 in the first case or 3000, 4000, 5000, 6000 in the second?

I know that going around and creating another column in the dataframe works but that is not wanted (adds unnecessary columns and even if I do it on the fly, it's just not what I am looking for).

Workaround:

def myfunc(mass):
    if mass <3500:
        return 3000
    elif mass <4500:
        return 4000
    elif mass <5500:
        return 5000
    return 6000

penguins["mass"] = penguins.apply(lambda x: myfunc(x['body_mass_g']), axis=1)

sns.scatterplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", size="mass")

Body:
I don't think seaborn has a fine-grained control, it just tries to come up with something that works a bit intuitively for many situations, but not for all.  The legend='full' parameter shows all values of the size column, but that can be too overwhelming.

The suggestion to create a new column with binned sizes has the drawback that this will also change the sizes used in the scatterplot.

An approach could be to create your own custom legend. Note that when the legend also contains other elements, this approach needs to be adapted a bit.

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

tips = sns.load_dataset("tips")

ax = sns.scatterplot(data=tips, x="total_bill", y="tip", size="total_bill", legend='full')
handles, labels = ax.get_legend_handles_labels()
labels = np.array([float(l) for l in labels])
desired_labels = [10, 20, 30, 40, 50]
desired_handles = [handles[np.argmin(np.abs(labels - d))] for d in desired_labels]
ax.legend(handles=desired_handles, labels=desired_labels, title=ax.legend_.get_title().get_text())
plt.show()

The code can be wrapped into a function, and e.g. applied to the penguins:

from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np

def sizes_legend(desired_sizes, ax=None):
    ax = ax or plt.gca()
    handles, labels = ax.get_legend_handles_labels()
    labels = np.array([float(l) for l in labels])
    desired_handles = [handles[np.argmin(np.abs(labels - d))] for d in desired_sizes]
    ax.legend(handles=desired_handles, labels=desired_sizes, title=ax.legend_.get_title().get_text())

penguins = sns.load_dataset("penguins")
ax = sns.scatterplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", size="body_mass_g", legend='full')
sizes_legend([3000, 4000, 5000, 6000], ax)
plt.show()


问:
SQL: Changing datetime into seconds
I had a calculation in my query to minus one datetime from another which has given me the correct result in terms of it's given to me in minutes and seconds but it is displaying oddly and I want to change it to just show seconds. I'll show you the section of code and the result below:

SELECT *, (last_hit - first_hit) as hit_difference,

FROM (SELECT
id,
MIN(case when pagepath LIKE '%yourquote%' THEN hittime end) AS first_hit,
MAX(case when pagepath LIKE '%yourquote%' THEN hittime end) AS last_hit

first_hit example 2022-01-11 16:59:22.770 UTC

last_hit example 2022-01-11 17:01:08.964 UTC

hit_difference result 0-0 0 0:1:46.194

答:
I want to change it to just show seconds.

Use below instead

```<code>SELECT *,
  (UNIX_SECONDS(last_hit) - UNIX_SECONDS(first_hit)) as hit_difference,
FROM ...
</code>```

Title: SQL: Changing datetime into seconds

Body:
I want to change it to just show seconds.

Use below instead

SELECT *,
  (UNIX_SECONDS(last_hit) - UNIX_SECONDS(first_hit)) as hit_difference,
FROM ...


问:
How to set value 1 (integer) into an variable inside IF clause in ASP classic?
I'm currently working on a webpage using ASP Classic.
I have created an If statement, if the company id is equal to 1, then the variable receives a connection.execute.
Else, the variable must receive an fixed value of 1.
For some reason it's not working. I've tried to google the correct syntax for such case, but I haven't been successful... here is the part of the code I have just told you guys about:</p>
```<code><%
Dim integrated_code
if SESSION("Company_ID") = 1 Then
    set integrated_code = connection.execute("SELECT TOP 1 ID_BLABLABLA FROM BLABLABLA")
Else
   set integrated_code = 1
End if
%>
</code>```

答:
Lose the "set", at least for the simple variable. The other one depends on the nature of "connection".</p>
```<code><%
Dim integrated_code
If Session("Company_ID") = 1 Then
    Set integrated_code = connection.execute("...")
Else
    integrated_code = 1
End If
%>
</code>```

Body:
I'm currently working on a webpage using ASP Classic.
I have created an If statement, if the company id is equal to 1, then the variable receives a connection.execute.
Else, the variable must receive an fixed value of 1.
For some reason it's not working. I've tried to google the correct syntax for such case, but I haven't been successful... here is the part of the code I have just told you guys about:

<%
Dim integrated_code
if SESSION("Company_ID") = 1 Then
    set integrated_code = connection.execute("SELECT TOP 1 ID_BLABLABLA FROM BLABLABLA")
Else
   set integrated_code = 1
End if
%>

Body:
Lose the "set", at least for the simple variable. The other one depends on the nature of "connection".

<%
Dim integrated_code
If Session("Company_ID") = 1 Then
    Set integrated_code = connection.execute("...")
Else
    integrated_code = 1
End If
%>


问:
Django on Heroku: relation does not exist
I built a Django 1.9 project locally with sqlite3 as my default database. I have an application named Download which defines the DownloadedSongs table in models.py:

models.py

```<code>from __future__ import unicode_literals
from django.db import models

class DownloadedSongs(models.Model):
    song_name = models.CharField(max_length = 255)
    song_artist = models.CharField(max_length = 255)

    def __str__(self):
        return self.song_name + ' - ' + self.song_artist
</code>```

Now, in order to deploy my local project to Heroku, I added the following lines at the bottom of my settings.py file:

```<code>import dj_database_url
DATABASES['default'] =  dj_database_url.config()
</code>```

My application has a form with a couple of text fields, and on submitting that form, the data gets inserted into the DownloadedSongs table. Now, when I deployed my project on Heroku and tried submitting this form, I got the following error:

```<code>Exception Type: ProgrammingError at /download/
Exception Value: relation "Download_downloadedsongs" does not exist
LINE 1: INSERT INTO "Download_downloadedsongs" ("song_name", "song_a...
</code>```

This is how my requirements.txt file looks like:

```<code>beautifulsoup4==4.4.1
cssselect==0.9.1
dj-database-url==0.4.1
dj-static==0.0.6
Django==1.9
django-toolbelt==0.0.1
gunicorn==19.6.0
lxml==3.6.0
psycopg2==2.6.1
requests==2.10.0
static3==0.7.0
</code>```

Also, I did try to run the following commands as well:

```<code>heroku run python manage.py makemigrations
heroku run python manage.py migrate
</code>```

However, the issue still persists. What seems to be wrong here?

答:
```<code>python manage.py makemigrations
python manage.py migrate
python manage.py migrate --run-syncdb
</code>```

this worked for me.

Body:
I built a Django 1.9 project locally with sqlite3 as my default database. I have an application named Download which defines the DownloadedSongs table in models.py:

models.py

from __future__ import unicode_literals
from django.db import models

class DownloadedSongs(models.Model):
    song_name = models.CharField(max_length = 255)
    song_artist = models.CharField(max_length = 255)

    def __str__(self):
        return self.song_name + ' - ' + self.song_artist

Now, in order to deploy my local project to Heroku, I added the following lines at the bottom of my settings.py file:

import dj_database_url
DATABASES['default'] =  dj_database_url.config()

My application has a form with a couple of text fields, and on submitting that form, the data gets inserted into the DownloadedSongs table. Now, when I deployed my project on Heroku and tried submitting this form, I got the following error:

Exception Type: ProgrammingError at /download/
Exception Value: relation "Download_downloadedsongs" does not exist
LINE 1: INSERT INTO "Download_downloadedsongs" ("song_name", "song_a...

This is how my requirements.txt file looks like:

beautifulsoup4==4.4.1
cssselect==0.9.1
dj-database-url==0.4.1
dj-static==0.0.6
Django==1.9
django-toolbelt==0.0.1
gunicorn==19.6.0
lxml==3.6.0
psycopg2==2.6.1
requests==2.10.0
static3==0.7.0

Also, I did try to run the following commands as well:

heroku run python manage.py makemigrations
heroku run python manage.py migrate

However, the issue still persists. What seems to be wrong here?

Body:
python manage.py makemigrations
python manage.py migrate
python manage.py migrate --run-syncdb

this worked for me.