问:
How to construct a person class that allows tracking of property values over time
I'd like to construct a person class that has a property which the value may change over time but I want to keep the history of values. A person grows taller over time and their weight may change.  You may imagine a "HockeyPlayer: Person" that plays over many seasons.  Each season their height/weight may be different.  I would then use EntityFramework to create tables.  I think the main question I have is where do I put those properties? In their own class? In HockeyPlayer?  In Person?  Thank you in advance

pseudocode example:

```<code>public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public System.DateTime DateOfBirth { get; set; }
}

public class Season
{
    public int Id { get; set; }
    public string season { get; set; }
}

public class HockeyPlayer : Person
{
    public int PersonId {get; set; }
    public int SeasonId { get; set; }
    public int JerseyNumber { get; set; }
    public int HeightInches { get; set; }
    public int WeightPounds { get; set; }
}
</code>```

答:
I'm not sure your domain model here really models what you are looking for.  Don't think of your player playing in a season as a player.  A player participates in a season and gets a record for season specific information.  So a player has a history of seasons played. a player is NOT a history of seasons.

I think I'd define something like this

```<code>public class Player
{
    public Player() { Seasons = new List<PlayerSeason> { }; }

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public System.DateTime DateOfBirth { get; set; }
    public IEnumerable<PlayerSeason> Seasons { get; private set; }

    public void AddSeason(PlayerSeason playerSeason)
    {
        //some code that adds a season.  may check if already exists. whatever your business rules say to do
        Seasons.Add(playerSeason);
    }
}

public class Season
{
    public int Id { get; set; }
    public string season { get; set; }
}

public class PlayerSeason
{
    public int PlayerId {get; set; }
    public int SeasonId { get; set; }
    public int JerseyNumber { get; set; }
    public int HeightInches { get; set; }
    public int WeightPounds { get; set; }
}
</code>```

I'm not going to get into fancier stuff like collection encapsulation, there's enough here already to think about.

I'd take the entity classes you define here and then build your using ef-migrations.

Body:
I'd like to construct a person class that has a property which the value may change over time but I want to keep the history of values. A person grows taller over time and their weight may change.  You may imagine a "HockeyPlayer: Person" that plays over many seasons.  Each season their height/weight may be different.  I would then use EntityFramework to create tables.  I think the main question I have is where do I put those properties? In their own class? In HockeyPlayer?  In Person?  Thank you in advance

pseudocode example:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public System.DateTime DateOfBirth { get; set; }
}

public class Season
{
    public int Id { get; set; }
    public string season { get; set; }
}

public class HockeyPlayer : Person
{
    public int PersonId {get; set; }
    public int SeasonId { get; set; }
    public int JerseyNumber { get; set; }
    public int HeightInches { get; set; }
    public int WeightPounds { get; set; }
}

Body:
I'm not sure your domain model here really models what you are looking for.  Don't think of your player playing in a season as a player.  A player participates in a season and gets a record for season specific information.  So a player has a history of seasons played. a player is NOT a history of seasons.

I think I'd define something like this

public class Player
{
    public Player() { Seasons = new List<PlayerSeason> { }; }

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public System.DateTime DateOfBirth { get; set; }
    public IEnumerable<PlayerSeason> Seasons { get; private set; }

    public void AddSeason(PlayerSeason playerSeason)
    {
        //some code that adds a season.  may check if already exists. whatever your business rules say to do
        Seasons.Add(playerSeason);
    }
}

public class Season
{
    public int Id { get; set; }
    public string season { get; set; }
}

public class PlayerSeason
{
    public int PlayerId {get; set; }
    public int SeasonId { get; set; }
    public int JerseyNumber { get; set; }
    public int HeightInches { get; set; }
    public int WeightPounds { get; set; }
}

I'm not going to get into fancier stuff like collection encapsulation, there's enough here already to think about.

I'd take the entity classes you define here and then build your using ef-migrations.


来源: stackexchange

问:
AWS Hadoop MapReduce - Word Count Average
Hi I have a csv data file as below.

bus,train,bus,TRAIN,car,bus,Train,CAr,car,Train,Cart,Bus,Bicycle,Bicycle,Car,Bus,Cart,Cart,Bicycle,Threewheel

I need to count the average word count in the above CSV using MapReduce.

Eg: Bus = 5/20 =0.25

I can get the word count easily but I need the Total Number of records (20 in this case) to take word count average. But Passing that to reduce function using global Variables did not work out. I tried to pass this as a key-value pair in the map. Key = "Total" Value = total Count to the reducer input. It was not successfull as well.

Any Suggestions to pass this Total Count from Map function to  Reducer Function?

I used One master and 3 slaves in EMR Cluster if that is a piece of needed information.

Thank You in Advance !!!

答:
Once you have the pairs (K, V) where K is the word and V the times it appears, you can map all to a single key, lets say (W, (K, V)). Now you can reduce to obtain a total word count. Then you can make another map/reduce step to join the old keys with the new count.
Hope it helps.</p>

ContentLicense: CC BY-SA 4.0


问:
How to change color of SVG image using CSS (jQuery SVG image replacement)?
This is a self Q&A of a handy piece of code I came up with.

Currently, there isn't an easy way to embed an SVG image and then have access to the SVG elements via CSS. There are various methods of using JS SVG frameworks, but they are overly complicated if all you are doing is making a simple icon with a rollover state.

So here is what I came up with, which I think is by far the easiest way to use SVG files on a website. It takes its concept from the early text-to-image replacement methods, but as far as I am aware has never been done for SVGs.

This is the question:

How do I embed an SVG and change its color in CSS without using a JS-SVG framework?

答:
TL/DR: GO here-> https://codepen.io/sosuke/pen/Pjoqqp

Explanation:

I'm assuming you have html something like this:

```<code><img src="/img/source.svg" class="myClass">
</code>```

Definitely go the filter route, ie. your svg is most likely black or white. You can apply a filter to get it to be whatever color you want, for example, I have a black svg that I want mint green. I first invert it to be white (which is technically all RGB colors on full) then play with the hue saturation etc. To get it right:

```<code>filter: invert(86%) sepia(21%) saturate(761%) hue-rotate(92deg) brightness(99%) contrast(107%);
</code>```

Even better is that you could just use a tool to convert the hex you want into a filter for you:  https://codepen.io/sosuke/pen/Pjoqqp

ContentLicense: CC BY-SA 3.0

Body:
TL/DR: GO here-> https://codepen.io/sosuke/pen/Pjoqqp

Explanation:

I'm assuming you have html something like this:

<img src="/img/source.svg" class="myClass">

Definitely go the filter route, ie. your svg is most likely black or white. You can apply a filter to get it to be whatever color you want, for example, I have a black svg that I want mint green. I first invert it to be white (which is technically all RGB colors on full) then play with the hue saturation etc. To get it right:

filter: invert(86%) sepia(21%) saturate(761%) hue-rotate(92deg) brightness(99%) contrast(107%);

Even better is that you could just use a tool to convert the hex you want into a filter for you:  https://codepen.io/sosuke/pen/Pjoqqp


问:
Can I negate NestJS's Guard?
I have AuthGuard from @nestjs/passport used on one my method (route) like this:

```<code>  @UseGuards(AuthGuard('jwt'))
  @Get('profile')
  getProfile(@Req() req) {
    return this.userService.findOne(req.user.id);
  }
</code>```

Can I negate this guard, so only users without JWT can go trough? I do not want users with JWT in header to access login/register route accidentally.

答:
As bashleigh said in her comment, you can create your own guard that checks for a jwt and rejects if it comes in. A simple example could be something like

@Injectable()
export class NoJwtGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const req = context.switchToHttp().getRequest();
    const auth = req.headers['Authroization'];
    // as you should not have any authorization headers you an reject if the header exists
    return !auth;
  }
}
```

While it isn't possible to immediately negate a built in guard, you could also extend the AuthGuard('jwt') and then in your custom implementation of canActivate you could return !super.canActivate(context)

Title: Can I negate NestJS's Guard?

Body:
I have AuthGuard from @nestjs/passport used on one my method (route) like this:

  @UseGuards(AuthGuard('jwt'))
  @Get('profile')
  getProfile(@Req() req) {
    return this.userService.findOne(req.user.id);
  }

Can I negate this guard, so only users without JWT can go trough? I do not want users with JWT in header to access login/register route accidentally.

Body:
As bashleigh said in her comment, you can create your own guard that checks for a jwt and rejects if it comes in. A simple example could be something like

@Injectable()
export class NoJwtGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const req = context.switchToHttp().getRequest();
    const auth = req.headers['Authroization'];
    // as you should not have any authorization headers you an reject if the header exists
    return !auth;
  }
}

While it isn't possible to immediately negate a built in guard, you could also extend the AuthGuard('jwt') and then in your custom implementation of canActivate you could return !super.canActivate(context)


问:
How to show which values of one list are in other list?
Having 2 lists, I want check which values of List1 are in List2. I'm trying as below but I get error

```<code>List1 = {3,2,8,7,5}
List2 = {1,3,4,2,6,7,9}
= List.Transform(List1, each Text.Contains(List2, _))

Expression.Error: We cannot convert a value of type List to type Text.
Details:
    Value=[List]
    Type=[Type]
</code>```

My expected output would be 3,2,7.

How can I do this?

答:
See List.Intersect Documentation</p>

```<code>Intersect = List.Intersect({List1,List2})
</code>```

Body:
Having 2 lists, I want check which values of List1 are in List2. I'm trying as below but I get error

List1 = {3,2,8,7,5}
List2 = {1,3,4,2,6,7,9}
= List.Transform(List1, each Text.Contains(List2, _))

Expression.Error: We cannot convert a value of type List to type Text.
Details:
    Value=[List]
    Type=[Type]

My expected output would be 3,2,7.

How can I do this?

Body:
See List.Intersect Documentation

Intersect = List.Intersect({List1,List2})


问:
what is the relationship between spatial resolution of the image and size of the CNN architecture?
I am working on different spatial resolutions of the image and thought to implement CNN architecture for each spatial resolution as resizing images affect the object details. Is there any particular relationship that can quantitatively explained between size of the network and spatial resolution of the image?</p>

答:
An image input is represent as H x W x C where H , W and C are height, width and channel respectively. The size of your convolutional network i.e. (number of parameters) is only dependent on the number and size of convolutional layers you have. Each convolutional layer will add (Hk * Wk * Cin + 1) * Cout parameters where Hk and Wk are height and width of the convolutional kernel, Cin the input channels and Cout the output channels.

The input image can only really affect the first convolutional layer. Even then, its spatial dimension will not have an impact on the layer. But the number of channels will.

Consider the following example:

I have a 3 layer CNN consisting of two 3 x 3 convs and one 1 x 1 convs constructed as follows:

Input (H x W x 3) -> Conv1 (3 x 3 x 3) -> Conv2 (3 x 3 x 5) -> Conv3 (1 x 1 x 7)

Weights of first conv layer:

Hk = 3, Wk = 3, Cin = 3, Cout = 3

Number of parameters in 1st layer = (Hk * Wk * Cin + 1) * Cout = (3*3*3 + 1)*3 = 84 parameters

Weights of second conv layer:

Hk = 3, Wk = 3, Cin = 3, Cout = 5

Number of parameters in 2nd layer = (Hk * Wk * Cin + 1) * Cout = (3*3*3 + 1)*5 = 140 parameters

Weights of third conv layer:

Hk = 1, Wk = 1, Cin = 5, Cout = 7

Number of parameters in 3rd layer = (Hk * Wk * Cin + 1) * Cout = (1*1*5 + 1)*7 = 42 parameters

Total number of parameters in the network = 84 + 42 + 140 = 266 parameters.

As you can see, the spatial dims of the input image (H x W) doesn't affect the size of the network but the number of channels of the image does.


问:
Spring custom annotation for this behavior
I have code like this.

```<code>@org.springframework.stereotype.Component("studentInfo")
@org.springframework.context.annotation.Profile("studentInfo")
public class CustomStudentInfo{
</code>```

As you can see i have the component name and the same profile i mean i just want to set this class as a bean only when the profile is set and fact this is working but is kind annoying to type this on 2 lines my question is can i have this on a custom annotation i mean a annotation that help me just to write.

```<code>@CustomSpringAnnotation("studentInfo")
public class CustomStudentInfo{
</code>```

Thanks and sorry if the question is plain.

答:
You can "incorporate" the spring annotations into a custom one like (source/proof: SpringBootApplicaiton source code):

```<code>package my.package.annotations;

@org.springframework.stereotype.Component("studentInfo") // needs "constant expression" here
@org.springframework.context.annotation.Profile("studentInfo") // .. and here!
public @interface MyCustomSpringAnnotation { ...
    // but here you have a problem,
    // since you cannot pass (at least not to the above annotations,
    // ... but maybe dynamically *hack* into the spring context):
    String value() default ""; //?
}
</code>```

...then you could use it like:

```<code>@MyCustomSpringAnnotation
public class CustomStudentInfo { // ...
</code>```

but with the fixed "studentInfo" it is no improvement (but the contrary).

The probably "most spring-like" and best solution (no stress with "too many annotations") is: To consume "studentInfo" from a "visible" (static) final variable (probably best in the affected class):

```<code>@org.springframework.stereotype.Component(CustomStudentInfo.PROFILE_NAME)
@org.springframework.context.annotation.Profile(CustomStudentInfo.PROFILE_NAME)
public class CustomStudentInfo {

    public static final String PROFILE_NAME = "studentInfo";
    // ...
</code>```

Body:
I have code like this.

@org.springframework.stereotype.Component("studentInfo")
@org.springframework.context.annotation.Profile("studentInfo")
public class CustomStudentInfo{

As you can see i have the component name and the same profile i mean i just want to set this class as a bean only when the profile is set and fact this is working but is kind annoying to type this on 2 lines my question is can i have this on a custom annotation i mean a annotation that help me just to write.

@CustomSpringAnnotation("studentInfo")
public class CustomStudentInfo{

Thanks and sorry if the question is plain.

Body:
You can "incorporate" the spring annotations into a custom one like (source/proof: SpringBootApplicaiton source code):

package my.package.annotations;

@org.springframework.stereotype.Component("studentInfo") // needs "constant expression" here
@org.springframework.context.annotation.Profile("studentInfo") // .. and here!
public @interface MyCustomSpringAnnotation { ...
    // but here you have a problem,
    // since you cannot pass (at least not to the above annotations,
    // ... but maybe dynamically *hack* into the spring context):
    String value() default ""; //?
}

...then you could use it like:

@MyCustomSpringAnnotation
public class CustomStudentInfo { // ...

but with the fixed "studentInfo" it is no improvement (but the contrary).

The probably "most spring-like" and best solution (no stress with "too many annotations") is: To consume "studentInfo" from a "visible" (static) final variable (probably best in the affected class):

@org.springframework.stereotype.Component(CustomStudentInfo.PROFILE_NAME)
@org.springframework.context.annotation.Profile(CustomStudentInfo.PROFILE_NAME)
public class CustomStudentInfo {

    public static final String PROFILE_NAME = "studentInfo";
    // ...


问:
Parse json key value from inside of a json object
```<code>{
   "data":
      {
         "key1" : "Key"
      }
}
</code>```

I am currently trying to parse the value of the key named, 'key1' from inside of the jso object, I am still quite new to javascript and am unsure as to how i would achieve this.

The JSON is located inside of a file named, 'jsonData.json'

答:
You can ‘require’ the file then access the value like this:

```<code>const theData = require(‘./filename.json’);
const value = theData.data.key1;
</code>```

What is happening is the require loads the file and converts it to a JavaScript object. That object gets assigned to the local variable theData, which you can then use to navigate the contents of the object with.

Body:
{
   "data":
      {
         "key1" : "Key"
      }
}

I am currently trying to parse the value of the key named, 'key1' from inside of the jso object, I am still quite new to javascript and am unsure as to how i would achieve this.

The JSON is located inside of a file named, 'jsonData.json'

Body:
You can ‘require’ the file then access the value like this:

const theData = require(‘./filename.json’);
const value = theData.data.key1;

What is happening is the require loads the file and converts it to a JavaScript object. That object gets assigned to the local variable theData, which you can then use to navigate the contents of the object with.


问:
what should I do with "You don't have permission to access" error?
on a React-Native project I'm trying to fetch some data from an API but I end up with this error:

"error":"You don't have permission to access!"

here is my code:

```<code>import React, {useEffect} from 'react';
import {View, Text} from 'react-native';
import base64 from 'react-native-base64';
const ProductScreen = props => {
    const url = 'Some_URL';
    const encoded = base64.encode('user:pass');
    const auth = 'Basic ' + encoded;

    useEffect( () => {
        fetch(url, {
          method: 'POST',
          'Authorization': auth,
        }).then(response => response.json()).then(responseJson => {
            const jsonString = JSON.stringify(responseJson);
            console.log(jsonString);
        });

    }

    );

  return (
    <View>
      <Text>some text</Text>
    </View>
  );
}

export default ProductScreen;
</code>```

what does this error mean? are my username and password wrong? or it means I need to get permission from the user of the app for fetching? or something else?

答: the problem was the 'https'. By changing it to 'http' the problem was solved. </p>

Body:
on a React-Native project I'm trying to fetch some data from an API but I end up with this error:

"error":"You don't have permission to access!"

here is my code:

import React, {useEffect} from 'react';
import {View, Text} from 'react-native';
import base64 from 'react-native-base64';
const ProductScreen = props => {
    const url = 'Some_URL';
    const encoded = base64.encode('user:pass');
    const auth = 'Basic ' + encoded;

    useEffect( () => {
        fetch(url, {
          method: 'POST',
          'Authorization': auth,
        }).then(response => response.json()).then(responseJson => {
            const jsonString = JSON.stringify(responseJson);
            console.log(jsonString);
        });

    }

    );

  return (
    <View>
      <Text>some text</Text>
    </View>
  );
}

export default ProductScreen;

what does this error mean? are my username and password wrong? or it means I need to get permission from the user of the app for fetching? or something else?


问:
How to automatically rotate credentials of service accounts on Red Hat IDM
I've been searching the documentation on - https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/linux_domain_identity_authentication_and_policy_guide/pwd-policies-how - to figure out how to automate password rotation on service accounts. Unfortunately, I cannot find any available option on Red Hat documentation. I've found some 3rd-party applications that can automate the rotation of the service accounts' passwords. I'll like to find out if the 3rd-party application is the only option here. Thanks</p>

答: By default, Max lifetime of service account passwords on redhat IDM = 90 days. No configuration needed to automate the process, except you require a lower Max lifetime.</p>


问:
Getting a null pointer when testing a controller using MockMvc
I am getting a null pointer when unit testing a controller. The null pointer is occurring in the controller when calling a mocked service to get an id. I tried many things but I am still getting the same error.

Below is a snippet from the controller code where the null pointer is occurring:

```<code>@RestController
@RequestMapping(ELEMENTS_BASE_URI)
@EnableCommonRestHeaders
public class ElementController {
    @Autowired
    private ElementService elementService;
...
public ResponseEntity<ElementDto> createElement(
            @Valid @RequestBody ElementDto elementDto) {

        ElementDto saved = elementService.createElement(elementDto);

        HttpHeaders headers = new HttpHeaders();

        URI location = UriBuilder.builder(ELEMENT_LINK_URI)
                .pathVariable(ELEMENT_ID, saved.getId())
                .create();
        headers.setLocation(location);

        return new ResponseEntity<>(saved, headers, HttpStatus.CREATED);
    }
...

}
</code>```

In the controller code above, The null pointer occurs at the line below:
saved is null

```<code>   ElementDto saved = elementService.createElement(elementDto);
</code>```

The test code is as below:

```<code>import static com.sas.fcs.networkbuild.util.matchers.JSONContentResultMatcher.jsonObject;
import static com.sas.fcs.networkbuild.util.matchers.JSONContentResultMatcher.jsonPath;

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(controllers = ElementController.class, excludeAutoConfiguration = MockMvcSecurityAutoConfiguration.class)
@ActiveProfiles(value = {"test", "hsql", "disable-oauth2"})
@TestPropertySource("classpath:/test.properties")
public class ElementControllerTest {

    @MockBean
    private ElementService elementService;

    @Autowired
    ElementController elementController;

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper mapper;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders
                .standaloneSetup(elementController)
                .build();
    }

    @Test
    public void testCreateElementSuccess() throws Exception {
        ElementDto element = new ElementDto();
        element.setName("firstname");
        element.setModifiedTimeStamp(new Date());

        ElementDto createdElement = new ElementDto();
        String elementId = "123";
        createdElement.setId(elementId);
        createdElement.setName("firstname");
        createdElement.setLabel("firstname");
        createdElement.setAttribute(true);
        createdElement.setKeep(true);

        when(elementService.create(element)).thenReturn(createdElement);

        // make sure returns location with new element id
        mockMvc.perform(
                post(ServiceConstants.ELEMENTS_BASE_URI)
                     .content(mapper.writeValueAsBytes(element))
                     .accept(ElementDto.MEDIA_TYPE_JSON_VALUE)
                     .contentType(ElementDto.MEDIA_TYPE_JSON_VALUE))
                     .andExpect(status().isCreated())
                     .andExpect(header().string("Location",
                        Matchers.endsWith(ServiceConstants.SERVICE_URI + ServiceConstants.ELEMENTS_BASE_URI + "/" + elementId)))
                     .andExpect(header().string("Last-Modified", not(isEmptyString())))
                     .andExpect(jsonObject().is(createdElement))
                     .andExpect(jsonPath("name").value(element.getName()))
                     .andReturn();
    }
}
</code>```

The line:

```<code>when(elementService.create(element)).thenReturn(createdElement);
</code>```

does not seem to have any effect. Any help on this is really appreciated.

Regards,
Firas

答:
The cause for this issue, was a mistake I made. The function is createElement and the when/any was referencing create function.

I changed:

```<code>when(elementService.create(eq(element))).thenReturn(createdElement);
</code>```

to:

```<code>when(elementService.createElement(eq(element))).thenReturn(createdElement);
</code>```

The rest of the code and notations are correct.

Body:
I am getting a null pointer when unit testing a controller. The null pointer is occurring in the controller when calling a mocked service to get an id. I tried many things but I am still getting the same error.

Below is a snippet from the controller code where the null pointer is occurring:

@RestController
@RequestMapping(ELEMENTS_BASE_URI)
@EnableCommonRestHeaders
public class ElementController {
    @Autowired
    private ElementService elementService;
...
public ResponseEntity<ElementDto> createElement(
            @Valid @RequestBody ElementDto elementDto) {

        ElementDto saved = elementService.createElement(elementDto);

        HttpHeaders headers = new HttpHeaders();

        URI location = UriBuilder.builder(ELEMENT_LINK_URI)
                .pathVariable(ELEMENT_ID, saved.getId())
                .create();
        headers.setLocation(location);

        return new ResponseEntity<>(saved, headers, HttpStatus.CREATED);
    }
...

}

In the controller code above, The null pointer occurs at the line below:
saved is null

   ElementDto saved = elementService.createElement(elementDto);

The test code is as below:

import static com.sas.fcs.networkbuild.util.matchers.JSONContentResultMatcher.jsonObject;
import static com.sas.fcs.networkbuild.util.matchers.JSONContentResultMatcher.jsonPath;

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(controllers = ElementController.class, excludeAutoConfiguration = MockMvcSecurityAutoConfiguration.class)
@ActiveProfiles(value = {"test", "hsql", "disable-oauth2"})
@TestPropertySource("classpath:/test.properties")
public class ElementControllerTest {

    @MockBean
    private ElementService elementService;

    @Autowired
    ElementController elementController;

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper mapper;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders
                .standaloneSetup(elementController)
                .build();
    }

    @Test
    public void testCreateElementSuccess() throws Exception {
        ElementDto element = new ElementDto();
        element.setName("firstname");
        element.setModifiedTimeStamp(new Date());

        ElementDto createdElement = new ElementDto();
        String elementId = "123";
        createdElement.setId(elementId);
        createdElement.setName("firstname");
        createdElement.setLabel("firstname");
        createdElement.setAttribute(true);
        createdElement.setKeep(true);

        when(elementService.create(element)).thenReturn(createdElement);

        // make sure returns location with new element id
        mockMvc.perform(
                post(ServiceConstants.ELEMENTS_BASE_URI)
                     .content(mapper.writeValueAsBytes(element))
                     .accept(ElementDto.MEDIA_TYPE_JSON_VALUE)
                     .contentType(ElementDto.MEDIA_TYPE_JSON_VALUE))
                     .andExpect(status().isCreated())
                     .andExpect(header().string("Location",
                        Matchers.endsWith(ServiceConstants.SERVICE_URI + ServiceConstants.ELEMENTS_BASE_URI + "/" + elementId)))
                     .andExpect(header().string("Last-Modified", not(isEmptyString())))
                     .andExpect(jsonObject().is(createdElement))
                     .andExpect(jsonPath("name").value(element.getName()))
                     .andReturn();
    }
}

The line:

when(elementService.create(element)).thenReturn(createdElement);

does not seem to have any effect. Any help on this is really appreciated.

Regards,
Firas

Body:
The cause for this issue, was a mistake I made. The function is createElement and the when/any was referencing create function.

I changed:

when(elementService.create(eq(element))).thenReturn(createdElement);

to:

when(elementService.createElement(eq(element))).thenReturn(createdElement);

The rest of the code and notations are correct.


问:
Given a number, find the next higher number which has the exact same set of digits as the original number
I just bombed an interview and made pretty much zero progress on my interview question.

Given a number, find the next higher number which has the exact same
set of digits as the original number. For example: given 38276 return
38627

I wanted to begin by finding the index of the first digit (from the right) that was less than the ones digit. Then I would rotate the last digits in the subset such that it was the next biggest number comprised of the same digits, but got stuck.

The interviewer also suggested trying to swap digits one at a time, but I couldn't figure out the algorithm and just stared at a screen for like 20-30 minutes. Needless to say, I think I'm going to have to continue the job hunt.

答:
PHP Code

```<code>function NextHigherNumber($num1){
$num = strval($num1);
$max = 0;
for($i=(strlen($num)-2); $i>=0; $i--){
    $numArrayRaw = substr($num, $i);
    $numArray = str_split($numArrayRaw);
    $max = max($numArray);
    if ($numArray[0] < $max){
        sort( $numArray, SORT_NUMERIC );
        array_pop($numArray);
        $numarrstr = implode("",$numArray);
        $rt = substr($num,0,$i) . $max . $numarrstr;
        return $rt;
    }
}
return "-1";
}
echo NextHigherNumber(123);
</code>```

Body:
PHP Code

function NextHigherNumber($num1){
$num = strval($num1);
$max = 0;
for($i=(strlen($num)-2); $i>=0; $i--){
    $numArrayRaw = substr($num, $i);
    $numArray = str_split($numArrayRaw);
    $max = max($numArray);
    if ($numArray[0] < $max){
        sort( $numArray, SORT_NUMERIC );
        array_pop($numArray);
        $numarrstr = implode("",$numArray);
        $rt = substr($num,0,$i) . $max . $numarrstr;
        return $rt;
    }
}
return "-1";
}
echo NextHigherNumber(123);


问:
Two Inputs side by side CSS
I'm currently practicing some WebDev and I'm working on an interactive food pyramid. I've been able to align the other inputs but the inputs on top of the triangle are giving me trouble, I've tried everything from floats to flex and inline blocks. Nothing seems to work, any help would be greatly appreciated.

function incrementValue1() {
  let value = parseInt(document.getElementById('number1').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number1').value = value;
}

function decrementValue1() {
  let value = parseInt(document.getElementById('number1').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number1').value = value;
}

function incrementValue2() {
  let value = parseInt(document.getElementById('number2').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number2').value = value;
}

function decrementValue2() {
  let value = parseInt(document.getElementById('number2').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number2').value = value;
}

function incrementValue3() {
  let value = parseInt(document.getElementById('number3').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number3').value = value;
}

function decrementValue3() {
  let value = parseInt(document.getElementById('number3').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number3').value = value;
}

function incrementValue4() {
  let value = parseInt(document.getElementById('number4').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number4').value = value;
}

function decrementValue4() {
  let value = parseInt(document.getElementById('number4').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number4').value = value;
}

function incrementValue5() {
  let value = parseInt(document.getElementById('number5').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number5').value = value;
}

function decrementValue5() {
  let value = parseInt(document.getElementById('number5').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number5').value = value;
}

function incrementValue6() {
  let value = parseInt(document.getElementById('number6').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number6').value = value;
}

function decrementValue6() {
  let value = parseInt(document.getElementById('number6').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number6').value = value;
}

var colors = ["red", "blue", "green", "yellow", "purple", "gold", "pink", "grey", "turquoise", "aqua"];
var i = 0;
var selectedColor;

function changeColour() {
  selectedColor = colors[i];
  document.getElementById("number" + 1).style.backgroundColor = selectedColor;
  i++;
  if (i > colors.length)
    i = 0;
}

function printDate() {
  let value = document.getElementById("date").value;
  document.getElementById("check").innerHTML = "Date: " + value;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  text-align: center;
  position: relative;
  top: 40%;
}

.inside-text1 {
  display: none;
  position: absolute;
  top: 20px;
  left: 248px;
  text-align: center;
  bottom: -65px;
}

.inside-text {
  display: none;
  position: relative;
  text-align: center;
  bottom: -25px;
}

.inside-text6 {
  display: none;
  position: relative;
  text-align: center;
  bottom: -120px;
  /*float: left;*/
}

#p6 {
  border-bottom: 200px solid blue;
  border-left: 100px solid transparent;
  border-right: 100px solid transparent;
  height: 0;
  width: 0;
  margin-right: auto;
  margin-left: auto;
}

#p5-5 {
  border-bottom: 20px solid white;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 10px;
  margin-right: auto;
  margin-left: auto;
}

#p5 {
  border-bottom: 80px solid black;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 220px;
  margin-right: auto;
  margin-left: auto;
}

#p4-5 {
  border-bottom: 20px solid white;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 240px;
  margin-right: auto;
  margin-left: auto;
}

#p4 {
  border-bottom: 80px solid purple;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 330px;
  margin-right: auto;
  margin-left: auto;
}

#p3 {
  border-bottom: 80px solid green;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 420px;
  margin-right: auto;
  margin-left: auto;
}

#p2 {
  border-bottom: 80px solid yellow;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 510px;
  margin-right: auto;
  margin-left: auto;
}

#p1 {
  position: relative;
  top: 40%;
  border-bottom: 80px solid red;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 600px;
  margin-right: auto;
  margin-left: auto;
}

#p1:hover .inside-text1 {
  display: block;
}

#p2:hover .inside-text {
  display: block;
}

#p3:hover .inside-text {
  display: block;
}

#p4:hover .inside-text {
  display: block;
}

#p5:hover .inside-text {
  display: block;
}

#p6:hover .inside-text6 {
  display: block;
}

.button {
  margin-right: auto;
  margin-left: auto;
  position: relative;
}

#b1 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number1 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  background-color: grey;
  text-align: center;
}

#b2 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b3 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number2 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b4 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b5 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number3 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b6 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b7 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number4 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b8 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b9 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number5 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b10 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b11 {
  /*display: inline-flex;*/
  float: left;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number6 {
  /*display: inline-flex;*/
  float: left;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b12 {
  /*display: inline-flex;*/
  float: left;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#check {
  display: block;
  position: center;
  height: 25px;
  width: 125px;
  /*border-radius: 50%;*/
  border: solid red;
  text-align: center;
}</code>```

      <input type="button" onclick="decrementValue6()" value="-" id="b11" />
      <input type="text" id="number6" value="0" />
      <input type="button" onclick="incrementValue6()" value="+" id="b12" />

      <form>
        <input type="button" onclick="decrementValue5()" value="-" id="b9" />
        <input type="text" id="number5" value="1" />
        <input type="button" onclick="incrementValue5()" value="+" id="b10" />
      </form>

      <form>
        <input type="button" onclick="decrementValue4()" value="-" id="b7" />
        <input type="text" id="number4" value="2" />
        <input type="button" onclick="incrementValue4();" value="+" id="b8" />
      </form>

      <form>
        <input type="button" onclick="decrementValue3()" value="-" id="b5" />
        <input type="text" id="number3" value="3" />
        <input type="button" onclick="incrementValue3()" value="+" id="b6" />
      </form>

      <form>
        <input type="button" onclick="decrementValue2()" value="-" id="b3" />
        <input type="text" id="number2" value="4" />
        <input type="button" onclick="incrementValue2()" value="+" id="b4" />
      </form>

      <form>
        <input type="button" onclick="decrementValue1('number6');changeColour()" value="-" id="b2" />
        <input type="text" id="number1" value="6" />
        <input type="button" onclick="incrementValue1();changeColour()" value="+" id="b1" />
      </form>

Enter Date of Submission:
<input type="date" id="date" value="0" />
<input type="button" onclick="printDate()" value="Record" />

```

答:
Change your CSS here:

```<code>#p6:hover .inside-text6{
    display: block;
}
</code>```

The :hover rule overruled your display: flex approaches.

P.S.: I've put this into a fiddle, this helps people with getting at your problem easier - welcome to SO! :)

Title: Two Inputs side by side CSS

Body:
I'm currently practicing some WebDev and I'm working on an interactive food pyramid. I've been able to align the other inputs but the inputs on top of the triangle are giving me trouble, I've tried everything from floats to flex and inline blocks. Nothing seems to work, any help would be greatly appreciated.

function incrementValue1() {
  let value = parseInt(document.getElementById('number1').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number1').value = value;
}

function decrementValue1() {
  let value = parseInt(document.getElementById('number1').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number1').value = value;
}

function incrementValue2() {
  let value = parseInt(document.getElementById('number2').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number2').value = value;
}

function decrementValue2() {
  let value = parseInt(document.getElementById('number2').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number2').value = value;
}

function incrementValue3() {
  let value = parseInt(document.getElementById('number3').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number3').value = value;
}

function decrementValue3() {
  let value = parseInt(document.getElementById('number3').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number3').value = value;
}

function incrementValue4() {
  let value = parseInt(document.getElementById('number4').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number4').value = value;
}

function decrementValue4() {
  let value = parseInt(document.getElementById('number4').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number4').value = value;
}

function incrementValue5() {
  let value = parseInt(document.getElementById('number5').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number5').value = value;
}

function decrementValue5() {
  let value = parseInt(document.getElementById('number5').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number5').value = value;
}

function incrementValue6() {
  let value = parseInt(document.getElementById('number6').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number6').value = value;
}

function decrementValue6() {
  let value = parseInt(document.getElementById('number6').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number6').value = value;
}

var colors = ["red", "blue", "green", "yellow", "purple", "gold", "pink", "grey", "turquoise", "aqua"];
var i = 0;
var selectedColor;

function changeColour() {
  selectedColor = colors[i];
  document.getElementById("number" + 1).style.backgroundColor = selectedColor;
  i++;
  if (i > colors.length)
    i = 0;
}

function printDate() {
  let value = document.getElementById("date").value;
  document.getElementById("check").innerHTML = "Date: " + value;
}

.container {
  text-align: center;
  position: relative;
  top: 40%;
}

.inside-text1 {
  display: none;
  position: absolute;
  top: 20px;
  left: 248px;
  text-align: center;
  bottom: -65px;
}

.inside-text {
  display: none;
  position: relative;
  text-align: center;
  bottom: -25px;
}

.inside-text6 {
  display: none;
  position: relative;
  text-align: center;
  bottom: -120px;
  /*float: left;*/
}

#p6 {
  border-bottom: 200px solid blue;
  border-left: 100px solid transparent;
  border-right: 100px solid transparent;
  height: 0;
  width: 0;
  margin-right: auto;
  margin-left: auto;
}

#p5-5 {
  border-bottom: 20px solid white;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 10px;
  margin-right: auto;
  margin-left: auto;
}

#p5 {
  border-bottom: 80px solid black;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 220px;
  margin-right: auto;
  margin-left: auto;
}

#p4-5 {
  border-bottom: 20px solid white;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 240px;
  margin-right: auto;
  margin-left: auto;
}

#p4 {
  border-bottom: 80px solid purple;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 330px;
  margin-right: auto;
  margin-left: auto;
}

#p3 {
  border-bottom: 80px solid green;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 420px;
  margin-right: auto;
  margin-left: auto;
}

#p2 {
  border-bottom: 80px solid yellow;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 510px;
  margin-right: auto;
  margin-left: auto;
}

#p1 {
  position: relative;
  top: 40%;
  border-bottom: 80px solid red;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 600px;
  margin-right: auto;
  margin-left: auto;
}

#p1:hover .inside-text1 {
  display: block;
}

#p2:hover .inside-text {
  display: block;
}

#p3:hover .inside-text {
  display: block;
}

#p4:hover .inside-text {
  display: block;
}

#p5:hover .inside-text {
  display: block;
}

#p6:hover .inside-text6 {
  display: block;
}

.button {
  margin-right: auto;
  margin-left: auto;
  position: relative;
}

#b1 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number1 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  background-color: grey;
  text-align: center;
}

#b2 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b3 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number2 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b4 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b5 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number3 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b6 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b7 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number4 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b8 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b9 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number5 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b10 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b11 {
  /*display: inline-flex;*/
  float: left;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number6 {
  /*display: inline-flex;*/
  float: left;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b12 {
  /*display: inline-flex;*/
  float: left;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#check {
  display: block;
  position: center;
  height: 25px;
  width: 125px;
  /*border-radius: 50%;*/
  border: solid red;
  text-align: center;
}

      <input type="button" onclick="decrementValue6()" value="-" id="b11" />
      <input type="text" id="number6" value="0" />
      <input type="button" onclick="incrementValue6()" value="+" id="b12" />

      <form>
        <input type="button" onclick="decrementValue5()" value="-" id="b9" />
        <input type="text" id="number5" value="1" />
        <input type="button" onclick="incrementValue5()" value="+" id="b10" />
      </form>

      <form>
        <input type="button" onclick="decrementValue4()" value="-" id="b7" />
        <input type="text" id="number4" value="2" />
        <input type="button" onclick="incrementValue4();" value="+" id="b8" />
      </form>

      <form>
        <input type="button" onclick="decrementValue3()" value="-" id="b5" />
        <input type="text" id="number3" value="3" />
        <input type="button" onclick="incrementValue3()" value="+" id="b6" />
      </form>

      <form>
        <input type="button" onclick="decrementValue2()" value="-" id="b3" />
        <input type="text" id="number2" value="4" />
        <input type="button" onclick="incrementValue2()" value="+" id="b4" />
      </form>

      <form>
        <input type="button" onclick="decrementValue1('number6');changeColour()" value="-" id="b2" />
        <input type="text" id="number1" value="6" />
        <input type="button" onclick="incrementValue1();changeColour()" value="+" id="b1" />
      </form>

Enter Date of Submission:
<input type="date" id="date" value="0" />
<input type="button" onclick="printDate()" value="Record" />

Body:
Change your CSS here:

#p6:hover .inside-text6{
    display: block;
}

The :hover rule overruled your display: flex approaches.

P.S.: I've put this into a fiddle, this helps people with getting at your problem easier - welcome to SO! :)


问:
How do you add a favicon to HTML page?
I know this is a duplicate question, but I was trying to add a favicon.ico file to my site on localhost:8000 made with Django. The favicon exists on templates\articles (in an app called articles), and I've tried everything on stackoverflow, youtube, and used realfavicongenerator.net, but nothing works. Do I have to define the Django URL/view for the ICO file, as localhost:8000/favicon.ico brings up error? Here's my (simplified) code by the way:

```<code><title>Newsreed | Articles</title>
<link rel="shortcut icon" type = 'image/x-icon' href="favicon.ico">
</code>```

What should I do, because I've been struggling with it for several days now and tere has been no solution on anything.

答:
I like to use:

https://www.favicon-generator.org/

They let you upload an image to use and it will output a directory with all scaled versions of the image for all manner of devices your page could be viewed on including the html that you will need to copy and paste.

Title: How do you add a favicon to HTML page?

Body:
I know this is a duplicate question, but I was trying to add a favicon.ico file to my site on localhost:8000 made with Django. The favicon exists on templates\articles (in an app called articles), and I've tried everything on stackoverflow, youtube, and used realfavicongenerator.net, but nothing works. Do I have to define the Django URL/view for the ICO file, as localhost:8000/favicon.ico brings up error? Here's my (simplified) code by the way:

<title>Newsreed | Articles</title>
<link rel="shortcut icon" type = 'image/x-icon' href="favicon.ico">

What should I do, because I've been struggling with it for several days now and tere has been no solution on anything.


问:
Call Oracle stored procedure from Select statement?
I have an Oracle stored procedure that gets 2 parameters and returns 2 parameters (status and message).

I am making changes to this legacy application capable of only executing select statements,

My question is it possible to wrap the stored procedure with some function or other stored procedure or a view, or any other object I might not no about, so can I execute the stored procedure using simple a select statement?

Correct execution code will be something like:

```<code>DECLARE
  PRINTER_ID VARCHAR2(200);
  O_STATUS VARCHAR2(200);
  O_MESSAGE VARCHAR2(200);
BEGIN
  PRINTER_ID := '551555115';
  IMPL_XEROX_PRINTER_CHECK(    PRINTER_ID => PRINTER_ID,    O_STATUS => O_STATUS,    O_MESSAGE => O_MESSAGE  );
  DBMS_OUTPUT.PUT_LINE('O_STATUS = ' || O_STATUS);
  DBMS_OUTPUT.PUT_LINE('O_MESSAGE = ' || O_MESSAGE);
END;
</code>```

What I am trying to get is something like:

```<code>Select O_STATUS,O_MESSAGE from IMPL_XEROX_PRINTER_CHECk_WRAPPER where PRINTER_ID = '551555115';
</code>```

The thing is that the SP is inserting some data to a temporary table...
this is the table:

```<code> CREATE TABLE "TEST_PRNT_DATA"    ( "COLUMN1" VARCHAR2(20 BYTE),    "COLUMN2" VARCHAR2(20 BYTE),    "COLUMN3" VARCHAR2(20 BYTE)   )
</code>```

/

This is the stored procedure:

```<code>CREATE OR REPLACE PROCEDURE IMPL_XEROX_PRINTER_CHECK
(
  PRINTER_ID IN VARCHAR2

, O_STATUS  OUT VARCHAR2
, O_MESSAGE OUT VARCHAR2
)  AS
    PROC_STATUS         VARCHAR2(10);
    PROC_ERROR_MESSAGE  VARCHAR2(4000);

    rand_num number;
BEGIN

     dbms_output.put_line('IMPL_XEROX_PRINTER_CHECK ');
     select round(dbms_random.value(1,10)) into rand_num     from dual;

     insert into TEST_PRNT_DATA values(1,2,3);

    IF rand_num < 5 THEN
            PROC_STATUS  := 'TRUE';
            O_STATUS:= 'TRUE';
            PROC_ERROR_MESSAGE := 'ALL IS GOOD';
            O_MESSAGE:= 'ALL IS GOOD';
    ELSE
            PROC_STATUS  := 'FALSE';
            O_STATUS:= 'FALSE';
            PROC_ERROR_MESSAGE := 'SOMTHING WENT WRONG!!! ';
            O_MESSAGE:= 'SOMTHING WENT WRONG!!! ';
    END IF;

END IMPL_XEROX_PRINTER_CHECK;
</code>```

答:
It depends what your application can handle. You could have a wrapper function that returns a ref cursor:

```<code>create or replace function impl_xerox_printer_check_wrap (
  printer_id in varchar2
)
return sys_refcursor as
  o_status varchar2(200);
  o_message varchar2(200);
  o_refcursor sys_refcursor;
begin
  impl_xerox_printer_check(printer_id => printer_id, o_status => o_status, o_message => o_message);
  open o_refcursor for select o_status as status, o_message as message from dual;
  return o_refcursor;
end;
/

select impl_xerox_printer_check_wrap('551555115') from dual;

IMPL_XEROX_PRINTER_C
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

STATUS     MESSAGE
---------- ------------------------------
TRUE       ALL IS GOOD
</code>```

(output as shown by SQL Developer, run as a script). But your application might not know what to do with that.

You could use a collection or object type but unless you define your own at schema level it's a bit of a pain to interpret:

```<code>create or replace function impl_xerox_printer_check_wrap (
  printer_id in varchar2
)
return sys.odcivarchar2list as
  o_result sys.odcivarchar2list;
begin
  o_result := new sys.odcivarchar2list();
  o_result.extend(2);
  impl_xerox_printer_check(printer_id => printer_id, o_status => o_result(1), o_message => o_result(2));
  return o_result;
end;
/

select * from table (impl_xerox_printer_check_wrap('551555115'));

Result Sequence
------------------------------------------------
TRUE
ALL IS GOOD
</code>```

Or you could go via XML, which sounds odd but gives a nice result:

```<code>create or replace function impl_xerox_printer_check_wrap (
  printer_id in varchar2
)
return xmltype as
  o_status varchar2(200);
  o_message varchar2(200);
  o_refcursor sys_refcursor;
begin
  impl_xerox_printer_check(printer_id => printer_id, o_status => o_status, o_message => o_message);
  open o_refcursor for select o_status as status, o_message as message from dual;
  return xmltype(o_refcursor);
end;
/

select impl_xerox_printer_check_wrap('551555115') from dual;

IMPL_XEROX_PRINTER_CHECK_WRAP('551555115')
--------------------------------------------------------------------------------
<?xml version="1.0"?>
<ROWSET>
 <ROW>
  <STATUS>FALSE</STATUS>
  <MESSAGE>SOMTHING WENT WRONG!!! </MESSAGE>
 </ROW>
</ROWSET>
</code>```

OK, that doesn't look very helpful... but then you extract the values:

```<code>select status, message
from xmltable(
  '/ROWSET/ROW'
  passing impl_xerox_printer_check_wrap('551555115')
  columns status varchar2(200) path 'STATUS',
    message varchar2(200) path 'MESSAGE'
);

STATUS     MESSAGE
---------- ------------------------------
FALSE      SOMTHING WENT WRONG!!!
</code>```

db<>fiddle

Your application can run that query - passing the printer ID as a bind variable of course - and will get back a simple result set.

As you're on 12c you can use the PL/SQL capabilities added to subquery factoring, so you don't need to create a permanent function at all (though you may still prefer to):

```<code>drop function IMPL_XEROX_PRINTER_CHECK_WRAP;

with
  function impl_xerox_printer_check_wrap (
    printer_id in varchar2
  )
  return xmltype as
    o_status varchar2(200);
    o_message varchar2(200);
    o_refcursor sys_refcursor;
  begin
    impl_xerox_printer_check(printer_id => printer_id, o_status => o_status, o_message => o_message);
    open o_refcursor for select o_status as status, o_message as message from dual;
    return xmltype(o_refcursor);
  end;
select impl_xerox_printer_check_wrap('551555115')
from dual
/
</code>```

if you want XML (as per comment), or with XMLTable if you don't:

```<code>IMPL_XEROX_PRINTER_CHECK_WRAP('551555115')
--------------------------------------------------------------------------------
<?xml version="1.0"?>
<ROWSET>
 <ROW>
  <STATUS>TRUE</STATUS>
  <MESSAGE>ALL IS GOOD</MESSAGE>
 </ROW>
</ROWSET>
with
  function impl_xerox_printer_check_wrap (
    printer_id in varchar2
  )
  return xmltype as
    o_status varchar2(200);
    o_message varchar2(200);
    o_refcursor sys_refcursor;
  begin
    impl_xerox_printer_check(printer_id => printer_id, o_status => o_status, o_message => o_message);
    open o_refcursor for select o_status as status, o_message as message from dual;
    return xmltype(o_refcursor);
  end;
select status, message
from xmltable(
  '/ROWSET/ROW'
  passing impl_xerox_printer_check_wrap('551555115')
  columns status varchar2(200) path 'STATUS',
    message varchar2(200) path 'MESSAGE'
)
/

STATUS     MESSAGE
---------- ------------------------------
FALSE      SOMTHING WENT WRONG!!!
</code>```

The thing is that the SP is inserting some data to a temporary table

That's a fairly crucial omission. You can't perform an insert or update in a function call from a select. The documentation lists restrictions on functions called from SQL, and goes into more detail in this warning:

Because SQL is a declarative language, rather than an imperative (or procedural) one, you cannot know how many times a function invoked by a SQL statement will run—even if the function is written in PL/SQL, an imperative language.

If the function was allowed to do DML then you would have no control over how many times that DML was performed. If it was doing an insert, for instance, it might try to insert the same row twice and either duplicate data or get a constraint violation.

You could, technically, declare the function with pragma autonomous_transaction, as in this modified db<>fiddle, but that's a horrible hack and one that will probably ultimately cause more problems than it solves, for the reasons shown above. You might get away with it if you only ever make single-row calls as in your example, but even then it isn't guaranteed to work; and even if it works now it might break in the future.

Body:
I have an Oracle stored procedure that gets 2 parameters and returns 2 parameters (status and message).

I am making changes to this legacy application capable of only executing select statements,

My question is it possible to wrap the stored procedure with some function or other stored procedure or a view, or any other object I might not no about, so can I execute the stored procedure using simple a select statement?

Correct execution code will be something like:

DECLARE
  PRINTER_ID VARCHAR2(200);
  O_STATUS VARCHAR2(200);
  O_MESSAGE VARCHAR2(200);
BEGIN
  PRINTER_ID := '551555115';
  IMPL_XEROX_PRINTER_CHECK(    PRINTER_ID => PRINTER_ID,    O_STATUS => O_STATUS,    O_MESSAGE => O_MESSAGE  );
  DBMS_OUTPUT.PUT_LINE('O_STATUS = ' || O_STATUS);
  DBMS_OUTPUT.PUT_LINE('O_MESSAGE = ' || O_MESSAGE);
END;

What I am trying to get is something like:

Select O_STATUS,O_MESSAGE from IMPL_XEROX_PRINTER_CHECk_WRAPPER where PRINTER_ID = '551555115';

The thing is that the SP is inserting some data to a temporary table...
this is the table:

 CREATE TABLE "TEST_PRNT_DATA"    ( "COLUMN1" VARCHAR2(20 BYTE),    "COLUMN2" VARCHAR2(20 BYTE),    "COLUMN3" VARCHAR2(20 BYTE)   )

/

This is the stored procedure:

CREATE OR REPLACE PROCEDURE IMPL_XEROX_PRINTER_CHECK
(
  PRINTER_ID IN VARCHAR2

, O_STATUS  OUT VARCHAR2
, O_MESSAGE OUT VARCHAR2
)  AS
    PROC_STATUS         VARCHAR2(10);
    PROC_ERROR_MESSAGE  VARCHAR2(4000);

    rand_num number;
BEGIN

     dbms_output.put_line('IMPL_XEROX_PRINTER_CHECK ');
     select round(dbms_random.value(1,10)) into rand_num     from dual;

     insert into TEST_PRNT_DATA values(1,2,3);

    IF rand_num < 5 THEN
            PROC_STATUS  := 'TRUE';
            O_STATUS:= 'TRUE';
            PROC_ERROR_MESSAGE := 'ALL IS GOOD';
            O_MESSAGE:= 'ALL IS GOOD';
    ELSE
            PROC_STATUS  := 'FALSE';
            O_STATUS:= 'FALSE';
            PROC_ERROR_MESSAGE := 'SOMTHING WENT WRONG!!! ';
            O_MESSAGE:= 'SOMTHING WENT WRONG!!! ';
    END IF;

END IMPL_XEROX_PRINTER_CHECK;

Body:
It depends what your application can handle. You could have a wrapper function that returns a ref cursor:

create or replace function impl_xerox_printer_check_wrap (
  printer_id in varchar2
)
return sys_refcursor as
  o_status varchar2(200);
  o_message varchar2(200);
  o_refcursor sys_refcursor;
begin
  impl_xerox_printer_check(printer_id => printer_id, o_status => o_status, o_message => o_message);
  open o_refcursor for select o_status as status, o_message as message from dual;
  return o_refcursor;
end;
/

select impl_xerox_printer_check_wrap('551555115') from dual;

IMPL_XEROX_PRINTER_C
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

STATUS     MESSAGE
---------- ------------------------------
TRUE       ALL IS GOOD

(output as shown by SQL Developer, run as a script). But your application might not know what to do with that.

You could use a collection or object type but unless you define your own at schema level it's a bit of a pain to interpret:

create or replace function impl_xerox_printer_check_wrap (
  printer_id in varchar2
)
return sys.odcivarchar2list as
  o_result sys.odcivarchar2list;
begin
  o_result := new sys.odcivarchar2list();
  o_result.extend(2);
  impl_xerox_printer_check(printer_id => printer_id, o_status => o_result(1), o_message => o_result(2));
  return o_result;
end;
/

select * from table (impl_xerox_printer_check_wrap('551555115'));

Result Sequence
------------------------------------------------
TRUE
ALL IS GOOD

Or you could go via XML, which sounds odd but gives a nice result:

create or replace function impl_xerox_printer_check_wrap (
  printer_id in varchar2
)
return xmltype as
  o_status varchar2(200);
  o_message varchar2(200);
  o_refcursor sys_refcursor;
begin
  impl_xerox_printer_check(printer_id => printer_id, o_status => o_status, o_message => o_message);
  open o_refcursor for select o_status as status, o_message as message from dual;
  return xmltype(o_refcursor);
end;
/

select impl_xerox_printer_check_wrap('551555115') from dual;

IMPL_XEROX_PRINTER_CHECK_WRAP('551555115')
--------------------------------------------------------------------------------
<?xml version="1.0"?>
<ROWSET>
 <ROW>
  <STATUS>FALSE</STATUS>
  <MESSAGE>SOMTHING WENT WRONG!!! </MESSAGE>
 </ROW>
</ROWSET>

OK, that doesn't look very helpful... but then you extract the values:

select status, message
from xmltable(
  '/ROWSET/ROW'
  passing impl_xerox_printer_check_wrap('551555115')
  columns status varchar2(200) path 'STATUS',
    message varchar2(200) path 'MESSAGE'
);

STATUS     MESSAGE
---------- ------------------------------
FALSE      SOMTHING WENT WRONG!!!

db<>fiddle

Your application can run that query - passing the printer ID as a bind variable of course - and will get back a simple result set.

As you're on 12c you can use the PL/SQL capabilities added to subquery factoring, so you don't need to create a permanent function at all (though you may still prefer to):

drop function IMPL_XEROX_PRINTER_CHECK_WRAP;

with
  function impl_xerox_printer_check_wrap (
    printer_id in varchar2
  )
  return xmltype as
    o_status varchar2(200);
    o_message varchar2(200);
    o_refcursor sys_refcursor;
  begin
    impl_xerox_printer_check(printer_id => printer_id, o_status => o_status, o_message => o_message);
    open o_refcursor for select o_status as status, o_message as message from dual;
    return xmltype(o_refcursor);
  end;
select impl_xerox_printer_check_wrap('551555115')
from dual
/

if you want XML (as per comment), or with XMLTable if you don't:

IMPL_XEROX_PRINTER_CHECK_WRAP('551555115')
--------------------------------------------------------------------------------
<?xml version="1.0"?>
<ROWSET>
 <ROW>
  <STATUS>TRUE</STATUS>
  <MESSAGE>ALL IS GOOD</MESSAGE>
 </ROW>
</ROWSET>
with
  function impl_xerox_printer_check_wrap (
    printer_id in varchar2
  )
  return xmltype as
    o_status varchar2(200);
    o_message varchar2(200);
    o_refcursor sys_refcursor;
  begin
    impl_xerox_printer_check(printer_id => printer_id, o_status => o_status, o_message => o_message);
    open o_refcursor for select o_status as status, o_message as message from dual;
    return xmltype(o_refcursor);
  end;
select status, message
from xmltable(
  '/ROWSET/ROW'
  passing impl_xerox_printer_check_wrap('551555115')
  columns status varchar2(200) path 'STATUS',
    message varchar2(200) path 'MESSAGE'
)
/

STATUS     MESSAGE
---------- ------------------------------
FALSE      SOMTHING WENT WRONG!!!

The thing is that the SP is inserting some data to a temporary table

That's a fairly crucial omission. You can't perform an insert or update in a function call from a select. The documentation lists restrictions on functions called from SQL, and goes into more detail in this warning:

Because SQL is a declarative language, rather than an imperative (or procedural) one, you cannot know how many times a function invoked by a SQL statement will run—even if the function is written in PL/SQL, an imperative language.

If the function was allowed to do DML then you would have no control over how many times that DML was performed. If it was doing an insert, for instance, it might try to insert the same row twice and either duplicate data or get a constraint violation.

You could, technically, declare the function with pragma autonomous_transaction, as in this modified db<>fiddle, but that's a horrible hack and one that will probably ultimately cause more problems than it solves, for the reasons shown above. You might get away with it if you only ever make single-row calls as in your example, but even then it isn't guaranteed to work; and even if it works now it might break in the future.


问:
How to keep an image open in OpenCV even if u press a key
How I do it? In matplotlib we have Show with False argument you can keep the image without closing. In my script, I pop out two images with cv2.imshow and I read that I can keep them up with waitKey(0), but when I press a key, they dissapear as the waitKey stablishs.

I want to know if there is a equivalent method for OpenCV as Show(False) from matplotlib.pyplot.

答:
When you use waitKey(number), you are setting a timer for how long OpenCV should wait for any key to be pressed and will halt execution during that time until either a key is pressed or the timer is up. When you set number = 0, this is shorthand for saying wait forever until a key is pressed.

```<code>key = cv2.waitKey(0)
if key == 27:
   cv2.destroyAllWindows()
</code>```

The above code sets it so that when you press a key, it returns the key that you pressed to the variable: key. Now if key = 27 (i.e. the esacpe key has been pressed), then it will close the window. If not, then it will not. More details can be seen in the link below!

OpenCV Images

Cheers,

warning: if you are using a 64-bit machine, then you need to use

```<code>k = cv2.waitKey(0) & 0xFF
</code>```

Body:
When you use waitKey(number), you are setting a timer for how long OpenCV should wait for any key to be pressed and will halt execution during that time until either a key is pressed or the timer is up. When you set number = 0, this is shorthand for saying wait forever until a key is pressed.

key = cv2.waitKey(0)
if key == 27:
   cv2.destroyAllWindows()

The above code sets it so that when you press a key, it returns the key that you pressed to the variable: key. Now if key = 27 (i.e. the esacpe key has been pressed), then it will close the window. If not, then it will not. More details can be seen in the link below!

OpenCV Images

Cheers,

warning: if you are using a 64-bit machine, then you need to use

k = cv2.waitKey(0) & 0xFF


问:
c++ self in initialisation list
i have this code snippet

```<code>class Osoba{
         Osoba(char* imie,int wiek){
                     this->imie=new char[strlen(imie)+1];
                     strcpy(this->imie,imie);
                     this->wiek=wiek;
                     cout<<"Utworzono Osobe "<<this->imie<<endl;
         }
         Osoba(Osoba& x){
                 Osoba(x.imie,x.wiek);
         }
[...]
</code>```

and when i call the copy constructor it doesnt work (creates and destroyes object).

Edit:
if i use

```<code>         Osoba(Osoba& x): Osoba(x.imie,x.wiek){
</code>```

i get type 'class Osoba' is not a direct base of 'Osoba'

how is this done ?

答: You can't call constructors like that. Well you can, but what happens is a nameless temporary  object gets created. Write your copy constructor without reference to the other constructor. Also, if you use std::string instead of char *, you won't need a copy constructor. If you persist in using char  *, you will also need a destructor and an assignment operator.</p>

Title: c++ self in initialisation list

Body:
i have this code snippet

class Osoba{
         Osoba(char* imie,int wiek){
                     this->imie=new char[strlen(imie)+1];
                     strcpy(this->imie,imie);
                     this->wiek=wiek;
                     cout<<"Utworzono Osobe "<<this->imie<<endl;
         }
         Osoba(Osoba& x){
                 Osoba(x.imie,x.wiek);
         }
[...]

and when i call the copy constructor it doesnt work (creates and destroyes object).

Edit:
if i use

         Osoba(Osoba& x): Osoba(x.imie,x.wiek){

i get type 'class Osoba' is not a direct base of 'Osoba'

how is this done ?


问:
Bad formation on wrapfiure latex overlap image text

I am using overleaf online to compile my report and I am experiencing this problem with wrap figure. particularly over a weight of 6cm I experience the problem as shown in figure, image overlaps the text while independent on the size of the image there is some text with a weird formation in the successive page. Can someone help me?

```<code> \documentclass[a4paper,14pt]{extarticle}
  \usepackage{geometry}
     \usepackage[latin1]{inputenc}
   \usepackage{amsmath}
 \usepackage{amsfonts}
 \usepackage{amssymb}
 \usepackage{graphicx}
 \usepackage{subcaption}
 \usepackage{multicol}
\usepackage[english]{babel}
   \usepackage{graphicx,bm,times}
 \usepackage{mathtools}
 \usepackage{subcaption}
 \usepackage{wrapfig}
 \usepackage{siunitx}
 \usepackage{gensymb}
 \usepackage{amsmath}
 \usepackage{geometry}
  %\geometry{lmargin=1in,rmargin=1in}
   ...
   to suppress axial growth during GaInP shell growth, the nanowire cores were taken out from the reactor and the Au seed particles were removed using a cyanide based Au etchant. Shell growth was carried out in the same MOCVD as the core, using PH3, (TMIn), and TMGa as precursors gases.The shell growth temperature was set to 600 $\textdegree $C.

  \begin{wrapfigure}{l}{0.25\textwidth}
 \includegraphics[width=6cm,height=7cm]{IMAGES/nanos1.png}
%\caption{Caption1}
\label{fig:wrapfig}
\end{wrapfigure}
Transmission electron microscopy \textbf{TEM} and Electron Diffraction Spectroscopy \textbf{SEM} allow to investigate nanowires revealing its crystal structure: pure zinc blende, (without wurtzite segments, stacking faults, or twins).  Particularly high-resolution transmission electron microscopy showed dense fringes indicating significant strain (Fig A).
</code>```

答:
you could add an extra option to the wrapfigure command:

```<code>\begin{wrapfigure}[22]{L}{0.45\textwidth}
</code>```

where the '22' represents the number of lines you want to wrap around.

Body:
I am using overleaf online to compile my report and I am experiencing this problem with wrap figure. particularly over a weight of 6cm I experience the problem as shown in figure, image overlaps the text while independent on the size of the image there is some text with a weird formation in the successive page. Can someone help me?

 \documentclass[a4paper,14pt]{extarticle}
  \usepackage{geometry}
     \usepackage[latin1]{inputenc}
   \usepackage{amsmath}
 \usepackage{amsfonts}
 \usepackage{amssymb}
 \usepackage{graphicx}
 \usepackage{subcaption}
 \usepackage{multicol}
\usepackage[english]{babel}
   \usepackage{graphicx,bm,times}
 \usepackage{mathtools}
 \usepackage{subcaption}
 \usepackage{wrapfig}
 \usepackage{siunitx}
 \usepackage{gensymb}
 \usepackage{amsmath}
 \usepackage{geometry}
  %\geometry{lmargin=1in,rmargin=1in}
   ...
   to suppress axial growth during GaInP shell growth, the nanowire cores were taken out from the reactor and the Au seed particles were removed using a cyanide based Au etchant. Shell growth was carried out in the same MOCVD as the core, using PH3, (TMIn), and TMGa as precursors gases.The shell growth temperature was set to 600 $\textdegree $C.

  \begin{wrapfigure}{l}{0.25\textwidth}
 \includegraphics[width=6cm,height=7cm]{IMAGES/nanos1.png}
%\caption{Caption1}
\label{fig:wrapfig}
\end{wrapfigure}
Transmission electron microscopy \textbf{TEM} and Electron Diffraction Spectroscopy \textbf{SEM} allow to investigate nanowires revealing its crystal structure: pure zinc blende, (without wurtzite segments, stacking faults, or twins).  Particularly high-resolution transmission electron microscopy showed dense fringes indicating significant strain (Fig A).

Body:
you could add an extra option to the wrapfigure command:

\begin{wrapfigure}[22]{L}{0.45\textwidth}

where the '22' represents the number of lines you want to wrap around.


问:
Purpose of mapDispatchToProps in Redux land
Is there a purpose to mapDispatchToProps:

```<code>const mapDispatchToProps = dispatch => {
  return {
    addProductToCart: product => dispatch(addProductToCart(product))
  }
}
</code>```

or is it acceptable to just do this:

```<code>const mapDispatchToProps = dispatch => {
  return {dispatch};
}
</code>```

and then just call:

props.dispatch() in the component

答:
mapDispatchToProps allows you to simply specify actions your component needs to dispatch. You may take this approach because it's more declarative (letting the mapDispatchToProps handle all the heavy lifting so you can easily call a function from your component) or perhaps you want to share the dispatch function with an unconnected redux component.

In fact, it is perfectly acceptable not to have a mapDispatchToProps function at all.

Additionally based on your example. Instead of doing the following:

```<code>const mapDispatchToProps = dispatch => {
  return {dispatch};
}
</code>```

You could simply exclude the mapDispatchToProps function from the connect method like so:

```<code>connect(mapStateToProps)(MyComponent)
</code>```

Then do the following in your component:

```<code>props.dispatch({ type: 'MY_ACTION' })}
</code>```

Body:
Is there a purpose to mapDispatchToProps:

const mapDispatchToProps = dispatch => {
  return {
    addProductToCart: product => dispatch(addProductToCart(product))
  }
}

or is it acceptable to just do this:

const mapDispatchToProps = dispatch => {
  return {dispatch};
}

and then just call:

props.dispatch() in the component

Body:
mapDispatchToProps allows you to simply specify actions your component needs to dispatch. You may take this approach because it's more declarative (letting the mapDispatchToProps handle all the heavy lifting so you can easily call a function from your component) or perhaps you want to share the dispatch function with an unconnected redux component.

In fact, it is perfectly acceptable not to have a mapDispatchToProps function at all.

Additionally based on your example. Instead of doing the following:

const mapDispatchToProps = dispatch => {
  return {dispatch};
}

You could simply exclude the mapDispatchToProps function from the connect method like so:

connect(mapStateToProps)(MyComponent)

Then do the following in your component:

props.dispatch({ type: 'MY_ACTION' })}


问:
why do I have to cast when assigning
EarthquakeMarker is an abstract class that extends SimplePointMarker. OceanQuakeMarker extends EarthquakeMarker.

```<code>SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = pm;
</code>```

I read that this code wont compile because of the assignment of em = pm. However, pm has an "is-a" relationship with em, so I'm wondering why I have to cast it:

```<code>SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = (EarthquakeMarker) pm;
</code>```

Also, I'm wondering what happens to the functionality of em since it has been casted to the abstract parent class. Does it lose the functionality that the OceanQuakeMarker has?

答:
As per your explanation, given below is the hierarchy:

```<code>OceanQuakeMarker ▸ EarthquakeMarker ▸ SimplePointMarker
</code>```

In the code given below, you are trying to assign a reference of SimplePointMarker to that of EarthquakeMarker which voilates the OOP principle. While a child class reference can be assigned to that of a parent class, the reverse is not true.

```<code>SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = pm;
</code>```

The code given below is correct because you have cast the parent class reference to the child class reference.

```<code>SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = (EarthquakeMarker) pm;
</code>```

The following code also will compile successfully for the same reason:

```<code>OceanQuakeMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = pm;
</code>```

Title: why do I have to cast when assigning

Body:
EarthquakeMarker is an abstract class that extends SimplePointMarker. OceanQuakeMarker extends EarthquakeMarker.

SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = pm;

I read that this code wont compile because of the assignment of em = pm. However, pm has an "is-a" relationship with em, so I'm wondering why I have to cast it:

SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = (EarthquakeMarker) pm;

Also, I'm wondering what happens to the functionality of em since it has been casted to the abstract parent class. Does it lose the functionality that the OceanQuakeMarker has?

Body:
As per your explanation, given below is the hierarchy:

OceanQuakeMarker ▸ EarthquakeMarker ▸ SimplePointMarker

In the code given below, you are trying to assign a reference of SimplePointMarker to that of EarthquakeMarker which voilates the OOP principle. While a child class reference can be assigned to that of a parent class, the reverse is not true.

SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = pm;

The code given below is correct because you have cast the parent class reference to the child class reference.

SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = (EarthquakeMarker) pm;

The following code also will compile successfully for the same reason:

OceanQuakeMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = pm;


问:
Rich Text Editor Is Not Working in umbraco8
body text formats(Rich Text Editor) not working. It is not showing formatting bar after adding to a document type. </p>

答:
There are three different text editors in Umbraco:

Textbox (no format options)

Textarea (no format options)

Rich Text Editor

Have you selected either 1 or 2, then there's no format options. You can choose which format options to work with in the RTE by selecting the options in the configuration.


问:
Merging maps in Gremlin
I'm trying to write a single query that satisfies two requirements in the response object:

Must include all properties of a vertex, without specifying individual fields in the query.

Must flatten results at the same level on the object.

As separate queries, I can do:

1. valueMap query

```<code>g.V(1)
.valueMap().by(unfold()).fold()
</code>```

Response:

{
  "property1": "value1",
  "property2": "value2"
}
```

<h3>2. <code>project</code> query</h3>

```g.V(1)
.project("projectedProperty")
.by(out("X").valueMap().by(unfold()).fold())
```

<p>Response:</p>

<pre class="lang-json prettyprint-override"><code>{
  "projectedProperty": "value",
}
</code>```

Combined query

I've attempted to use a union to combine these results:

```<code>g.V(1)
.union(
  valueMap().by(unfold()).fold(), // Query 1
  project("projectedField").by(out("X").valueMap().by(unfold()).fold()) // Query 2
).fold()
</code>```

Response:

{
  [
    {
      "property1": "value1",
      "property2": "value2"
    },
    {
      "projectedProperty": "value"
    }
  ]
}
```

<p>This union approach relies on me putting a fold at the end, which in turn doesn't merge/flatten the two maps properly. Expected response is:</p>

<pre class="lang-json prettyprint-override"><code>{
  "property1": "value1",
  "property2": "value2",
  "projectedProperty": "value"
}
</code>```

Is there a better way to accomplish this task of merging/flattening two maps in the response object?

答:
The typical pattern is to unfold() your maps to entries (keys/values) then group() them back together as one:

```<code>gremlin> g.V().has('person','name','marko').
......1>   union(project('count').by(outE().count()), elementMap()).
......2>   unfold().
......3>   group().by(keys).by(select(values))
==>[count:3,name:marko,label:person,id:1,age:29]
</code>```

Title: Merging maps in Gremlin

Body:
I'm trying to write a single query that satisfies two requirements in the response object:

Must include all properties of a vertex, without specifying individual fields in the query.

Must flatten results at the same level on the object.

As separate queries, I can do:

1. valueMap query

g.V(1)
.valueMap().by(unfold()).fold()

Response:

{
  "property1": "value1",
  "property2": "value2"
}

2. project query

g.V(1)
.project("projectedProperty")
.by(out("X").valueMap().by(unfold()).fold())

Response:

{
  "projectedProperty": "value",
}

Combined query

I've attempted to use a union to combine these results:

g.V(1)
.union(
  valueMap().by(unfold()).fold(), // Query 1
  project("projectedField").by(out("X").valueMap().by(unfold()).fold()) // Query 2
).fold()

Response:

{
  [
    {
      "property1": "value1",
      "property2": "value2"
    },
    {
      "projectedProperty": "value"
    }
  ]
}

This union approach relies on me putting a fold at the end, which in turn doesn't merge/flatten the two maps properly. Expected response is:

{
  "property1": "value1",
  "property2": "value2",
  "projectedProperty": "value"
}

Is there a better way to accomplish this task of merging/flattening two maps in the response object?

Body:
The typical pattern is to unfold() your maps to entries (keys/values) then group() them back together as one:

gremlin> g.V().has('person','name','marko').
......1>   union(project('count').by(outE().count()), elementMap()).
......2>   unfold().
......3>   group().by(keys).by(select(values))
==>[count:3,name:marko,label:person,id:1,age:29]


问:
want to download images from server
I want to transfer site from shared hosting server to dedicated server.current server has folder,which includes approx. 16000 images...we can not use FTP to download these much images.and i do not have SSH rights? how can i download images from this shared hosting server.</p>

答:
Zip them all, adapted from http://davidwalsh.name/create-zip-php</p>

```<code>    <?php

        function create_zip($files = array(),$destination = '',$overwrite = false) {
          //if the zip file already exists and overwrite is false, return false
          if(file_exists($destination) && !$overwrite) { return false; }
          //vars
          $valid_files = array();
          //if files were passed in...
          if(is_array($files)) {
            //cycle through each file
            foreach($files as $file) {
              //make sure the file exists
              if(file_exists($file)) {
                $valid_files[] = $file;
              }
            }
          }
          //if we have good files...
          if(count($valid_files)) {
            //create the archive
            $zip = new ZipArchive();
            if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
              return false;
            }
            //add the files
            foreach($valid_files as $file) {
              $zip->addFile($file,$file);
            }
            //debug
            //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

            //close the zip -- done!
            $zip->close();

            //check to make sure the file exists
            return file_exists($destination);
          }
          else
          {
            return false;
          }
        }

    //glob images folder into an array
    foreach (glob("*.jpg") as $filename) {
        $files_to_zip[]='images/'.$filename;
    }
    //create the zip
    $result = create_zip($files_to_zip,'my-images.zip');
    if($result==true){echo'<a href="my-images.zip">Download Images</a>';
}else{
echo'Could not create zip';}

    ?>
</code>```

Title: want to download images from server

Body:
Zip them all, adapted from http://davidwalsh.name/create-zip-php

    <?php

        function create_zip($files = array(),$destination = '',$overwrite = false) {
          //if the zip file already exists and overwrite is false, return false
          if(file_exists($destination) && !$overwrite) { return false; }
          //vars
          $valid_files = array();
          //if files were passed in...
          if(is_array($files)) {
            //cycle through each file
            foreach($files as $file) {
              //make sure the file exists
              if(file_exists($file)) {
                $valid_files[] = $file;
              }
            }
          }
          //if we have good files...
          if(count($valid_files)) {
            //create the archive
            $zip = new ZipArchive();
            if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
              return false;
            }
            //add the files
            foreach($valid_files as $file) {
              $zip->addFile($file,$file);
            }
            //debug
            //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

            //close the zip -- done!
            $zip->close();

            //check to make sure the file exists
            return file_exists($destination);
          }
          else
          {
            return false;
          }
        }

    //glob images folder into an array
    foreach (glob("*.jpg") as $filename) {
        $files_to_zip[]='images/'.$filename;
    }
    //create the zip
    $result = create_zip($files_to_zip,'my-images.zip');
    if($result==true){echo'<a href="my-images.zip">Download Images</a>';
}else{
echo'Could not create zip';}

    ?>


问:
.map() function and deleting a row from a table with ReactJS
I'm having a problem wrapping my head around the .map() function as it relates to ReactJS. In practice, I have a table onto which I can add rows, but deleting a row by passing the index of the row is just not working. Here's what I have; can anyone clear up what I'm doing wrong?

```<code>import React from 'react';
import { render } from 'react-dom';

class CommentList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            comments: []
        };
        this.handleCommentDelete = this.handleCommentDelete.bind(this);
    }
    handleCommentDelete(i) {
        alert('i = ' + i);
        let comments = [...this.state.comments];
        comments.splice(i, 1);
        this.setState({
            comments: comments
        });
    }
    render() {
        return (
            <table className="commentList">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>Email</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    {
                        this.props.data.map((comment, i) => {
                            return (
                                <tr className="comment" key={i}>
                                    <td className="commentId">{comment.Id}</td>
                                    <td className="commentName">{comment.Name}</td>
                                    <td className="commentPhone">{comment.Phone}</td>
                                    <td className="commentEmail">{comment.Email}</td>
                                    <td className="commentCRUD">
                                        <a onClick={(i) => this.handleCommentDelete(i)}>
                                            <i className="fa fa-trash" />
                                        </a>
                                    </td>
                                </tr>
                            );
                        })
                    }
                </tbody>
            </table>
        );
    }
}

export default CommentList;

</code>```

Thanks in advance!

答:
You are passing the index i, not the right way. Also i would prefer to pass id rather than index. Here is how you can do that:

import React from 'react';
import { render } from 'react-dom';

class CommentList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            comments: []
        };
        this.handleCommentDelete = this.handleCommentDelete.bind(this);
    }
    handleCommentDelete(id) {
        let comments = this.state.comments.filter(comment => comment.id !== id);
        this.setState({
            comments: comments
        });
    }
    render() {
        return (

                        Name
                        Phone
                        Email

                    {
                        this.props.data.map(comment => {
                            return (

                                    {comment.Id}
                                    {comment.Name}
                                    {comment.Phone}
                                    {comment.Email}

                                         this.handleCommentDelete(comment.Id)}>

                            );
                        })
                    }

        );
    }
}

export default CommentList;
```

Hope this works for you.

Body:
I'm having a problem wrapping my head around the .map() function as it relates to ReactJS. In practice, I have a table onto which I can add rows, but deleting a row by passing the index of the row is just not working. Here's what I have; can anyone clear up what I'm doing wrong?

import React from 'react';
import { render } from 'react-dom';

class CommentList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            comments: []
        };
        this.handleCommentDelete = this.handleCommentDelete.bind(this);
    }
    handleCommentDelete(i) {
        alert('i = ' + i);
        let comments = [...this.state.comments];
        comments.splice(i, 1);
        this.setState({
            comments: comments
        });
    }
    render() {
        return (

                        Name
                        Phone
                        Email

                    {
                        this.props.data.map((comment, i) => {
                            return (

                                    {comment.Id}
                                    {comment.Name}
                                    {comment.Phone}
                                    {comment.Email}

                                         this.handleCommentDelete(i)}>

                            );
                        })
                    }

        );
    }
}

export default CommentList;

Thanks in advance!

Body:
You are passing the index i, not the right way. Also i would prefer to pass id rather than index. Here is how you can do that:

import React from 'react';
import { render } from 'react-dom';

class CommentList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            comments: []
        };
        this.handleCommentDelete = this.handleCommentDelete.bind(this);
    }
    handleCommentDelete(id) {
        let comments = this.state.comments.filter(comment => comment.id !== id);
        this.setState({
            comments: comments
        });
    }
    render() {
        return (
            <table className="commentList">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>Email</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    {
                        this.props.data.map(comment => {
                            return (
                                <tr className="comment" key={comment.Id}>
                                    <td className="commentId">{comment.Id}</td>
                                    <td className="commentName">{comment.Name}</td>
                                    <td className="commentPhone">{comment.Phone}</td>
                                    <td className="commentEmail">{comment.Email}</td>
                                    <td className="commentCRUD">
                                        <a onClick={() => this.handleCommentDelete(comment.Id)}>
                                            <i className="fa fa-trash" />
                                        </a>
                                    </td>
                                </tr>
                            );
                        })
                    }
                </tbody>
            </table>
        );
    }
}

export default CommentList;

Hope this works for you.