问:
How to texture a cylinder in XNA4 with multiple textures?
Basically, I'm trying to cover a slot machine reel (white cylinder model) with multiple evenly spaced textures around the exterior.  The program will be Windows only and the textures will be dynamically loaded at run-time instead of using the content pipeline. (Windows based multi-screen setup with XNA from the Microsoft example)

Most of the examples I can find online are for XNA3 and are still seemingly gibberish to me at this point.

So I'm looking for any help someone can provide on the subject of in-game texturing of objects like cylinders with multiple textures.

Maybe there is a good book out there that can properly describe how texturing works in XNA (4.0 specifically)?

Thanks

答:
You have a few options. It depends two things: whether the model is loaded or generated at runtime, and whether your multiple textures get combined into one or kept individual.

If you have art skills or know an artist, probably the easiest approach is to get them to texture map the cylinder with as many textures as you want (multiple materials). You'd want your Model to have one mesh (ModelMesh) and one material (ModelMeshPart) per texture required. This is assuming the cylinders always have a fixed number of textures!. Then, to swap the textures at runtime you'd iterate through the ModelMesh.Effects collection, cast each to a BasicEffect and set it's Texture property.

If you can't modify the model, you'll have to generate it. There's an example of this on the AppHub site: http://create.msdn.com/en-US/education/catalog/sample/primitives_3d. It probably does not generate texture coordinates so you'd need to add them. If you wanted 5 images per cylinder, you should make sure the number of segments is a multiple of 5 and the V coordinate should go from 0 to 1, 5 times as it wraps around the cylinder. To keep your textures individual with this technique, you'd need to draw the cylinder in 5 chunks, each time setting the GraphicsDevice.Textures[0] to your current texture.

With both techniques it would be possible to draw the cylinder in a single draw call, but you'd need to merge your textures into a single one using Texture2D.GetData and Texture2D.SetData. This is going to be more efficient, but really isn't worth the trouble. Well not unless you making some kind of crazy slot machine particle system anyway.


来源: stackexchange

问:
Python Plotly tips on how to set Z-axis to logscale
Greetings fellow humans,
What I wish to do is simply plot the 3d surface plots Z-scale (code below) as logarithmic scale. I've been looking at the official documentation for a bit now and I can't seem to find the "fig.update_xaxes(type="log")" equivalent for the Z scale. I've tried simply replacing the 1st 'x' with a 'z', but that resulted in an error:
File "/path/to/file.py", line 18, in
fig.update_zaxes(type="log")
AttributeError: 'Figure' object has no attribute 'update_zaxes'

Does anyone perhaps have some advice? The surface plot in 3D looks good, but it would look better in log-scale.

```<code>import plotly.graph_objects as go

import pandas as pd

z_data = pd.read_csv('data.csv',index_col=False)

y = z_data['1']
z = z_data.iloc[:,1:]

fig = go.Figure(data=[go.Surface(z=z, y=y)])
fig.update_layout(title='3D plot', autosize=False,
                  width=1880, height=1080,
                  margin=dict(l=65, r=50, b=65, t=90))
#fig.update_zaxes(type="log")
fig.write_image("data.png")
fig.show()
</code>```

Thank you to anyone trying to help!

答:
The axes of the 3D graph can be set using the scene. Since we didn't have any data, we added the log setting for the z-axis from the official reference example. setting dtick=1, the result will be 1,10,100,100.... For more details, please check this.

```<code>import plotly.graph_objects as go

import pandas as pd

# Read data from a csv
z_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv')

fig = go.Figure(data=[go.Surface(z=z_data.values)])

fig.update_layout(title='Mt Bruno Elevation', autosize=False,
                  width=500, height=500,
                  margin=dict(l=65, r=50, b=65, t=90))

fig.update_layout(scene=dict(zaxis=dict(dtick=1, type='log')))

fig.show()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Greetings fellow humans,
What I wish to do is simply plot the 3d surface plots Z-scale (code below) as logarithmic scale. I've been looking at the official documentation for a bit now and I can't seem to find the "fig.update_xaxes(type="log")" equivalent for the Z scale. I've tried simply replacing the 1st 'x' with a 'z', but that resulted in an error:
File "/path/to/file.py", line 18, in
fig.update_zaxes(type="log")
AttributeError: 'Figure' object has no attribute 'update_zaxes'

Does anyone perhaps have some advice? The surface plot in 3D looks good, but it would look better in log-scale.

import plotly.graph_objects as go

import pandas as pd

z_data = pd.read_csv('data.csv',index_col=False)

y = z_data['1']
z = z_data.iloc[:,1:]

fig = go.Figure(data=[go.Surface(z=z, y=y)])
fig.update_layout(title='3D plot', autosize=False,
                  width=1880, height=1080,
                  margin=dict(l=65, r=50, b=65, t=90))
#fig.update_zaxes(type="log")
fig.write_image("data.png")
fig.show()

Thank you to anyone trying to help!

Body:
The axes of the 3D graph can be set using the scene. Since we didn't have any data, we added the log setting for the z-axis from the official reference example. setting dtick=1, the result will be 1,10,100,100.... For more details, please check this.

import plotly.graph_objects as go

import pandas as pd

# Read data from a csv
z_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv')

fig = go.Figure(data=[go.Surface(z=z_data.values)])

fig.update_layout(title='Mt Bruno Elevation', autosize=False,
                  width=500, height=500,
                  margin=dict(l=65, r=50, b=65, t=90))

fig.update_layout(scene=dict(zaxis=dict(dtick=1, type='log')))

fig.show()


问:
In SwiftUI how can I animate a button offset when displayed
In SwiftUI, I want a button to appear from off screen by dropping in from the top into a final position when the view is initially displayed, I'm not asking for animation when the button is pressed.

I have tried:

```<code>Button(action: {}) {
    Text("Button")
}.offset(x: 0.0, y: 100.0).animation(.basic(duration: 5))
</code>```

but no joy.

答:
For those that do want to start from a Button that moves when you tap on it, try this:

```<code>import SwiftUI

struct ContentView : View {
    @State private var xLoc: CGFloat = 0

    var body: some View {
        Button("Tap me") {
            withAnimation(.linear(duration: 2)) { self.xLoc+=50.0 }
        }.offset(x: xLoc, y: 0.0)
    }

}
</code>```

Or alternatively (can replace Text with anything):

```<code>        Button(action: {
            withAnimation(.linear(duration: 2)) { self.xLoc+=50.0 }
            } )
        { Text("Tap me") }.offset(x: xLoc, y: 0.0)
</code>```

Body:
In SwiftUI, I want a button to appear from off screen by dropping in from the top into a final position when the view is initially displayed, I'm not asking for animation when the button is pressed.

I have tried:

Button(action: {}) {
    Text("Button")
}.offset(x: 0.0, y: 100.0).animation(.basic(duration: 5))

but no joy.

Body:
For those that do want to start from a Button that moves when you tap on it, try this:

import SwiftUI

struct ContentView : View {
    @State private var xLoc: CGFloat = 0

    var body: some View {
        Button("Tap me") {
            withAnimation(.linear(duration: 2)) { self.xLoc+=50.0 }
        }.offset(x: xLoc, y: 0.0)
    }

}

Or alternatively (can replace Text with anything):

        Button(action: {
            withAnimation(.linear(duration: 2)) { self.xLoc+=50.0 }
            } )
        { Text("Tap me") }.offset(x: xLoc, y: 0.0)


问:
Extending the Django Admin with images
django.db.models.Model defines an app_label which can be changed within a Model by appending:

```<code>class Meta:
   app_label = "something"
</code>```

Now I am trying to find a not too hacky/pythonic way to let each app have an image. I don't really want to break into the django contrib stuff, because that tends to get complicated.. Is it possible to do something within the package's __init__ file possibly?

Any hint would be welcome

答:
You shouldn't change app_label for model, this value is not only used for admin and changing it can break things badly.

If you want to change admin index page presentation then override the admin template (see https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#overriding-admin-templates ) and put the HTML and logic you want.

It may be easier to accomplish your task with django-admin-tools by creating custom dashboard module.

ContentLicense: CC BY-SA 3.0

Title: Extending the Django Admin with images

Body:
django.db.models.Model defines an app_label which can be changed within a Model by appending:

class Meta:
   app_label = "something"

Now I am trying to find a not too hacky/pythonic way to let each app have an image. I don't really want to break into the django contrib stuff, because that tends to get complicated.. Is it possible to do something within the package's __init__ file possibly?

Any hint would be welcome


问:
Leave-one out means by group in R
Imagine a table of individuals over time in different firms. I'm trying to compute for every individual the mean wage of their co-workers (ie the mean wage in their firm at time t excluding them). I have a working code using data.table in R which works, but I'm wondering whether there is a better, more efficient of doing this:</p>
```<code>foo <- data.table(
  i = rep(1:6, each = 2),
  t = rep(1:2, 6),
  f = rep(1:2, each = 6),
  w = 1:12
)

foo[, x := mean(foo[t == .BY$t & f == foo[i == .BY$i & t == .BY$t]$f & i != .BY$i]$w), by = .(i, t)]
</code>```

Title: Leave-one out means by group in R

Body:
Imagine a table of individuals over time in different firms. I'm trying to compute for every individual the mean wage of their co-workers (ie the mean wage in their firm at time t excluding them). I have a working code using data.table in R which works, but I'm wondering whether there is a better, more efficient of doing this:

foo <- data.table(
  i = rep(1:6, each = 2),
  t = rep(1:2, 6),
  f = rep(1:2, each = 6),
  w = 1:12
)

foo[, x := mean(foo[t == .BY$t & f == foo[i == .BY$i & t == .BY$t]$f & i != .BY$i]$w), by = .(i, t)]

Body:
We can calculate the LOO mean directly: sum all the wages, subtract the current row wage, divide by the number of rows minus 1.

foo[, loow := (sum(w) - w) / (.N - 1), by = .(f, t)]
#     i t f  w  x loow
#  1: 1 1 1  1  4    4
#  2: 1 2 1  2  5    5
#  3: 2 1 1  3  3    3
#  4: 2 2 1  4  4    4
#  5: 3 1 1  5  2    2
#  6: 3 2 1  6  3    3
#  7: 4 1 2  7 10   10
#  8: 4 2 2  8 11   11
#  9: 5 1 2  9  9    9
# 10: 5 2 2 10 10   10
# 11: 6 1 2 11  8    8
# 12: 6 2 2 12  9    9


问:
ReactJS app: I need to click a button twice to retrieve API call?
Hi guys Im building a weather app in React and I wanted to set the state variable "city" to the input value so that I can plug it back into the API URL but I had to click twice for the API to display properly. The first click returned "Error: Request failed with status code 400".

This is where I am getting the API from:

```<code>const URL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${APIKey}`;

</code>```

This is my API call:

```<code>  const getCity = () => {
    axios
      .get(URL)
      .then(function (response) {
        setWeatherData(response.data);
      })
      .catch(function (err) {
        console.warn(err);
      });
  };
</code>```

This is the function I was having trouble with...

```<code>  function handleChange() {
    const bar = document.getElementById("input-field").value;
    if (bar.indexOf(" ") > -1) {
      setCity(bar.split(" ").join("+"));
    } else {
      setCity(bar);
    }
  }
</code>```

This is the JSX:

```<code> <input
   id="input-field"
   className="searchbar"
   type="text"
   placeholder="Name of city (e.g. Austin"
  />
  <button
    className="searchbtn"
    onClick={() => {
      handleChange();
      getCity();
    }}
  >
    search
  </button>

</code>```

答:
The problem is that city and therefore URL are only evaluated at the next render, not immediately.

Remove getCity() from your onClick handler and add it in a useEffect() that depends on city

useEffect(() => {
  axios.get("https://api.openweathermap.org/data/2.5/weather", {
    params: {
      q: city,
      appid: APIKey
    }
  })
  .then(({ data }) => setWeatherData(data))
  .catch(console.warn)
}, [ city ])
```

Body:
Hi guys Im building a weather app in React and I wanted to set the state variable "city" to the input value so that I can plug it back into the API URL but I had to click twice for the API to display properly. The first click returned "Error: Request failed with status code 400".

This is where I am getting the API from:

const URL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${APIKey}`;

This is my API call:

  const getCity = () => {
    axios
      .get(URL)
      .then(function (response) {
        setWeatherData(response.data);
      })
      .catch(function (err) {
        console.warn(err);
      });
  };

This is the function I was having trouble with...

  function handleChange() {
    const bar = document.getElementById("input-field").value;
    if (bar.indexOf(" ") > -1) {
      setCity(bar.split(" ").join("+"));
    } else {
      setCity(bar);
    }
  }

This is the JSX:

 <input
   id="input-field"
   className="searchbar"
   type="text"
   placeholder="Name of city (e.g. Austin"
  />
  <button
    className="searchbtn"
    onClick={() => {
      handleChange();
      getCity();
    }}
  >
    search
  </button>


问:
The exe doesn't run
I used the following Java code for move the file form one directory to another, then execute the file in the destination directory. My code is

```<code>import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

import org.apache.commons.io.FileUtils;
public class JFileChooserTest {
  public static void main(String[] args) {
        String filelocation="C:\\Users\\FSSD\\Desktop\\OutPut\\Target";
        File trgDir = new File(filelocation);
        System.err
                .println("file location>>>>>>>>>>>>>>>>>>>"
                        + filelocation);
        File desDir = new File(
                "C:\\Users\\FSSD\\IndigoWorkSpace\\Swing\\test");

        try {
            FileUtils.copyDirectory(trgDir, desDir);
            // FileUtils.copyDirectory(srcDir, trgDir);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        Runtime rt=Runtime.getRuntime();
        try {
            Process p=rt.exec("test\\setup.exe");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
  }
}
</code>```

While i executing this code, the file was successfully moved by i execute this code i got the following error.

```<code>java.io.IOException: Cannot run program "test\setup.exe": CreateProcess error=740, The requested operation requires elevation
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
    at java.lang.Runtime.exec(Runtime.java:593)
    at java.lang.Runtime.exec(Runtime.java:431)
    at java.lang.Runtime.exec(Runtime.java:328)
    at JFileChooserTest.main(JFileChooserTest.java:34)
Caused by: java.io.IOException: CreateProcess error=740, The requested operation requires elevation
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
    at java.lang.ProcessImpl.start(ProcessImpl.java:30)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:453)
    ... 4 more
</code>```

Here i used "setup.exe". It is an executable file. while i execute at run time i got the above error. Why it will happens, is any possible to resolve it. Thanks in advance..

答: I'm guessing you are using windows 7, when you run your batch process to start your JFileChooser test, right click and select "run as administrator".</p>

Title: The exe doesn't run

Body:
I used the following Java code for move the file form one directory to another, then execute the file in the destination directory. My code is

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

import org.apache.commons.io.FileUtils;
public class JFileChooserTest {
  public static void main(String[] args) {
        String filelocation="C:\\Users\\FSSD\\Desktop\\OutPut\\Target";
        File trgDir = new File(filelocation);
        System.err
                .println("file location>>>>>>>>>>>>>>>>>>>"
                        + filelocation);
        File desDir = new File(
                "C:\\Users\\FSSD\\IndigoWorkSpace\\Swing\\test");

        try {
            FileUtils.copyDirectory(trgDir, desDir);
            // FileUtils.copyDirectory(srcDir, trgDir);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        Runtime rt=Runtime.getRuntime();
        try {
            Process p=rt.exec("test\\setup.exe");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
  }
}

While i executing this code, the file was successfully moved by i execute this code i got the following error.

java.io.IOException: Cannot run program "test\setup.exe": CreateProcess error=740, The requested operation requires elevation
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
    at java.lang.Runtime.exec(Runtime.java:593)
    at java.lang.Runtime.exec(Runtime.java:431)
    at java.lang.Runtime.exec(Runtime.java:328)
    at JFileChooserTest.main(JFileChooserTest.java:34)
Caused by: java.io.IOException: CreateProcess error=740, The requested operation requires elevation
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
    at java.lang.ProcessImpl.start(ProcessImpl.java:30)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:453)
    ... 4 more

Here i used "setup.exe". It is an executable file. while i execute at run time i got the above error. Why it will happens, is any possible to resolve it. Thanks in advance..


问:
Animate view height with Swift
I have view sView inside my ViewController. It height has constraint - I created IBOutlet for this constraint - sViewHeightConstraint. I want to decrease height of sView with animation.

I created function

```<code>UIView.animateWithDuration(5.5, animations: {
                self.sViewHeightConstraint.constant = 50
            })
</code>```

Height of view is changing but i don't see any animation. What I am doing wrong?

答:
In case your view updates but animation isn't working, this solution works for me.</p>
```<code>UIView.animate(withDuration: 0.2, animations: {
    self.sViewHeightConstraint.constant = 50
    self.sView.size = CGSize(width: self.sView.frame.width, height: 50)
    self.view.layoutIfNeeded()
})
</code>```

Title: Animate view height with Swift

Body:
I have view sView inside my ViewController. It height has constraint - I created IBOutlet for this constraint - sViewHeightConstraint. I want to decrease height of sView with animation.

I created function

UIView.animateWithDuration(5.5, animations: {
                self.sViewHeightConstraint.constant = 50
            })

Height of view is changing but i don't see any animation. What I am doing wrong?

Body:
In case your view updates but animation isn't working, this solution works for me.

UIView.animate(withDuration: 0.2, animations: {
    self.sViewHeightConstraint.constant = 50
    self.sView.size = CGSize(width: self.sView.frame.width, height: 50)
    self.view.layoutIfNeeded()
})


问:
@Autowired - No qualifying bean of type found for dependency
I've started my project by creating entities, services and JUnit tests for services using Spring and Hibernate. All of this works great.
Then I've added spring-mvc to make this web application using many different step-by-step tutorials, but when I'm trying to make Controller with @Autowired annotation, I'm getting errors from Glassfish during deployment. I guess that for some reason Spring doesn't see my services, but after many attempts I still can't handle it.

Tests for services with

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml"})
</code>```

and

```<code>@Autowired
MailManager mailManager;
</code>```

works properly.

Controllers without @Autowired too, I can open my project in web browser without trouble.

/src/main/resources/beans.xml

```<code><?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd">

    <context:property-placeholder location="jdbc.properties" />

    <context:component-scan base-package="pl.com.radzikowski.webmail">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!--<context:component-scan base-package="pl.com.radzikowski.webmail.service" />-->

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- Persistance Unit Manager for persistance options managing -->
    <bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
        <property name="defaultDataSource" ref="dataSource"/>
    </bean>

    <!-- Entity Manager Factory for creating/updating DB schema based on persistence files and entity classes -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitManager" ref="persistenceUnitManager"/>
        <property name="persistenceUnitName" value="WebMailPU"/>
    </bean>

    <!-- Hibernate Session Factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--<property name="schemaUpdate" value="true" />-->
        <property name="packagesToScan" value="pl.com.radzikowski.webmail.domain" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            </props>
        </property>
    </bean>

    <!-- Hibernate Transaction Manager -->
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- Activates annotation based transaction management -->
    <tx:annotation-driven transaction-manager="txManager"/>

</beans>
</code>```

/webapp/WEB-INF/web.xml

```<code><web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="WebApp_ID" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Spring Web MVC Application</display-name>
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>
</code>```

/webapp/WEB-INF/mvc-dispatcher-servlet.xml

```<code><beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="pl.com.radzikowski.webmail" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <mvc:annotation-driven/>

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

</beans>
</code>```

pl.com.radzikowski.webmail.service.AbstractManager

```<code>package pl.com.radzikowski.webmail.service;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Master Manager class providing basic fields for services.
 * @author Maciej Radzikowski <maciej@radzikowski.com.pl>
 */
public class AbstractManager {

    @Autowired
    protected SessionFactory sessionFactory;

    protected final Logger logger = Logger.getLogger(this.getClass());

}
</code>```

pl.com.radzikowski.webmail.service.MailManager

```<code>package pl.com.radzikowski.webmail.service;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class MailManager extends AbstractManager {
    // some methods...
}
</code>```

pl.com.radzikowski.webmail.HomeController

```<code>package pl.com.radzikowski.webmail.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pl.com.radzikowski.webmail.service.MailManager;

@Controller
@RequestMapping("/")
public class HomeController {

    @Autowired
    public MailManager mailManager;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String homepage(ModelMap model) {
        return "homepage";
    }

}
</code>```

Error:

SEVERE:   Exception while loading the app

SEVERE:   Undeployment failed for context /WebMail

SEVERE:   Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public pl.com.radzikowski.webmail.service.MailManager pl.com.radzikowski.webmail.controller.HomeController.mailManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [pl.com.radzikowski.webmail.service.MailManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Sorry for a lot of code, but I don't know what can cause that error anymore.

Added

I've created the interface:

```<code>@Component
public interface IMailManager {
</code>```

added implements:

```<code>@Component
@Transactional
public class MailManager extends AbstractManager implements IMailManager {
</code>```

and changed autowired:

```<code>@Autowired
public IMailManager mailManager;
</code>```

But it still throws errors (also when I've tried with @Qualifier)

..Could not autowire field: public
pl.com.radzikowski.webmail.service.IMailManager
pl.com.radzikowski.webmail.controller.HomeController.mailManager...

I've tried with different combinations of @Component and @Transactional too.

Shouldn't I include beans.xml in web.xml somehow?

答:
I've reproduced similar issue in multi-module project w/ No qualifying bean of type like:

```<code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.stockclient.repository.StockPriceRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
</code>```

and the reason for this error was missing annotation @EnableJpaRepositories in my specific use case.

To clarify: this annotation needs to be added for enabling auto configuration support for Spring Data JPA required to know the path of JPA repositories. By default, it will scan only the main application package and its sub packages for detecting the JPA repositories.

For more details you can refer, for instance, to this article.

Body:
I've started my project by creating entities, services and JUnit tests for services using Spring and Hibernate. All of this works great.
Then I've added spring-mvc to make this web application using many different step-by-step tutorials, but when I'm trying to make Controller with @Autowired annotation, I'm getting errors from Glassfish during deployment. I guess that for some reason Spring doesn't see my services, but after many attempts I still can't handle it.

Tests for services with

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml"})

and

@Autowired
MailManager mailManager;

works properly.

Controllers without @Autowired too, I can open my project in web browser without trouble.

/src/main/resources/beans.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd">

    <context:property-placeholder location="jdbc.properties" />

    <context:component-scan base-package="pl.com.radzikowski.webmail">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
        <property name="defaultDataSource" ref="dataSource"/>
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitManager" ref="persistenceUnitManager"/>
        <property name="persistenceUnitName" value="WebMailPU"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>

        <property name="packagesToScan" value="pl.com.radzikowski.webmail.domain" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            </props>
        </property>
    </bean>

    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="txManager"/>

</beans>

/webapp/WEB-INF/web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="WebApp_ID" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Spring Web MVC Application</display-name>
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

/webapp/WEB-INF/mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="pl.com.radzikowski.webmail" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <mvc:annotation-driven/>

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

</beans>

pl.com.radzikowski.webmail.service.AbstractManager

package pl.com.radzikowski.webmail.service;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Master Manager class providing basic fields for services.
 * @author Maciej Radzikowski <maciej@radzikowski.com.pl>
 */
public class AbstractManager {

    @Autowired
    protected SessionFactory sessionFactory;

    protected final Logger logger = Logger.getLogger(this.getClass());

}

pl.com.radzikowski.webmail.service.MailManager

package pl.com.radzikowski.webmail.service;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class MailManager extends AbstractManager {
    // some methods...
}

pl.com.radzikowski.webmail.HomeController

package pl.com.radzikowski.webmail.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pl.com.radzikowski.webmail.service.MailManager;

@Controller
@RequestMapping("/")
public class HomeController {

    @Autowired
    public MailManager mailManager;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String homepage(ModelMap model) {
        return "homepage";
    }

}

Error:

SEVERE:   Exception while loading the app

SEVERE:   Undeployment failed for context /WebMail

SEVERE:   Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public pl.com.radzikowski.webmail.service.MailManager pl.com.radzikowski.webmail.controller.HomeController.mailManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [pl.com.radzikowski.webmail.service.MailManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Sorry for a lot of code, but I don't know what can cause that error anymore.

Added

I've created the interface:

@Component
public interface IMailManager {

added implements:

@Component
@Transactional
public class MailManager extends AbstractManager implements IMailManager {

and changed autowired:

@Autowired
public IMailManager mailManager;

But it still throws errors (also when I've tried with @Qualifier)

..Could not autowire field: public
pl.com.radzikowski.webmail.service.IMailManager
pl.com.radzikowski.webmail.controller.HomeController.mailManager...

I've tried with different combinations of @Component and @Transactional too.

Shouldn't I include beans.xml in web.xml somehow?

Body:
I've reproduced similar issue in multi-module project w/ No qualifying bean of type like:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.stockclient.repository.StockPriceRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

and the reason for this error was missing annotation @EnableJpaRepositories in my specific use case.

To clarify: this annotation needs to be added for enabling auto configuration support for Spring Data JPA required to know the path of JPA repositories. By default, it will scan only the main application package and its sub packages for detecting the JPA repositories.

For more details you can refer, for instance, to this article.


问:
Can you simplify Else If?
Currently working on a project from school. And they want us to take a users input and display their grades.

Now I am just being curious here, but is there any way to make this more simple? I feel like this could easily get out of hand.

My first thought was instead of creating each grade as a variable. You could make it an array. Could you then create some sort of loop that will check instead of creating an if else?

Sorry if this isn't possible. Just very curious about how i could improve on this.

```<code>> Grades = [
    '9',
    '8',
    '7',
    '6',
    '5',
    '4',
    '3',
    '2',
    '1',
    'U'
]

Component_1 = int(input("Enter your Component 1 mark here: "))
if Component_1 <= 9:
    print(f"You got the grade {Grades[9]} ")
elif Component_1 <= 17:
    print(f"You got the grade {Grades[8]}")
elif Component_1 <= 25:
    print(f"You got the grade {Grades[7]}")
elif Component_1 <= 34:
    print(f"You got the grade {Grades[6]}")
</code>```

The task I was originally asked to do:

答:
Use a list of tuples that map the component score to the grade.</p>
```<code>comp1_grades = [(9, 'U'), (17, '1'), (25, '2'), ...]

for max_score, grade in comp1_grades:
    if Component_1 <= max_score:
        print(f"You got the grade {grade}")
        break
</code>```

Title: Can you simplify Else If?

Body:
Currently working on a project from school. And they want us to take a users input and display their grades.

Now I am just being curious here, but is there any way to make this more simple? I feel like this could easily get out of hand.

My first thought was instead of creating each grade as a variable. You could make it an array. Could you then create some sort of loop that will check instead of creating an if else?

Sorry if this isn't possible. Just very curious about how i could improve on this.

> Grades = [
    '9',
    '8',
    '7',
    '6',
    '5',
    '4',
    '3',
    '2',
    '1',
    'U'
]

Component_1 = int(input("Enter your Component 1 mark here: "))
if Component_1 <= 9:
    print(f"You got the grade {Grades[9]} ")
elif Component_1 <= 17:
    print(f"You got the grade {Grades[8]}")
elif Component_1 <= 25:
    print(f"You got the grade {Grades[7]}")
elif Component_1 <= 34:
    print(f"You got the grade {Grades[6]}")

The task I was originally asked to do:

Body:
Use a list of tuples that map the component score to the grade.

comp1_grades = [(9, 'U'), (17, '1'), (25, '2'), ...]

for max_score, grade in comp1_grades:
    if Component_1 <= max_score:
        print(f"You got the grade {grade}")
        break


问:
Excel split column by words

It seems there are some formatting problem here, I can't get the table format correct, so I attached a screenshot on preview.

答:
In B1 write this formula and drag it to the right and down.

```<code>=MID($A1;COLUMNS($B$1:B1);1)
</code>```

Change semicolon to comma first, if your Excel version uses commas instead.

Title: Excel split column by words

Body:
In B1 write this formula and drag it to the right and down.

=MID($A1;COLUMNS($B$1:B1);1)

Change semicolon to comma first, if your Excel version uses commas instead.


问:
What else do I need for CodeHS 8.3.8: Word Ladder?
This is what I am supposed to do:

Your friend wants to try to make a word ladder! This is a list of words where each word has a one-letter difference from the word before it. Here’s an example:

```<code>cat
cot
cog
log
</code>```

Write a program to help your friend. It should do the following:

Ask your friend for an initial word.

Repeatedly ask them for an index and a letter.

You should replace the letter at the index they provided with the letter they enter.

You should then print the new word.

Stop asking for input when the user enters -1 for the index.

Here’s what should be happening behind the scenes:

You should have a function, get_index, that repeatedly asks the user for an index until they enter a valid integer that is within the acceptable range of indices for the initial string. (If they enter a number out of range, you should output invalid index.)

You should have another function, get_letter, that repeatedly asks the user for a letter until they enter exactly one lowercase letter. (If they enter more than one character, you should output Must be exactly one character!. If they enter a capital letter, you should output Character must be a lowercase letter!.)

You should store a list version of the current word in a variable. This is what you should update each time the user swaps out a new letter.

Each time you have to print the current word, print the string version of the list you are keeping in your variable.

Here’s what an example run of your program might look like:

```<code>Enter a word: cat
Enter an index (-1 to quit): 1
Enter a letter: o
cot
Enter an index (-1 to quit): 2
Enter a letter: g
cog
Enter an index (-1 to quit): 5
Invalid index
Enter an index (-1 to quit): -3
Invalid index
Enter an index (-1 to quit): 0
Enter a letter: L
Character must be a lowercase letter!
Enter a letter: l
log
Enter an index (-1 to quit): -1
</code>```

This is my code right now:

word = input("Enter a word: ")
for i in range():
    get_index = int(input("Enter an index (-1 to quit): "))
    if get_index < -1:
        print "Invalid index"
    elif get_index > 3:
        print "Invalid index"
    else:
        letter = input("Enter a letter: ")
        word = word[:get_index] + letter + word[get_index + 1:]
        print word
```

So I'm not entirely sure how to make an if/else statement for all capital letters and only allow one letter. I'm also not sure about what I need to put in my for loop to make it end when I enter -1.

答:
Remember that you can call a function in a variable like this:

```<code>returned_index = get_index()
</code>```

Here is the correct code:

```<code>user_string = input("Enter a string: ")

def get_index():
    while True:
        try:
            user_index = int(input("Enter an Index: "))
            if user_index >= len(user_string):
                print("Invalid Index")
                continue
            if user_index < -1:
                print("Invalid Index")
                continue
        except ValueError:
            print("Invalid Index")
            continue
        return user_index

def get_string():
    while True:
        user_letter = input("Enter letter: ")
        if user_letter.isupper():
            print("Character must be a lowercase letter!")
            continue
        if len(user_letter) > 1:
            print("Must be exactly one character!")
            continue
        return user_letter

while True:
    user_string = list(user_string)
    returned_index = get_index()
    if returned_index == -1:
        break
    returned_string = get_string()
    user_string[returned_index] = returned_string
    print("".join(user_string))
</code>```

Body:
This is what I am supposed to do:

Your friend wants to try to make a word ladder! This is a list of words where each word has a one-letter difference from the word before it. Here’s an example:

cat
cot
cog
log

Write a program to help your friend. It should do the following:

Ask your friend for an initial word.

Repeatedly ask them for an index and a letter.

You should replace the letter at the index they provided with the letter they enter.

You should then print the new word.

Stop asking for input when the user enters -1 for the index.

Here’s what should be happening behind the scenes:

You should have a function, get_index, that repeatedly asks the user for an index until they enter a valid integer that is within the acceptable range of indices for the initial string. (If they enter a number out of range, you should output invalid index.)

You should have another function, get_letter, that repeatedly asks the user for a letter until they enter exactly one lowercase letter. (If they enter more than one character, you should output Must be exactly one character!. If they enter a capital letter, you should output Character must be a lowercase letter!.)

You should store a list version of the current word in a variable. This is what you should update each time the user swaps out a new letter.

Each time you have to print the current word, print the string version of the list you are keeping in your variable.

Here’s what an example run of your program might look like:

Enter a word: cat
Enter an index (-1 to quit): 1
Enter a letter: o
cot
Enter an index (-1 to quit): 2
Enter a letter: g
cog
Enter an index (-1 to quit): 5
Invalid index
Enter an index (-1 to quit): -3
Invalid index
Enter an index (-1 to quit): 0
Enter a letter: L
Character must be a lowercase letter!
Enter a letter: l
log
Enter an index (-1 to quit): -1

This is my code right now:

word = input("Enter a word: ")
for i in range():
    get_index = int(input("Enter an index (-1 to quit): "))
    if get_index < -1:
        print "Invalid index"
    elif get_index > 3:
        print "Invalid index"
    else:
        letter = input("Enter a letter: ")
        word = word[:get_index] + letter + word[get_index + 1:]
        print word

So I'm not entirely sure how to make an if/else statement for all capital letters and only allow one letter. I'm also not sure about what I need to put in my for loop to make it end when I enter -1.

Body:
Remember that you can call a function in a variable like this:

returned_index = get_index()

Here is the correct code:

user_string = input("Enter a string: ")

def get_index():
    while True:
        try:
            user_index = int(input("Enter an Index: "))
            if user_index >= len(user_string):
                print("Invalid Index")
                continue
            if user_index < -1:
                print("Invalid Index")
                continue
        except ValueError:
            print("Invalid Index")
            continue
        return user_index

def get_string():
    while True:
        user_letter = input("Enter letter: ")
        if user_letter.isupper():
            print("Character must be a lowercase letter!")
            continue
        if len(user_letter) > 1:
            print("Must be exactly one character!")
            continue
        return user_letter

while True:
    user_string = list(user_string)
    returned_index = get_index()
    if returned_index == -1:
        break
    returned_string = get_string()
    user_string[returned_index] = returned_string
    print("".join(user_string))


问:
MediaRecorder.GetSurface() returning null
I am using this code for Screen Recording on my Nexus 5 running 6.0.1 with July Security Update. The screen recording works fine on other devices running 5.0.1, 6.0, 6.0.1 however it's not working on my phone. It gives me the following error when I try to start screen recording.

```<code>E/MediaRecorder: SurfaceMediaSource could not be initialized!
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1995, result=-1, data=Intent { (has extras) }} to activity {MainActivity}: java.lang.IllegalStateException: failed to get surface
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
Caused by: java.lang.IllegalStateException: failed to get surface
at android.media.MediaRecorder.getSurface(Native Method)
</code>```

It's failing to get Surface for screen recording. What's causing this and how can I resolve this?

Source Code:

```<code> public static MediaProjectionManager getmMediaProjectionManager(final MainActivity context) {
        DisplayMetrics metrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mScreenDensity = metrics.densityDpi;
        DISPLAY_HEIGHT = metrics.heightPixels;
        DISPLAY_WIDTH = metrics.widthPixels;
        mMediaRecorder = new MediaRecorder();

        mMediaProjectionManager = (MediaProjectionManager) context.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        return mMediaProjectionManager;
    }

    @TargetApi(21)
    public static void startScreenRecording(Intent data) {
        mMediaProjectionCallback = new MediaProjectionCallback();
        initRecorder(null);
        mMediaProjection = mMediaProjectionManager.getMediaProjection(RESULT_OK, data);
        mMediaProjection.registerCallback(mMediaProjectionCallback, null);
        mVirtualDisplay = createVirtualDisplay();
        mMediaRecorder.start();
    }

    @TargetApi(21)
    private static VirtualDisplay createVirtualDisplay() {
        return mMediaProjection.createVirtualDisplay("MainActivity",
                DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mMediaRecorder.getSurface(), null /*Callbacks*/, null
                /*Handler*/);
    }

    @TargetApi(21)
    private static void initRecorder(MainActivity context) {
        try {
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mMediaRecorder.setOutputFile(Environment
                    .getExternalStorageDirectory() + "/video"+ System.currentTimeMillis()+".mp4");
            mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setVideoEncodingBitRate(VIDEO_ENCODING_BITRATE);
            mMediaRecorder.setVideoFrameRate(VIDEO_FRAME_RATE);
            mMediaRecorder.prepare();
        } catch (Exception e) {
            Log.e("Util", e.getLocalizedMessage());
        }
    }

    @TargetApi(21)
    private static class MediaProjectionCallback extends MediaProjection.Callback {
        @Override
        public void onStop() {

        }
    }

    @TargetApi(21)
    public static void stopScreenSharing() {
        mMediaRecorder.stop();
        mMediaRecorder.reset();
        if (mVirtualDisplay == null) {
            return;
        }

        mVirtualDisplay.release();

        destroyMediaProjection();
    }

    @TargetApi(21)
    private static void destroyMediaProjection() {
        if (mMediaProjection != null) {
            Log.e(TAG, "destroying projection");
            mMediaProjection.unregisterCallback(mMediaProjectionCallback);
            mMediaProjection.stop();
            mMediaProjection = null;
        }
    }
</code>```

Best Regards

答:
This code will work !!</p>
```<code> package com.example.signeyweb.TestingPackage;
 import static android.content.ContentValues.TAG;
 import android.content.Context;
 import android.content.Intent;
 import android.hardware.display.DisplayManager;
 import android.hardware.display.VirtualDisplay;
 import android.media.MediaRecorder;
 import android.media.projection.MediaProjection;
 import android.media.projection.MediaProjectionManager;
 import android.os.Bundle;
 import android.os.Environment;
 import android.util.DisplayMetrics;
 import android.util.Log;
 import android.view.View;
 import android.widget.Toast;

 import androidx.appcompat.app.AppCompatActivity;

 import com.example.signeyweb.R;

 import java.io.File;
 import java.text.SimpleDateFormat;
 import java.util.Date;

 public class TestingTwoActivity extends AppCompatActivity {
private static final int CAST_PERMISSION_CODE = 22;
public DisplayMetrics mDisplayMetrics  = new DisplayMetrics();
public MediaProjection mMediaProjection;
public VirtualDisplay mVirtualDisplay;
public MediaRecorder mMediaRecorder;
MediaProjectionManager mProjectionManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_testing_two);
    mMediaRecorder = new MediaRecorder();

    mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);

    mDisplayMetrics = getApplicationContext().getResources().getDisplayMetrics();

    prepareRecording();
}

private void startRecording() {
    // If mMediaProjection is null that means we didn't get a context, lets ask the user
    if (mMediaProjection == null) {
        // This asks for user permissions to capture the screen
        startActivityForResult(mProjectionManager.createScreenCaptureIntent(), CAST_PERMISSION_CODE);
        return;
    }
    mVirtualDisplay = getVirtualDisplay();
    mMediaRecorder.start();
}

private void stopRecording() {
    if (mMediaRecorder != null) {
        mMediaRecorder.stop();
        mMediaRecorder.reset();
    }
    if (mVirtualDisplay != null) {
        mVirtualDisplay.release();
    }
    if (mMediaProjection != null) {
        mMediaProjection.stop();
    }
    prepareRecording();
}

public String getCurSysDate() {
    return new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
}

private void prepareRecording() {

    final String directory = Environment.getExternalStorageDirectory() + File.separator + "Recordings";
    if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        Toast.makeText(this, "Failed to get External Storage", Toast.LENGTH_SHORT).show();
        return;
    }
    final File folder = new File(directory);
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdir();
    }
    String filePath;
    if (success) {
        String videoName = ("capture_" + getCurSysDate() + ".mp4");
        filePath = directory + File.separator + videoName;
    } else {
        Toast.makeText(this, "Failed to create Recordings directory", Toast.LENGTH_SHORT).show();
        return;
    }

    int width = mDisplayMetrics.widthPixels;
   int height = mDisplayMetrics.heightPixels;

    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
    mMediaRecorder.setVideoFrameRate(30);
    mMediaRecorder.setVideoSize(width, height);
    mMediaRecorder.setOutputFile(filePath);
    try {
        mMediaRecorder.prepare();
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode != CAST_PERMISSION_CODE) {
        // Where did we get this request from ? -_-
        Log.w(TAG, "Unknown request code: " + requestCode);
        return;
    }
    if (resultCode != RESULT_OK) {
        Toast.makeText(this, "Screen Cast Permission Denied :(", Toast.LENGTH_SHORT).show();
        return;
    }
    mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
    // TODO Register a callback that will listen onStop and release & prepare the recorder for next recording
    // mMediaProjection.registerCallback(callback, null);
    mVirtualDisplay = getVirtualDisplay();
    mMediaRecorder.start();
}

private VirtualDisplay getVirtualDisplay() {
    int screenDensity = mDisplayMetrics.densityDpi;
    int width = mDisplayMetrics.widthPixels;
    int height = mDisplayMetrics.heightPixels;

    return mMediaProjection.createVirtualDisplay(this.getClass().getSimpleName(),
            width, height, screenDensity,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            mMediaRecorder.getSurface(), null /*Callbacks*/, null /*Handler*/);
}

public void startrecording(View view) {
    startRecording();
}

public void stoprecordingg(View view) {
    stopRecording();
}
      }
</code>```

Body:
I am using this code for Screen Recording on my Nexus 5 running 6.0.1 with July Security Update. The screen recording works fine on other devices running 5.0.1, 6.0, 6.0.1 however it's not working on my phone. It gives me the following error when I try to start screen recording.

E/MediaRecorder: SurfaceMediaSource could not be initialized!
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1995, result=-1, data=Intent { (has extras) }} to activity {MainActivity}: java.lang.IllegalStateException: failed to get surface
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
Caused by: java.lang.IllegalStateException: failed to get surface
at android.media.MediaRecorder.getSurface(Native Method)

It's failing to get Surface for screen recording. What's causing this and how can I resolve this?

Source Code:

 public static MediaProjectionManager getmMediaProjectionManager(final MainActivity context) {
        DisplayMetrics metrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mScreenDensity = metrics.densityDpi;
        DISPLAY_HEIGHT = metrics.heightPixels;
        DISPLAY_WIDTH = metrics.widthPixels;
        mMediaRecorder = new MediaRecorder();

        mMediaProjectionManager = (MediaProjectionManager) context.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        return mMediaProjectionManager;
    }

    @TargetApi(21)
    public static void startScreenRecording(Intent data) {
        mMediaProjectionCallback = new MediaProjectionCallback();
        initRecorder(null);
        mMediaProjection = mMediaProjectionManager.getMediaProjection(RESULT_OK, data);
        mMediaProjection.registerCallback(mMediaProjectionCallback, null);
        mVirtualDisplay = createVirtualDisplay();
        mMediaRecorder.start();
    }

    @TargetApi(21)
    private static VirtualDisplay createVirtualDisplay() {
        return mMediaProjection.createVirtualDisplay("MainActivity",
                DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mMediaRecorder.getSurface(), null /*Callbacks*/, null
                /*Handler*/);
    }

    @TargetApi(21)
    private static void initRecorder(MainActivity context) {
        try {
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mMediaRecorder.setOutputFile(Environment
                    .getExternalStorageDirectory() + "/video"+ System.currentTimeMillis()+".mp4");
            mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setVideoEncodingBitRate(VIDEO_ENCODING_BITRATE);
            mMediaRecorder.setVideoFrameRate(VIDEO_FRAME_RATE);
            mMediaRecorder.prepare();
        } catch (Exception e) {
            Log.e("Util", e.getLocalizedMessage());
        }
    }

    @TargetApi(21)
    private static class MediaProjectionCallback extends MediaProjection.Callback {
        @Override
        public void onStop() {

        }
    }

    @TargetApi(21)
    public static void stopScreenSharing() {
        mMediaRecorder.stop();
        mMediaRecorder.reset();
        if (mVirtualDisplay == null) {
            return;
        }

        mVirtualDisplay.release();

        destroyMediaProjection();
    }

    @TargetApi(21)
    private static void destroyMediaProjection() {
        if (mMediaProjection != null) {
            Log.e(TAG, "destroying projection");
            mMediaProjection.unregisterCallback(mMediaProjectionCallback);
            mMediaProjection.stop();
            mMediaProjection = null;
        }
    }

Best Regards

Body:
This code will work !!

 package com.example.signeyweb.TestingPackage;
 import static android.content.ContentValues.TAG;
 import android.content.Context;
 import android.content.Intent;
 import android.hardware.display.DisplayManager;
 import android.hardware.display.VirtualDisplay;
 import android.media.MediaRecorder;
 import android.media.projection.MediaProjection;
 import android.media.projection.MediaProjectionManager;
 import android.os.Bundle;
 import android.os.Environment;
 import android.util.DisplayMetrics;
 import android.util.Log;
 import android.view.View;
 import android.widget.Toast;

 import androidx.appcompat.app.AppCompatActivity;

 import com.example.signeyweb.R;

 import java.io.File;
 import java.text.SimpleDateFormat;
 import java.util.Date;

 public class TestingTwoActivity extends AppCompatActivity {
private static final int CAST_PERMISSION_CODE = 22;
public DisplayMetrics mDisplayMetrics  = new DisplayMetrics();
public MediaProjection mMediaProjection;
public VirtualDisplay mVirtualDisplay;
public MediaRecorder mMediaRecorder;
MediaProjectionManager mProjectionManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_testing_two);
    mMediaRecorder = new MediaRecorder();

    mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);

    mDisplayMetrics = getApplicationContext().getResources().getDisplayMetrics();

    prepareRecording();
}

private void startRecording() {
    // If mMediaProjection is null that means we didn't get a context, lets ask the user
    if (mMediaProjection == null) {
        // This asks for user permissions to capture the screen
        startActivityForResult(mProjectionManager.createScreenCaptureIntent(), CAST_PERMISSION_CODE);
        return;
    }
    mVirtualDisplay = getVirtualDisplay();
    mMediaRecorder.start();
}

private void stopRecording() {
    if (mMediaRecorder != null) {
        mMediaRecorder.stop();
        mMediaRecorder.reset();
    }
    if (mVirtualDisplay != null) {
        mVirtualDisplay.release();
    }
    if (mMediaProjection != null) {
        mMediaProjection.stop();
    }
    prepareRecording();
}

public String getCurSysDate() {
    return new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
}

private void prepareRecording() {

    final String directory = Environment.getExternalStorageDirectory() + File.separator + "Recordings";
    if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        Toast.makeText(this, "Failed to get External Storage", Toast.LENGTH_SHORT).show();
        return;
    }
    final File folder = new File(directory);
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdir();
    }
    String filePath;
    if (success) {
        String videoName = ("capture_" + getCurSysDate() + ".mp4");
        filePath = directory + File.separator + videoName;
    } else {
        Toast.makeText(this, "Failed to create Recordings directory", Toast.LENGTH_SHORT).show();
        return;
    }

    int width = mDisplayMetrics.widthPixels;
   int height = mDisplayMetrics.heightPixels;

    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
    mMediaRecorder.setVideoFrameRate(30);
    mMediaRecorder.setVideoSize(width, height);
    mMediaRecorder.setOutputFile(filePath);
    try {
        mMediaRecorder.prepare();
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode != CAST_PERMISSION_CODE) {
        // Where did we get this request from ? -_-
        Log.w(TAG, "Unknown request code: " + requestCode);
        return;
    }
    if (resultCode != RESULT_OK) {
        Toast.makeText(this, "Screen Cast Permission Denied :(", Toast.LENGTH_SHORT).show();
        return;
    }
    mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
    // TODO Register a callback that will listen onStop and release & prepare the recorder for next recording
    // mMediaProjection.registerCallback(callback, null);
    mVirtualDisplay = getVirtualDisplay();
    mMediaRecorder.start();
}

private VirtualDisplay getVirtualDisplay() {
    int screenDensity = mDisplayMetrics.densityDpi;
    int width = mDisplayMetrics.widthPixels;
    int height = mDisplayMetrics.heightPixels;

    return mMediaProjection.createVirtualDisplay(this.getClass().getSimpleName(),
            width, height, screenDensity,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            mMediaRecorder.getSurface(), null /*Callbacks*/, null /*Handler*/);
}

public void startrecording(View view) {
    startRecording();
}

public void stoprecordingg(View view) {
    stopRecording();
}
      }


问:
What's happening when I use miniforge with pyenv?
I'm struggling to find any documentation on this.

I started using pyenv a while back on my M1 Mac to manage python versions.

Recently I had some issues getting tensorflow installed, so followed some instructions online which recommended using miniforge

pyenv local miniforge
python -v venv venv
source venv/bin/activate
conda install -c apple tensorflow-deps
pip install tensorflow-macos
pip install tensorflow-metal
```

However, I'm really not sure what this is doing. It's setting pyenv local to miniforge (rather than a python version). It's setting up a virtual environment and activating. Then using the conda command to install something tensorflow related, and then using pip to install some more tensorflow stuff.

What exactly is happening when I set miniforge with pyenv? I only thought you could set python versions here, and though miniforge was just an installer of sorts.

答: I think you want to check out the anaconda docs.  The api is the same. https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html</p>

Body:
I'm struggling to find any documentation on this.

I started using pyenv a while back on my M1 Mac to manage python versions.

Recently I had some issues getting tensorflow installed, so followed some instructions online which recommended using miniforge

pyenv local miniforge
python -v venv venv
source venv/bin/activate
conda install -c apple tensorflow-deps
pip install tensorflow-macos
pip install tensorflow-metal

However, I'm really not sure what this is doing. It's setting pyenv local to miniforge (rather than a python version). It's setting up a virtual environment and activating. Then using the conda command to install something tensorflow related, and then using pip to install some more tensorflow stuff.

What exactly is happening when I set miniforge with pyenv? I only thought you could set python versions here, and though miniforge was just an installer of sorts.


问:
How to install red5 on heroku server
I am trying to build an audio recorder and have 3 questions:

Is red5 enough for building an audio recorder? No need for a flash recorder or something?

How can I install red5 on heroku server?

Is there a tutorial for audio recorder in rails?

答:
Simple answer - you can't.

The Heroku platform is 'as is' - you can only install gems as specified in your gemfile.

Title: How to install red5 on heroku server


问:
check if an IP is within a range of CIDR in Python
I know there are some similar questions up here, but they mostly either want to find the range itself (which uses some libraries, like the example that stackoverflow says is a dupe of my question) and is in another language.

I have a way to convert the subnet into the beginning and the end of the range of ip's in a subnet (okay, bad wording, it's simply like1.1.1.1/16 -> (1.1.0.0 , 1.1.255.255))

I now want to check if 1.1.2.2 is within this subnet. Can I simply do a > and < to compare?

```<code>ip_range = ('1.1.0.0', '1.1.255.255')
if '1.1.2.2' >= ip_range[0] and '1.1.2.2' <= ip_range[1]:
     return True
</code>```

When I tested it, it works, but I don't know if it would always work for any ipv4 ip's. I'd assume I'm just comparing ASCII order , so this should always work, but is there any exception?

答:
For IPv6:

Python3

```<code>import ipaddress as ips

ip1=tuple(int(n,16) for n in ips.ip_address("fc00::255:3").exploded.split(':'))
ip2=tuple(int(n,16) for n in ips.ip_address("fc00::255:e").exploded.split(':'))
ip_bet=tuple(int(n,16) for n in ips.ip_address("fc00::255:a").exploded.split(':'))

if ip1 <= ip_bet <= ip2:
    print('Yes')
else:
    print('No')
</code>```

Body:
I know there are some similar questions up here, but they mostly either want to find the range itself (which uses some libraries, like the example that stackoverflow says is a dupe of my question) and is in another language.

I have a way to convert the subnet into the beginning and the end of the range of ip's in a subnet (okay, bad wording, it's simply like1.1.1.1/16 -> (1.1.0.0 , 1.1.255.255))

I now want to check if 1.1.2.2 is within this subnet. Can I simply do a > and < to compare?

ip_range = ('1.1.0.0', '1.1.255.255')
if '1.1.2.2' >= ip_range[0] and '1.1.2.2' <= ip_range[1]:
     return True

When I tested it, it works, but I don't know if it would always work for any ipv4 ip's. I'd assume I'm just comparing ASCII order , so this should always work, but is there any exception?

Body:
For IPv6:

Python3

import ipaddress as ips

ip1=tuple(int(n,16) for n in ips.ip_address("fc00::255:3").exploded.split(':'))
ip2=tuple(int(n,16) for n in ips.ip_address("fc00::255:e").exploded.split(':'))
ip_bet=tuple(int(n,16) for n in ips.ip_address("fc00::255:a").exploded.split(':'))

if ip1 <= ip_bet <= ip2:
    print('Yes')
else:
    print('No')


问:
What is the best way to transfer file from FTP to AWS s3?
I want to copy 100-200GB files from a secure FTP server (here ftp server with username and password is secure FTP server for me) to AWS S3 bucket. Obviously, I don't want to download and upload file. So, I looked into FTP2Cloud, but it is in beta phase and the limit is only 100MB. Also, I've also looked into s3cmd, but I couldn't figure out a way to connect to secure ftp server. So, I'm stuck on transferring the files. Can somebody help me in transferring files from FTP to S3 without explicitly downloading and uploading data?

答: Create an EC2 instance, download to that instance and upload to S3.</p>


问:
Updating tick labels with set_axis_ticks does not work properly, labels corrupted
Calling repetitively set_axis_ticks does not work as intended.

Here is an example that replicates the error. Press buttons Inc or Dec to increase the number of groups, for which then new tick labels are set via set_axis_ticks.

You will see that the label texts get corrupted.

Is there another way to re-generate labels dynamically when the data changes?

Here is an example showing the issue:

```<code>import dearpygui.dearpygui as dpg
import asyncio
import numpy as np

class BarPlot:
    def __init__(self):
        self.m = 5
        self.n = 2
        self.data = np.random.rand(self.n, self.m)
        self.labels_coords = None

    def offsets(self):
        return (self.m + 1)*(np.cumsum(np.ones(self.n)) - 1)

    def labels(self, offsets):
        assert(len(offsets) == self.n)
        texts = [f"Group {i}" for i in range(self.n)]
        return tuple(zip(texts, list(offsets + self.m / 2)))

    def update(self):
        self.data = np.random.rand(self.n, self.m)
        print(f"update {self.n}x{self.m} data:\n {self.data}")
        offsets = self.offsets()
        for i in range(self.m):
            ys = list(self.data[:, i])
            xs = list(offsets + i)
            dpg.set_value(f"series-{i}", [xs, ys])
        dpg.set_axis_ticks("x-axis", self.labels(offsets))

    def on_inc(self, sender, app_data, user_data):
        self.n += user_data
        self.n = max(1, self.n)
        self.update()

    def render(self):
        with dpg.group(horizontal=True):
            dpg.add_button(label="Inc", callback=self.on_inc, user_data=1)
            dpg.add_button(label="Dec", callback=self.on_inc, user_data=-1)

        with dpg.plot(label="Bar Plot", width=700, height=400):
            offsets = self.offsets()

            dpg.add_plot_legend()
            dpg.add_plot_axis(dpg.mvXAxis, label="X", tag="x-axis", no_gridlines=True)
            dpg.set_axis_ticks("x-axis", self.labels(offsets))

            with dpg.plot_axis(dpg.mvYAxis, label="Y", tag="y-axis"):
                for i in range(self.m):
                    ys = self.data[:, i]
                    xs = offsets + i
                    dpg.add_bar_series(list(xs), list(ys), label=f"Series {i}", tag=f"series-{i}", weight=1)

            dpg.set_axis_limits_auto("x-axis")
            dpg.set_axis_limits_auto("y-axis")

bar_plot = BarPlot()

def render_gui():
    with dpg.window(tag="main_window"):
        dpg.add_spacer()
        bar_plot.render()

def run():
    dpg.create_context()
    dpg.create_viewport(title='Bug', width=720, height=720)
    render_gui()
    dpg.setup_dearpygui()
    dpg.show_viewport()
    dpg.start_dearpygui()
    dpg.destroy_context()

if __name__ == "__main__":
    run()
</code>```

Initially all good:

After increasing the number of groups:

Is this a bug or a wrong usage of set_axis_ticks?

Thanks for any help or suggestions.

答:
Apparently it looks like that one has first to reset the ticks.

Adding reset before setting the new ticks like this

```<code>dpg.reset_axis_ticks("x-axis")
dpg.set_axis_ticks("x-axis", self.labels(offsets))
</code>```

seems to do the job.

Body:
Calling repetitively set_axis_ticks does not work as intended.

Here is an example that replicates the error. Press buttons Inc or Dec to increase the number of groups, for which then new tick labels are set via set_axis_ticks.

You will see that the label texts get corrupted.

Is there another way to re-generate labels dynamically when the data changes?

Here is an example showing the issue:

import dearpygui.dearpygui as dpg
import asyncio
import numpy as np

class BarPlot:
    def __init__(self):
        self.m = 5
        self.n = 2
        self.data = np.random.rand(self.n, self.m)
        self.labels_coords = None

    def offsets(self):
        return (self.m + 1)*(np.cumsum(np.ones(self.n)) - 1)

    def labels(self, offsets):
        assert(len(offsets) == self.n)
        texts = [f"Group {i}" for i in range(self.n)]
        return tuple(zip(texts, list(offsets + self.m / 2)))

    def update(self):
        self.data = np.random.rand(self.n, self.m)
        print(f"update {self.n}x{self.m} data:\n {self.data}")
        offsets = self.offsets()
        for i in range(self.m):
            ys = list(self.data[:, i])
            xs = list(offsets + i)
            dpg.set_value(f"series-{i}", [xs, ys])
        dpg.set_axis_ticks("x-axis", self.labels(offsets))

    def on_inc(self, sender, app_data, user_data):
        self.n += user_data
        self.n = max(1, self.n)
        self.update()

    def render(self):
        with dpg.group(horizontal=True):
            dpg.add_button(label="Inc", callback=self.on_inc, user_data=1)
            dpg.add_button(label="Dec", callback=self.on_inc, user_data=-1)

        with dpg.plot(label="Bar Plot", width=700, height=400):
            offsets = self.offsets()

            dpg.add_plot_legend()
            dpg.add_plot_axis(dpg.mvXAxis, label="X", tag="x-axis", no_gridlines=True)
            dpg.set_axis_ticks("x-axis", self.labels(offsets))

            with dpg.plot_axis(dpg.mvYAxis, label="Y", tag="y-axis"):
                for i in range(self.m):
                    ys = self.data[:, i]
                    xs = offsets + i
                    dpg.add_bar_series(list(xs), list(ys), label=f"Series {i}", tag=f"series-{i}", weight=1)

            dpg.set_axis_limits_auto("x-axis")
            dpg.set_axis_limits_auto("y-axis")

bar_plot = BarPlot()

def render_gui():
    with dpg.window(tag="main_window"):
        dpg.add_spacer()
        bar_plot.render()

def run():
    dpg.create_context()
    dpg.create_viewport(title='Bug', width=720, height=720)
    render_gui()
    dpg.setup_dearpygui()
    dpg.show_viewport()
    dpg.start_dearpygui()
    dpg.destroy_context()

if __name__ == "__main__":
    run()

Initially all good:

After increasing the number of groups:

Is this a bug or a wrong usage of set_axis_ticks?

Thanks for any help or suggestions.

Body:
Apparently it looks like that one has first to reset the ticks.

Adding reset before setting the new ticks like this

dpg.reset_axis_ticks("x-axis")
dpg.set_axis_ticks("x-axis", self.labels(offsets))

seems to do the job.


问:
followed urllib.request.urlopen documentation but still not working
I followed the documentation but still getting errors which I can't figure out. I am using Python 3.

Here is my code:

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen('http://pythonscraping.com/pages/page1.html')

bs = BeautifulSoup(html.read(), "html.parser")
print(bs.h1)
</code>```

Code Editor with code and errors

答:
You did everything right.

The URL you supplied uses HTTPS and the error you get is related to the certificate problems on the website.

If you are trying to learn new things, just change the URL to some other example website.

If you want to get the result from a specific URL no matter the cost, add keyword argument context to your urlopen call and provide a correct SSL context for it to work:

```<code>from ssl import create_default_context, CERT_NONE
from urllib.request import urlopen
from bs4 import BeautifulSoup
context = create_default_context()
context.verify_mode = ssl.CERT_NONE
html = urlopen('http://pythonscraping.com/pages/page1.html', context=context)
bs = BeautifulSoup(html.read(), "html.parser")
print(bs.h1)
</code>```

Body:
I followed the documentation but still getting errors which I can't figure out. I am using Python 3.

Here is my code:

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen('http://pythonscraping.com/pages/page1.html')

bs = BeautifulSoup(html.read(), "html.parser")
print(bs.h1)

Code Editor with code and errors

Body:
You did everything right.

The URL you supplied uses HTTPS and the error you get is related to the certificate problems on the website.

If you are trying to learn new things, just change the URL to some other example website.

If you want to get the result from a specific URL no matter the cost, add keyword argument context to your urlopen call and provide a correct SSL context for it to work:

from ssl import create_default_context, CERT_NONE
from urllib.request import urlopen
from bs4 import BeautifulSoup
context = create_default_context()
context.verify_mode = ssl.CERT_NONE
html = urlopen('http://pythonscraping.com/pages/page1.html', context=context)
bs = BeautifulSoup(html.read(), "html.parser")
print(bs.h1)


问:
React Router Set Up in VS Code
I am learning React Js and the IDE I am using is VS Code. I am not able to install the react router dom using the command npm install react-router dom. Whenever I type npm install react-router-dom I get the message. react-router is not getting installed.

Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved.
up to date, audited 1407 packages in 4s
169 packages are looking for funding
run `npm fund for details
8 moderate severity vulnerabilities
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit for details.
```

答: Try npm install react-router-dom

Title: React Router Set Up in VS Code

Body: Try npm install react-router-dom


问:
Colspan all columns
How can I specify a td tag should span all columns (when the exact amount of columns in the table will be variable/difficult to determine when the HTML is being rendered)? w3schools mentions you can use colspan="0", but it doesn't say exactly what browsers support that value (IE 6 is in our list to support).

It appears that setting colspan to a value greater than the theoretical amount of columns you may have will work, but it will not work if you have table-layout set to fixed. Are there any disadvantages to using an automatic layout with a large number for colspan? Is there a more correct way of doing this?

答:
Simply set colspan to the number of columns in the table.

All other "shortcuts" have pitfalls.

The best thing to do is set the colspan to the correct number to begin with. If your table has 5 columns, set it to colspan="5" That is the only way that will work in all scenarios. No, it's not an outdated solution or only recommended for IE6 or anything -- that's literally the best way to handle this.

I wouldn't recommend using Javascript to solve this unless the number of columns changes during runtime.

If the number of columns is variable, then you'll need to calculate the number of columns so that you can populate the colspan. If you have a variable number of columns, whatever is generating the table should be able to be adapted to also calculate the number of columns the table has.

As other answers have mentioned, if your table is not set to table-layout: fixed, you can also just set colspan to a really large number. But I find this solution messy, and it can be a headache if you come back later and decide it should be a fixed table layout. Better just to do it correctly the first time.

OwnerDisplayName: Bob

Title: Colspan all columns

LastEditorDisplayName: Bob