问:
Accessing Apollo's loading boolean outside of Mutation component
The Mutation component in react-apollo exposes a handy loading boolean in the render prop function which is ideal for adding loaders to the UI whilst a request is being made. In the example below my Button component calls the createPlan function when clicked which initiates a GraphQL mutation. Whilst this is happening a spinner appears on the button courtesy of the loading prop.

```<code><Mutation mutation={CREATE_PLAN}>
  {(createPlan, { loading }) => (
    <Button
      onClick={() => createPlan({ variables: { input: {} } })}
      loading={loading}
    >
      Save
    </Button>
  )}
</Mutation>
</code>```

The issue I have is that other aspects of my UI also need to change based on this loading boolean. I have tried lifting the Mutation component up the React tree so that I can manually pass the loading prop down to any components which rely on it, which works, but the page I am building has multiple mutations that can take place at any given time (such as deleting a plan, adding a single item in a plan, deleting a single item in a plan etc.) and having all of these Mutation components sitting at the page-level component feels very messy.

Is there a way that I can access the loading property outside of this Mutation component? If not, what is the best way to handle this problem? I have read that you can manually update the Apollo local state using the update function on the Mutation component (see example below) but I haven't been able to work out how to access the loading value here (plus it feels like accessing the loading property of a specific mutation without having to manually write it to the cache yourself would be a common request).

```<code><Mutation
  mutation={CREATE_PLAN}
  update={cache => {
    cache.writeData({
      data: {
        createPlanLoading: `I DON"T HAVE ACCESS TO THE LOADING BOOLEAN HERE`,
      },
    });
  }}
>
  {(createPlan, { loading }) => (
    <Button
      onClick={() => createPlan({ variables: { input: {} } })}
      loading={loading}
    >
      Save
    </Button>
  )}
</Mutation>
</code>```

答:
I face the same problem in my projects and yes, putting all mutations components at the page-level component is very messy. The best way I found to handle this is by creating React states. For instance:</p>

```<code>const [createPlanLoading, setCreatePLanLoading] = React.useState(false);

...

<Mutation mutation={CREATE_PLAN} onCompleted={() => setCreatePLanLoading(false)}>
  {(createPlan, { loading }) => (
    <Button
      onClick={() => {
        createPlan({ variables: { input: {} } });
        setCreatePLanLoading(true);
      }
      loading={loading}
    >
      Save
    </Button>
  )}
</Mutation>
</code>```

Body:
The Mutation component in react-apollo exposes a handy loading boolean in the render prop function which is ideal for adding loaders to the UI whilst a request is being made. In the example below my Button component calls the createPlan function when clicked which initiates a GraphQL mutation. Whilst this is happening a spinner appears on the button courtesy of the loading prop.

<Mutation mutation={CREATE_PLAN}>
  {(createPlan, { loading }) => (
    <Button
      onClick={() => createPlan({ variables: { input: {} } })}
      loading={loading}
    >
      Save
    </Button>
  )}
</Mutation>

The issue I have is that other aspects of my UI also need to change based on this loading boolean. I have tried lifting the Mutation component up the React tree so that I can manually pass the loading prop down to any components which rely on it, which works, but the page I am building has multiple mutations that can take place at any given time (such as deleting a plan, adding a single item in a plan, deleting a single item in a plan etc.) and having all of these Mutation components sitting at the page-level component feels very messy.

Is there a way that I can access the loading property outside of this Mutation component? If not, what is the best way to handle this problem? I have read that you can manually update the Apollo local state using the update function on the Mutation component (see example below) but I haven't been able to work out how to access the loading value here (plus it feels like accessing the loading property of a specific mutation without having to manually write it to the cache yourself would be a common request).

<Mutation
  mutation={CREATE_PLAN}
  update={cache => {
    cache.writeData({
      data: {
        createPlanLoading: `I DON"T HAVE ACCESS TO THE LOADING BOOLEAN HERE`,
      },
    });
  }}
>
  {(createPlan, { loading }) => (
    <Button
      onClick={() => createPlan({ variables: { input: {} } })}
      loading={loading}
    >
      Save
    </Button>
  )}
</Mutation>

Body:
I face the same problem in my projects and yes, putting all mutations components at the page-level component is very messy. The best way I found to handle this is by creating React states. For instance:

const [createPlanLoading, setCreatePLanLoading] = React.useState(false);

...

<Mutation mutation={CREATE_PLAN} onCompleted={() => setCreatePLanLoading(false)}>
  {(createPlan, { loading }) => (
    <Button
      onClick={() => {
        createPlan({ variables: { input: {} } });
        setCreatePLanLoading(true);
      }
      loading={loading}
    >
      Save
    </Button>
  )}
</Mutation>


来源: stackexchange

问:
Count duplicate values that share same FK id
I am trying to Count how many duplicates there are in one column that share the same FK id. There should only be one type per Shared_FK_id.

```<code>table:
Shared_FK_ID : bigint
type: varchar(50)
</code>```

Sample data:

```<code>831 Ford
831 Fiat
831 Honda
831 Honda
831 Dodge
831 Volvo
831 Volvo
831 Opel
</code>```

答:
To elaborate on Serg's answer, and also make it SQL-Server specific, you can do either of the following depending on exactly what output you need.

1)  the number of types which contain duplicates:

```<code>select Shared_FK_ID, count(*) nmbr_of_dbls
from (
   select Shared_FK_ID, [type] , count(*) nmbr
   from data
   group by Shared_FK_ID, [type]
   having count(*) > 1
) t
group by Shared_FK_ID
</code>```

2) the total number of duplicated rows in the whole FK ID:

```<code>select Shared_FK_ID, sum(nmbr) nmbr_of_dbls
from (
   select Shared_FK_ID, [type] , count(*) nmbr
   from data
   group by Shared_FK_ID, [type]
   having count(*) > 1
) t
group by Shared_FK_ID
</code>```

live demo: https://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=c8e1ed9607430fde16157367d59afc90

ContentLicense: CC BY-SA 4.0

Body:
I am trying to Count how many duplicates there are in one column that share the same FK id. There should only be one type per Shared_FK_id.

table:
Shared_FK_ID : bigint
type: varchar(50)

Sample data:

831 Ford
831 Fiat
831 Honda
831 Honda
831 Dodge
831 Volvo
831 Volvo
831 Opel

Body:
To elaborate on Serg's answer, and also make it SQL-Server specific, you can do either of the following depending on exactly what output you need.

1)  the number of types which contain duplicates:

select Shared_FK_ID, count(*) nmbr_of_dbls
from (
   select Shared_FK_ID, [type] , count(*) nmbr
   from data
   group by Shared_FK_ID, [type]
   having count(*) > 1
) t
group by Shared_FK_ID

2) the total number of duplicated rows in the whole FK ID:

select Shared_FK_ID, sum(nmbr) nmbr_of_dbls
from (
   select Shared_FK_ID, [type] , count(*) nmbr
   from data
   group by Shared_FK_ID, [type]
   having count(*) > 1
) t
group by Shared_FK_ID

live demo: https://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=c8e1ed9607430fde16157367d59afc90


问:
Porting std::map to C?
I am porting some c++ code to c. What is a viable equivalent of std::map in c?
I know there is no equivalent in c.

This is what I am thinking of using:

In c++:

```<code>std::map< uint, sTexture > m_Textures;
</code>```

In c:

```<code>typedef struct
{
  uint* intKey;
  sTexture* textureValue;
} sTMTextureMap;
</code>```

Is that viable or am I simplifying map too much? Just in case you did not get the purpose its a Texture Map.

答:
I have tried implementing a map in C, it is based on void *

https://github.com/davinash/cstl

It is work in progress, but map is complete.

https://github.com/davinash/cstl/blob/master/src/c_map.c

It is written based on Red Black Tree.

OwnerDisplayName: kthakore

ContentLicense: CC BY-SA 2.5

Title: Porting std::map to C?

Body:
I am porting some c++ code to c. What is a viable equivalent of std::map in c?
I know there is no equivalent in c.

This is what I am thinking of using:

In c++:

std::map< uint, sTexture > m_Textures;

In c:

typedef struct
{
  uint* intKey;
  sTexture* textureValue;
} sTMTextureMap;

Is that viable or am I simplifying map too much? Just in case you did not get the purpose its a Texture Map.

LastEditorDisplayName: kthakore


问:
C standard regarding pointer arithmetic outside arrays
I read lot of things about pointer arithmetic and undefined behavior (link, link, link, link, link). It always ends up to the same conclusion: Pointer arithmetic is well defined only on array type and between array[0] and array[array_size+1] (one element past the end is valid with regard to the C standard).

My question is: Does it means that when the compiler sees a pointer arithmetic not related to any array (undefined behavior), it could emit what it want (even nothing) ? Or is it more a high level "undefined behavior" meaning you could reach unmapped memory, garbage data, etc and there is not guarantee about the address validity?

In this example:

```<code>char test[10];
char * ptr = &test[0];
printf("test[-1] : %d", *(ptr-1))
</code>```

By "undefined behavior", is it just that the value is not guarantee at all (could be garbage, unmapped memory, etc) but we can still say with certainty that we are accessing the memory address contiguous to the array 8 bytes before the start? Or is it "undefined behavior" in a way that the compiler can just not emit this code at all?

Another simple use case: You want to compute the in-memory size of one function. One naïve implementation could be the following code assuming that the functions are outputted in the binary in the same order, are contiguous and without any padding in between.

```<code>#include <stdint.h>
#include <stdio.h>

void func1()
{}

void func2()
{}

int main()
{
  uint8_t * ptr1 = (uint8_t*) &func1;
  uint8_t * ptr2 = (uint8_t*) &func2;

  printf("Func 1 size : %ld", ptr2-ptr1);

  return 0;
}

</code>```

Since ptr1 and ptr2 are not part of an array, it is considered as undefined behavior. Again, does it means the compiler could not emit those code? Or does "undefined behavior" means that the subtraction is meaningless depending on the system (functions not contiguous in memory, with padding, etc) but still occurs as expected? Is there any well defined way to compute the subtraction between two unrelated pointers?

答:
The C standard has to say undefined behavior simply because things like memory mapping is beyond the scope of the standard.

This doesn't apply only to array indexing being the only allowed form of pointer arithmetic, but also the C concept of "effective type", which can be described as the compiler's internal list of what types that are actually stored at any given address it knows about. And accessing parts of memory which the compiler doesn't know about is essentially undefined behavior too.

If you look at the average embedded system, you frequently need to access addresses where there are no arrays, and as far as the compiler knows, no objects at all (memory-mapped registers etc). Therefore all such embedded C compilers have guarantees that such code behaves predictably, even though such guarantees are "non-standard extensions". Which in practice means that pointers boil down to integer numbers representing physical addresses.

Best practice is to write code that is safe no matter. For example, if we are to write a program that dumps the contents of a flash memory page, we want to iterate over it byte by byte (to drop the result on some serial bus). With the average embedded systems compiler, it is safe to simply set a volatile const uint8_t* to the first byte of the flash page, then iterate away, regardless of what variables and types that happen to be stored there. But from C's point of view, this is undefined behavior.

We can sate both the requirements from C and the real world by placing all variables to be allocated in that page inside one enormous struct foo { ... } bar;. Which we are allowed to iterate over byte by byte using a pointer to a character type like uint8_t. (C17 6.3.2.3/7).

So the effort of dodging undefined behavior isn't necessarily that cumbersome. There's often work-arounds with structs, unions, converting pointers to integers etc etc.

Body:
I read lot of things about pointer arithmetic and undefined behavior (link, link, link, link, link). It always ends up to the same conclusion: Pointer arithmetic is well defined only on array type and between array[0] and array[array_size+1] (one element past the end is valid with regard to the C standard).

My question is: Does it means that when the compiler sees a pointer arithmetic not related to any array (undefined behavior), it could emit what it want (even nothing) ? Or is it more a high level "undefined behavior" meaning you could reach unmapped memory, garbage data, etc and there is not guarantee about the address validity?

In this example:

char test[10];
char * ptr = &test[0];
printf("test[-1] : %d", *(ptr-1))

By "undefined behavior", is it just that the value is not guarantee at all (could be garbage, unmapped memory, etc) but we can still say with certainty that we are accessing the memory address contiguous to the array 8 bytes before the start? Or is it "undefined behavior" in a way that the compiler can just not emit this code at all?

Another simple use case: You want to compute the in-memory size of one function. One naïve implementation could be the following code assuming that the functions are outputted in the binary in the same order, are contiguous and without any padding in between.

#include <stdint.h>
#include <stdio.h>

void func1()
{}

void func2()
{}

int main()
{
  uint8_t * ptr1 = (uint8_t*) &func1;
  uint8_t * ptr2 = (uint8_t*) &func2;

  printf("Func 1 size : %ld", ptr2-ptr1);

  return 0;
}

Since ptr1 and ptr2 are not part of an array, it is considered as undefined behavior. Again, does it means the compiler could not emit those code? Or does "undefined behavior" means that the subtraction is meaningless depending on the system (functions not contiguous in memory, with padding, etc) but still occurs as expected? Is there any well defined way to compute the subtraction between two unrelated pointers?


问:
Ignore empty ComboBoxItems
I have a ComboBox which has bounded items, like

```<code><ComboBox ItemsSource="{Binding Path=list}"
          DisplayMemberPath="name"
          SelectedValuePath="id"
          SelectedValue="{Binding Path=id, Mode=TwoWay}"/>
</code>```

The Problem is that there is a minimum of 10 items in the list which can be empty.

Is there a way to ignore empty values as items?

I tried to remove the empty values with different methods, like

```<code>[System.Xml.Serialization.XmlIgnore]
public ObservableCollection<myclass> list
{
    get
    {
        ObservableCollection<myclass> list = new ObservableCollection<myclass>();

        foreach (var item in org_list.Where(x => !string.IsNullOrWhiteSpace(x.name)).ToList())
        {
            list.Add(item);
        }

        return list;
    }
}
</code>```

but it doesn't update the ComboBox any more if I'm adding any items to org_list.

答: Create a mirror list which exposes the list without the empties. For changes subscribe to the observable collections events that are relevant such as add/remove and keep the mirror consistent. Then bind to this filtered list. </p>

Title: Ignore empty ComboBoxItems

Body:
I have a ComboBox which has bounded items, like

<ComboBox ItemsSource="{Binding Path=list}"
          DisplayMemberPath="name"
          SelectedValuePath="id"
          SelectedValue="{Binding Path=id, Mode=TwoWay}"/>

The Problem is that there is a minimum of 10 items in the list which can be empty.

Is there a way to ignore empty values as items?

I tried to remove the empty values with different methods, like

[System.Xml.Serialization.XmlIgnore]
public ObservableCollection<myclass> list
{
    get
    {
        ObservableCollection<myclass> list = new ObservableCollection<myclass>();

        foreach (var item in org_list.Where(x => !string.IsNullOrWhiteSpace(x.name)).ToList())
        {
            list.Add(item);
        }

        return list;
    }
}

but it doesn't update the ComboBox any more if I'm adding any items to org_list.


问:
How do I add an extra column to the results of a GROUP BY with a value that matches a condition?
I'm trying to use GROUP BY to generate a summary of a table, but I want to add a column with a value that matches a condition from the original table.  The condition I want to check for is that style = 2 so that a new column with the filename that matches that style is shown in the results.

This is what the original table looks like:

```<code>category  |  value | style | filename
   A      |   8    |   0   |   AAA
   B      |   4    |   2   |   BBB
   B      |   6    |   1   |   CCC
   A      |   3    |   2   |   DDD
   A      |   6    |   1   |   EEE
   C      |   7    |   2   |   FFF
   B      |   5    |   1   |   GGG
   A      |   3    |   1   |   HHH
</code>```

This is what I want:

```<code>category  |  total_value   | filename
   A      |        20      |   DDD
   B      |        15      |   BBB
   C      |         7      |   FFF
</code>```

I tried this query, but the filename chosen was the MINIMUM, not the one that matches style = 2:

```<code>SELECT category, SUM(value) AS total_value, MIN(filename) AS filename FROM data GROUP BY category;
</code>```

答:
If I correctly understand, you need this: </p>

```<code>SELECT category, SUM(value) AS total_value,
MIN(case when style = 2 then filename end) AS filename
FROM data GROUP BY category;
</code>```

Body:
I'm trying to use GROUP BY to generate a summary of a table, but I want to add a column with a value that matches a condition from the original table.  The condition I want to check for is that style = 2 so that a new column with the filename that matches that style is shown in the results.

This is what the original table looks like:

category  |  value | style | filename
   A      |   8    |   0   |   AAA
   B      |   4    |   2   |   BBB
   B      |   6    |   1   |   CCC
   A      |   3    |   2   |   DDD
   A      |   6    |   1   |   EEE
   C      |   7    |   2   |   FFF
   B      |   5    |   1   |   GGG
   A      |   3    |   1   |   HHH

This is what I want:

category  |  total_value   | filename
   A      |        20      |   DDD
   B      |        15      |   BBB
   C      |         7      |   FFF

I tried this query, but the filename chosen was the MINIMUM, not the one that matches style = 2:

SELECT category, SUM(value) AS total_value, MIN(filename) AS filename FROM data GROUP BY category;

Body:
If I correctly understand, you need this:

SELECT category, SUM(value) AS total_value,
MIN(case when style = 2 then filename end) AS filename
FROM data GROUP BY category;


问:
Selenium python Error: element could not be scrolled into view
I am working on automating the IdentiGO application for my company, and I'm getting the following error:

```<code>Internal Server Error: /identigo
Traceback (most recent call last):
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/jane/Code/maynard_env/maynard/employee/views.py", line 63, in post
    driver.main(employee)
  File "/Users/jane/Code/maynard_env/maynard/employee/driver.py", line 31, in main
    WebDriverWait(driver, 1000000).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[5]/div[3]/div/button/span'))).click()
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: Element <span class="ui-button-text"> could not be scrolled into view
</code>```

Here is my code, with the scripts leading up to this page omitted since they aren't relevant to my problem.

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(driver, 1000000).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[5]/div[3]/div/button/span'))).click()
</code>```

On the page prior to this code, where the user selects an appointment date and time; I want the script to wait for the "Go" button to be pushed, then click on "Continue" in the following screenshot:

If you would like to see the exact page, go to this url, then you will have to make a series of POST requests using the following info:

click schedule a new appointment

other

vendors and contractors (children)

tnvc00047

37204

make random appointment date

Any advice would really be appreciated!

Update

Here is a JS Fiddle with the html of the page:

https://jsfiddle.net/khf4tym3/

When I click "view page source", the popup html doesn't show in the source code, so I assume that it is generated with JS.

```<code><div class="ui-dialog-buttonset">
    <button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
        <span class="ui-button-text">Continue</span>
    </button>
</div>
</code>```

Update 2

If I change the line WebDriverWait(driver, 1000000) to WebDriverWait(driver, 30), I get the following error instead:

```<code>Internal Server Error: /identigo
Traceback (most recent call last):
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/jane/Code/maynard_env/maynard/employee/views.py", line 63, in post
    driver.main(employee)
  File "/Users/jane/Code/maynard_env/maynard/employee/driver.py", line 34, in main
    element=WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.XPATH,"//div[@class='ui-dialog-buttonset']/button[@class='ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only']/span[contains(.,'Continue')]")))
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/support/wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
</code>```

pythonfiddle

code for the project so far, so you can skip the forum entry.

https://jsfiddle.net/93k5s2xg/1/

The working solution:

```<code>WebDriverWait(driver, 20).until(expected_conditions.element_to_be_clickable((By.XPATH, "//div[starts-with(@aria-describedby, 'ui-id-')]//span[@class='ui-button-text' and text()='Continue']"))).click()
</code>```

答:
This error message...

```<code>selenium.common.exceptions.ElementNotInteractableException: Message: Element <span class="ui-button-text"> could not be scrolled into view
</code>```

...implies that the WebDriver instance i.e. driver was unable to scroll the element within the Viewport to invoke click().

First of all, as your usecase is to invoke click() on the element, ideally instead of using presence_of_element_located() you need to use the ExpectedConditions as element_to_be_clickable() as follows:

```<code>WebDriverWait(driver, 1000000).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[5]/div[3]/div/button/span'))).click()
</code>```

You can find a couple of detailed discussions in:

Message: Element  could not be scrolled into view while trying to click on an option within a dropdown menu through Selenium

org.openqa.selenium.ElementNotInteractableException: Element  could not be scrolled into view when trying to click a button

As an alternative, as per the error message, to scroll an element within the Viewport before invoking click() you can also use the Element.scrollIntoView() method.

You can find a detailed discussion in:
- What is the difference between the different scroll options?

At this point it is worth to mention, the following methods:

move_to_element() from selenium.webdriver.common.action_chains

element_to_be_clickable() from selenium.webdriver.support.expected_conditions

will automatically scroll the element within the Viewport.

You can find a detailed discussion in:
- How to scroll a webpage using selenium webdriver in Python without using javascript method execute_script()

This usecase

The button with text as Continue is within the Top Level Content but rendered within a Modal Dialog Box.

DevTools Snapshot:

As the desired element is within a Modal Dialog Box, so to locate and invoke click() on the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use the following Locator Strategy:

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[starts-with(@aria-describedby, 'ui-id-')]//span[@class='ui-button-text' and text()='Continue']"))).click()
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

DevTools Snapshot:

Body:
I am working on automating the IdentiGO application for my company, and I'm getting the following error:

Internal Server Error: /identigo
Traceback (most recent call last):
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/jane/Code/maynard_env/maynard/employee/views.py", line 63, in post
    driver.main(employee)
  File "/Users/jane/Code/maynard_env/maynard/employee/driver.py", line 31, in main
    WebDriverWait(driver, 1000000).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[5]/div[3]/div/button/span'))).click()
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: Element  could not be scrolled into view

Here is my code, with the scripts leading up to this page omitted since they aren't relevant to my problem.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(driver, 1000000).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[5]/div[3]/div/button/span'))).click()

On the page prior to this code, where the user selects an appointment date and time; I want the script to wait for the "Go" button to be pushed, then click on "Continue" in the following screenshot:

If you would like to see the exact page, go to this url, then you will have to make a series of POST requests using the following info:

click schedule a new appointment

other

vendors and contractors (children)

tnvc00047

37204

make random appointment date

Any advice would really be appreciated!

Update

Here is a JS Fiddle with the html of the page:

https://jsfiddle.net/khf4tym3/

When I click "view page source", the popup html doesn't show in the source code, so I assume that it is generated with JS.

    <button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
        Continue
    </button>

Update 2

If I change the line WebDriverWait(driver, 1000000) to WebDriverWait(driver, 30), I get the following error instead:

Internal Server Error: /identigo
Traceback (most recent call last):
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/jane/Code/maynard_env/maynard/employee/views.py", line 63, in post
    driver.main(employee)
  File "/Users/jane/Code/maynard_env/maynard/employee/driver.py", line 34, in main
    element=WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.XPATH,"//div[@class='ui-dialog-buttonset']/button[@class='ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only']/span[contains(.,'Continue')]")))
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/support/wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

pythonfiddle

code for the project so far, so you can skip the forum entry.

https://jsfiddle.net/93k5s2xg/1/

The working solution:

WebDriverWait(driver, 20).until(expected_conditions.element_to_be_clickable((By.XPATH, "//div[starts-with(@aria-describedby, 'ui-id-')]//span[@class='ui-button-text' and text()='Continue']"))).click()

Body:
This error message...

selenium.common.exceptions.ElementNotInteractableException: Message: Element <span class="ui-button-text"> could not be scrolled into view

...implies that the WebDriver instance i.e. driver was unable to scroll the element within the Viewport to invoke click().

First of all, as your usecase is to invoke click() on the element, ideally instead of using presence_of_element_located() you need to use the ExpectedConditions as element_to_be_clickable() as follows:

WebDriverWait(driver, 1000000).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[5]/div[3]/div/button/span'))).click()

You can find a couple of detailed discussions in:

Message: Element  could not be scrolled into view while trying to click on an option within a dropdown menu through Selenium

org.openqa.selenium.ElementNotInteractableException: Element  could not be scrolled into view when trying to click a button

As an alternative, as per the error message, to scroll an element within the Viewport before invoking click() you can also use the Element.scrollIntoView() method.

You can find a detailed discussion in:
- What is the difference between the different scroll options?

At this point it is worth to mention, the following methods:

move_to_element() from selenium.webdriver.common.action_chains

element_to_be_clickable() from selenium.webdriver.support.expected_conditions

will automatically scroll the element within the Viewport.

You can find a detailed discussion in:
- How to scroll a webpage using selenium webdriver in Python without using javascript method execute_script()

This usecase

The button with text as Continue is within the Top Level Content but rendered within a Modal Dialog Box.

DevTools Snapshot:

As the desired element is within a Modal Dialog Box, so to locate and invoke click() on the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use the following Locator Strategy:

Using XPATH:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[starts-with(@aria-describedby, 'ui-id-')]//span[@class='ui-button-text' and text()='Continue']"))).click()

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

DevTools Snapshot:


问:
Sum column based on another column in Pandas DataFrame
I have a pandas DataFrame like this:

```<code>>>> df = pd.DataFrame({'MONTREGL':[10,10,2222,35,200,56,5555],'SINID':['aaa','aaa','aaa','bbb','bbb','ccc','ccc'],'EXTRA':[400,400,400,500,500,333,333]})
>>> df
   MONTREGL SINID EXTRA
0        10   aaa   400
1        10   aaa   400
2      2222   aaa   400
3        35   bbb   500
4       200   bbb   500
5        56   ccc   333
6      5555   ccc   333
</code>```

I want to sum the column MONTREGL for each groupby SINID...

So I get 2242 for aaa and so on... ALSO I want to keep the value of column EXTRA.

This is the expected result:

```<code>   MONTREGL SINID EXTRA
0      2242   aaa   400
1       235   bbb   500
2      5611   ccc   333
</code>```

Thanks for your help in advance!

答:
my suggestion would be to filter you dataframe with conditions related to other columns then apply sum function,

it goes something like this.

import pandas as pd

df=pd.Dataframe({a:[1,2,3],b:[2001,2015,2019],c:[1,0,1]})

aux=df[df.c>0]

sa=aux.a.sum()

sb=aux.b.sum()

My syntax may not be correct ( i didnt run the code ) but it will probably work and lead you to your answer

Good luck.

Body:
I have a pandas DataFrame like this:

>>> df = pd.DataFrame({'MONTREGL':[10,10,2222,35,200,56,5555],'SINID':['aaa','aaa','aaa','bbb','bbb','ccc','ccc'],'EXTRA':[400,400,400,500,500,333,333]})
>>> df
   MONTREGL SINID EXTRA
0        10   aaa   400
1        10   aaa   400
2      2222   aaa   400
3        35   bbb   500
4       200   bbb   500
5        56   ccc   333
6      5555   ccc   333

I want to sum the column MONTREGL for each groupby SINID...

So I get 2242 for aaa and so on... ALSO I want to keep the value of column EXTRA.

This is the expected result:

   MONTREGL SINID EXTRA
0      2242   aaa   400
1       235   bbb   500
2      5611   ccc   333

Thanks for your help in advance!


问:
C# Check if Flags enum has only one value set
I have a Flags enum and want to assert that a given instance of it, is one of the primitive values, i.e. it has exactly one '1' in its binary representation, i.e. it's a power of two.

What's the best way to check this?

(I suppose "best" isn't necessarily well-defined, so ...)

What's the fastest way to check this?

What's the most semantically clear way to check this?

How do I check this, whilst writing the least code?

答:
Using Framework functionality and be more flexible concerning the number of set flags one could use something like:</p>

```<code>[Flags]
public enum FlagsEnum {
   None = 0,
   One = 1,
   Two = 2,
   Three = 4,
}

void Main()
{
    var flags = FlagsEnum.Two;
    var hasOneElement = Enum.GetValues(typeof(FlagsEnum)).OfType<FlagsEnum>().Where(i => i != FlagsEnum.None && flags.HasFlag(i)).Count() == 1;
}
</code>```

Body:
Using Framework functionality and be more flexible concerning the number of set flags one could use something like:

[Flags]
public enum FlagsEnum {
   None = 0,
   One = 1,
   Two = 2,
   Three = 4,
}

void Main()
{
    var flags = FlagsEnum.Two;
    var hasOneElement = Enum.GetValues(typeof(FlagsEnum)).OfType<FlagsEnum>().Where(i => i != FlagsEnum.None && flags.HasFlag(i)).Count() == 1;
}


问:
Java sending files through sockets
I want to send files as  well as some other information through sockets. I am using the following code

```<code> public void receiveFile(Socket socket,int filesize,String filename) throws IOException
{
    //after receiving file send ack
    System.out.println("waiting ");
 // int filesize=70; // filesize temporary hardcoded

long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
System.out.println("Connecting...");

// receive file
byte [] mybytearray  = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
System.out.println("recv..."+mybytearray.length);
do {
   bytesRead =
      is.read(mybytearray, current, (mybytearray.length-current));
   System.out.println(bytesRead);
   if(bytesRead > 0) current += bytesRead;
} while(bytesRead > 0);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
System.out.println(" File received");
}
</code>```

After receiving the file, I have to receive some other strings. But when I try to read the input stream, I am getting the contents of the file. How to flush the contents of the file from the inputstream.

```<code>BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(
                webServerSocket.getInputStream()));

receiveFile(webServerSocket,filesize,filename);
    while(true)
    {
        msg = inFromServer.readLine(); //here i receive the contents of the file again
     System.out.println(msg);
    }
</code>```

答: By reading the file to completion, you will have read the whole file. If you are still getting the contents of the file, you haven't read the whole file.</p>

ContentLicense: CC BY-SA 3.0

Title: Java sending files through sockets

Body:
I want to send files as  well as some other information through sockets. I am using the following code

 public void receiveFile(Socket socket,int filesize,String filename) throws IOException
{
    //after receiving file send ack
    System.out.println("waiting ");
 // int filesize=70; // filesize temporary hardcoded

long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
System.out.println("Connecting...");

// receive file
byte [] mybytearray  = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
System.out.println("recv..."+mybytearray.length);
do {
   bytesRead =
      is.read(mybytearray, current, (mybytearray.length-current));
   System.out.println(bytesRead);
   if(bytesRead > 0) current += bytesRead;
} while(bytesRead > 0);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
System.out.println(" File received");
}

After receiving the file, I have to receive some other strings. But when I try to read the input stream, I am getting the contents of the file. How to flush the contents of the file from the inputstream.

BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(
                webServerSocket.getInputStream()));

receiveFile(webServerSocket,filesize,filename);
    while(true)
    {
        msg = inFromServer.readLine(); //here i receive the contents of the file again
     System.out.println(msg);
    }


问:
Animate fragment from bottom up, over top previous fragment
I'd like to animate in a new fragment from the bottom up, over top of the previous fragment.

Unfortunately, my current implementation pushes the previous fragment up, as the new fragment is animating in, like this:

https://i.imgur.com/IgMUamp.png

What I would like it to do is have the new fragment animate over top the previous fragment, like so:

https://i.imgur.com/DTrEfcm.png

Here is what my code looks like now:

```<code>    private void pushFragment(String fragmentTag, Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.setCustomAnimations(R.anim.anim_in_test, R.anim.anim_out_test);
        fragmentTransaction.replace(
                R.id.fragment_container,
                fragment,
                fragmentTag);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commitAllowingStateLoss();
    }
</code>```

Here is anim_in_test.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator">
    <translate
        android:duration="@android:integer/config_longAnimTime"
        android:fromYDelta="100%p"
        android:toYDelta="0" />
</set>
</code>```

And here is anim_out_test.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_longAnimTime"
        android:fromYDelta="0%p"
        android:toYDelta="-100%p"
        />
</set>
</code>```

What do I need to change to get this working right?

答:
```<code> setCustomAnimations(int enter, int exit)
</code>```

Exit animation should be empty (because you need old fragment stay on screen while new one appears), but if you pass 0 to second param view dissapear without animation. Thats why I add empty alpha animation which changes alpha from 1 to 1.

```<code>fragmentTransaction.setCustomAnimations(R.anim.anim_in_test, R.anim.anim_out_test);
</code>```

anim_out_test.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha
        android:duration="@android:integer/config_longAnimTime"
        android:fromAlpha="1"
        android:toAlpha="1" />
</set>
</code>```

But at that point it doesnt' work because android draw and animate new fragment BELOW old fragment. You can see it if you make fragment backgrounds transparent.

To resolve this issue I use setZ(z), setElevation(z) or setTranslationZ(z) methods on root view of fragment. It looks like all of them are working. Z value of new fragment should be more than old fragment Z.

```<code> @Override
 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.view, container, false);
        view.setZ(value);
</code>```

Here is result:

It works but I dont know side effects of this solution. On android 4 I think it can be done via custom ViewGroup as fragment container, which draws children in reverse order.

Body:
I'd like to animate in a new fragment from the bottom up, over top of the previous fragment.

Unfortunately, my current implementation pushes the previous fragment up, as the new fragment is animating in, like this:

https://i.imgur.com/IgMUamp.png

What I would like it to do is have the new fragment animate over top the previous fragment, like so:

https://i.imgur.com/DTrEfcm.png

Here is what my code looks like now:

    private void pushFragment(String fragmentTag, Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.setCustomAnimations(R.anim.anim_in_test, R.anim.anim_out_test);
        fragmentTransaction.replace(
                R.id.fragment_container,
                fragment,
                fragmentTag);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commitAllowingStateLoss();
    }

Here is anim_in_test.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator">
    <translate
        android:duration="@android:integer/config_longAnimTime"
        android:fromYDelta="100%p"
        android:toYDelta="0" />
</set>

And here is anim_out_test.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_longAnimTime"
        android:fromYDelta="0%p"
        android:toYDelta="-100%p"
        />
</set>

What do I need to change to get this working right?

Body:
 setCustomAnimations(int enter, int exit)

Exit animation should be empty (because you need old fragment stay on screen while new one appears), but if you pass 0 to second param view dissapear without animation. Thats why I add empty alpha animation which changes alpha from 1 to 1.

fragmentTransaction.setCustomAnimations(R.anim.anim_in_test, R.anim.anim_out_test);

anim_out_test.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha
        android:duration="@android:integer/config_longAnimTime"
        android:fromAlpha="1"
        android:toAlpha="1" />
</set>

But at that point it doesnt' work because android draw and animate new fragment BELOW old fragment. You can see it if you make fragment backgrounds transparent.

To resolve this issue I use setZ(z), setElevation(z) or setTranslationZ(z) methods on root view of fragment. It looks like all of them are working. Z value of new fragment should be more than old fragment Z.

 @Override
 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.view, container, false);
        view.setZ(value);

Here is result:

It works but I dont know side effects of this solution. On android 4 I think it can be done via custom ViewGroup as fragment container, which draws children in reverse order.


问:
How to make, that the Rover drives to the left and stop
at the moment I'm using an L298 Motor Driver, an ultrasonic Sensor, and an ESP32. The goal is when the Ultrasonic Sensor(which is at the front of the Rover) detects an object, the Rover drives to the left and stops.
The problem is, that when the Sensor detects an object, the rover only stops without moving to the left. Otherwise, if I delete the Stop part of the code, my rover goes to the left. However, I do not know how I make, that he does both commands.

```<code>// defines Sensor pins

#define trigPin 12
#define echoPin 13

//Define Motor pins
#define motorIn3  16 //Input 3
#define motorIn1  17 //Input 1
#define motorIn4  18 //Input 4
#define motorIn2  19 //Input 2

// defines variables
long duration;
int distance;

// define ActivateDistance
double activateDistance = 20;

void setup()
{
  // Sets the trigPin as an Output
  pinMode(trigPin, OUTPUT);
  // Sets the echoPin as an Input
  pinMode(echoPin, INPUT);

  // sets the Motorpins  as outputs:
  pinMode(motorIn1, OUTPUT);
  pinMode(motorIn2, OUTPUT);
  pinMode(motorIn3, OUTPUT);
  pinMode(motorIn4, OUTPUT);

  Serial.begin(9600); // Starts the serial communication

}

void loop()
{

  //Moving Motor forward
  digitalWrite(motorIn2, HIGH);
  digitalWrite(motorIn4, HIGH);
  digitalWrite(motorIn3, LOW);
  digitalWrite(motorIn1, LOW);

  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

 // Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

 // Reads the echoPin, returns the sound wave travel time in microseconds
 duration = pulseIn(echoPin, HIGH);

 // Calculating the distance
 distance = duration * 0.034 / 2;

//when the distance is under 20, the motor should drives to the left and stopps.
 if (distance <= activateDistance)
 {
  //for loop using that the motor drives a specific amount to the left
  for(int i = 0; i<5;i++)
  {
 //Motor drives to left
  digitalWrite(motorIn1, LOW);
  digitalWrite(motorIn2, HIGH);
  digitalWrite(motorIn3, HIGH);
  digitalWrite(motorIn4, LOW);
//After drives to left, the motor should stop.
    if(i == 4)
    {
      //Moves forward
      digitalWrite(motorIn2, HIGH);
      digitalWrite(motorIn4, HIGH);
      digitalWrite(motorIn3, LOW);
      digitalWrite(motorIn1, LOW);
      delay(1000);
      //Motor Stops.
      digitalWrite(motorIn1, LOW);
      digitalWrite(motorIn2, LOW);
      digitalWrite(motorIn3, LOW);
      digitalWrite(motorIn4, LOW);
    }
  }

 }
  delay(1000);
}
</code>```

Sorry for my bad English.

答:
There is no delay at all after you instructed the Rover drives to the left, thus the four first times in the for(int i = 0; i<5;i++) will execute very quickly. Maybe add a delay there in order for the Rover to have time to complete the turn.

Also I do not understand why you put if(i == 4) and the following instruction at the end of the for loop: you can put it after the for loop and having exactly the same behaviour.

Hope it helps.

Body:
at the moment I'm using an L298 Motor Driver, an ultrasonic Sensor, and an ESP32. The goal is when the Ultrasonic Sensor(which is at the front of the Rover) detects an object, the Rover drives to the left and stops.
The problem is, that when the Sensor detects an object, the rover only stops without moving to the left. Otherwise, if I delete the Stop part of the code, my rover goes to the left. However, I do not know how I make, that he does both commands.

// defines Sensor pins

#define trigPin 12
#define echoPin 13

//Define Motor pins
#define motorIn3  16 //Input 3
#define motorIn1  17 //Input 1
#define motorIn4  18 //Input 4
#define motorIn2  19 //Input 2

// defines variables
long duration;
int distance;

// define ActivateDistance
double activateDistance = 20;

void setup()
{
  // Sets the trigPin as an Output
  pinMode(trigPin, OUTPUT);
  // Sets the echoPin as an Input
  pinMode(echoPin, INPUT);

  // sets the Motorpins  as outputs:
  pinMode(motorIn1, OUTPUT);
  pinMode(motorIn2, OUTPUT);
  pinMode(motorIn3, OUTPUT);
  pinMode(motorIn4, OUTPUT);

  Serial.begin(9600); // Starts the serial communication

}

void loop()
{

  //Moving Motor forward
  digitalWrite(motorIn2, HIGH);
  digitalWrite(motorIn4, HIGH);
  digitalWrite(motorIn3, LOW);
  digitalWrite(motorIn1, LOW);

  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

 // Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

 // Reads the echoPin, returns the sound wave travel time in microseconds
 duration = pulseIn(echoPin, HIGH);

 // Calculating the distance
 distance = duration * 0.034 / 2;

//when the distance is under 20, the motor should drives to the left and stopps.
 if (distance <= activateDistance)
 {
  //for loop using that the motor drives a specific amount to the left
  for(int i = 0; i<5;i++)
  {
 //Motor drives to left
  digitalWrite(motorIn1, LOW);
  digitalWrite(motorIn2, HIGH);
  digitalWrite(motorIn3, HIGH);
  digitalWrite(motorIn4, LOW);
//After drives to left, the motor should stop.
    if(i == 4)
    {
      //Moves forward
      digitalWrite(motorIn2, HIGH);
      digitalWrite(motorIn4, HIGH);
      digitalWrite(motorIn3, LOW);
      digitalWrite(motorIn1, LOW);
      delay(1000);
      //Motor Stops.
      digitalWrite(motorIn1, LOW);
      digitalWrite(motorIn2, LOW);
      digitalWrite(motorIn3, LOW);
      digitalWrite(motorIn4, LOW);
    }
  }

 }
  delay(1000);
}

Sorry for my bad English.


问:
Generating angular/typescript class that specifies allowed values for property
Imagine I'm making a simple model that describes (for instance) the details of a query:

```<code>export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: string;
}
</code>```

That sortDirection is much more vague than necessary.  After all, the API accepts either asc or desc, and no other string values are allowed.  Therefore it would be nice to specify that only those two values are allowed, but I'm not quite sure how I would specify such a property, and the typescript docs haven't helped.  In essence I want to do this:

```<code>export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: 'asc' | 'desc';
}
</code>```

Except of course the union operator works with types, not values.  I could conceptually try something like this:

```<code>export class asc {
   direction = 'asc';
}
export class desc {
   direction = 'desc';
}
export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: asc | desc;
}
</code>```

But even if that works the structure of my model has changed (the sort direction is now model.sortDirection.direction instead of model.sortDirection)

Is there an obvious option that I'm missing?

答:
You can define a "literal type" with union values.

export type SortDirection = 'asc' | 'desc';

and use it in your model:

```<code>export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: SortDirection;
}

</code>```

Body:
Imagine I'm making a simple model that describes (for instance) the details of a query:

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: string;
}

That sortDirection is much more vague than necessary.  After all, the API accepts either asc or desc, and no other string values are allowed.  Therefore it would be nice to specify that only those two values are allowed, but I'm not quite sure how I would specify such a property, and the typescript docs haven't helped.  In essence I want to do this:

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: 'asc' | 'desc';
}

Except of course the union operator works with types, not values.  I could conceptually try something like this:

export class asc {
   direction = 'asc';
}
export class desc {
   direction = 'desc';
}
export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: asc | desc;
}

But even if that works the structure of my model has changed (the sort direction is now model.sortDirection.direction instead of model.sortDirection)

Is there an obvious option that I'm missing?

Body:
You can define a "literal type" with union values.

export type SortDirection = 'asc' | 'desc';

and use it in your model:

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: SortDirection;
}


问:
Webhook call failed. Error: 500 Internal Server Error
https://dialogflow.com/docs/tutorial-build-an-agent/create-fulfillment-using-webhook

I want to try this example out

but after I follow the step on this page

It's give me

Webhook call failed. Error: 500 Internal Server Error

```<code>{
  "responseId": "a89123c6-42e5-45fa-ab2d-153a9d7e3692",
  "queryResult": {
    "queryText": "I need to make an appointment at 3 PM today.",
    "parameters": {
      "time": "",
      "date": ""
    },
    "allRequiredParamsPresent": true,
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            ""
          ]
        }
      }
    ],
    "intent": {
      "name": "projects/newagent-b231a/agent/intents/f6477cf2-cd73-4dc3-a8bd-614d45998754",
      "displayName": "Make Appointment"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {
      "webhook_latency_ms": 142
    },
    "languageCode": "zh-tw"
  },
  "webhookStatus": {
    "code": 13,
    "message": "Webhook call failed. Error: 500 Internal Server Error"
  }
}
</code>```

amd I check logs on firebase

how to fix it?

答:
I faced the similar error. After I updated the npm. It was resolved.

try npm install

Body:
https://dialogflow.com/docs/tutorial-build-an-agent/create-fulfillment-using-webhook

I want to try this example out

but after I follow the step on this page

It's give me

Webhook call failed. Error: 500 Internal Server Error

{
  "responseId": "a89123c6-42e5-45fa-ab2d-153a9d7e3692",
  "queryResult": {
    "queryText": "I need to make an appointment at 3 PM today.",
    "parameters": {
      "time": "",
      "date": ""
    },
    "allRequiredParamsPresent": true,
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            ""
          ]
        }
      }
    ],
    "intent": {
      "name": "projects/newagent-b231a/agent/intents/f6477cf2-cd73-4dc3-a8bd-614d45998754",
      "displayName": "Make Appointment"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {
      "webhook_latency_ms": 142
    },
    "languageCode": "zh-tw"
  },
  "webhookStatus": {
    "code": 13,
    "message": "Webhook call failed. Error: 500 Internal Server Error"
  }
}

amd I check logs on firebase

how to fix it?


问:
Pass model name to a viewcontroller
On the click of a button I load my tableview like so...

```<code>class MyViewController: UIViewController {

  @IBOutlet weak var tableview: UITableView!
  var tableConfig : TableViewConfig<Company, CompanyCell>?

  private var tabledata = [Company]() {
    didSet {
      tableConfig?.items = tabledata
    }
  }

  // MARK: - View Life Cycle
  override func viewDidLoad() {
    super.viewDidLoad()
    configureTableView()
  }

  private func configureTableView() {
    let cellIdentifier = String(describing: CompanyCell.self)
    tableview.register(UINib(nibName: cellIdentifier, bundle: Bundle.main), forCellReuseIdentifier: cellIdentifier)

    tableConfig = TableViewConfig<Company, CompanyCell>(tableview, items: tabledata, cellIdentifier: cellIdentifier, configClosure: { object, cell in
      cell.configureCompany(object)
    })

    tableConfig?.selectedRow { indexPath in
      // Call Delegate Action
      if let index = indexPath?.row {
        let company = self.tabledata[index]
        self.tabledata[index] = company
        self.tableConfig?.items = self.tabledata
        self.tableview.reloadRows(at: [indexPath!], with: .automatic)
      }
    }
    tableview.dataSource = tableConfig
    tableview.delegate = tableConfig
  }
}
</code>```

Here, in this line...var tableConfig : TableViewConfig<Company, CompanyCell>?, the Company and CompanyCell are names of the model and UITableViewCell respectively.

What I want is that on the click of the button, while loading MyViewController (i.e. the viewcontroller given above), I want to pass the model name and the tableviewcell name. But how to pass the model name from one viewcontroller to the other, I can't figure out.

I have tried this, this and this link. But it didn't help.

Hope somebody can help...

答:
I'm not sure if I've understood your question. Maybe what you're trying to achieve is something like this:</p>

```<code>class MyViewController<Company, CompanyCell>: UIViewController
{
    ...
}

let myViewController = MyViewController<MyCompany, MyCompanyCell>()
</code>```

Title: Pass model name to a viewcontroller

Body:
On the click of a button I load my tableview like so...

class MyViewController: UIViewController {

  @IBOutlet weak var tableview: UITableView!
  var tableConfig : TableViewConfig<Company, CompanyCell>?

  private var tabledata = [Company]() {
    didSet {
      tableConfig?.items = tabledata
    }
  }

  // MARK: - View Life Cycle
  override func viewDidLoad() {
    super.viewDidLoad()
    configureTableView()
  }

  private func configureTableView() {
    let cellIdentifier = String(describing: CompanyCell.self)
    tableview.register(UINib(nibName: cellIdentifier, bundle: Bundle.main), forCellReuseIdentifier: cellIdentifier)

    tableConfig = TableViewConfig<Company, CompanyCell>(tableview, items: tabledata, cellIdentifier: cellIdentifier, configClosure: { object, cell in
      cell.configureCompany(object)
    })

    tableConfig?.selectedRow { indexPath in
      // Call Delegate Action
      if let index = indexPath?.row {
        let company = self.tabledata[index]
        self.tabledata[index] = company
        self.tableConfig?.items = self.tabledata
        self.tableview.reloadRows(at: [indexPath!], with: .automatic)
      }
    }
    tableview.dataSource = tableConfig
    tableview.delegate = tableConfig
  }
}

Here, in this line...var tableConfig : TableViewConfig<Company, CompanyCell>?, the Company and CompanyCell are names of the model and UITableViewCell respectively.

What I want is that on the click of the button, while loading MyViewController (i.e. the viewcontroller given above), I want to pass the model name and the tableviewcell name. But how to pass the model name from one viewcontroller to the other, I can't figure out.

I have tried this, this and this link. But it didn't help.

Hope somebody can help...

Body:
I'm not sure if I've understood your question. Maybe what you're trying to achieve is something like this:

class MyViewController<Company, CompanyCell>: UIViewController
{
    ...
}

let myViewController = MyViewController<MyCompany, MyCompanyCell>()


问:
Starting Jetty returns: ERROR : Nothing to start, exiting
I want to serve a directory so I could open an html webpage. My structure is as follows:

```<code>C:\
¦
¦-- myProj\
    ¦
    ¦index.html
    ¦
    ¦jar\
      ¦
     jetty-distribution-9.4.18.v20190429\
      ¦
      ¦(some jetty folders...)
      ¦(some jetty files...)
      ¦start.jar
</code>```

and inside the folder C:\myProj\jar\jetty-distribution-9.4.18.v20190429  I have unzipped jetty-distribution-9.4.18.v20190429.zip which I downloaded from Eclipse Jetty Downloads.

I then cd C:\myProj and try to start the server with the following

```<code>java -jar ./jar/jetty-distribution-9.4.18.v20190429/start.jar
</code>```

However I receive the following msg

```<code>    C:\myProj>java -jar ./jar/jetty-distribution-9.4.18.v20190429/start.jar
ERROR : Nothing to start, exiting ...

Usage: java -jar $JETTY_HOME/start.jar [options] [properties] [configs]
       java -jar $JETTY_HOME/start.jar --help  # for more information
</code>```

What am I doing wrong please? According to this example near the bottom of the page in the documentation
it should work

"The following demonstrates this by allowing default discovery of ${jetty.home} via locating the start.jar, and using the user.dir System Property for ${jetty.base}."

```<code>[jetty-distribution-9.4.18.v20190429]$ pwd
/home/user/jetty-distribution-9.4.18.v20190429

[jetty-distribution-9.4.18.v20190429]$ cd /home/user/my-base
[my-base]$ java -jar /home/user/jetty-distribution-9.4.18.v20190429/start.jar

2013-10-16 09:08:47.802:INFO:oejs.Server:main: jetty-9.4.18.v20190429
2013-10-16 09:08:47.817:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/home/user/my-base/webapps/] at interval 1
</code>```

Obviously I must be missing something here....

答:
The start.jar in the ${jetty.home} directory (in your case that directory is /home/user/jetty-distribution-9.4.18.v20190429/) is for starting a configured instance of Jetty.

Note: you can also use the newer jetty-home-<ver>.tar.gz artifact
  instead of the older jetty-distribution artifact.

What does that mean?

Well, it means ...

You have a ${jetty.base} directory somewhere

The ${jetty.base} directory doesn't overlap with the ${jetty.home} directory (and vice-versa)

The ${jetty.base} directory has its configuration in *.ini files.

First it looks for ${jetty.base}/start.ini

Then it looks for ${jetty.base}/start.d/*.ini

Each line in the various *.ini files are just command line options for start.jar

You can see this configuration by using the --list-config option.

example:

```<code>[~]$ cd /home/user/my-base
[my-base]$ java -jar /home/user/jetty-distribution-9.4.18.v20190429/start.jar --list-config
</code>```

Body:
I want to serve a directory so I could open an html webpage. My structure is as follows:

C:\
¦
¦-- myProj\
    ¦
    ¦index.html
    ¦
    ¦jar\
      ¦
     jetty-distribution-9.4.18.v20190429\
      ¦
      ¦(some jetty folders...)
      ¦(some jetty files...)
      ¦start.jar

and inside the folder C:\myProj\jar\jetty-distribution-9.4.18.v20190429  I have unzipped jetty-distribution-9.4.18.v20190429.zip which I downloaded from Eclipse Jetty Downloads.

I then cd C:\myProj and try to start the server with the following

java -jar ./jar/jetty-distribution-9.4.18.v20190429/start.jar

However I receive the following msg

    C:\myProj>java -jar ./jar/jetty-distribution-9.4.18.v20190429/start.jar
ERROR : Nothing to start, exiting ...

Usage: java -jar $JETTY_HOME/start.jar [options] [properties] [configs]
       java -jar $JETTY_HOME/start.jar --help  # for more information

What am I doing wrong please? According to this example near the bottom of the page in the documentation
it should work

"The following demonstrates this by allowing default discovery of ${jetty.home} via locating the start.jar, and using the user.dir System Property for ${jetty.base}."

[jetty-distribution-9.4.18.v20190429]$ pwd
/home/user/jetty-distribution-9.4.18.v20190429

[jetty-distribution-9.4.18.v20190429]$ cd /home/user/my-base
[my-base]$ java -jar /home/user/jetty-distribution-9.4.18.v20190429/start.jar

2013-10-16 09:08:47.802:INFO:oejs.Server:main: jetty-9.4.18.v20190429
2013-10-16 09:08:47.817:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/home/user/my-base/webapps/] at interval 1

Obviously I must be missing something here....

Body:
The start.jar in the ${jetty.home} directory (in your case that directory is /home/user/jetty-distribution-9.4.18.v20190429/) is for starting a configured instance of Jetty.

Note: you can also use the newer jetty-home-<ver>.tar.gz artifact
  instead of the older jetty-distribution artifact.

What does that mean?

Well, it means ...

You have a ${jetty.base} directory somewhere

The ${jetty.base} directory doesn't overlap with the ${jetty.home} directory (and vice-versa)

The ${jetty.base} directory has its configuration in *.ini files.

First it looks for ${jetty.base}/start.ini

Then it looks for ${jetty.base}/start.d/*.ini

Each line in the various *.ini files are just command line options for start.jar

You can see this configuration by using the --list-config option.

example:

[~]$ cd /home/user/my-base
[my-base]$ java -jar /home/user/jetty-distribution-9.4.18.v20190429/start.jar --list-config


问:
mkdir command doesn't work using exec() in PHP
This is strange. Although basic commands such as ls, date, whoami are working. I cant seem to make a directory using the mkdir command using exec

```<code>$output=exec("mkdir helloworld");
</code>```

Also it is worth asking, if such an error is occurring. is there any parameter or i can use to capture this error. Like the example below?

```<code>exec("mkdir helloworld 2>&1",$output,$return_val)
if($return_val !== 0)
echo "there was an error"
</code>```

答:
this is most probably due to missing file priviliges of the user that is executing the code (the apache-user in many cases).
If you add " 2>&1" to your command, you can also see the error output in $output</p>

Body:
This is strange. Although basic commands such as ls, date, whoami are working. I cant seem to make a directory using the mkdir command using exec

$output=exec("mkdir helloworld");

Also it is worth asking, if such an error is occurring. is there any parameter or i can use to capture this error. Like the example below?

exec("mkdir helloworld 2>&1",$output,$return_val)
if($return_val !== 0)
echo "there was an error"


问:
How can I horizontally center an element?
How can I horizontally center a
 within another
 using CSS?

Foo foo

```

答:
```<code>#inner {
  width: 50%;
  margin: 0 auto;
}
</code>```

OwnerDisplayName: Lukas

Body:
#inner {
  width: 50%;
  margin: 0 auto;
}


问:
Can anyone suggest me any tools using which I can schedule my UI testing, so that it automatically starts testing at a given interval of time
I want to write a scheduler inside my java code that schedules my UI test cases and it automatically starts testing at the given time. Suggestion needed for plugins or tools.</p>

答:
There are different options, depending on what you're trying to achieve.

If you want to schedule the next execution purely from Java - consider Quartz Job Scheduling Library

Alternatively you can use underlying operating system task scheduling mechanisms, to wit:

Windows: Task Scheduler

Linux: crontab

MacOS: launchd

And last but not the least, you can put your tests under CI tool orchestration like:

Jenkins

Buildbot

CruiseControl


问:
Test Hibernate + Spring from public static void main
I'm Spring and Hibernate newbie.
I've created the entity User and DAO - UserHibernateDao.
I want to test how the hibernate working in simple java-class with public static void main:

```<code>public class Starter {

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("/org/jtalks/jcommune/model/entity/applicationContext-dao.xml");
    Dao<User> uhd = (Dao) context.getBean("userDao");
    User user = new User();
    user.setNickName("UserName");
    uhd.saveOrUpdate(user);
}
</code>```

}

but I get the error

INFO: Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@17b4703] of Hibernate SessionFactory for HibernateTransactionManager
Exception in thread "main" org.springframework.orm.hibernate3.HibernateSystemException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:679)

I understand I need to create something like session and transaction but I don't know how exactly I should do this.

my config
User.java
UserHibernateDao.java
Full Project

Thanks

答:
Add the @Transactional annotation to your DAO's method.

That will initiate the transactional context.

```<code>import org.springframework.transaction.annotation.Transactional;

@Transactional
public User getUser(int id) {
..
}
</code>```

Body:
I'm Spring and Hibernate newbie.
I've created the entity User and DAO - UserHibernateDao.
I want to test how the hibernate working in simple java-class with public static void main:

public class Starter {

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("/org/jtalks/jcommune/model/entity/applicationContext-dao.xml");
    Dao<User> uhd = (Dao) context.getBean("userDao");
    User user = new User();
    user.setNickName("UserName");
    uhd.saveOrUpdate(user);
}

}

but I get the error

INFO: Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@17b4703] of Hibernate SessionFactory for HibernateTransactionManager
Exception in thread "main" org.springframework.orm.hibernate3.HibernateSystemException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:679)

I understand I need to create something like session and transaction but I don't know how exactly I should do this.

my config
User.java
UserHibernateDao.java
Full Project

Thanks

Body:
Add the @Transactional annotation to your DAO's method.

That will initiate the transactional context.

import org.springframework.transaction.annotation.Transactional;

@Transactional
public User getUser(int id) {
..
}


问:
Accessing children in auxiliary routing : Angular
I have root routing defined as

const routes: Routes = [{
    path: '',
    component: HomeComponent
  },
  {
    path: 'module1',
    loadChildren: './module1/module1.module#Module1Module'
  },
  {
    path: '**',
    redirectTo: ''
  }
];```
</div>
</div>
</p>

<p>the <code>module1.routing.ts</code> has:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const routes: Routes = [{
  path: '',
  component: SubModule1Component,
  children: [{
      path: 'mod1child1',
      component: SubMod1Child1Component
    },
    {
      path: 'mod1child2',
      component: SubMod1Child2Component,
      children: [{
          path: '',
          component: Outlet1Component,
          outlet: 'outlet1'
        },
        {
          path: 'newout1',
          component: Outlet1NewComponent,
          outlet: 'outlet1'
        },
        {
          path: '',
          component: Outlet2Component,
          outlet: 'outlet2',
          children: [{
            path: 'childoutlet2',
            component: ChildOutlet2Component,
            outlet: 'outlet2'
          }],
        },
      ],
    },
  ],
  canActivate: [AuthGuardService],
}, ];</code>```

This code works when I navigate to /module1/mod1child2 as below:

My HTML page for above image is:

Child 2

<button [routerLink]="[{outlets: {'outlet1': ['newout1']}}]">Change Outlet 1</button>
<button [routerLink]="[{outlets: {'outlet2': ['childoutlet2']}}]">Change Outlet 2</button>

    <router-outlet name="outlet1"></router-outlet>

    <router-outlet name="outlet2"></router-outlet>

```
</div>
</div>
</p>

<p><strong>I am unable to load</strong></p>

<p><code>{ path: 'childoutlet2', component: ChildOutlet2Component , outlet: 'outlet2'}</code></p>

<p>by clicking on :</p>

<p><code><button [routerLink]="[{outlets: {'outlet2': ['childoutlet2']}}]">Change Outlet 2</button></code></p>

<p>What am I doing wrong. I tried </p>

```<button [routerLink]="['/module1/mod1child2',{outlets: {'outlet2': ['childoutlet2']}}]">
   Change Outlet 2
 </button>`
```

but this doesn't seem to work as well

答:
Unfortunately, it is a know issue when using loadChildren for lazy loading. But it is easily fixable, you just need to provide always a name to your default route for every new route you define. In this case

```<code>{
    path: 'base',
    component: SubModule1Component,
    children: [
    ...
    ]
}

</code>```

Body:
I have root routing defined as

const routes: Routes = [{
    path: '',
    component: HomeComponent
  },
  {
    path: 'module1',
    loadChildren: './module1/module1.module#Module1Module'
  },
  {
    path: '**',
    redirectTo: ''
  }
];

the module1.routing.ts has:

const routes: Routes = [{
  path: '',
  component: SubModule1Component,
  children: [{
      path: 'mod1child1',
      component: SubMod1Child1Component
    },
    {
      path: 'mod1child2',
      component: SubMod1Child2Component,
      children: [{
          path: '',
          component: Outlet1Component,
          outlet: 'outlet1'
        },
        {
          path: 'newout1',
          component: Outlet1NewComponent,
          outlet: 'outlet1'
        },
        {
          path: '',
          component: Outlet2Component,
          outlet: 'outlet2',
          children: [{
            path: 'childoutlet2',
            component: ChildOutlet2Component,
            outlet: 'outlet2'
          }],
        },
      ],
    },
  ],
  canActivate: [AuthGuardService],
}, ];

This code works when I navigate to /module1/mod1child2 as below:

My HTML page for above image is:

Child 2

<button [routerLink]="[{outlets: {'outlet1': ['newout1']}}]">Change Outlet 1</button>
<button [routerLink]="[{outlets: {'outlet2': ['childoutlet2']}}]">Change Outlet 2</button>

    <router-outlet name="outlet1"></router-outlet>

    <router-outlet name="outlet2"></router-outlet>

I am unable to load

{ path: 'childoutlet2', component: ChildOutlet2Component , outlet: 'outlet2'}

by clicking on :

<button [routerLink]="[{outlets: {'outlet2': ['childoutlet2']}}]">Change Outlet 2</button>

What am I doing wrong. I tried

<button [routerLink]="['/module1/mod1child2',{outlets: {'outlet2': ['childoutlet2']}}]">
   Change Outlet 2
 </button>`

but this doesn't seem to work as well

Body:
Unfortunately, it is a know issue when using loadChildren for lazy loading. But it is easily fixable, you just need to provide always a name to your default route for every new route you define. In this case

{
    path: 'base',
    component: SubModule1Component,
    children: [
    ...
    ]
}


问:
ArcGIS, move map to point using ArcGIS API for JavaScript
I'm new on ArcGis (and also Angular, I start today developing in both), can't find an example on how to move the map to certain point, I was trying:

```<code>this.mapa.map.centerAt(new Point(-118.15, 33.80));
</code>```

But I have a javascript error TocComponent.html:10 ERROR ReferenceError: Point is not defined

When I do console.log(this.mapa.map); I got this (I put this in case someone is wondering if this.mapa.map was incorrect):

EDIT: My solution, same as the answer. It not all, it's a demo of my app with Angular:

```<code>import { MapaComponent } from '../mapa/mapa.component';

// some code

export class MyComponent implements OnInit {

    constructor(private arcgisService: ArcgisApiService, private mapa: MapaComponent) { }

    // another code

    onChangeSomething(evt: any): void {
        // more code
        loadModules([
            'esri/geometry/Point'
        ]).then(([Point]) => {
            const my_center = new Point([-99.94867549215655, 20.55088183550196]);
            this.mapa.map.centerAndZoom(my_center, 5);
        });
</code>```

答:
You may not be including the Point module in your AMD includes at the top of your file. Your list should include esri/geometry/Point like this:

```<code>require([
  "esri/map",
  "esri/layers/FeatureLayer",
  "esri/geometry/Point",
], function(Map, FeatureLayer, Point) {

    [... the rest of your code ...]

});
</code>```

Body:
I'm new on ArcGis (and also Angular, I start today developing in both), can't find an example on how to move the map to certain point, I was trying:

this.mapa.map.centerAt(new Point(-118.15, 33.80));

But I have a javascript error TocComponent.html:10 ERROR ReferenceError: Point is not defined

When I do console.log(this.mapa.map); I got this (I put this in case someone is wondering if this.mapa.map was incorrect):

EDIT: My solution, same as the answer. It not all, it's a demo of my app with Angular:

import { MapaComponent } from '../mapa/mapa.component';

// some code

export class MyComponent implements OnInit {

    constructor(private arcgisService: ArcgisApiService, private mapa: MapaComponent) { }

    // another code

    onChangeSomething(evt: any): void {
        // more code
        loadModules([
            'esri/geometry/Point'
        ]).then(([Point]) => {
            const my_center = new Point([-99.94867549215655, 20.55088183550196]);
            this.mapa.map.centerAndZoom(my_center, 5);
        });

Body:
You may not be including the Point module in your AMD includes at the top of your file. Your list should include esri/geometry/Point like this:

require([
  "esri/map",
  "esri/layers/FeatureLayer",
  "esri/geometry/Point",
], function(Map, FeatureLayer, Point) {

    [... the rest of your code ...]

});


问:
How can I give input files for cuda parallel programming?
I have to implement vector dot product in CUDA parallel programming model to make use of GPUs for computing. I will test my code by input files, which has two vectors to be multiplied. How can I give input files in cuda parallel programming for this implementation?</p>

答:
CUDA is an extension of C/C++. There is no special way to provide input to CUDA ( It does not even make sense said this way).

You first need to read the files like you would normally do in C/C++ and then use CUDA API to transfer the data to the GPU using cudaMemCpy for instance. Once you are finished with it you can transfer it back to the CPU side.


问:
X (java:sdk) should not link to Y (java:platform)
I am an android firmware developer. I work with source of android 9. I've written a custom network location provider for AOSP firmware, named offline location service. I've added this application to packages/apps/offlinelocatonservice path in AOSP build tree.

I've created an Android.mk file for it to include it in default packages in android OS.

```<code>LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_PACKAGE_NAME := OfflineLocationService

LOCAL_SDK_VERSION := current

LOCAL_SRC_FILES := $(call all-java-files-under, src)

LOCAL_CERTIFICATE := platform

LOCAL_USE_AAPT2 := true

# Include libraries

LOCAL_JAVA_LIBRARIES := framework com.android.location.provider

LOCAL_STATIC_JAVA_LIBRARIES := android-common

LOCAL_STATIC_ANDROID_LIBRARIES := \
    android-support-v4 \
    android-support-v7-appcompat \
    android-support-design \
    android-support-v7-preference \
    android-support-v7-recyclerview \

LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res

LOCAL_AAPT_FLAGS := --auto-add-overlay

LOCAL_AAPT_FLAGS += --extra-packages android.support.v7.appcompat

LOCAL_AAPT_FLAGS += --extra-packages android.support.design

include $(BUILD_PACKAGE)
</code>```

But when I build AOSP, I encounter with this error:

```<code>packages/apps/OfflineLocationService/Android.mk: error: OfflineLocationService (java:sdk) should not link to com.android.location.provider (java:platform)
packages/apps/OfflineLocationService/Android.mk: error: OfflineLocationService (java:sdk) should not link to framework (java:platform)
</code>```

Why I should not link to com.android.location.provider and framework?
In previous androids such as android 8 and earlier, this error doesn't happen.

How can I solve this error?

答:
From Android documentation:

Starting in Android 9 (API level 28), the platform restricts which non-SDK interfaces your app can use.

Ideally, you should rewrite your app to only use the Android public SDK.

You can read more information on this page: https://developer.android.com/distribute/best-practices/develop/restrictions-non-sdk-interfaces

Body:
I am an android firmware developer. I work with source of android 9. I've written a custom network location provider for AOSP firmware, named offline location service. I've added this application to packages/apps/offlinelocatonservice path in AOSP build tree.

I've created an Android.mk file for it to include it in default packages in android OS.

LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_PACKAGE_NAME := OfflineLocationService

LOCAL_SDK_VERSION := current

LOCAL_SRC_FILES := $(call all-java-files-under, src)

LOCAL_CERTIFICATE := platform

LOCAL_USE_AAPT2 := true

# Include libraries

LOCAL_JAVA_LIBRARIES := framework com.android.location.provider

LOCAL_STATIC_JAVA_LIBRARIES := android-common

LOCAL_STATIC_ANDROID_LIBRARIES := \
    android-support-v4 \
    android-support-v7-appcompat \
    android-support-design \
    android-support-v7-preference \
    android-support-v7-recyclerview \

LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res

LOCAL_AAPT_FLAGS := --auto-add-overlay

LOCAL_AAPT_FLAGS += --extra-packages android.support.v7.appcompat

LOCAL_AAPT_FLAGS += --extra-packages android.support.design

include $(BUILD_PACKAGE)

But when I build AOSP, I encounter with this error:

packages/apps/OfflineLocationService/Android.mk: error: OfflineLocationService (java:sdk) should not link to com.android.location.provider (java:platform)
packages/apps/OfflineLocationService/Android.mk: error: OfflineLocationService (java:sdk) should not link to framework (java:platform)

Why I should not link to com.android.location.provider and framework?
In previous androids such as android 8 and earlier, this error doesn't happen.

How can I solve this error?


问:
selenium error(while taking a screenshot) 'NoneType' object has no attribute 'encode'
I am using selenium on Google Cloud Platform and geckodriver to take a screenshot of a page but
my selenium throws an error like this...

```<code>get_screenshot_as_png

return base64.b64decode(self.get_screenshot_as_base64().encode('ascii'))

AttributeError: 'NoneType' object has no attribute 'encode'
</code>```

I am using firefox 68.xx and geckodriver 78(I am not sure tho)

```<code>cap = DesiredCapabilities().FIREFOX
cap['marionette'] = True
#cap['binary'] = '/usr/local/bin/firefox'

options = Options()
#options.headless = True
options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
options.add_argument("--disable-dev-shm-usage")

date_time  = datetime.datetime.now()
page_time = datetime.timedelta(hours = +9)
print(page_time+date_time)
page_time = page_time + date_time
page_time = page_time.strftime('%Y.%m.%d')

driver.save_screenshot(page_time+"screen.png")
</code>```

Thank you for your help in advance!

答:
Ok, so this issue is because you are using . to separate the date.

Try changing it to -:

```<code>page_time.strftime('%Y-%m-%d')
</code>```

Hope this helps you!

Body:
I am using selenium on Google Cloud Platform and geckodriver to take a screenshot of a page but
my selenium throws an error like this...

get_screenshot_as_png

return base64.b64decode(self.get_screenshot_as_base64().encode('ascii'))

AttributeError: 'NoneType' object has no attribute 'encode'

I am using firefox 68.xx and geckodriver 78(I am not sure tho)

cap = DesiredCapabilities().FIREFOX
cap['marionette'] = True
#cap['binary'] = '/usr/local/bin/firefox'

options = Options()
#options.headless = True
options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
options.add_argument("--disable-dev-shm-usage")

date_time  = datetime.datetime.now()
page_time = datetime.timedelta(hours = +9)
print(page_time+date_time)
page_time = page_time + date_time
page_time = page_time.strftime('%Y.%m.%d')

driver.save_screenshot(page_time+"screen.png")

Thank you for your help in advance!

Body:
Ok, so this issue is because you are using . to separate the date.

Try changing it to -:

page_time.strftime('%Y-%m-%d')

Hope this helps you!


问:
Spark - Creating Nested DataFrame
I'm starting with PySpark and I'm having troubles with creating DataFrames with nested objects.

This is my example.

I have users.

```<code>$ cat user.json
{"id":1,"name":"UserA"}
{"id":2,"name":"UserB"}
</code>```

Users have orders.

```<code>$ cat order.json
{"id":1,"price":202.30,"userid":1}
{"id":2,"price":343.99,"userid":1}
{"id":3,"price":399.99,"userid":2}
</code>```

And I like to join it to get such a struct where orders are array nested in users.

```<code>$ cat join.json
{"id":1, "name":"UserA", "orders":[{"id":1,"price":202.30,"userid":1},{"id":2,"price":343.99,"userid":1}]}
{"id":2,"name":"UserB","orders":[{"id":3,"price":399.99,"userid":2}]}
</code>```

How can I do that ?
Is there any kind of nested join or something similar ?

```<code>>>> user = sqlContext.read.json("user.json")
>>> user.printSchema();
root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)

>>> order =  sqlContext.read.json("order.json")
>>> order.printSchema();
root
 |-- id: long (nullable = true)
 |-- price: double (nullable = true)
 |-- userid: long (nullable = true)

>>> joined = sqlContext.read.json("join.json")
>>> joined.printSchema();
root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- orders: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id: long (nullable = true)
 |    |    |-- price: double (nullable = true)
 |    |    |-- userid: long (nullable = true)
</code>```

EDIT:
I know there is possibility to do this using join and foldByKey, but is there any simpler way ?

EDIT2:
I'm using solution by @zero323

```<code>def joinTable(tableLeft, tableRight, columnLeft, columnRight, columnNested, joinType = "left_outer"):
    tmpTable = sqlCtx.createDataFrame(tableRight.rdd.groupBy(lambda r: r.asDict()[columnRight]))
    tmpTable = tmpTable.select(tmpTable._1.alias("joinColumn"), tmpTable._2.data.alias(columnNested))
    return tableLeft.join(tmpTable, tableLeft[columnLeft] == tmpTable["joinColumn"], joinType).drop("joinColumn")
</code>```

I add second nested structure 'lines'

```<code>>>> lines =  sqlContext.read.json(path + "lines.json")
>>> lines.printSchema();
root
 |-- id: long (nullable = true)
 |-- orderid: long (nullable = true)
 |-- product: string (nullable = true)

orders = joinTable(order, lines, "id", "orderid", "lines")
joined = joinTable(user, orders, "id", "userid", "orders")
joined.printSchema()

root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- orders: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id: long (nullable = true)
 |    |    |-- price: double (nullable = true)
 |    |    |-- userid: long (nullable = true)
 |    |    |-- lines: array (nullable = true)
 |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |-- _1: long (nullable = true)
 |    |    |    |    |-- _2: long (nullable = true)
 |    |    |    |    |-- _3: string (nullable = true)
</code>```

After this column names from lines are lost.
Any ideas ?

EDIT 3:
I tried to manual specify schema.

```<code>from pyspark.sql.types import *
fields = []
fields.append(StructField("_1", LongType(), True))
inner = ArrayType(lines.schema)
fields.append(StructField("_2", inner))
new_schema = StructType(fields)
print new_schema

grouped =  lines.rdd.groupBy(lambda r: r.orderid)
grouped =  grouped.map(lambda x: (x[0], list(x[1])))
g = sqlCtx.createDataFrame(grouped, new_schema)
</code>```

Error:

```<code>TypeError: StructType(List(StructField(id,LongType,true),StructField(orderid,LongType,true),StructField(product,StringType,true))) can not accept object in type <class 'pyspark.sql.types.Row'>
</code>```

答:
For flatining your data frame from nested to normal use

dff= df.select("column with multiple columns.*")

Title: Spark - Creating Nested DataFrame

Body:
I'm starting with PySpark and I'm having troubles with creating DataFrames with nested objects.

This is my example.

I have users.

$ cat user.json
{"id":1,"name":"UserA"}
{"id":2,"name":"UserB"}

Users have orders.

$ cat order.json
{"id":1,"price":202.30,"userid":1}
{"id":2,"price":343.99,"userid":1}
{"id":3,"price":399.99,"userid":2}

And I like to join it to get such a struct where orders are array nested in users.

$ cat join.json
{"id":1, "name":"UserA", "orders":[{"id":1,"price":202.30,"userid":1},{"id":2,"price":343.99,"userid":1}]}
{"id":2,"name":"UserB","orders":[{"id":3,"price":399.99,"userid":2}]}

How can I do that ?
Is there any kind of nested join or something similar ?

>>> user = sqlContext.read.json("user.json")
>>> user.printSchema();
root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)

>>> order =  sqlContext.read.json("order.json")
>>> order.printSchema();
root
 |-- id: long (nullable = true)
 |-- price: double (nullable = true)
 |-- userid: long (nullable = true)

>>> joined = sqlContext.read.json("join.json")
>>> joined.printSchema();
root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- orders: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id: long (nullable = true)
 |    |    |-- price: double (nullable = true)
 |    |    |-- userid: long (nullable = true)

EDIT:
I know there is possibility to do this using join and foldByKey, but is there any simpler way ?

EDIT2:
I'm using solution by @zero323

def joinTable(tableLeft, tableRight, columnLeft, columnRight, columnNested, joinType = "left_outer"):
    tmpTable = sqlCtx.createDataFrame(tableRight.rdd.groupBy(lambda r: r.asDict()[columnRight]))
    tmpTable = tmpTable.select(tmpTable._1.alias("joinColumn"), tmpTable._2.data.alias(columnNested))
    return tableLeft.join(tmpTable, tableLeft[columnLeft] == tmpTable["joinColumn"], joinType).drop("joinColumn")

I add second nested structure 'lines'

>>> lines =  sqlContext.read.json(path + "lines.json")
>>> lines.printSchema();
root
 |-- id: long (nullable = true)
 |-- orderid: long (nullable = true)
 |-- product: string (nullable = true)

orders = joinTable(order, lines, "id", "orderid", "lines")
joined = joinTable(user, orders, "id", "userid", "orders")
joined.printSchema()

root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- orders: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id: long (nullable = true)
 |    |    |-- price: double (nullable = true)
 |    |    |-- userid: long (nullable = true)
 |    |    |-- lines: array (nullable = true)
 |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |-- _1: long (nullable = true)
 |    |    |    |    |-- _2: long (nullable = true)
 |    |    |    |    |-- _3: string (nullable = true)

After this column names from lines are lost.
Any ideas ?

EDIT 3:
I tried to manual specify schema.

from pyspark.sql.types import *
fields = []
fields.append(StructField("_1", LongType(), True))
inner = ArrayType(lines.schema)
fields.append(StructField("_2", inner))
new_schema = StructType(fields)
print new_schema

grouped =  lines.rdd.groupBy(lambda r: r.orderid)
grouped =  grouped.map(lambda x: (x[0], list(x[1])))
g = sqlCtx.createDataFrame(grouped, new_schema)

Error:

TypeError: StructType(List(StructField(id,LongType,true),StructField(orderid,LongType,true),StructField(product,StringType,true))) can not accept object in type <class 'pyspark.sql.types.Row'>