问:
R. Display only TRUE values from a boolean expression?
Data science student here. New to R, in my first course. I've spent way too much time trying to figure out this exercise, so I figured I would ask someone on here.

I have created a dataframe built from 4 matrices, titled bee_numbers_data_2:

```<code>buff_tail garden_bee red_tail honeybee carder_bee
    10          8       18       12          8
     1          3        9       13         27
    37         19        1       16          6
     5          6        2        9         32
    12          4        4       10         23
</code>```

The exercise asks us to only show honeybee numbers >= 10.

So I've created a boolean expression to display the TRUE FALSE statements:

```<code>bee_numbers_data_2$honeybee>=10
</code>```

Which returns:

```<code>[1]  TRUE  TRUE  TRUE FALSE  TRUE
</code>```

However, I want to display a list of the VALUES of the true statements, not a list of TRUE FALSE statements.

I've been pouring over my textbook and the internet trying to figure out this simple problem, so any help would be greatly appreciated. Thanks so much.

答:
Although this is a fairly simple question, covered in most introductory texts on R, I could not find a duplicate on SO, so it seems worth answering here.

Let's break it down.  As you already showed, we can use boolean expressions to generate a vector of boolean values:

```<code>bee_numbers_data_2 = data.frame(honeybee=c(12,13,16,9,10))
bee_numbers_data_2$honeybee >= 10
# [1]  TRUE  TRUE  TRUE FALSE  TRUE
</code>```

If we want to know which of those are true, we can use the base R function which:

```<code>which(bee_numbers_data_2$honeybee >= 10)
# [1] 1 2 3 5
</code>```

If we want to know the original values corresponding to those position indices, we can use those indices to subset the original data, using [

```<code>bee_numbers_data_2$honeybee[which(bee_numbers_data_2$honeybee >= 10)]
# [1] 12 13 16 10
</code>```

Or, equivalently and a little more simple, we can subset using the boolean vales directly:

```<code>bee_numbers_data_2$honeybee[bee_numbers_data_2$honeybee >= 10]
</code>```

Note that as you learn more R, you will find that there are also some more advanced ways to filter and subset data, such as the packages data.table and dplyr.  However, it is best to understand how to use base R first, as shown above.

Body:
Data science student here. New to R, in my first course. I've spent way too much time trying to figure out this exercise, so I figured I would ask someone on here.

I have created a dataframe built from 4 matrices, titled bee_numbers_data_2:

buff_tail garden_bee red_tail honeybee carder_bee
    10          8       18       12          8
     1          3        9       13         27
    37         19        1       16          6
     5          6        2        9         32
    12          4        4       10         23

The exercise asks us to only show honeybee numbers >= 10.

So I've created a boolean expression to display the TRUE FALSE statements:

bee_numbers_data_2$honeybee>=10

Which returns:

[1]  TRUE  TRUE  TRUE FALSE  TRUE

However, I want to display a list of the VALUES of the true statements, not a list of TRUE FALSE statements.

I've been pouring over my textbook and the internet trying to figure out this simple problem, so any help would be greatly appreciated. Thanks so much.

Body:
Although this is a fairly simple question, covered in most introductory texts on R, I could not find a duplicate on SO, so it seems worth answering here.

Let's break it down.  As you already showed, we can use boolean expressions to generate a vector of boolean values:

bee_numbers_data_2 = data.frame(honeybee=c(12,13,16,9,10))
bee_numbers_data_2$honeybee >= 10
# [1]  TRUE  TRUE  TRUE FALSE  TRUE

If we want to know which of those are true, we can use the base R function which:

which(bee_numbers_data_2$honeybee >= 10)
# [1] 1 2 3 5

If we want to know the original values corresponding to those position indices, we can use those indices to subset the original data, using [

bee_numbers_data_2$honeybee[which(bee_numbers_data_2$honeybee >= 10)]
# [1] 12 13 16 10

Or, equivalently and a little more simple, we can subset using the boolean vales directly:

bee_numbers_data_2$honeybee[bee_numbers_data_2$honeybee >= 10]

Note that as you learn more R, you will find that there are also some more advanced ways to filter and subset data, such as the packages data.table and dplyr.  However, it is best to understand how to use base R first, as shown above.


来源: stackexchange

问:
Any reason why I shouldn't use couchdb for message passing or realtime activity streams?
While using ampq or xmpp (rabbitmq or ejabbered that could have couchdb as backends) seems like a good fit to deliver real time updates about friend state in a social gaming platform where updates are small but frequent, I can't help but think why wouldn't couchdb be a good platform to deliver such updates?

The main advantage I could think of is its ability to filter updates based on friends and availability of changes api, which makes developing such an application and managing it (including replication) quite easy compared to ampq or xmpp where you have to think about how to manage the pubsub nodes and who is subscribed to them at any point in time.

However, I can't help but think this is too good to be true, I can't find information on what couchdb's shortcomings are. Somehow, it feels like using MySQL for message passing which is why I am hesitant to using it.

Anyone have any experience in using couchdb for such applications? would you recommend another platform to use?

答:
I can think of one very simple reason...because databases were not designed to do this!

A message queue is exactly what this sort of work flow needs. Have you looked at some of the AMQP based products or services? These include RabbitMQ (installed locally) and StormMQ (cloud based service). More here:
http://www.amqp.org

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Wiremock customize recording and playback
I am using Wiremock for stubbing the service. So that I can continue working on client application while service is down. I am recording the request and response by creating the proxy to service and using the recordings while service is down.

Their is one problem here. The api I am calling accepts xml input. One of the parameter is guid which changes every time. Now for Wiremock change in guid is another request it does another recording. Also when running playback the request does not match because of new guid in every request. Is their any way to ignore this parameter completely while doing recording and responding through playback ?

TIA

答:
You can create an implementation of StubMappingTransformer in Java and register it as an extension with WireMock via wireMockConfig().extensions(new MyStubMappingTransformer() when you're starting it programmatically.

This will be called after a recording is completed and passed each stub that gets created, so you can add code that will e.g. swap the fields you don't want to match on exactly for placeholders.

ContentLicense: CC BY-SA 4.0


问:
How to change Tailwind CSS background color with Svelte, based on a value unpacked in #each?
I am a beginner in both Svelte and Tailwind and want to avoid an XY-Problem, so here is my goal:

I generate rows of a table with an #each loop in Svelte. (6 values per row). I now want to conditionally color the background of this row based on one value (the battery charge).

My idea was to conditionally render different  tags based on this value. Like this:

```<code>        {#each allLZ as {id, name, mac, status, lastcontact, battery}, i}

        {#if battery > 70}
          <tr class="bg-green-50">
        {:else if battery > 40}
          <tr class="bg-yellow-50">
        {:else }
          <tr class="bg-red-50">
        {/if}
</code>```

But this doesn't work as Svelte wants to see the tags closed to be full elements, not piecemeal code, fair enough.

So is there a good way to change tailwind background color based on a value unpacked in #each?

答:
I would recommend having a function that give you back the background color according to the batteryValue like:

let getBatteryColor = (batteryValue) => {
    if (batteryValue > 70) return 'green'
    if (batteryValue > 40) return 'yellow'
    return 'red'
}
```
<p>...and then consume it in the node's class:</p>
<pre class="lang-html prettyprint-override"><code><tr class={`bg-${getBatteryColor(batteryValue)}`}>
    <td>...</td>
</tr>
</code>```

Have a look at the REPL.

Body:
I am a beginner in both Svelte and Tailwind and want to avoid an XY-Problem, so here is my goal:

I generate rows of a table with an #each loop in Svelte. (6 values per row). I now want to conditionally color the background of this row based on one value (the battery charge).

My idea was to conditionally render different  tags based on this value. Like this:

        {#each allLZ as {id, name, mac, status, lastcontact, battery}, i}

        {#if battery > 70}

        {:else if battery > 40}

        {:else }

        {/if}

But this doesn't work as Svelte wants to see the tags closed to be full elements, not piecemeal code, fair enough.

So is there a good way to change tailwind background color based on a value unpacked in #each?

Body:
I would recommend having a function that give you back the background color according to the batteryValue like:

let getBatteryColor = (batteryValue) => {
    if (batteryValue > 70) return 'green'
    if (batteryValue > 40) return 'yellow'
    return 'red'
}

...and then consume it in the node's class:

<tr class={`bg-${getBatteryColor(batteryValue)}`}>
    <td>...</td>
</tr>

Have a look at the REPL.


问:
High memory usage in React Native FlatList
I am developing an app which allows the user to search for books and then display it in the search results. For displaying the results, I am using a FlatList with 3 columns and displaying the book cover and some basic information about the book.

I am storing the results from the API response in state without the comoponent. As more results are added, the memory consumption increases but the data is in JSON format, no images are store in state.

I have tried, using removeClippedSubviews and few other options that allow setting the window size but that has little to no difference on the memory usage.

Am I missing something here or is there a way to optimise this? Sample code is uploaded to this github repo

Here is the code snippet I am using:

```<code>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import type { Node } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import {
    ActivityIndicator,
    FlatList,
    Platform,
    SafeAreaView,
    StatusBar,
    StyleSheet,
    useColorScheme,
    View,
} from 'react-native';
import { Button, SearchBar, useTheme } from 'react-native-elements';
import { searchBooks } from './api/GoogleBooksService';
import HttpClient from './network/HttpClient';
import BookCard from './components/BookCard';

const searchParamsInitialState = {
    startIndex: 1,
    maxResults: 12,
    totalItems: null,
};

let debounceTimer;
const debounce = (callback, time) => {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(callback, time);
};

const isEndOfList = searchParams => {
    const { startIndex, maxResults, totalItems } = searchParams;
    if (totalItems == null) {
        return false;
    }
    console.log('isEndOfList', totalItems - (startIndex - 1 + maxResults) < 0);
    return totalItems - (startIndex - 1 + maxResults) < 0;
};

const App: () => Node = () => {
    const isDarkMode = useColorScheme() === 'dark';
    const [isLoading, setIsLoading] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const [globalSearchResults, setGlobalSearchResults] = useState([]);
    const [searchParams, setSearchParams] = useState(searchParamsInitialState);

    let searchCancelToken;
    let searchCancelTokenSource;

    // This ref will be used to track if the search Term has changed when tab is switched
    const searchRef = useRef();

    const clearSearch = () => {
        console.log('Clear everything!');
        searchRef.current = null;
        setGlobalSearchResults([]);
        setSearchParams(searchParamsInitialState);
        setIsLoading(false);
        searchCancelTokenSource?.cancel();
        searchCancelToken = null;
        searchCancelTokenSource = null;
    };

    useEffect(() => {
        debounce(async () => {
            setIsLoading(true);
            await searchGlobal(searchTerm);
            setIsLoading(false);
        }, 1000);
    }, [searchTerm]);

    /**
     * Search method
     */
    const searchGlobal = async text => {
        if (!text) {
            // Clear everything
            clearSearch();
            return;
        }
        setIsLoading(true);
        try {
            // Use the initial state values if the search term has changed
            let params = searchParams;
            if (searchRef.current !== searchTerm) {
                params = searchParamsInitialState;
            }

            const { items, totalItems } = await searchBooks(
                text,
                params.startIndex,
                params.maxResults,
                searchCancelTokenSource?.token,
            );
            if (searchRef.current === searchTerm) {
                console.log('Search term has not changed. Appending data');
                setGlobalSearchResults(prevState => prevState.concat(items));
                setSearchParams(prevState => ({
                    ...prevState,
                    startIndex: prevState.startIndex + prevState.maxResults,
                    totalItems,
                }));
            } else {
                console.log(
                    'Search term has changed. Updating data',
                    searchTerm,
                );
                if (!searchTerm) {
                    console.log('!searchTerm', searchTerm);
                    clearSearch();
                    return;
                }
                setGlobalSearchResults(items);
                setSearchParams({
                    ...searchParamsInitialState,
                    startIndex:
                        searchParamsInitialState.startIndex +
                        searchParamsInitialState.maxResults,
                    totalItems,
                });
            }
            searchRef.current = text;
        } catch (err) {
            if (HttpClient.isCancel(err)) {
                console.error('Cancelled', err.message);
            }
            console.error(`Error searching for "${text}"`, err);
        }
        setIsLoading(false);
    };

    const renderGlobalItems = ({ item }) => {
        return <BookCard book={item} />;
    };

    const { theme } = useTheme();

    return (
        <SafeAreaView style={styles.backgroundStyle}>
            <StatusBar
                barStyle={isDarkMode ? 'light-content' : 'dark-content'}
            />
            <View style={styles.container}>
                <SearchBar
                    showLoading={isLoading}
                    placeholder="Enter search term here"
                    onChangeText={text => {
                        setSearchTerm(text);
                    }}
                    value={searchTerm}
                    platform={Platform.OS}
                />
                {isLoading && globalSearchResults.length <= 0 && (
                    <ActivityIndicator animating style={styles.loader} />
                )}
                {globalSearchResults.length > 0 && (
                    <FlatList
                        removeClippedSubviews
                        columnWrapperStyle={styles.columnWrapper}
                        data={globalSearchResults}
                        numColumns={3}
                        showsHorizontalScrollIndicator={false}
                        keyExtractor={item => item + item.id}
                        renderItem={renderGlobalItems}
                        ListFooterComponent={
                            <>
                                {!isLoading &&
                                    !isEndOfList(searchParams) &&
                                    searchParams.totalItems > 0 && (
                                        <Button
                                            type="clear"
                                            title="Load more..."
                                            onPress={async () => {
                                                await searchGlobal(searchTerm);
                                            }}
                                        />
                                    )}
                                {isLoading && searchParams.totalItems != null && (
                                    <ActivityIndicator
                                        size="large"
                                        style={{
                                            justifyContent: 'center',
                                        }}
                                        color={theme.colors.primary}
                                    />
                                )}
                            </>
                        }
                    />
                )}
            </View>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    backgroundStyle: 'white',
    container: {
        height: '100%',
        width: '100%',
    },
    columnWrapper: {
        flex: 1,
    },
    loader: {
        flex: 1,
        justifyContent: 'center',
    },
});

export default App;

</code>```

答:
Can you try to chuck your array of list items into small sub-arrays, this package uses this mechanism https://github.com/bolan9999/react-native-largelist

The package has been praised by complex app teams including the Discord Mobile Team - https://discord.com/blog/how-discord-achieves-native-ios-performance-with-react-native

Body:
I am developing an app which allows the user to search for books and then display it in the search results. For displaying the results, I am using a FlatList with 3 columns and displaying the book cover and some basic information about the book.

I am storing the results from the API response in state without the comoponent. As more results are added, the memory consumption increases but the data is in JSON format, no images are store in state.

I have tried, using removeClippedSubviews and few other options that allow setting the window size but that has little to no difference on the memory usage.

Am I missing something here or is there a way to optimise this? Sample code is uploaded to this github repo

Here is the code snippet I am using:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import type { Node } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import {
    ActivityIndicator,
    FlatList,
    Platform,
    SafeAreaView,
    StatusBar,
    StyleSheet,
    useColorScheme,
    View,
} from 'react-native';
import { Button, SearchBar, useTheme } from 'react-native-elements';
import { searchBooks } from './api/GoogleBooksService';
import HttpClient from './network/HttpClient';
import BookCard from './components/BookCard';

const searchParamsInitialState = {
    startIndex: 1,
    maxResults: 12,
    totalItems: null,
};

let debounceTimer;
const debounce = (callback, time) => {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(callback, time);
};

const isEndOfList = searchParams => {
    const { startIndex, maxResults, totalItems } = searchParams;
    if (totalItems == null) {
        return false;
    }
    console.log('isEndOfList', totalItems - (startIndex - 1 + maxResults) < 0);
    return totalItems - (startIndex - 1 + maxResults) < 0;
};

const App: () => Node = () => {
    const isDarkMode = useColorScheme() === 'dark';
    const [isLoading, setIsLoading] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const [globalSearchResults, setGlobalSearchResults] = useState([]);
    const [searchParams, setSearchParams] = useState(searchParamsInitialState);

    let searchCancelToken;
    let searchCancelTokenSource;

    // This ref will be used to track if the search Term has changed when tab is switched
    const searchRef = useRef();

    const clearSearch = () => {
        console.log('Clear everything!');
        searchRef.current = null;
        setGlobalSearchResults([]);
        setSearchParams(searchParamsInitialState);
        setIsLoading(false);
        searchCancelTokenSource?.cancel();
        searchCancelToken = null;
        searchCancelTokenSource = null;
    };

    useEffect(() => {
        debounce(async () => {
            setIsLoading(true);
            await searchGlobal(searchTerm);
            setIsLoading(false);
        }, 1000);
    }, [searchTerm]);

    /**
     * Search method
     */
    const searchGlobal = async text => {
        if (!text) {
            // Clear everything
            clearSearch();
            return;
        }
        setIsLoading(true);
        try {
            // Use the initial state values if the search term has changed
            let params = searchParams;
            if (searchRef.current !== searchTerm) {
                params = searchParamsInitialState;
            }

            const { items, totalItems } = await searchBooks(
                text,
                params.startIndex,
                params.maxResults,
                searchCancelTokenSource?.token,
            );
            if (searchRef.current === searchTerm) {
                console.log('Search term has not changed. Appending data');
                setGlobalSearchResults(prevState => prevState.concat(items));
                setSearchParams(prevState => ({
                    ...prevState,
                    startIndex: prevState.startIndex + prevState.maxResults,
                    totalItems,
                }));
            } else {
                console.log(
                    'Search term has changed. Updating data',
                    searchTerm,
                );
                if (!searchTerm) {
                    console.log('!searchTerm', searchTerm);
                    clearSearch();
                    return;
                }
                setGlobalSearchResults(items);
                setSearchParams({
                    ...searchParamsInitialState,
                    startIndex:
                        searchParamsInitialState.startIndex +
                        searchParamsInitialState.maxResults,
                    totalItems,
                });
            }
            searchRef.current = text;
        } catch (err) {
            if (HttpClient.isCancel(err)) {
                console.error('Cancelled', err.message);
            }
            console.error(`Error searching for "${text}"`, err);
        }
        setIsLoading(false);
    };

    const renderGlobalItems = ({ item }) => {
        return <BookCard book={item} />;
    };

    const { theme } = useTheme();

    return (
        <SafeAreaView style={styles.backgroundStyle}>
            <StatusBar
                barStyle={isDarkMode ? 'light-content' : 'dark-content'}
            />
            <View style={styles.container}>
                <SearchBar
                    showLoading={isLoading}
                    placeholder="Enter search term here"
                    onChangeText={text => {
                        setSearchTerm(text);
                    }}
                    value={searchTerm}
                    platform={Platform.OS}
                />
                {isLoading && globalSearchResults.length <= 0 && (
                    <ActivityIndicator animating style={styles.loader} />
                )}
                {globalSearchResults.length > 0 && (
                    <FlatList
                        removeClippedSubviews
                        columnWrapperStyle={styles.columnWrapper}
                        data={globalSearchResults}
                        numColumns={3}
                        showsHorizontalScrollIndicator={false}
                        keyExtractor={item => item + item.id}
                        renderItem={renderGlobalItems}
                        ListFooterComponent={
                            <>
                                {!isLoading &&
                                    !isEndOfList(searchParams) &&
                                    searchParams.totalItems > 0 && (
                                        <Button
                                            type="clear"
                                            title="Load more..."
                                            onPress={async () => {
                                                await searchGlobal(searchTerm);
                                            }}
                                        />
                                    )}
                                {isLoading && searchParams.totalItems != null && (
                                    <ActivityIndicator
                                        size="large"
                                        style={{
                                            justifyContent: 'center',
                                        }}
                                        color={theme.colors.primary}
                                    />
                                )}
                            </>
                        }
                    />
                )}
            </View>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    backgroundStyle: 'white',
    container: {
        height: '100%',
        width: '100%',
    },
    columnWrapper: {
        flex: 1,
    },
    loader: {
        flex: 1,
        justifyContent: 'center',
    },
});

export default App;


问:
sagemaker-sklearn-container 1.0 requires pandas==0.25.*, but you have pandas 1.3.5 which is incompatible
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behavior is the source of the following dependency conflicts.

sagemaker-sklearn-container 1.0 requires pandas==0.25.*, but you have pandas 1.3.5 which is incompatible.

I am running my notebook locally under python virtual machine , and I have pandas 0.25.3 version but when I am training the model on sagemaker , it shows an error that amazon scikitlearn container 1.0 using 0.25.* but I have 1.3.5,

I don't understand how can I solve it , though locally I have 0.25.3

答:
As a workaround, You can use you training script to uninstall and install the required version of Pandas.

For example

```<code>import os
os.execute('pip ...')
</code>```

To speed up experimenting this workaround, you can use SageMaker local mode.

You can apply the same workaround while deploying the model by using the inference.py script.

Otherwise, you can extend the scikit-learn container and install the desired version of Pandas. The example here explains how to extend the pre-built containers.

Body:
As a workaround, You can use you training script to uninstall and install the required version of Pandas.

For example

import os
os.execute('pip ...')

To speed up experimenting this workaround, you can use SageMaker local mode.

You can apply the same workaround while deploying the model by using the inference.py script.

Otherwise, you can extend the scikit-learn container and install the desired version of Pandas. The example here explains how to extend the pre-built containers.


问:
Display pop up when user uploads file with the wrong extension in shiny app
In the app below when the user does not upload a .xls file I want a pop up to be displayed. Now it appears only in the beginning but if upload another lets say doc file it is hidden. I do not care it is with shinyalert package or other method.

```<code>library(shiny)
library(shinyalert)

ui <- fluidPage(
  useShinyalert(),  # Set up shinyalert
  fileInput('file1', 'Choose xls file',
            accept = c(".xls")
  )
)

server <- function(input, output, session) {
  observeEvent(input$file1, {
    if (is.null(input$file1))
    # Show a modal when the button is pressed
    shinyalert("Oops!", "Something went wrong.", type = "error")
  }, ignoreNULL = FALSE)
}

shinyApp(ui, server)
</code>```

答:
This also resets the fileInput:

```<code>library(shiny)
library(tools)

ui <- fluidPage(
  uiOutput("fileUpload")
)

server <- function(input, output, session) {

  showModal(modalDialog("My startup modal..."))

  resetFileUpload <- reactiveVal(FALSE)
  output$fileUpload <- renderUI({
    resetFileUpload() # reactive dependency
    resetFileUpload(FALSE)
    fileInput('file1', 'Choose xls file', accept = c(".xls"))
  })

  observeEvent(input$file1, {
    if(file_ext(input$file1$name) != "xls"){
      resetFileUpload(TRUE)
      showModal(modalDialog("That's not a .xls file"))
    }
  })
}

shinyApp(ui, server)
</code>```

Body:
In the app below when the user does not upload a .xls file I want a pop up to be displayed. Now it appears only in the beginning but if upload another lets say doc file it is hidden. I do not care it is with shinyalert package or other method.

library(shiny)
library(shinyalert)

ui <- fluidPage(
  useShinyalert(),  # Set up shinyalert
  fileInput('file1', 'Choose xls file',
            accept = c(".xls")
  )
)

server <- function(input, output, session) {
  observeEvent(input$file1, {
    if (is.null(input$file1))
    # Show a modal when the button is pressed
    shinyalert("Oops!", "Something went wrong.", type = "error")
  }, ignoreNULL = FALSE)
}

shinyApp(ui, server)

Body:
This also resets the fileInput:

library(shiny)
library(tools)

ui <- fluidPage(
  uiOutput("fileUpload")
)

server <- function(input, output, session) {

  showModal(modalDialog("My startup modal..."))

  resetFileUpload <- reactiveVal(FALSE)
  output$fileUpload <- renderUI({
    resetFileUpload() # reactive dependency
    resetFileUpload(FALSE)
    fileInput('file1', 'Choose xls file', accept = c(".xls"))
  })

  observeEvent(input$file1, {
    if(file_ext(input$file1$name) != "xls"){
      resetFileUpload(TRUE)
      showModal(modalDialog("That's not a .xls file"))
    }
  })
}

shinyApp(ui, server)


问:
Using multiple variables to create a Transport Rule
I am having an issue getting a piece of code working and would love some help with this.
I am confident this will be super easy for someone else.

Basically, I am trying to setup a script to create (and eventually update) a new exchange transport rule using two variables:

$Displaynames

$Emails

The issue I have is that I can't seem to find a way to utilize both variables at the same time.

I know I could get around this by first exporting my results into a CSV and then re-importing them each time, but I am sure there must be a better way.

Here's the problematic part of the script:

```<code>$ruleName = "My Rule"
$ruleHtml = "My html code"
$rule = Get-TransportRule | Where-Object {$_.Identity -contains $ruleName}
$DisplayNames = (Get-Mailbox -ResultSize Unlimited).DisplayName
$Emails = (Get-Mailbox -resultsize unlimited | Select-Object displayname -expandproperty emailaddresses).SMTPAddress

New-TransportRule -Name $ruleName -Priority 0 -FromScope "NotInOrganization" -ApplyHtmlDisclaimerLocation "Prepend" -HeaderMatchesMessageHeader From -HeaderMatchesPatterns $Displaynames -ApplyHtmlDisclaimerText $ruleHtml
</code>```

I've tried using -HeaderMatchesPatterns "$Displaynames","Emails" and various ways of turning the two variables into a single one, but still no luck.

Any help would be much appreciated!

答:
```<code>$VN = "Mike.*Meyer"
$NV = "Meyer.*Mike"

New-TransportRule -Name "Test123456" -HeaderMatchesPatterns $VN,$NV -HeaderMatchesMessageHeader "From"
</code>```

Works

Body:
I am having an issue getting a piece of code working and would love some help with this.
I am confident this will be super easy for someone else.

Basically, I am trying to setup a script to create (and eventually update) a new exchange transport rule using two variables:

$Displaynames

$Emails

The issue I have is that I can't seem to find a way to utilize both variables at the same time.

I know I could get around this by first exporting my results into a CSV and then re-importing them each time, but I am sure there must be a better way.

Here's the problematic part of the script:

$ruleName = "My Rule"
$ruleHtml = "My html code"
$rule = Get-TransportRule | Where-Object {$_.Identity -contains $ruleName}
$DisplayNames = (Get-Mailbox -ResultSize Unlimited).DisplayName
$Emails = (Get-Mailbox -resultsize unlimited | Select-Object displayname -expandproperty emailaddresses).SMTPAddress

New-TransportRule -Name $ruleName -Priority 0 -FromScope "NotInOrganization" -ApplyHtmlDisclaimerLocation "Prepend" -HeaderMatchesMessageHeader From -HeaderMatchesPatterns $Displaynames -ApplyHtmlDisclaimerText $ruleHtml

I've tried using -HeaderMatchesPatterns "$Displaynames","Emails" and various ways of turning the two variables into a single one, but still no luck.

Any help would be much appreciated!

Body:
$VN = "Mike.*Meyer"
$NV = "Meyer.*Mike"

New-TransportRule -Name "Test123456" -HeaderMatchesPatterns $VN,$NV -HeaderMatchesMessageHeader "From"

Works


问:
Perl Get File Last Modified Date Time No Module
I'm creating a script where I need to get the Last Modified Date of the files
I checked this thread How do I get a file's last modified time in Perl?

So I used the script below to get the last modified, at first it was working but when I try to run it again, the timestamp returns 00:00 January 1, 1970.

Why is that happening and how can I get the correct last modified date and time?

```<code>my $dir = '/tmp';

opendir(DIR, $dir) or die $!;
@content=readdir(DIR);

foreach(@content)
{
    next unless ($_ =~ m/\bfile.txt|file2.csv\b/);

    my $epoch_timestamp = (stat($_))[9];
    my $timestamp       = localtime($epoch_timestamp);
    $f_detail = $_ .' '.$timestamp;
    print "$f_detail\n";
}
closedir(DIR);

exit 0;
</code>```

When I tried to run the perl, I will get this result

file.txt Thu Jan  1 00:00:00 1970

file2.csv Thu Jan  1 00:00:00 1970

Ok, last update, it is working now, I try to run all of the scripts you've given to me, standalone script. I found what's causing the default time, see the script below, I remove that in my program and it works, didn't notice this at first, sorry. But still, it feels weird because I was sure that it is working when I first run it, but now it is working so yeah thank you guys!

```<code>if (($month = ((localtime)[4] + 1)) < 10)
{
  $month = '0' . $month;
}
if (($day = ((localtime)[3])) < 10)
{
  $day = '0' . $day;
}
if (($year = ((localtime)[5]+1900)) >= 2000)
{

  if (($year = $year - 2000) < 10)
  {
    $year = '0' . $year;
  }
}
else
{
  $year = $year - 1900;
}

$date = $month . $day . $year;
</code>```

答:
readdir returns file names without the full path. You need to prepend the path manually:

for (@content) {
    next unless /^(?:file\.txt|file2\.csv)\z/;

    my $epoch_timestamp = (stat("$dir/$_"))[9];
    #                           ~~~~~~~~~
```

Also note how I changed the regex to match the file names.

Body:
I'm creating a script where I need to get the Last Modified Date of the files
I checked this thread How do I get a file's last modified time in Perl?

So I used the script below to get the last modified, at first it was working but when I try to run it again, the timestamp returns 00:00 January 1, 1970.

Why is that happening and how can I get the correct last modified date and time?

my $dir = '/tmp';

opendir(DIR, $dir) or die $!;
@content=readdir(DIR);

foreach(@content)
{
    next unless ($_ =~ m/\bfile.txt|file2.csv\b/);

    my $epoch_timestamp = (stat($_))[9];
    my $timestamp       = localtime($epoch_timestamp);
    $f_detail = $_ .' '.$timestamp;
    print "$f_detail\n";
}
closedir(DIR);

exit 0;

When I tried to run the perl, I will get this result

file.txt Thu Jan  1 00:00:00 1970

file2.csv Thu Jan  1 00:00:00 1970

Ok, last update, it is working now, I try to run all of the scripts you've given to me, standalone script. I found what's causing the default time, see the script below, I remove that in my program and it works, didn't notice this at first, sorry. But still, it feels weird because I was sure that it is working when I first run it, but now it is working so yeah thank you guys!

if (($month = ((localtime)[4] + 1)) < 10)
{
  $month = '0' . $month;
}
if (($day = ((localtime)[3])) < 10)
{
  $day = '0' . $day;
}
if (($year = ((localtime)[5]+1900)) >= 2000)
{

  if (($year = $year - 2000) < 10)
  {
    $year = '0' . $year;
  }
}
else
{
  $year = $year - 1900;
}

$date = $month . $day . $year;

Body:
readdir returns file names without the full path. You need to prepend the path manually:

for (@content) {
    next unless /^(?:file\.txt|file2\.csv)\z/;

    my $epoch_timestamp = (stat("$dir/$_"))[9];
    #                           ~~~~~~~~~

Also note how I changed the regex to match the file names.


问:
How to check if the field exists in firestore?
I am checking whether the Boolean field called attending exists, however I am not sure how to do that.

Is there a function such as .child().exists() or something similar that I could use?

```<code>firebaseFirestore.collection("Events")
    .document(ID)
    .collection("Users")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if(task.isSuccessful()) {
                for(QueryDocumentSnapshot document: task.getResult()){
                    attending = document.getBoolean("attending");
                }
            }
        }
    });
</code>```

答:
Here is how you can achieve it or you may have resolved already, this for any one searches for solution.

As per the documentation:

```<code>CollectionReference citiesRef = db.collection("cities");

Query query = citiesRef.whereNotEqualTo("capital", false);
</code>```

This query returns every city document where the capital field exists with a value other than false or null. This includes city documents where the capital field value equals true or any non-boolean value besides null.

For more information : https://cloud.google.com/firestore/docs/query-data/order-limit-data#java_5

Body:
I am checking whether the Boolean field called attending exists, however I am not sure how to do that.

Is there a function such as .child().exists() or something similar that I could use?

firebaseFirestore.collection("Events")
    .document(ID)
    .collection("Users")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if(task.isSuccessful()) {
                for(QueryDocumentSnapshot document: task.getResult()){
                    attending = document.getBoolean("attending");
                }
            }
        }
    });

Body:
Here is how you can achieve it or you may have resolved already, this for any one searches for solution.

As per the documentation:

CollectionReference citiesRef = db.collection("cities");

Query query = citiesRef.whereNotEqualTo("capital", false);

This query returns every city document where the capital field exists with a value other than false or null. This includes city documents where the capital field value equals true or any non-boolean value besides null.

For more information : https://cloud.google.com/firestore/docs/query-data/order-limit-data#java_5


问:
even if the screen exist the kivyMD is rasing error : kivy.uix.screenmanager.ScreenManagerException: No Screen with name "Main_page"
now i have made this whole project using kivyMD and I'm new to it what i want is to just login but for some reason its showing the error that the screen does not exist i tried everything but nothing helps any help will be appreciated.
NOW HERE the main .py file.

```<code>Builder.load_file("welcome.kv")
class Login_page(Screen):
    def validate_user(self):
        self.sm = ScreenManager(transition=NoTransition())
        print(details.keys())
        Username = MainApp.get_running_app().root.get_screen('Login_Page').ids.Username.text
        if Username in list(details.keys()):
            if details[Username] == MainApp.get_running_app().root.get_screen('Login_Page').ids.Password.text:
                self.manager.current = "Main_page"
        else:
            print("not here")
class ScreenManagement(ScreenManager):
    pass
class Main_page(Screen):
    pass
class MainApp(MDApp):
    def build(self):
        self.sm = ScreenManager(transition=NoTransition())
        self.sm.add_widget(Login_page(name = "Login_Page"))
        self.sm.add_widget(Sign_in_Page(name="Sign_in_Page"))
        self.sm.add_widget(Main_page(name = "Main_page"))
        self.sm.add_widget(Billings_Table(name="Billings_Table"))
        self.sm.add_widget(Employee_Table(name="Employee_Table"))
        self.sm.add_widget(Courier_Order_and_Details(name = "Courier_Order_and_Details"))
        return self.sm
</code>```

now below is the .kv part

```<code><Login_Page>:
    name : "Login_Page"
    MDScreen:
        MDToolbar:
            title : "Courier Service System"
            pos_hint : {"top":1}
        Image :
            source : "courier_design(256256).png"
            pos_hint : {'center_x':0.5,'center_y':0.7}
        MDTextField :
            id : Username
            hint_text: "Enter Username"
            halign : "center"
            size_hint : (0.25, 0.10)
            pos_hint : {'center_x': 0.5, 'center_y': 0.45}
            font_size : 12
        MDTextField :
            id : Password
            hint_text : "Password"
            halign : "center"
            size_hint : (0.25, 0.1)
            pos_hint : {'center_x': 0.5, 'center_y': 0.35}
            font_size : 12
            password : True
        MDFillRoundFlatButton :
            text : "Log in"
            font_size : 12
            size_hint : (0.25,0.05)
            pos_hint : {'center_x' : 0.5,'center_y' : 0.28}
            on_release: app.validate_user()
        MDLabel :
            text : "——————— or ———————"
            font_size : 15
            size_hint : (0.25, 0.05)
            pos_hint : {'center_x': 0.508, 'center_y': 0.23}
            theme_text_color : "Secondary"
        MDFillRoundFlatButton :
            text : "Sign in"
            font_size : 12
            size_hint : (0.25, 0.05)
            pos_hint : {'center_x': 0.5, 'center_y': 0.18}
            on_release: app.root.current = "Sign_in_Page"
<Main_page>
    name : "Main_page"
    MDScreen:
        MDLabel :
            text : "Our Services :"
            align : "center"
            font_size : 30
            size_hint : (0.5, 0.5)
            pos_hint : {'center_x': 0.5, 'center_y': 0.8}
            theme_text_color : "Secondary"
        MDToolbar:
            title: "Back"
            left_action_items: [["arrow-left",  lambda x: app.change_screen("Login_Page")]]
            pos_hint : {"top":1}
            font_size : 15

        MDFillRoundFlatButton :
            text : "Courier Order and Courier Details"
            font_size : 14
            size_hint : (0.4, 0.09)
            pos_hint : {'center_x': 0.5, 'center_y': 0.6}
            on_release: app.root.current = "Courier_Order_and_Details"
        MDFillRoundFlatButton :
            text : "Billings Details"
            font_size : 14
            size_hint : (0.4, 0.09)
            pos_hint : {'center_x': 0.5, 'center_y': 0.4}
            on_release: app.root.current = "Billings_Table"
        MDFillRoundFlatButton :
            text : "Our Employees"
            font_size : 14
            size_hint : (0.4, 0.09)
            pos_hint : {'center_x': 0.5, 'center_y': 0.2}
            on_release: app.root.current ='Employee_Table'

</code>```

now there two validate codes and i know that first one i used when i wrote

```<code>root.validate_user
</code>```

and still got the similar problem

答:
When building a large app with kivymd, it is more effective to use the screen manager as the root of the app. which means the kv fill look like this

```<code>#: import NoTransition kivy.uix.screenmanager.NoTransition

<LoginPage>:
     MDScreen:
        MDToolbar:
            title : "Courier Service System"
            pos_hint : {"top":1}
        Image :
            source : "courier_design(256256).png"
            pos_hint : {'center_x':0.5,'center_y':0.7}
        MDTextField :
            id : Username
            hint_text: "Enter Username"
            halign : "center"
            size_hint : (0.25, 0.10)
            pos_hint : {'center_x': 0.5, 'center_y': 0.45}
            font_size : 12
        MDTextField :
            id : Password
            hint_text : "Password"
            halign : "center"
            size_hint : (0.25, 0.1)
            pos_hint : {'center_x': 0.5, 'center_y': 0.35}
            font_size : 12
            password : True
        MDFillRoundFlatButton :
            text : "Log in"
            font_size : 12
            size_hint : (0.25,0.05)
            pos_hint : {'center_x' : 0.5,'center_y' : 0.28}
            on_release: root.validate_user()
        MDLabel :
            text : "——————— or ———————"
            font_size : 15
            size_hint : (0.25, 0.05)
            pos_hint : {'center_x': 0.508, 'center_y': 0.23}
            theme_text_color : "Secondary"
        MDFillRoundFlatButton :
            text : "Sign in"
            font_size : 12
            size_hint : (0.25, 0.05)
            pos_hint : {'center_x': 0.5, 'center_y': 0.18}
            on_release: app.root.current = "signin_page"
<MainPage>
    MDScreen:
        MDLabel :
            text : "Our Services :"
            align : "center"
            font_size : 30
            size_hint : (0.5, 0.5)
            pos_hint : {'center_x': 0.5, 'center_y': 0.8}
            theme_text_color : "Secondary"
        MDToolbar:
            title: "Back"
            left_action_items: [["arrow-left",  lambda x: app.change_screen("Login_Page")]]
            pos_hint : {"top":1}
            font_size : 15

        MDFillRoundFlatButton :
            text : "Courier Order and Courier Details"
            font_size : 14
            size_hint : (0.4, 0.09)
            pos_hint : {'center_x': 0.5, 'center_y': 0.6}
            on_release: app.root.current = "c_o_a_details"
        MDFillRoundFlatButton :
            text : "Billings Details"
            font_size : 14
            size_hint : (0.4, 0.09)
            pos_hint : {'center_x': 0.5, 'center_y': 0.4}
            on_release: app.root.current = "billings_table"
        MDFillRoundFlatButton :
            text : "Our Employees"
            font_size : 14
            size_hint : (0.4, 0.09)
            pos_hint : {'center_x': 0.5, 'center_y': 0.2}
            on_release: app.root.current ='employee_table'

ScreenManager:
    id: screen_manager
    transition: NoTransition()

    LoginPage:
        id: login_page
         name: "login_page"

    MainPage:
        id: main_page
         name: "main_page"

    SigninPage:
        id: signin_page
         name: "signin_page"

    BillingsTable:
        id: billings_table
         name: "billings_table"

    EmployeeTable:
        id: employee_table
         name: "employee_table"

    CourierOrderAndDetails:
        id: c_o_a_details
         name: "c_o_a_details"
</code>```

and the main.py file should be something like this

```<code>class LoginPage(Screen):
    def validate_user(self):
        print(details.keys())
        Username = self.ids.Username.text
        if Username in list(details.keys()):
            if details[Username] == self.ids.Password.text:
                MDApp.get_running_app().switch_screen(main_page)
        else:
            print("not here")

class MainPage(Screen):
    pass

class SigninPage(Screen):
    pass

class BillingsTable(Screen):
    pass

class EmployeeTable(Screen):
    pass

class CourierOrderAndDetails(Screen):
    pass

class MainApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.load_kv("welcome.kv")

    def switch_screen(self, screen_name, *args):
        self.root.current = screen_name
</code>```

if you noticed, i have restructured most of your code. the idea is not that what your did was wrong. just that it would be easier to scale the app when structured like this.

The error you had with the main page screen not being found is because
first you created a whole new instance of the screenmanager object which is completely differen from the one in the build function of the MainApp class and hence does not have the screens added

here: self.sm = ScreenManager(transition=NoTransition())

Next you use self.manager.current = "Main_page" to naviagate to the mainpage screen but Login_Page has no attribute self.manager. you  created self.sm but used self.manager

Anyways, This should solve your problem.

Body:
now i have made this whole project using kivyMD and I'm new to it what i want is to just login but for some reason its showing the error that the screen does not exist i tried everything but nothing helps any help will be appreciated.
NOW HERE the main .py file.

Builder.load_file("welcome.kv")
class Login_page(Screen):
    def validate_user(self):
        self.sm = ScreenManager(transition=NoTransition())
        print(details.keys())
        Username = MainApp.get_running_app().root.get_screen('Login_Page').ids.Username.text
        if Username in list(details.keys()):
            if details[Username] == MainApp.get_running_app().root.get_screen('Login_Page').ids.Password.text:
                self.manager.current = "Main_page"
        else:
            print("not here")
class ScreenManagement(ScreenManager):
    pass
class Main_page(Screen):
    pass
class MainApp(MDApp):
    def build(self):
        self.sm = ScreenManager(transition=NoTransition())
        self.sm.add_widget(Login_page(name = "Login_Page"))
        self.sm.add_widget(Sign_in_Page(name="Sign_in_Page"))
        self.sm.add_widget(Main_page(name = "Main_page"))
        self.sm.add_widget(Billings_Table(name="Billings_Table"))
        self.sm.add_widget(Employee_Table(name="Employee_Table"))
        self.sm.add_widget(Courier_Order_and_Details(name = "Courier_Order_and_Details"))
        return self.sm

now below is the .kv part

<Login_Page>:
    name : "Login_Page"
    MDScreen:
        MDToolbar:
            title : "Courier Service System"
            pos_hint : {"top":1}
        Image :
            source : "courier_design(256256).png"
            pos_hint : {'center_x':0.5,'center_y':0.7}
        MDTextField :
            id : Username
            hint_text: "Enter Username"
            halign : "center"
            size_hint : (0.25, 0.10)
            pos_hint : {'center_x': 0.5, 'center_y': 0.45}
            font_size : 12
        MDTextField :
            id : Password
            hint_text : "Password"
            halign : "center"
            size_hint : (0.25, 0.1)
            pos_hint : {'center_x': 0.5, 'center_y': 0.35}
            font_size : 12
            password : True
        MDFillRoundFlatButton :
            text : "Log in"
            font_size : 12
            size_hint : (0.25,0.05)
            pos_hint : {'center_x' : 0.5,'center_y' : 0.28}
            on_release: app.validate_user()
        MDLabel :
            text : "——————— or ———————"
            font_size : 15
            size_hint : (0.25, 0.05)
            pos_hint : {'center_x': 0.508, 'center_y': 0.23}
            theme_text_color : "Secondary"
        MDFillRoundFlatButton :
            text : "Sign in"
            font_size : 12
            size_hint : (0.25, 0.05)
            pos_hint : {'center_x': 0.5, 'center_y': 0.18}
            on_release: app.root.current = "Sign_in_Page"
<Main_page>
    name : "Main_page"
    MDScreen:
        MDLabel :
            text : "Our Services :"
            align : "center"
            font_size : 30
            size_hint : (0.5, 0.5)
            pos_hint : {'center_x': 0.5, 'center_y': 0.8}
            theme_text_color : "Secondary"
        MDToolbar:
            title: "Back"
            left_action_items: [["arrow-left",  lambda x: app.change_screen("Login_Page")]]
            pos_hint : {"top":1}
            font_size : 15

        MDFillRoundFlatButton :
            text : "Courier Order and Courier Details"
            font_size : 14
            size_hint : (0.4, 0.09)
            pos_hint : {'center_x': 0.5, 'center_y': 0.6}
            on_release: app.root.current = "Courier_Order_and_Details"
        MDFillRoundFlatButton :
            text : "Billings Details"
            font_size : 14
            size_hint : (0.4, 0.09)
            pos_hint : {'center_x': 0.5, 'center_y': 0.4}
            on_release: app.root.current = "Billings_Table"
        MDFillRoundFlatButton :
            text : "Our Employees"
            font_size : 14
            size_hint : (0.4, 0.09)
            pos_hint : {'center_x': 0.5, 'center_y': 0.2}
            on_release: app.root.current ='Employee_Table'

now there two validate codes and i know that first one i used when i wrote

root.validate_user

and still got the similar problem

Body:
When building a large app with kivymd, it is more effective to use the screen manager as the root of the app. which means the kv fill look like this

#: import NoTransition kivy.uix.screenmanager.NoTransition

<LoginPage>:
     MDScreen:
        MDToolbar:
            title : "Courier Service System"
            pos_hint : {"top":1}
        Image :
            source : "courier_design(256256).png"
            pos_hint : {'center_x':0.5,'center_y':0.7}
        MDTextField :
            id : Username
            hint_text: "Enter Username"
            halign : "center"
            size_hint : (0.25, 0.10)
            pos_hint : {'center_x': 0.5, 'center_y': 0.45}
            font_size : 12
        MDTextField :
            id : Password
            hint_text : "Password"
            halign : "center"
            size_hint : (0.25, 0.1)
            pos_hint : {'center_x': 0.5, 'center_y': 0.35}
            font_size : 12
            password : True
        MDFillRoundFlatButton :
            text : "Log in"
            font_size : 12
            size_hint : (0.25,0.05)
            pos_hint : {'center_x' : 0.5,'center_y' : 0.28}
            on_release: root.validate_user()
        MDLabel :
            text : "——————— or ———————"
            font_size : 15
            size_hint : (0.25, 0.05)
            pos_hint : {'center_x': 0.508, 'center_y': 0.23}
            theme_text_color : "Secondary"
        MDFillRoundFlatButton :
            text : "Sign in"
            font_size : 12
            size_hint : (0.25, 0.05)
            pos_hint : {'center_x': 0.5, 'center_y': 0.18}
            on_release: app.root.current = "signin_page"
<MainPage>
    MDScreen:
        MDLabel :
            text : "Our Services :"
            align : "center"
            font_size : 30
            size_hint : (0.5, 0.5)
            pos_hint : {'center_x': 0.5, 'center_y': 0.8}
            theme_text_color : "Secondary"
        MDToolbar:
            title: "Back"
            left_action_items: [["arrow-left",  lambda x: app.change_screen("Login_Page")]]
            pos_hint : {"top":1}
            font_size : 15

        MDFillRoundFlatButton :
            text : "Courier Order and Courier Details"
            font_size : 14
            size_hint : (0.4, 0.09)
            pos_hint : {'center_x': 0.5, 'center_y': 0.6}
            on_release: app.root.current = "c_o_a_details"
        MDFillRoundFlatButton :
            text : "Billings Details"
            font_size : 14
            size_hint : (0.4, 0.09)
            pos_hint : {'center_x': 0.5, 'center_y': 0.4}
            on_release: app.root.current = "billings_table"
        MDFillRoundFlatButton :
            text : "Our Employees"
            font_size : 14
            size_hint : (0.4, 0.09)
            pos_hint : {'center_x': 0.5, 'center_y': 0.2}
            on_release: app.root.current ='employee_table'

ScreenManager:
    id: screen_manager
    transition: NoTransition()

    LoginPage:
        id: login_page
         name: "login_page"

    MainPage:
        id: main_page
         name: "main_page"

    SigninPage:
        id: signin_page
         name: "signin_page"

    BillingsTable:
        id: billings_table
         name: "billings_table"

    EmployeeTable:
        id: employee_table
         name: "employee_table"

    CourierOrderAndDetails:
        id: c_o_a_details
         name: "c_o_a_details"

and the main.py file should be something like this

class LoginPage(Screen):
    def validate_user(self):
        print(details.keys())
        Username = self.ids.Username.text
        if Username in list(details.keys()):
            if details[Username] == self.ids.Password.text:
                MDApp.get_running_app().switch_screen(main_page)
        else:
            print("not here")

class MainPage(Screen):
    pass

class SigninPage(Screen):
    pass

class BillingsTable(Screen):
    pass

class EmployeeTable(Screen):
    pass

class CourierOrderAndDetails(Screen):
    pass

class MainApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.load_kv("welcome.kv")

    def switch_screen(self, screen_name, *args):
        self.root.current = screen_name

if you noticed, i have restructured most of your code. the idea is not that what your did was wrong. just that it would be easier to scale the app when structured like this.

The error you had with the main page screen not being found is because
first you created a whole new instance of the screenmanager object which is completely differen from the one in the build function of the MainApp class and hence does not have the screens added

here: self.sm = ScreenManager(transition=NoTransition())

Next you use self.manager.current = "Main_page" to naviagate to the mainpage screen but Login_Page has no attribute self.manager. you  created self.sm but used self.manager

Anyways, This should solve your problem.


问:
Protecting Range through Google Apps Script
I am trying to protect a range through google apps script in my google sheet. Whenever the data point in column O is checked i.e. value is yes. I would like that row be protected.
Secondly, I have prior protected columns E:H and M:N, which should stay protected.
There are around 1000 rows, 10-15 new rows that need to be protected daily. By the code I have currently written, it removes the protection and then re-adds it, which takes a lot of time. If I remove the part where it removes the rights then it still re-adds the same protection regardless.

Is there anyway to check if the cell is protected, if protected move onto the next row?

Secondly, I'm unable to provide access to the other emails i.e. "add editors"

```<code>function removecompleted(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var purchased = ss.getSheetByName("Purchased Inventory")
  last_row_purchased = purchased.getLastRow()
  var emails = [
    'user@domain.com'
  ];

var protections = purchased.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
  var protection = protections[i];
  if (protection.canEdit()) {
    protection.remove();
  }
}

  for(var i = 1; i < last_row_purchased; i++) {
    if(purchased.getRange(i, 15).getValue() == "Yes")
    {
      target_range = purchased.getRange(i, 1, 1, 15)
      protection = target_range.protect().setDescription('Sample protected range');

      var me = Session.getEffectiveUser();
      protection.addEditor(me);
      protection.removeEditors(protection.getEditors())
      protection.addEditors(emails);

protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

    }
  }
var range = purchased.getRange('E:H');
var protection = range.protect().setDescription('Always Protected');
var range = purchased.getRange('M:N');
var protection = range.protect().setDescription('Always Protected');
}

</code>```

答:
You can do this on edit, but rather than checking to see if the cell is protected (which is not that much faster than just setting the protection anyway) you can just check the row of each protected range and remove the protection if its row is equal to the row of the cell that was just unticked:

```<code>function onEdit(e) {
  // List of sheet names the function should run on
  const sheets = ["Sheet1", "Sheet2", "Sheet3", "etc"]

  const sheet = e.source.getActiveSheet()

  // if current sheet is not in permitted sheets, return
  if (!~sheets.indexOf(sheet.getName())) {
    return
  }

  const row = e.range.getRow()

  if (e.range.getColumn() === 15) {
    const ss = e.source

    if (e.value === "TRUE") {
      range = sheet.getRange(`${row}:${row}`)
      const me = Session.getEffectiveUser().getEmail()
      const protection = range.protect()
      protection.getEditors().forEach(user => {
        protection.removeEditor(user.getEmail())
      })
      protection.addEditor(me)
    }
    else {
      const protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE)
      protections.forEach(function(p) {
        if (p.getRange().getRow() === row) {
          if (row === 1 && p.getRange().getColumn() !== 1) return
          p.remove()
        }
      })
    }
  }
}
</code>```

Code Rundown:

Get the row number of the edited range

Check if the edited cell was column 15

If the value of the cell is "TRUE", protect the row, and remove all editors aside yourself.

If the value of the cell is "FALSE", then get all the sheet's protections, check the value of their row, and if the row matches the edited cell's row, then remove that protection

NB : The final check also has a condition to check if the column is not equal to 1 so to not remove the protections on E:H or M:N.

References:

Class Protection

Class: Sheet

Class: Range

Body:
I am trying to protect a range through google apps script in my google sheet. Whenever the data point in column O is checked i.e. value is yes. I would like that row be protected.
Secondly, I have prior protected columns E:H and M:N, which should stay protected.
There are around 1000 rows, 10-15 new rows that need to be protected daily. By the code I have currently written, it removes the protection and then re-adds it, which takes a lot of time. If I remove the part where it removes the rights then it still re-adds the same protection regardless.

Is there anyway to check if the cell is protected, if protected move onto the next row?

Secondly, I'm unable to provide access to the other emails i.e. "add editors"

function removecompleted(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var purchased = ss.getSheetByName("Purchased Inventory")
  last_row_purchased = purchased.getLastRow()
  var emails = [
    'user@domain.com'
  ];

var protections = purchased.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
  var protection = protections[i];
  if (protection.canEdit()) {
    protection.remove();
  }
}

  for(var i = 1; i < last_row_purchased; i++) {
    if(purchased.getRange(i, 15).getValue() == "Yes")
    {
      target_range = purchased.getRange(i, 1, 1, 15)
      protection = target_range.protect().setDescription('Sample protected range');

      var me = Session.getEffectiveUser();
      protection.addEditor(me);
      protection.removeEditors(protection.getEditors())
      protection.addEditors(emails);

protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

    }
  }
var range = purchased.getRange('E:H');
var protection = range.protect().setDescription('Always Protected');
var range = purchased.getRange('M:N');
var protection = range.protect().setDescription('Always Protected');
}

Body:
You can do this on edit, but rather than checking to see if the cell is protected (which is not that much faster than just setting the protection anyway) you can just check the row of each protected range and remove the protection if its row is equal to the row of the cell that was just unticked:

function onEdit(e) {
  // List of sheet names the function should run on
  const sheets = ["Sheet1", "Sheet2", "Sheet3", "etc"]

  const sheet = e.source.getActiveSheet()

  // if current sheet is not in permitted sheets, return
  if (!~sheets.indexOf(sheet.getName())) {
    return
  }

  const row = e.range.getRow()

  if (e.range.getColumn() === 15) {
    const ss = e.source

    if (e.value === "TRUE") {
      range = sheet.getRange(`${row}:${row}`)
      const me = Session.getEffectiveUser().getEmail()
      const protection = range.protect()
      protection.getEditors().forEach(user => {
        protection.removeEditor(user.getEmail())
      })
      protection.addEditor(me)
    }
    else {
      const protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE)
      protections.forEach(function(p) {
        if (p.getRange().getRow() === row) {
          if (row === 1 && p.getRange().getColumn() !== 1) return
          p.remove()
        }
      })
    }
  }
}

Code Rundown:

Get the row number of the edited range

Check if the edited cell was column 15

If the value of the cell is "TRUE", protect the row, and remove all editors aside yourself.

If the value of the cell is "FALSE", then get all the sheet's protections, check the value of their row, and if the row matches the edited cell's row, then remove that protection

NB : The final check also has a condition to check if the column is not equal to 1 so to not remove the protections on E:H or M:N.

References:

Class Protection

Class: Sheet

Class: Range


问:
table of "mean of combined columns" and join with original table in R
I have a file (tekoopl) with 300,000 rows and 16 columns. Column 2 is PRICE and column 13 is DISTRICT. (In the DISTRICT column there are different districts in London; for example 2000 rows with district Westend, 4000 rows with district London etc.. The rows are interchangeable).
Now I get stuck on the following questions:
a. Generate a table with the average PRICE per DISTRICT
b. Join this with the original table 'tekoopl). (So the final table is not aggregated but has the same number of rows as the original table)
c. Create a new column (PRICE-DISTRICTPRICE) with the difference between the PRICE and the DISTRICT average.
I only manage to calculate the average/mean PRICE of the column PRICE, but I need to have the average PRICE of all rows 'district a', all rows district b'and the number of rows of the new table (dfl07) must be equal to the number of rows in 'tekoopl'. Because after that, I have to join them. Which of course I cannot do.  :-( Can someone help me?

```<code>tekoopl <- read.csv("datafiles/ppd_london_15161718.csv",
                    stringsAsFactors = FALSE)
str(tekoopl)
dfl07 <- select(tekoopl, PRICE, DISTRICT) %>%
GEM = round(mean(tekoopl$PRICE, na.rm = TRUE))
</code>```

(I am currently using the packages dplyr and tidyr)

答:
To generate a seperate table for the average price per district:

```<code>dfl07 %>% dplyr::group_by(DISTRICT) %>% summarise(mean_price=mean(PRICE, na.rm=T))
</code>```

If you want to have it in your original table (so a column with an average prize per district, which I think is what you want to achieve), then:

```<code>dfl07 %>% dplyr::group_by(DISTRICT) %>% mutate(mean_price=mean(PRICE, na.rm=T))
</code>```

To create mean price per district and the difference between the price and mean price for district (for the reference tekpool data frame):

```<code>tekoopl %>% dplyr::group_by(DISTRICT) %>% mutate(mean_price=mean(PRICE, na.rm=T), price_diff=PRICE-mean_price)
</code>```

Body:
I have a file (tekoopl) with 300,000 rows and 16 columns. Column 2 is PRICE and column 13 is DISTRICT. (In the DISTRICT column there are different districts in London; for example 2000 rows with district Westend, 4000 rows with district London etc.. The rows are interchangeable).
Now I get stuck on the following questions:
a. Generate a table with the average PRICE per DISTRICT
b. Join this with the original table 'tekoopl). (So the final table is not aggregated but has the same number of rows as the original table)
c. Create a new column (PRICE-DISTRICTPRICE) with the difference between the PRICE and the DISTRICT average.
I only manage to calculate the average/mean PRICE of the column PRICE, but I need to have the average PRICE of all rows 'district a', all rows district b'and the number of rows of the new table (dfl07) must be equal to the number of rows in 'tekoopl'. Because after that, I have to join them. Which of course I cannot do.  :-( Can someone help me?

tekoopl <- read.csv("datafiles/ppd_london_15161718.csv",
                    stringsAsFactors = FALSE)
str(tekoopl)
dfl07 <- select(tekoopl, PRICE, DISTRICT) %>%
GEM = round(mean(tekoopl$PRICE, na.rm = TRUE))

(I am currently using the packages dplyr and tidyr)

Body:
To generate a seperate table for the average price per district:

dfl07 %>% dplyr::group_by(DISTRICT) %>% summarise(mean_price=mean(PRICE, na.rm=T))

If you want to have it in your original table (so a column with an average prize per district, which I think is what you want to achieve), then:

dfl07 %>% dplyr::group_by(DISTRICT) %>% mutate(mean_price=mean(PRICE, na.rm=T))

To create mean price per district and the difference between the price and mean price for district (for the reference tekpool data frame):

tekoopl %>% dplyr::group_by(DISTRICT) %>% mutate(mean_price=mean(PRICE, na.rm=T), price_diff=PRICE-mean_price)


问:
Should I Use ExceptionFilter or Middleware for Exception Handling in .NET
I am using .NET 5 and I need to global exception handling mechanism.

Should I use ExceptionFilter or Middleware? Which one is the best practice for most of the ASP.NET Core applications?

答:
As general guidance, you should pick the middleware over the filter whenever is possible.

If you don't need any specific constructs from MVC, then you can safely implement your thing by using middleware. If you want to use MVC constructs (eg: ModelState or IActionResults), then use a filter because it will enable access to MVC.


问:
how save theme or color of my flutter app
please any one help me when I close my app the theme reback to defult theme,how can I save the theme when I pick color from colorpicker library and I use hive library to save data,
if there are any another libraries to save data better than hive please tell me

```<code>import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/src/block_picker.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';

void main() async {
  await Hive.initFlutter();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Counter',
      debugShowCheckedModeBanner: false,
      //theme: ThemeData(primarySwatch: Colors.blue),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Box? box;
  Color? z;

  @override
  void initState() {
    super.initState();
    openBox();
    try {
      getData();
    } catch (e) {
      print(e);
    }
  }

  Future openBox() async {
    var dir = await getApplicationDocumentsDirectory();
    Hive.init(dir.path);
    box = await Hive.openBox('colorBox');
    return;
  }

  void saveData(val) {
    box!.put('color1', val);
  }

  void getData() {
    setState(() {
      z = Color(box!.get('color1'));
    });
  }

  int counter = 0;

  void incrementCounter() {
    setState(() {
      counter++;
    });
  }

  Color color = Colors.blue;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Counter"),
        backgroundColor: z,
      ),
      endDrawer: Drawer(
        child: ListView(
          children: [
            ListTile(
              title: Text("pick color"),
              leading: Icon(Icons.color_lens),
              onTap: () => showDialog(
                  context: context,
                  builder: (ctx) => AlertDialog(
                        title: Text("select your color"),
                        content: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            BlockPicker(
                              onColorChanged: (Color value) {
                                saveData(value.value);

                              },
                              pickerColor: Colors.blue,
                            ),
                            TextButton(
                                onPressed: () {
                                  getData();
                                  Navigator.pop(ctx);
                                },
                                child: Text("close"))
                          ],
                        ),
                      )),
            ),
          ],
        ),
      ),
      body: Center(
        child: Container(
          width: double.infinity,
          height: double.infinity,
          child: TextButton(
            onPressed: () {
              incrementCounter();
            },
            child: Text(
              '${counter}',),
          ),
        ),
      ),
    );
  }
}
</code>```

I make code smaller as I can,and I remove all the style.

答:
Step 1: Install flutter hive from https://pub.dev/packages/hive_flutter

Step 2: import 'package:hive_flutter/adapters.dart'; in your models

This class as of writing this answer contains two classes:
Color and TimeOfDay

Body:
please any one help me when I close my app the theme reback to defult theme,how can I save the theme when I pick color from colorpicker library and I use hive library to save data,
if there are any another libraries to save data better than hive please tell me

import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/src/block_picker.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';

void main() async {
  await Hive.initFlutter();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Counter',
      debugShowCheckedModeBanner: false,
      //theme: ThemeData(primarySwatch: Colors.blue),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Box? box;
  Color? z;

  @override
  void initState() {
    super.initState();
    openBox();
    try {
      getData();
    } catch (e) {
      print(e);
    }
  }

  Future openBox() async {
    var dir = await getApplicationDocumentsDirectory();
    Hive.init(dir.path);
    box = await Hive.openBox('colorBox');
    return;
  }

  void saveData(val) {
    box!.put('color1', val);
  }

  void getData() {
    setState(() {
      z = Color(box!.get('color1'));
    });
  }

  int counter = 0;

  void incrementCounter() {
    setState(() {
      counter++;
    });
  }

  Color color = Colors.blue;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Counter"),
        backgroundColor: z,
      ),
      endDrawer: Drawer(
        child: ListView(
          children: [
            ListTile(
              title: Text("pick color"),
              leading: Icon(Icons.color_lens),
              onTap: () => showDialog(
                  context: context,
                  builder: (ctx) => AlertDialog(
                        title: Text("select your color"),
                        content: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            BlockPicker(
                              onColorChanged: (Color value) {
                                saveData(value.value);

                              },
                              pickerColor: Colors.blue,
                            ),
                            TextButton(
                                onPressed: () {
                                  getData();
                                  Navigator.pop(ctx);
                                },
                                child: Text("close"))
                          ],
                        ),
                      )),
            ),
          ],
        ),
      ),
      body: Center(
        child: Container(
          width: double.infinity,
          height: double.infinity,
          child: TextButton(
            onPressed: () {
              incrementCounter();
            },
            child: Text(
              '${counter}',),
          ),
        ),
      ),
    );
  }
}

I make code smaller as I can,and I remove all the style.


问:
Iterating over whole Pandas DataFrame with one variable
I thought my request was pretty simple but it seems like there might be no solution the way I would like it to be.
Let's say I have the following DataFrame:

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
```
<p>What I'm looking for is a function that would allow me to iterate over every cell in the DataFrame with the iteration variable being the content of the current cell. Something like</p>
<pre class="lang-py prettyprint-override"><code>for i in df.function():
    print(i)
</code>```

Ideally, this print command should count from 1 to 9 in this example. Is there a DataFrame function that would enable something like this?

答:
You can iterate over the flattened underlying numpy array:

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
#    0  1  2
# 0  1  2  3
# 1  4  5  6
# 2  7  8  9

for cell in df.to_numpy().ravel():
    print(cell, end=', ')
```
<p>output:</p>
```1, 2, 3, 4, 5, 6, 7, 8, 9,
```
<h5>iterating through rows first:</h5>
<pre class="lang-py prettyprint-override"><code>for cell in df.to_numpy().ravel(order='F'):
    print(cell, end=', ')
</code>```

output:

```<code>1, 4, 7, 2, 5, 8, 3, 6, 9,
</code>```

Body:
I thought my request was pretty simple but it seems like there might be no solution the way I would like it to be.
Let's say I have the following DataFrame:

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])

What I'm looking for is a function that would allow me to iterate over every cell in the DataFrame with the iteration variable being the content of the current cell. Something like

for i in df.function():
    print(i)

Ideally, this print command should count from 1 to 9 in this example. Is there a DataFrame function that would enable something like this?

Body:
You can iterate over the flattened underlying numpy array:

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
#    0  1  2
# 0  1  2  3
# 1  4  5  6
# 2  7  8  9

for cell in df.to_numpy().ravel():
    print(cell, end=', ')

output:

1, 2, 3, 4, 5, 6, 7, 8, 9,

iterating through rows first:

for cell in df.to_numpy().ravel(order='F'):
    print(cell, end=', ')

output:

1, 4, 7, 2, 5, 8, 3, 6, 9,


问:
How do I inject httpClient into an instantiated service?
I am instantiating MyService in app.module.ts, and providing it throughout my code.

However, I want MyService to use httpClient, and I am unable to angular-idiomatically instantiate httpClient to pass as a parameter to MyService. I'm not sure what the right way to access httpClient in MyService is.

I've looked at instantiating httpClient directly and then passing it as a parameter to my service. However it seems this creates a circular dependency. I have also tried messing with Injectors but this is specifically advised against by the Angular team apparently. I strongly feel I am missing something simple.

app.module.ts

```<code>imports: [
    ...
    httpClientModule
    ...
],

function MainServiceFactory() {
    return new MyService();
}
...
providers: [{
    provide: MyService,
    useFactory: MainServiceFactory
}],
...
</code>```

MyService.ts

```<code>...
constructor(private http : HttpClient) {
    ...
}
</code>```

Without instantiation and passing as parameter of httpClient: I get an "error in app.module.ts, expected 1 argument", naturally!
With instantiation I break angular recommendations.

Edit:
I had neglected to specify that I did import the httpClientModule

答:
As stated in the Angular API the FactoryProvider has an optional deps field inherited from core/FactorySansProvider. This field is an array where you can put dependencies for your factory. The only needed changes are:

```<code>function MainServiceFactory(http: HttpClient) {
    return new MyService(http);
}

providers: [{
    provide: MyService,
    useFactory: MainServiceFactory,
    deps: [HttpClient]
}],
</code>```

Here a reference to Angular dependency providers. The documentation also says that the useFactory should be used to evaluate run time dependencies and not static ones, but I guess that you have multiple options in your real code.

Body:
I am instantiating MyService in app.module.ts, and providing it throughout my code.

However, I want MyService to use httpClient, and I am unable to angular-idiomatically instantiate httpClient to pass as a parameter to MyService. I'm not sure what the right way to access httpClient in MyService is.

I've looked at instantiating httpClient directly and then passing it as a parameter to my service. However it seems this creates a circular dependency. I have also tried messing with Injectors but this is specifically advised against by the Angular team apparently. I strongly feel I am missing something simple.

app.module.ts

imports: [
    ...
    httpClientModule
    ...
],

function MainServiceFactory() {
    return new MyService();
}
...
providers: [{
    provide: MyService,
    useFactory: MainServiceFactory
}],
...

MyService.ts

...
constructor(private http : HttpClient) {
    ...
}

Without instantiation and passing as parameter of httpClient: I get an "error in app.module.ts, expected 1 argument", naturally!
With instantiation I break angular recommendations.

Edit:
I had neglected to specify that I did import the httpClientModule

Body:
As stated in the Angular API the FactoryProvider has an optional deps field inherited from core/FactorySansProvider. This field is an array where you can put dependencies for your factory. The only needed changes are:

function MainServiceFactory(http: HttpClient) {
    return new MyService(http);
}

providers: [{
    provide: MyService,
    useFactory: MainServiceFactory,
    deps: [HttpClient]
}],

Here a reference to Angular dependency providers. The documentation also says that the useFactory should be used to evaluate run time dependencies and not static ones, but I guess that you have multiple options in your real code.


问:
Datatips (mouse hover over variables in debug mode) not working in Visual Studio 2012 / Win 7 64bit
When I hover my mouse over a variable when debugging a C# app in Visual Studio nothing popups. I expect to see the value of the variable (aka datatips). I'm running Visual Studio 2012 Ultimate (trial edition) on Windows 7 64bit. Does anyone know what may prevent them from showing?

Things I've tried to no avail:
- Reinstall VS
- Search for an enable/disable setting but there doesn't seem to be one

I can see the datatips correctly with the same C# project on Windows 8/64bit with the same version of Visual Studio.

答: I updated the package of RestSharp, and my problem solved. Packages with warning icon on it can cause this problem.</p>


问:
Removing index numbers in QTablewidget
How can I remove the column with index numbers in QTableWidget ?

Title: Removing index numbers in QTablewidget

Body:
PyQt6
self.tableWidget.verticalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setVisible(False)


问:
ImportError: No module named ecmwfapi
I am having a hard time using the ecmwf-api-client.

I have successfully installed the interface.

I have also created a ~/.ecmwfapirc file with my credentials.

I have saved the test script in a file: myMac ~ % ./test.sh

When I run the script I get the following error:

```<code>Traceback (most recent call last):
  File "./test.sh", line 2, in <module>
    from ecmwfapi import ECMWFDataServer
ImportError: No module named ecmwfapi
</code>```

I am not sure what I am doing wrong, as I have followed the instructions provided.

Edit:

I thought this might be caused by a conflict between pip and python, so I made sure to have compatible versions:

pip 22.0.3 (python 3.9)

Python 3.9.10

Also, I created an alias in my ~/.bashrc for Python 3:

alias py3=python3

so as to do something like: $py3 -m pip install ecmwf-api-client

(I have uninstalled the api version I had previously installed before continuing)

However, it's still not working. The plot thickens.

答:
There, I fixed it.

I came across this, and although the accepted answer seemed plausible, it didn't do the trick for me. Even though the default version of python I am using is 3.9.10, when trying to install pip from scratch I got a 'ERROR: This script does not work on Python 2.7 The minimum supported Python version is 3.7'.

While looking into this, I found this other issue, and if you read through the comments you'll soon find out that the relationship between Homebrew and Python <3 is troublesome.

So, assuming that for some reason pip was targeting Python 2.7, which is indeed installed but to my knowledge not used, I ran pip2 install ecmwf-api-client, which gave me a deprecation warning, but did its job.

I can now connect to the API, everything seems to be working correctly.

Title: ImportError: No module named ecmwfapi

Body:
I am having a hard time using the ecmwf-api-client.

I have successfully installed the interface.

I have also created a ~/.ecmwfapirc file with my credentials.

I have saved the test script in a file: myMac ~ % ./test.sh

When I run the script I get the following error:

Traceback (most recent call last):
  File "./test.sh", line 2, in <module>
    from ecmwfapi import ECMWFDataServer
ImportError: No module named ecmwfapi

I am not sure what I am doing wrong, as I have followed the instructions provided.

Edit:

I thought this might be caused by a conflict between pip and python, so I made sure to have compatible versions:

pip 22.0.3 (python 3.9)

Python 3.9.10

Also, I created an alias in my ~/.bashrc for Python 3:

alias py3=python3

so as to do something like: $py3 -m pip install ecmwf-api-client

(I have uninstalled the api version I had previously installed before continuing)

However, it's still not working. The plot thickens.


问:
Add class in drop area (file input) when dragging an external image over
Hi how to add class using Jquery when I'm dragging element over drop area.

This is my HTML

```<code><div class="upload">
   <form action="">
      <input class="uploadfile" type="file" id="imageLoader" name="imageLoader">
      <div class="circle"><i class="flaticon-arrows-1"></i></div>
      <div class="text">Drag and Drop or browse from you computer</div>
   </form>
</div>
</code>```

I want to add class in upload div class something like this

```<code><div class="upload dragging"></div>
</code>```

答:
To remove dragging class when you leave drag area you can add this to Mosh Feu code:</p>
```<code>upload.addEventListener("dragleave", function( event ) {
    this.classList.remove('dragging');
}, false);
</code>```

Body:
Hi how to add class using Jquery when I'm dragging element over drop area.

This is my HTML

   <form action="">
      <input class="uploadfile" type="file" id="imageLoader" name="imageLoader">

Drag and Drop or browse from you computer

   </form>

I want to add class in upload div class something like this

Body:
To remove dragging class when you leave drag area you can add this to Mosh Feu code:

upload.addEventListener("dragleave", function( event ) {
    this.classList.remove('dragging');
}, false);


问:
Have multiple aggregations in a query always the same order?
Im asking for PostgreSQL specifically, but answers for other popular SQL implementations are appreciated as well.

Given an sql query with multiple aggregates, especially array_agg, is the order of the aggregated values deterministic?

Example:

```<code>SELECT ARRAY_AGG(columnA), ARRAY_AGG(columnB) FROM myTable
GROUP BY columnC
</code>```

Can I rely on both arrays to have the same order, meaning values at position i in both arrays will belong to the same source row?

I can't find anything about this in the docs and I'm unsure because I've read that parallelization could be used in calculating aggregates, which I'm afraid could possibly result in non-deterministic orders.

答:
The order is never deterministic if you don't provide an order by

So if you need a specific order, then specify it:

```<code>SELECT ARRAY_AGG(columnA order by some_sort_column),
       ARRAY_AGG(columnB order by some_sort_column)
FROM myTable
GROUP BY columnC
</code>```

Body:
Im asking for PostgreSQL specifically, but answers for other popular SQL implementations are appreciated as well.

Given an sql query with multiple aggregates, especially array_agg, is the order of the aggregated values deterministic?

Example:

SELECT ARRAY_AGG(columnA), ARRAY_AGG(columnB) FROM myTable
GROUP BY columnC

Can I rely on both arrays to have the same order, meaning values at position i in both arrays will belong to the same source row?

I can't find anything about this in the docs and I'm unsure because I've read that parallelization could be used in calculating aggregates, which I'm afraid could possibly result in non-deterministic orders.

Body:
The order is never deterministic if you don't provide an order by

So if you need a specific order, then specify it:

SELECT ARRAY_AGG(columnA order by some_sort_column),
       ARRAY_AGG(columnB order by some_sort_column)
FROM myTable
GROUP BY columnC


问:
Using PIL to fill empty image space with nearby colors (aka inpainting)
I create an image with PIL:

I need to fill in the empty space (depicted as black). I could easily fill it with a static color, but what I'd like to do is fill the pixels in with nearby colors. For example, the first pixel after the border might be a Gaussian blur of the filled-in pixels. Or perhaps a push-pull type algorithm described in The Lumigraph, Gortler, et al..

I need something that is not too slow because I have to run this on many images. I have access to other libraries, like numpy, and you can assume that I know the borders or a mask of the outside region or inside region. Any suggestions on how to approach this?

UPDATE:

As suggested by belisarius, opencv's inpaint method is perfect for this. Here's some python code that uses opencv to achieve what I wanted:

```<code>import Image, ImageDraw, cv

im = Image.open("u7XVL.png")
pix = im.load()

#create a mask of the background colors
# this is slow, but easy for example purposes
mask = Image.new('L', im.size)
maskdraw = ImageDraw.Draw(mask)
for x in range(im.size[0]):
    for y in range(im.size[1]):
        if pix[(x,y)] == (0,0,0):
            maskdraw.point((x,y), 255)

#convert image and mask to opencv format
cv_im = cv.CreateImageHeader(im.size, cv.IPL_DEPTH_8U, 3)
cv.SetData(cv_im, im.tostring())
cv_mask = cv.CreateImageHeader(mask.size, cv.IPL_DEPTH_8U, 1)
cv.SetData(cv_mask, mask.tostring())

#do the inpainting
cv_painted_im = cv.CloneImage(cv_im)
cv.Inpaint(cv_im, cv_mask, cv_painted_im, 3, cv.CV_INPAINT_NS)

#convert back to PIL
painted_im = Image.fromstring("RGB", cv.GetSize(cv_painted_im), cv_painted_im.tostring())
painted_im.show()
</code>```

And the resulting image:

答:
A method with nice results is the Navier-Stokes Image Restoration. I know OpenCV has it, don't know about PIL.

Your example:

I did it with Mathematica.

Edit

As per your reuquest, the code is:

```<code>i = Import["http://i.stack.imgur.com/uEPqc.png"];
Inpaint[i, ColorNegate@Binarize@i, Method -> "NavierStokes"]
</code>```

The  ColorNegate@ ...  part creates the replacement mask.
The filling is done with just the Inpaint[] command.

Body:
I create an image with PIL:

I need to fill in the empty space (depicted as black). I could easily fill it with a static color, but what I'd like to do is fill the pixels in with nearby colors. For example, the first pixel after the border might be a Gaussian blur of the filled-in pixels. Or perhaps a push-pull type algorithm described in The Lumigraph, Gortler, et al..

I need something that is not too slow because I have to run this on many images. I have access to other libraries, like numpy, and you can assume that I know the borders or a mask of the outside region or inside region. Any suggestions on how to approach this?

UPDATE:

As suggested by belisarius, opencv's inpaint method is perfect for this. Here's some python code that uses opencv to achieve what I wanted:

import Image, ImageDraw, cv

im = Image.open("u7XVL.png")
pix = im.load()

#create a mask of the background colors
# this is slow, but easy for example purposes
mask = Image.new('L', im.size)
maskdraw = ImageDraw.Draw(mask)
for x in range(im.size[0]):
    for y in range(im.size[1]):
        if pix[(x,y)] == (0,0,0):
            maskdraw.point((x,y), 255)

#convert image and mask to opencv format
cv_im = cv.CreateImageHeader(im.size, cv.IPL_DEPTH_8U, 3)
cv.SetData(cv_im, im.tostring())
cv_mask = cv.CreateImageHeader(mask.size, cv.IPL_DEPTH_8U, 1)
cv.SetData(cv_mask, mask.tostring())

#do the inpainting
cv_painted_im = cv.CloneImage(cv_im)
cv.Inpaint(cv_im, cv_mask, cv_painted_im, 3, cv.CV_INPAINT_NS)

#convert back to PIL
painted_im = Image.fromstring("RGB", cv.GetSize(cv_painted_im), cv_painted_im.tostring())
painted_im.show()

And the resulting image:

Body:
A method with nice results is the Navier-Stokes Image Restoration. I know OpenCV has it, don't know about PIL.

Your example:

I did it with Mathematica.

Edit

As per your reuquest, the code is:

i = Import["http://i.stack.imgur.com/uEPqc.png"];
Inpaint[i, ColorNegate@Binarize@i, Method -> "NavierStokes"]

The  ColorNegate@ ...  part creates the replacement mask.
The filling is done with just the Inpaint[] command.


问:
What parameter i have to assign inside my variable so i can start it from my Main?
im new to C# and Tia Openness and have an problem. I dont know what parameter goes inside my ImportSingleTextList();.Its an example from Siemens but there is never mentioned how to call it inisde the main. That is my code.</p>
```<code>private static void ImportSingleTextList(HmiTarget hmitarget)
        {
            TextListComposition textListsComposition = hmitarget.TextLists;
            IList<TextList> importedTextLists = textListsComposition.Import(new FileInfo(@"D:\SamplesImport\myTextList.xml"), ImportOptions.Override);
        }
</code>```

答:
I guess you have to look into your HmiTarget exactly. Is it a class, then you should instantiate a first instance of it; what constructor does this class have - with or without parameters? Click on HmiTarget and see what input it expects.

I guess you class has some kind of enumerable hmitarget.TextLists that you have to fill or get too.

Body:
im new to C# and Tia Openness and have an problem. I dont know what parameter goes inside my ImportSingleTextList();.Its an example from Siemens but there is never mentioned how to call it inisde the main. That is my code.

private static void ImportSingleTextList(HmiTarget hmitarget)
        {
            TextListComposition textListsComposition = hmitarget.TextLists;
            IList<TextList> importedTextLists = textListsComposition.Import(new FileInfo(@"D:\SamplesImport\myTextList.xml"), ImportOptions.Override);
        }


问:
How to parse integer column to String in CDAP (Datafusion)
Need your help to understand how Integer columns can be parsed to String Columns in Data Fusion using wrangler plugin.
Apologies to this naïve question as I am quite new to GCP and I tried googling it but could not find any solution.

Regards,
Vaishali

答: Wrangler Plugin supports parsing to limited formats. Integer to String parsing is not supported in the Data Fusion Wrangler plugin according to this doc. You can change the datatype of the data but parsing is not possible for integers to string.</p>