问:
Spring Boot - Security - How to add pre authentication rules in authentication workflow
I am running a Spring Boot REST API secured with OAuth2.

Here's my actual working 100% configuration for require for an access token & refresh token:

```<code>@Configuration
public class ServerSecurityConfig extends GlobalAuthenticationConfigurerAdapter {

    @Autowired
    CustomPasswordEncoder passwordEncoder;

    @Autowired
    CustomUserDetailsService userDetailsService;

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder);
    }
}
</code>```

I need now to add a pre authentication configuration, so login it's only available if some configuration it's available.

I'm confused if I need to override the AuthenticationManager or the AuthenticationProvider

I tried to add a CustomAuthenticationProvider like this in the same class above:

```<code>@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
    // @formatter:off
    auth
        .authenticationProvider(authProvider)
        .userDetailsService(userDetailsService)
        .passwordEncoder(passwordEncoder);
    // @formatter:on
}
</code>```

And then:

```<code>@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (allowLogin()) {
            // Should call the UserDetailService as normally workflow.
            return null;
        }
        throw new AuthenticationServiceException("Out of service");
    }

    private boolean allowLogin() {
        //Custom logic
        return false;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
</code>```

But then when I throw the exception, my UserDetailService is triggered anyway. So this is not an option or maybe I am implementing in a wrong way.

What about implementing a CustomAuthenticationManager? I don't know where to call it.

I am trying to avoid throwing an exception in the loadByUsername method of the UserDetailService because if anybody has already got a token then he will be still available of consuming my API. Maybe I have to create the logic in both processes?

UPDATED

What I think that I need to do is to add a CustomAccessDecisionVoter, but don't know where to configure for the resource server.

答:
Have you considered writing a Custom userDetailsService decorating the current UserDetailsService and overriding the loadUserByUsername method and return UserDetails with an 'ANONYMOUS' Role and do not permit users with that role to your app

```<code>public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserDetails user = userRolesManager.loadUserByUsername(username);
    if(allowLogin()){
        return user;
    }else{
        return new User(username, "notUsed", true, true,true,true, AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
    }
}
</code>```

Body:
I am running a Spring Boot REST API secured with OAuth2.

Here's my actual working 100% configuration for require for an access token & refresh token:

@Configuration
public class ServerSecurityConfig extends GlobalAuthenticationConfigurerAdapter {

    @Autowired
    CustomPasswordEncoder passwordEncoder;

    @Autowired
    CustomUserDetailsService userDetailsService;

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder);
    }
}

I need now to add a pre authentication configuration, so login it's only available if some configuration it's available.

I'm confused if I need to override the AuthenticationManager or the AuthenticationProvider

I tried to add a CustomAuthenticationProvider like this in the same class above:

@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
    // @formatter:off
    auth
        .authenticationProvider(authProvider)
        .userDetailsService(userDetailsService)
        .passwordEncoder(passwordEncoder);
    // @formatter:on
}

And then:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (allowLogin()) {
            // Should call the UserDetailService as normally workflow.
            return null;
        }
        throw new AuthenticationServiceException("Out of service");
    }

    private boolean allowLogin() {
        //Custom logic
        return false;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

But then when I throw the exception, my UserDetailService is triggered anyway. So this is not an option or maybe I am implementing in a wrong way.

What about implementing a CustomAuthenticationManager? I don't know where to call it.

I am trying to avoid throwing an exception in the loadByUsername method of the UserDetailService because if anybody has already got a token then he will be still available of consuming my API. Maybe I have to create the logic in both processes?

UPDATED

What I think that I need to do is to add a CustomAccessDecisionVoter, but don't know where to configure for the resource server.

Body:
Have you considered writing a Custom userDetailsService decorating the current UserDetailsService and overriding the loadUserByUsername method and return UserDetails with an 'ANONYMOUS' Role and do not permit users with that role to your app

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserDetails user = userRolesManager.loadUserByUsername(username);
    if(allowLogin()){
        return user;
    }else{
        return new User(username, "notUsed", true, true,true,true, AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
    }
}


来源: stackexchange

问:
Unselect an Android View when selecting another one
I have 4 ImageView's inside a LinearLayout. There is also a selector.xml file that sets background color red when android:state_selected="true"

What I want is to have only one view selected. I don't know how I can keep a reference to the last selected view so I can unselected it.

The code I have so far is :

```<code>        ImageView beer = (ImageView)findViewById(R.id.beer_button);
    ImageView coffee = (ImageView)findViewById(R.id.coffee_button);
    ImageView food = (ImageView)findViewById(R.id.food_button);
    ImageView wifi = (ImageView)findViewById(R.id.wifi_button);

    beer.setOnClickListener(new OnClickListener()   {
           public void onClick(View v)     {
               Log.v("flag", "1");
               v.setSelected(true);
           }
    });

    coffee.setOnClickListener(new OnClickListener() {
           public void onClick(View v)     {
               Log.v("flag", "2");
               v.setSelected(true);
           }
    });

    food.setOnClickListener(new OnClickListener()   {
           public void onClick(View v)     {
               Log.v("flag", "3");
               v.setSelected(true);
           }
    });

    wifi.setOnClickListener(new OnClickListener()   {
           public void onClick(View v)     {
               Log.v("flag", "4");
               v.setSelected(true);
           }
    });
</code>```

答:
```<code>water.setOnClickListener(new OnClickListener()   {
       public void onClick(View v)     {
           Log.v("flag", "0");
           ((LinearLayout)v.getParent()).dispatchSetSelected(false);
           v.setSelected(true);
       }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have 4 ImageView's inside a LinearLayout. There is also a selector.xml file that sets background color red when android:state_selected="true"

What I want is to have only one view selected. I don't know how I can keep a reference to the last selected view so I can unselected it.

The code I have so far is :

        ImageView beer = (ImageView)findViewById(R.id.beer_button);
    ImageView coffee = (ImageView)findViewById(R.id.coffee_button);
    ImageView food = (ImageView)findViewById(R.id.food_button);
    ImageView wifi = (ImageView)findViewById(R.id.wifi_button);

    beer.setOnClickListener(new OnClickListener()   {
           public void onClick(View v)     {
               Log.v("flag", "1");
               v.setSelected(true);
           }
    });

    coffee.setOnClickListener(new OnClickListener() {
           public void onClick(View v)     {
               Log.v("flag", "2");
               v.setSelected(true);
           }
    });

    food.setOnClickListener(new OnClickListener()   {
           public void onClick(View v)     {
               Log.v("flag", "3");
               v.setSelected(true);
           }
    });

    wifi.setOnClickListener(new OnClickListener()   {
           public void onClick(View v)     {
               Log.v("flag", "4");
               v.setSelected(true);
           }
    });


问:
How do I call the default deserializer from a custom deserializer in Jackson
I have a problem in my custom deserializer in Jackson. I want to access the default serializer to populate the object I am deserializing into. After the population I will do some custom things but first I want to deserialize the object with the default Jackson behavior.

This is the code that I have at the moment.

```<code>public class UserEventDeserializer extends StdDeserializer<User> {

  private static final long serialVersionUID = 7923585097068641765L;

  public UserEventDeserializer() {
    super(User.class);
  }

  @Override
  @Transactional
  public User deserialize(JsonParser jp, DeserializationContext ctxt)
      throws IOException, JsonProcessingException {

    ObjectCodec oc = jp.getCodec();
    JsonNode node = oc.readTree(jp);
    User deserializedUser = null;
    deserializedUser = super.deserialize(jp, ctxt, new User());
    // The previous line generates an exception java.lang.UnsupportedOperationException
    // Because there is no implementation of the deserializer.
    // I want a way to access the default spring deserializer for my User class.
    // How can I do that?

    //Special logic

    return deserializedUser;
  }

}
</code>```

What I need is a way to initialize the default deserializer so that I can pre-populate my POJO before I start my special logic.

When calling deserialize from within the custom deserializer It seems the method is called from the current context no matter how I construct the serializer class. Because of the annotation in my POJO. This causes a Stack Overflow exception for obvious reasons.

I have tried initializing a BeanDeserializer but the process is extremely complex and I haven't managed to find the right way to do it. I have also tried overloading the AnnotationIntrospector to no avail, thinking that it might help me ignore the annotation in the DeserializerContext. Finally it seams I might have had some success using JsonDeserializerBuilders although this required me to do some magic stuff to get hold of the application context from Spring. I would appreciate any thing that could lead me to a cleaner solution for example how Can I construct a deserialization context without reading the JsonDeserializer annotation.

答:
Along the lines of what Tomáš Záluský has suggested, in cases where using BeanDeserializerModifier is undesirable you can construct a default deserializer yourself using BeanDeserializerFactory, although there is some extra setup necessary. In context, this solution would look like so:

```<code>public User deserialize(JsonParser jp, DeserializationContext ctxt)
  throws IOException, JsonProcessingException {

    ObjectCodec oc = jp.getCodec();
    JsonNode node = oc.readTree(jp);
    User deserializedUser = null;

    DeserializationConfig config = ctxt.getConfig();
    JavaType type = TypeFactory.defaultInstance().constructType(User.class);
    JsonDeserializer<Object> defaultDeserializer = BeanDeserializerFactory.instance.buildBeanDeserializer(ctxt, type, config.introspect(type));

    if (defaultDeserializer instanceof ResolvableDeserializer) {
        ((ResolvableDeserializer) defaultDeserializer).resolve(ctxt);
    }

    JsonParser treeParser = oc.treeAsTokens(node);
    config.initialize(treeParser);

    if (treeParser.getCurrentToken() == null) {
        treeParser.nextToken();
    }

    deserializedUser = (User) defaultDeserializer.deserialize(treeParser, context);

    return deserializedUser;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem in my custom deserializer in Jackson. I want to access the default serializer to populate the object I am deserializing into. After the population I will do some custom things but first I want to deserialize the object with the default Jackson behavior.

This is the code that I have at the moment.

public class UserEventDeserializer extends StdDeserializer<User> {

  private static final long serialVersionUID = 7923585097068641765L;

  public UserEventDeserializer() {
    super(User.class);
  }

  @Override
  @Transactional
  public User deserialize(JsonParser jp, DeserializationContext ctxt)
      throws IOException, JsonProcessingException {

    ObjectCodec oc = jp.getCodec();
    JsonNode node = oc.readTree(jp);
    User deserializedUser = null;
    deserializedUser = super.deserialize(jp, ctxt, new User());
    // The previous line generates an exception java.lang.UnsupportedOperationException
    // Because there is no implementation of the deserializer.
    // I want a way to access the default spring deserializer for my User class.
    // How can I do that?

    //Special logic

    return deserializedUser;
  }

}

What I need is a way to initialize the default deserializer so that I can pre-populate my POJO before I start my special logic.

When calling deserialize from within the custom deserializer It seems the method is called from the current context no matter how I construct the serializer class. Because of the annotation in my POJO. This causes a Stack Overflow exception for obvious reasons.

I have tried initializing a BeanDeserializer but the process is extremely complex and I haven't managed to find the right way to do it. I have also tried overloading the AnnotationIntrospector to no avail, thinking that it might help me ignore the annotation in the DeserializerContext. Finally it seams I might have had some success using JsonDeserializerBuilders although this required me to do some magic stuff to get hold of the application context from Spring. I would appreciate any thing that could lead me to a cleaner solution for example how Can I construct a deserialization context without reading the JsonDeserializer annotation.

Body:
Along the lines of what Tomáš Záluský has suggested, in cases where using BeanDeserializerModifier is undesirable you can construct a default deserializer yourself using BeanDeserializerFactory, although there is some extra setup necessary. In context, this solution would look like so:

public User deserialize(JsonParser jp, DeserializationContext ctxt)
  throws IOException, JsonProcessingException {

    ObjectCodec oc = jp.getCodec();
    JsonNode node = oc.readTree(jp);
    User deserializedUser = null;

    DeserializationConfig config = ctxt.getConfig();
    JavaType type = TypeFactory.defaultInstance().constructType(User.class);
    JsonDeserializer<Object> defaultDeserializer = BeanDeserializerFactory.instance.buildBeanDeserializer(ctxt, type, config.introspect(type));

    if (defaultDeserializer instanceof ResolvableDeserializer) {
        ((ResolvableDeserializer) defaultDeserializer).resolve(ctxt);
    }

    JsonParser treeParser = oc.treeAsTokens(node);
    config.initialize(treeParser);

    if (treeParser.getCurrentToken() == null) {
        treeParser.nextToken();
    }

    deserializedUser = (User) defaultDeserializer.deserialize(treeParser, context);

    return deserializedUser;
}


答:
-- Updates boolean for recent ID

UPDATE TableA SET boolean = 1 WHERE date = SELECT date FROM(SELECT ROW_NUMBER() OVER(PARTITION BY id ORDER BY date DESC) AS RowNum,date FROM TableA) AS TableB
WHERE RowNum = 1

Title: Update 1 record according to 2 sorts criteria

Body:
Do you know how can I update 1 record according to 2 sorts criteria?

I have in my table A :

id    |     date    | boolean  | data
-------------------------------------------
001    | 11.13.2017  |    0     | value 1
001    | 09.13.2017  |    1     | value 2
001    | 01.01.2017  |    0     | value 0
002    | 06.15.2017  |    1     | value 3
003    | 04.23.2017  |    1     | value 4
003    | 12.13.2017  |    0     | value 5

I would like by id, change the boolean value according with the most recent date.

for example:

id     |     date    | boolean  | data
-------------------------------------------
001    | 11.13.2017  |    1     | value 1
001    | 09.13.2017  |    0     | value 2
001    | 01.01.2017  |    0     | value 0

Thank you


问:
Bean injection inside a JPA @Entity
Is it possible to inject beans to a JPA @Entity using Spring's dependency injection?

I attempted to @Autowire ServletContext but, while the server did start successfully, I received a NullPointerException when trying to access the bean property.

```<code>@Autowired
@Transient
ServletContext servletContext;
</code>```

答:
After a long time I stumbled across this SO answer that made me think of an elegant solution:

Add to your entities all the @Transient @Autowired fields you need

Make a @Repository DAO with this autowired field:

@Autowired private AutowireCapableBeanFactory autowirer;

From your DAO, after fetching the entity from DB, call this autowiring code:

String beanName = fetchedEntity.getClass().getSimpleName();
autowirer.autowireBean(fetchedEntity);
fetchedEntity = (FetchedEntity) autowirer.initializeBean(fetchedEntity, beanName);

Your entity will then be able to access the autowired fields as any @Component can.

Title: Bean injection inside a JPA @Entity

Body:
Is it possible to inject beans to a JPA @Entity using Spring's dependency injection?

I attempted to @Autowire ServletContext but, while the server did start successfully, I received a NullPointerException when trying to access the bean property.

@Autowired
@Transient
ServletContext servletContext;


问:
VueJs directive two way binding
I created a custom directive to handle select2 in VueJs. The code below works when I am binding a select to a data property in my viewmodel that is not a propert of an object within data.

Like this.userId but if it is bound to something like this.user.id, it would not update the value in my viewmodel data object.

```<code>Vue.directive('selected', {
    bind: function (el, binding, vnode) {
        var key = binding.expression;
        var select = $(el);

        select.select2();
        vnode.context.$data[binding.expression] = select.val();

        select.on('change', function () {
            vnode.context.$data[binding.expression] = select.val();
        });
    },
    update: function (el, binding, newVnode, oldVnode) {
        var select = $(el);
        select.val(binding.value).trigger('change');
    }
});

<select v-selected="userEditor.Id">
   <option v-for="user in users" v-bind:value="user.id" >
       {{ user.fullName}}
   </option>
</select>
</code>```

Related fiddle:
https://jsfiddle.net/raime910/rHm4e/4/

答:
When you using 1st level $data's-property, it accessing to $data object directly through []-brackets

But you want to pass to selected-directive the path to nested object, so you should do something like this:

```<code>// source: https://stackoverflow.com/a/6842900/8311719
function deepSet(obj, value, path) {
    var i;
    path = path.split('.');
    for (i = 0; i < path.length - 1; i++)
        obj = obj[path[i]];

    obj[path[i]] = value;
}

Vue.directive('selected', {
bind: function (el, binding, vnode) {
    var select = $(el);

    select.select2();
    deepSet(vnode.context.$data, select.val(), binding.expression);

    select.on('change', function () {
        deepSet(vnode.context.$data, select.val(), binding.expression);
    });
},
update: function (el, binding, newVnode, oldVnode) {
    var select = $(el);
    select.val(binding.value).trigger('change');
}
});

<select v-selected="userEditor.Id">
<option v-for="user in users" v-bind:value="user.id" >
   {{ user.fullName}}
</option>
</select>
</code>```

Description:

Suppose we have two $data's props: valOrObjectWithoutNesting and objLvl1:

```<code>data: function(){
  return{
    valOrObjectWithoutNesting: 'let it be some string',
    objLvl1:{
      objLvl2:{
        objLvl3:{
          objField: 'primitive string'
        }
      }
    }
  }
}
</code>```

Variant with 1st level $data's-property:

```<code><select v-selected="valOrObjectWithoutNesting">

// Now this code:
vnode.context.$data[binding.expression] = select.val();
// Equals to:
vnode.context.$data['valOrObjectWithoutNesting'] = select.val();
</code>```

Variant with 4th level $data's-property:

```<code><select v-selected="objLvl1.objLvl2.objLvl3.objField">

// Now this code:
vnode.context.$data[binding.expression] = select.val();
// Equals to:
vnode.context.$data['objLvl1.objLvl2.objLvl3.objField'] = select.val(); // error here
</code>```

So the deepSet function in my code above "converting" $data['objLvl1.objLvl2.objLvl3.objField'] to $data['objLvl1']['objLvl2']['objLvl3']['objField'].

As you see, as I mentioned in comments to your question, when you want make select2-wrapper more customisable, the directive-way much more complicated, than separate component-way. In component, you would pass as much configuration props and event subscriptions as you want, you would avoid doing side mutations like vnode.context.$data[binding.expression] and your code would become more understandable and simpler for further support.

Title: VueJs directive two way binding

Body:
I created a custom directive to handle select2 in VueJs. The code below works when I am binding a select to a data property in my viewmodel that is not a propert of an object within data.

Like this.userId but if it is bound to something like this.user.id, it would not update the value in my viewmodel data object.

Vue.directive('selected', {
    bind: function (el, binding, vnode) {
        var key = binding.expression;
        var select = $(el);

        select.select2();
        vnode.context.$data[binding.expression] = select.val();

        select.on('change', function () {
            vnode.context.$data[binding.expression] = select.val();
        });
    },
    update: function (el, binding, newVnode, oldVnode) {
        var select = $(el);
        select.val(binding.value).trigger('change');
    }
});

<select v-selected="userEditor.Id">
   <option v-for="user in users" v-bind:value="user.id" >
       {{ user.fullName}}
   </option>
</select>

Related fiddle:
https://jsfiddle.net/raime910/rHm4e/4/

Body:
When you using 1st level $data's-property, it accessing to $data object directly through []-brackets

But you want to pass to selected-directive the path to nested object, so you should do something like this:

// source: https://stackoverflow.com/a/6842900/8311719
function deepSet(obj, value, path) {
    var i;
    path = path.split('.');
    for (i = 0; i < path.length - 1; i++)
        obj = obj[path[i]];

    obj[path[i]] = value;
}

Vue.directive('selected', {
bind: function (el, binding, vnode) {
    var select = $(el);

    select.select2();
    deepSet(vnode.context.$data, select.val(), binding.expression);

    select.on('change', function () {
        deepSet(vnode.context.$data, select.val(), binding.expression);
    });
},
update: function (el, binding, newVnode, oldVnode) {
    var select = $(el);
    select.val(binding.value).trigger('change');
}
});

<select v-selected="userEditor.Id">
<option v-for="user in users" v-bind:value="user.id" >
   {{ user.fullName}}
</option>
</select>

Description:

Suppose we have two $data's props: valOrObjectWithoutNesting and objLvl1:

data: function(){
  return{
    valOrObjectWithoutNesting: 'let it be some string',
    objLvl1:{
      objLvl2:{
        objLvl3:{
          objField: 'primitive string'
        }
      }
    }
  }
}

Variant with 1st level $data's-property:

<select v-selected="valOrObjectWithoutNesting">

// Now this code:
vnode.context.$data[binding.expression] = select.val();
// Equals to:
vnode.context.$data['valOrObjectWithoutNesting'] = select.val();

Variant with 4th level $data's-property:

<select v-selected="objLvl1.objLvl2.objLvl3.objField">

// Now this code:
vnode.context.$data[binding.expression] = select.val();
// Equals to:
vnode.context.$data['objLvl1.objLvl2.objLvl3.objField'] = select.val(); // error here

So the deepSet function in my code above "converting" $data['objLvl1.objLvl2.objLvl3.objField'] to $data['objLvl1']['objLvl2']['objLvl3']['objField'].

As you see, as I mentioned in comments to your question, when you want make select2-wrapper more customisable, the directive-way much more complicated, than separate component-way. In component, you would pass as much configuration props and event subscriptions as you want, you would avoid doing side mutations like vnode.context.$data[binding.expression] and your code would become more understandable and simpler for further support.


问:
Which programming language Google app engine is most likely to work with next and why?
Their roadmap says their next release will be in March 2009, and that they'll be adding a new 'runtime language'. I'm hoping its either Java or PHP but realy not sure, and would like to know which language is the most probable so i can plan accordingly for a project I plan on hosting with google app engine.

Any ideas?

答: JRuby on Rails. </p>

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Click Upvote

Body: JRuby on Rails.

OwnerDisplayName: PEZ


问:
VBA: How create a loop altering dates
I have a sheet of data where each row has been copied and pasted three time.  Each row has a date in column S.  Within these sets of three, the first row will remain the original date, the second row will be one month later than the original date, and the third row will be two months after the original date.

How do I turn this into a loop that repeats the process for the entire sheet?  My problem lies with the DateAdd function.  I''m getting a compile error on that function (never used it before).  Thanks in advance!  Here is the code that I have thus far:

```<code>Sub DateChange()

Dim r As Long

Application.ScreenUpdating = False

For r = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
With Cells(r, 1).EntireRow
    .Copy
    .Resize(2).Offset(1, 0).Insert Shift:=xlDown
End With
Cells(r + 1, "S").Value = DateAdd("m", 1, Cells(r, "S"))
Cells(r + 2, "S").Value = DateAdd("m", 2, Cells(r, "S"))
Next r

Application.ScreenUpdating = True
End Sub
</code>```

答:
Here is an alternative to DateAdd which is erroring for reasons currently unknown.</p>

```<code>Sub Macro()

Dim r As Long, d As String

Application.ScreenUpdating = False

For r = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
    With Cells(r, 1).EntireRow
        .Copy
        .Resize(2).Offset(1, 0).Insert Shift:=xlDown
    End With
    d = Cells(r, "S").Address
    Cells(r + 1, "S").Value = Evaluate("date(year(" & d & "),month(" & d & ")+1,day(" & d & "))")
    Cells(r + 2, "S").Value = Evaluate("date(year(" & d & "),month(" & d & ")+2,day(" & d & "))")
Next r

Application.ScreenUpdating = True

End Sub
</code>```

Title: VBA: How create a loop altering dates

Body:
I have a sheet of data where each row has been copied and pasted three time.  Each row has a date in column S.  Within these sets of three, the first row will remain the original date, the second row will be one month later than the original date, and the third row will be two months after the original date.

How do I turn this into a loop that repeats the process for the entire sheet?  My problem lies with the DateAdd function.  I''m getting a compile error on that function (never used it before).  Thanks in advance!  Here is the code that I have thus far:

Sub DateChange()

Dim r As Long

Application.ScreenUpdating = False

For r = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
With Cells(r, 1).EntireRow
    .Copy
    .Resize(2).Offset(1, 0).Insert Shift:=xlDown
End With
Cells(r + 1, "S").Value = DateAdd("m", 1, Cells(r, "S"))
Cells(r + 2, "S").Value = DateAdd("m", 2, Cells(r, "S"))
Next r

Application.ScreenUpdating = True
End Sub

Body:
Here is an alternative to DateAdd which is erroring for reasons currently unknown.

Sub Macro()

Dim r As Long, d As String

Application.ScreenUpdating = False

For r = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
    With Cells(r, 1).EntireRow
        .Copy
        .Resize(2).Offset(1, 0).Insert Shift:=xlDown
    End With
    d = Cells(r, "S").Address
    Cells(r + 1, "S").Value = Evaluate("date(year(" & d & "),month(" & d & ")+1,day(" & d & "))")
    Cells(r + 2, "S").Value = Evaluate("date(year(" & d & "),month(" & d & ")+2,day(" & d & "))")
Next r

Application.ScreenUpdating = True

End Sub


问:
Multiples validation into ng-disabled dont work
I am trying to validate all fields of a form with angularjs 1.5, validation requires, full fields, and enable buttons in case these fields are full, I have already checked several operators but this does not work well, ng-disabled = "! ( var1 && var2 && var3 && var4) ". I need your help please leave reference code.

Thank you very much

AngularJS: 1.5.11

Code Example

答:
If you are using a form, you won't need to check for individual fields, just check for form validity:</p>

```<code><form role="form" name="testForm" novalidate>
    <input type="text" name="field1" ng-model="obj.field1" required>

    <input type="text" name="field2" ng-model="obj.field2" required>

    <button type="submit" ng-disabled="testForm.$invalid">Send</button>
</form>
</code>```

Body:
If you are using a form, you won't need to check for individual fields, just check for form validity:

<form role="form" name="testForm" novalidate>
    <input type="text" name="field1" ng-model="obj.field1" required>

    <input type="text" name="field2" ng-model="obj.field2" required>

    <button type="submit" ng-disabled="testForm.$invalid">Send</button>
</form>


问:
Xamarin forms Picker Binding error
I have a picker control:

```<code><Picker Title="Number of People"
            ItemsSource="{Binding SomeList, Source={x:Static local:MyModelHandler.MyModel}}"
            SelectedItem="{Binding SomeListSelectedIndex, Source={x:Static local:MyModelHandler.MyModel}}">
    </Picker>
</code>```

when trying to build i get "No property, bindable property, or event found for 'ItemsSource'" error.

Above that i have a label:

```<code><Label Text ="{Binding SomeLabel, Source={x:Static local:MyModelHandler.MyModel}, Mode=OneWay}"></Label>
</code>```

And that binding works perfectly

MyModelHandler is an static class that allowes only one Model

```<code>public static class MyModelHandler
{
    private static MyModel myModel = new MyModel();

    public static MyModel MyModel
    {
        get
        {
            return myModel;
        }
    }
}
</code>```

And Model is simple:

```<code>public class MyModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private int selectedNumber = 1;
    private string someLabel = "";

    public IList<int> SomeList
    {
        get
        {
            return Enumerable.Range(1, 10).ToList();
        }
    }

    public int SomeListSelectedIndex
    {
        get
        {
            return SomeList.IndexOf(this.selectedNumberOfPeople);
        }
        set
        {
            this.selectedNumber = SomeList[value];
        }
    }

        public double SomeLabel
        {
            get
            {
                return this.someLabel;
            }
            set
            {
                this.someLabel= value;
            }
        }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
     }
...
}
</code>```

Edit: Using Xamarin 4.3

答:
You might check your Xamarin.Forms version.

The ItemsSource property was introduced in Xamarin.Forms 2.3.4.184-pre1, see release notes here:

https://developer.xamarin.com/releases/xamarin-forms/xamarin-forms-2.3/2.3.4-stable/#2.3.4.184-pre1.

If you are using an older Xamarin.Forms version you will get the Xamarin.Forms XAML error "No property, bindable property, or event found for 'ItemsSource'".

Title: Xamarin forms Picker Binding error

Body:
I have a picker control:

<Picker Title="Number of People"
            ItemsSource="{Binding SomeList, Source={x:Static local:MyModelHandler.MyModel}}"
            SelectedItem="{Binding SomeListSelectedIndex, Source={x:Static local:MyModelHandler.MyModel}}">
    </Picker>

when trying to build i get "No property, bindable property, or event found for 'ItemsSource'" error.

Above that i have a label:

And that binding works perfectly

MyModelHandler is an static class that allowes only one Model

public static class MyModelHandler
{
    private static MyModel myModel = new MyModel();

    public static MyModel MyModel
    {
        get
        {
            return myModel;
        }
    }
}

And Model is simple:

public class MyModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private int selectedNumber = 1;
    private string someLabel = "";

    public IList<int> SomeList
    {
        get
        {
            return Enumerable.Range(1, 10).ToList();
        }
    }

    public int SomeListSelectedIndex
    {
        get
        {
            return SomeList.IndexOf(this.selectedNumberOfPeople);
        }
        set
        {
            this.selectedNumber = SomeList[value];
        }
    }

        public double SomeLabel
        {
            get
            {
                return this.someLabel;
            }
            set
            {
                this.someLabel= value;
            }
        }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
     }
...
}

Edit: Using Xamarin 4.3


问:
Is there any legitimate use for Intel's RDRAND?
Today I thought: well, even if there is great suspicion on RDRAND implementation of NIST SP 800-90A, it is still a hardware implementation of pseudo-random number generator (PRNG) that must be good enough for non-sensitive applications. So I thought of using it on my game instead of Mersenne Twister.

So, to see if there was any performance gain on using the instruction, I compared the time of the two following codes:

```<code>// test.cpp
#include <cstdio>

int main()
{
    unsigned int rnd = 0;
    for(int i = 0; i < 10000000; ++i) {
        __builtin_ia32_rdrand32_step(&rnd);
    }
    printf("%x\n", rnd);
}
</code>```

and

```<code>//test2.cpp
#include <cstdio>
#include <random>

int main()
{
    unsigned int rnd = 0;
    __builtin_ia32_rdrand32_step(&rnd);
    std::mt19937 gen(rnd);
    for(int i = 0; i < 10000000; ++i) {
        rnd ^= gen();
    }
    printf("%x\n", rnd);
}
</code>```

and by running the two I get:

```<code>$ time ./test
d230449a

real    0m0.361s
user    0m0.358s
sys     0m0.002s

$ time ./test2
bfc4e472

real    0m0.051s
user    0m0.050s
sys     0m0.002s
</code>```

So, Mersenne Twister is much faster than RDRAND on my CPU. Well, I was disappointed, ruled out from my game. But RDRAND is a cryptographically secure PRNG (CSPRNG), so it does much behind the scenes... more fair would be compare it to other CSPRNG. So I took my Rabbit implementation (plain translation of the RFC to C, no fancy tricks for performance), and wrote the following test:

```<code>// test3.cpp
#include <cstdio>

extern "C"
{
#include "rabbit.h"
}

int main()
{
    rabbit_state s;
    unsigned long long buf[2];
    __builtin_ia32_rdrand64_step(&buf[0]);
    __builtin_ia32_rdrand64_step(&buf[1]);
    rabbit_init_key(&s, (uint8_t*)&buf[0]);

    for(int i = 0; i < 10000000; ++i) {
        rabbit_extract(&s, (uint8_t*)&buf[0]);
    }
    printf("%llx\n", buf[0]);
}
</code>```

And for my surprise, generating twice as much pseudo-random data as the first two of them, I got a better time than RDRAND:

```<code>$ time ./test3
8ef9772277b70aba

real    0m0.344s
user    0m0.341s
sys     0m0.002s
</code>```

All three were compiled with optimization enabled.

So, we have a widespread paranoia that RDRAND was made to embed NSA backdoors into everybody's software cryptography. Also we have at least one software CSPRNG faster than RDRAND, and the most widely used decent PRNG, Mersenne Twister, is much faster than RDRAND. Finally, we have open-source auditable software entropy pools, like /dev/random and /dev/urandom, that are not hidden behind twofold scrambler layers of AES, like RDRAND.

So, the question: should people be using RDRAND? Is there any legitimate use for it? Or should we stop using it altogether?

答:
There is an astrophysics research paper here (http://iopscience.iop.org/article/10.3847/1538-4357/aa7ede/meta;jsessionid=A9DA9DDB925E6522D058F3CEEC7D0B21.ip-10-40-2-120), (non-paywalled) version here (https://arxiv.org/abs/1707.02212) that gives a legitimate use for RdRand.

It examines the effects of RdRand on a Monte Carlo simulator, as an earlier post advised.  But the author didn't find any statistical difference in the results that use or do not use RdRand.  From the performance standpoint, it looks like the Mersenne Twister is much faster.  I think Sections 2.2.1 and 5 have all of the details.

Body:
Today I thought: well, even if there is great suspicion on RDRAND implementation of NIST SP 800-90A, it is still a hardware implementation of pseudo-random number generator (PRNG) that must be good enough for non-sensitive applications. So I thought of using it on my game instead of Mersenne Twister.

So, to see if there was any performance gain on using the instruction, I compared the time of the two following codes:

// test.cpp
#include <cstdio>

int main()
{
    unsigned int rnd = 0;
    for(int i = 0; i < 10000000; ++i) {
        __builtin_ia32_rdrand32_step(&rnd);
    }
    printf("%x\n", rnd);
}

and

//test2.cpp
#include <cstdio>
#include <random>

int main()
{
    unsigned int rnd = 0;
    __builtin_ia32_rdrand32_step(&rnd);
    std::mt19937 gen(rnd);
    for(int i = 0; i < 10000000; ++i) {
        rnd ^= gen();
    }
    printf("%x\n", rnd);
}

and by running the two I get:

$ time ./test
d230449a

real    0m0.361s
user    0m0.358s
sys     0m0.002s

$ time ./test2
bfc4e472

real    0m0.051s
user    0m0.050s
sys     0m0.002s

So, Mersenne Twister is much faster than RDRAND on my CPU. Well, I was disappointed, ruled out from my game. But RDRAND is a cryptographically secure PRNG (CSPRNG), so it does much behind the scenes... more fair would be compare it to other CSPRNG. So I took my Rabbit implementation (plain translation of the RFC to C, no fancy tricks for performance), and wrote the following test:

// test3.cpp
#include <cstdio>

extern "C"
{
#include "rabbit.h"
}

int main()
{
    rabbit_state s;
    unsigned long long buf[2];
    __builtin_ia32_rdrand64_step(&buf[0]);
    __builtin_ia32_rdrand64_step(&buf[1]);
    rabbit_init_key(&s, (uint8_t*)&buf[0]);

    for(int i = 0; i < 10000000; ++i) {
        rabbit_extract(&s, (uint8_t*)&buf[0]);
    }
    printf("%llx\n", buf[0]);
}

And for my surprise, generating twice as much pseudo-random data as the first two of them, I got a better time than RDRAND:

$ time ./test3
8ef9772277b70aba

real    0m0.344s
user    0m0.341s
sys     0m0.002s

All three were compiled with optimization enabled.

So, we have a widespread paranoia that RDRAND was made to embed NSA backdoors into everybody's software cryptography. Also we have at least one software CSPRNG faster than RDRAND, and the most widely used decent PRNG, Mersenne Twister, is much faster than RDRAND. Finally, we have open-source auditable software entropy pools, like /dev/random and /dev/urandom, that are not hidden behind twofold scrambler layers of AES, like RDRAND.

So, the question: should people be using RDRAND? Is there any legitimate use for it? Or should we stop using it altogether?


问:
How to specify "any word" in route?
I want to attach the following action to /articles/<any word>/{article}.html :

```<code>public function show(Article $article)
{
   return $this->doShow($article);
}
</code>```

If I use wildcard (in place of <any word>) - for example {catalogue} - Laravel inserts it to action's arguments, which is undesirable. I tried * symbol, ':any', ':any?" - the route just stops working (I get 404). What should I use?

答:
Routes do not always have to be bound to a model. If a route parameter is not bound to a model the string will be sent to the controller. </p>

<p>"Laravel inserts it to action's arguments, which is undesirable" This is the expected behavior, but you do not have to use the variable if you don't need it. But if that's the case you should reconsider your URL scheme.</p>

```<code>Route::get('/articles/{term}/{article}.html', 'ArticleController@show');

public function show($term, Article $article)
{
   // $term will be a string wish whichever value is in the {term} section
   // $article will be the model that matches the key in the {article} section
   return $this->doShow($article);
}
</code>```

Title: How to specify "any word" in route?

Body:
I want to attach the following action to /articles/<any word>/{article}.html :

public function show(Article $article)
{
   return $this->doShow($article);
}

If I use wildcard (in place of <any word>) - for example {catalogue} - Laravel inserts it to action's arguments, which is undesirable. I tried * symbol, ':any', ':any?" - the route just stops working (I get 404). What should I use?

Body:
Routes do not always have to be bound to a model. If a route parameter is not bound to a model the string will be sent to the controller.

"Laravel inserts it to action's arguments, which is undesirable" This is the expected behavior, but you do not have to use the variable if you don't need it. But if that's the case you should reconsider your URL scheme.

Route::get('/articles/{term}/{article}.html', 'ArticleController@show');

public function show($term, Article $article)
{
   // $term will be a string wish whichever value is in the {term} section
   // $article will be the model that matches the key in the {article} section
   return $this->doShow($article);
}


问:
Task timed out after 3.00 seconds - Lambda application with nodeJS
I am trying to put a hard-coded data item to DynamoDB. I am using AWS SDK object to perform this update. And all the debug "Console.log" in the below code is getting printed but eventually it prints Task timed out after 3.00 seconds

With no update to the DynamoDB

```<code>function updatedb(intent, session, callback) {
    let country;
     const repromptText = null;
     const sessionAttributes = {};
     let shouldEndSession = false;

console.log("In the function");
const AWS = require("aws-sdk");
const docClient = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1' });

var params = {
    TableName: "Location",
    Item: {
        "LocationID": { "S": "11" },
        "Country": { "S": "10" },
        "Description": { "S": "10" },
        "Name": { "S": "10" }
    }
};
console.log("Param loaded & executing the DocClient Put");

docClient.put(params, function (err, data) {
    if (err) {
        speechOutput = 'Update failed';
        console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2));
        callback(sessionAttributes,
            buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));
    } else {
        console.log("Created table. Table description JSON:", JSON.stringify(data, null, 2));
        speechOutput = 'Update successful';
        callback(sessionAttributes,
            buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));
    }
});
}
</code>```

The following items are already checked

1) There is a table named "Location" in DynamoDB
2) Both DynamoDB and this lambda function are in ue-west-1 (Ireland)
3) The role assigned for this Lambda function can do all operation on this table. See the policy details below

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "Stmt1510603004000",
        "Effect": "Allow",
        "Action": [
            "dynamodb:*"
        ],
        "Resource": [
            "arn:aws:dynamodb:eu-west-1:752546663632:table/Location"
        ]
    }
]
}
</code>```

How does my Lambda function locate the table "location"  just with the region?- the code does not appear to have end-point, etc.? - just developed based on a tutorial.

Is that what I am missing?

Please can you help?

答:
I believe that AWS locates the table based on your identity, in combination with the region and the table name.

I was able to successfully post to a table using this code:

```<code>const AWS = require('aws-sdk');

const dynamoDB = new AWS.DynamoDB({region: 'us-west-2'});

var params = {
  TableName: "my-table",
  Item: {
    "LocationID": { S: "11" },
    "Country": { S: "10" },
    "Description": { S: "10" },
    "Name": { S: "10" }
  }
};

dynamoDB.putItem(params, (err, data) => {
  if (err){
    console.error(err.stack);
  } else {
    console.log(data);
  }
});
</code>```

If you can in fact post to the table from the CLI, then there is still at least one remaining issue: it appears that you are using the DocumentClient class incorrectly.  It looks like you're mixing up the syntax for DynamoDB.putItem with the syntax for DynamoDB.DocumentClient.put.

If you notice, my code uses the DynamoDB class directly-- based on what you're doing, I see no reason why you couldn't do the same. Otherwise, you should change your Item object:

```<code>var params = {
  TableName: "my-table",
  Item: {
    "LocationID": "11",
    "Country": "10",
    "Description": "10",
    "Name": "10"
  }
};
</code>```

My guess is your code is currently erroring out because you are trying to insert Maps where you want to insert Strings.  If you have Cloudwatch configured you could check the logs.

Finally, I don't see you using callback in your code.  If your intention is to respond to a client calling the lambda you should do that.  Depending on your NodeJS version, the lambda can simply time out without returning a useful response.

Body:
I am trying to put a hard-coded data item to DynamoDB. I am using AWS SDK object to perform this update. And all the debug "Console.log" in the below code is getting printed but eventually it prints Task timed out after 3.00 seconds

With no update to the DynamoDB

function updatedb(intent, session, callback) {
    let country;
     const repromptText = null;
     const sessionAttributes = {};
     let shouldEndSession = false;

console.log("In the function");
const AWS = require("aws-sdk");
const docClient = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1' });

var params = {
    TableName: "Location",
    Item: {
        "LocationID": { "S": "11" },
        "Country": { "S": "10" },
        "Description": { "S": "10" },
        "Name": { "S": "10" }
    }
};
console.log("Param loaded & executing the DocClient Put");

docClient.put(params, function (err, data) {
    if (err) {
        speechOutput = 'Update failed';
        console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2));
        callback(sessionAttributes,
            buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));
    } else {
        console.log("Created table. Table description JSON:", JSON.stringify(data, null, 2));
        speechOutput = 'Update successful';
        callback(sessionAttributes,
            buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));
    }
});
}

The following items are already checked

1) There is a table named "Location" in DynamoDB
2) Both DynamoDB and this lambda function are in ue-west-1 (Ireland)
3) The role assigned for this Lambda function can do all operation on this table. See the policy details below

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "Stmt1510603004000",
        "Effect": "Allow",
        "Action": [
            "dynamodb:*"
        ],
        "Resource": [
            "arn:aws:dynamodb:eu-west-1:752546663632:table/Location"
        ]
    }
]
}

How does my Lambda function locate the table "location"  just with the region?- the code does not appear to have end-point, etc.? - just developed based on a tutorial.

Is that what I am missing?

Please can you help?

Body:
I believe that AWS locates the table based on your identity, in combination with the region and the table name.

I was able to successfully post to a table using this code:

const AWS = require('aws-sdk');

const dynamoDB = new AWS.DynamoDB({region: 'us-west-2'});

var params = {
  TableName: "my-table",
  Item: {
    "LocationID": { S: "11" },
    "Country": { S: "10" },
    "Description": { S: "10" },
    "Name": { S: "10" }
  }
};

dynamoDB.putItem(params, (err, data) => {
  if (err){
    console.error(err.stack);
  } else {
    console.log(data);
  }
});

If you can in fact post to the table from the CLI, then there is still at least one remaining issue: it appears that you are using the DocumentClient class incorrectly.  It looks like you're mixing up the syntax for DynamoDB.putItem with the syntax for DynamoDB.DocumentClient.put.

If you notice, my code uses the DynamoDB class directly-- based on what you're doing, I see no reason why you couldn't do the same. Otherwise, you should change your Item object:

var params = {
  TableName: "my-table",
  Item: {
    "LocationID": "11",
    "Country": "10",
    "Description": "10",
    "Name": "10"
  }
};

My guess is your code is currently erroring out because you are trying to insert Maps where you want to insert Strings.  If you have Cloudwatch configured you could check the logs.

Finally, I don't see you using callback in your code.  If your intention is to respond to a client calling the lambda you should do that.  Depending on your NodeJS version, the lambda can simply time out without returning a useful response.


问:
Lock tables and/or transaction for stock table?
How can I maintain data integrity for a stock table with InnoDB? Does this require the use of both a table lock and a transaction? I have tried to find some good examples, but even well known opensource ecommerce software doesn't implement table locks/transactions. Would below code work? Do I really need to lock the whole table, or is there a way to only lock the rows of the sold products? Or does anyone have a good example?

```<code>CREATE TABLE `stock` (
    `product_id` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_unicode_ci',
    `quantity` INT(10) UNSIGNED NOT NULL DEFAULT '0',
    PRIMARY KEY (`product_id`)
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB;
</code>```

.

```<code>LOCK TABLES stock WRITE;
START TRANSACTION;
SET autocommit = 0;
UPDATE stock SET quantity = quantity - 4 WHERE product_id = 'PRODUCT_1' AND quantity >= 4;
UPDATE stock SET quantity = quantity - 2 WHERE product_id = 'PRODUCT_2' AND quantity >= 2;
UPDATE stock SET quantity = quantity - 5 WHERE product_id = 'PRODUCT_3' AND quantity >= 5;
COMMIT or ROLLBACK;
</code>```

COMMIT if all UPDATE queries have 1 affected row, otherwise ROLLBACK

答:
It should not be necessary to do the table-lock, unless you want to make sure concurrent clients running the same code don't run simultaneous updates. I'm not sure that matters, because each of your updates is working on distinct subsets of rows.

In any case, it's not necessary to set autocommit=0 after you start a transaction. Starting a transaction implicitly means that it won't commit until you use COMMIT (or some statement causes an implicit commit).

You might even wrap all three updates into one update, except that you said you want to make sure each update changes at least one row.

Body:
How can I maintain data integrity for a stock table with InnoDB? Does this require the use of both a table lock and a transaction? I have tried to find some good examples, but even well known opensource ecommerce software doesn't implement table locks/transactions. Would below code work? Do I really need to lock the whole table, or is there a way to only lock the rows of the sold products? Or does anyone have a good example?

CREATE TABLE `stock` (
    `product_id` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_unicode_ci',
    `quantity` INT(10) UNSIGNED NOT NULL DEFAULT '0',
    PRIMARY KEY (`product_id`)
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB;

.

LOCK TABLES stock WRITE;
START TRANSACTION;
SET autocommit = 0;
UPDATE stock SET quantity = quantity - 4 WHERE product_id = 'PRODUCT_1' AND quantity >= 4;
UPDATE stock SET quantity = quantity - 2 WHERE product_id = 'PRODUCT_2' AND quantity >= 2;
UPDATE stock SET quantity = quantity - 5 WHERE product_id = 'PRODUCT_3' AND quantity >= 5;
COMMIT or ROLLBACK;

COMMIT if all UPDATE queries have 1 affected row, otherwise ROLLBACK


问:
Access to AmazonWorkspaces
I am setting up an Amazon Workspace instance, and need to provide the user with a password to log in. The invite email only contains the registration code.

How do I set up a user password to enable the user to login into Amazon workspace only (no console access)?

I am creating an AmazonWorkspace from a custom bundle, and adding a user to Simple AD.

答:
To set the user password for AmazonWorkspace, set user password on the WorkMail application for that user.   Directory service manages users for both AmazonWorkspaces and WorkMail, and the password is shared across.

The user must exist, but can be disabled. Email address can be anything, in my case users do not use AWS email.

Users defined in IAM are not visible from AmazonWorkspaces and WorkMail. If a user has console, S3, ec2, etc.. access in addition to Workspace, they would need to be defined separately in IAM and Directory.

Title: Access to AmazonWorkspaces


问:
Change style of n items after selector
I have a group of radio buttons with labels.

input[type="radio"]:checked+label{
  color:red;
}
input[type="radio"]:checked+label~label{
  font-weight:bold;
}

input[type="radio"]:checked+label~label:nth-of-type(-n+3){
  background-color:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input type="radio" name="group1"><label>A</label><br/>
  <input type="radio" name="group1"><label>B</label><br/>
  <input type="radio" name="group1"><label>C</label><br/>
  <input type="radio" name="group1"><label>D</label><br/>
  <input type="radio" name="group1"><label>E</label><br/>
  <input type="radio" name="group1"><label>F</label>
</div></code>```

When I select a radio button I'd like the next three items have a style applied to them.

However, if you run the snippet, you will see that my code only highlights the first three items in the div, not the first three items after the selection.

How can I get the style applied to the first three items after the selection?

Basically I want the following to happen:

答:
An ugly working solution (if I consider the case that you cannot change your html structure) :

input[type="radio"]:checked+label{
  color:red;
}
input[type="radio"]:checked+label~label{
  font-weight:bold;
}

input[type="radio"]:checked+label+br+input+label{
  background-color:green;
}
input[type="radio"]:checked+label+br+input+label+br+input+label{
  background-color:green;
}
input[type="radio"]:checked+label+br+input+label+br+input+label+br+input+label{
  background-color:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input type="radio" name="group1"><label>A</label><br/>
  <input type="radio" name="group1"><label>B</label><br/>
  <input type="radio" name="group1"><label>C</label><br/>
  <input type="radio" name="group1"><label>D</label><br/>
  <input type="radio" name="group1"><label>E</label><br/>
  <input type="radio" name="group1"><label>F</label>
</div></code>```

Title: Change style of n items after selector

Body:
I have a group of radio buttons with labels.

input[type="radio"]:checked+label{
  color:red;
}
input[type="radio"]:checked+label~label{
  font-weight:bold;
}

input[type="radio"]:checked+label~label:nth-of-type(-n+3){
  background-color:green;
}

  <input type="radio" name="group1">A

  <input type="radio" name="group1">B

  <input type="radio" name="group1">C

  <input type="radio" name="group1">D

  <input type="radio" name="group1">E

  <input type="radio" name="group1">F

When I select a radio button I'd like the next three items have a style applied to them.

However, if you run the snippet, you will see that my code only highlights the first three items in the div, not the first three items after the selection.

How can I get the style applied to the first three items after the selection?

Basically I want the following to happen:

Body:
An ugly working solution (if I consider the case that you cannot change your html structure) :

input[type="radio"]:checked+label{
  color:red;
}
input[type="radio"]:checked+label~label{
  font-weight:bold;
}

input[type="radio"]:checked+label+br+input+label{
  background-color:green;
}
input[type="radio"]:checked+label+br+input+label+br+input+label{
  background-color:green;
}
input[type="radio"]:checked+label+br+input+label+br+input+label+br+input+label{
  background-color:green;
}

<div>
  <input type="radio" name="group1"><label>A</label><br/>
  <input type="radio" name="group1"><label>B</label><br/>
  <input type="radio" name="group1"><label>C</label><br/>
  <input type="radio" name="group1"><label>D</label><br/>
  <input type="radio" name="group1"><label>E</label><br/>
  <input type="radio" name="group1"><label>F</label>
</div>


问:
Dynamic BigQuery datasource in Google DataPrep - can it be done?
Can it really be right that I can't define a dynamic datasource using Dataprep. As far as i can see i can only point on a BigQuery Table. I need to point at a certain partion within a table. The naming of the partions always includes the date. like. "ga_20171113".

I really dont understand why i just cant define a SQL thoughwards BQ and use that as a source.

答: Dataprep can ingest data from BigQuery views, which should hopefully be able to support your use case. https://cloud.google.com/bigquery/docs/views has details on creating views. One note: Dataprep only supports views created using standard SQL rather than legacy SQL. So when creating a view from a query, please make sure that "Use Legacy SQL" is unchecked in the query options.</p>


问:
VisualStudio doesn't recognize a new reference that I add
I have written a DLL and then in my solution I am adding a reference to it, but when I declare it in the usings section, it gives me error that this is not recognized, are you missing a reference?

here is how I set up my solution...

1- First I had created my DLL. Let's name it MyDLLLibrary, sitting somewhere on hard drive.

2- I also had a solution, consisting of several other projects...for all of these I have created a folder like "C:\_debug" and I have set "Output Path" and "Reference Path" of all these projects to point to that common folder. So far, s good.

3- Now I add that MyDLLLibrary to this solution, change its "Output" and Reference Path to point to the same common debug folder, use Add Refrence and at the reference to MyDLLLibrary to the project I want in the solution and rebuild the solution...

Now if I use a using statement, still it doesn't recognize it.

I even tried the add refrence from projects tab..that didn't work either.

答: While using Visual Studio 2017, I had to close visual studio and delete the .vs folder (at the root of the solution). This fixed my issues


问:
SQL Server 2016 T-SQL convert comma string to inner join database name(s)
I have a value for one of my columns that looks like this:

```<code>ID   | userPerms | Name      | DOB
-----+-----------+-----------+----------
5985 |1,3,4      |Bob Barker |12/12/1923
895  |1,2        |Bill Gates |10/14/1955
5897 |1,2,4      |Steve Jobs |02/24/1955
</code>```

That column being the userPerms column.

I need to be able to Inner Join with the userPerm table associated with those numbers.

My query is currently:

```<code>SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' + uT.email + '|' +
    uT.firstName  + '|' + uT.lastName        + '|' + uT.active + '|' + uT.userPerms + '|' +
    uT.userPermPages
FROM
    usersTbl AS uT
INNER JOIN
    usersPermissions AS uP ON uP.id = uT.userPerms
WHERE
    uT.id = 1
</code>```

Naturally it won't work since the data has commas in it.

So what I am looking for in the output:

```<code>ID   | userPerms        | Name      | DOB
-----+------------------+-----------+------------
5985 |Read,Upload,Admin |Bob Barker |12/12/1923
895  |Read,Write        |Bill Gates |10/14/1955
5897 |Read,Write,Admin  |Steve Jobs |02/24/1955
</code>```

Does anyone know how to split these out so that the inner join would then work as designed?

UPDATE 1

I got it working but:

It does not combine the userPerms into the original string

```<code>SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' +
    uT.email + '|' + uT.firstName + '|' + uT.lastName + '|' + uT.active,
    (
        SELECT
            ',' + uP.type
        FROM
            usersPermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPerms,
    (
        SELECT
            ',' + uP.name
        FROM
            pagePermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPermPages
FROM
    usersTbl as uT
WHERE
    uT.id = '1';
</code>```

答:
Well, you asked me... :-)

I do not have an installation of SQL-Server 2016 working at the moment, so this is untested air code. But I think you need something like this:

```<code>SET DATEFORMAT mdy;

DECLARE @tblData TABLE(ID INT, userPerms VARCHAR(100),Name VARCHAR(100),DOB DATE);
INSERT INTO @tblData VALUES
 (5985,'1,3,4','Bob Barker','12/12/1923')
,(895,'1,2','Bill Gates','10/14/1955')
,(5897,'1,2,4','Steve Jobs','02/24/1955');

DECLARE @tblPerm TABLE(ID INT, Perm VARCHAR(100));
INSERT INTO @tblPerm VALUES
 (1,'Read')
,(2,'Write')
,(3,'Upload')
,(4,'Admin');

SELECT d.ID,d.Name,d.DOB
      ,STRING_AGG(p.Perm,',') AS Perms
FROM @tblData AS d
CROSS APPLY STRING_SPLIT(d.userPerms,',') AS A
INNER JOIN @tblPerm AS p ON CAST(A.value AS INT)=p.ID --<-- added cast to int
GROUP BY d.ID,d.Name,d.DOB;
</code>```

The function string_split() will separate the values at commas, which allows you to JOIN your catalog table. GROUP BY in combination with STRING_AGG() should return what you want. But I've never used this before...

Hope this helps!

UPDATE: A working solution without string-split and string-agg

```<code>SET DATEFORMAT mdy;

DECLARE @tblData TABLE(ID INT, userPerms VARCHAR(100),Name VARCHAR(100),DOB DATE);
INSERT INTO @tblData VALUES
 (5985,'1,3,4','Bob Barker','12/12/1923')
,(895,'1,2','Bill Gates','10/14/1955')
,(5897,'1,2,4','Steve Jobs','02/24/1955');

DECLARE @tblPerm TABLE(ID INT, Perm VARCHAR(100));
INSERT INTO @tblPerm VALUES
 (1,'Read')
,(2,'Write')
,(3,'Upload')
,(4,'Admin');

WITH Joined As
(
    SELECT d.ID
          ,d.Name
          ,d.DOB
          ,p.Perm
    FROM @tblData AS d
    CROSS APPLY(SELECT CAST('<x>' +  REPLACE(d.userPerms,',','</x><x>') + '</x>' AS XML)) AS A(casted)
    CROSS APPLY A.casted.nodes(N'/x') AS B(numbers)
    INNER JOIN @tblPerm AS p ON CAST(B.numbers.value(N'text()[1]',N'int') AS INT)=p.ID
)
SELECT j.ID
      ,j.Name
      ,j.DOB
      ,STUFF((
        SELECT ',' + x.perm
        FROM Joined AS x
        WHERE x.ID=j.ID
        FOR XML PATH('')
       ),1,1,'') AS Perm
FROM Joined AS j
GROUP BY ID,Name,DOB
</code>```

Body:
I have a value for one of my columns that looks like this:

ID   | userPerms | Name      | DOB
-----+-----------+-----------+----------
5985 |1,3,4      |Bob Barker |12/12/1923
895  |1,2        |Bill Gates |10/14/1955
5897 |1,2,4      |Steve Jobs |02/24/1955

That column being the userPerms column.

I need to be able to Inner Join with the userPerm table associated with those numbers.

My query is currently:

SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' + uT.email + '|' +
    uT.firstName  + '|' + uT.lastName        + '|' + uT.active + '|' + uT.userPerms + '|' +
    uT.userPermPages
FROM
    usersTbl AS uT
INNER JOIN
    usersPermissions AS uP ON uP.id = uT.userPerms
WHERE
    uT.id = 1

Naturally it won't work since the data has commas in it.

So what I am looking for in the output:

ID   | userPerms        | Name      | DOB
-----+------------------+-----------+------------
5985 |Read,Upload,Admin |Bob Barker |12/12/1923
895  |Read,Write        |Bill Gates |10/14/1955
5897 |Read,Write,Admin  |Steve Jobs |02/24/1955

Does anyone know how to split these out so that the inner join would then work as designed?

UPDATE 1

I got it working but:

It does not combine the userPerms into the original string

SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' +
    uT.email + '|' + uT.firstName + '|' + uT.lastName + '|' + uT.active,
    (
        SELECT
            ',' + uP.type
        FROM
            usersPermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPerms,
    (
        SELECT
            ',' + uP.name
        FROM
            pagePermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPermPages
FROM
    usersTbl as uT
WHERE
    uT.id = '1';

Body:
Well, you asked me... :-)

I do not have an installation of SQL-Server 2016 working at the moment, so this is untested air code. But I think you need something like this:

SET DATEFORMAT mdy;

DECLARE @tblData TABLE(ID INT, userPerms VARCHAR(100),Name VARCHAR(100),DOB DATE);
INSERT INTO @tblData VALUES
 (5985,'1,3,4','Bob Barker','12/12/1923')
,(895,'1,2','Bill Gates','10/14/1955')
,(5897,'1,2,4','Steve Jobs','02/24/1955');

DECLARE @tblPerm TABLE(ID INT, Perm VARCHAR(100));
INSERT INTO @tblPerm VALUES
 (1,'Read')
,(2,'Write')
,(3,'Upload')
,(4,'Admin');

SELECT d.ID,d.Name,d.DOB
      ,STRING_AGG(p.Perm,',') AS Perms
FROM @tblData AS d
CROSS APPLY STRING_SPLIT(d.userPerms,',') AS A
INNER JOIN @tblPerm AS p ON CAST(A.value AS INT)=p.ID --<-- added cast to int
GROUP BY d.ID,d.Name,d.DOB;

The function string_split() will separate the values at commas, which allows you to JOIN your catalog table. GROUP BY in combination with STRING_AGG() should return what you want. But I've never used this before...

Hope this helps!

UPDATE: A working solution without string-split and string-agg

SET DATEFORMAT mdy;

DECLARE @tblData TABLE(ID INT, userPerms VARCHAR(100),Name VARCHAR(100),DOB DATE);
INSERT INTO @tblData VALUES
 (5985,'1,3,4','Bob Barker','12/12/1923')
,(895,'1,2','Bill Gates','10/14/1955')
,(5897,'1,2,4','Steve Jobs','02/24/1955');

DECLARE @tblPerm TABLE(ID INT, Perm VARCHAR(100));
INSERT INTO @tblPerm VALUES
 (1,'Read')
,(2,'Write')
,(3,'Upload')
,(4,'Admin');

WITH Joined As
(
    SELECT d.ID
          ,d.Name
          ,d.DOB
          ,p.Perm
    FROM @tblData AS d
    CROSS APPLY(SELECT CAST('<x>' +  REPLACE(d.userPerms,',','</x><x>') + '</x>' AS XML)) AS A(casted)
    CROSS APPLY A.casted.nodes(N'/x') AS B(numbers)
    INNER JOIN @tblPerm AS p ON CAST(B.numbers.value(N'text()[1]',N'int') AS INT)=p.ID
)
SELECT j.ID
      ,j.Name
      ,j.DOB
      ,STUFF((
        SELECT ',' + x.perm
        FROM Joined AS x
        WHERE x.ID=j.ID
        FOR XML PATH('')
       ),1,1,'') AS Perm
FROM Joined AS j
GROUP BY ID,Name,DOB


问:
Bootstrap CSS not working with Flask
*edit
I think the code is correct so maybe it is something to do with Chrome?

*edit 2 included the file structure
enter image description here

I have tried adding a Bootstrap pill to my page but the CSS does not seem to be working. I have tried adding other components as well but the CSS does not seem to work for them either.

I have also tried using "cmd shift r" (I am using a mac), but that has not helped either.

Anyone know why this is not working and how to fix it?

I have downloaded and put into the static the folder the bootstrap-dist.

What the page looks like

The python code

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Home Page</title>
  <meta name="viewport" content="width=device-width, initial scale=1">
  <link type="text/css" href="{{ url_for('static', filename='css/bootstrap.min.css') }}"
   rel="stylesheet">

Home 42

Profile

Messages 3

```

答:
Using the HTML code from your question yields different results depending on the version of Bootstrap you reference. It is possible that you are using Bootstrap 4 when you need to be using Bootstrap 3. This would cause the nav pills to show up like the image in your question.

HTML (from question)

```<code><header>
  <ul class="nav nav-pills" role="tablist">
    <li role="presentation" class="active"><a href="#">Home <span class="badge">42</span></a></li>
    <li role="presentation"><a href="#">Profile</a></li>
    <li role="presentation"><a href="#">Messages <span class="badge">3</span></a></li>
  </ul>
</header>
</code>```

Linking to Bootstrap 3

Linking to Bootstrap 4

Title: Bootstrap CSS not working with Flask

Body:
Using the HTML code from your question yields different results depending on the version of Bootstrap you reference. It is possible that you are using Bootstrap 4 when you need to be using Bootstrap 3. This would cause the nav pills to show up like the image in your question.

HTML (from question)

<header>
  <ul class="nav nav-pills" role="tablist">
    <li role="presentation" class="active"><a href="#">Home <span class="badge">42</span></a></li>
    <li role="presentation"><a href="#">Profile</a></li>
    <li role="presentation"><a href="#">Messages <span class="badge">3</span></a></li>
  </ul>
</header>

Linking to Bootstrap 3

Linking to Bootstrap 4


问:
how to test a cascade delete with Rspec
for my Rails 4 app, I want to test that deleting a Course object deletes associated Chapter objects.

There, on my Course model I defined the assiociation as follows:

```<code>has_many :chapters, dependent: :delete_all
</code>```

This works fine. However, I can't figure out how to write a test for this cascaded delete.

My Rspec test looks like this:

```<code>before do
    @course = Fabricate(:course)
end
it "deletes associated chapters" do
  set_current_admin
  chapter1 = Fabricate(:chapter, course_id: @course_id)
  delete :destroy, id: @course.id
  expect(Chapter.count).to eq(0)
end
</code>```

I would expect Chapter.all to be 0 but when I run this test, I get this result:

```<code>1) Admin::CoursesController DELETE #destroy deletes associated chapters
 Failure/Error: expect(Chapter.all).to eq(0)

   expected: 0
        got: #<ActiveRecord::Relation [#<Chapter id: 709, title: "omnis corrupti eos et   aperiam", description: "Alias sunt tempore aut deserunt. Optio ea assumenda...", course_id: nil, created_at: "2013-11-01 07:10:28", updated_at: "2013-11-01 07:10:28", tagline: "Omnis nemo praesentium corporis. Doloremque dolorib...", badge_image: nil>]>

   (compared using ==)
 # ./spec/controllers/admin/courses_controller_spec.rb:181:in `block (3 levels) in <top (required)>'
</code>```

How can I make this test pass?

Thanks for your help,

Anthony

答:
It's not RSpec, but the following may provide some motivation.</p>

```<code>test 'authentication - dependent destroy' do
  user = users(:adam)
  authentication = user.authentications.first
  user.destroy
  assert_nil Authentication.find_by_id(authentication.id)
end
</code>```

Title: how to test a cascade delete with Rspec

Body:
for my Rails 4 app, I want to test that deleting a Course object deletes associated Chapter objects.

There, on my Course model I defined the assiociation as follows:

has_many :chapters, dependent: :delete_all

This works fine. However, I can't figure out how to write a test for this cascaded delete.

My Rspec test looks like this:

before do
    @course = Fabricate(:course)
end
it "deletes associated chapters" do
  set_current_admin
  chapter1 = Fabricate(:chapter, course_id: @course_id)
  delete :destroy, id: @course.id
  expect(Chapter.count).to eq(0)
end

I would expect Chapter.all to be 0 but when I run this test, I get this result:

1) Admin::CoursesController DELETE #destroy deletes associated chapters
 Failure/Error: expect(Chapter.all).to eq(0)

   expected: 0
        got: #<ActiveRecord::Relation [#<Chapter id: 709, title: "omnis corrupti eos et   aperiam", description: "Alias sunt tempore aut deserunt. Optio ea assumenda...", course_id: nil, created_at: "2013-11-01 07:10:28", updated_at: "2013-11-01 07:10:28", tagline: "Omnis nemo praesentium corporis. Doloremque dolorib...", badge_image: nil>]>

   (compared using ==)
 # ./spec/controllers/admin/courses_controller_spec.rb:181:in `block (3 levels) in <top (required)>'

How can I make this test pass?

Thanks for your help,

Anthony

Body:
It's not RSpec, but the following may provide some motivation.

test 'authentication - dependent destroy' do
  user = users(:adam)
  authentication = user.authentications.first
  user.destroy
  assert_nil Authentication.find_by_id(authentication.id)
end


问:
How can i reload UIPickerView with no scrolling to first ellement? (obj c)
I need to reload UIPickerView components, but it scroll to first row.

The problem: it need to remain selected on current row (i need only update
 rows).
At moment using [stringPicker reloadAllComponents];

Can anybody help with this?

答:
Get the currently selected row, reload the components, then select the previously selected row (without animation).

```<code>NSInteger currentRow = [stringPicker selectedRowInComponent:0]; // or whatever component
[stringPicker reloadAllComponents];
[stringPicker selectRow:currentRow inComponent:0 animated:NO];
</code>```

If the reloaded component might have less rows than it did before being reloaded, you need to ensure that currentRow isn't too big for the reloaded component.

Body:
Get the currently selected row, reload the components, then select the previously selected row (without animation).

NSInteger currentRow = [stringPicker selectedRowInComponent:0]; // or whatever component
[stringPicker reloadAllComponents];
[stringPicker selectRow:currentRow inComponent:0 animated:NO];

If the reloaded component might have less rows than it did before being reloaded, you need to ensure that currentRow isn't too big for the reloaded component.


问:
Symfony template does not render labels in EasyAdmin
Instead of interpreting things like {{ list.page_title }}, it's just rendering as list.page_title, paginator.next, action.search, etc. I'm not getting any errors in the debug toolbar or dev log. I have cleared the cache.

Is there some setting I missed? How do I fix this or figure out where the error is?

答:
Make sure that the translator service is enabled in config.yml

```<code>framework:
    translator: { fallbacks: [ "en" ] }
</code>```

For more translation customisation see: https://symfony.com/doc/current/bundles/EasyAdminBundle/tutorials/i18n.html

Body:
Make sure that the translator service is enabled in config.yml

framework:
    translator: { fallbacks: [ "en" ] }

For more translation customisation see: https://symfony.com/doc/current/bundles/EasyAdminBundle/tutorials/i18n.html


问:
Debugger Not Installed While Starting C# Console App in Visual Studio Community 2017
I have freshly installed Visual Studio Community 2017. I have a simple console app that prints a message. When I click the Start button I get the message

Error while trying to run project: Unable to start program

The debugger is not properly installed. Run setup to install or repair the debugger.

If I click on Debug in the menu and Start Without Debugging, I see the output of the program, so build and run seem to be working. However, I guess the debugger is not installed and I'm not sure how to install it. I've done exhaustive Google searches and seen posts talking about running regsvr32 and repair, both of which have proved fruitless.

EDIT:

Installing VS2015 fixed the problem.

答:
@David Bradford, long time after Novell isn't it? Anyway, after looking all over the place this is the best solution I found. You don't have to install VS2015 just follow the directions below. I tried this and it fixed the problem for me and another person I was working with.

Link to the VS developer community that has various comments and the fix below

Added a solution by Andrey · Jun 23 at 06:01 PM
Best Solultion
C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug
C:\Program Files\Common Files\microsoft shared\VS7Debug

```<code>Solution for this problem for Visual Studio 2017 Community.
</code>```

Clean folders: Delete all the files in the two folders
C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug
C:\Program Files\Common Files\microsoft shared\VS7Debug
Then run repair Visual Studio by clicking the menu (three lines stacked up) to the right of the Modify and Launch buttons.
P.S. This issue happen because dlls corrupted. Here is this case
shareimprove this answer

```<code>This seems to be a known issue and is under investigation by the VS 2017 team. More information here: https://developercommunity.visualstudio.com/content/problem/26630/the-debugger-is-not-properly-installed-cannot-debu.html
</code>```

Body:
@David Bradford, long time after Novell isn't it? Anyway, after looking all over the place this is the best solution I found. You don't have to install VS2015 just follow the directions below. I tried this and it fixed the problem for me and another person I was working with.

Link to the VS developer community that has various comments and the fix below

Added a solution by Andrey · Jun 23 at 06:01 PM
Best Solultion
C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug
C:\Program Files\Common Files\microsoft shared\VS7Debug

Solution for this problem for Visual Studio 2017 Community.

Clean folders: Delete all the files in the two folders
C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug
C:\Program Files\Common Files\microsoft shared\VS7Debug
Then run repair Visual Studio by clicking the menu (three lines stacked up) to the right of the Modify and Launch buttons.
P.S. This issue happen because dlls corrupted. Here is this case
shareimprove this answer

This seems to be a known issue and is under investigation by the VS 2017 team. More information here: https://developercommunity.visualstudio.com/content/problem/26630/the-debugger-is-not-properly-installed-cannot-debu.html


问:
How to insert string into the output string stream
I want to simply write code that inserts my userItems into the output string stream itemsOSS. Each of my item will be followed by a space. I want the output to reflect the following for example,  "red purple yellow Exit":

Output example,

red purple yellow

public class StringStreamOutput {

   public static void main (String [] args) {

      Scanner scnr = new Scanner(System.in);
      String userItem = "";

      StringWriter itemCharStream = new StringWriter();
      PrintWriter itemsOSS = new PrintWriter(itemCharStream);

      System.out.println("Enter items (type Exit to quit):");
      userItem = scnr.next();

      while (!userItem.equals("Exit")) {

         // confused here,

         userItem = scnr.next();
      }

      userItem = itemCharStream.toString();
      System.out.println(userItem);

      return;
   }
}
```

答:
I found the code that works, I just needed to utilize the print method.

itemsOSS.print(userItem + " ");

userItem = itemCharStream.toString();
```


问:
How to close a picture after displaying it?
I wrote JavaScript code that displays an image on click for my site. How do I add a way for it to close after users are done?

function picture() {
  var a = document.getElementById('QR');
  a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
  a.style.display = 'block';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="QR" src="https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg" style="display:none;" />
<button onclick="picture()">Apoyar</button></code>```

https://jsfiddle.net/dmtakr3w/

答:
To close that image after displaying it, you can remove the node by taking the parent element and invoking .removeChild(node); on the parent element.

```<code>function closePicture() {
  var a = document.getElementById('QR');
  var parent = a.parentNode;
  console.log(parent);
  parent.removeChild(a);
}
</code>```

If you assign this function to a button you are able to close the image by clicking it:

```<code><button onclick="closePicture()">Close</button>
</code>```

You can also do a setTimeout() to automatically close the image after a certain amount of seconds or so:

// Removes the image after 5 seconds upon opening:

```<code>function picture() {
  var a = document.getElementById('QR');
  a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
  a.style.display='block';

  setTimeout(function() {
    var a = document.getElementById('QR');
    a.parentNode.removeChild(a);
  }, 5000);
}
</code>```

Body:
I wrote JavaScript code that displays an image on click for my site. How do I add a way for it to close after users are done?

function picture() {
  var a = document.getElementById('QR');
  a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
  a.style.display = 'block';
}

<button onclick="picture()">Apoyar</button>

https://jsfiddle.net/dmtakr3w/

Body:
To close that image after displaying it, you can remove the node by taking the parent element and invoking .removeChild(node); on the parent element.

function closePicture() {
  var a = document.getElementById('QR');
  var parent = a.parentNode;
  console.log(parent);
  parent.removeChild(a);
}

If you assign this function to a button you are able to close the image by clicking it:

<button onclick="closePicture()">Close</button>

You can also do a setTimeout() to automatically close the image after a certain amount of seconds or so:

// Removes the image after 5 seconds upon opening:

function picture() {
  var a = document.getElementById('QR');
  a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
  a.style.display='block';

  setTimeout(function() {
    var a = document.getElementById('QR');
    a.parentNode.removeChild(a);
  }, 5000);
}


答:
As Sag1v said in the comments, just add an on click event to the QR code tag and switch the display back to none.

function picture() {
  var a = document.getElementById('QR');
  a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
  a.style.display = 'block';
}

function closePicture() {
    var a = document.getElementById('QR');
    a.style.display = 'none';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="QR" src="https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg" style="display:none;" onclick="closePicture()" />
<button onclick="picture()">Apoyar</button></code>```

Title: How to close a picture after displaying it?

Body:
As Sag1v said in the comments, just add an on click event to the QR code tag and switch the display back to none.

function picture() {
  var a = document.getElementById('QR');
  a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
  a.style.display = 'block';
}

function closePicture() {
    var a = document.getElementById('QR');
    a.style.display = 'none';
}

<img id="QR" src="https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg" style="display:none;" onclick="closePicture()" />
<button onclick="picture()">Apoyar</button>


问:
SSHClient paramiko Python?
I use this method to send file to remote server:

```<code>def runSendArchive(host, port, username, password, remote_directory, archive):
    try:
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        s.connect(host, username, password, port)

        sftp = s.open_sftp()
        sftp.put(archive, remote_directory)
        print "3 - The file was uploaded via SSH!"

    except (BadHostKeyException, AuthenticationException, SSHException, socket.error) as e:
        print "4 - Error! The file was not uploaded: ", e
</code>```

It returns me an exception:

```<code>except (BadHostKeyException, AuthenticationException, SSHException, socket.error) as e: NameError: global name
</code>```

'BadHostKeyException' is not defined

How to use this library right?

Now I get the following error:

```<code>File "run.py", line 65, in runSendArchive
    sftp.put(archive, remote_directory)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 721, in put
    return self.putfo(fl, remotepath, file_size, callback, confirm)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 677, in putfo
    with self.file(remotepath, 'wb') as fr:
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 338, in open
    t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 774, in _request
    return self._read_response(num)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 826, in _read_response
    self._convert_status(msg)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 859, in _convert_status
    raise IOError(text)
IOError: Failure
</code>```

65 line is sftp.put(archive, remote_directory)

答:
Judging from the line

```<code>paramiko.SSHClient()
</code>```

you are calling import paramiko

Since BadHostKeyException is in paramiko.ssh_exception, you need to add an

```<code>from paramiko.ssh_exception import BadHostKeyException, AuthenticationException, SSHException
</code>```

See http://docs.paramiko.org/en/2.3/api/ssh_exception.html

paramiko.ssh_exception.BadHostKeyException

paramiko.ssh_exception.AuthenticationException

paramiko.ssh_exception.SSHException

reside in that module.

For your example code snippet you would need to add the following before the runSendArchive function

```<code>import socket
import paramiko
from paramiko.ssh_exception import BadHostKeyException, AuthenticationException, SSHException
</code>```

Title: SSHClient paramiko Python?

Body:
I use this method to send file to remote server:

def runSendArchive(host, port, username, password, remote_directory, archive):
    try:
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        s.connect(host, username, password, port)

        sftp = s.open_sftp()
        sftp.put(archive, remote_directory)
        print "3 - The file was uploaded via SSH!"

    except (BadHostKeyException, AuthenticationException, SSHException, socket.error) as e:
        print "4 - Error! The file was not uploaded: ", e

It returns me an exception:

except (BadHostKeyException, AuthenticationException, SSHException, socket.error) as e: NameError: global name

'BadHostKeyException' is not defined

How to use this library right?

Now I get the following error:

File "run.py", line 65, in runSendArchive
    sftp.put(archive, remote_directory)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 721, in put
    return self.putfo(fl, remotepath, file_size, callback, confirm)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 677, in putfo
    with self.file(remotepath, 'wb') as fr:
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 338, in open
    t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 774, in _request
    return self._read_response(num)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 826, in _read_response
    self._convert_status(msg)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 859, in _convert_status
    raise IOError(text)
IOError: Failure

65 line is sftp.put(archive, remote_directory)

Body:
Judging from the line

paramiko.SSHClient()

you are calling import paramiko

Since BadHostKeyException is in paramiko.ssh_exception, you need to add an

from paramiko.ssh_exception import BadHostKeyException, AuthenticationException, SSHException

See http://docs.paramiko.org/en/2.3/api/ssh_exception.html

paramiko.ssh_exception.BadHostKeyException

paramiko.ssh_exception.AuthenticationException

paramiko.ssh_exception.SSHException

reside in that module.

For your example code snippet you would need to add the following before the runSendArchive function

import socket
import paramiko
from paramiko.ssh_exception import BadHostKeyException, AuthenticationException, SSHException


问:
python distinguish between '300' and '300.0' for a dataframe column
Recently I have been developing some code to read a csv file and store key data columns in a dataframe. Afterwards I plan to have some mathematical functions performed on certain columns in the dataframe.

I've been fairly successful in storing the correct columns in the dataframe. I have been able to have it do whatever maths is necessary such as summations, additions of dataframe columns, averaging etc.

My problem lies in accessing specific columns once they are stored in the dataframe. I was working with a test file to get everything working and managed this no problem. The problems arise when I open a different csv file, it will store the data in the dataframe, but the accessing the column I want no longer works and it stops at the calculation part.

From what I can tell the problem lies with how it reads the column name. The column names are all numbers. For example, df['300'], df['301'] etc. When accessing the column df['300'] works fine in the testfile, while the next file requires df['300.0']. If I switch to a different file it may require df['300'] again. All the data was obtained in the same way so I am not certain why some are read as 300 and the others 300.0.

Short of constantly changing the column labels each time I open a different file, is there anyway to have it automatically distinguish between '300' and '300.0' when opening the file, or force '300.0' = '300'?

Thanks

答:
In your dataframe df, one way to keep consistency may be to convert to similar types of columns. You can update all the column name to string value of integer from float i.e. '300.0' to '300' using .columns as below. Then, I think using integer value of string should work i.e. df['300] or any other columns other than 300.

```<code>df.columns = [str(int(float(column))) for column in df.columns]
</code>```

Or, if integer value is not required,extra int conversion can be removed and float string value can be used:

```<code>df.columns = [str(float(column)) for column in df.columns]
</code>```

Then, df['300.0'] can be used instead of df['300'].

If string type is not required then, I think converting them float would work as well.

```<code>df.columns = [float(column) for column in df.columns]
</code>```

Then, df[300.0] would work as well.

Other alternative to change column names may be using map:

Changing to float value for all columns, then as mentioned above use df[300.0]:

df.columns = map(float, df.columns)

Changing to string value of float, then df['300.0']:

df.columns = map(str, map(float, df.columns))

Changing to string value of int, then df['300']:

df.columns = map(str, map(int, map(float, df.columns)))

Body:
In your dataframe df, one way to keep consistency may be to convert to similar types of columns. You can update all the column name to string value of integer from float i.e. '300.0' to '300' using .columns as below. Then, I think using integer value of string should work i.e. df['300] or any other columns other than 300.

df.columns = [str(int(float(column))) for column in df.columns]

Or, if integer value is not required,extra int conversion can be removed and float string value can be used:

df.columns = [str(float(column)) for column in df.columns]

Then, df['300.0'] can be used instead of df['300'].

If string type is not required then, I think converting them float would work as well.

df.columns = [float(column) for column in df.columns]

Then, df[300.0] would work as well.

Other alternative to change column names may be using map:

Changing to float value for all columns, then as mentioned above use df[300.0]:

df.columns = map(float, df.columns)

Changing to string value of float, then df['300.0']:

df.columns = map(str, map(float, df.columns))

Changing to string value of int, then df['300']:

df.columns = map(str, map(int, map(float, df.columns)))


问:
Anyway to obtain cell Precedents and Dependents in Excel Javascript API?
Unlike the desktop Excel APIs, which contain a "Precedents" and a "Dependents" on the Range object, the short answer is no for the Excel Javascript APIs, which brings me here.

Is there a way or third-party piece of code to circumvent this huge lack from Microsoft ? If I can't navigate the formula tree, there is just not much useful I can add in terms of add-ins for Excel Online.

Javascript API for Excel

Office Online

UPDATE: to add some context, I've been writing auditing add-ins in C# in the past, to evaluate formula complexity, perform advanced reconciliation of formulas, reconstruct formulas differently, etc... I'm trying to convert a small piece of it, as a javascript prototype add-in, to see whether Excel online can handle it.

答:
Why do you want to know a cell's precedents? Is it to implement formula-like functionality so that your add in can enable a function such as =JEROMESUM(A1,A7)?

If so, the JavaScript API has recently added this capability in preview for you to try, called "custom functions": https://aka.ms/customfunctions


问:
HTML5 Changing paragraphs background color with button js
I got small troubles with this one:

```<code><style>
p:empty {height:20px};
p:nth-child(4n+3) {background:black};
</style>
</head>

<body>

<button onclick="f()">white</button>
<script>
function f() {
var x = document.getElementsByTagName("p");
x.style.backgroundColor = "white";
}
</script>

<p></p>
<p></p>
<p></p>
....
</code>```

(there are 20paragraphs)
So every 4th paragraph got black background, and it all works well.
I want this button to switch black back to the white after clicking on it, but it's just not working, what am I doing wrong?

答:
From what I can see, your function f makes the  call document.getElementsByTagName("p"). document.getElementsByTagName returns an HTMLCollection object, which does not have a style property, and setting it wont do anything. What you want to do is iterate through the items of the HTMLCollection and set the style for each element, like so:

```<code>// This function will make all <p> elements have a white background
function f() {
    var paragraphs = document.getElementsByTagName("p");
    for (var i = 0; i < paragraphs.length; i++) {
        paragraphs[i].style.backgroundColor = "white";
    }
}
</code>```

For more information see Mozilla's documentation for HTMLCollection and document.getElementsByTagName.

Body:
I got small troubles with this one:

<button onclick="f()">white</button>

....

(there are 20paragraphs)
So every 4th paragraph got black background, and it all works well.
I want this button to switch black back to the white after clicking on it, but it's just not working, what am I doing wrong?

Body:
From what I can see, your function f makes the  call document.getElementsByTagName("p"). document.getElementsByTagName returns an HTMLCollection object, which does not have a style property, and setting it wont do anything. What you want to do is iterate through the items of the HTMLCollection and set the style for each element, like so:

// This function will make all <p> elements have a white background
function f() {
    var paragraphs = document.getElementsByTagName("p");
    for (var i = 0; i < paragraphs.length; i++) {
        paragraphs[i].style.backgroundColor = "white";
    }
}

For more information see Mozilla's documentation for HTMLCollection and document.getElementsByTagName.