问:
How to check entered all values are white spaces or not?
I have a problem with validation in textField.
if I enter all values in textField are white space, it should throw a validation error when i pressed submit button.
I tried to resolve with isEmpty but not working. </p>

```<code>TextFormField textField(BuildContext context) {
    return TextFormField(
        maxLines: 10,
        minLines: 6,
        controller: _noteTextController,
        decoration: InputDecoration(
            border: OutlineInputBorder(
              borderRadius:
                  BorderRadius.circular(screenAwareSize(3, 6, context)),
              gapPadding: 0,
            ),
            hintText: 'Enter Note'),
        onSaved: (value) {
          //store your value here
        },
        validator: (value) {
          if (value.isEmpty) {
            return 'Notes can\'t be empty';
          } else {
            return null;
          }
        });
  }
</code>```

答:
Trim the value before checking.

```<code>validator: (value) {
  if (value.trim().isEmpty)
    return "Notes can't be empty";

  return null;
}
</code>```

(This was also suggested by Harsha Pulikollu as a comment, not sure why it wasn't added as an answer)

Body:
I have a problem with validation in textField.
if I enter all values in textField are white space, it should throw a validation error when i pressed submit button.
I tried to resolve with isEmpty but not working.

TextFormField textField(BuildContext context) {
    return TextFormField(
        maxLines: 10,
        minLines: 6,
        controller: _noteTextController,
        decoration: InputDecoration(
            border: OutlineInputBorder(
              borderRadius:
                  BorderRadius.circular(screenAwareSize(3, 6, context)),
              gapPadding: 0,
            ),
            hintText: 'Enter Note'),
        onSaved: (value) {
          //store your value here
        },
        validator: (value) {
          if (value.isEmpty) {
            return 'Notes can\'t be empty';
          } else {
            return null;
          }
        });
  }

Body:
Trim the value before checking.

validator: (value) {
  if (value.trim().isEmpty)
    return "Notes can't be empty";

  return null;
}

(This was also suggested by Harsha Pulikollu as a comment, not sure why it wasn't added as an answer)


来源: stackexchange

问:
Best way to get rid of hungarian notation?
Let's say you've inherited a C# codebase that uses one class with 200 static methods to provide core functionality (such as database lookups). Of the many nightmares in that class, there's copious use of Hungarian notation (the bad kind).

Would you refactor the variable names to remove the Hungarian notation, or would you leave them alone?

If you chose to change all the variables to remove Hungarian notation, what would be your method?

答:
If you're gonna break code just for the sake of refactoring, I would seriously consider leaving i alone, specially, if you are going to affect other people in your team who may be depending on that code.

If your team is OK with this refactoring, and investing your time in doing this (which may be a time-saver in the future, if it means the code is more readable/maintainable), use Visual Studio (or whatever IDE you are using) to help you refactor the code.

However, if a big change like this is not a risk your team/boss is willing to take, I would suggest a somewhat unorthodox, half-way approach. Instead of doing all your refactoring in a single sweep, why not refactor sections of code (more specifically, functions) that need to be touched during normal maintenance? Over time, this slow refactoring will bring the code up to a cleaner state, at which point you can finish the refactoring process with a final sweep.

OwnerDisplayName: Robert S.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
django widget tweaks form control not action
when Making django board, I met the problem.

django version is 3.

I wanted form like this. but my code can't alert me  "This field is required"

But widget tweaks form-control wasn't working.

which part is problem?

My code is like this

```<code>{% extends 'base.html' %}

{% load widget_tweaks %}

{% block title %}Start a New Topic{% endblock %}

{% block breadcrumb %}
  <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li>
  <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li>
  <li class="breadcrumb-item active">New topic</li>
{% endblock %}

{% block content %}
  <form method="post" novalidate>
    {% csrf_token %}

    {% for field in form %}
      <div class="form-group">
        {{ field.label_tag }}

                {% if form.is_bound %}
        {% if field.errors %}

          {% render_field field class="form-control is-invalid" %}
          {% for error in field.errors %}
            <div class="invalid-feedback">
              {{ error }}
            </div>
          {% endfor %}

        {% else %}
          {% render_field field class="form-control is-valid" %}
        {% endif %}
      {% else %}
        {% render_field field class="form-control" %}
      {% endif %}

      {% if field.help_text %}
        <small class="form-text text-muted">
          {{ field.help_text }}
        </small>
      {% endif %}
    </div>
  {% endfor %}

  <button type="submit" class="btn btn-success">Post</button>
</form>
{% endblock %}
</code>```

答:
just change your code to blow with proper indent</p>

```<code>{% load widget_tweaks %}
{% block title %}Start a New Topic{% endblock %}
{% block breadcrumb %}
  <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li>
  <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li>
  <li class="breadcrumb-item active">New topic</li>
{% endblock %}

{% block content %}
<form method="post" novalidate>
    {% csrf_token %}

    {% for field in form %}
      <div class="form-group">
        {{ field.label_tag }}

        {% if form.is_bound %}
          {% if field.errors %}

            {% render_field field class="form-control is-invalid" %}
            {% for error in field.errors %}
              <div class="invalid-feedback">
                {{ error }}
              </div>
            {% endfor %}

          {% else %}
            {% render_field field class="form-control is-valid" %}
          {% endif %}
        {% else %}
          {% render_field field class="form-control" %}
        {% endif %}

        {% if field.help_text %}
          <small class="form-text text-muted">
            {{ field.help_text }}
          </small>
        {% endif %}
      </div>
    {% endfor %}

    <button type="submit" class="btn btn-success">Post</button>
  </form>
{% endblock %}```
</code>```

ContentLicense: CC BY-SA 4.0

Body:
when Making django board, I met the problem.

django version is 3.

I wanted form like this. but my code can't alert me  "This field is required"

But widget tweaks form-control wasn't working.

which part is problem?

My code is like this

{% extends 'base.html' %}

{% load widget_tweaks %}

{% block title %}Start a New Topic{% endblock %}

{% block breadcrumb %}

Boards

{{ board.name }}

New topic

{% endblock %}

{% block content %}
  <form method="post" novalidate>
    {% csrf_token %}

    {% for field in form %}

        {{ field.label_tag }}

                {% if form.is_bound %}
        {% if field.errors %}

          {% render_field field class="form-control is-invalid" %}
          {% for error in field.errors %}

              {{ error }}

          {% endfor %}

        {% else %}
          {% render_field field class="form-control is-valid" %}
        {% endif %}
      {% else %}
        {% render_field field class="form-control" %}
      {% endif %}

      {% if field.help_text %}

          {{ field.help_text }}

      {% endif %}

  {% endfor %}

  <button type="submit" class="btn btn-success">Post</button>
</form>
{% endblock %}

Body:
just change your code to blow with proper indent

{% load widget_tweaks %}
{% block title %}Start a New Topic{% endblock %}
{% block breadcrumb %}
  <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li>
  <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li>
  <li class="breadcrumb-item active">New topic</li>
{% endblock %}

{% block content %}
<form method="post" novalidate>
    {% csrf_token %}

    {% for field in form %}
      <div class="form-group">
        {{ field.label_tag }}

        {% if form.is_bound %}
          {% if field.errors %}

            {% render_field field class="form-control is-invalid" %}
            {% for error in field.errors %}
              <div class="invalid-feedback">
                {{ error }}
              </div>
            {% endfor %}

          {% else %}
            {% render_field field class="form-control is-valid" %}
          {% endif %}
        {% else %}
          {% render_field field class="form-control" %}
        {% endif %}

        {% if field.help_text %}
          <small class="form-text text-muted">
            {{ field.help_text }}
          </small>
        {% endif %}
      </div>
    {% endfor %}

    <button type="submit" class="btn btn-success">Post</button>
  </form>
{% endblock %}```


问:
Room database in a Android library and Objects and Dao's in Android project
I want to implement Room database in my app, but I want to do that by creating a Library project.

Library project will store data
Android project will have the Objects and Dao's

Is this possible?

For this I have to implement Room in both Android project as well as Library

But can I have Dao's and Objects in Android project and Database in Library

Why I want to do this.
I want to build this feature in a generic way so that it can be used in my other project. Also Library will not just store the data, it will have some offline functionality which read a Offline data table and checks the internet connection and picks data from the table and send it to server.

None of this is implemented yet. I am in the process of thinking what is the right aproach

Thanks for your suggestions

R

答:
It's a great desire to move Room to the separate module as far it's Android specific and violates the principle of the Clean Architecture. Here is where you can start, at least it looks similar: another stack question and take a look at all the answers.

About re-usage, probably, it will be quite hard. Not sure, that time you spend to make it universal be less than when you implement it in each project. So, take the time in the account also.

The case where it makes sense.

At my company, we did the next. We have a few related products (a few apps) that have similar user-intended logic. So we have a library that takes care of all user login / token expiration logic and so on and it provides a simple interface for the app to handle user account. Single code base, useful when fixing bugs. And connect this library to each project as a general module. But still, each app has its own internet communication and database because of domain-specific data.

The best for testing and architecture - move all room and internet logic to the module in the app. Access it by interfaces. You can share that module between apps.


问:
Global styles for FontImageSource property
I have following button in my Xamarin Forms application

    <Button
        Grid.Column="1"
        Grid.Row="0">
        <Button.ImageSource>
            <FontImageSource Glyph="" FontFamily="{StaticResource IconFont}" Color="{StaticResource BaseColor}"/>
        </Button.ImageSource>
    </Button>
```
<p>where <code>IconFont</code> is:</p>
<pre class="lang-xml prettyprint-override"><code>    <OnPlatform x:TypeArguments="x:String" x:Key="IconFont">
        <On Platform="Android" Value="materialdesignicons-webfont.ttf#Material design" />
        <On Platform="iOS" Value="Material Design Icons" />
    </OnPlatform>
</code>```

Everything is working fine. Now, because all of my icons are in materialdesignicons-webfont and I will never use different icons I decided to move entire styling to App.xaml. I would like to set default properties like that:

```
<p>And use button by passing glyph only.</p>
<pre class="lang-xml prettyprint-override"><code>    <Button
        Grid.Column="1"
        Grid.Row="0">
        <Button.ImageSource>
            <FontImageSource Glyph=""/>
        </Button.ImageSource>
    </Button>
</code>```

For some reasons Icon is not rendered without specifying FontFamily and Color directly in FontImageSource. Am I missing something?

Is there some way to call my button in simpler way? F.e.

    <Button
        Grid.Column="1"
        Grid.Row="0"
        MDGlyph="" />
```

答:
have you tried this:

```

Body:
I have following button in my Xamarin Forms application

    <Button
        Grid.Column="1"
        Grid.Row="0">
        <Button.ImageSource>
            <FontImageSource Glyph="" FontFamily="{StaticResource IconFont}" Color="{StaticResource BaseColor}"/>
        </Button.ImageSource>
    </Button>

where IconFont is:

    <OnPlatform x:TypeArguments="x:String" x:Key="IconFont">
        <On Platform="Android" Value="materialdesignicons-webfont.ttf#Material design" />
        <On Platform="iOS" Value="Material Design Icons" />
    </OnPlatform>

Everything is working fine. Now, because all of my icons are in materialdesignicons-webfont and I will never use different icons I decided to move entire styling to App.xaml. I would like to set default properties like that:

And use button by passing glyph only.

    <Button
        Grid.Column="1"
        Grid.Row="0">
        <Button.ImageSource>
            <FontImageSource Glyph=""/>
        </Button.ImageSource>
    </Button>

For some reasons Icon is not rendered without specifying FontFamily and Color directly in FontImageSource. Am I missing something?

Is there some way to call my button in simpler way? F.e.

    <Button
        Grid.Column="1"
        Grid.Row="0"
        MDGlyph="" />

Body:
have you tried this:

    <Style x:Key="ButtonWithFontImageSource" TargetType="Button">
       <Setter Property="ImageSource">
            <FontImageSource
                FontFamily="{StaticResource FontIcons}"
                Glyph="{DynamicResource IconText}">
            </FontImageSource>
        <Setter>
    </Style>


问:
Why isnt my Android module Activity found in Merged AndroidManifest from Main App?
My current Android Application has a main App and multiple UI modules,

I am trying to start a UI module Activity from my main App as follows...

```<code> activity.startActivity(Intent().setClassName(it.screen.packageName(), it.screen.className()))
</code>```

the exception I see is

```<code> android.content.ActivityNotFoundException: Unable to find explicit activity class {org.research.development.ui_module_a/org.research.development.ui_module_a.ModuleAScreenOneActivity}; have you declared this activity in your AndroidManifest.xml?
</code>```

I thought all AndroidManifiest files were merged into one, so surely at runtime theres one manifest file and it will hold all activities?

Is it not possible to start a module Activity using package name and class name as strings?

Is my only option to use Action Intent filters?

答:
I thought all AndroidManifiest files were merged into one, so surely at runtime theres one manifest file and it will hold all activities?

They are. You can check this on Android Studio by opening your main manifest file (usually located under app/) and selecting the "merged manifest" tab.

It's likely that you're not setting the class name and package name correctly. To illustrate, let's say I have the app module (the main one) and another module, mymodule. The app module depends on this one. Let's also say this is a debug build and we have the ".debug" suffix configured. In this case the values would be

```<code>package = "com.mypackage.debug"
classname = "com.mypackage.somethingonmymodule.MyActivity"
</code>```

So the package should be your app's package as seen by the OS (and defined in the end manifest that's bundled with the apk) and the class name the fully qualified package as you define it in your codebase. Both these values should be visible in the merged manifest view (as mentioned above).

Alternatively, if the app module depends on mymodule, you can build your Intent in a different way:

```<code>Intent(context, MyActivity::class.java)
</code>```

Body:
My current Android Application has a main App and multiple UI modules,

I am trying to start a UI module Activity from my main App as follows...

 activity.startActivity(Intent().setClassName(it.screen.packageName(), it.screen.className()))

the exception I see is

 android.content.ActivityNotFoundException: Unable to find explicit activity class {org.research.development.ui_module_a/org.research.development.ui_module_a.ModuleAScreenOneActivity}; have you declared this activity in your AndroidManifest.xml?

I thought all AndroidManifiest files were merged into one, so surely at runtime theres one manifest file and it will hold all activities?

Is it not possible to start a module Activity using package name and class name as strings?

Is my only option to use Action Intent filters?

Body:
I thought all AndroidManifiest files were merged into one, so surely at runtime theres one manifest file and it will hold all activities?

They are. You can check this on Android Studio by opening your main manifest file (usually located under app/) and selecting the "merged manifest" tab.

It's likely that you're not setting the class name and package name correctly. To illustrate, let's say I have the app module (the main one) and another module, mymodule. The app module depends on this one. Let's also say this is a debug build and we have the ".debug" suffix configured. In this case the values would be

package = "com.mypackage.debug"
classname = "com.mypackage.somethingonmymodule.MyActivity"

So the package should be your app's package as seen by the OS (and defined in the end manifest that's bundled with the apk) and the class name the fully qualified package as you define it in your codebase. Both these values should be visible in the merged manifest view (as mentioned above).

Alternatively, if the app module depends on mymodule, you can build your Intent in a different way:

Intent(context, MyActivity::class.java)


问:
split a string without adjacent characters that matched regex in java
i am first to this site.
I want to split a string without the characters that matched in regex of string split method in java.

The string for splitting is (for eg.) : "conditional&&operator and ampersand&Symbol."

My regex-expression for spit is : "[^\\&]\\&[^\\&]"

My expectation is : [conditional&&operator and ampersand, Symbol]

But, the output is : [conditional&&operator and *ampersan, ymbol*]

The code i used is:

```<code>String s = "conditional&&operator and ampersand&Symbol.";
String[] sarr = s.split("[^\\&]\\&[^\\&]");
System.out.println(Arrays.toString(sarr));
</code>```

So, please tell me what regex i should use to get the expected output, that is without the additional characters removed.

答:
I suppose it's impossible to split your string by regex as you wish.
The problem is that [^\\&]\\&[^\\&] matches 3 characters -> d&S and it splits by 3 characters, so you have them removed.
You can use Pattern and Matcher to split a string in this way:

```<code>    String s = "conditional&&operator and ampersand&Symbol.";
    final Matcher matcher = Pattern.compile("[^&]&[^&]").matcher(s);
    if (matcher.find()) {
        final int indexOfMatchStart = matcher.start();
        final String firstPart = s.substring(0, indexOfMatchStart + 1); // + 1 to include first symbol of RegEx
        final String secondPart = s.substring(indexOfMatchStart + 2); // + 2  to skip &
        System.out.println(firstPart + secondPart); // will print conditional&&operator and ampersandSymbol.
    }
</code>```

Body:
i am first to this site.
I want to split a string without the characters that matched in regex of string split method in java.

The string for splitting is (for eg.) : "conditional&&operator and ampersand&Symbol."

My regex-expression for spit is : "[^\\&]\\&[^\\&]"

My expectation is : [conditional&&operator and ampersand, Symbol]

But, the output is : [conditional&&operator and *ampersan, ymbol*]

The code i used is:

String s = "conditional&&operator and ampersand&Symbol.";
String[] sarr = s.split("[^\\&]\\&[^\\&]");
System.out.println(Arrays.toString(sarr));

So, please tell me what regex i should use to get the expected output, that is without the additional characters removed.

Body:
I suppose it's impossible to split your string by regex as you wish.
The problem is that [^\\&]\\&[^\\&] matches 3 characters -> d&S and it splits by 3 characters, so you have them removed.
You can use Pattern and Matcher to split a string in this way:

    String s = "conditional&&operator and ampersand&Symbol.";
    final Matcher matcher = Pattern.compile("[^&]&[^&]").matcher(s);
    if (matcher.find()) {
        final int indexOfMatchStart = matcher.start();
        final String firstPart = s.substring(0, indexOfMatchStart + 1); // + 1 to include first symbol of RegEx
        final String secondPart = s.substring(indexOfMatchStart + 2); // + 2  to skip &
        System.out.println(firstPart + secondPart); // will print conditional&&operator and ampersandSymbol.
    }


问:
Cucumber Integration Tests with Spring Boot
I have been looking over countless posts on here and other sites to no avail.

I am attempting to run my cucumber integration tests against a running, local version of my spring boot app as part of my CI pipeline. I am constantly getting "Connection Refused" which would lead you to believe the app isn't starting up, however, if I try to start my app up normally using the port provided when the tests are at a breakpoint, it will tell me this port is already being used.

pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.busybee</groupId>
    <artifactId>backend</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>backend</name>
    <description>Busy Bees backend API</description>

    <properties>
        <java.version>1.8</java.version>
        <cucumber-version>1.2.5</cucumber-version>
        <unit-tests.skip>false</unit-tests.skip>
        <integration-tests.skip>false</integration-tests.skip>
    </properties>

    <profiles>
        <!-- The Configuration of the unit profile. This is the default profile -->
        <profile>
            <id>unit-test</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <build.profile.id>unit-test</build.profile.id>
                <skip.integration.tests>true</skip.integration.tests>
                <skip.unit.tests>false</skip.unit.tests>
            </properties>
        </profile>
        <!-- The Configuration of the integration-test profile -->
        <profile>
            <id>integration-test</id>
            <properties>
                <build.profile.id>integration-test</build.profile.id>
                <skip.integration.tests>false</skip.integration.tests>
                <skip.unit.tests>true</skip.unit.tests>
            </properties>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>5.0.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java8</artifactId>
            <version>5.0.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>5.0.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-spring</artifactId>
            <version>5.0.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.197</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!-- Run *Test.java tests as unit tests during test phase  -->
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.21.0</version>
                <configuration>
                    <skipTests>${skip.unit.tests}</skipTests>
                </configuration>
            </plugin>

            <!-- Run *IT.java tests as integration tests during verify phase -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.21.0</version>
                <configuration>
                    <skipTests>${skip.integration.tests}</skipTests>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

BackendApplication

```<code>@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
@EnableJpaRepositories
public class BackendApplication {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public static void main(String[] args) {
        final SpringApplication springApplication =
                new SpringApplication(BackendApplication.class);
        // it is being added here for LOCAL run ONLY , spring profiles should be be run time parameters when run spring boot jar
        springApplication.setDefaultProperties(Collections.singletonMap("spring.profiles.default","LOCAL"));
        springApplication.addListeners(new ApplicationPidFileWriter());
        springApplication.run(args);
    }

}
</code>```

Step defintions

```<code>public class GetNodeSteps extends CucumberBase {
    ResponseEntity<Location> responseLoc;

    @Before("@BeforeCreateLocation")
    public void create_existing_location() throws Throwable {
        Location location = generateLocation();

        responseLoc = template.postForEntity("/location/register", location, Location.class);
        if (responseLoc.getStatusCodeValue() == HttpStatus.BAD_REQUEST.value()) {
            fail("Couldn't create location");
        }
    }
//Rest of steps omitted
</code>```

CucumberBase

```<code>@SpringBootTest(classes = BackendApplication.class, webEnvironment = RANDOM_PORT)
@ContextConfiguration
public class CucumberBase {
    @Autowired
    public TestRestTemplate template;

    @LocalServerPort
    public int randomServerPort;

    @Before
    public void contextLoads() throws Exception {
    }

}
</code>```

FeaturesIT

```<code>@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/features", glue = {"com.busybee.backend.integration"})
public class FeaturesIT {
}
</code>```

Stack trace

```<code>
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.4.RELEASE)

2020-05-27 17:49:49.787  INFO 20488 --- [           main] c.b.backend.integration.GetNodeSteps     : Starting GetNodeSteps on Rob-Desktop with PID 20488 (started by Robert in C:\dir)
2020-05-27 17:49:49.791  INFO 20488 --- [           main] c.b.backend.integration.GetNodeSteps     : The following profiles are active: test
2020-05-27 17:49:50.630  INFO 20488 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-27 17:49:50.694  INFO 20488 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 56ms. Found 4 JPA repository interfaces.
2020-05-27 17:49:51.183  INFO 20488 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-05-27 17:49:51.757  INFO 20488 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 0 (http)
2020-05-27 17:49:51.765  INFO 20488 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-05-27 17:49:51.766  INFO 20488 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-05-27 17:49:51.882  INFO 20488 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-05-27 17:49:51.882  INFO 20488 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2037 ms
2020-05-27 17:49:52.110  INFO 20488 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-27 17:49:52.184  INFO 20488 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.4.10.Final}
2020-05-27 17:49:52.323  INFO 20488 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-05-27 17:49:52.449  INFO 20488 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-05-27 17:49:52.601  INFO 20488 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-05-27 17:49:52.626  INFO 20488 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-05-27 17:49:53.369  INFO 20488 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-27 17:49:53.375  INFO 20488 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-27 17:49:53.967  WARN 20488 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-05-27 17:49:54.199  INFO 20488 --- [           main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [springfox.documentation.swagger2.web.Swagger2Controller#getDocumentation(String, HttpServletRequest)]
2020-05-27 17:49:54.391  INFO 20488 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-27 17:49:54.439  INFO 20488 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page template: index
2020-05-27 17:49:54.728  INFO 20488 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2020-05-27 17:49:54.749  INFO 20488 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2020-05-27 17:49:54.774  INFO 20488 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2020-05-27 17:49:54.982  INFO 20488 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 58500 (http) with context path ''
2020-05-27 17:49:54.985  INFO 20488 --- [           main] c.b.backend.integration.GetNodeSteps     : Started GetNodeSteps in 5.609 seconds (JVM running for 6.852)

Step failed
org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:58500/location/register": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:751)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677)
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:452)
    at org.springframework.boot.test.web.client.TestRestTemplate.postForEntity(TestRestTemplate.java:457)
    at com.busybee.backend.integration.GetNodeSteps.create_existing_location(GetNodeSteps.java:48)

</code>```

Appreciate any help that can be given, thanks.

答:
I managed to figure it out, my H2 db wasn't being created by the  SpringBootTestApplication as my test properties had:

spring.jpa.hibernate.ddl-auto=update

When it needed to be:

spring.jpa.hibernate.ddl-auto=create

Body:
I have been looking over countless posts on here and other sites to no avail.

I am attempting to run my cucumber integration tests against a running, local version of my spring boot app as part of my CI pipeline. I am constantly getting "Connection Refused" which would lead you to believe the app isn't starting up, however, if I try to start my app up normally using the port provided when the tests are at a breakpoint, it will tell me this port is already being used.

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.busybee</groupId>
    <artifactId>backend</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>backend</name>
    <description>Busy Bees backend API</description>

    <properties>
        <java.version>1.8</java.version>
        <cucumber-version>1.2.5</cucumber-version>
        <unit-tests.skip>false</unit-tests.skip>
        <integration-tests.skip>false</integration-tests.skip>
    </properties>

    <profiles>

        <profile>
            <id>unit-test</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <build.profile.id>unit-test</build.profile.id>
                <skip.integration.tests>true</skip.integration.tests>
                <skip.unit.tests>false</skip.unit.tests>
            </properties>
        </profile>

        <profile>
            <id>integration-test</id>
            <properties>
                <build.profile.id>integration-test</build.profile.id>
                <skip.integration.tests>false</skip.integration.tests>
                <skip.unit.tests>true</skip.unit.tests>
            </properties>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>5.0.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java8</artifactId>
            <version>5.0.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>5.0.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-spring</artifactId>
            <version>5.0.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.197</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.21.0</version>
                <configuration>
                    <skipTests>${skip.unit.tests}</skipTests>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.21.0</version>
                <configuration>
                    <skipTests>${skip.integration.tests}</skipTests>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

BackendApplication

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
@EnableJpaRepositories
public class BackendApplication {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public static void main(String[] args) {
        final SpringApplication springApplication =
                new SpringApplication(BackendApplication.class);
        // it is being added here for LOCAL run ONLY , spring profiles should be be run time parameters when run spring boot jar
        springApplication.setDefaultProperties(Collections.singletonMap("spring.profiles.default","LOCAL"));
        springApplication.addListeners(new ApplicationPidFileWriter());
        springApplication.run(args);
    }

}

Step defintions

public class GetNodeSteps extends CucumberBase {
    ResponseEntity<Location> responseLoc;

    @Before("@BeforeCreateLocation")
    public void create_existing_location() throws Throwable {
        Location location = generateLocation();

        responseLoc = template.postForEntity("/location/register", location, Location.class);
        if (responseLoc.getStatusCodeValue() == HttpStatus.BAD_REQUEST.value()) {
            fail("Couldn't create location");
        }
    }
//Rest of steps omitted

CucumberBase

@SpringBootTest(classes = BackendApplication.class, webEnvironment = RANDOM_PORT)
@ContextConfiguration
public class CucumberBase {
    @Autowired
    public TestRestTemplate template;

    @LocalServerPort
    public int randomServerPort;

    @Before
    public void contextLoads() throws Exception {
    }

}

FeaturesIT

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/features", glue = {"com.busybee.backend.integration"})
public class FeaturesIT {
}

Stack trace

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.4.RELEASE)

2020-05-27 17:49:49.787  INFO 20488 --- [           main] c.b.backend.integration.GetNodeSteps     : Starting GetNodeSteps on Rob-Desktop with PID 20488 (started by Robert in C:\dir)
2020-05-27 17:49:49.791  INFO 20488 --- [           main] c.b.backend.integration.GetNodeSteps     : The following profiles are active: test
2020-05-27 17:49:50.630  INFO 20488 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-27 17:49:50.694  INFO 20488 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 56ms. Found 4 JPA repository interfaces.
2020-05-27 17:49:51.183  INFO 20488 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-05-27 17:49:51.757  INFO 20488 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 0 (http)
2020-05-27 17:49:51.765  INFO 20488 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-05-27 17:49:51.766  INFO 20488 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-05-27 17:49:51.882  INFO 20488 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-05-27 17:49:51.882  INFO 20488 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2037 ms
2020-05-27 17:49:52.110  INFO 20488 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-27 17:49:52.184  INFO 20488 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.4.10.Final}
2020-05-27 17:49:52.323  INFO 20488 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-05-27 17:49:52.449  INFO 20488 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-05-27 17:49:52.601  INFO 20488 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-05-27 17:49:52.626  INFO 20488 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-05-27 17:49:53.369  INFO 20488 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-27 17:49:53.375  INFO 20488 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-27 17:49:53.967  WARN 20488 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-05-27 17:49:54.199  INFO 20488 --- [           main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [springfox.documentation.swagger2.web.Swagger2Controller#getDocumentation(String, HttpServletRequest)]
2020-05-27 17:49:54.391  INFO 20488 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-27 17:49:54.439  INFO 20488 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page template: index
2020-05-27 17:49:54.728  INFO 20488 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2020-05-27 17:49:54.749  INFO 20488 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2020-05-27 17:49:54.774  INFO 20488 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2020-05-27 17:49:54.982  INFO 20488 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 58500 (http) with context path ''
2020-05-27 17:49:54.985  INFO 20488 --- [           main] c.b.backend.integration.GetNodeSteps     : Started GetNodeSteps in 5.609 seconds (JVM running for 6.852)

Step failed
org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:58500/location/register": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:751)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677)
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:452)
    at org.springframework.boot.test.web.client.TestRestTemplate.postForEntity(TestRestTemplate.java:457)
    at com.busybee.backend.integration.GetNodeSteps.create_existing_location(GetNodeSteps.java:48)

Appreciate any help that can be given, thanks.


问:
trouble getting my create-react-app to render on heroku
I have my react-app working totally fine on my localhost server, and I tried deploying it onto Heroku. However when I go to my app address I got from Heroku I am met with a blank page. None of the components or anything is being rendered. Any ideas why? I will post my server.js and App.js below or if there is anything else I can post to help figure this out let me know. Am I just linking something wrong so the components aren't being included in my builds index.html or is something else happening?

import React from 'react';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import "./styles.css";
import Home from './Home';
import Locations from './Locations';
import ContactForm from './Contact';
import NoMatch from './NoMatch';
import AboutUs from './AboutUs';
import Menu from './Menu';
import { NavigationBar } from './components/NavBar';

function App() {

  return (
    <React.Fragment>
      <NavigationBar />

        <Router>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/aboutus" component={AboutUs} />
            <Route path="/locations" component={Locations} />
            <Route path="/contact" component={ContactForm} />
            <Route path="/menu" component={Menu} />
            <Route component={NoMatch} />
          </Switch>
        </Router>

    </React.Fragment>
  );
}

export default App;```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const express = require('express')
const path = require('path')
const app = express()

app.use(express.static(path.join(__dirname, 'build')));

app.get('/*', function (req, res) {
   res.sendFile(path.join(__dirname, 'build', 'index.html'));
 });

app.listen(process.env.PORT || 5000)</code>```

Any help would be appreciated. You can look at the deployed page by going to https://desolate-river-56657.herokuapp.com/ if that helps at all as well. The only other thing I can think would be causing this is a wrong file structure where the components just aren't being included or something like that.

答:
if you are deploying your backend and frontend together then you need to write heroko post build script in backend package.json</p>

```<code>"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix ../FRONTEND FOLDER_NAME && npm run build --prefix npm start --prefix ../FRONTEND FOLDER_NAME"
</code>```

Body:
I have my react-app working totally fine on my localhost server, and I tried deploying it onto Heroku. However when I go to my app address I got from Heroku I am met with a blank page. None of the components or anything is being rendered. Any ideas why? I will post my server.js and App.js below or if there is anything else I can post to help figure this out let me know. Am I just linking something wrong so the components aren't being included in my builds index.html or is something else happening?

import React from 'react';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import "./styles.css";
import Home from './Home';
import Locations from './Locations';
import ContactForm from './Contact';
import NoMatch from './NoMatch';
import AboutUs from './AboutUs';
import Menu from './Menu';
import { NavigationBar } from './components/NavBar';

function App() {

  return (
    <React.Fragment>
      <NavigationBar />

        <Router>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/aboutus" component={AboutUs} />
            <Route path="/locations" component={Locations} />
            <Route path="/contact" component={ContactForm} />
            <Route path="/menu" component={Menu} />
            <Route component={NoMatch} />
          </Switch>
        </Router>

    </React.Fragment>
  );
}

export default App;

const express = require('express')
const path = require('path')
const app = express()

app.use(express.static(path.join(__dirname, 'build')));

app.get('/*', function (req, res) {
   res.sendFile(path.join(__dirname, 'build', 'index.html'));
 });

app.listen(process.env.PORT || 5000)

Any help would be appreciated. You can look at the deployed page by going to https://desolate-river-56657.herokuapp.com/ if that helps at all as well. The only other thing I can think would be causing this is a wrong file structure where the components just aren't being included or something like that.

Body:
if you are deploying your backend and frontend together then you need to write heroko post build script in backend package.json

"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix ../FRONTEND FOLDER_NAME && npm run build --prefix npm start --prefix ../FRONTEND FOLDER_NAME"


问:
Issue with delete triggers - SQL Server 2005
I have two fields, LastModifiedBy and DateLastModified in a SQL table. Using ADO.net, I am modifying these fields and calling AcceptChanges function to commit these changes to the dataset (not to the database). I am then calling the Delete function on the datarow. I then call the Update function on the adapter. Technically, the datarow now has values in the two fields mentioned above and they are committed to the dataset, but the SQL Server delete trigger still shows that the values in these fields is null. How can this be?

Regards,
Santosh

答:
Because of several issues:

You modify fields and then calling AcceptChanges = datasets thinks that these data were saved to database but they didn't!

You delete the row but deletion doesn't cause changes to be passed to the database. It simply calls delete for the current state of the row in the database.

So you must divide the operation into two steps:

Modify fields and Update changes to the database - it will write fields to the record

Delete row and Update changes to the database - it will delete record with already passed fields

Make this in single transaction.


问:
How do I find element in object typescript code
So, am trying to assign colours to my icons dynamically ... but this line of code keeps complaining,

```<code>let icon = iconsList[name];
</code>```

When I hover of it .. This is the explanation "

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ heart: string; star: string; like: string; dislike: string; flash: string; marker: string; filter: string; user: string; circle: string; hashtag: string; calendar: string; chevronLeft: string; optionsV: string; optionsH: string; chat: string; explore: string; }'.
    No index signature with a parameter of type 'string' was found on type '{ heart: string; star: string; like: string; dislike: string; flash: string; marker: string; filter: string; user: string; circle: string; hashtag: string; calendar: string; chevronLeft: string; optionsV: string; optionsH: string; chat: string; explore: string; }'.ts(7053)

interface Props{
    name:string,
}

const Icon = ({ name }:Props) => {
    const iconsList = {
      heart: '',
      star: '',
      like: '',
      dislike: '',
      flash: '',
      marker: '',
      filter: '',
      user: '',
      circle: '',
      hashtag: '',
      calendar: '',
      chevronLeft: '',
      optionsV: '',
      optionsH: '',
      chat: '',
      explore: ''
    };

    let icon = iconsList[name];
    icon = icon.substr(3);
    icon = String.fromCharCode(parseInt(icon, 16));

    return icon;
  };

  export default Icon;
  ```

ScreenShot of the code in Vscode On line 25, am trying to pick the specific icon color but it complains

答:
So according to OliverRadini this how you can implement it if am following him in the correct way.

Icon.ts file

```<code>const iconsList = {
    heart: '',
    star: '',
    like: '',
    dislike: '',
    flash: '',
    marker: '',
    filter: '',
    user: '',
    circle: '',
    hashtag: '',
    calendar: '',
    chevronLeft: '',
    optionsV: '',
    optionsH: '',
    chat: '',
    explore: ''
};

interface Props{
    name: keyof typeof iconsList;
}

const Icon = ({ name }:Props) => {
    const path = <T>(o: T) => (k: keyof T) => o[k];

    const getIcon = path(iconsList);
    const x = getIcon(name); // works
    return x;
 };

export default Icon;
</code>```

Then how to reuse the icon on the

test.tsx file

```<code>import React from 'react';
import { Text, View } from 'react-native';
import Icon from './Icon';

interface Props {
}

const TestComponent = ({}: Props) => {
  return (
    <View style={styles.containerTest}>
      <View style={styles.testView}>
        <Text style={styles.testText}>
          <Icon name="heart" /> Test icon
        </Text>
      </View>
    </View>
  );
};

export default TestComponent;
</code>```

Body:
So, am trying to assign colours to my icons dynamically ... but this line of code keeps complaining,

let icon = iconsList[name];

When I hover of it .. This is the explanation "

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ heart: string; star: string; like: string; dislike: string; flash: string; marker: string; filter: string; user: string; circle: string; hashtag: string; calendar: string; chevronLeft: string; optionsV: string; optionsH: string; chat: string; explore: string; }'.
    No index signature with a parameter of type 'string' was found on type '{ heart: string; star: string; like: string; dislike: string; flash: string; marker: string; filter: string; user: string; circle: string; hashtag: string; calendar: string; chevronLeft: string; optionsV: string; optionsH: string; chat: string; explore: string; }'.ts(7053)

interface Props{
    name:string,
}

const Icon = ({ name }:Props) => {
    const iconsList = {
      heart: '',
      star: '',
      like: '',
      dislike: '',
      flash: '',
      marker: '',
      filter: '',
      user: '',
      circle: '',
      hashtag: '',
      calendar: '',
      chevronLeft: '',
      optionsV: '',
      optionsH: '',
      chat: '',
      explore: ''
    };

    let icon = iconsList[name];
    icon = icon.substr(3);
    icon = String.fromCharCode(parseInt(icon, 16));

    return icon;
  };

  export default Icon;

ScreenShot of the code in Vscode On line 25, am trying to pick the specific icon color but it complains

Body:
So according to OliverRadini this how you can implement it if am following him in the correct way.

Icon.ts file

const iconsList = {
    heart: '&#xe800;',
    star: '&#xe801;',
    like: '&#xe800;',
    dislike: '&#xe802;',
    flash: '&#xe803;',
    marker: '&#xf031;',
    filter: '&#xf0b0;',
    user: '&#xf061;',
    circle: '&#xf039;',
    hashtag: '&#xf029;',
    calendar: '&#xf4c5;',
    chevronLeft: '&#xf004;',
    optionsV: '&#xf142;',
    optionsH: '&#xf141;',
    chat: '&#xf4ac;',
    explore: '&#xf50d;'
};

interface Props{
    name: keyof typeof iconsList;
}

const Icon = ({ name }:Props) => {
    const path = <T>(o: T) => (k: keyof T) => o[k];

    const getIcon = path(iconsList);
    const x = getIcon(name); // works
    return x;
 };

export default Icon;

Then how to reuse the icon on the

test.tsx file

import React from 'react';
import { Text, View } from 'react-native';
import Icon from './Icon';

interface Props {
}

const TestComponent = ({}: Props) => {
  return (
    <View style={styles.containerTest}>
      <View style={styles.testView}>
        <Text style={styles.testText}>
          <Icon name="heart" /> Test icon
        </Text>
      </View>
    </View>
  );
};

export default TestComponent;


问:
Set but no Reset of Modbus Coils with ajax
I'm using ajax to create a modbus connection an write coils. My Problem is that i can set coils as true but not false..

Side to call from Browser:

```<code>    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Startseite</title>
    <link rel="stylesheet" href="./style.css">
    <script src="jquery-latest.js" type="text/javascript"></script>
    <script type="text/javascript">
        // Beispiel ähnlich https://www.lima-city.de/thread/jquery-alle-x-sekunden-div-neu-laden-load

        var datei2load1 = "raum_1_content.php";  // --- zu ladende PHP Datei
        var sek2load = 0.5;              // --- alle x Sekunden!

        $(document).ready(function() {
            $.ajaxSetup ({
                cache: false
            });

            $("#refresh1").load(datei2load1);
            setInterval(function() {
                $('#refresh1').load(datei2load1);
            }, (sek2load * 1000));
        });

        function swichting(regitser, value) { // Beispiel ähnlich: https://stackoverflow.com/questions/39110915/use-ajax-to-run-php-script-with-button-click
            $.ajax({
                type: 'POST',
                url: 'example_fc16_send.php',
                data: "register=" + register + "&value=" + value
            });

        }

        function writecoil(coil, value) { // Beispiel ähnlich: https://stackoverflow.com/questions/39110915/use-ajax-to-run-php-script-with-button-click
            $.ajax({
                type: 'POST',
                url: 'example_fc15_send.php',
                data: "coil=" + coil + "&value=" + value
            });

        }

    </script>

</head>
<body >
<?php
    echo "<div id='refresh1'></div>";
?>
</code>```

PHP write function

```<code><?php

$register = $_POST[coil];
$value = $_POST[value];

//$value = (isset($_POST[value]);

echo "Coil: " + $coil + "; ";
echo "Value" + $value + ";";
require_once dirname(__FILE__) . '/phpmodbus/ModbusMaster.php';

// Create Modbus object
$modbus = new ModbusMaster("192.168.188.33", "TCP");

// Data to be writen
$data = array($value);
$dataTypes = array("BOOL");

try {
    // FC15
    $modbus->writeMultipleCoils(1, $register, $data);
}
catch (Exception $e) {
    // Print error information if any
    echo $modbus;
    echo $e;
    exit;
}

// Print status information
//echo $modbus;

?>
</code>```

Side to display with onclick event (writing "true" works..."false" works not)

```<code><?php
    require_once dirname(__FILE__) . '/phpmodbus/ModbusMaster.php';

    // Create Modbus object
    $modbus = new ModbusMaster("192.168.188.33", "TCP");

    try {
        // FC 3
        $recDataCmd = $modbus->readMultipleRegisters(1, 12288, 16); // Command Array lesen
        $recDataState = $modbus->readMultipleRegisters(1, 12288, 16); // Status Array lesen
    }
    catch (Exception $e) {
        // Print error information if any
        echo $modbus;
        echo $e;
        exit;
    }

    echo '
    <main>
    <div id="txt_seitentitel2"><font size = "+3" color="white" face="Arial">STARTSEITE</font></div>
     <div id="backgroundstartseite"></div>
    <a href="./Beleuchtung.html"><div id="but_bel_beleuchtung"></div></a>
    <a href="./Beschattung.html"><div id="but_bel_beschattung"></div></a>
    <a href="./Klima.html"><div id="but_bel_klima"></div></a>

        <!-- Beleuchtung Szenenauswahl -->
    <div id="but_bel_raum_ein" onclick="writecoil(Coil = 3, Value = true)"></div>
    <div id="txt_raum_ein"><font size = "+2" color="white" face="Arial">RAUM EIN</p></font></div>

    <div id="but_bel_raum_aus" onclick="writecoil(Coil = 3, Value = false)"></div>
    <div id="txt_raum_aus"><font size = "+2" color="white" face="Arial">RAUM AUS</p></font></div>

    <div id="but_bel_szene_1"></div>
    <div id="txt_szene_1"><font size = "+2" color="white" face="Arial">SZENE 1</p></font></div>

    <div id="but_bel_szene_2"></div>
    <div id="txt_szene_2"><font size = "+2" color="white" face="Arial">SZENE 2</p></font></div>

    <div id="fld_status_bel"></div>

    <div id="fld_status_szene_1" ></div>

    <div id="fld_status_szene_2"></div>

    </main>
    ';
?>
</code>```

I'm checking the connection with Modbus Poll..I can set every coil to true but not to false. If i set them back to false in Modbus Poll, i can set them true again from my html page.

答:
You probably need to convert the string value to boolean.

```<code>$data = array(boolval($value));
</code>```

https://www.php.net/manual/en/function.boolval.php

The values in your post data will be strings, which without explicitly parsing them, will evaluate to true.

https://www.php.net/manual/en/types.comparisons.php

Body:
I'm using ajax to create a modbus connection an write coils. My Problem is that i can set coils as true but not false..

Side to call from Browser:

    <!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Startseite</title>
    <link rel="stylesheet" href="./style.css">

<?php
    echo "

";
?>

PHP write function

<?php

$register = $_POST[coil];
$value = $_POST[value];

//$value = (isset($_POST[value]);

echo "Coil: " + $coil + "; ";
echo "Value" + $value + ";";
require_once dirname(__FILE__) . '/phpmodbus/ModbusMaster.php';

// Create Modbus object
$modbus = new ModbusMaster("192.168.188.33", "TCP");

// Data to be writen
$data = array($value);
$dataTypes = array("BOOL");

try {
    // FC15
    $modbus->writeMultipleCoils(1, $register, $data);
}
catch (Exception $e) {
    // Print error information if any
    echo $modbus;
    echo $e;
    exit;
}

// Print status information
//echo $modbus;

?>

Side to display with onclick event (writing "true" works..."false" works not)

<?php
    require_once dirname(__FILE__) . '/phpmodbus/ModbusMaster.php';

    // Create Modbus object
    $modbus = new ModbusMaster("192.168.188.33", "TCP");

    try {
        // FC 3
        $recDataCmd = $modbus->readMultipleRegisters(1, 12288, 16); // Command Array lesen
        $recDataState = $modbus->readMultipleRegisters(1, 12288, 16); // Status Array lesen
    }
    catch (Exception $e) {
        // Print error information if any
        echo $modbus;
        echo $e;
        exit;
    }

    echo '

STARTSEITE

RAUM EIN

RAUM AUS

SZENE 1

SZENE 2

    ';
?>

I'm checking the connection with Modbus Poll..I can set every coil to true but not to false. If i set them back to false in Modbus Poll, i can set them true again from my html page.

Body:
You probably need to convert the string value to boolean.

$data = array(boolval($value));

https://www.php.net/manual/en/function.boolval.php

The values in your post data will be strings, which without explicitly parsing them, will evaluate to true.

https://www.php.net/manual/en/types.comparisons.php


问:
How can I wait for an item to become visible, then disappear?
I need to write a pure JavaScript function (no jQuery) that will:
1. Wait for a DOC element to become visible.
2. Wait for the same element to then become invisible.
Here is my current attempt:

```<code>var checkVisible = setInterval(function() {
    var el = document.getElementById('submitBusy');
    var style = window.getComputedStyle(el);
    /* See if element is visible. */
    if (style.display !== 'none') {
        clearInterval(checkVisible);

        var checkInvisible = setInterval(function() {
            var el = document.getElementById('submitBusy');
            var style = window.getComputedStyle(el);
            /* See if element is visible. */
            if (style.display === 'none') {
                clearInterval(checkInvisible);
            }
        }, 50);
    }
}, 50);
</code>```

On the page, when a certain button is clicked to load a table on the page, the following function is called:

```<code>function searchStart() {
    $("#submitBusy").css("display", "inline-block");
}
</code>```

once the page's contents are pulled from the server, the following is called:

```<code>function searchDone() {
    $("#submitBusy").css("display", "none");
}
</code>```

Once the "submitBusy" element is shown and then disappears, I then want to walk through all rows in the newly generated table so I need to know where to put that code.

Thanks for your help.

答:
A custom event might be a cleaner way to respond when the submitBusy element disappears.

If you want to try this way see the code (and comments) in the snippet below.

In this demo, the custom event, called removedEvent, bubbles up and is listened for by document, although any ancestor of submitBusy could just as easily have the eventListener attached instead.
(The button in the demo code is just there to simulate the completion of your table data loading.)

// Adds event listener to demo button to simulate end of loading
const removeBtn = document.querySelector("#removeBtn");
removeBtn.addEventListener("click", simulateEndOfLoading);

// Function that runs when table data is loaded
function simulateEndOfLoading() {
  const submitBusy = document.querySelector("#submitBusy");
  submitBusy.style.display = "none";
  submitBusy.dispatchEvent(removedEvent); // Triggers custom event
}

// Defines custom event
const removedEvent = new CustomEvent("removedEvent", {bubbles: true});

// Listens for custom event
document.addEventListener("removedEvent", respondToRemovedEvent);

// The #submitBusy element is gone, and we can respond accordingly
function respondToRemovedEvent(e){
  console.log("The thing happened")
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#removeBtn { box-shadow: 1px 1px grey; }
#submitBusy{ width: 15ch; margin-top: 1em; }</code>```

<button id="removeBtn">Simuate end of loading</button>

loading...
```

Body:
I need to write a pure JavaScript function (no jQuery) that will:
1. Wait for a DOC element to become visible.
2. Wait for the same element to then become invisible.
Here is my current attempt:

var checkVisible = setInterval(function() {
    var el = document.getElementById('submitBusy');
    var style = window.getComputedStyle(el);
    /* See if element is visible. */
    if (style.display !== 'none') {
        clearInterval(checkVisible);

        var checkInvisible = setInterval(function() {
            var el = document.getElementById('submitBusy');
            var style = window.getComputedStyle(el);
            /* See if element is visible. */
            if (style.display === 'none') {
                clearInterval(checkInvisible);
            }
        }, 50);
    }
}, 50);

On the page, when a certain button is clicked to load a table on the page, the following function is called:

function searchStart() {
    $("#submitBusy").css("display", "inline-block");
}

once the page's contents are pulled from the server, the following is called:

function searchDone() {
    $("#submitBusy").css("display", "none");
}

Once the "submitBusy" element is shown and then disappears, I then want to walk through all rows in the newly generated table so I need to know where to put that code.

Thanks for your help.

Body:
A custom event might be a cleaner way to respond when the submitBusy element disappears.

If you want to try this way see the code (and comments) in the snippet below.

In this demo, the custom event, called removedEvent, bubbles up and is listened for by document, although any ancestor of submitBusy could just as easily have the eventListener attached instead.
(The button in the demo code is just there to simulate the completion of your table data loading.)

// Adds event listener to demo button to simulate end of loading
const removeBtn = document.querySelector("#removeBtn");
removeBtn.addEventListener("click", simulateEndOfLoading);

// Function that runs when table data is loaded
function simulateEndOfLoading() {
  const submitBusy = document.querySelector("#submitBusy");
  submitBusy.style.display = "none";
  submitBusy.dispatchEvent(removedEvent); // Triggers custom event
}

// Defines custom event
const removedEvent = new CustomEvent("removedEvent", {bubbles: true});

// Listens for custom event
document.addEventListener("removedEvent", respondToRemovedEvent);

// The #submitBusy element is gone, and we can respond accordingly
function respondToRemovedEvent(e){
  console.log("The thing happened")
}

#removeBtn { box-shadow: 1px 1px grey; }
#submitBusy{ width: 15ch; margin-top: 1em; }

<button id="removeBtn">Simuate end of loading</button>
<div id="submitBusy">loading...</div>


问:
Rails : rake db:create mysql error
I am trying to setup a mysql database, but I am getting this error message:

```
rake db:create
(in /Users/yookd/Desktop/rails/blog)
WARNING: Global access to Rake DSL methods is deprecated.  Please Include
    ...  Rake::DSL into classes and modules which use the Rake DSL methods.
WARNING: DSL method Blog::Application#task called at /Library/Ruby/Gems/1.8/gems/railties-3.0.7/lib/rails/application.rb:215:in `initialize_tasks'
db/test.sqlite3 already exists
rake aborted!
uninitialized constant Mysql2

Tasks: TOP => db:create
(See full trace by running task with --trace)
```

Any assistance with this?
(following directions on http://guides.rubyonrails.org/getting_started.html)

EDIT:::

How can I use mysql as my database as opposed to sqlite?  In the gemfile, it explicitly states: gem 'sqlite'... do I need to replace that line with something like gem mysql?

答:
This is a known issue. See: Rails - rake db:create error

BUT note that Rake 0.9.1 has been released which supposedly fixes things. So first try upgrading rake with:

```<code>gem update rake
</code>```

And update your bundle:

```<code>bundle update rake
</code>```

Title: Rails : rake db:create mysql error

Body:
I am trying to setup a mysql database, but I am getting this error message:

rake db:create
(in /Users/yookd/Desktop/rails/blog)
WARNING: Global access to Rake DSL methods is deprecated.  Please Include
    ...  Rake::DSL into classes and modules which use the Rake DSL methods.
WARNING: DSL method Blog::Application#task called at /Library/Ruby/Gems/1.8/gems/railties-3.0.7/lib/rails/application.rb:215:in `initialize_tasks'
db/test.sqlite3 already exists
rake aborted!
uninitialized constant Mysql2

Tasks: TOP => db:create
(See full trace by running task with --trace)

Any assistance with this?
(following directions on http://guides.rubyonrails.org/getting_started.html)

EDIT:::

How can I use mysql as my database as opposed to sqlite?  In the gemfile, it explicitly states: gem 'sqlite'... do I need to replace that line with something like gem mysql?

Body:
This is a known issue. See: Rails - rake db:create error

BUT note that Rake 0.9.1 has been released which supposedly fixes things. So first try upgrading rake with:

gem update rake

And update your bundle:

bundle update rake


问:
remove special char from rows in pandas python
I have the following dataframe...unable to remove the "-" char and trim it to the right "int" number for the cell:

```<code>    Branch   Market Company     Brand Name  MRP 2020-05-15 2020-05-19 2020-05-22 2020-05-26
1      USA      abc     xqz           A     165    180-190    170-180        170        170
2      USA      abc     xqz           B     165    180-190    170-180        170        170
3      USA      abc     xqz           C     100        120    110-120        120        120
4      USA      abc     xqz           D      95        110        100        100        110
5      USA      abc     xqz           E      59         70         70         70         70

</code>```

want the following dataframe to plot a scatter plot with brand name in x-axis and MRP in y axis.

```<code>    Branch   Market Company     Brand Name  MRP 2020-05-15 2020-05-19 2020-05-22 2020-05-26
1      USA      abc     xqz           A     165        185        175        170        170
2      USA      abc     xqz           B     165        185        175        170        170
3      USA      abc     xqz           C     100        120        115        120        120
4      USA      abc     xqz           D      95        110        100        100        110
5      USA      abc     xqz           E      59         70         70         70         70

</code>```

can you plz help. tried many codes, but unable to get the desired result/df.

Body:
I have the following dataframe...unable to remove the "-" char and trim it to the right "int" number for the cell:

    Branch   Market Company     Brand Name  MRP 2020-05-15 2020-05-19 2020-05-22 2020-05-26
1      USA      abc     xqz           A     165    180-190    170-180        170        170
2      USA      abc     xqz           B     165    180-190    170-180        170        170
3      USA      abc     xqz           C     100        120    110-120        120        120
4      USA      abc     xqz           D      95        110        100        100        110
5      USA      abc     xqz           E      59         70         70         70         70

want the following dataframe to plot a scatter plot with brand name in x-axis and MRP in y axis.

    Branch   Market Company     Brand Name  MRP 2020-05-15 2020-05-19 2020-05-22 2020-05-26
1      USA      abc     xqz           A     165        185        175        170        170
2      USA      abc     xqz           B     165        185        175        170        170
3      USA      abc     xqz           C     100        120        115        120        120
4      USA      abc     xqz           D      95        110        100        100        110
5      USA      abc     xqz           E      59         70         70         70         70

can you plz help. tried many codes, but unable to get the desired result/df.

Body:
Let's try:

# extract the date columns
cols = [col for col in df.columns if '-' in col]

df[cols] = (df[cols].astype(str).stack()
     .str.extractall('(\d+)')
     .astype(float).mean(level=[0,1])[0]
     .unstack()
)

Output:

      Branch  Market    Company    Brand    Name      MRP    2020-05-15    2020-05-19    2020-05-22    2020-05-26
--  --------  --------  ---------  -------  ------  -----  ------------  ------------  ------------  ------------
 0         1  USA       abc        xqz      A         165          92.5          87.5            85            85
 1         2  USA       abc        xqz      B         165          92.5          87.5            85            85
 2         3  USA       abc        xqz      C         100          60            57.5            60            60
 3         4  USA       abc        xqz      D          95          55            50              50            55
 4         5  USA       abc        xqz      E          59          35            35              35            35


问:
TTF_RenderText_Solid(...) causes segmentation fault error
I'm trying to utilize a class Text to handle with text in my c++ SDL2-based program.

TTF_RenderText_Solid works perfectly in the main function, although in my classe Text, in this line here SDL_Surface *surface = TTF_RenderText_Solid( font, text.c_str(), fg );, it's causing some errors. Sometimes it gives me a segmentation fault error, sometimes it didn't.

I debugged the code and all the three variables, TTF_Font *font, std::string text and SDL_Color fg, were with theirs respective correct values.

My main function:

```<code>#include <iostream>

#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>

#include "Text.h"

int main()
{
    try
    {
        SDL_Init( SDL_INIT_VIDEO );
        TTF_Init();

        SDL_Window *window = SDL_CreateWindow( "Window", SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED, 800, 800, SDL_WINDOW_SHOWN );
        SDL_Renderer *renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED );

        TTF_Font *f = TTF_OpenFont( "cruft.ttf", 32 );
        SDL_Surface *s = TTF_RenderText_Solid( f, "Avocado", {0,0,0,255} );
        if(s == NULL)
            std::cout << "s == NULL\n";

        Text title;
        title = Text( renderer, "cruft.ttf", 32, "title" );
        title.render_Text_Solid( "Avocado", {0,0,0,255} );

        SDL_Quit();
        TTF_Quit();

        return 0;
    }
    catch( std::exception& e )
    {
        std::cerr << "Error: " << e.what() << "\n";
        return 0;
    }
    catch(...)
    {
        std::cerr << "Unkown error!\n";
        return 0;
    }
}
</code>```

My Text.cpp file:

```<code>#include <iostream>
#include <string.h>

#include "Text.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>

//Constructors
Text::Text(){}

Text::Text(SDL_Renderer *renderer, std::string file, int ptsize, std::string name)
{
    set_renderer( renderer );
    this->name = name;

    set_TTF_Font( file, ptsize );
}

Text::~Text()
{
    TTF_CloseFont( font );
    SDL_DestroyTexture( texture );
}

void Text::set_renderer( SDL_Renderer *renderer )
{
    if( renderer == NULL )
        throw std::runtime_error( name + ": Renderer could not be set! renderer == NULL\n" + SDL_GetError() );

    this->renderer = renderer;
}

void Text::set_TTF_Font( std::string file, int ptsize )
{
    TTF_CloseFont( font );
    font = NULL;
    SDL_DestroyTexture( texture );
    texture = NULL;
    width = 0;
    height = 0;

    if( file == "" )
        throw std::runtime_error( name + ": TTF_Font* could not be set! file == ""\n" + SDL_GetError() );
    if( ptsize <= 0 )
        throw std::runtime_error( name + ": TTF_Font* could not be set! ptsize <= 0\n" + SDL_GetError() );

    TTF_Font *font = TTF_OpenFont( file.c_str(), ptsize );

    if( font == NULL )
        throw std::runtime_error( name + ": TTF_Font* could not be set! font == NULL\n" + SDL_GetError() );

    this->font = font;
}

void Text::render_Text_Solid( std::string text, SDL_Color fg )
{
    SDL_DestroyTexture( texture );
    texture = NULL;
    width = 0;
    height = 0;

    SDL_Surface *surface = TTF_RenderText_Solid( font, text.c_str(), fg );

    if( surface == NULL )
        throw std::runtime_error( name + ": Text could not be created! surface == NULL\n" + SDL_GetError() );

    texture = SDL_CreateTextureFromSurface( renderer, surface );
    width = surface->w;
    height = surface->h;
    SDL_FreeSurface( surface );

    if( texture == NULL )
        throw std::runtime_error( name + ": Text could not be created! texture == NULL\n" + SDL_GetError() );
}
</code>```

My Text.h file:

```<code>#ifndef TEXT_H_INCLUDED
#define TEXT_H_INCLUDED

#include <iostream>

#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>

class Text
{
    public:

    //constructors
    Text();
    Text(SDL_Renderer *renderer, std::string file, int ptsize, std::string name);
    ~Text();

    void set_renderer( SDL_Renderer *renderer );
    void set_TTF_Font( std::string file, int ptsize );
    void render_Text_Solid( std::string text, SDL_Color fg );

    //render
    void render( int x, int y );
    void render( SDL_Rect *srcrect, SDL_Rect *dstrect );

    //variables
    int width = 0;
    int height = 0;

    private:
    SDL_Renderer *renderer = NULL;
    SDL_Texture *texture = NULL;
    TTF_Font *font = NULL;
    std::string name = "";

};

#endif // TEXT_H_INCLUDED
</code>```

PS: I utilizing Manjaro Linux and Codeblocks

答:
Let's first look at what these lines do:

```<code>    Text title;
    title = Text( renderer, "cruft.ttf", 32, "title" );
</code>```

First you create title, and initialise it with default constructor Text::Text(), which sets default values to its fields. Then you create a second Text (let's call it title1 for clarity) object with specialised constructor. Then you copy title1 to title - since no operator= is defined, default copy is generated. Now your title have the same values as title1. And title1.~Text() is invoked, killing your font.

What you have is your title.font still having its previous value, but it points to already closed font structure.

That could be avoided by not constructing temporary Text object - e.g. Text title = Text(.......) will not produce temporary object and copying. That's just a workaround, actual problem remains - your Text objects cannot be safely copied. There are many ways to approach this problem - like using some sort of unique_ptr wrappers or dropping destructors in favor of manual deinit method, etc..

Which brings us to next problem - if you solve your copying, you now can generate text surface and texture, but look at your exit code:

```<code>    Text title;
    // ... omitted
    SDL_Quit();
    TTF_Quit();
    return 0;
</code>```

You have your finalisation in reverse - you want to close font, drop textures, destroy renderer/window, then call TTF_Quit and SDL_Quit, but instead you have SDL_Quit(), TTF_Quit(), and only after that title.~Text() - will'll probably crash because SDL/TTF already finalised and you're not supposed to perform SDL calls after that. Of course that could also be solved, e.g. by enclosing your title into extra code block, but the amount of things to watch for becoming too large.

Body:
I'm trying to utilize a class Text to handle with text in my c++ SDL2-based program.

TTF_RenderText_Solid works perfectly in the main function, although in my classe Text, in this line here SDL_Surface *surface = TTF_RenderText_Solid( font, text.c_str(), fg );, it's causing some errors. Sometimes it gives me a segmentation fault error, sometimes it didn't.

I debugged the code and all the three variables, TTF_Font *font, std::string text and SDL_Color fg, were with theirs respective correct values.

My main function:

#include <iostream>

#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>

#include "Text.h"

int main()
{
    try
    {
        SDL_Init( SDL_INIT_VIDEO );
        TTF_Init();

        SDL_Window *window = SDL_CreateWindow( "Window", SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED, 800, 800, SDL_WINDOW_SHOWN );
        SDL_Renderer *renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED );

        TTF_Font *f = TTF_OpenFont( "cruft.ttf", 32 );
        SDL_Surface *s = TTF_RenderText_Solid( f, "Avocado", {0,0,0,255} );
        if(s == NULL)
            std::cout << "s == NULL\n";

        Text title;
        title = Text( renderer, "cruft.ttf", 32, "title" );
        title.render_Text_Solid( "Avocado", {0,0,0,255} );

        SDL_Quit();
        TTF_Quit();

        return 0;
    }
    catch( std::exception& e )
    {
        std::cerr << "Error: " << e.what() << "\n";
        return 0;
    }
    catch(...)
    {
        std::cerr << "Unkown error!\n";
        return 0;
    }
}

My Text.cpp file:

#include <iostream>
#include <string.h>

#include "Text.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>

//Constructors
Text::Text(){}

Text::Text(SDL_Renderer *renderer, std::string file, int ptsize, std::string name)
{
    set_renderer( renderer );
    this->name = name;

    set_TTF_Font( file, ptsize );
}

Text::~Text()
{
    TTF_CloseFont( font );
    SDL_DestroyTexture( texture );
}

void Text::set_renderer( SDL_Renderer *renderer )
{
    if( renderer == NULL )
        throw std::runtime_error( name + ": Renderer could not be set! renderer == NULL\n" + SDL_GetError() );

    this->renderer = renderer;
}

void Text::set_TTF_Font( std::string file, int ptsize )
{
    TTF_CloseFont( font );
    font = NULL;
    SDL_DestroyTexture( texture );
    texture = NULL;
    width = 0;
    height = 0;

    if( file == "" )
        throw std::runtime_error( name + ": TTF_Font* could not be set! file == ""\n" + SDL_GetError() );
    if( ptsize <= 0 )
        throw std::runtime_error( name + ": TTF_Font* could not be set! ptsize <= 0\n" + SDL_GetError() );

    TTF_Font *font = TTF_OpenFont( file.c_str(), ptsize );

    if( font == NULL )
        throw std::runtime_error( name + ": TTF_Font* could not be set! font == NULL\n" + SDL_GetError() );

    this->font = font;
}

void Text::render_Text_Solid( std::string text, SDL_Color fg )
{
    SDL_DestroyTexture( texture );
    texture = NULL;
    width = 0;
    height = 0;

    SDL_Surface *surface = TTF_RenderText_Solid( font, text.c_str(), fg );

    if( surface == NULL )
        throw std::runtime_error( name + ": Text could not be created! surface == NULL\n" + SDL_GetError() );

    texture = SDL_CreateTextureFromSurface( renderer, surface );
    width = surface->w;
    height = surface->h;
    SDL_FreeSurface( surface );

    if( texture == NULL )
        throw std::runtime_error( name + ": Text could not be created! texture == NULL\n" + SDL_GetError() );
}

My Text.h file:

#ifndef TEXT_H_INCLUDED
#define TEXT_H_INCLUDED

#include <iostream>

#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>

class Text
{
    public:

    //constructors
    Text();
    Text(SDL_Renderer *renderer, std::string file, int ptsize, std::string name);
    ~Text();

    void set_renderer( SDL_Renderer *renderer );
    void set_TTF_Font( std::string file, int ptsize );
    void render_Text_Solid( std::string text, SDL_Color fg );

    //render
    void render( int x, int y );
    void render( SDL_Rect *srcrect, SDL_Rect *dstrect );

    //variables
    int width = 0;
    int height = 0;

    private:
    SDL_Renderer *renderer = NULL;
    SDL_Texture *texture = NULL;
    TTF_Font *font = NULL;
    std::string name = "";

};

#endif // TEXT_H_INCLUDED

PS: I utilizing Manjaro Linux and Codeblocks

Body:
Let's first look at what these lines do:

    Text title;
    title = Text( renderer, "cruft.ttf", 32, "title" );

First you create title, and initialise it with default constructor Text::Text(), which sets default values to its fields. Then you create a second Text (let's call it title1 for clarity) object with specialised constructor. Then you copy title1 to title - since no operator= is defined, default copy is generated. Now your title have the same values as title1. And title1.~Text() is invoked, killing your font.

What you have is your title.font still having its previous value, but it points to already closed font structure.

That could be avoided by not constructing temporary Text object - e.g. Text title = Text(.......) will not produce temporary object and copying. That's just a workaround, actual problem remains - your Text objects cannot be safely copied. There are many ways to approach this problem - like using some sort of unique_ptr wrappers or dropping destructors in favor of manual deinit method, etc..

Which brings us to next problem - if you solve your copying, you now can generate text surface and texture, but look at your exit code:

    Text title;
    // ... omitted
    SDL_Quit();
    TTF_Quit();
    return 0;

You have your finalisation in reverse - you want to close font, drop textures, destroy renderer/window, then call TTF_Quit and SDL_Quit, but instead you have SDL_Quit(), TTF_Quit(), and only after that title.~Text() - will'll probably crash because SDL/TTF already finalised and you're not supposed to perform SDL calls after that. Of course that could also be solved, e.g. by enclosing your title into extra code block, but the amount of things to watch for becoming too large.


问:
Iterating over tf.Tensor is not allowed: AutoGraph is disabled in this function
I am using tensorflow 2.1 along with python 3.7

The following snippet of code is being used to build a tensorflow graph. The code runs without errors when executed as a standalone python script. (Probably tensorflow is running in eager mode? I am not sure.)

```<code>import tensorflow as tf
patches = tf.random.uniform(shape=(1, 10, 50, 300), dtype=tf.dtypes.float32)
s = tf.shape(patches)
patches = [patches[0][x][y] - tf.reduce_mean(patches[0][x][y]) for y in tf.range(s[2]) for x in tf.range(s[1])]
</code>```

However, the code fails when this is part of a tensorflow graph. I receive the following error:
tensorflow.

python.framework.errors_impl.OperatorNotAllowedInGraphError: iterating
  over tf.Tensor is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.

I also added the decorator @tf.function to the method which wraps the above lines of code. It didn't help. I am not sure if I fully understand the meaning of decorating with @tf.function. I also checked that this could be a problem with using python list comprehension inside the tensorflow graph. I am not sure how to use tf.map_fn or tf.while_loop for my case, since I have nested loops.

Thanks in advance!

答:
List comprehensions are not yet supported in autograph. The error that's raised needs to be improved, too. Piling up on https://github.com/tensorflow/tensorflow/issues/32546 should help resolve it sooner.

Until comprehensions are supported, you have to use map_fn, which in this case would look something like this:

```<code>def outer_comp(x):
  def inner_comp(y):
    return patches[0][x][y] - tf.reduce_mean(patches[0][x][y])
  return tf.map_fn(inner_comp, tf.range(s[2]), dtype=tf.float32)
patches = tf.map_fn(outer_comp, tf.range(s[1]), dtype=tf.float32)
</code>```

That said, I believe you can just use reduce_mean directly:

```<code>patches = patches - tf.expand_dims(tf.reduce_mean(patches, axis=3), -1)
</code>```

Body:
I am using tensorflow 2.1 along with python 3.7

The following snippet of code is being used to build a tensorflow graph. The code runs without errors when executed as a standalone python script. (Probably tensorflow is running in eager mode? I am not sure.)

import tensorflow as tf
patches = tf.random.uniform(shape=(1, 10, 50, 300), dtype=tf.dtypes.float32)
s = tf.shape(patches)
patches = [patches[0][x][y] - tf.reduce_mean(patches[0][x][y]) for y in tf.range(s[2]) for x in tf.range(s[1])]

However, the code fails when this is part of a tensorflow graph. I receive the following error:
tensorflow.

python.framework.errors_impl.OperatorNotAllowedInGraphError: iterating
  over tf.Tensor is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.

I also added the decorator @tf.function to the method which wraps the above lines of code. It didn't help. I am not sure if I fully understand the meaning of decorating with @tf.function. I also checked that this could be a problem with using python list comprehension inside the tensorflow graph. I am not sure how to use tf.map_fn or tf.while_loop for my case, since I have nested loops.

Thanks in advance!

Body:
List comprehensions are not yet supported in autograph. The error that's raised needs to be improved, too. Piling up on https://github.com/tensorflow/tensorflow/issues/32546 should help resolve it sooner.

Until comprehensions are supported, you have to use map_fn, which in this case would look something like this:

def outer_comp(x):
  def inner_comp(y):
    return patches[0][x][y] - tf.reduce_mean(patches[0][x][y])
  return tf.map_fn(inner_comp, tf.range(s[2]), dtype=tf.float32)
patches = tf.map_fn(outer_comp, tf.range(s[1]), dtype=tf.float32)

That said, I believe you can just use reduce_mean directly:

patches = patches - tf.expand_dims(tf.reduce_mean(patches, axis=3), -1)


问:
Font-size that expands when you resize the window
How do I make my font in HTML such that when I expand the window, the size of the text expands also. Sort of like setting a percentage for the text that will take on a percentage of the size of the box it is in.

Here is an illustration of what I would like to happen:

```<code>#box #text {
   font-size: 50%;
}
</code>```

Now lets say #box is 200px, #text should be 100px.
Obviously I can't just put a fix width for #text because in the site #box will be a dynamic width.

答:
Do it in jquery.</p>

```<code>$(window).resize(function(){
    $('#box #text').css('font-size',($(window).width()*0.5)+'px');
});
</code>```

Body:
How do I make my font in HTML such that when I expand the window, the size of the text expands also. Sort of like setting a percentage for the text that will take on a percentage of the size of the box it is in.

Here is an illustration of what I would like to happen:

#box #text {
   font-size: 50%;
}

Now lets say #box is 200px, #text should be 100px.
Obviously I can't just put a fix width for #text because in the site #box will be a dynamic width.

Body:
Do it in jquery.

$(window).resize(function(){
    $('#box #text').css('font-size',($(window).width()*0.5)+'px');
});