问:
C# Custom Copy constructor, copy events
I'm trying to create a copy constructor for my C# object using reflection.  I am able to copy all of the fields and properties (those are easy) but I'm having some issues copying the Events.

Is there a way to (via reflection) copy all of the delegates that have subscribed to an event from one object to another?  (Both will be the same type)

Thank you :)

答:
It will entirely depend on the implementation. After all, an event can be implemented any way you want. If you're using a field-like event then you should be able to just copy the field value:

```<code>using System;

class Test
{
    public event EventHandler SomeEvent;

    public Test(Test other)
    {
        this.SomeEvent = other.SomeEvent;
    }
}
</code>```

This is fine as delegates are immutable - subscribing to an event creates a new delegate and assigns that to the field, so your two objects would be independent. If the event was implemented using something like EventHandlerList you would want to create a clone rather than using simple field assignment.

EDIT: To do this with reflection, you'd simply use the fields like any other. Field-like events are simply events backed by fields. If you're already copying all the fields within a class, you won't have any extra work to do.

Be aware that unless you go to extra effort, you'll only make a shallow copy - for example, if you have a field of type List<string>, your new object will refer to the same object as the old object, so any changes to the list will be seen via both objects.

Title: C# Custom Copy constructor, copy events

Body:
It will entirely depend on the implementation. After all, an event can be implemented any way you want. If you're using a field-like event then you should be able to just copy the field value:

using System;

class Test
{
    public event EventHandler SomeEvent;

    public Test(Test other)
    {
        this.SomeEvent = other.SomeEvent;
    }
}

This is fine as delegates are immutable - subscribing to an event creates a new delegate and assigns that to the field, so your two objects would be independent. If the event was implemented using something like EventHandlerList you would want to create a clone rather than using simple field assignment.

EDIT: To do this with reflection, you'd simply use the fields like any other. Field-like events are simply events backed by fields. If you're already copying all the fields within a class, you won't have any extra work to do.

Be aware that unless you go to extra effort, you'll only make a shallow copy - for example, if you have a field of type List<string>, your new object will refer to the same object as the old object, so any changes to the list will be seen via both objects.


来源: stackexchange

问:
Unnecessary Foreign Key Constraint Failure
So I have a mock database for a conference where I'm creating tables for the authors, papers, reviewers, etc.

The reviewers provide an email which refers to the Program Committee emails. This is the key constraint I put in place. Then I add data to the PC table and then attempt to add data to the reviewer table. This is the error I get:

```<code>Exception encountered com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`sampledb`.`review`, CONSTRAINT `review_ibfk_2` FOREIGN KEY (`email`) REFERENCES `pcmember` (`email`))
</code>```

Here are the other functions:

```<code>public int loadPCMember(){
    String tablename = "pcmember";
    String create = "CREATE TABLE IF NOT EXISTS pcmember(email VARCHAR(100), name VARCHAR(50), PRIMARY KEY (email));";
    makeTable(create);
    System.out.println("made table pcmember");
    //CSV Reader
    String[][] content = CSVReader(tablename,2);

    for(int i = 0 ; i < content.length; i++){
        try{
            String query = "INSERT INTO pcmember(email,name) VALUES (?,?)";
            PreparedStatement ps2 = net.prepareStatement(query);
            ps2.setString(1, content[i][0]);
            ps2.setString(2, content[i][1]);
            ps2.executeUpdate();
            System.out.println((i+1)+ " done");
        // Throw exception
        }catch (SQLException e){System.out.println("Exception encountered");return 0;}
    }
    System.out.println("PC Member Done");
    return 1;
}
//Load next
public int loadReview(){
    String tablename = "review";
    String create = "CREATE TABLE IF NOT EXISTS review(reportid INTEGER, sdate DATE, comment VARCHAR(250), recommendation VARCHAR(6), paperid INTEGER NOT NULL, email VARCHAR(100) NOT NULL, PRIMARY KEY(reportid), FOREIGN KEY (paperid) REFERENCES paper(paperid), FOREIGN KEY(email) REFERENCES pcmember(email));";
    makeTable(create);
    System.out.println("made table review");
    //CSV Reader
    String[][] content = CSVReader(tablename,6);

    for(int i = 0 ; i < content.length; i++){
        System.out.println("" + content[i][0] + "\t" +content[i][1] + "\t" + content[i][2] + "\t" +content[i][3] + "\t" +content[i][4] + "\t" +content[i][5]);
        try{
            //SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
            //java.util.Date date = sdf.parse(content[i][1]);
            //System.out.println(""+date);
            //Date newDate = new Date(date.getTime());
            //System.out.println(""+newDate);
            String query = "INSERT INTO review(reportid,sdate,comment,recommendation,paperid,email) VALUES (?,?,?,?,?,?)";
            PreparedStatement ps2 = net.prepareStatement(query);
            ps2.setInt(1, Integer.parseInt(content[i][0]));
            ps2.setDate(2, java.sql.Date.valueOf(content[i][1]));
            ps2.setString(3, content[i][2]);
            ps2.setString(4, content[i][3]);
            ps2.setInt(5, Integer.parseInt(content[i][4]));
            ps2.setString(6, content[i][5]);
            ps2.executeUpdate();
            System.out.println((i+1)+ " done");
        // Throw exception
        }catch (SQLException e){System.out.println("Exception encountered "+ e);return 0;
        }//catch (ParseException e){System.out.println("Parse Exception encountered "+e);}

    }
    System.out.println("Review Done");
    return 1;
}
</code>```

I have a decent understanding of the key constraints and I'm pretty spot on with the CSV files having the same exact emails, so what could be causing this error?

答: I'm a SQL guy, not a Java guy.  If I ask or suggest anything that doesn't make sense because of that - you know why.  To be clear - based on that error message and the sql you have included it looks like you trying to insert a record into the review table that has an email address that doesn't exist in the pcmember table thus violating the foreign key constraint on the review table.  This seems like a data problem with the CVSs you are using. However since you mentioned that you are confident in the data files is it possible that the it's trying to INSERT the rows into the review table before the pcmember INSERT has successfully completed?</p>

ContentLicense: CC BY-SA 3.0

Body:
So I have a mock database for a conference where I'm creating tables for the authors, papers, reviewers, etc.

The reviewers provide an email which refers to the Program Committee emails. This is the key constraint I put in place. Then I add data to the PC table and then attempt to add data to the reviewer table. This is the error I get:

Exception encountered com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`sampledb`.`review`, CONSTRAINT `review_ibfk_2` FOREIGN KEY (`email`) REFERENCES `pcmember` (`email`))

Here are the other functions:

public int loadPCMember(){
    String tablename = "pcmember";
    String create = "CREATE TABLE IF NOT EXISTS pcmember(email VARCHAR(100), name VARCHAR(50), PRIMARY KEY (email));";
    makeTable(create);
    System.out.println("made table pcmember");
    //CSV Reader
    String[][] content = CSVReader(tablename,2);

    for(int i = 0 ; i < content.length; i++){
        try{
            String query = "INSERT INTO pcmember(email,name) VALUES (?,?)";
            PreparedStatement ps2 = net.prepareStatement(query);
            ps2.setString(1, content[i][0]);
            ps2.setString(2, content[i][1]);
            ps2.executeUpdate();
            System.out.println((i+1)+ " done");
        // Throw exception
        }catch (SQLException e){System.out.println("Exception encountered");return 0;}
    }
    System.out.println("PC Member Done");
    return 1;
}
//Load next
public int loadReview(){
    String tablename = "review";
    String create = "CREATE TABLE IF NOT EXISTS review(reportid INTEGER, sdate DATE, comment VARCHAR(250), recommendation VARCHAR(6), paperid INTEGER NOT NULL, email VARCHAR(100) NOT NULL, PRIMARY KEY(reportid), FOREIGN KEY (paperid) REFERENCES paper(paperid), FOREIGN KEY(email) REFERENCES pcmember(email));";
    makeTable(create);
    System.out.println("made table review");
    //CSV Reader
    String[][] content = CSVReader(tablename,6);

    for(int i = 0 ; i < content.length; i++){
        System.out.println("" + content[i][0] + "\t" +content[i][1] + "\t" + content[i][2] + "\t" +content[i][3] + "\t" +content[i][4] + "\t" +content[i][5]);
        try{
            //SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
            //java.util.Date date = sdf.parse(content[i][1]);
            //System.out.println(""+date);
            //Date newDate = new Date(date.getTime());
            //System.out.println(""+newDate);
            String query = "INSERT INTO review(reportid,sdate,comment,recommendation,paperid,email) VALUES (?,?,?,?,?,?)";
            PreparedStatement ps2 = net.prepareStatement(query);
            ps2.setInt(1, Integer.parseInt(content[i][0]));
            ps2.setDate(2, java.sql.Date.valueOf(content[i][1]));
            ps2.setString(3, content[i][2]);
            ps2.setString(4, content[i][3]);
            ps2.setInt(5, Integer.parseInt(content[i][4]));
            ps2.setString(6, content[i][5]);
            ps2.executeUpdate();
            System.out.println((i+1)+ " done");
        // Throw exception
        }catch (SQLException e){System.out.println("Exception encountered "+ e);return 0;
        }//catch (ParseException e){System.out.println("Parse Exception encountered "+e);}

    }
    System.out.println("Review Done");
    return 1;
}

I have a decent understanding of the key constraints and I'm pretty spot on with the CSV files having the same exact emails, so what could be causing this error?


问:
Spring Oauth 2 Facebook Authentication Redirects User To My Home Page

I am trying to redirect a user who have been authenticated to another page other than the home page. I am using spring boot 1.5.6 and Oauth 2. User is authenticated but was redirected to the home page. I don't understand why this is happening. Please, someone should help me. Some answers to related problem on stackoverflow and the internet didn't help me.

Here is my SecurityConfig file

```<code>@Configuration
@EnableGlobalAuthentication
@EnableOAuth2Client
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(2)
public class SecurityConfig extends WebSecurityConfigurerAdapter{

protected final Log logger = LogFactory.getLog(getClass());

@Autowired
private OAuth2ClientContext oauth2ClientContext;

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private GeneralConfig generalConfig;

@Override
public void configure(WebSecurity web) throws Exception {
    super.configure(web);
}

@Override
public void configure(HttpSecurity http) throws Exception {

   http.authorizeRequests()
   .antMatchers("/user*")
   .access("hasRole('CUSTOMER')")
   .and()

   .formLogin()
   .loginPage("/loginUser")
   .loginProcessingUrl("/user_login")
   .failureUrl("/loginUser?error=loginError")
   .defaultSuccessUrl("/customer/dashboard")

   .and()
   .logout()
   .logoutUrl("/user_logout")
   .logoutSuccessUrl("/loginUser").permitAll()
   .deleteCookies("JSESSIONID")

   .and()
   .exceptionHandling()
   .accessDeniedPage("/403")

   .and()
   .csrf().disable()
   .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);

}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws               Exception {
    auth.userDetailsService(userDetailsService).
    passwordEncoder(bCryptPasswordEncoder());
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws
Exception {
    auth.userDetailsService(userDetailsService);
}

@Bean
public FilterRegistrationBeanoauth2ClientFilterRegistration
(OAuth2ClientContextFilter filter) {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(filter);
    registration.setOrder(-100);
    return registration;
}

private Filter ssoFilter(ClientResources client, String path) {
    OAuth2ClientAuthenticationProcessingFilter filter = new
    OAuth2ClientAuthenticationProcessingFilter(path);
    OAuth2RestTemplate template = new
    OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
    filter.setRestTemplate(template);
    UserInfoTokenServices tokenServices = new
         UserInfoTokenServices(client.getResource().getUserInfoUri(),
         client.getClient().getClientId());
    tokenServices.setRestTemplate(template);
    filter.setTokenServices(tokenServices);
    return filter;
}

private Filter ssoFilter() {
    CompositeFilter filter = new CompositeFilter();
    List<Filter> filters = new ArrayList<>();
    filters.add(ssoFilter(facebook(), "/signin/facebook"));
    filters.add(ssoFilter(google(), "/signin/google"));
    filter.setFilters(filters);
    return filter;
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}

@Bean
@ConfigurationProperties("google")
public ClientResources google() {
    return new ClientResources();
}

@Bean
@ConfigurationProperties("facebook")
public ClientResources facebook() {
    return new ClientResources();
}
</code>```

}

From the SecurityConfig I expect the user upon successful authentication to be redirected to customer/dashboard so that I can do further processing. I know the user is authenticated because I can access their data. It's not just redirecting to the right page

But instead it keep redirecting the user to the home page. What am I doing wrong? I also have another Security Config File for admin. I can provide it if required.

答:
To change the default strategy, you have to set an AuthenticationSuccessHandler, see AbstractAuthenticationProcessingFilter#setAuthenticationSuccessHandler:

Sets the strategy used to handle a successful authentication. By default a SavedRequestAwareAuthenticationSuccessHandler is used.

Your modified code:

private Filter ssoFilter(ClientResources client, String path) {
    OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(path);
    OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
    filter.setRestTemplate(template);
    UserInfoTokenServices tokenServices = new UserInfoTokenServices(client.getResource().getUserInfoUri(),client.getClient().getClientId());
    tokenServices.setRestTemplate(template);
    filter.setTokenServices(tokenServices);
    filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/customer/dashboard");
    return filter;
}
```

Body:
I am trying to redirect a user who have been authenticated to another page other than the home page. I am using spring boot 1.5.6 and Oauth 2. User is authenticated but was redirected to the home page. I don't understand why this is happening. Please, someone should help me. Some answers to related problem on stackoverflow and the internet didn't help me.

Here is my SecurityConfig file

@Configuration
@EnableGlobalAuthentication
@EnableOAuth2Client
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(2)
public class SecurityConfig extends WebSecurityConfigurerAdapter{

protected final Log logger = LogFactory.getLog(getClass());

@Autowired
private OAuth2ClientContext oauth2ClientContext;

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private GeneralConfig generalConfig;

@Override
public void configure(WebSecurity web) throws Exception {
    super.configure(web);
}

@Override
public void configure(HttpSecurity http) throws Exception {

   http.authorizeRequests()
   .antMatchers("/user*")
   .access("hasRole('CUSTOMER')")
   .and()

   .formLogin()
   .loginPage("/loginUser")
   .loginProcessingUrl("/user_login")
   .failureUrl("/loginUser?error=loginError")
   .defaultSuccessUrl("/customer/dashboard")

   .and()
   .logout()
   .logoutUrl("/user_logout")
   .logoutSuccessUrl("/loginUser").permitAll()
   .deleteCookies("JSESSIONID")

   .and()
   .exceptionHandling()
   .accessDeniedPage("/403")

   .and()
   .csrf().disable()
   .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);

}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws               Exception {
    auth.userDetailsService(userDetailsService).
    passwordEncoder(bCryptPasswordEncoder());
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws
Exception {
    auth.userDetailsService(userDetailsService);
}

@Bean
public FilterRegistrationBeanoauth2ClientFilterRegistration
(OAuth2ClientContextFilter filter) {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(filter);
    registration.setOrder(-100);
    return registration;
}

private Filter ssoFilter(ClientResources client, String path) {
    OAuth2ClientAuthenticationProcessingFilter filter = new
    OAuth2ClientAuthenticationProcessingFilter(path);
    OAuth2RestTemplate template = new
    OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
    filter.setRestTemplate(template);
    UserInfoTokenServices tokenServices = new
         UserInfoTokenServices(client.getResource().getUserInfoUri(),
         client.getClient().getClientId());
    tokenServices.setRestTemplate(template);
    filter.setTokenServices(tokenServices);
    return filter;
}

private Filter ssoFilter() {
    CompositeFilter filter = new CompositeFilter();
    List<Filter> filters = new ArrayList<>();
    filters.add(ssoFilter(facebook(), "/signin/facebook"));
    filters.add(ssoFilter(google(), "/signin/google"));
    filter.setFilters(filters);
    return filter;
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}

@Bean
@ConfigurationProperties("google")
public ClientResources google() {
    return new ClientResources();
}

@Bean
@ConfigurationProperties("facebook")
public ClientResources facebook() {
    return new ClientResources();
}

}

From the SecurityConfig I expect the user upon successful authentication to be redirected to customer/dashboard so that I can do further processing. I know the user is authenticated because I can access their data. It's not just redirecting to the right page

But instead it keep redirecting the user to the home page. What am I doing wrong? I also have another Security Config File for admin. I can provide it if required.


问:
Partially applied functions
While studying functional programming, the concept partially applied functions comes up a lot. In Haskell, something like the built-in function take is considered to be partially applied.

I am still unclear as to what it exactly means for a function to be partially applied or the use/implication of it.

答:
This is best understood by example. Here's the type of the addition operator:

```<code>(+) :: Num a => a -> a -> a
</code>```

What does it mean? As you know, it takes two numbers and outputs another one. Right? Well, sort of.

You see, a -> a -> a actually means this: a -> (a -> a). Whoa, looks weird! This means that (+) is a function that takes one argument and outputs a function(!!) that also takes one argument and outputs a value.

What this means is you can supply that one value to (+) to get another, partially applied, function:

```<code>(+ 5) :: Num a => a -> a
</code>```

This function takes one argument and adds five to it. Now, call that new function with some argument:

```<code>Prelude> (+5) 3
8
</code>```

Here you go! Partial function application at work!

Note the type of (+ 5) 3:

```<code>(+5) 3 :: Num a => a
</code>```

Look what we end up with:

(+)    :: Num a => a -> a -> a

(+ 5)  :: Num a => a -> a

(+5) 3 :: Num a => a

Do you see how the number of as in the type signature decreases by one every time you add a new argument?

Function with one argument that outputs a function with one argument that in turn, outputs a value

Function with one argument that outputs a value

The value itself

"...something like the built-in function take is considered to be partially applied" - I don't quite understand what this means. The function take itself is not partially applied. A function is partially applied when it is the result of supplying between 1 and (N - 1) arguments to a function that takes N arguments. So, take 5 is a partially applied function, but take and take 5 [1..10] are not.

Title: Partially applied functions

Body:
This is best understood by example. Here's the type of the addition operator:

(+) :: Num a => a -> a -> a

What does it mean? As you know, it takes two numbers and outputs another one. Right? Well, sort of.

You see, a -> a -> a actually means this: a -> (a -> a). Whoa, looks weird! This means that (+) is a function that takes one argument and outputs a function(!!) that also takes one argument and outputs a value.

What this means is you can supply that one value to (+) to get another, partially applied, function:

(+ 5) :: Num a => a -> a

This function takes one argument and adds five to it. Now, call that new function with some argument:

Prelude> (+5) 3
8

Here you go! Partial function application at work!

Note the type of (+ 5) 3:

(+5) 3 :: Num a => a

Look what we end up with:

(+)    :: Num a => a -> a -> a

(+ 5)  :: Num a => a -> a

(+5) 3 :: Num a => a

Do you see how the number of as in the type signature decreases by one every time you add a new argument?

Function with one argument that outputs a function with one argument that in turn, outputs a value

Function with one argument that outputs a value

The value itself

"...something like the built-in function take is considered to be partially applied" - I don't quite understand what this means. The function take itself is not partially applied. A function is partially applied when it is the result of supplying between 1 and (N - 1) arguments to a function that takes N arguments. So, take 5 is a partially applied function, but take and take 5 [1..10] are not.


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答:
Further, what are the axioms of programming? The very atomic truths of the field?

Are the opcodes the "atomic truths"? For example on seeing ...

```<code>mov ax,1
</code>```

... mightn't a programmer assert as axiomatic that, barring a hardware problem, after executing this statement the CPU's ax register would now contain 1?

If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?

The "previous work" then might be the run-time environment in which the new program runs.

The new program can be proven: apart from formal proofs, it can be proven "by inspection" and by various forms of "testing" (including "acceptance testing").

How do you prove a Picasso?

If software is more like industrial design or engineering than like art, a better question might be "how do you prove a bridge, or an airplane?"

ContentLicense: CC BY-SA 2.5

Title: Why can't programs be proven?

Body:
Further, what are the axioms of programming? The very atomic truths of the field?

Are the opcodes the "atomic truths"? For example on seeing ...

mov ax,1

... mightn't a programmer assert as axiomatic that, barring a hardware problem, after executing this statement the CPU's ax register would now contain 1?

If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?

The "previous work" then might be the run-time environment in which the new program runs.

The new program can be proven: apart from formal proofs, it can be proven "by inspection" and by various forms of "testing" (including "acceptance testing").

How do you prove a Picasso?

If software is more like industrial design or engineering than like art, a better question might be "how do you prove a bridge, or an airplane?"

OwnerDisplayName: ChrisW

LastEditorDisplayName: ChrisW


问:
How to deploy custom Outlook Social Connector Provider
I have developed a simple outlook provider using C# 4.0 and VS 2010 but I am not able to create successfull installation package. I have read a lot of documentation, including links below and I have fullfilled all of the requirements for installing my custom provider on Win7 64 bit and MS Outlook (64 bit), but still I am not succeed.

These are the reference articles:

http://msdn.microsoft.com/en-us/library/ff759430.aspx

http://msdn.microsoft.com/en-us/library/ff759437.aspx

I am using standart Setup Project and I have added some custom actions within the installation process, where I register my provider's assembly and also register my provider under HKCU\Software\Microsoft\Office\Outlook\SocialConnector\SocialProviders. The installation proccess completes successfully but when I start an instance of Outlook, my custom provider does not exist in the providers list. Here is the code I use to register the assembly and write to the registry:

```<code>//I edit the WR here, where I am adding info about my provider
using (RegistryKey regKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Office\Outlook\SocialConnector\SocialProviders\CustomProvider.CustomProvider"))
{
    regKey.SetValue("FriendlyName", “CustomProvider”);
    regKey.SetValue("Url", “www.mySocialNetworkTest.com”);
}

//Register custom provider assembly
string file = base.Context.Parameters["assemblypath"];
RegistrationServices regsrv = new RegistrationServices();
Assembly assembly = Assembly.LoadFrom(file);

regsrv.RegisterAssembly(assembly, AssemblyRegistrationFlags.SetCodeBase);
</code>```

When I am using the manual process described in http://msdn.microsoft.com/en-us/library/ff759452.aspx to run my custom x64 provider on Outlook 64 bit within my Visual Studio(In debug mode) everthing is OK. My Provider appears in the OSC providers list.

After normal installation my provider is listed in the Windows Registry under:
HKEY_CLASSES_ROOT\CLSID\

HKEY_LOCAL_MACHINE\SOFTWARE\CLASSESS\CLSID\

HKEY_CURRENT_USER\Software\Microsoft\Office\Outlook\SocialConnector\SocialProviders

I am trying to find out why my provider does not appear in Outlook.
Would you explain the appropriate installation process about custom OSC provider on 64 bit version of Outlook (will be nice if there is an example). It will be great if you could provide me a list with the required key/value pairs situated in Windows Registy, needed for my custom provider to work.

p.s. I am a little bit confused about the role of the networkID value of my custom provider. Should I generate my custom provider’s networkID using guidgen.exe  and then to add it in the Windows Registry key - HKCU\Software\Microsoft\Office\Outlook\SocialConnector\SocialProviders  -> LocalProviderList (of course in I have added  the same value in SocialNetworkGuid Property of my provider) and should I add the networkId value anywhere else in the Windows Registry?

答:
Here is a sample project that will get you started.  Let me know if you have issues.

http://socialsetup.codeplex.com

It's on the download tab, and also checked in through TFS for online browsing.  Good luck, and do share details about your app when you can

ContentLicense: CC BY-SA 4.0

Body:
I have developed a simple outlook provider using C# 4.0 and VS 2010 but I am not able to create successfull installation package. I have read a lot of documentation, including links below and I have fullfilled all of the requirements for installing my custom provider on Win7 64 bit and MS Outlook (64 bit), but still I am not succeed.

These are the reference articles:

http://msdn.microsoft.com/en-us/library/ff759430.aspx

http://msdn.microsoft.com/en-us/library/ff759437.aspx

I am using standart Setup Project and I have added some custom actions within the installation process, where I register my provider's assembly and also register my provider under HKCU\Software\Microsoft\Office\Outlook\SocialConnector\SocialProviders. The installation proccess completes successfully but when I start an instance of Outlook, my custom provider does not exist in the providers list. Here is the code I use to register the assembly and write to the registry:

//I edit the WR here, where I am adding info about my provider
using (RegistryKey regKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Office\Outlook\SocialConnector\SocialProviders\CustomProvider.CustomProvider"))
{
    regKey.SetValue("FriendlyName", “CustomProvider”);
    regKey.SetValue("Url", “www.mySocialNetworkTest.com”);
}

//Register custom provider assembly
string file = base.Context.Parameters["assemblypath"];
RegistrationServices regsrv = new RegistrationServices();
Assembly assembly = Assembly.LoadFrom(file);

regsrv.RegisterAssembly(assembly, AssemblyRegistrationFlags.SetCodeBase);

When I am using the manual process described in http://msdn.microsoft.com/en-us/library/ff759452.aspx to run my custom x64 provider on Outlook 64 bit within my Visual Studio(In debug mode) everthing is OK. My Provider appears in the OSC providers list.

After normal installation my provider is listed in the Windows Registry under:
HKEY_CLASSES_ROOT\CLSID\

HKEY_LOCAL_MACHINE\SOFTWARE\CLASSESS\CLSID\

HKEY_CURRENT_USER\Software\Microsoft\Office\Outlook\SocialConnector\SocialProviders

I am trying to find out why my provider does not appear in Outlook.
Would you explain the appropriate installation process about custom OSC provider on 64 bit version of Outlook (will be nice if there is an example). It will be great if you could provide me a list with the required key/value pairs situated in Windows Registy, needed for my custom provider to work.

p.s. I am a little bit confused about the role of the networkID value of my custom provider. Should I generate my custom provider’s networkID using guidgen.exe  and then to add it in the Windows Registry key - HKCU\Software\Microsoft\Office\Outlook\SocialConnector\SocialProviders  -> LocalProviderList (of course in I have added  the same value in SocialNetworkGuid Property of my provider) and should I add the networkId value anywhere else in the Windows Registry?


问:
how to use jmathplot with java and maven?

I'm trying to plot a 3d surface using jmathplot. I currently have a java file that I run by using

```<code>javac Plot.java
java Plot
</code>```

Running the program returns 3 arrays corresponding to the x, y, and, z values of the graph. Where x[0], y[0], z[0] are the coordinates of the first point of the graph.

How do I use jmathplot to graph this 3d surface?

With python I would usually use

```<code>pip install jmathplot
</code>```

and then I can simply use

```<code>import jmathplot as jmp
</code>```

at the start of my code so that I can use any of the jmathplot functions.

I don't understand how this process works with Java. I'm not using eclipse because the whole program is really only a few files. I've read that you can use Maven and edit the pom.xml file but so far that hasn't been working for me either.

答:
First of all, you do not have to use an IDE. Although if you would then you will develop your project a lot easier. Writing a java project (no matter how big it is) without an IDE is like trying to make multiple calculations on paper. You have to use an IDE in order to make the development process far more easier and save a lot of time.

Secondly, if you want to include the jmathplot library to your project you have to include it as a maven dependency inside your pom file like below:

```<code><dependencies>
...
    <dependency>
      <groupId>com.github.yannrichet</groupId>
      <artifactId>JMathPlot</artifactId>
      <version>1.0.1</version>
    </dependency>
...
</dependencies
</code>```

Then you have to build your project with mvn install goal-phase in order to download and package the library into your local repository so to use it as a dependency in your project. You can read here more information about maven build phases and goals.

Finally, just import the library in the class where you want to use it like below:

```<code>import org.math.plot.*;
</code>```

Body:
I'm trying to plot a 3d surface using jmathplot. I currently have a java file that I run by using

javac Plot.java
java Plot

Running the program returns 3 arrays corresponding to the x, y, and, z values of the graph. Where x[0], y[0], z[0] are the coordinates of the first point of the graph.

How do I use jmathplot to graph this 3d surface?

With python I would usually use

pip install jmathplot

and then I can simply use

import jmathplot as jmp

at the start of my code so that I can use any of the jmathplot functions.

I don't understand how this process works with Java. I'm not using eclipse because the whole program is really only a few files. I've read that you can use Maven and edit the pom.xml file but so far that hasn't been working for me either.

Body:
First of all, you do not have to use an IDE. Although if you would then you will develop your project a lot easier. Writing a java project (no matter how big it is) without an IDE is like trying to make multiple calculations on paper. You have to use an IDE in order to make the development process far more easier and save a lot of time.

Secondly, if you want to include the jmathplot library to your project you have to include it as a maven dependency inside your pom file like below:

<dependencies>
...
    <dependency>
      <groupId>com.github.yannrichet</groupId>
      <artifactId>JMathPlot</artifactId>
      <version>1.0.1</version>
    </dependency>
...
</dependencies

Then you have to build your project with mvn install goal-phase in order to download and package the library into your local repository so to use it as a dependency in your project. You can read here more information about maven build phases and goals.

Finally, just import the library in the class where you want to use it like below:

import org.math.plot.*;


问:
Serverless plugin "serverless-offline" not found. Make sure it's installed and listed in the "plugins" section of your serverless config file
When I deploy my SLS project, I get the following error:

Serverless plugin "serverless-offline" not found. Make sure it's
  installed and listed in the "plugins" section of your serverless
  config file

But I did install the plugin serverless-offline correctly, please can someone help me fix it.

Here is my serverless.yml file:

```<code>   service: email-sender

    provider:
      name: aws
      runtime: nodejs4.3

    functions:
      send:
        handler: handler.send
        events:
          - http:
              path: submissions
              method: post
              response:
                headers:
                  Content-Type: "text/json"
              cors:
                origins:
                  - '*'
    package:
      exclude:
        - node_modules/**
      include:
        - node_modules/serverless-offline/**

    plugins:
      - serverless-offline
</code>```

答:
Serverless offline is a plugin to run only on your development machine, not in production.

To enable it add the following to serverless.yml:

```<code>    plugins:
      - serverless-offline
</code>```

and remove the following lines

```<code>      include:
        - node_modules/serverless-offline/**
</code>```

also check your package.json and make sure it is a devDependencies.

Body:
When I deploy my SLS project, I get the following error:

Serverless plugin "serverless-offline" not found. Make sure it's
  installed and listed in the "plugins" section of your serverless
  config file

But I did install the plugin serverless-offline correctly, please can someone help me fix it.

Here is my serverless.yml file:

   service: email-sender

    provider:
      name: aws
      runtime: nodejs4.3

    functions:
      send:
        handler: handler.send
        events:
          - http:
              path: submissions
              method: post
              response:
                headers:
                  Content-Type: "text/json"
              cors:
                origins:
                  - '*'
    package:
      exclude:
        - node_modules/**
      include:
        - node_modules/serverless-offline/**

    plugins:
      - serverless-offline

Body:
Serverless offline is a plugin to run only on your development machine, not in production.

To enable it add the following to serverless.yml:

    plugins:
      - serverless-offline

and remove the following lines

      include:
        - node_modules/serverless-offline/**

also check your package.json and make sure it is a devDependencies.


问:
Levenshtein implementation in Clojure with memoization
This is a minimal Levenshtein (edit distance) implementation using Clojure with recursion:

```<code>(defn levenshtein [s1, i1, s2, i2]
  (cond
    (= 0 i1) i2
    (= 0 i2) i1
    :else
    (min (+ (levenshtein s1 (- i1 1) s2 i2) 1)
         (+ (levenshtein s1 i1 s2 (- i2 1)) 1)
         (+ (levenshtein s1 (- i1 1) s2 (- i2 1)) (if (= (subs s1 i1 (+ i1 1)) (subs s2 i2 (+ i2 1))) 0 1))
         )
    )
  )

(defn levenshteinSimple [s1, s2]
  (levenshtein s1, (- (count s1) 1), s2, (- (count s2) 1)))
</code>```

Which can be used like this:

```<code>(println (levenshteinSimple "hello", "hilloo"))
(println (levenshteinSimple "hello", "hilloo"))
(println (levenshteinSimple "bananas", "bananas"))
(println (levenshteinSimple "ananas", "bananas"))
</code>```

And prints this:

```<code>2
2
0
1
</code>```

How can you add memoize to this implementation to improve performance?

Please note: I am a Clojure beginner. These are my first lines in Clojure

答:
The simplest way is to just make use of the memoize function. It takes a function, and returns a memoized function:

```<code>(let [mem-lev (memoize levenshteinSimple]
  (println (mem-lev "hello", "hilloo"))
  (println (mem-lev "hello", "hilloo"))
  (println (mem-lev "bananas", "bananas"))
  (println (mem-lev "ananas", "bananas")))
</code>```

mem-lev will memorize every argument you give it and the result of what your function returns, and will return the cached result if it's already seen the arguments that you gave it.

Note that this will not cause the recursive calls to become memoized, but it's unlikely that any recursive calls would benefit from memoization anyways.

This will also not cause your original function to become memoized. In this example, only mem-lev will be memoized. If you really wanted to have your global function memoized, you could change your definition to something like:

```<code>(def levenshteinSimple
  (memoize
    (fn [s1, s2]
      ...
</code>```

But I wouldn't recommend doing this. This causes the function itself to hold state, which isn't ideal. It'll also hold onto that state for the length of the program, which could cause memory issues if abused.

(As a great exercise, try writing your own version of memoize. I learned a lot by doing that).

Body:
This is a minimal Levenshtein (edit distance) implementation using Clojure with recursion:

(defn levenshtein [s1, i1, s2, i2]
  (cond
    (= 0 i1) i2
    (= 0 i2) i1
    :else
    (min (+ (levenshtein s1 (- i1 1) s2 i2) 1)
         (+ (levenshtein s1 i1 s2 (- i2 1)) 1)
         (+ (levenshtein s1 (- i1 1) s2 (- i2 1)) (if (= (subs s1 i1 (+ i1 1)) (subs s2 i2 (+ i2 1))) 0 1))
         )
    )
  )

(defn levenshteinSimple [s1, s2]
  (levenshtein s1, (- (count s1) 1), s2, (- (count s2) 1)))

Which can be used like this:

(println (levenshteinSimple "hello", "hilloo"))
(println (levenshteinSimple "hello", "hilloo"))
(println (levenshteinSimple "bananas", "bananas"))
(println (levenshteinSimple "ananas", "bananas"))

And prints this:

2
2
0
1

How can you add memoize to this implementation to improve performance?

Please note: I am a Clojure beginner. These are my first lines in Clojure

Body:
The simplest way is to just make use of the memoize function. It takes a function, and returns a memoized function:

(let [mem-lev (memoize levenshteinSimple]
  (println (mem-lev "hello", "hilloo"))
  (println (mem-lev "hello", "hilloo"))
  (println (mem-lev "bananas", "bananas"))
  (println (mem-lev "ananas", "bananas")))

mem-lev will memorize every argument you give it and the result of what your function returns, and will return the cached result if it's already seen the arguments that you gave it.

Note that this will not cause the recursive calls to become memoized, but it's unlikely that any recursive calls would benefit from memoization anyways.

This will also not cause your original function to become memoized. In this example, only mem-lev will be memoized. If you really wanted to have your global function memoized, you could change your definition to something like:

(def levenshteinSimple
  (memoize
    (fn [s1, s2]
      ...

But I wouldn't recommend doing this. This causes the function itself to hold state, which isn't ideal. It'll also hold onto that state for the length of the program, which could cause memory issues if abused.

(As a great exercise, try writing your own version of memoize. I learned a lot by doing that).


问:
Is it possible to add image to content of label wpf
I wonder if it is possible to add an image to the content of the label.
Now label is something like that:

```<code><Label Content="some text" />
</code>```

And my target is to add a small icon near to the text.

答:
You can set the Content to a Panel that contains both a TextBlock and an Image:

```<code><Label>
    <StackPanel Orientation="Horizontal">
        <TextBlock>some text...</TextBlock>
        <Image Source="pic.png" Width="40" Height="40" />
    </StackPanel>
</Label>
</code>```

Body:
I wonder if it is possible to add an image to the content of the label.
Now label is something like that:

And my target is to add a small icon near to the text.

Body:
You can set the Content to a Panel that contains both a TextBlock and an Image:

<Label>
    <StackPanel Orientation="Horizontal">
        <TextBlock>some text...</TextBlock>
        <Image Source="pic.png" Width="40" Height="40" />
    </StackPanel>
</Label>


问:
React TransitionGroup lifecycle methods not being called when component is loaded
I'm trying to animate a list entering and exiting with gsap, so I wrapped my list with <TransitionGroup>. I want to use componentWillEnter and componentWillLeave to trigger my animations, but they aren't being called. I've checked everything 1000x and can't figure it out... Should I be using <Transition> instead for this sort of animation?

```<code>import React from "react";
import { TransitionGroup } from "react-transition-group";

import animations from './animations';

class Events extends React.Component {
  componentWillEnter(cb) {
    console.log('entered');
    const items = document.getElementsByClassName("items");
    animations.animateIn(items, cb);
  }
  componentWillLeave(cb) {
    console.log('exited');
    const items = document.getElementsByClassName("items");
    animations.animateOut(items, cb);
  }

  render() {
    const event = this.props.event;
    return (
      <li key={event._id} className="items">
        <h1>{event.title}</h1>
      </li>
    );
  }
}

class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      events: []
    };
  }
  componentDidMount() {
    return fetch("https://pickup-btown.herokuapp.com/api/event/biking",
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json"
      },
      mode: "cors"
    })
      .then(response => {
        return response.json();
      })
      .then(events => {
        this.setState({ events: events.docs });
      })
      .catch(err => console.log(err));
  }

  unLoad(e) {
    e.preventDefault();
    this.setState({ events: [] });
  }
  render() {
    const events = this.state.events;
    return (
      <section>
        <button onClick={this.unLoad.bind(this)}>back</button>
        <TransitionGroup component="ul">
          {events.length ? (
            events.map(event => {
              return <Events event={event} key={event._id} />;
            })
          ) : (
            <div />
          )}
        </TransitionGroup>
      </section>
    );
  }
}

export default Main;
</code>```

Any help would be much appreciated!

答:
Child component life cycle methods has been removed in current react-transition-group and you can use onEnter and onExit methods to achieve like in your Events component will be

```<code>class Events extends React.Component {
  render() {
    const event = this.props.event;
    return (
      <Transition
        timeout={300}
        key={event._id}
        onEntering={el => console.log("Entering", el)}
        onEnter={el => console.log("enter", el)}
        onExit={el => console.log("exit", el)}
        in={true}
      >
        <li
          key={event._id}
          className="items"
        >
          <h1>{event.title}</h1>
        </li>
      </Transition>
    );
  }
}
</code>```

I have worked on your codesandbox also and its working. For detailed info please go through documentation.

Body:
I'm trying to animate a list entering and exiting with gsap, so I wrapped my list with <TransitionGroup>. I want to use componentWillEnter and componentWillLeave to trigger my animations, but they aren't being called. I've checked everything 1000x and can't figure it out... Should I be using <Transition> instead for this sort of animation?

import React from "react";
import { TransitionGroup } from "react-transition-group";

import animations from './animations';

class Events extends React.Component {
  componentWillEnter(cb) {
    console.log('entered');
    const items = document.getElementsByClassName("items");
    animations.animateIn(items, cb);
  }
  componentWillLeave(cb) {
    console.log('exited');
    const items = document.getElementsByClassName("items");
    animations.animateOut(items, cb);
  }

  render() {
    const event = this.props.event;
    return (

{event.title}

    );
  }
}

class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      events: []
    };
  }
  componentDidMount() {
    return fetch("https://pickup-btown.herokuapp.com/api/event/biking",
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json"
      },
      mode: "cors"
    })
      .then(response => {
        return response.json();
      })
      .then(events => {
        this.setState({ events: events.docs });
      })
      .catch(err => console.log(err));
  }

  unLoad(e) {
    e.preventDefault();
    this.setState({ events: [] });
  }
  render() {
    const events = this.state.events;
    return (

        <button onClick={this.unLoad.bind(this)}>back</button>
        <TransitionGroup component="ul">
          {events.length ? (
            events.map(event => {
              return <Events event={event} key={event._id} />;
            })
          ) : (

          )}
        </TransitionGroup>

    );
  }
}

export default Main;

Any help would be much appreciated!

Body:
Child component life cycle methods has been removed in current react-transition-group and you can use onEnter and onExit methods to achieve like in your Events component will be

class Events extends React.Component {
  render() {
    const event = this.props.event;
    return (
      <Transition
        timeout={300}
        key={event._id}
        onEntering={el => console.log("Entering", el)}
        onEnter={el => console.log("enter", el)}
        onExit={el => console.log("exit", el)}
        in={true}
      >
        <li
          key={event._id}
          className="items"
        >
          <h1>{event.title}</h1>
        </li>
      </Transition>
    );
  }
}

I have worked on your codesandbox also and its working. For detailed info please go through documentation.


问:
CallKit can reactivate sound after swapping call
I'm developing CallKit application, I have a problem, Call Holding is failing to restart audio when "swapping" calls on the CallKit screen until user returns to in-app call screen. I can bypass this by updating:

```<code>supportsHolding = false
</code>```

but I can I solve this problem, whatsapp for example can do this correctly!

p.s. I'm using webrtc to make a call!

thanks!

EDIT:

This is code of provider:

```<code>public func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {

    guard let call = conductor!.callWithUUID(uuid: action.callUUID) else {
        WebRtcConductor.debug("\(self.TAG)  failed to perform HeldAction: uuid: \(action.uuid), calluiid: \(action.callUUID)")
        action.fail()
        return
    }

    setIsHeld(call: call, isHeld: action.isOnHold)
    action.fulfill()
}
</code>```

the setIsHeld function simply do:

```<code>audioTrack.isEnabled = enabled
</code>```

If I use "mute" button of callkit screen, all works fine, but if I have 2 active calls, when I swipe from webrtc call to normal call, CXSetHeldCallAction is called and audio track did disabled, If I swipe again to webrtc call, audio track is enabled but i do not hear nothing, if I return to main app screen, audio works fine again!

答:
Had the same issue. If I have 1 active call, then new calls is incoming, I tap hold&accept. New call works, but after using Swap in CallKit audio stops working.

Found that provider:performSetHeldCallAction: method from CXProviderDelegate protocol is the spot where you can actually deactivate/activate audio for Swap calls via CallKit native interface.

In my case I used the audioController.deactivateAudioSession() method for the call was putting in OnHold.
But found that the same method provider:performSetHeldCallAction: was fired for other call that is being put active (from OnHold state), when tap Swap button via CallKit.

So you just need to deactivate/activate audio respectively to call's state (either hold or not).

In common way it should look this way:

```<code>func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {
    // Retrieve the Call instance corresponding to the action's call UUID
    guard let call = callManager.callWithUUID(uuid: action.callUUID) else {
        action.fail()
        return
    }

    // Update the Call's underlying hold state.
    call.isOnHold = action.isOnHold

    // Stop or start audio in response to holding or unholding the call.
    if call.isOnHold {
        stopAudio()
    } else {
        startAudio()
    }

    // Signal to the system that the action has been successfully performed.
    action.fulfill()
}
</code>```

P.S. It looks like you should have some class that responds for Audio session. It should implement kind of activate audio session / deactivate audio session.

Body:
I'm developing CallKit application, I have a problem, Call Holding is failing to restart audio when "swapping" calls on the CallKit screen until user returns to in-app call screen. I can bypass this by updating:

supportsHolding = false

but I can I solve this problem, whatsapp for example can do this correctly!

p.s. I'm using webrtc to make a call!

thanks!

EDIT:

This is code of provider:

public func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {

    guard let call = conductor!.callWithUUID(uuid: action.callUUID) else {
        WebRtcConductor.debug("\(self.TAG)  failed to perform HeldAction: uuid: \(action.uuid), calluiid: \(action.callUUID)")
        action.fail()
        return
    }

    setIsHeld(call: call, isHeld: action.isOnHold)
    action.fulfill()
}

the setIsHeld function simply do:

audioTrack.isEnabled = enabled

If I use "mute" button of callkit screen, all works fine, but if I have 2 active calls, when I swipe from webrtc call to normal call, CXSetHeldCallAction is called and audio track did disabled, If I swipe again to webrtc call, audio track is enabled but i do not hear nothing, if I return to main app screen, audio works fine again!

Body:
Had the same issue. If I have 1 active call, then new calls is incoming, I tap hold&accept. New call works, but after using Swap in CallKit audio stops working.

Found that provider:performSetHeldCallAction: method from CXProviderDelegate protocol is the spot where you can actually deactivate/activate audio for Swap calls via CallKit native interface.

In my case I used the audioController.deactivateAudioSession() method for the call was putting in OnHold.
But found that the same method provider:performSetHeldCallAction: was fired for other call that is being put active (from OnHold state), when tap Swap button via CallKit.

So you just need to deactivate/activate audio respectively to call's state (either hold or not).

In common way it should look this way:

func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {
    // Retrieve the Call instance corresponding to the action's call UUID
    guard let call = callManager.callWithUUID(uuid: action.callUUID) else {
        action.fail()
        return
    }

    // Update the Call's underlying hold state.
    call.isOnHold = action.isOnHold

    // Stop or start audio in response to holding or unholding the call.
    if call.isOnHold {
        stopAudio()
    } else {
        startAudio()
    }

    // Signal to the system that the action has been successfully performed.
    action.fulfill()
}

P.S. It looks like you should have some class that responds for Audio session. It should implement kind of activate audio session / deactivate audio session.


问:
No more background on 100% height when scrolling page
This should be an easy one for you guys..

How can I give the blue background a full 100% height from top to bottom by only using CSS2 and HTML ? (no javascript!) When the page contains a scrollbar the offscreen part will go blank if you scroll down.

Copy paste this code, and see for yourself:

```<code><html>
  <body>
      <div id="mainContent" style="height: 100%; position:absolute; top:0px; left: 50%; right:0px; bottom:0px; background:#06C; z-index:-1"></div>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ac tortor purus, lacinia tincidunt urna. Duis nec massa vel est dictum sollicitudin. Morbi vestibulum metus quis mi aliquam sagittis condimentum nisi posuere. Donec imperdiet, eros vitae tincidunt sagittis, nisl ipsum tempor nisl, eu dapibus lorem mi vitae lorem. Pellentesque consectetur semper turpis id tincidunt. Aenean eu metus vitae augue rutrum porta. Ut viverra mauris id est sollicitudin at vestibulum leo suscipit. Praesent nibh mi, mattis eu elementum vel, laoreet eu augue. Suspendisse pellentesque enim quis lacus tincidunt lobortis. Etiam pharetra arcu a dui vulputate pretium sit amet id eros. Pellentesque et magna ac metus placerat tristique. Praesent sit amet sem metus. Suspendisse ut arcu quam. Cras magna velit, sollicitudin eu ornare sed, aliquet at velit. Proin purus augue, faucibus in sollicitudin vitae, porttitor sit amet purus. Maecenas tempus congue sodales. Suspendisse tincidunt tempor erat, id faucibus neque iaculis sit amet.</p>
<p>
Phasellus bibendum lorem turpis. Mauris imperdiet mattis sapien, eget blandit urna egestas sit amet. Maecenas tincidunt gravida ullamcorper. Donec pharetra ipsum volutpat justo venenatis vestibulum. Ut lacinia justo sed odio pellentesque in bibendum augue mollis. Aliquam in laoreet lectus. Fusce in lorem vitae augue vulputate consectetur. Phasellus at diam elit, at posuere urna. Nunc pulvinar suscipit fermentum. Vestibulum vel orci enim. Aenean in sollicitudin risus. Quisque turpis leo, placerat at sollicitudin at, molestie et risus. Etiam feugiat, elit nec pellentesque gravida, ligula dolor blandit est, vitae ultrices libero augue vel nibh.</p>
<p>
Suspendisse dignissim posuere eros. Praesent egestas varius nibh sed elementum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque tortor ipsum, pulvinar in vestibulum ut, porta nec nisi. Vivamus mi purus, convallis vitae suscipit at, consectetur vel justo. Vivamus erat neque, luctus accumsan dictum eget, consectetur vitae ligula. Nunc eget orci ut felis suscipit porta. Cras tincidunt lectus ut massa facilisis ullamcorper accumsan velit ultricies. Sed ullamcorper leo eget elit molestie interdum. Cras sollicitudin mattis orci, in porttitor augue accumsan ac. Suspendisse potenti. Nunc semper purus nec arcu iaculis placerat. Vestibulum sed neque ligula, eget cursus arcu.</p>
<p>
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin ante sem, porttitor in venenatis eget, egestas ultricies arcu. Nullam lacinia vehicula dui, sed bibendum lacus interdum vestibulum. Donec sagittis lectus eget nulla blandit at ornare purus faucibus. Vivamus quis augue in neque viverra posuere quis vitae mauris. Proin a felis sapien. Aenean sed felis nulla, non molestie metus. Etiam bibendum commodo blandit. In aliquet, dui vel tempor mollis, sem mauris interdum dolor, eu aliquam augue sem eget mauris. Ut ipsum nulla, vestibulum quis feugiat ac, sollicitudin et est. Nunc et massa vitae arcu pulvinar porta. Sed elementum egestas adipiscing. Sed quis quam id odio eleifend rutrum. Ut libero nulla, auctor eget pellentesque in, placerat non lorem. In fermentum velit eu augue hendrerit rutrum. Donec adipiscing pretium justo, id iaculis metus scelerisque a. Mauris pretium volutpat justo, non pellentesque eros blandit et. Vestibulum tristique interdum erat volutpat molestie. Nullam pretium dictum nulla quis facilisis. Sed massa libero, lacinia ac volutpat non, pharetra non lorem.</p>
<p>
Donec gravida neque eu ante dapibus in suscipit nisi pellentesque. Cras egestas faucibus mi nec adipiscing. Donec sodales nunc sit amet augue egestas sed suscipit dui accumsan. In libero risus, blandit ut semper id, volutpat ullamcorper felis. Quisque vitae tortor mauris, ut venenatis turpis. Donec tristique cursus lacinia. Etiam vel odio dolor. Duis posuere mattis semper. Ut euismod mattis luctus. Donec pellentesque euismod purus, vel rhoncus turpis tincidunt sit amet. In vitae libero turpis. Aliquam suscipit suscipit feugiat. Mauris eu magna enim, sit amet egestas diam. Praesent nibh turpis, ultricies a dapibus in, posuere et dui. Pellentesque pellentesque augue a est aliquet ut tincidunt augue pulvinar. Nam vel lacus erat. Praesent id dolor sapien. </p>
<p>
Donec gravida neque eu ante dapibus in suscipit nisi pellentesque. Cras egestas faucibus mi nec adipiscing. Donec sodales nunc sit amet augue egestas sed suscipit dui accumsan. In libero risus, blandit ut semper id, volutpat ullamcorper felis. Quisque vitae tortor mauris, ut venenatis turpis. Donec tristique cursus lacinia. Etiam vel odio dolor. Duis posuere mattis semper. Ut euismod mattis luctus. Donec pellentesque euismod purus, vel rhoncus turpis tincidunt sit amet. In vitae libero turpis. Aliquam suscipit suscipit feugiat. Mauris eu magna enim, sit amet egestas diam. Praesent nibh turpis, ultricies a dapibus in, posuere et dui. Pellentesque pellentesque augue a est aliquet ut tincidunt augue pulvinar. Nam vel lacus erat. Praesent id dolor sapien. </p>
  </body>
</html>
</code>```

答:
Give the parent element the position: relative property.

So in your case, give the body element this property:

```<code>body {
    position: relative;
}
</code>```

DEMO: http://jsfiddle.net/marcuswhybrow/wNbgG/

P.S. Don't use the style attribute unless absolutely necessary, it leads to unmanageable code. You should prefer using CSS rules instead.

Body:
This should be an easy one for you guys..

How can I give the blue background a full 100% height from top to bottom by only using CSS2 and HTML ? (no javascript!) When the page contains a scrollbar the offscreen part will go blank if you scroll down.

Copy paste this code, and see for yourself:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ac tortor purus, lacinia tincidunt urna. Duis nec massa vel est dictum sollicitudin. Morbi vestibulum metus quis mi aliquam sagittis condimentum nisi posuere. Donec imperdiet, eros vitae tincidunt sagittis, nisl ipsum tempor nisl, eu dapibus lorem mi vitae lorem. Pellentesque consectetur semper turpis id tincidunt. Aenean eu metus vitae augue rutrum porta. Ut viverra mauris id est sollicitudin at vestibulum leo suscipit. Praesent nibh mi, mattis eu elementum vel, laoreet eu augue. Suspendisse pellentesque enim quis lacus tincidunt lobortis. Etiam pharetra arcu a dui vulputate pretium sit amet id eros. Pellentesque et magna ac metus placerat tristique. Praesent sit amet sem metus. Suspendisse ut arcu quam. Cras magna velit, sollicitudin eu ornare sed, aliquet at velit. Proin purus augue, faucibus in sollicitudin vitae, porttitor sit amet purus. Maecenas tempus congue sodales. Suspendisse tincidunt tempor erat, id faucibus neque iaculis sit amet.

Phasellus bibendum lorem turpis. Mauris imperdiet mattis sapien, eget blandit urna egestas sit amet. Maecenas tincidunt gravida ullamcorper. Donec pharetra ipsum volutpat justo venenatis vestibulum. Ut lacinia justo sed odio pellentesque in bibendum augue mollis. Aliquam in laoreet lectus. Fusce in lorem vitae augue vulputate consectetur. Phasellus at diam elit, at posuere urna. Nunc pulvinar suscipit fermentum. Vestibulum vel orci enim. Aenean in sollicitudin risus. Quisque turpis leo, placerat at sollicitudin at, molestie et risus. Etiam feugiat, elit nec pellentesque gravida, ligula dolor blandit est, vitae ultrices libero augue vel nibh.

Suspendisse dignissim posuere eros. Praesent egestas varius nibh sed elementum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque tortor ipsum, pulvinar in vestibulum ut, porta nec nisi. Vivamus mi purus, convallis vitae suscipit at, consectetur vel justo. Vivamus erat neque, luctus accumsan dictum eget, consectetur vitae ligula. Nunc eget orci ut felis suscipit porta. Cras tincidunt lectus ut massa facilisis ullamcorper accumsan velit ultricies. Sed ullamcorper leo eget elit molestie interdum. Cras sollicitudin mattis orci, in porttitor augue accumsan ac. Suspendisse potenti. Nunc semper purus nec arcu iaculis placerat. Vestibulum sed neque ligula, eget cursus arcu.

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin ante sem, porttitor in venenatis eget, egestas ultricies arcu. Nullam lacinia vehicula dui, sed bibendum lacus interdum vestibulum. Donec sagittis lectus eget nulla blandit at ornare purus faucibus. Vivamus quis augue in neque viverra posuere quis vitae mauris. Proin a felis sapien. Aenean sed felis nulla, non molestie metus. Etiam bibendum commodo blandit. In aliquet, dui vel tempor mollis, sem mauris interdum dolor, eu aliquam augue sem eget mauris. Ut ipsum nulla, vestibulum quis feugiat ac, sollicitudin et est. Nunc et massa vitae arcu pulvinar porta. Sed elementum egestas adipiscing. Sed quis quam id odio eleifend rutrum. Ut libero nulla, auctor eget pellentesque in, placerat non lorem. In fermentum velit eu augue hendrerit rutrum. Donec adipiscing pretium justo, id iaculis metus scelerisque a. Mauris pretium volutpat justo, non pellentesque eros blandit et. Vestibulum tristique interdum erat volutpat molestie. Nullam pretium dictum nulla quis facilisis. Sed massa libero, lacinia ac volutpat non, pharetra non lorem.

Donec gravida neque eu ante dapibus in suscipit nisi pellentesque. Cras egestas faucibus mi nec adipiscing. Donec sodales nunc sit amet augue egestas sed suscipit dui accumsan. In libero risus, blandit ut semper id, volutpat ullamcorper felis. Quisque vitae tortor mauris, ut venenatis turpis. Donec tristique cursus lacinia. Etiam vel odio dolor. Duis posuere mattis semper. Ut euismod mattis luctus. Donec pellentesque euismod purus, vel rhoncus turpis tincidunt sit amet. In vitae libero turpis. Aliquam suscipit suscipit feugiat. Mauris eu magna enim, sit amet egestas diam. Praesent nibh turpis, ultricies a dapibus in, posuere et dui. Pellentesque pellentesque augue a est aliquet ut tincidunt augue pulvinar. Nam vel lacus erat. Praesent id dolor sapien.

Donec gravida neque eu ante dapibus in suscipit nisi pellentesque. Cras egestas faucibus mi nec adipiscing. Donec sodales nunc sit amet augue egestas sed suscipit dui accumsan. In libero risus, blandit ut semper id, volutpat ullamcorper felis. Quisque vitae tortor mauris, ut venenatis turpis. Donec tristique cursus lacinia. Etiam vel odio dolor. Duis posuere mattis semper. Ut euismod mattis luctus. Donec pellentesque euismod purus, vel rhoncus turpis tincidunt sit amet. In vitae libero turpis. Aliquam suscipit suscipit feugiat. Mauris eu magna enim, sit amet egestas diam. Praesent nibh turpis, ultricies a dapibus in, posuere et dui. Pellentesque pellentesque augue a est aliquet ut tincidunt augue pulvinar. Nam vel lacus erat. Praesent id dolor sapien.

Body:
Give the parent element the position: relative property.

So in your case, give the body element this property:

body {
    position: relative;
}

DEMO: http://jsfiddle.net/marcuswhybrow/wNbgG/

P.S. Don't use the style attribute unless absolutely necessary, it leads to unmanageable code. You should prefer using CSS rules instead.


问:
Writing a custom Qt Location GeoServices plugin to use geo-referenced image file as map source
I'm currently working on a Qt Quick application that will provide a map viewer for a smallish area (1 square KM or so), the map details for which will be provided in a single geo-referenced image file (GeoTIFF, geo-referenced PDF, ESRI Shape file etc.), along with display of current location, operator identified points of interest etc. It's primarily responsibility is the display of custom maps (as opposed to generic maps retrieved from public map image service providers (OSM, MabBox, ESRI etc)), and it will often be used in areas with limited connectivity

An extensive web search has identified others who have made similar enquiries in the past (here, Qt forums etc), and the general suggestions for solutions are as follows:

ArcGIS Runtime with Qt SDK Doesn't work for me as down the track I'm intending to target an embedded linux device using an ARM processor, and ArcGIS doesn't make source available for cross-compilation for arbitrary targets. They've recently produced an Android release, but nothing for ARM linux in general)

QGIS developer libraries GPL licence not compatible with my commercial development

Use the Qt Location Map component with a local tile server or offline tile collection (some plugins have recently introduced support for this) Seems a bit of a hack, as noted I'm primarily using custom maps, as opposed to offline copies of public map server images, and my images won't be big enough to really warrant tiling otherwise

It would be feasible to develop a Qt Quick component from scratch to do this, but given that the existing Qt Location Map component provides a well defined pre-existing front end interface for everything my map would need to do and has an extendable plugin based architecture, writing a custom Qt Location GeoServices plugin seems the most sensible and elegant way forward.

I've started examining the source code of the existing plugins, but can't shake the feeling that in a world containing 8 billion people, with "nothing new under the sun", this would have been done already if it was a good idea....

Would anyone with more familiarity with the Qt Location module care to comment?

答:
Since geo-referenced images can be arbitrarily large, it is the standard to convert them into a tile pyramid, to be able to efficiently display them on any hardware (at the cost of doubling the size, at worst, depending on how many layers you want).
Even if you would write your own geoservice plugin, you most likely will end up (directly or by using 3rd party code) tiling your geotiff.

This said, QtLocation does allow you to use custom tilesets ( http://doc.qt.io/qt-5/location-plugin-osm.html, look for osm.mapping.custom.host) served in most ways (http, https, file, qrc, etc.).

So go ahead, fire up QGis, install the QTiler plugin, and convert your images.
If you need to serve these pictures over the net directly to the clients (thus needing to do the conversion on the client), you can either see what QTiler does, or build up your gdal pipeline (gdal_translate, gdalwarp and gdal2tiles), and ship the relevant gdal bits with your application.

If you need multiple images at the same time, you can either use multiple Plugin elements with different plugin parameters, or you can fork the osm plugin and support multiple custom hosts.


问:
Why is this std::vector being cleared when program enters main function?
The problem I'm having is that I am pushing an element into a vector at initialisation when all the static variables are initialised, and then when it enters the main function the vector resets to 0, as if it has cleared. In my case the vector was in a different CPP, but this also shows the problem:

```<code>#include <iostream>
#include <vector>

struct List
{
    static std::vector<int> listVector;
};

struct Foo
{
    Foo()
    {
        std::cout << List::listVector.size() << '\n';   // Prints 0
        List::listVector.push_back(1);
        std::cout << List::listVector.size() << '\n';   // Prints 1
    }
};
Foo fooObj;

std::vector<int> List::listVector;

int main()
{
    std::cout << List::listVector.size() << '\n';   // Prints 0
    List::listVector.push_back(2);
    std::cout << List::listVector.size() << '\n';   // Prints 1
}
</code>```

The first element I added to the vector has been lost. I know one has to be careful with initialisation order of static global variables, but I can't understand why the vector is being cleared. I'm tempted to think that when the Foo constructor runs it adds an element to the vector, but the vector hasn't been created yet, because it's written on the line after the Foo object is created. However, if this is the case, just what vector am I adding into when I do so in the constructor and it prints out a size of 1?

I'm kind of confused.

答:
You have to understand that your program doesn't run from top to bottom. Every programm will start at your main() function. All the code above main() will basically get ignored if it doesn't get called in the main() function.

Questions like these should not be asked here though. It seems like you are a beginner and you should start by reading yourself more into the subject before asking questions.

Body:
The problem I'm having is that I am pushing an element into a vector at initialisation when all the static variables are initialised, and then when it enters the main function the vector resets to 0, as if it has cleared. In my case the vector was in a different CPP, but this also shows the problem:

#include <iostream>
#include <vector>

struct List
{
    static std::vector<int> listVector;
};

struct Foo
{
    Foo()
    {
        std::cout << List::listVector.size() << '\n';   // Prints 0
        List::listVector.push_back(1);
        std::cout << List::listVector.size() << '\n';   // Prints 1
    }
};
Foo fooObj;

std::vector<int> List::listVector;

int main()
{
    std::cout << List::listVector.size() << '\n';   // Prints 0
    List::listVector.push_back(2);
    std::cout << List::listVector.size() << '\n';   // Prints 1
}

The first element I added to the vector has been lost. I know one has to be careful with initialisation order of static global variables, but I can't understand why the vector is being cleared. I'm tempted to think that when the Foo constructor runs it adds an element to the vector, but the vector hasn't been created yet, because it's written on the line after the Foo object is created. However, if this is the case, just what vector am I adding into when I do so in the constructor and it prints out a size of 1?

I'm kind of confused.


问:
Codeception Recorder is disabled, no available modules
In order to record my tests I run codeception with this command

```<code>codecept --ext Recorder
</code>```

However I can't manage to record anything. Does one see what I'm doing wrong?

```<code>Codeception Recorder is disabled, no available modules:
</code>```

gravityflow/codeception.dist.yml

gravityflow/plugin/tests/acceptance-tests/acceptance.suite.yml:

答:
You're using the WordPress module, WPWebDriver. You need to tell recorder it's active. Put this in your main codeception.yml file:

```<code>extensions:
    enabled:
        - Codeception\Extension\RunFailed
        - Codeception\Extension\Recorder
    config:
        Codeception\Extension\Recorder:
            delete_successful: false
            module: WPWebDriver
</code>```

Body:
In order to record my tests I run codeception with this command

codecept --ext Recorder

However I can't manage to record anything. Does one see what I'm doing wrong?

Codeception Recorder is disabled, no available modules:

gravityflow/codeception.dist.yml

gravityflow/plugin/tests/acceptance-tests/acceptance.suite.yml:

Body:
You're using the WordPress module, WPWebDriver. You need to tell recorder it's active. Put this in your main codeception.yml file:

extensions:
    enabled:
        - Codeception\Extension\RunFailed
        - Codeception\Extension\Recorder
    config:
        Codeception\Extension\Recorder:
            delete_successful: false
            module: WPWebDriver


问:
Visual Studio 2017 v15.5 Aspnet Core 2.0.3 fails to debug on IISExpress
After I recently updated my visual studio 2017 installation from 15.4.5 to 15.5 I have lost the ability to hit breakpoints in my aspnet core 2.0 applications. The configuration is in debug any cpu.

While this works fine on kestrel (Debugging as a consoile app), on IISExpress it does not hit my breakpoints.

As a sidenote the weird thing here is it seems to have the debug symbols loaded on runtime (the breakpoint is correctly highlighted) and no warning.

Environment:

```<code>Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.16299
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\2.1.2\

Microsoft .NET Core Shared Framework Host

  Version  : 2.0.3
  Build    : a9190d4a75f4a982ae4b4fa8d1a24526566c69df

Microsoft Visual Studio Enterprise 2017

  Version  : 15.5.0
</code>```

I have already tried to repair visual studio but the problem persists

答:
After careful inspection of my last commit after I updated to 15.5 I noticed that I had an unintentional change to my launchSettings.json file located under my project Properties folder. There was a new use64bit setting added and was set by vs to true.

I had to set it to false in order for visualstudio to work with debugging on iisexpress. Below is my current state of the IIS Express profile in launchSettings.json

```<code>{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:20202",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "use64Bit": false
    }
}
</code>```

Body:
After I recently updated my visual studio 2017 installation from 15.4.5 to 15.5 I have lost the ability to hit breakpoints in my aspnet core 2.0 applications. The configuration is in debug any cpu.

While this works fine on kestrel (Debugging as a consoile app), on IISExpress it does not hit my breakpoints.

As a sidenote the weird thing here is it seems to have the debug symbols loaded on runtime (the breakpoint is correctly highlighted) and no warning.

Environment:

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.16299
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\2.1.2\

Microsoft .NET Core Shared Framework Host

  Version  : 2.0.3
  Build    : a9190d4a75f4a982ae4b4fa8d1a24526566c69df

Microsoft Visual Studio Enterprise 2017

  Version  : 15.5.0

I have already tried to repair visual studio but the problem persists

Body:
After careful inspection of my last commit after I updated to 15.5 I noticed that I had an unintentional change to my launchSettings.json file located under my project Properties folder. There was a new use64bit setting added and was set by vs to true.

I had to set it to false in order for visualstudio to work with debugging on iisexpress. Below is my current state of the IIS Express profile in launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:20202",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "use64Bit": false
    }
}


问:
Problem with multi threaded / invocation:(
i have 2 script 1- Soket.cs (Soket Server Working with thread) FormMain.cs(Working Normal) i call a function in FormMain from soket.cs with this code :

```<code>public void ResiveFunc(string FuncResive)
{

    string FuncName = "";
    string FuncValue = "";
    for (int i = 0; i <= 2; i++)
    {
        FuncName += FuncResive[i];
    }
    for (int j = 4; j <= FuncResive.Length - 1; j++)
    {
        FuncValue += FuncResive[j];
    }
    MessageBox.Show(FuncName);
    MessageBox.Show(FuncValue);
    if (FuncName == "TAB")
    {
        Form1 mainForm = new Form1();
        mainForm.AdverFilter(FuncValue);
    }

}
</code>```

i call this AdverFilter() function in FormMain :

```<code>  public void AdverFilter(string value)
    {
        if (this.InvokeRequired)
        {

            this.BeginInvoke(new Action<string>(AdverFilter),value);
        }
        else
        {
            this.richTextBox1.Text = value;
            MessageBox.Show("AdverFilter(string value)");
            MessageBox.Show(this.richTextBox1.Text);
        }

    }
</code>```

but its dont work!!! Messagebox show fine the value but richtextbox.text is null in GUI (after the function is ended)... please tell me how can i fix this problem...!?

答:
send a string clone:</p>

```<code>mainForm.AdverFilter(FuncValue.Clone());

this.BeginInvoke(new Action<string>(AdverFilter),value.Clone());
</code>```

Body:
i have 2 script 1- Soket.cs (Soket Server Working with thread) FormMain.cs(Working Normal) i call a function in FormMain from soket.cs with this code :

public void ResiveFunc(string FuncResive)
{

    string FuncName = "";
    string FuncValue = "";
    for (int i = 0; i <= 2; i++)
    {
        FuncName += FuncResive[i];
    }
    for (int j = 4; j <= FuncResive.Length - 1; j++)
    {
        FuncValue += FuncResive[j];
    }
    MessageBox.Show(FuncName);
    MessageBox.Show(FuncValue);
    if (FuncName == "TAB")
    {
        Form1 mainForm = new Form1();
        mainForm.AdverFilter(FuncValue);
    }

}

i call this AdverFilter() function in FormMain :

  public void AdverFilter(string value)
    {
        if (this.InvokeRequired)
        {

            this.BeginInvoke(new Action<string>(AdverFilter),value);
        }
        else
        {
            this.richTextBox1.Text = value;
            MessageBox.Show("AdverFilter(string value)");
            MessageBox.Show(this.richTextBox1.Text);
        }

    }

but its dont work!!! Messagebox show fine the value but richtextbox.text is null in GUI (after the function is ended)... please tell me how can i fix this problem...!?

Body:
send a string clone:

mainForm.AdverFilter(FuncValue.Clone());

this.BeginInvoke(new Action<string>(AdverFilter),value.Clone());


问:
IncompatibleClassChangeError: Class 'java.lang.VirtualMachineError' does not implement interface 'java.lang.CharSequence'
I am having weird problems with my code and I cannot explain anything that's happening. It's crashing on Marshmallow but not on Nougat which makes this more bizarre.

I can point to a line where the error occurs but the error itself is not clear. I am not sure what is crashing and how to prevent it. Here are the details:

The crash happens when I try to make a call to the server. To do this, I use Retrofit alongside RxJava and I do this in Kotlin. Here is my code:

```<code>fun login(username: String, password: String, callback: Login.OnLoginListener) {
    RestClient.getInstance().service
    .loginUser( //<- This line is crashing for no apparent reason
            Utils.RequestBodyParser.parseString(username),
            Utils.RequestBodyParser.parseString(password)
    )
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(
        { success ->
            (
            if (success.status)
                callback.onLoginSuccess()
            else
                callback.onLoginError()
            )
        },
        { error ->
            GenericErrorHandler.handleError(error, callback.retrieveContext())
        }
    )
}
</code>```

Here is the logcat output:

```<code>java.lang.IncompatibleClassChangeError: Class 'java.lang.VirtualMachineError' does not implement interface 'java.lang.CharSequence' in call to 'java.lang.String java.lang.CharSequence.toString()' (declaration of 'java.lang.Throwable' appears in /system/framework/core-libart.jar)
  at fi.hohtolabs.kuuratablet.network.WebController$Companion.login(WebController.kt:19)
  at fi.hohtolabs.kuuratablet.presenter.LoginPresenter.login(LoginPresenter.kt:31)
  at fi.hohtolabs.kuuratablet.dialog.LoginDialog.lambda$onResume$2$LoginDialog(LoginDialog.java:74)
  at fi.hohtolabs.kuuratablet.dialog.LoginDialog$$Lambda$2.onClick(Unknown Source)
  at android.view.View.performClick(View.java:5198)
  at android.view.View$PerformClick.run(View.java:21147)
  at android.os.Handler.handleCallback(Handler.java:739)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:148)
  at android.app.ActivityThread.main(ActivityThread.java:5417)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

Does anybody have any suggestions on what I should do? (I tried cleaning, rebuilding, restarting and invalidating caches, deleted the .gradle folder and all other stuff like that, nothing helps)

答:
The problem had occurred only on Marshmellow devices and later was different one. Later i got the ArrayIndexOutOfBoundsException and finally found out what the problem was.

The problem was that my libraries were over 64K methods and because Instant Run was on, there was no multidex error and whole application did not compile well.

Body:
I am having weird problems with my code and I cannot explain anything that's happening. It's crashing on Marshmallow but not on Nougat which makes this more bizarre.

I can point to a line where the error occurs but the error itself is not clear. I am not sure what is crashing and how to prevent it. Here are the details:

The crash happens when I try to make a call to the server. To do this, I use Retrofit alongside RxJava and I do this in Kotlin. Here is my code:

fun login(username: String, password: String, callback: Login.OnLoginListener) {
    RestClient.getInstance().service
    .loginUser( //<- This line is crashing for no apparent reason
            Utils.RequestBodyParser.parseString(username),
            Utils.RequestBodyParser.parseString(password)
    )
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(
        { success ->
            (
            if (success.status)
                callback.onLoginSuccess()
            else
                callback.onLoginError()
            )
        },
        { error ->
            GenericErrorHandler.handleError(error, callback.retrieveContext())
        }
    )
}

Here is the logcat output:

java.lang.IncompatibleClassChangeError: Class 'java.lang.VirtualMachineError' does not implement interface 'java.lang.CharSequence' in call to 'java.lang.String java.lang.CharSequence.toString()' (declaration of 'java.lang.Throwable' appears in /system/framework/core-libart.jar)
  at fi.hohtolabs.kuuratablet.network.WebController$Companion.login(WebController.kt:19)
  at fi.hohtolabs.kuuratablet.presenter.LoginPresenter.login(LoginPresenter.kt:31)
  at fi.hohtolabs.kuuratablet.dialog.LoginDialog.lambda$onResume$2$LoginDialog(LoginDialog.java:74)
  at fi.hohtolabs.kuuratablet.dialog.LoginDialog$$Lambda$2.onClick(Unknown Source)
  at android.view.View.performClick(View.java:5198)
  at android.view.View$PerformClick.run(View.java:21147)
  at android.os.Handler.handleCallback(Handler.java:739)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:148)
  at android.app.ActivityThread.main(ActivityThread.java:5417)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Does anybody have any suggestions on what I should do? (I tried cleaning, rebuilding, restarting and invalidating caches, deleted the .gradle folder and all other stuff like that, nothing helps)


问:
Cannot open output file name.exe permission denied in Eclipse C/C++
I'm creating a C program in Eclipse and I get this error when I go to run my program. This is my first time using Eclipse for a C program I've only used Eclipse for java and never had any problems then so I'm not sure what is causing it. Now I'm using the Eclipse environment specifically for C/C++. So the program builds and debugs just fine but when I go to run it, it says "info: nothing to build" and also shows the permission denied error under "problems." I know this question has been asked and I've tried different solutions they suggested like changing certain windows settings, but nothing is working. Any ideas?    </p>

答:
The same happened to me and I was sure there was no name.exe running.
In my case, make a clean build helped solve the problem.

Project -> Clean and then Project -> Build All should work


问:
AttributeError: 'tuple' object has no attribute 'lower'
I wanted to specify the format of the date because it's in European format(Or else the dates will not be in order after I make it as index column). I did exactly from the tutorial as follow:

But after I execute

```<code>df.date=pd.to_datetime(df.date,format='%d.%m.%Y %H:%M:%S.%f')
</code>```

I get this error

```<code>df = pd.read_csv("F:\Python\Jupyter notes\AUDCAD1h.csv")
df.columns = [['date', 'open','high','low','close','volume']]

df.head()
Out[66]:
                               date     open     high      low    close volume
0  01.01.2015 00:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821    0.0
1  01.01.2015 01:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821    0.0
2  01.01.2015 02:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821    0.0
3  01.01.2015 03:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821    0.0
4  01.01.2015 04:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821    0.0

df.Date=pd.to_datetime(df.date,format='%d.%m.%Y %H:%M:%S.%f')
Traceback (most recent call last):

  File "<ipython-input-67-29b50fd32986>", line 1, in <module>
    df.Date=pd.to_datetime(df.date,format='%d.%m.%Y %H:%M:%S.%f')

  File "C:\Users\AM\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py", line 376, in to_datetime
    result = _assemble_from_unit_mappings(arg, errors=errors)

  File "C:\Users\AM\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py", line 446, in _assemble_from_unit_mappings
    unit = {k: f(k) for k in arg.keys()}

  File "C:\Users\AM\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py", line 446, in <dictcomp>
    unit = {k: f(k) for k in arg.keys()}

  File "C:\Users\AM\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py", line 441, in f
    if value.lower() in _unit_map:

AttributeError: 'tuple' object has no attribute 'lower'
</code>```

How come I got the error but the one I followed didn't? I copied the code exactly. What's wrong with it? Thanks.

答:
You have double brackets in the columns name.

Also why not let pandas work for you? Example,

EDIT: since you don't want the GMT part to be taken into account, I removed it with a list comprehension

```<code>import pandas as pd

df = pd.read_csv("date_t.csv")

print(df)
df.columns = ['date', 'open','high','low','close','volume']

df['date'] = pd.to_datetime([x[:-9] for x in df['date'].squeeze().tolist()], dayfirst=True)

df.set_index('date', inplace=True)

print(df)
</code>```

EDIT 2: explanation of the line
[x[:-9] for x in df['date'].squeeze().tolist()]

df['date'].squeeze() -> squeeze dataframe column in a series

df['date'].squeeze().tolist() -> turn in into a list

[x[:-9] for x in df['date'].squeeze().tolist()] -> for each date in the list keep only the elements until the 9th counting from the end, meaning remove the GMT part

From your subset data, this is what I get. Pandas is smart enough to understand the GMT-0500 and convert the dates taking this into account.

```<code>                              1        2        3        4        5      6
0  01.01.2015 00:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821  0
1  01.01.2015 01:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821  0
2  01.01.2015 02:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821  0
3  01.01.2015 03:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821  0
4  01.01.2015 04:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821  0
                        open     high      low    close  volume
date
2015-01-01 00:00:00  0.94821  0.94821  0.94821  0.94821     0.0
2015-01-01 01:00:00  0.94821  0.94821  0.94821  0.94821     0.0
2015-01-01 02:00:00  0.94821  0.94821  0.94821  0.94821     0.0
2015-01-01 03:00:00  0.94821  0.94821  0.94821  0.94821     0.0
2015-01-01 04:00:00  0.94821  0.94821  0.94821  0.94821     0.0
</code>```

Body:
I wanted to specify the format of the date because it's in European format(Or else the dates will not be in order after I make it as index column). I did exactly from the tutorial as follow:

But after I execute

df.date=pd.to_datetime(df.date,format='%d.%m.%Y %H:%M:%S.%f')

I get this error

df = pd.read_csv("F:\Python\Jupyter notes\AUDCAD1h.csv")
df.columns = [['date', 'open','high','low','close','volume']]

df.head()
Out[66]:
                               date     open     high      low    close volume
0  01.01.2015 00:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821    0.0
1  01.01.2015 01:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821    0.0
2  01.01.2015 02:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821    0.0
3  01.01.2015 03:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821    0.0
4  01.01.2015 04:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821    0.0

df.Date=pd.to_datetime(df.date,format='%d.%m.%Y %H:%M:%S.%f')
Traceback (most recent call last):

  File "<ipython-input-67-29b50fd32986>", line 1, in <module>
    df.Date=pd.to_datetime(df.date,format='%d.%m.%Y %H:%M:%S.%f')

  File "C:\Users\AM\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py", line 376, in to_datetime
    result = _assemble_from_unit_mappings(arg, errors=errors)

  File "C:\Users\AM\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py", line 446, in _assemble_from_unit_mappings
    unit = {k: f(k) for k in arg.keys()}

  File "C:\Users\AM\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py", line 446, in <dictcomp>
    unit = {k: f(k) for k in arg.keys()}

  File "C:\Users\AM\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py", line 441, in f
    if value.lower() in _unit_map:

AttributeError: 'tuple' object has no attribute 'lower'

How come I got the error but the one I followed didn't? I copied the code exactly. What's wrong with it? Thanks.

Body:
You have double brackets in the columns name.

Also why not let pandas work for you? Example,

EDIT: since you don't want the GMT part to be taken into account, I removed it with a list comprehension

import pandas as pd

df = pd.read_csv("date_t.csv")

print(df)
df.columns = ['date', 'open','high','low','close','volume']

df['date'] = pd.to_datetime([x[:-9] for x in df['date'].squeeze().tolist()], dayfirst=True)

df.set_index('date', inplace=True)

print(df)

EDIT 2: explanation of the line
[x[:-9] for x in df['date'].squeeze().tolist()]

df['date'].squeeze() -> squeeze dataframe column in a series

df['date'].squeeze().tolist() -> turn in into a list

[x[:-9] for x in df['date'].squeeze().tolist()] -> for each date in the list keep only the elements until the 9th counting from the end, meaning remove the GMT part

From your subset data, this is what I get. Pandas is smart enough to understand the GMT-0500 and convert the dates taking this into account.

                              1        2        3        4        5      6
0  01.01.2015 00:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821  0
1  01.01.2015 01:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821  0
2  01.01.2015 02:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821  0
3  01.01.2015 03:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821  0
4  01.01.2015 04:00:00.000 GMT-0500  0.94821  0.94821  0.94821  0.94821  0
                        open     high      low    close  volume
date
2015-01-01 00:00:00  0.94821  0.94821  0.94821  0.94821     0.0
2015-01-01 01:00:00  0.94821  0.94821  0.94821  0.94821     0.0
2015-01-01 02:00:00  0.94821  0.94821  0.94821  0.94821     0.0
2015-01-01 03:00:00  0.94821  0.94821  0.94821  0.94821     0.0
2015-01-01 04:00:00  0.94821  0.94821  0.94821  0.94821     0.0


问:
Java Streams Files.lines() throws IOException. Why?
Files.lines() returns a Stream<String> which, as I understand it, is not evaluated unless I apply a terminal operation on it. Why, then, does it declare an IOException. What could go wrong during the initialization of the Stream that would justify the exception declaration?

My use case is the method below. I want to create a stream that streams all text lines with a search pattern from all files in a directory.

Now, if Files.lines() encounters a file formatted in an unexpected encoding during the stream evaluation, it will fail with a runtime exception. This exception will not be caught by the catch block. Why, then, do I need the exception handling at all?

```<code>public static Stream<String> grep(Path dir, Pattern pattern) throws IOException {
    return Files.walk(dir)
            .filter(p -> !Files.isDirectory(p) && p.getFileName().toString().endsWith(".log"))
            .map(p -> {
                try {
                    return Files.lines(p);
                } catch(Exception e) {
                    return Stream.<String>empty();
                }
            }).flatMap(s -> s)
            .filter(l -> pattern.matcher(l).find());
}
</code>```

答:
while the stream that is returned is not evaluated until a terminal operation is applied the creation of the stream itself within Files.lines is creating a new Files.newBufferedReader which could throw the given exception.

We can see this on line 3744 - source.

```<code>public static Stream<String> lines(Path path, Charset cs) throws IOException {
    BufferedReader br = Files.newBufferedReader(path, cs); // this could throw IOException
    try {
        return br.lines().onClose(asUncheckedRunnable(br));
    } catch (Error|RuntimeException e) {
        try {
            br.close();
        } catch (IOException ex) {
            try {
                e.addSuppressed(ex);
            } catch (Throwable ignore) {}
        }
        throw e;
    }
}
</code>```

Body:
Files.lines() returns a Stream<String> which, as I understand it, is not evaluated unless I apply a terminal operation on it. Why, then, does it declare an IOException. What could go wrong during the initialization of the Stream that would justify the exception declaration?

My use case is the method below. I want to create a stream that streams all text lines with a search pattern from all files in a directory.

Now, if Files.lines() encounters a file formatted in an unexpected encoding during the stream evaluation, it will fail with a runtime exception. This exception will not be caught by the catch block. Why, then, do I need the exception handling at all?

public static Stream<String> grep(Path dir, Pattern pattern) throws IOException {
    return Files.walk(dir)
            .filter(p -> !Files.isDirectory(p) && p.getFileName().toString().endsWith(".log"))
            .map(p -> {
                try {
                    return Files.lines(p);
                } catch(Exception e) {
                    return Stream.<String>empty();
                }
            }).flatMap(s -> s)
            .filter(l -> pattern.matcher(l).find());
}

Body:
while the stream that is returned is not evaluated until a terminal operation is applied the creation of the stream itself within Files.lines is creating a new Files.newBufferedReader which could throw the given exception.

We can see this on line 3744 - source.

public static Stream<String> lines(Path path, Charset cs) throws IOException {
    BufferedReader br = Files.newBufferedReader(path, cs); // this could throw IOException
    try {
        return br.lines().onClose(asUncheckedRunnable(br));
    } catch (Error|RuntimeException e) {
        try {
            br.close();
        } catch (IOException ex) {
            try {
                e.addSuppressed(ex);
            } catch (Throwable ignore) {}
        }
        throw e;
    }
}