问:
cleanest way to access sproc data in asp.net
I haven't accessed data using SqlCommand etc. for a while as I tend to use NHibernate these days. I am just wondering whether the following code could be improved. I have tried to use best practises (after some google-ing) and potential exceptions are caught at a higher layer.

```<code>[WebMethod]
    public XmlDocument GetClassRegistrationReport()
    {
        XmlDocument doc = new XmlDocument();

        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["bla"].ToString()))
        {
            using (SqlCommand command = connection.CreateCommand())
            {
                command.CommandText = "bla";
                command.CommandType = CommandType.StoredProcedure;
                connection.Open();
                doc.Load(command.ExecuteXmlReader());
            }
        }

        return doc;
    }

Thanks!
</code>```

Best wishes,

Christian

答:
There are a few ways you could improve it a little:

Although the WebMethod pulls data and returns it verbatim with no input parameters, I would suggest seperating service interface and the data into seperate classes.  It may make things easier to maintain at a later date.

Assuming there are other DB calls in your framework you may want to consider a helper method in your data layer that wraps up the invocation of a stored procedure.  This way you only have one method that all SP calls filter down into which again will make things easier to maintain in the future.

Make the 'bla' key for your connection string setting a constant, this way you can easily reuse and change.

The same applies to the name of the stored procedure, alternatively make it part of your web.config - this means you can change the stored proc name without having to recompile.

If an exception is throw there is no handling for this so the exception will bubble out to the caller, consider catching and handling/logging exceptions.  That said you do mention that you are handling exceptions at a higher layer, so I assume this is being done in whatever is calling your webservices.

You should be disposing the SQL command object (in the finally of the try/catch/finally if you do implement exception handling)

EDIT : Code Sample

```<code>public class MyWebService
{
    [WebMethod]
    public XmlDocument GetClassRegistrationReport()
    {
        return DataLayer.GetClassRegistrationReport();
    }
}
// Notice that this is a static internal class, internal to hide the
// data access class from everything but this library and static because
// we don't need instances and using statics will optimise a little.
internal static class DataLayer
{
    private const string SP_GetRegistrationReport = "GetRegistrationReport";
    private const string Config_DBConnectionString = "PrimaryDB";

    private static string GetDB
    {
        get
        {
            string dbConnectionString = ConfigurationManager.ConnectionStrings[Config_DBConnectionString].ConnectionString;

            if (string.IsNullOrEmpty(dbConnectionString))
            {
                // This error should could/should be in a resource file.
                throw new ConfigurationException("Database connection string is not defined");
            }

            return dbConnectionString;
        }
    }

    internal static XmlDocument GetClassRegistrationReport()
    {
        XmlDocument doc = new XmlDocument();

        using (SqlConnection connection = new SqlConnection())
        {
            using (SqlCommand command = connection.CreateCommand())
            {
                command.CommandText = SP_GetRegistrationReport;
                command.CommandType = CommandType.StoredProcedure;
                connection.Open();
                doc.Load(command.ExecuteXmlReader());
            }
        }

        return doc;
    }
}
</code>```

Body:
I haven't accessed data using SqlCommand etc. for a while as I tend to use NHibernate these days. I am just wondering whether the following code could be improved. I have tried to use best practises (after some google-ing) and potential exceptions are caught at a higher layer.

[WebMethod]
    public XmlDocument GetClassRegistrationReport()
    {
        XmlDocument doc = new XmlDocument();

        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["bla"].ToString()))
        {
            using (SqlCommand command = connection.CreateCommand())
            {
                command.CommandText = "bla";
                command.CommandType = CommandType.StoredProcedure;
                connection.Open();
                doc.Load(command.ExecuteXmlReader());
            }
        }

        return doc;
    }

Thanks!

Best wishes,

Christian

Body:
There are a few ways you could improve it a little:

Although the WebMethod pulls data and returns it verbatim with no input parameters, I would suggest seperating service interface and the data into seperate classes.  It may make things easier to maintain at a later date.

Assuming there are other DB calls in your framework you may want to consider a helper method in your data layer that wraps up the invocation of a stored procedure.  This way you only have one method that all SP calls filter down into which again will make things easier to maintain in the future.

Make the 'bla' key for your connection string setting a constant, this way you can easily reuse and change.

The same applies to the name of the stored procedure, alternatively make it part of your web.config - this means you can change the stored proc name without having to recompile.

If an exception is throw there is no handling for this so the exception will bubble out to the caller, consider catching and handling/logging exceptions.  That said you do mention that you are handling exceptions at a higher layer, so I assume this is being done in whatever is calling your webservices.

You should be disposing the SQL command object (in the finally of the try/catch/finally if you do implement exception handling)

EDIT : Code Sample

public class MyWebService
{
    [WebMethod]
    public XmlDocument GetClassRegistrationReport()
    {
        return DataLayer.GetClassRegistrationReport();
    }
}
// Notice that this is a static internal class, internal to hide the
// data access class from everything but this library and static because
// we don't need instances and using statics will optimise a little.
internal static class DataLayer
{
    private const string SP_GetRegistrationReport = "GetRegistrationReport";
    private const string Config_DBConnectionString = "PrimaryDB";

    private static string GetDB
    {
        get
        {
            string dbConnectionString = ConfigurationManager.ConnectionStrings[Config_DBConnectionString].ConnectionString;

            if (string.IsNullOrEmpty(dbConnectionString))
            {
                // This error should could/should be in a resource file.
                throw new ConfigurationException("Database connection string is not defined");
            }

            return dbConnectionString;
        }
    }

    internal static XmlDocument GetClassRegistrationReport()
    {
        XmlDocument doc = new XmlDocument();

        using (SqlConnection connection = new SqlConnection())
        {
            using (SqlCommand command = connection.CreateCommand())
            {
                command.CommandText = SP_GetRegistrationReport;
                command.CommandType = CommandType.StoredProcedure;
                connection.Open();
                doc.Load(command.ExecuteXmlReader());
            }
        }

        return doc;
    }
}


来源: stackexchange

问:
Unit test controller, angularJS and jasmine
Hi I've been trying to unit test basic functions in my controller however I can't seem to connect when setting up the unit test.

Error: [$injector:modulerr] Failed to instantiate module myApp due to:
[$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Here is my controller:

```<code>    var myApp = angular.module("myApp", []);
myApp.controller('studentController', function($scope,$route,$routeParams,$http,$location){

//Get all students
    $scope.getStudents = function(){
        $http.get('/api/student/').then(function(response){
            $scope.students = response.data;
        });
    };
</code>```

and my test:

```<code>describe("studentController", function () {
    beforeEach(module('myApp'));

    var $controller;
    beforeEach(inject(function (_$controller_){
        $controller = _$controller_;
    }))

    describe("studentController", function(){
        it("should get student data", function (){
            var $scope = {};
            $scope.getStudents();
            expect($scope.students.length).toBe(15)
        })
    })

    });
</code>```

I have included both these files in the jasmine html file along with the angular-mocks.js

any help would be much appreciated

答:
You have to create controller in before each by using following and as you are calling getStudents that shuold be mocked by using HttpBackend service in unit test.

Controller

```<code>    var myApp = angular.module("myApp", []);

    myApp.controller('studentController', function($scope, $route, $routeParams, $http, $location) {
      //Get all students
      $scope.getStudents = function() {
        $http.get('/api/student/').then(function(response) {
          $scope.students = response.data;
        });
      };
    });
</code>```

Test file

```<code>    describe("studentController", function() {
      beforeEach(module('myApp'));

      var $controller, scope, route;
      beforeEach(inject(function(_$controller_, $rootScope, $route, $routeParams, $http, $location) {
        $controller = _$controller_;
        scope = $rootScope.$new();
        $controller('studentController', {
          '$scope': scope,
          '$route': $route,
          '$routeParams': $routeParams,
          '$http': $http,
          '$location': $location

        });

      }))

      describe("studentController", function() {
        it("should get student data", function() {
          // for this you have to use httpBackend
          // you have to mock the response of api
          $scope.getStudents();
          // then you are able to verify the result in student
          expect($scope.students.length).toBe(15)
        })
      })

    });
</code>```

For more information you can refer unit testing and Httpbackend

ContentLicense: CC BY-SA 3.0

Body:
Hi I've been trying to unit test basic functions in my controller however I can't seem to connect when setting up the unit test.

Error: [$injector:modulerr] Failed to instantiate module myApp due to:
[$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Here is my controller:

    var myApp = angular.module("myApp", []);
myApp.controller('studentController', function($scope,$route,$routeParams,$http,$location){

//Get all students
    $scope.getStudents = function(){
        $http.get('/api/student/').then(function(response){
            $scope.students = response.data;
        });
    };

and my test:

describe("studentController", function () {
    beforeEach(module('myApp'));

    var $controller;
    beforeEach(inject(function (_$controller_){
        $controller = _$controller_;
    }))

    describe("studentController", function(){
        it("should get student data", function (){
            var $scope = {};
            $scope.getStudents();
            expect($scope.students.length).toBe(15)
        })
    })

    });

I have included both these files in the jasmine html file along with the angular-mocks.js

any help would be much appreciated

Body:
You have to create controller in before each by using following and as you are calling getStudents that shuold be mocked by using HttpBackend service in unit test.

Controller

    var myApp = angular.module("myApp", []);

    myApp.controller('studentController', function($scope, $route, $routeParams, $http, $location) {
      //Get all students
      $scope.getStudents = function() {
        $http.get('/api/student/').then(function(response) {
          $scope.students = response.data;
        });
      };
    });

Test file

    describe("studentController", function() {
      beforeEach(module('myApp'));

      var $controller, scope, route;
      beforeEach(inject(function(_$controller_, $rootScope, $route, $routeParams, $http, $location) {
        $controller = _$controller_;
        scope = $rootScope.$new();
        $controller('studentController', {
          '$scope': scope,
          '$route': $route,
          '$routeParams': $routeParams,
          '$http': $http,
          '$location': $location

        });

      }))

      describe("studentController", function() {
        it("should get student data", function() {
          // for this you have to use httpBackend
          // you have to mock the response of api
          $scope.getStudents();
          // then you are able to verify the result in student
          expect($scope.students.length).toBe(15)
        })
      })

    });

For more information you can refer unit testing and Httpbackend


问:
how to apply spring message convertors based on condition?
I have a controller whose response is camelCase json value. Now we are re-writing the code with new version and the response required is in snake_case.

I have added a message converter and modified object mapper to setsetPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

```<code>public class ResponseJSONConverter extends MappingJackson2HttpMessageConverter {

@Autowired
public ResponseJSONConverter(ObjectMapper objectMapper) {
    setObjectMapper(objectMapper);
  }
}
</code>```

I have registered this convertor with spring and its working as expected. Now I want my old endpoints to return in camelCase for backward compatibility for my consumers and new endpoints with snake_case.

I have tried to have one more message convertor with simple object mapper without setting camelCase to Snake case property and registered with spring. Only one message convertor gets applied based on the order declared in the spring configuration.

Is there any way we can achieve this ? Loading message convertor based on the condition ?

EDIT

Added my spring config file

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

<bean id="moneySerializer" class="api.serialize.MoneySerializer"/>
    <bean id="moneyDeserializer" class="api.serialize.MoneyDeserializer"/>
    <bean id="serializationModule" class="api.serialize.SerializationModule">
        <constructor-arg index="0" ref="moneySerializer"/>
        <constructor-arg index="1" ref="moneyDeserializer"/>
    </bean>

    <bean id="customObjectMapper" class="api.serialize.CustomObjectMapper" primary="true">
        <constructor-arg ref="serializationModule"/>
    </bean>
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="api.serialize.ResponseJSONConverterCamelCaseToSnakeCase" >
                <constructor-arg ref="customObjectMapper"/>
            </bean>
            <bean class="api.serialize.ResponseJSONConverter">
                <constructor-arg ref="objectMapper"/>
            </bean>
        </mvc:message-converters>

    </mvc:annotation-driven>

    <bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper"/>

</beans>
```

<p><strong>EDIT 2.0</strong></p>

<p><em>my servlet.xml</em></p>

```<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean class="com.tgt.promotions.api.serialize.ServiceJSONConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>
```

<p><em>CustomMessageConverter</em></p>

```    public class ServiceJSONConverter extends MappingJackson2HttpMessageConverter {

    @Autowired
    public ServiceJSONConverter(SnakeCaseObjectMapper snakeCaseObjectMapper) {
        setObjectMapper(snakeCaseObjectMapper);
    }
}
```

<p><em>Custom Object Mapper</em></p>

```@Component
public class SnakeCaseObjectMapper extends ObjectMapper {
    @Autowired
    public SnakeCaseObjectMapper(PropertyNamingStrategy propertyNamingStrategy) {
        setSerializationInclusion(JsonInclude.Include.NON_NULL);
        setPropertyNamingStrategy(propertyNamingStrategy);
    }
}
```

<p><em>Custom Property Naming Strategy</em></p>

```@Component
public class CustomPropertyNamingStrategy extends PropertyNamingStrategy {

    @Autowired
    private HttpServletRequest request;

    private final PropertyNamingStrategy legacyStrategy  = PropertyNamingStrategy.LOWER_CASE;
    private final PropertyNamingStrategy defaultStrategy  = PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES;

    @Override
    public String nameForConstructorParameter(MapperConfig<?> config, AnnotatedParameter ctorParam, String defaultName) {
        return getStrategy().nameForConstructorParameter(config, ctorParam, defaultName);
    }

    @Override
    public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
        return getStrategy().nameForField(config, field, defaultName);
    }

    @Override
    public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        return getStrategy().nameForGetterMethod(config, method, defaultName);
    }

    @Override
    public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        return getStrategy().nameForSetterMethod(config, method, defaultName);
    }

    private PropertyNamingStrategy getStrategy() {
        if (isLegacyEndpoint(request)) {
            return legacyStrategy;
        } else {
            return defaultStrategy;
        }
    }

    private boolean isLegacyEndpoint(HttpServletRequest request) {
        return request != null && request.getRequestURL() != null && !request.getRequestURL().toString().contains("/v3");
    }
}
```

答:
Well, nothing worked after many attempts. Finally ended up defining 2 different servlets. one without any version and one with v1 version.

web.xml

```<code>        <servlet>
            <servlet-name>snake-case</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>

        <servlet-mapping>
            <servlet-name>snake-case</servlet-name>
            <url-pattern>/v1</url-pattern>
        </servlet-mapping>

         <servlet>
            <servlet-name>camel-case</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>

        <servlet-mapping>
            <servlet-name>camel-case</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
</code>```

Accordingly defined two servlets snake-case-servlet.xml and camel-case-servlet.xml.

snake-case-servlet.xml

```<code>    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="com.tgt.promotions.api.serialize.DataJSONConverter">
            <constructor-arg ref="snakeCaseObjectMapper"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</code>```

camel-case-servlet.xml

```<code>    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="com.tgt.promotions.api.serialize.DataJSONConverter">
            <constructor-arg ref="objectMapper"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</code>```

Now, for any requests with /v1* , snakeCaseObjectMapper is used and for other requests default object mapper is used.

Body:
I have a controller whose response is camelCase json value. Now we are re-writing the code with new version and the response required is in snake_case.

I have added a message converter and modified object mapper to setsetPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

public class ResponseJSONConverter extends MappingJackson2HttpMessageConverter {

@Autowired
public ResponseJSONConverter(ObjectMapper objectMapper) {
    setObjectMapper(objectMapper);
  }
}

I have registered this convertor with spring and its working as expected. Now I want my old endpoints to return in camelCase for backward compatibility for my consumers and new endpoints with snake_case.

I have tried to have one more message convertor with simple object mapper without setting camelCase to Snake case property and registered with spring. Only one message convertor gets applied based on the order declared in the spring configuration.

Is there any way we can achieve this ? Loading message convertor based on the condition ?

EDIT

Added my spring config file

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

<bean id="moneySerializer" class="api.serialize.MoneySerializer"/>
    <bean id="moneyDeserializer" class="api.serialize.MoneyDeserializer"/>
    <bean id="serializationModule" class="api.serialize.SerializationModule">
        <constructor-arg index="0" ref="moneySerializer"/>
        <constructor-arg index="1" ref="moneyDeserializer"/>
    </bean>

    <bean id="customObjectMapper" class="api.serialize.CustomObjectMapper" primary="true">
        <constructor-arg ref="serializationModule"/>
    </bean>
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="api.serialize.ResponseJSONConverterCamelCaseToSnakeCase" >
                <constructor-arg ref="customObjectMapper"/>
            </bean>
            <bean class="api.serialize.ResponseJSONConverter">
                <constructor-arg ref="objectMapper"/>
            </bean>
        </mvc:message-converters>

    </mvc:annotation-driven>

    <bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper"/>

</beans>

EDIT 2.0

my servlet.xml

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean class="com.tgt.promotions.api.serialize.ServiceJSONConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>

CustomMessageConverter

    public class ServiceJSONConverter extends MappingJackson2HttpMessageConverter {

    @Autowired
    public ServiceJSONConverter(SnakeCaseObjectMapper snakeCaseObjectMapper) {
        setObjectMapper(snakeCaseObjectMapper);
    }
}

Custom Object Mapper

@Component
public class SnakeCaseObjectMapper extends ObjectMapper {
    @Autowired
    public SnakeCaseObjectMapper(PropertyNamingStrategy propertyNamingStrategy) {
        setSerializationInclusion(JsonInclude.Include.NON_NULL);
        setPropertyNamingStrategy(propertyNamingStrategy);
    }
}

Custom Property Naming Strategy

@Component
public class CustomPropertyNamingStrategy extends PropertyNamingStrategy {

    @Autowired
    private HttpServletRequest request;

    private final PropertyNamingStrategy legacyStrategy  = PropertyNamingStrategy.LOWER_CASE;
    private final PropertyNamingStrategy defaultStrategy  = PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES;

    @Override
    public String nameForConstructorParameter(MapperConfig<?> config, AnnotatedParameter ctorParam, String defaultName) {
        return getStrategy().nameForConstructorParameter(config, ctorParam, defaultName);
    }

    @Override
    public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
        return getStrategy().nameForField(config, field, defaultName);
    }

    @Override
    public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        return getStrategy().nameForGetterMethod(config, method, defaultName);
    }

    @Override
    public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        return getStrategy().nameForSetterMethod(config, method, defaultName);
    }

    private PropertyNamingStrategy getStrategy() {
        if (isLegacyEndpoint(request)) {
            return legacyStrategy;
        } else {
            return defaultStrategy;
        }
    }

    private boolean isLegacyEndpoint(HttpServletRequest request) {
        return request != null && request.getRequestURL() != null && !request.getRequestURL().toString().contains("/v3");
    }
}

Body:
Well, nothing worked after many attempts. Finally ended up defining 2 different servlets. one without any version and one with v1 version.

web.xml

        <servlet>
            <servlet-name>snake-case</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>

        <servlet-mapping>
            <servlet-name>snake-case</servlet-name>
            <url-pattern>/v1</url-pattern>
        </servlet-mapping>

         <servlet>
            <servlet-name>camel-case</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>

        <servlet-mapping>
            <servlet-name>camel-case</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>

Accordingly defined two servlets snake-case-servlet.xml and camel-case-servlet.xml.

snake-case-servlet.xml

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="com.tgt.promotions.api.serialize.DataJSONConverter">
            <constructor-arg ref="snakeCaseObjectMapper"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

camel-case-servlet.xml

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="com.tgt.promotions.api.serialize.DataJSONConverter">
            <constructor-arg ref="objectMapper"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

Now, for any requests with /v1* , snakeCaseObjectMapper is used and for other requests default object mapper is used.


问:
How do I access textField Value, which is created dynamically in Objective C using for loop?
I have created 4 UITextField using for loop in Objective C. Now I want to validate those text. whether those text field is empty or not.

```<code> for(int i=0;i<4; i++){

            UITextField   *textField = [[UITextField alloc] initWithFrame:CGRectMake(x, y, 211, 39)];
            UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
            [textField setTag:i];
            textField.leftView = paddingView;
            textField.leftViewMode = UITextFieldViewModeAlways;
            textField.backgroundColor = [UIColor colorWithRed:237.0/255.0 green:237.0/255.0 blue:237.0/255.0 alpha:1.0];
            textField.font = [UIFont systemFontOfSize:15];
            textField.placeholder = [placeholder objectAtIndex:i];
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            textField.keyboardType = UIKeyboardTypeDefault;
            textField.returnKeyType = UIReturnKeyDone;
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            if(i>=2){
                [textField setSecureTextEntry:YES];
            }
             [self.view addSubview:textField];
            y=y+69;
}
</code>```

答:
You can retrieve textfields like below with tag value.

```<code>UITextField *txtField1 = [self.view viewWithTag:0];
UITextField *txtField2 = [self.view viewWithTag:1];
UITextField *txtField3 = [self.view viewWithTag:2];
UITextField *txtField4 = [self.view viewWithTag:3];
UITextField *txtField5 = [self.view viewWithTag:4];

if(txtField1.text.length > 0)
{

}
</code>```

Same check you can apply for other textfields.

Note:
 Make sure you have unique tag values rather than 0,1,2,3,4,5.

Body:
I have created 4 UITextField using for loop in Objective C. Now I want to validate those text. whether those text field is empty or not.

 for(int i=0;i<4; i++){

            UITextField   *textField = [[UITextField alloc] initWithFrame:CGRectMake(x, y, 211, 39)];
            UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
            [textField setTag:i];
            textField.leftView = paddingView;
            textField.leftViewMode = UITextFieldViewModeAlways;
            textField.backgroundColor = [UIColor colorWithRed:237.0/255.0 green:237.0/255.0 blue:237.0/255.0 alpha:1.0];
            textField.font = [UIFont systemFontOfSize:15];
            textField.placeholder = [placeholder objectAtIndex:i];
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            textField.keyboardType = UIKeyboardTypeDefault;
            textField.returnKeyType = UIReturnKeyDone;
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            if(i>=2){
                [textField setSecureTextEntry:YES];
            }
             [self.view addSubview:textField];
            y=y+69;
}

Body:
You can retrieve textfields like below with tag value.

UITextField *txtField1 = [self.view viewWithTag:0];
UITextField *txtField2 = [self.view viewWithTag:1];
UITextField *txtField3 = [self.view viewWithTag:2];
UITextField *txtField4 = [self.view viewWithTag:3];
UITextField *txtField5 = [self.view viewWithTag:4];

if(txtField1.text.length > 0)
{

}

Same check you can apply for other textfields.

Note:
 Make sure you have unique tag values rather than 0,1,2,3,4,5.


问:
How can I replace %20 with - from url using php?
code:

```<code> <?php
    $query = "select * from latest_news limit 0,10";
    $fet = mysqli_query($link,$query);
    while ($fetch = mysqli_fetch_array($fet))
    {
 ?>
 <p id="news-h3"><?php echo $fetch['news_title']; ?>...<a href="news-details.php?news_tags=<?php echo $fetch['news_tags']; ?>" style="color:red;">[Read More]</a></p>
 <?php
     }
 ?>
</code>```

When I click on link i.e.

```<code><a href="news-details.php?news_tags=<?php echo $fetch['news_tags']; ?>" style="color:red;">[Read More]</a>
</code>```

It show

```<code>best%20engineering%20college%20in%20India
</code>```

Here, I want to replace %20 with (-) from url and get result like

```<code>best-engineering-college-in-India
</code>```

how can I fix this problem please help.

Thank you

答:
1.you can use this php built in function.you just want to replace a piece of string by another.

```<code>$new_url = str_replace('%20', '-', $url);
</code>```

for more information

http://fr2.php.net/str_replace

2.Use urlencode to encode. The decoding will happen automatically,
and if you want to remove total 20% then use this code.

```<code> $url = "one%20%26%20two";
 $a = urldecode($url); // -> "one & two"
</code>```

suppose your page when loading then create your url like this

```<code> $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$base_url = $protocol . $_SERVER["SERVER_NAME"];
</code>```

then use it

```<code>urldecode($base_url)
</code>```

if you want to use this in url then

```<code> echo '<a href="?mycgi?foo=', urlencode($userinput), '">';
</code>```

for more information

http://www.php.net/manual/en/function.urldecode.php

Body:
code:

 <?php
    $query = "select * from latest_news limit 0,10";
    $fet = mysqli_query($link,$query);
    while ($fetch = mysqli_fetch_array($fet))
    {
 ?>

<?php echo $fetch['news_title']; ?>...<a href="news-details.php?news_tags=<?php echo $fetch['news_tags']; ?>" style="color:red;">[Read More]

 <?php
     }
 ?>

When I click on link i.e.

<a href="news-details.php?news_tags=<?php echo $fetch['news_tags']; ?>" style="color:red;">[Read More]

It show

best%20engineering%20college%20in%20India

Here, I want to replace %20 with (-) from url and get result like

best-engineering-college-in-India

how can I fix this problem please help.

Thank you

Body:
1.you can use this php built in function.you just want to replace a piece of string by another.

$new_url = str_replace('%20', '-', $url);

for more information

http://fr2.php.net/str_replace

2.Use urlencode to encode. The decoding will happen automatically,
and if you want to remove total 20% then use this code.

 $url = "one%20%26%20two";
 $a = urldecode($url); // -> "one & two"

suppose your page when loading then create your url like this

 $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$base_url = $protocol . $_SERVER["SERVER_NAME"];

then use it

urldecode($base_url)

if you want to use this in url then

 echo '<a href="?mycgi?foo=', urlencode($userinput), '">';

for more information

http://www.php.net/manual/en/function.urldecode.php


问:
Ruby on Rails: How can I revert a migration with rake db:migrate?
After installing devise MODEL User i got this.

```<code>class DeviseCreateUsers < ActiveRecord::Migration
  def self.up
    create_table(:users) do |t|
      t.database_authenticatable :null => false
      t.recoverable
      t.rememberable
      t.trackable

      # t.encryptable
      # t.confirmable
      # t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both
      # t.token_authenticatable

      t.timestamps
    end

    add_index :users, :email,                :unique => true
    add_index :users, :reset_password_token, :unique => true
    # add_index :users, :confirmation_token,   :unique => true
    # add_index :users, :unlock_token,         :unique => true
    # add_index :users, :authentication_token, :unique => true
  end

  def self.down
    drop_table :users
  end
end
</code>```

Now if i do rake db:migrate the users table will be created.

How can i revert this migration, i.e. how can I delete the users table using rake again ?

答:
For rails 5 we can use rails command instead of rake

```<code>rails db:migrate:down VERSION=<version>
</code>```

example

rails db:migrate:down VERSION=20170330090327

Body:
After installing devise MODEL User i got this.

class DeviseCreateUsers < ActiveRecord::Migration
  def self.up
    create_table(:users) do |t|
      t.database_authenticatable :null => false
      t.recoverable
      t.rememberable
      t.trackable

      # t.encryptable
      # t.confirmable
      # t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both
      # t.token_authenticatable

      t.timestamps
    end

    add_index :users, :email,                :unique => true
    add_index :users, :reset_password_token, :unique => true
    # add_index :users, :confirmation_token,   :unique => true
    # add_index :users, :unlock_token,         :unique => true
    # add_index :users, :authentication_token, :unique => true
  end

  def self.down
    drop_table :users
  end
end

Now if i do rake db:migrate the users table will be created.

How can i revert this migration, i.e. how can I delete the users table using rake again ?

Body:
For rails 5 we can use rails command instead of rake

rails db:migrate:down VERSION=<version>

example

rails db:migrate:down VERSION=20170330090327


问:
Chrome Driver Error using Selenium: Unable to Discover Open Pages
I'm getting a Chrome Driver related error when running my Selenium tests. The error message is "Unable to Discover Open Pages." The Selenium tests were all running fine until last evening. The problem seemed to begin after a reboot of the server the day before. I cannot reproduce this error on my local box. Running the Selenium tests from the command line on the server does open the Chrome Browser but results in the same error. Any ideas?

Line that is failing:

```<code>chromeDriver = new OpenQA.Selenium.Chrome.ChromeDriver(externalDriverPath);
</code>```

Error message and stacktrace:

unable to discover open pages   (Driver info:
  chromedriver=2.1,platform=Windows NT 6.1 SP1 x86_64)   at
  OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response
  errorResponse)    at
  OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String
  driverCommandToExecute, Dictionary`2 parameters)    at
  OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities
  desiredCapabilities)    at
  OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor
  commandExecutor, ICapabilities desiredCapabilities)    at
  OpenQA.Selenium.Chrome.ChromeDriver..ctor(String
  chromeDriverDirectory, ChromeOptions options)    at
  OpenQA.Selenium.Chrome.ChromeDriver..ctor(String
  chromeDriverDirectory)    at SeleniumTests.BaseTest.SetupBrowsers()

When creating an instance of the ChromeDriver, a console window appears.  The server with the error seems to refer to things NOT IMPLEMENTED.

ChomeDriver Output From the Server with the Error:

Started ChromeDriver (v2.1) on port 2984
  [4700:4292:0108/111503:ERROR:gpu_info_collector_win.cc(102)] Can't
  retrieve a va lid WinSAT assessment.
  [4700:4292:0108/111503:ERROR:chrome_views_delegate.cc(176)] NOT
  IMPLEMENTED
  [4700:4292:0108/111503:ERROR:desktop_root_window_host_win.cc(746)] NOT
  IMPLEMENT ED [0108/111504:ERROR:gl_surface_egl.cc(132)] eglInitialize
  failed with error UNKNO WN [0108/111504:ERROR:gl_surface_win.cc(97)]
  GLSurfaceEGL::InitializeOneOff failed.

ChomeDriver Output From My PC which works fine:

Started ChromeDriver (v2.1) on port 18786
  [884540:883760:0108/114010:ERROR:gpu_info_collector_win.cc(102)] Can't
  retrieve a valid WinSAT assessment.
  [884992:884996:0108/114010:ERROR:base_feature_provider.cc(122)]
  manifestTypes: A llowing web_page contexts requires supplying a value
  for matches.
  [885232:885236:0108/114011:ERROR:base_feature_provider.cc(122)]
  manifestTypes: A llowing web_page contexts requires supplying a value
  for matches.
  [884540:883760:0108/114011:ERROR:base_feature_provider.cc(122)]
  manifestTypes: A llowing web_page contexts requires supplying a value
  for matches. [0108/114011:ERROR:gl_surface_egl.cc(131)] eglInitialize
  failed with error UNKNO WN [0108/114011:ERROR:gl_surface_win.cc(54)]
  GLSurfaceEGL::InitializeOneOff failed.

答: For some reason the Chrome driver cannot interpret https traffic. If you change your link to http it will work nicely.</p>

Body:
I'm getting a Chrome Driver related error when running my Selenium tests. The error message is "Unable to Discover Open Pages." The Selenium tests were all running fine until last evening. The problem seemed to begin after a reboot of the server the day before. I cannot reproduce this error on my local box. Running the Selenium tests from the command line on the server does open the Chrome Browser but results in the same error. Any ideas?

Line that is failing:

chromeDriver = new OpenQA.Selenium.Chrome.ChromeDriver(externalDriverPath);

Error message and stacktrace:

unable to discover open pages   (Driver info:
  chromedriver=2.1,platform=Windows NT 6.1 SP1 x86_64)   at
  OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response
  errorResponse)    at
  OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String
  driverCommandToExecute, Dictionary`2 parameters)    at
  OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities
  desiredCapabilities)    at
  OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor
  commandExecutor, ICapabilities desiredCapabilities)    at
  OpenQA.Selenium.Chrome.ChromeDriver..ctor(String
  chromeDriverDirectory, ChromeOptions options)    at
  OpenQA.Selenium.Chrome.ChromeDriver..ctor(String
  chromeDriverDirectory)    at SeleniumTests.BaseTest.SetupBrowsers()

When creating an instance of the ChromeDriver, a console window appears.  The server with the error seems to refer to things NOT IMPLEMENTED.

ChomeDriver Output From the Server with the Error:

Started ChromeDriver (v2.1) on port 2984
  [4700:4292:0108/111503:ERROR:gpu_info_collector_win.cc(102)] Can't
  retrieve a va lid WinSAT assessment.
  [4700:4292:0108/111503:ERROR:chrome_views_delegate.cc(176)] NOT
  IMPLEMENTED
  [4700:4292:0108/111503:ERROR:desktop_root_window_host_win.cc(746)] NOT
  IMPLEMENT ED [0108/111504:ERROR:gl_surface_egl.cc(132)] eglInitialize
  failed with error UNKNO WN [0108/111504:ERROR:gl_surface_win.cc(97)]
  GLSurfaceEGL::InitializeOneOff failed.

ChomeDriver Output From My PC which works fine:

Started ChromeDriver (v2.1) on port 18786
  [884540:883760:0108/114010:ERROR:gpu_info_collector_win.cc(102)] Can't
  retrieve a valid WinSAT assessment.
  [884992:884996:0108/114010:ERROR:base_feature_provider.cc(122)]
  manifestTypes: A llowing web_page contexts requires supplying a value
  for matches.
  [885232:885236:0108/114011:ERROR:base_feature_provider.cc(122)]
  manifestTypes: A llowing web_page contexts requires supplying a value
  for matches.
  [884540:883760:0108/114011:ERROR:base_feature_provider.cc(122)]
  manifestTypes: A llowing web_page contexts requires supplying a value
  for matches. [0108/114011:ERROR:gl_surface_egl.cc(131)] eglInitialize
  failed with error UNKNO WN [0108/114011:ERROR:gl_surface_win.cc(54)]
  GLSurfaceEGL::InitializeOneOff failed.

ContentLicense: CC BY-SA 4.0


问:
jQuery trigger("click") not working
Can someone please explain what is wrong with the pasted code. It shows alert on hover but does not perform click event like I expect, and click does not work on either  tag or <select> tag. My purpose is to expand the select element on hover by triggering click event

```<code><!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>

<body>
    <a id="linkElement" href="www.google.co.uk">click</a>

    <select name="cars" id="selectElemet">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>

    <script>
        $(document).ready(function () {
            $("#selectElement").mouseover(function () {
                $("#selectElement").trigger("click");
            });

            $("#linkElement").mouseover(function () {
                alert('here');
                $("#linkElement").trigger("click");
            });
        });
    </script>
</body>

</html>
</code>```

答:
Try this,</p>

```<code>$('#selectElement').on('change', function() {
});
</code>```

Title: jQuery trigger("click") not working

Body:
Can someone please explain what is wrong with the pasted code. It shows alert on hover but does not perform click event like I expect, and click does not work on either  tag or <select> tag. My purpose is to expand the select element on hover by triggering click event

<!DOCTYPE html>

    click

    <select name="cars" id="selectElemet">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>

Body:
Try this,

$('#selectElement').on('change', function() {
});


问:
Google Maps v3 - using accented characters in marker titles
I'm building a Google Maps implementation for a Swedish company, so the language has lots of uses of ä, å, and ö. I have no problems getting the special characters to display correctly (the site charset is UTF-8) except in the "title" attributes for each map marker. My code for the markers is (you can ignore everything in square brackets):

```<code>var marker = new google.maps.Marker({
    position: [coordinates],
    map: [map container div],
    icon: [icon image],
    title: "Läs mer om "+[text from JSON]  //THIS IS WHERE THE PROBLEM IS
});
</code>```

When I hover over the marker on the map, the tooltip comes up as "L�s mer om...". If I change the "ä" to ä in the Javascript, the tooltip displays "Läs mer om..." instead.

The kicker is that using special characters anywhere else in the site, either directly in raw HTML or generated text placed by CMS or what-have-you works just fine. It's only in the Google Maps implementation that it's cracking.

Again, given that the site is entirely in Swedish, this could be a fairly significant issue. Any bright ideas from SO resident geniuses?

答:
I had give it a try and it worked here ,

if you need to test it so fast try
console.log("L\u00e4s mer om") or alert("L\u00e4s mer om")  it would output
 "Läs mer om "

Source : http://www.ietf.org/rfc/rfc4627.txt

```<code>2.5.  Strings
   The representation of strings is similar to conventions used in the C
   family of programming languages.  A string begins and ends with
   quotation marks.  All Unicode characters may be placed within the
   quotation marks except for the characters that must be escaped:
   quotation mark, reverse solidus, and the control characters (U+0000
   through U+001F).

   Any character may be escaped.  If the character is in the Basic
   Multilingual Plane (U+0000 through U+FFFF), then it may be
   represented as a six-character sequence: a reverse solidus, followed
   by the lowercase letter u, followed by four hexadecimal digits that
   encode the character's code point.  The hexadecimal letters A though
   F can be upper or lowercase.  So, for example, a string containing
   only a single reverse solidus character may be represented as
   "\u005C".

   Alternatively, there are two-character sequence escape
   representations of some popular characters.  So, for example, a
   string containing only a single reverse solidus character may be
   represented more compactly as "\\".

   To escape an extended character that is not in the Basic Multilingual
   Plane, the character is represented as a twelve-character sequence,
   encoding the UTF-16 surrogate pair.  So, for example, a string
   containing only the G clef character (U+1D11E) may be represented as
   "\uD834\uDD1E".
</code>```

explanation :

since the marker is an JS object , so it should follow the upper listed rules

```<code>{
    position: [coordinates],
    map: [map container div],
    icon: [icon image],
    title: "Läs mer om "+[text from JSON]  //THIS IS WHERE THE PROBLEM IS
}
</code>```

okay then what to do ???
use <?php echo json_encode("Läs mer om ");  ?>  or what ever your serverside language is

and append the value to your JSON object or write it manually and  Go on !!

ContentLicense: CC BY-SA 2.5

Body:
I'm building a Google Maps implementation for a Swedish company, so the language has lots of uses of ä, å, and ö. I have no problems getting the special characters to display correctly (the site charset is UTF-8) except in the "title" attributes for each map marker. My code for the markers is (you can ignore everything in square brackets):

var marker = new google.maps.Marker({
    position: [coordinates],
    map: [map container div],
    icon: [icon image],
    title: "Läs mer om "+[text from JSON]  //THIS IS WHERE THE PROBLEM IS
});

When I hover over the marker on the map, the tooltip comes up as "L�s mer om...". If I change the "ä" to ä in the Javascript, the tooltip displays "Läs mer om..." instead.

The kicker is that using special characters anywhere else in the site, either directly in raw HTML or generated text placed by CMS or what-have-you works just fine. It's only in the Google Maps implementation that it's cracking.

Again, given that the site is entirely in Swedish, this could be a fairly significant issue. Any bright ideas from SO resident geniuses?

Body:
I had give it a try and it worked here ,

if you need to test it so fast try
console.log("L\u00e4s mer om") or alert("L\u00e4s mer om")  it would output
 "Läs mer om "

Source : http://www.ietf.org/rfc/rfc4627.txt

2.5.  Strings
   The representation of strings is similar to conventions used in the C
   family of programming languages.  A string begins and ends with
   quotation marks.  All Unicode characters may be placed within the
   quotation marks except for the characters that must be escaped:
   quotation mark, reverse solidus, and the control characters (U+0000
   through U+001F).

   Any character may be escaped.  If the character is in the Basic
   Multilingual Plane (U+0000 through U+FFFF), then it may be
   represented as a six-character sequence: a reverse solidus, followed
   by the lowercase letter u, followed by four hexadecimal digits that
   encode the character's code point.  The hexadecimal letters A though
   F can be upper or lowercase.  So, for example, a string containing
   only a single reverse solidus character may be represented as
   "\u005C".

   Alternatively, there are two-character sequence escape
   representations of some popular characters.  So, for example, a
   string containing only a single reverse solidus character may be
   represented more compactly as "\\".

   To escape an extended character that is not in the Basic Multilingual
   Plane, the character is represented as a twelve-character sequence,
   encoding the UTF-16 surrogate pair.  So, for example, a string
   containing only the G clef character (U+1D11E) may be represented as
   "\uD834\uDD1E".

explanation :

since the marker is an JS object , so it should follow the upper listed rules

{
    position: [coordinates],
    map: [map container div],
    icon: [icon image],
    title: "Läs mer om "+[text from JSON]  //THIS IS WHERE THE PROBLEM IS
}

okay then what to do ???
use <?php echo json_encode("Läs mer om ");  ?>  or what ever your serverside language is

and append the value to your JSON object or write it manually and  Go on !!


问:
How can I get kermit script to accept arguments and connect to serial device
I wrote the following in a kermit script to connect to my serial device:

```<code>#!/usr/bin/env kermit
set port /dev/ttyUSB8
set speed 115200
set carrier-watch off
set flow-control none
set prefixing all
set input echo on
</code>```

It does the job pretty well. Now, I want to make this a generic script and would like to take the input from the user which port he wants to connect. So, I thought taking input as a commandline argument is the best way to do. And I modified the above in the following way:

```<code>#!/usr/bin/env kermit
port_num="/dev/ttyUSB"+$1
set port port_num
set speed 115200
set carrier-watch off
set flow-control none
set prefixing all
set input echo on
</code>```

But, I get the following error:

```<code>user4@user-pc-4:~/Scripts$ ./test.script 8
?Not a command or macro name: "port_num="/dev/ttyUSB$1""
File: /home/Scripts/test.script, Line: 2
port_num
?SET SPEED has no effect without prior SET LINE
"8" - invalid command-line option, type "kermit -h" for help
</code>```

I tried replacing

```<code>port_num="/dev/ttyUSB"+$1
</code>```

with

```<code>port_num="/dev/ttyUSB$1"
</code>```

as well.

There is an obvious flaw in my second script. How can I get the script to accept the user input and connect to the serial port using kermit?

答:
Don't need the "+" sign. Just say</p>

```<code>port_num="/dev/ttyUSB$1"
</code>```

Body:
I wrote the following in a kermit script to connect to my serial device:

#!/usr/bin/env kermit
set port /dev/ttyUSB8
set speed 115200
set carrier-watch off
set flow-control none
set prefixing all
set input echo on

It does the job pretty well. Now, I want to make this a generic script and would like to take the input from the user which port he wants to connect. So, I thought taking input as a commandline argument is the best way to do. And I modified the above in the following way:

#!/usr/bin/env kermit
port_num="/dev/ttyUSB"+$1
set port port_num
set speed 115200
set carrier-watch off
set flow-control none
set prefixing all
set input echo on

But, I get the following error:

user4@user-pc-4:~/Scripts$ ./test.script 8
?Not a command or macro name: "port_num="/dev/ttyUSB$1""
File: /home/Scripts/test.script, Line: 2
port_num
?SET SPEED has no effect without prior SET LINE
"8" - invalid command-line option, type "kermit -h" for help

I tried replacing

port_num="/dev/ttyUSB"+$1

with

port_num="/dev/ttyUSB$1"

as well.

There is an obvious flaw in my second script. How can I get the script to accept the user input and connect to the serial port using kermit?

Body:
Don't need the "+" sign. Just say

port_num="/dev/ttyUSB$1"


问:
Resize image in Laravel 5.2
Can anyone help me how to implement resizing image in Laravel?

I have this code only:

```<code>if($request->hasFile('image')){
    if (Input::file('image')->isValid()) {
        $file = Input::file('image');
        $destination = base_path() . '/public/images/ServiceImages';
        $extension = Input::file('image')->getClientOriginalExtension();
        $fileName = rand(111,99999).'.'.$extension;

        if(!empty($data['Image'])){
            unlink($destination.$data['Image']);
        }

        $file->move($destination, $fileName);
        $service->image=$fileName;
    }
}
</code>```

答:
Laravel does not have a default resize of image. But most Laravel developers use 'Image intervention' in handling the image. It is easy to use.

To install (Image intervention):

STEP 1 Run

```<code>composer require intervention/image
</code>```

STEP 2 On your config/app.php:

In the $providers array, add the following:

```<code>Intervention\Image\ImageServiceProvider::class
</code>```

In the $aliases array,add the following:

```<code>'Image' => Intervention\Image\Facades\Image::class
</code>```

If you have problems your GD library is missing, install it

PHP5: sudo apt-get install php5-gd

PHP7: sudo apt-get install php7.0-gd

To use on your controller.

STEP 3

On top of your controller

use Intervention\Image\ImageManagerStatic as Image;

STEP 4

On your method (there are several ways but this will give you an idea)

```<code>if($request->hasFile('image')) {

    $image       = $request->file('image');
    $filename    = $image->getClientOriginalName();

    $image_resize = Image::make($image->getRealPath());
    $image_resize->resize(300, 300);
    $image_resize->save(public_path('images/ServiceImages/' .$filename));

}
</code>```

Reference here.

Title: Resize image in Laravel 5.2

Body:
Can anyone help me how to implement resizing image in Laravel?

I have this code only:

if($request->hasFile('image')){
    if (Input::file('image')->isValid()) {
        $file = Input::file('image');
        $destination = base_path() . '/public/images/ServiceImages';
        $extension = Input::file('image')->getClientOriginalExtension();
        $fileName = rand(111,99999).'.'.$extension;

        if(!empty($data['Image'])){
            unlink($destination.$data['Image']);
        }

        $file->move($destination, $fileName);
        $service->image=$fileName;
    }
}

Body:
Laravel does not have a default resize of image. But most Laravel developers use 'Image intervention' in handling the image. It is easy to use.

To install (Image intervention):

STEP 1 Run

composer require intervention/image

STEP 2 On your config/app.php:

In the $providers array, add the following:

Intervention\Image\ImageServiceProvider::class

In the $aliases array,add the following:

'Image' => Intervention\Image\Facades\Image::class

If you have problems your GD library is missing, install it

PHP5: sudo apt-get install php5-gd

PHP7: sudo apt-get install php7.0-gd

To use on your controller.

STEP 3

On top of your controller

use Intervention\Image\ImageManagerStatic as Image;

STEP 4

On your method (there are several ways but this will give you an idea)

if($request->hasFile('image')) {

    $image       = $request->file('image');
    $filename    = $image->getClientOriginalName();

    $image_resize = Image::make($image->getRealPath());
    $image_resize->resize(300, 300);
    $image_resize->save(public_path('images/ServiceImages/' .$filename));

}

Reference here.


问:
How to write to local JSON file using jQuery
Please note; everything I'm doing here is local.
I've been looking for and testing ways to write to a JSON from a JS file using jQuery. I've found ways that use PHP, but I'm not fluent in PHP and would rather stay away from it for now.

Is there any function in jQuery, or JavaScript, that can let me easily write to JSON files?

Thanks in advance,
Benjamin.

答: If you are going with browser then it will not work in any way. If you are using nodejs on local system then you can do it with nodejs. With only remote side script it is not possible. With javascript running in browser you can only perform browser based task. </p>


问:
In pagerSlidindTabStrip text display incomplete for Moto G 4+ android 7
In my project I have used PagerSlidingTabStrip library .now in all other device it display proper text in PagerSlidingTabStrip . but in Moto G 4+ it displays incomplete text in PagerSlidingTabStrip. like it display only "Entertain” instead "Entertainment” . what need to change, plz help me. Thanks In advance.

```<code> <com.astuetz.PagerSlidingTabStrip
        android:id="@+id/VideoTabs"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/toolbar_color"
        android:paddingLeft="11dp"
        android:layout_marginRight="0dp"
        android:paddingRight="0dp"
        android:textSize="15sp"
        app:pstsActivateTextColor="@color/white"
        app:pstsDeactivateTextColor="@color/white"
        app:pstsDividerColor="@color/toolbar_color"
        app:pstsIndicatorHeight="0dp"
        app:pstsTabBackground="@color/toolbar_color"
        app:pstsTextAllCaps="false"
        app:pstsUnderlineHeight="0dp"
        android:layout_toLeftOf="@+id/ivNextFragment"/>
</code>```

In java file

```<code>   public void init(View rootview) {
      tabs = (PagerSlidingTabStrip) rootview.findViewById(R.id.VideoTabs);
      mTabsLinearLayout = ((LinearLayout) tabs.getChildAt(0));

      pager = (ViewPager) rootview.findViewById(R.id.viewpager);
     //        tabs.setShouldExpand(true);
     pager.setOffscreenPageLimit(listPublisherName.size());

     setupViewPager(pager);
     tabs.setViewPager(pager);
     tabs.setForegroundGravity(Gravity.CENTER);
     pager.setCurrentItem(0);
     tabs.setTabSwitch(true);

     TextView tv = (TextView) mTabsLinearLayout.getChildAt(pos);
     tv.setTextSize(16);
     tv.setTypeface(null, Typeface.BOLD);
   }
</code>```

screen is like this right now

答:
By doing some changes in code, it will work right now perfect. may be it help some one in future so post here changes.I made changes in xml file as below.

```<code> app:pstsShouldExpand="false"
</code>```

It will work fine .

Body:
In my project I have used PagerSlidingTabStrip library .now in all other device it display proper text in PagerSlidingTabStrip . but in Moto G 4+ it displays incomplete text in PagerSlidingTabStrip. like it display only "Entertain” instead "Entertainment” . what need to change, plz help me. Thanks In advance.

 <com.astuetz.PagerSlidingTabStrip
        android:id="@+id/VideoTabs"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/toolbar_color"
        android:paddingLeft="11dp"
        android:layout_marginRight="0dp"
        android:paddingRight="0dp"
        android:textSize="15sp"
        app:pstsActivateTextColor="@color/white"
        app:pstsDeactivateTextColor="@color/white"
        app:pstsDividerColor="@color/toolbar_color"
        app:pstsIndicatorHeight="0dp"
        app:pstsTabBackground="@color/toolbar_color"
        app:pstsTextAllCaps="false"
        app:pstsUnderlineHeight="0dp"
        android:layout_toLeftOf="@+id/ivNextFragment"/>

In java file

   public void init(View rootview) {
      tabs = (PagerSlidingTabStrip) rootview.findViewById(R.id.VideoTabs);
      mTabsLinearLayout = ((LinearLayout) tabs.getChildAt(0));

      pager = (ViewPager) rootview.findViewById(R.id.viewpager);
     //        tabs.setShouldExpand(true);
     pager.setOffscreenPageLimit(listPublisherName.size());

     setupViewPager(pager);
     tabs.setViewPager(pager);
     tabs.setForegroundGravity(Gravity.CENTER);
     pager.setCurrentItem(0);
     tabs.setTabSwitch(true);

     TextView tv = (TextView) mTabsLinearLayout.getChildAt(pos);
     tv.setTextSize(16);
     tv.setTypeface(null, Typeface.BOLD);
   }

screen is like this right now

Body:
By doing some changes in code, it will work right now perfect. may be it help some one in future so post here changes.I made changes in xml file as below.

 app:pstsShouldExpand="false"

It will work fine .


问:
In cmake, how can I always execute a process? (or capture stdout from add_custom_command)
I am using generated files in my cmake project. I have a script that generates source code from some input, and the same script can also validate the input, if given a different command line argument, like this:

generate_code.py --generate

generate_code.py --validate

The --validate mode will print errors to stdout if the input is not valid, and I would like to have those errors visible. My current setup is to run with --validate in an execute_process and with --generate in an add_custom_command. This works, but doesn't print the user-friendly error messages from the --validate mode when the input changes, because the execute_process doesn't run again.

What would be the best way to surface these errors? If I could force execute_process to always run, that would work, or if I could capture stdout when --generate fails and surface that, I could modify the --generate option to print friendly error messages, and then display them. How can I do one or both of those?

答:
Commands in add_custom_target statements are re-run every time the build is executed as long as you pass the ALL argument.  This may be what you are looking for.

Alternatively, you could make the inputs to generate_code.py be dependencies of the custom command (if they aren't already), and have the custom command execute generate_code.py --validate before generate_code.py --generate.  That way it would get revalidated when it needs to be rebuilt, and not at any other time.


问:
Self sign certificate with different server
I have generated a self sign ssl certificate for my server, can I use the same certificate with different server?</p>

答:
Well SSL certificates are usually used to protect domains and not ip addresses. You can try to generate a SSL certificate for an ip address.

You can enter the ip address in the common names field when generating Certificate Signing Request (CSR). But the same SSL certificate may not work on another ip address. A similar issue was discussed on: Is it possible to have SSL certificate for IP address, not domain name?

You can create your own host name and enter it in the hosts file of your operating system. Then you will have to create one self signed SSL certificate for this domain. You can use this SSL certificate on as many servers as you want.

If your server has a public ip address, then you should consider purchasing a domain from a domain provider such as GoDaddy.


问:
Record each character from UITextfield into NSDictionary in IOS
I am using UICollectionview and each cell have UITextfield and i am trying to get complete string from and each textfield and saving into dictionary. i used following code

```<code>  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField.tag==100) {
         [m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByAppendingString:string] forKey:@"image_0001"];
    }
    if (textField.tag==101) {
        [m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByAppendingString:string] forKey:@"image_0002"];
    }
    }
</code>```

I tried:

Using above code I able to set string correctly but, if i delete character the above method not called and dictionary not updated.

TextFieldDidBeginEditing call initially and able to record 1 character only. also tried other delegate methods

Expected Output:

```<code>{
image_0001: All Character,
image_0002: A
}
</code>```

Any help will up-voted. thanks.

答:
textField shouldChangeCharactersInRange gets called before text field actually changes its text, if you need to get the update value then do like

```<code>- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if (textField.tag==100) {
         [m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByReplacingCharactersInRange:range withString:string] forKey:@"image_0001"];
    }
    else if (textField.tag==101) {
    [m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByReplacingCharactersInRange:range withString:string] forKey:@"image_0002"];
}
}
</code>```

updated answer

```<code> - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

        NSString * currentStr = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if (textField.tag==100) {
         [m11ThumbImage_MutCaptionDictionary setValue:currentStr forKey:@"image_0001"];
    }
    else if (textField.tag==101) {
    [m11ThumbImage_MutCaptionDictionary setValue:currentStr forKey:@"image_0002"];
     }
  return YES;
}
</code>```

alternate way

add in your viewdidload  To get EditingChanged  textfield event, I suggested add selector as

```<code>[textField addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
</code>```

As textfield value changed, the changed value you will get from this textChanged: selector.

```<code> -(void)textChanged:(UITextField *)textField
   {
    NSLog(@"textfield data %@ ",textField.text);
    if (textField.tag==100) {
     [m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByAppendingString:string] forKey:@"image_0001"];
   }
 else if (textField.tag==101) {
    [m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByAppendingString:string] forKey:@"image_0002"];
}
}
</code>```

Body:
I am using UICollectionview and each cell have UITextfield and i am trying to get complete string from and each textfield and saving into dictionary. i used following code

  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField.tag==100) {
         [m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByAppendingString:string] forKey:@"image_0001"];
    }
    if (textField.tag==101) {
        [m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByAppendingString:string] forKey:@"image_0002"];
    }
    }

I tried:

Using above code I able to set string correctly but, if i delete character the above method not called and dictionary not updated.

TextFieldDidBeginEditing call initially and able to record 1 character only. also tried other delegate methods

Expected Output:

{
image_0001: All Character,
image_0002: A
}

Any help will up-voted. thanks.

Body:
textField shouldChangeCharactersInRange gets called before text field actually changes its text, if you need to get the update value then do like

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if (textField.tag==100) {
         [m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByReplacingCharactersInRange:range withString:string] forKey:@"image_0001"];
    }
    else if (textField.tag==101) {
    [m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByReplacingCharactersInRange:range withString:string] forKey:@"image_0002"];
}
}

updated answer

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

        NSString * currentStr = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if (textField.tag==100) {
         [m11ThumbImage_MutCaptionDictionary setValue:currentStr forKey:@"image_0001"];
    }
    else if (textField.tag==101) {
    [m11ThumbImage_MutCaptionDictionary setValue:currentStr forKey:@"image_0002"];
     }
  return YES;
}

alternate way

add in your viewdidload  To get EditingChanged  textfield event, I suggested add selector as

[textField addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];

As textfield value changed, the changed value you will get from this textChanged: selector.

 -(void)textChanged:(UITextField *)textField
   {
    NSLog(@"textfield data %@ ",textField.text);
    if (textField.tag==100) {
     [m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByAppendingString:string] forKey:@"image_0001"];
   }
 else if (textField.tag==101) {
    [m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByAppendingString:string] forKey:@"image_0002"];
}
}


问:
How to tackle this session problem in ASP.NET,VB.NET?
How to tackle this session problem in ASP.NET,VB.NET?

The following requirement are there:

When the authorized user logs into the system that user is not allowed to login from another computer or in different browser other than that user is using right at this time.

The remedy we applied was: We have kept "Is_Loggedin" as a column with data type "bit" in a mst_vendor as a table name. When a user logs in we set the flag, Is_Loggedin, to "1" and each time when someone tries to log in using this account, the system is showing the error "The user is already logged in.".

When the user logs out it turns to "0" as the logout procedure calls as soon as the user clicks the log out button.

Problem scenario:

When the user closes the browser the flag remains the same, that is, "1".

When power gets off, it remains the same as "1".

If the session timeouts after a predefined value it remains the same.

There may be different scenarios other than this.

Is there any way so that we can store this internal flagging for the user's login status using the application object?

It may improve efficiency of the system and also eliminates the above problematic scenarios.

答: Yeah, a script would be a good idea. Just set the session timeout to be 5 minutes instead of 20 and then write a method into session.end in the global.asax file that updates the database accordingly.


问:
difference size of list make Dataframe in pandas and how to make dummies
```<code>  index            0          1         2         3         4        5  \
0         0       Action  Adventure   Fantasy    Sci-Fi       NaN      NaN
1         1       Action  Adventure   Fantasy       NaN       NaN      NaN
2         2       Action  Adventure  Thriller       NaN       NaN      NaN
3         3       Action   Thriller       NaN       NaN       NaN      NaN
4         4  Documentary        NaN       NaN       NaN       NaN      NaN
5         5       Action  Adventure    Sci-Fi       NaN       NaN      NaN
6         6       Action  Adventure   Romance       NaN       NaN      NaN
7         7    Adventure  Animation    Comedy    Family   Fantasy  Musical
8         8       Action  Adventure    Sci-Fi       NaN       NaN      NaN
9         9    Adventure     Family   Fantasy   Mystery       NaN      NaN
</code>```

i have data like this...

but i have no idea to make dummies with difference size of data frame data in pandas python....

```<code>Action  Adventure   Fantasy Sci-Fi  Thriller    Ducumentary Romance Animation   Comedy  family  Fantasy Musical Mystery
0   1   1   1   1   0   0   0   0   0   0   0   0   0
1   1   1   1   0   0   0   0   0   0   0   0   0   0
2   1   1   0   0   1   0   0   0   0   0   0   0   0
3   1   0   0   0   1   0   0   0   0   0   0   0   0
4   0   0   0   0   0   1   0   0   0   0   0   0   0
5   1   1   0   1   0   0   0   0   0   0   0   0   0
6   1   1   0   0   0   0   1   0   0   0   0   0   0
7   0   1   0   0   0   0   0   1   1   1   1   1   0
8   1   1   0   1   0   0   0   0   0   0   0   0   0
9   0   1   0   0   0   0   0   0   0   1   1   0   1
</code>```

like this....

答:
House keeping:

make sure that pesky index column is out of the way

```<code>df = df.drop('index', 1)
</code>```

using pd.values_counts

```<code>df.stack().groupby(level=0).value_counts().unstack(fill_value=0)
</code>```

Or equivalently

```<code>df.apply(pd.value_counts, 1).fillna(0).astype(int)
</code>```

Body:
  index            0          1         2         3         4        5  \
0         0       Action  Adventure   Fantasy    Sci-Fi       NaN      NaN
1         1       Action  Adventure   Fantasy       NaN       NaN      NaN
2         2       Action  Adventure  Thriller       NaN       NaN      NaN
3         3       Action   Thriller       NaN       NaN       NaN      NaN
4         4  Documentary        NaN       NaN       NaN       NaN      NaN
5         5       Action  Adventure    Sci-Fi       NaN       NaN      NaN
6         6       Action  Adventure   Romance       NaN       NaN      NaN
7         7    Adventure  Animation    Comedy    Family   Fantasy  Musical
8         8       Action  Adventure    Sci-Fi       NaN       NaN      NaN
9         9    Adventure     Family   Fantasy   Mystery       NaN      NaN

i have data like this...

but i have no idea to make dummies with difference size of data frame data in pandas python....

Action  Adventure   Fantasy Sci-Fi  Thriller    Ducumentary Romance Animation   Comedy  family  Fantasy Musical Mystery
0   1   1   1   1   0   0   0   0   0   0   0   0   0
1   1   1   1   0   0   0   0   0   0   0   0   0   0
2   1   1   0   0   1   0   0   0   0   0   0   0   0
3   1   0   0   0   1   0   0   0   0   0   0   0   0
4   0   0   0   0   0   1   0   0   0   0   0   0   0
5   1   1   0   1   0   0   0   0   0   0   0   0   0
6   1   1   0   0   0   0   1   0   0   0   0   0   0
7   0   1   0   0   0   0   0   1   1   1   1   1   0
8   1   1   0   1   0   0   0   0   0   0   0   0   0
9   0   1   0   0   0   0   0   0   0   1   1   0   1

like this....

Body:
House keeping:

make sure that pesky index column is out of the way

df = df.drop('index', 1)

using pd.values_counts

df.stack().groupby(level=0).value_counts().unstack(fill_value=0)

Or equivalently

df.apply(pd.value_counts, 1).fillna(0).astype(int)


问:
controller not sending data back to ajax request codeigniter
I have developed a login system using ajax the problem is when i send the ajax request everything is working and validating fine i just need to pass data back to my ajax request I am using echo json_encode("true"); but somehow it is just echoing the value true in the controller and not going back in the view!

HTML

```<code>  <form onsubmit="return validate()" method="post" action="<?php echo base_url(); ?>admin/admin_login">
        <input class="md-input" placeholder="username" type="text" name = 'login_username'  id = 'login_username' />
        <input class="md-input" placeholder="password" type="password" name= 'login_password'  id= 'login_password' />
        <button type='submit' class="btn btn-primary btn-block btn-large">Login</button>
    </form>
</code>```

AJAX

```<code><script>

    function validate(){
        if(!$("#login_username").val()){
            alert("username is required");
            return false;
        }
        if(!$("#login_password").val()){
            alert("Password is required");
            return false;
        }
        return true;
        var data={
            "login_username" : $("#login_username").val(),
            "login_password" : $("#login_password").val()
        };
        $.ajax({
            type: 'post',
            url: '<?=base_url()?>Admin/admin_login',
            dataType: 'json',
            data:data,
            success: function (data) {
                if(data=="true"){
                    alert("ok");
                }
                else
                {
                    alert("not ok");
                }
            }
        });
    }
</script>
</code>```

admin_login controller

```<code> public function admin_login(){
        $data = $this->input->post();
        $status=$this->admin_validate->validate($data);
        if($status){
            $session=array(
                "admin"=>$this->input->post("login_username"),
            );

            $this->session->set_userdata($session);
            //redirect("Admin/contact");
            header('Content-Type: application/json');
            echo json_encode("true");
        }
        else
        {
            header('Content-Type: application/json');
            echo json_encode("false");
            //redirect("Admin");
        }
    }
</code>```

答:
you are returning true in the script so the form is get submitted. no ajax call occurs.

```<code><script>

    function validate(){
        if(!$("#login_username").val()){
            alert("username is required");
            return false;
        }
        if(!$("#login_password").val()){
            alert("Password is required");
            return false;
        }
        return true;  // HERE THE ISSUE //
        var data={
            "login_username" : $("#login_username").val(),
            "login_password" : $("#login_password").val()
        };
        $.ajax({
            type: 'post',
            url: '<?=base_url()?>Admin/admin_login',
            dataType: 'json',
            data:data,
            success: function (data) {
                if(data=="true"){
                    alert("ok");
                }
                else
                {
                    alert("not ok");
                }
            }
        });
}
</code>```

Body:
I have developed a login system using ajax the problem is when i send the ajax request everything is working and validating fine i just need to pass data back to my ajax request I am using echo json_encode("true"); but somehow it is just echoing the value true in the controller and not going back in the view!

HTML

  <form onsubmit="return validate()" method="post" action="<?php echo base_url(); ?>admin/admin_login">
        <input class="md-input" placeholder="username" type="text" name = 'login_username'  id = 'login_username' />
        <input class="md-input" placeholder="password" type="password" name= 'login_password'  id= 'login_password' />
        <button type='submit' class="btn btn-primary btn-block btn-large">Login</button>
    </form>

AJAX

admin_login controller

 public function admin_login(){
        $data = $this->input->post();
        $status=$this->admin_validate->validate($data);
        if($status){
            $session=array(
                "admin"=>$this->input->post("login_username"),
            );

            $this->session->set_userdata($session);
            //redirect("Admin/contact");
            header('Content-Type: application/json');
            echo json_encode("true");
        }
        else
        {
            header('Content-Type: application/json');
            echo json_encode("false");
            //redirect("Admin");
        }
    }

Body:
you are returning true in the script so the form is get submitted. no ajax call occurs.

<script>

    function validate(){
        if(!$("#login_username").val()){
            alert("username is required");
            return false;
        }
        if(!$("#login_password").val()){
            alert("Password is required");
            return false;
        }
        return true;  // HERE THE ISSUE //
        var data={
            "login_username" : $("#login_username").val(),
            "login_password" : $("#login_password").val()
        };
        $.ajax({
            type: 'post',
            url: '<?=base_url()?>Admin/admin_login',
            dataType: 'json',
            data:data,
            success: function (data) {
                if(data=="true"){
                    alert("ok");
                }
                else
                {
                    alert("not ok");
                }
            }
        });
}


问:
I got Initialization error in Cucumber with maven and selenium
Test Runner

import org.junit.runner.RunWith;

```<code>import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features="features",glue={"stepDefinition"})
public class TestRunner {

}
</code>```

MyApplication.feature

```<code>Feature: Test test smoke scenario

  Scenario Outline: Test  login with valid credentials
    Given open fireFox and start application
    When I enter valid "username" and valid "password"
    Then User should be able to login successfully

Examples:
      | username   | password          |
      | 9739817000 | mnbvcxz  |
      | 9739817001 | mnbvcxz1  |
      | 9739817002 | mnbvcxz2  |
</code>```

Maven POM

```<code><groupId>demo</groupId>
  <artifactId>prac</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>prac</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.1</version>
    </dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>1.2.5</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>1.2.4</version>
</dependency>
</dependencies>
</project>
</code>```

Smoke.java

```<code>public class Smoke {
    WebDriver driver;
    @Given("^open fireFox and start application$")
    public void open_fireFox_and_start_application() throws Throwable {
        driver=new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://testweb.com");

    }

    @When("^I click on Login$")
    public void I_click_on_Login() throws Throwable {
        driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();

    }

    @When("^enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
    public void enter_valid_and_valid(String un, String pwd) throws Throwable {
        driver.findElement(By.id("Username")).sendKeys(un);
        driver.findElement(By.id("Password")).sendKeys(pwd);

    }

    @Then("^Click on Login$")
    public void Click_on_Login() throws Throwable {
        driver.findElement(By.id("loginUser")).click();

    }
    @Then("^User should be able to login successfully$")
    public void User_should_be_able_to_login_successfully() throws Throwable {

    }
</code>```

These above are the test runner,feature file,Smoke test class.
Its throwing an Initilization error.I am new to Cucumber and recheck all the maven dependency ,its correct only.But even also its giving error

enter image description here

答:
As, you have not specified any sets of data for your feature file, you do not need to use Scenario Outline. You can use it when you need to execute same scenario with different sets of data. Hence, remove Scenario Outline from your feature file (shown below the updated feature file) and retry:

```<code>Feature: Test Milacron smoke scenario

Scenario: Test  login with valid credentials
Given open fireFox and start application
When I enter valid "username" and valid "password"
Then User should be able to login successfully
</code>```

Please refer to link for more details about writing feature files. Let me know, if you have any further queries.

Body:
Test Runner

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features="features",glue={"stepDefinition"})
public class TestRunner {

}

MyApplication.feature

Feature: Test test smoke scenario

  Scenario Outline: Test  login with valid credentials
    Given open fireFox and start application
    When I enter valid "username" and valid "password"
    Then User should be able to login successfully

Examples:
      | username   | password          |
      | 9739817000 | mnbvcxz  |
      | 9739817001 | mnbvcxz1  |
      | 9739817002 | mnbvcxz2  |

Maven POM

<groupId>demo</groupId>
  <artifactId>prac</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>prac</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.1</version>
    </dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>1.2.5</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>1.2.4</version>
</dependency>
</dependencies>
</project>

Smoke.java

public class Smoke {
    WebDriver driver;
    @Given("^open fireFox and start application$")
    public void open_fireFox_and_start_application() throws Throwable {
        driver=new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://testweb.com");

    }

    @When("^I click on Login$")
    public void I_click_on_Login() throws Throwable {
        driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();

    }

    @When("^enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
    public void enter_valid_and_valid(String un, String pwd) throws Throwable {
        driver.findElement(By.id("Username")).sendKeys(un);
        driver.findElement(By.id("Password")).sendKeys(pwd);

    }

    @Then("^Click on Login$")
    public void Click_on_Login() throws Throwable {
        driver.findElement(By.id("loginUser")).click();

    }
    @Then("^User should be able to login successfully$")
    public void User_should_be_able_to_login_successfully() throws Throwable {

    }

These above are the test runner,feature file,Smoke test class.
Its throwing an Initilization error.I am new to Cucumber and recheck all the maven dependency ,its correct only.But even also its giving error

enter image description here

Body:
As, you have not specified any sets of data for your feature file, you do not need to use Scenario Outline. You can use it when you need to execute same scenario with different sets of data. Hence, remove Scenario Outline from your feature file (shown below the updated feature file) and retry:

Feature: Test Milacron smoke scenario

Scenario: Test  login with valid credentials
Given open fireFox and start application
When I enter valid "username" and valid "password"
Then User should be able to login successfully

Please refer to link for more details about writing feature files. Let me know, if you have any further queries.


问:
how to put pictures in a row bootstrap
I'm trying to get these 3 pictures in a row with no or little spaces in between, but this code is causing them to stack on top of each other.  I also want them to be aligned to the center of the page.</p>

```<code><div class="container">
  <div class="row col-xs-2">
  <img style= "width: 25%; height: 25%" src="https://image.ibb.co/ckA7ka/mr_marbles.png" alt="Mister Marbles head tilt">
</div>
<div class="row col-xs-2">
  <img style= "width: 25%; height: 25%"  src="https://image.ibb.co/bTMKyv/kermit.png" alt="Kermit the Dog">
</div>
<div class="row col-xs-2">
  <img style= "width: 25%; height: 25%" src="https://image.ibb.co/ki8tQa/peach.png" alt="Peach posing magestically">
</div>
</div>
</code>```

答:
your code should be like this..

dont put class row on every col..

```<code><div class="container">
  <div class="row">
    <div class="col-xs-2">
  <img style="width: 25%; height: 25%" src="https://image.ibb.co/ckA7ka/mr_marbles.png" alt="Mister Marbles head tilt">
</div>
<div class="col-xs-2">
  <img style="width: 25%; height: 25%" src="https://image.ibb.co/bTMKyv/kermit.png" alt="Kermit the Dog">
</div>
<div class="col-xs-2">
  <img style="width: 25%; height: 25%" src="https://image.ibb.co/ki8tQa/peach.png" alt="Peach posing magestically">
</div>
  </div>
</div>
</code>```

sample code

Title: how to put pictures in a row bootstrap

Body:
your code should be like this..

dont put class row on every col..

<div class="container">
  <div class="row">
    <div class="col-xs-2">
  <img style="width: 25%; height: 25%" src="https://image.ibb.co/ckA7ka/mr_marbles.png" alt="Mister Marbles head tilt">
</div>
<div class="col-xs-2">
  <img style="width: 25%; height: 25%" src="https://image.ibb.co/bTMKyv/kermit.png" alt="Kermit the Dog">
</div>
<div class="col-xs-2">
  <img style="width: 25%; height: 25%" src="https://image.ibb.co/ki8tQa/peach.png" alt="Peach posing magestically">
</div>
  </div>
</div>

sample code


问:
How to change controller response in filter to make the response structure consistent all over the API's using spring-boot
I have implemented REST API using spring-boot application. All my API's are now returning response in JSON format for each entity. This response was consumed by other server which expects all these response are in same JSON format. For example;

All my responses should be accommodated within the following structure;

```<code>public class ResponseDto {
    private Object data;
    private int statusCode;
    private String error;
    private String message;
}
</code>```

Currently spring-boot returns error responses in a different format. How to achieve this using filter.

Error message format;

```<code>{
   "timestamp" : 1426615606,
   "exception" : "org.springframework.web.bind.MissingServletRequestParameterException",
   "status" : 400,
   "error" : "Bad Request",
   "path" : "/welcome",
   "message" : "Required String parameter 'name' is not present"
}
</code>```

I need both error and successfull response are in same json structure all over my spring-boot application

答:
This can be achieved simply by utilizing a ControllerAdvice and handling all possible exceptions, then returning a response of your own choosing.

```<code>@RestControllerAdvice
class GlobalControllerExceptionHandler {

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Throwable.class)
    public ResponseDto handleThrowable(Throwable throwable) {
        // can get details from throwable parameter
        // build and return your own response for all error cases.
    }

    // also you can add other handle methods and return
    // `ResponseDto` with different values in a similar fashion
    // for example you can have your own exceptions, and you'd like to have different status code for them

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(CustomNotFoundException.class)
    public ResponseDto handleCustomNotFoundException(CustomNotFoundException exception) {
        // can build a "ResponseDto" with 404 status code for custom "not found exception"
    }
}
</code>```

Some great read on controller advice exception handlers

Body:
I have implemented REST API using spring-boot application. All my API's are now returning response in JSON format for each entity. This response was consumed by other server which expects all these response are in same JSON format. For example;

All my responses should be accommodated within the following structure;

public class ResponseDto {
    private Object data;
    private int statusCode;
    private String error;
    private String message;
}

Currently spring-boot returns error responses in a different format. How to achieve this using filter.

Error message format;

{
   "timestamp" : 1426615606,
   "exception" : "org.springframework.web.bind.MissingServletRequestParameterException",
   "status" : 400,
   "error" : "Bad Request",
   "path" : "/welcome",
   "message" : "Required String parameter 'name' is not present"
}

I need both error and successfull response are in same json structure all over my spring-boot application

Body:
This can be achieved simply by utilizing a ControllerAdvice and handling all possible exceptions, then returning a response of your own choosing.

@RestControllerAdvice
class GlobalControllerExceptionHandler {

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Throwable.class)
    public ResponseDto handleThrowable(Throwable throwable) {
        // can get details from throwable parameter
        // build and return your own response for all error cases.
    }

    // also you can add other handle methods and return
    // `ResponseDto` with different values in a similar fashion
    // for example you can have your own exceptions, and you'd like to have different status code for them

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(CustomNotFoundException.class)
    public ResponseDto handleCustomNotFoundException(CustomNotFoundException exception) {
        // can build a "ResponseDto" with 404 status code for custom "not found exception"
    }
}

Some great read on controller advice exception handlers


问:
Picking a dll in a particular path while loading a shared library in Windows
I am using MinGW to create a shared library that is dynamically linked and loaded using the LoadLibrary function. My shared library is dependent on a dll that can be found in two different places on the path. These two are different (two different versions) and at the time of loading the library, it picks the wrong dll. How can I explicitly specify which dll to pick?

To be more specific these are the commands I am using:

Compilation

```<code>g++ -m64 -O3 -c my_file.cpp -o myfile.o
</code>```

Creating shared library

```<code>g++ -m64 -shared myfile.o -o myfile.dll
</code>```

I have tried many things including -L option but have not yet been able to figure out how to do this. I also have searched online for a couple of hours but it turn out to be of no use.

Any help is much appreciated.

Thanks in advance

It turns out that the dll I don't want to load is indeed at "The directory where the executable module for the current process is located." The other dll, with the same name is on the path but not where windows looks first. From what this document says, LoadLibrary will always pick the dll from the directory where the executable module for the current process is located, if the dll exists there, no matter what. Is there a way around this? Moving the dlls is really not an option as this is a third party program that we are building on

答:
The following article gives some guidance for effecting alternate DLL search strategies using the SetDllDirectory and LoadLibraryEx API calls, assuming those are options (you mentioned LoadLibrary is currently used).

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682586(v=vs.85).aspx

Body:
I am using MinGW to create a shared library that is dynamically linked and loaded using the LoadLibrary function. My shared library is dependent on a dll that can be found in two different places on the path. These two are different (two different versions) and at the time of loading the library, it picks the wrong dll. How can I explicitly specify which dll to pick?

To be more specific these are the commands I am using:

Compilation

g++ -m64 -O3 -c my_file.cpp -o myfile.o

Creating shared library

g++ -m64 -shared myfile.o -o myfile.dll

I have tried many things including -L option but have not yet been able to figure out how to do this. I also have searched online for a couple of hours but it turn out to be of no use.

Any help is much appreciated.

Thanks in advance

It turns out that the dll I don't want to load is indeed at "The directory where the executable module for the current process is located." The other dll, with the same name is on the path but not where windows looks first. From what this document says, LoadLibrary will always pick the dll from the directory where the executable module for the current process is located, if the dll exists there, no matter what. Is there a way around this? Moving the dlls is really not an option as this is a third party program that we are building on


问:
Spark Installation Problems
I am following instructions from here:

https://www.datacamp.com/community/tutorials/apache-spark-python#gs.WEktovg

I downloaded and prebuilt version of Spark , untarred it and mv it to /usr/local/spark.

According to this, this is all I should have to do.

Unfortunately, I can run the interactive shell as it cant find the file.

When i run :

```<code>./bin/pyspark
</code>```

I get

```<code>-bash: ./bin/pyspark: No such file or directory.
</code>```

I also notice that installing it this way does not add it to the bin directory.

Is this tutorial wrong or am I missing a trick?

答: Update your working Directory to /usr/local/spark and execute the command. Hopefully this will fix the issue.

Title: Spark Installation Problems

Body:
I am following instructions from here:

https://www.datacamp.com/community/tutorials/apache-spark-python#gs.WEktovg

I downloaded and prebuilt version of Spark , untarred it and mv it to /usr/local/spark.

According to this, this is all I should have to do.

Unfortunately, I can run the interactive shell as it cant find the file.

When i run :

./bin/pyspark

I get

-bash: ./bin/pyspark: No such file or directory.

I also notice that installing it this way does not add it to the bin directory.

Is this tutorial wrong or am I missing a trick?