问:
To find no.of columns in a data set with correlation more than certain percentage in R
I am working on a data set with 48 variables and by seeing the correlation plot in R, most of the variables are highly correlated. I am trying to find the number of variables that are correlated > 70%

My data frame is called diagnosed_data and the code I use is:

```<code>cor_data <- cor(diagnosed_data)
corrplot::corrplot(cor_data, method = "number",
                   title = "correlation plot b/w the attributes")
</code>```

From this plot I can figure out visually how many variables have high correlation, but I would like to find this using code instead.

How can I find those variables? Any help would me much appreciated. Thanks!

答:
Let's use the mtcars dataset, which has 10 variables (instead of your 48 variables).

There are 10(10-1)/2 unique correlation pairs. If you look at the correlation matrix, this corresponds to the elements above the diagonal. By checking whether the correlation is larger than 0.7 (or smaller than -0.7) for those upper-triangular elements, we can see how many unique pairs are heavily correlated:

```<code>cor_mat     <- cor(mtcars)
unique_cors <- cor_mat[upper.tri(cor_mat)]
sum(abs(unique_cors) > 0.7)
# [1] 19
</code>```

And if you want to just get a TRUE or FALSE indication for every pair, you could use:

```<code>abs(cor_mat) > 0.7
       mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
mpg   TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
cyl   TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE
disp  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE
hp    TRUE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE  TRUE
drat FALSE FALSE  TRUE FALSE  TRUE  TRUE FALSE FALSE  TRUE FALSE FALSE
wt    TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE
qsec FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE
vs   FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE
am   FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE  TRUE FALSE
gear FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE
carb FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
</code>```

Body:
I am working on a data set with 48 variables and by seeing the correlation plot in R, most of the variables are highly correlated. I am trying to find the number of variables that are correlated > 70%

My data frame is called diagnosed_data and the code I use is:

cor_data <- cor(diagnosed_data)
corrplot::corrplot(cor_data, method = "number",
                   title = "correlation plot b/w the attributes")

From this plot I can figure out visually how many variables have high correlation, but I would like to find this using code instead.

How can I find those variables? Any help would me much appreciated. Thanks!

Body:
Let's use the mtcars dataset, which has 10 variables (instead of your 48 variables).

There are 10(10-1)/2 unique correlation pairs. If you look at the correlation matrix, this corresponds to the elements above the diagonal. By checking whether the correlation is larger than 0.7 (or smaller than -0.7) for those upper-triangular elements, we can see how many unique pairs are heavily correlated:

cor_mat     <- cor(mtcars)
unique_cors <- cor_mat[upper.tri(cor_mat)]
sum(abs(unique_cors) > 0.7)
# [1] 19

And if you want to just get a TRUE or FALSE indication for every pair, you could use:

abs(cor_mat) > 0.7
       mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
mpg   TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
cyl   TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE
disp  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE
hp    TRUE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE  TRUE
drat FALSE FALSE  TRUE FALSE  TRUE  TRUE FALSE FALSE  TRUE FALSE FALSE
wt    TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE
qsec FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE
vs   FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE
am   FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE  TRUE FALSE
gear FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE
carb FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE


来源: stackexchange

问:
MySQL BETWEEN query w/ BETWEEN ? AND?
Can anyone guide me to or provide how the dual question marks work in a BETWEEN comparison.. I can't get it to work and I can't locate or search these data on the MySQL site and Google - bunches of random results.</p>

ContentLicense: CC BY-SA 2.5

Title: MySQL BETWEEN query w/ BETWEEN ? AND?


问:
Converting Dword into Bit array in C#
I am working in an app that connects to a Siemens PLC using LibnoDave library. I am getting a Dword value that I convert it into an INT value, but now I need to convert this INT value into a BIT array. For example, I get as a INT value the number 62000 that in binary is 1111001000110000. I need that value. How can this be done?</p>

答: The question is that in that DWORD I only need the second word. For exampel if I receive 11111111111111110000000000000000 , I only need the 1111111111111111 of this Dword. </p>

ContentLicense: CC BY-SA 3.0

Title: Converting Dword into Bit array in C#


问:
Integrate WSO2 API Manager with third party api gateway like kong
I´m interested in using the store and the developer portal. In some cases I want to integrate third-party gateway like kong.

The documentation from WSO2 API Manager 2.x says:
 - Components usable separately: developer portal can be used to catalog
   APIs deployed in third-party gateways
   (https://wso2.com/api-management/features/)

Do you have more information about that feature and how to configure it?

答:
Technical this is feasible but requires some work. I've found that someone did it with Intel Expressway Service Gateway.

You would need to implement a custom handler in WSO2 and connect it with Kong. But as the features might differ, the UI may not perfectly fit.

Besides than offering extension points, WSO2 has no real interest in supporting this as the API Gateway is the core component and all of their business models are based on it.


问:
Check if new starttime and endtime overlaps with starttime and endtime records in db using linq
I went through few answers and few match the solution I already have.

In my job scheduling app I want to check if a new added task overlaps with a task that is already in the db. The solution below gives me results for the basic scenarios but does not quite work for few. Like in case where endtime for a new task is the same as starttime of another.

e.g:

```<code>//this returns false as it should - no overlaps
New Task      : 14:00 - 15:00
Existing Task : 16:00 - 17:00

//this returns true, as existing taskstart is < new takend - 17:00 overlap
New Task      : 14:00 - 17:00
Existing Task : 16:00 - 17:00

//this scenario should return false
/*udpated*/the tasks do not overlap here but touch each other
New Task      : 14:00 - 16:00
Existing Task : 16:00 - 17:00

private bool CheckForOtherTasks(int UserId, DateTime _dtTaskStart, DateTime _dtTaskEnd)
{
    bool _bTasksExist = false;
    using (var _dbContext = new task_Entities())
    {
        _bTasksExist = (from t in _dbContext.Tasks
                        where t.UserId == UserId
                        where t.dtTaskStart < _dtTaskEnd && _dtTaskStart < t.dtTaskEnd
                        select t).Any();
    }

    return _bTasksExist;
}
</code>```

The above solution works fine until there new endtime == existing starttime or vice versa.

This solution seems to solve it but I am unsure how to implement it along with LINQ without iterating through all the records. How check intersection of DateTime periods

Would using LINQ for this task be a good approach or using a Stored Procedure to returns results be a better option?

Also, would a library such as https://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET be ideal for a small project.

Cheers

答:
The above solution works fine until there new endtime == existing starttime or vice versa.

Then simply change the conditions from < to <= and from > to >=:

```<code>    _bTasksExist = (from t in _dbContext.Tasks
                    where t.UserId == UserId
                    where t.dtTaskStart <= _dtTaskEnd && _dtTaskStart <= t.dtTaskEnd
                    select t).Any();
</code>```

Body:
I went through few answers and few match the solution I already have.

In my job scheduling app I want to check if a new added task overlaps with a task that is already in the db. The solution below gives me results for the basic scenarios but does not quite work for few. Like in case where endtime for a new task is the same as starttime of another.

e.g:

//this returns false as it should - no overlaps
New Task      : 14:00 - 15:00
Existing Task : 16:00 - 17:00

//this returns true, as existing taskstart is < new takend - 17:00 overlap
New Task      : 14:00 - 17:00
Existing Task : 16:00 - 17:00

//this scenario should return false
/*udpated*/the tasks do not overlap here but touch each other
New Task      : 14:00 - 16:00
Existing Task : 16:00 - 17:00

private bool CheckForOtherTasks(int UserId, DateTime _dtTaskStart, DateTime _dtTaskEnd)
{
    bool _bTasksExist = false;
    using (var _dbContext = new task_Entities())
    {
        _bTasksExist = (from t in _dbContext.Tasks
                        where t.UserId == UserId
                        where t.dtTaskStart < _dtTaskEnd && _dtTaskStart < t.dtTaskEnd
                        select t).Any();
    }

    return _bTasksExist;
}

The above solution works fine until there new endtime == existing starttime or vice versa.

This solution seems to solve it but I am unsure how to implement it along with LINQ without iterating through all the records. How check intersection of DateTime periods

Would using LINQ for this task be a good approach or using a Stored Procedure to returns results be a better option?

Also, would a library such as https://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET be ideal for a small project.

Cheers

Body:
The above solution works fine until there new endtime == existing starttime or vice versa.

Then simply change the conditions from < to <= and from > to >=:

    _bTasksExist = (from t in _dbContext.Tasks
                    where t.UserId == UserId
                    where t.dtTaskStart <= _dtTaskEnd && _dtTaskStart <= t.dtTaskEnd
                    select t).Any();


问:
How to handle Authentication header in Selenium?
I am new to selenium and trying to handle authentication header which had been put up on web end for security reason. I am trying to access the site and send data using url using selenium but as authentication is required, I am unable to do so.
I've tried below mentioned code but couldn't succeed.

```<code>//Selenium-WebDriver Java Code for entering Username & Password as below:
    driver.findElement(By.id("userID")).sendKeys("username");
    driver.findElement(By.id("password")).sendKeys("pass");
    driver.switchTo().alert().accept();
    driver.switchTo().defaultContent();*/
        //self.headers = { "Authorization": "Basic xyz=" };
  /*        driver.switchTo().window("Authentication Required");
        driver.findElement(By.id("userID")).sendKeys("username");
        driver.findElement(By.id("password")).sendKeys("pass");*/

        //selenium.start("addCustomRequestHeader=true");
        //selenium.windowMaximize();
        //selenium.addCustomRequestHeader( "Authorization","Basic "+"xyx=" );
</code>```

Any help or suggestion would do great. Thanks in advance.

答:
Try this,</p>

```<code>WebDriver driver = new ChromeDriver();

String baseUrl=”http://” + “USERNAME” + “:” + “PASSWORD” + “@” + “xyz.com”;

driver.get(baseUrl + “/”);
</code>```

Body:
I am new to selenium and trying to handle authentication header which had been put up on web end for security reason. I am trying to access the site and send data using url using selenium but as authentication is required, I am unable to do so.
I've tried below mentioned code but couldn't succeed.

//Selenium-WebDriver Java Code for entering Username & Password as below:
    driver.findElement(By.id("userID")).sendKeys("username");
    driver.findElement(By.id("password")).sendKeys("pass");
    driver.switchTo().alert().accept();
    driver.switchTo().defaultContent();*/
        //self.headers = { "Authorization": "Basic xyz=" };
  /*        driver.switchTo().window("Authentication Required");
        driver.findElement(By.id("userID")).sendKeys("username");
        driver.findElement(By.id("password")).sendKeys("pass");*/

        //selenium.start("addCustomRequestHeader=true");
        //selenium.windowMaximize();
        //selenium.addCustomRequestHeader( "Authorization","Basic "+"xyx=" );

Any help or suggestion would do great. Thanks in advance.

Body:
Try this,

WebDriver driver = new ChromeDriver();

String baseUrl=”http://” + “USERNAME” + “:” + “PASSWORD” + “@” + “xyz.com”;

driver.get(baseUrl + “/”);


问:
angular2+ can build a release module that does not contain src code?
for example, I have a project, and it export a module named 'myNgmodule'; other projects can install and import it to use. but as the usual, we can see all the src code in node_modules. so can I build a 'release' version that does not contain the src code for other use it?

and I found a repo, the library project seems build a release folder, and be imported into main.app, but I don't know how it works

答:
In order to build Angular in production mode, you have to call

```<code>ng build --prod --no-sourcemap
</code>```

You should also take a look at this documentation about running Angular in production: https://docs.angularjs.org/guide/production

See also this other question: How to bundle an Angular app for production

Body:
In order to build Angular in production mode, you have to call

ng build --prod --no-sourcemap

You should also take a look at this documentation about running Angular in production: https://docs.angularjs.org/guide/production

See also this other question: How to bundle an Angular app for production


问:
Dagger generating multiple instances of retrofit interceptor
I am new to Dagger and Retrofit. I am having issue where multiple instances of retrofit custom interceptor are being generated despite declared singleton in dagger module. I only require one instance.

Dagger Module

```<code>@Module
public class ApiModule
{
    private Config config;

    public ApiModule(Config config) {
        this.config = config;
    }

    @Provides @Singleton
    public OkHttpClient.Builder provideOkHttpClient()
    {
        return new OkHttpClient.Builder();
    }

    @Provides @Singleton
    public AuthenticationRequestInterceptor provideRequestInterceptor()
    {
        return new AuthenticationRequestInterceptor();
    }

    @Provides @Singleton
    public Retrofit provideRetrofitInstance()
    {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        // set your desired log level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        // add session headers interceptor
        httpClient.addInterceptor(provideRequestInterceptor());

        // add logging as last interceptor
        httpClient.addInterceptor(logging);

        return new Retrofit.Builder()
                .baseUrl(getConfig().getBaseUrl())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(httpClient.build()) //for logging purpose remove later
                .build();
    }
}
</code>```

Retrofit Interceptor

```<code>public class AuthenticationRequestInterceptor implements Interceptor
{
    private Map<String, String> defaultHeaders;

    public AuthenticationRequestInterceptor()
    {
        this.defaultHeaders = new HashMap<>();
    }

    public void setDefaultHeaders(Map<String, String> headers)
    {
        this.defaultHeaders = headers;
    }

    @Override
    public Response intercept(Chain chain) throws IOException
    {
        Request request = chain.request();

        Request.Builder requestBuilder = request.newBuilder();

        for (String key: this.defaultHeaders.keySet())
        {
            requestBuilder.addHeader(key, this.defaultHeaders.get(key));
        }

        return chain.proceed(requestBuilder.build());
    }
}
</code>```

Connector

```<code>public class Connect
{
    @Inject Retrofit retrofit;
    @Inject Config config;
    @Inject AuthenticationRequestInterceptor headerInterceptor;

    public Connect(PercentApp application)
    {
        ((PercentApp) application).getComponent().inject(this);
</code>```

/** Setting interceptor headers here, but this get sets in a different
  instances than the one gets called later in postUser **/

```<code>     headerInterceptor.setDefaultHeaders(generateDefaultAuthHeaders());
    }

    public void postUser(Observer observer, User user)
    {
        if(retrofit != null)
        {
            ApiServices api = retrofit.create(ApiServices.class);
            Observable<HashMap> observable = api.postUser("{post something}");
            observable.
                    subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        }
    }

}
</code>```

And in my Application I create instance of Dagger like this:

```<code>DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this))
                .apiModule(new ApiModule(new Config(environment)))
                .build();
</code>```

And in my MainActivity I create instance of Connect

```<code>Connect connect = new Connect((MyApp) getApplication());
User user = new User();
connect.postUser(new UserObserver(this), user);
</code>```

Now the problem is that AuthenticationRequestInterceptor contructor gets called twice which I don't understand why and because of that the headers that I set get sets to a different instance of Interceptor. Please help. Thanks

答:
There is on point creating another of instance OkHttpClient.Builder within the provideRetrofitInstance method, you have already provided it in your ApiModule. Be nice and use as httpClient argument instead.</p>

```<code>@Module
public class ApiModule
{
   private Config config;

   public ApiModule(Config config) {
      this.config = config;
   }

   @Provides @Singleton
   public OkHttpClient.Builder provideOkHttpClient()
   {
      return new OkHttpClient.Builder();
   }

   @Provides @Singleton
   public AuthenticationRequestInterceptor provideRequestInterceptor()
   {
      return new AuthenticationRequestInterceptor();
   }

   @Provides @Singleton
   public Retrofit provideRetrofitInstance(OkHttpClient.Builder httpClient,
        AuthenticationRequestInterceptor authInterceptor)
   {
       HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
       // set your desired log level
       logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        //YOU DON'T THIS LINE, REFER TO ARGUMENT LIST
       //OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

      // add session headers interceptor
      httpClient.addInterceptor(authInterceptor);

      // add logging as last interceptor
      httpClient.addInterceptor(logging);

      return new Retrofit.Builder()
            .baseUrl(getConfig().getBaseUrl())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(httpClient.build()) //for logging purpose remove later
            .build();
    }
}
</code>```

Body:
I am new to Dagger and Retrofit. I am having issue where multiple instances of retrofit custom interceptor are being generated despite declared singleton in dagger module. I only require one instance.

Dagger Module

@Module
public class ApiModule
{
    private Config config;

    public ApiModule(Config config) {
        this.config = config;
    }

    @Provides @Singleton
    public OkHttpClient.Builder provideOkHttpClient()
    {
        return new OkHttpClient.Builder();
    }

    @Provides @Singleton
    public AuthenticationRequestInterceptor provideRequestInterceptor()
    {
        return new AuthenticationRequestInterceptor();
    }

    @Provides @Singleton
    public Retrofit provideRetrofitInstance()
    {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        // set your desired log level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        // add session headers interceptor
        httpClient.addInterceptor(provideRequestInterceptor());

        // add logging as last interceptor
        httpClient.addInterceptor(logging);

        return new Retrofit.Builder()
                .baseUrl(getConfig().getBaseUrl())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(httpClient.build()) //for logging purpose remove later
                .build();
    }
}

Retrofit Interceptor

public class AuthenticationRequestInterceptor implements Interceptor
{
    private Map<String, String> defaultHeaders;

    public AuthenticationRequestInterceptor()
    {
        this.defaultHeaders = new HashMap<>();
    }

    public void setDefaultHeaders(Map<String, String> headers)
    {
        this.defaultHeaders = headers;
    }

    @Override
    public Response intercept(Chain chain) throws IOException
    {
        Request request = chain.request();

        Request.Builder requestBuilder = request.newBuilder();

        for (String key: this.defaultHeaders.keySet())
        {
            requestBuilder.addHeader(key, this.defaultHeaders.get(key));
        }

        return chain.proceed(requestBuilder.build());
    }
}

Connector

public class Connect
{
    @Inject Retrofit retrofit;
    @Inject Config config;
    @Inject AuthenticationRequestInterceptor headerInterceptor;

    public Connect(PercentApp application)
    {
        ((PercentApp) application).getComponent().inject(this);

/** Setting interceptor headers here, but this get sets in a different
  instances than the one gets called later in postUser **/

     headerInterceptor.setDefaultHeaders(generateDefaultAuthHeaders());
    }

    public void postUser(Observer observer, User user)
    {
        if(retrofit != null)
        {
            ApiServices api = retrofit.create(ApiServices.class);
            Observable<HashMap> observable = api.postUser("{post something}");
            observable.
                    subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        }
    }

}

And in my Application I create instance of Dagger like this:

DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this))
                .apiModule(new ApiModule(new Config(environment)))
                .build();

And in my MainActivity I create instance of Connect

Connect connect = new Connect((MyApp) getApplication());
User user = new User();
connect.postUser(new UserObserver(this), user);

Now the problem is that AuthenticationRequestInterceptor contructor gets called twice which I don't understand why and because of that the headers that I set get sets to a different instance of Interceptor. Please help. Thanks

Body:
There is on point creating another of instance OkHttpClient.Builder within the provideRetrofitInstance method, you have already provided it in your ApiModule. Be nice and use as httpClient argument instead.

@Module
public class ApiModule
{
   private Config config;

   public ApiModule(Config config) {
      this.config = config;
   }

   @Provides @Singleton
   public OkHttpClient.Builder provideOkHttpClient()
   {
      return new OkHttpClient.Builder();
   }

   @Provides @Singleton
   public AuthenticationRequestInterceptor provideRequestInterceptor()
   {
      return new AuthenticationRequestInterceptor();
   }

   @Provides @Singleton
   public Retrofit provideRetrofitInstance(OkHttpClient.Builder httpClient,
        AuthenticationRequestInterceptor authInterceptor)
   {
       HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
       // set your desired log level
       logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        //YOU DON'T THIS LINE, REFER TO ARGUMENT LIST
       //OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

      // add session headers interceptor
      httpClient.addInterceptor(authInterceptor);

      // add logging as last interceptor
      httpClient.addInterceptor(logging);

      return new Retrofit.Builder()
            .baseUrl(getConfig().getBaseUrl())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(httpClient.build()) //for logging purpose remove later
            .build();
    }
}


问:
Subtract numbers from the results of an SQL query
So what the title says.

My results look like these [100, 200, 300], i have multiple of these, around 2000.

From each one i want to subtract [50, 50, 50], so that the results would be something like [50, 150, 250] and so on and so on.

I guess it is easy for most people, but i cannot find any example and i could not do it myself. how can i subtract a specific number from a query.

My sql uses ST_AsGeoJSON, something like:

```<code>SELECT ST_AsGeoJSON(ST_Transform(geom, 32633)) FROM "database";
</code>```

being read via:

```<code>using (var reader = command.ExecuteReader()) {
    while (reader.Read()) {
      // ...
      resultTable[col].Add(reader[col].ToString());
    }
}
</code>```

答:
Your sql would really help, but if its something like:

select myCol1, myCol2, myCol3
from myTable
where
...

Then you could try:

select (myCol1-50),(myCol2-50),(myCol3-50)
from myTable
where
...

Body:
So what the title says.

My results look like these [100, 200, 300], i have multiple of these, around 2000.

From each one i want to subtract [50, 50, 50], so that the results would be something like [50, 150, 250] and so on and so on.

I guess it is easy for most people, but i cannot find any example and i could not do it myself. how can i subtract a specific number from a query.

My sql uses ST_AsGeoJSON, something like:

SELECT ST_AsGeoJSON(ST_Transform(geom, 32633)) FROM "database";

being read via:

using (var reader = command.ExecuteReader()) {
    while (reader.Read()) {
      // ...
      resultTable[col].Add(reader[col].ToString());
    }
}


答:
Options:

keep your existing query; after you have loaded the data, iterate over the rows and manually subtract from the values

change your query to subtract when querying

I'd probably suggest the 1st; this sounds like a view related thing, and it allows more flexibility (allowing different deltas per row, for example). Since you don't show how you're currently querying and loading the data, I can't really advise further.

Title: Subtract numbers from the results of an SQL query


问:
How to do Android datepicker To date greater than from date validation

I have two DatePicker. One with From date and other with To date. I want to
    display To date always greater than from date according to From date selection .I am using the Android default date picker, and want to disable the past
    dates of TO datepicker if its greater than the From date and vice versa. I know
    this topic has been asked many times here. But, I couldn't make my code work
    like the suggested solutions, so please help?

```<code>Calendar calendarOne = Calendar.getInstance();

     datePickerFrom= new DatePickerDialog(getActivity(), new
     DatePickerDialog.OnDateSetListener() {

     @Override
     public void onDateSet(DatePicker view, int year, int monthOfYear,
     int dayOfMonth) {
        StringBuilder selectedDate = new
    StringBuilder().append(dayOfMonth).append("-").append(monthOfYear +
    1).append("-").append(year);
     fromText.setText(selectedDate);
     fromText.setTextColor(android.graphics.Color.BLACK);
    }

  }, calendarOne.get(Calendar.YEAR), calendarOne.get(Calendar.MONTH),
     calendarOne.get(Calendar.DAY_OF_MONTH));

 fromText.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        datePickerFrom.getDatePicker().setMaxDate(new
     Date().getTime());
        datePickerFrom.show();
    }
});

  Calendar calendarTwo = Calendar.getInstance();
  datePickerTo = new DatePickerDialog(getActivity(), new
  DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int
    dayOfMonth) {
        StringBuilder selectedDate = new
   StringBuilder().append(dayOfMonth).append("-").append(monthOfYear +
   1).append("-").append(year);
        toText.setText(selectedDate);
        toText.setTextColor(android.graphics.Color.BLACK);
      }
   }, calendarTwo.get(Calendar.YEAR), calendarTwo.get(Calendar.MONTH),
   calendarTwo.get(Calendar.DAY_OF_MONTH));

   toText.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
       datePickerTo.getDatePicker().setMaxDate(new Date().getTime());
       datePickerTo.show();
      }
    });
   }
</code>```

................................
Updated Code

```<code>    final Calendar calendarOne = Calendar.getInstance();
    datePickerFrom= new DatePickerDialog(getActivity(), new
            DatePickerDialog.OnDateSetListener()
            {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onDateSet(DatePicker view, int year, final int
    monthOfYear, int dayOfMonth)
                {
                    StringBuilder selectedDate = new
                            StringBuilder().append(dayOfMonth).append("-
      ").append(monthOfYear + 1).append("-").append(year);
                  fromText.setText(selectedDate);
                  fromText.setTextColor(android.graphics.Color.BLACK);

                    Calendar calendarTwo = Calendar.getInstance();
                   datePickerTo = new DatePickerDialog(getActivity());

    datePickerTo.getDatePicker().setMinDate(calendarOne.getTimeInMillis());

                   datePickerTo = new DatePickerDialog(activity, new
   DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year, int
    month, int dayOfMonth) {
                            StringBuilder selectedDate = new
    StringBuilder().append(dayOfMonth).append("-").append(monthOfYear +
    1).append("-").append(year);
                              toText.setText(selectedDate);

   toText.setTextColor(android.graphics.Color.BLACK);
                        }
                    }, calendarTwo.get(Calendar.YEAR),
   calendarTwo.get(Calendar.MONTH),
                        calendarTwo.get(Calendar.DAY_OF_MONTH));

                      toText.setOnClickListener(new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View view)
                        {
                           datePickerTo.getDatePicker().setMaxDate(new
     Date().getTime());
                           datePickerTo.show();
                        }
                    });

                }

            }, calendarOne.get(Calendar.YEAR),
      calendarOne.get(Calendar.MONTH),
            calendarOne.get(Calendar.DAY_OF_MONTH));

   fromText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            datePickerFrom.getDatePicker().setMaxDate(new
                    Date().getTime());
            datePickerFrom.show();
        }
    });
</code>```

答:
First of all declare following in your class before onCreate :

```<code>private String fromDate;
private DatePickerDialog fromDatePicker;
private DatePickerDialog.OnDateSetListener fromDatePickerListener;
private Calendar fromDateCalendar;
private String toDate;
private DatePickerDialog toDatePicker;
private DatePickerDialog.OnDateSetListener toDatePickerListener;
private Calendar toDateCalendar;
</code>```

After that in your onCreate method add following code:

```<code>fromDateCalendar = Calendar.getInstance();
    fromDatePickerListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            fromDateCalendar.set(Calendar.YEAR, year);
            fromDateCalendar.set(Calendar.MONTH, monthOfYear);
            fromDateCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            fromDate = fromDateCalendar.get(Calendar.YEAR) + "-" + (fromDateCalendar.get(Calendar.MONTH)+1) + "-" + fromDateCalendar.get(Calendar.DAY_OF_MONTH);
            //etFromDate.setText(fromDate);
            toDatePicker.getDatePicker().setMinDate(fromDateCalendar.getTimeInMillis());
        }

    };

    toDateCalendar = Calendar.getInstance();
    toDatePickerListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            toDateCalendar.set(Calendar.YEAR, year);
            toDateCalendar.set(Calendar.MONTH, monthOfYear);
            toDateCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            toDate = toDateCalendar.get(Calendar.YEAR) + "-" + (toDateCalendar.get(Calendar.MONTH)+1) + "-" + toDateCalendar.get(Calendar.DAY_OF_MONTH);
            //etToDate.setText(toDate);
        }

    };

    toDatePicker = new DatePickerDialog(getContext(),toDatePickerListener, toDateCalendar.get(Calendar.YEAR), toDateCalendar.get(Calendar.MONTH), toDateCalendar.get(Calendar.DAY_OF_MONTH));
    fromDatePicker = new DatePickerDialog(getContext(),fromDatePickerListener, fromDateCalendar.get(Calendar.YEAR), fromDateCalendar.get(Calendar.MONTH), fromDateCalendar.get(Calendar.DAY_OF_MONTH));
</code>```

Next step is when you want to show your datePicker upon clicking button or edit text where ever you want to show your date picker use following lines to show:

```<code>fromDatePicker.show();
toDatePicker.show();
</code>```

Also you can use strings fromDate and toDate to show selected dates if you want to show them anywhere like in a textView or editText.

Body:
I have two DatePicker. One with From date and other with To date. I want to
    display To date always greater than from date according to From date selection .I am using the Android default date picker, and want to disable the past
    dates of TO datepicker if its greater than the From date and vice versa. I know
    this topic has been asked many times here. But, I couldn't make my code work
    like the suggested solutions, so please help?

Calendar calendarOne = Calendar.getInstance();

     datePickerFrom= new DatePickerDialog(getActivity(), new
     DatePickerDialog.OnDateSetListener() {

     @Override
     public void onDateSet(DatePicker view, int year, int monthOfYear,
     int dayOfMonth) {
        StringBuilder selectedDate = new
    StringBuilder().append(dayOfMonth).append("-").append(monthOfYear +
    1).append("-").append(year);
     fromText.setText(selectedDate);
     fromText.setTextColor(android.graphics.Color.BLACK);
    }

  }, calendarOne.get(Calendar.YEAR), calendarOne.get(Calendar.MONTH),
     calendarOne.get(Calendar.DAY_OF_MONTH));

 fromText.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        datePickerFrom.getDatePicker().setMaxDate(new
     Date().getTime());
        datePickerFrom.show();
    }
});

  Calendar calendarTwo = Calendar.getInstance();
  datePickerTo = new DatePickerDialog(getActivity(), new
  DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int
    dayOfMonth) {
        StringBuilder selectedDate = new
   StringBuilder().append(dayOfMonth).append("-").append(monthOfYear +
   1).append("-").append(year);
        toText.setText(selectedDate);
        toText.setTextColor(android.graphics.Color.BLACK);
      }
   }, calendarTwo.get(Calendar.YEAR), calendarTwo.get(Calendar.MONTH),
   calendarTwo.get(Calendar.DAY_OF_MONTH));

   toText.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
       datePickerTo.getDatePicker().setMaxDate(new Date().getTime());
       datePickerTo.show();
      }
    });
   }

................................
Updated Code

    final Calendar calendarOne = Calendar.getInstance();
    datePickerFrom= new DatePickerDialog(getActivity(), new
            DatePickerDialog.OnDateSetListener()
            {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onDateSet(DatePicker view, int year, final int
    monthOfYear, int dayOfMonth)
                {
                    StringBuilder selectedDate = new
                            StringBuilder().append(dayOfMonth).append("-
      ").append(monthOfYear + 1).append("-").append(year);
                  fromText.setText(selectedDate);
                  fromText.setTextColor(android.graphics.Color.BLACK);

                    Calendar calendarTwo = Calendar.getInstance();
                   datePickerTo = new DatePickerDialog(getActivity());

    datePickerTo.getDatePicker().setMinDate(calendarOne.getTimeInMillis());

                   datePickerTo = new DatePickerDialog(activity, new
   DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year, int
    month, int dayOfMonth) {
                            StringBuilder selectedDate = new
    StringBuilder().append(dayOfMonth).append("-").append(monthOfYear +
    1).append("-").append(year);
                              toText.setText(selectedDate);

   toText.setTextColor(android.graphics.Color.BLACK);
                        }
                    }, calendarTwo.get(Calendar.YEAR),
   calendarTwo.get(Calendar.MONTH),
                        calendarTwo.get(Calendar.DAY_OF_MONTH));

                      toText.setOnClickListener(new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View view)
                        {
                           datePickerTo.getDatePicker().setMaxDate(new
     Date().getTime());
                           datePickerTo.show();
                        }
                    });

                }

            }, calendarOne.get(Calendar.YEAR),
      calendarOne.get(Calendar.MONTH),
            calendarOne.get(Calendar.DAY_OF_MONTH));

   fromText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            datePickerFrom.getDatePicker().setMaxDate(new
                    Date().getTime());
            datePickerFrom.show();
        }
    });

Body:
First of all declare following in your class before onCreate :

private String fromDate;
private DatePickerDialog fromDatePicker;
private DatePickerDialog.OnDateSetListener fromDatePickerListener;
private Calendar fromDateCalendar;
private String toDate;
private DatePickerDialog toDatePicker;
private DatePickerDialog.OnDateSetListener toDatePickerListener;
private Calendar toDateCalendar;

After that in your onCreate method add following code:

fromDateCalendar = Calendar.getInstance();
    fromDatePickerListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            fromDateCalendar.set(Calendar.YEAR, year);
            fromDateCalendar.set(Calendar.MONTH, monthOfYear);
            fromDateCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            fromDate = fromDateCalendar.get(Calendar.YEAR) + "-" + (fromDateCalendar.get(Calendar.MONTH)+1) + "-" + fromDateCalendar.get(Calendar.DAY_OF_MONTH);
            //etFromDate.setText(fromDate);
            toDatePicker.getDatePicker().setMinDate(fromDateCalendar.getTimeInMillis());
        }

    };

    toDateCalendar = Calendar.getInstance();
    toDatePickerListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            toDateCalendar.set(Calendar.YEAR, year);
            toDateCalendar.set(Calendar.MONTH, monthOfYear);
            toDateCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            toDate = toDateCalendar.get(Calendar.YEAR) + "-" + (toDateCalendar.get(Calendar.MONTH)+1) + "-" + toDateCalendar.get(Calendar.DAY_OF_MONTH);
            //etToDate.setText(toDate);
        }

    };

    toDatePicker = new DatePickerDialog(getContext(),toDatePickerListener, toDateCalendar.get(Calendar.YEAR), toDateCalendar.get(Calendar.MONTH), toDateCalendar.get(Calendar.DAY_OF_MONTH));
    fromDatePicker = new DatePickerDialog(getContext(),fromDatePickerListener, fromDateCalendar.get(Calendar.YEAR), fromDateCalendar.get(Calendar.MONTH), fromDateCalendar.get(Calendar.DAY_OF_MONTH));

Next step is when you want to show your datePicker upon clicking button or edit text where ever you want to show your date picker use following lines to show:

fromDatePicker.show();
toDatePicker.show();

Also you can use strings fromDate and toDate to show selected dates if you want to show them anywhere like in a textView or editText.


问:
Parsing XML to an array for GMaps API using jQuery
I'm teaching myself javascript by creating my wedding website using the google maps API.  I've figured out a lot through the docs and copypasta experimentation, but don't know how to make this happen: what I want to do is read an external XML file containing icon information (names and offsets for a sprite image containing the icons), and store it in an array that I can access when creating map markers.  For example, I want to be able to create a marker for the reception and assign it the icon "party".  Here's the code I have so far for reading the icon file:

```<code>        jQuery.get("markericons.xml", {}, function(data) {
        jQuery(data).find("markericon").each(function() {
            var icon = jQuery(this);
            var name = icon.attr("name");
            var url = 'images/icons/mapsprites.png';
            var size = new google.maps.Size(32, 37);
            var origin = new google.maps.Point(parseInt(icon.attr("x")),parseInt(icon.attr("y")));
            var anchor = new google.maps.Point((origin.x+16),origin.y);
            var icon = new google.maps.MarkerImage(url, size, origin, anchor);
        });
    });  // how to store this in an array so that I can access elements by name later?
</code>```

And then, when creating the actual placemarks on the google map, something like the following:

```<code>                var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                icon: icon.name=="party",  // pseudo-code... how to do this?
                title: title
            });
</code>```

I'm still a programming noob, so I'd appreciate any help.  Thanks!

答:
you should have a JSON object outside of your .each() or .get() method, depending on how accessible you want it to be (i'm guessing outside of .get(), so we'll use that for this example) and then create a JSON object out of your variables inside your .each().

```<code>var storage = {}
jQuery.get("markericons.xml", {}, function(data) {
    jQuery(data).find("markericon").each(function() {
        var icon = jQuery(this),
            name = icon.attr("name");
        storage[name] = {
            url: 'images/icons/mapsprites.png',
            size: new google.maps.Size(32, 37),
            origin: new google.maps.Point(parseInt(icon.attr("x")),parseInt(icon.attr("y"))),
            anchor: new google.maps.Point((origin.x+16),origin.y),
            icon: new google.maps.MarkerImage(url, size, origin, anchor)
        };
    });
});
</code>```

now, you can access your google maps stuff by name:

```<code>// for this purpose, let's say `name` is "reception":
console.log(storage.reception)
// => prints out { url: ..., size: ..., origin: ..., anchor: ..., icon: ... }
</code>```

also, in your original JS, you have icon declared twice, so I'm not too sure what you want to do with that.

Body:
I'm teaching myself javascript by creating my wedding website using the google maps API.  I've figured out a lot through the docs and copypasta experimentation, but don't know how to make this happen: what I want to do is read an external XML file containing icon information (names and offsets for a sprite image containing the icons), and store it in an array that I can access when creating map markers.  For example, I want to be able to create a marker for the reception and assign it the icon "party".  Here's the code I have so far for reading the icon file:

        jQuery.get("markericons.xml", {}, function(data) {
        jQuery(data).find("markericon").each(function() {
            var icon = jQuery(this);
            var name = icon.attr("name");
            var url = 'images/icons/mapsprites.png';
            var size = new google.maps.Size(32, 37);
            var origin = new google.maps.Point(parseInt(icon.attr("x")),parseInt(icon.attr("y")));
            var anchor = new google.maps.Point((origin.x+16),origin.y);
            var icon = new google.maps.MarkerImage(url, size, origin, anchor);
        });
    });  // how to store this in an array so that I can access elements by name later?

And then, when creating the actual placemarks on the google map, something like the following:

                var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                icon: icon.name=="party",  // pseudo-code... how to do this?
                title: title
            });

I'm still a programming noob, so I'd appreciate any help.  Thanks!

Body:
you should have a JSON object outside of your .each() or .get() method, depending on how accessible you want it to be (i'm guessing outside of .get(), so we'll use that for this example) and then create a JSON object out of your variables inside your .each().

var storage = {}
jQuery.get("markericons.xml", {}, function(data) {
    jQuery(data).find("markericon").each(function() {
        var icon = jQuery(this),
            name = icon.attr("name");
        storage[name] = {
            url: 'images/icons/mapsprites.png',
            size: new google.maps.Size(32, 37),
            origin: new google.maps.Point(parseInt(icon.attr("x")),parseInt(icon.attr("y"))),
            anchor: new google.maps.Point((origin.x+16),origin.y),
            icon: new google.maps.MarkerImage(url, size, origin, anchor)
        };
    });
});

now, you can access your google maps stuff by name:

// for this purpose, let's say `name` is "reception":
console.log(storage.reception)
// => prints out { url: ..., size: ..., origin: ..., anchor: ..., icon: ... }

also, in your original JS, you have icon declared twice, so I'm not too sure what you want to do with that.


问:
Uploading files using a webview in Xamarin Android App
I'm working on a simple xamarin android app, that allows to display a responsive web site, and receive push notifications.

Webview seems to have some limitations on Xamarin, so I used the following workaround (https://github.com/GabLeRoux/xamarin-android-webview-upload) based on the following comments (https://forums.xamarin.com/discussion/3259/cannot-override-webviewclient-class-for-file-upload-support) in order to get html upload button work as expected.

Everything goes well, until I migrate push notifications from GCM to FCM. After that the webview, returns to work as the beginning.

Basically, the html upload button does not open a file chooser dialog, and don't raise any error. It simply does nothing.

Following is the code I'm using on the web activity.

I'm using Xamarin.Android 7.3, and VS 2015.

Any help is welcome.

```<code>using System;
using Android.Runtime;
using Android.Views;
using Android.App;
using Android.Content;
using Android.OS;

using Android.Webkit;
using Android.Widget;

namespace sigese
{
    [Activity(Label = "WebActivity")]
    public class WebActivity : Activity
    {

        IValueCallback mUploadMessage;
        private static int FILECHOOSER_RESULTCODE = 1;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.WebLayout);

            ActionBar.Hide();

            var username = Intent.GetStringExtra("username");
            var password = Intent.GetStringExtra("password");

            var chrome = new FileChooserWebChromeClient((uploadMsg, acceptType, capture) => {
                mUploadMessage = uploadMsg;
                var i = new Intent(Intent.ActionGetContent);
                i.AddCategory(Intent.CategoryOpenable);
                i.SetType("image/*");
                StartActivityForResult(Intent.CreateChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            });

            var webview = this.FindViewById<WebView>(Resource.Id.LocalWebView);
            webview.SetWebViewClient(new WebViewClient());
            webview.SetWebChromeClient(chrome);
            webview.Settings.JavaScriptEnabled = true;

           webview.LoadUrl("https://example.com/login.asp?username="+username+"&password="+password);

        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
        {
            if (requestCode == FILECHOOSER_RESULTCODE)
            {
                if (null == mUploadMessage)
                    return;
                Java.Lang.Object result = intent == null || resultCode != Result.Ok
                    ? null
                    : intent.Data;
                mUploadMessage.OnReceiveValue(result);
                mUploadMessage = null;
            }
        }

        public override void OnBackPressed()
        {
            WebView localWebView = FindViewById<WebView>(Resource.Id.LocalWebView);
            if (localWebView.CanGoBack())
            {
                localWebView.GoBack();
            }
            else
            {
               return;
            }
        }

    }
    partial class FileChooserWebChromeClient : WebChromeClient
    {
        Action<IValueCallback, Java.Lang.String, Java.Lang.String> callback;

        public FileChooserWebChromeClient(Action<IValueCallback, Java.Lang.String, Java.Lang.String> callback)
        {
            this.callback = callback;
        }

        // For Android < 5.0
        [Java.Interop.Export]
        public void openFileChooser(IValueCallback uploadMsg, Java.Lang.String acceptType, Java.Lang.String capture)
        {
            callback(uploadMsg, acceptType, capture);
        }

        // For Android > 5.0

    }
}
</code>```

答:
Step 1

File upload will work , we need to give Read / Write permission in android manifest.
in Main Activity.cs

Step 2

```<code>private Action<int, Result, Intent> resultCallbackvalue;

public void StartActivity(Intent intent, int requestCode, Action<int, Result, Intent> resultCallback)
{
    this.resultCallbackvalue = resultCallback;
    StartActivityForResult(intent, requestCode);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
    if (this.resultCallbackvalue != null)
{
   this.resultCallbackvalue(requestCode, resultCode, data);
   this.resultCallbackvalue = null;
}
</code>```

Step 3

Add ExtendedChromeClient,cs Inheriting from : WebChromeClient

```<code>private static int filechooser = 1;
private IValueCallback message;
private MainActivity activity = null;

public ExtendedChromeClient(MainActivity context)
{
    this.activity = context;
}

public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
{
    this.message = filePathCallback;
    Intent chooserIntent = fileChooserParams.CreateIntent();
    chooserIntent.AddCategory(Intent.CategoryOpenable);
    this.activity.StartActivity(Intent.CreateChooser(chooserIntent, "File Chooser"), filechooser, this.OnActivityResult);
    return true;
}

private void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    if (data != null)
    {
        if (requestCode == filechooser)
        {
            if (null == this.message)
            {`enter code here`
                    return;
            }

            this.message.OnReceiveValue(WebChromeClient.FileChooserParams.ParseResult((int)resultCode, data));
            this.message = null;
        }
    }
}
</code>```

Body:
I'm working on a simple xamarin android app, that allows to display a responsive web site, and receive push notifications.

Webview seems to have some limitations on Xamarin, so I used the following workaround (https://github.com/GabLeRoux/xamarin-android-webview-upload) based on the following comments (https://forums.xamarin.com/discussion/3259/cannot-override-webviewclient-class-for-file-upload-support) in order to get html upload button work as expected.

Everything goes well, until I migrate push notifications from GCM to FCM. After that the webview, returns to work as the beginning.

Basically, the html upload button does not open a file chooser dialog, and don't raise any error. It simply does nothing.

Following is the code I'm using on the web activity.

I'm using Xamarin.Android 7.3, and VS 2015.

Any help is welcome.

using System;
using Android.Runtime;
using Android.Views;
using Android.App;
using Android.Content;
using Android.OS;

using Android.Webkit;
using Android.Widget;

namespace sigese
{
    [Activity(Label = "WebActivity")]
    public class WebActivity : Activity
    {

        IValueCallback mUploadMessage;
        private static int FILECHOOSER_RESULTCODE = 1;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.WebLayout);

            ActionBar.Hide();

            var username = Intent.GetStringExtra("username");
            var password = Intent.GetStringExtra("password");

            var chrome = new FileChooserWebChromeClient((uploadMsg, acceptType, capture) => {
                mUploadMessage = uploadMsg;
                var i = new Intent(Intent.ActionGetContent);
                i.AddCategory(Intent.CategoryOpenable);
                i.SetType("image/*");
                StartActivityForResult(Intent.CreateChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            });

            var webview = this.FindViewById<WebView>(Resource.Id.LocalWebView);
            webview.SetWebViewClient(new WebViewClient());
            webview.SetWebChromeClient(chrome);
            webview.Settings.JavaScriptEnabled = true;

           webview.LoadUrl("https://example.com/login.asp?username="+username+"&password="+password);

        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
        {
            if (requestCode == FILECHOOSER_RESULTCODE)
            {
                if (null == mUploadMessage)
                    return;
                Java.Lang.Object result = intent == null || resultCode != Result.Ok
                    ? null
                    : intent.Data;
                mUploadMessage.OnReceiveValue(result);
                mUploadMessage = null;
            }
        }

        public override void OnBackPressed()
        {
            WebView localWebView = FindViewById<WebView>(Resource.Id.LocalWebView);
            if (localWebView.CanGoBack())
            {
                localWebView.GoBack();
            }
            else
            {
               return;
            }
        }

    }
    partial class FileChooserWebChromeClient : WebChromeClient
    {
        Action<IValueCallback, Java.Lang.String, Java.Lang.String> callback;

        public FileChooserWebChromeClient(Action<IValueCallback, Java.Lang.String, Java.Lang.String> callback)
        {
            this.callback = callback;
        }

        // For Android < 5.0
        [Java.Interop.Export]
        public void openFileChooser(IValueCallback uploadMsg, Java.Lang.String acceptType, Java.Lang.String capture)
        {
            callback(uploadMsg, acceptType, capture);
        }

        // For Android > 5.0

    }
}

Body:
Step 1

File upload will work , we need to give Read / Write permission in android manifest.
in Main Activity.cs

Step 2

private Action<int, Result, Intent> resultCallbackvalue;

public void StartActivity(Intent intent, int requestCode, Action<int, Result, Intent> resultCallback)
{
    this.resultCallbackvalue = resultCallback;
    StartActivityForResult(intent, requestCode);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
    if (this.resultCallbackvalue != null)
{
   this.resultCallbackvalue(requestCode, resultCode, data);
   this.resultCallbackvalue = null;
}

Step 3

Add ExtendedChromeClient,cs Inheriting from : WebChromeClient

private static int filechooser = 1;
private IValueCallback message;
private MainActivity activity = null;

public ExtendedChromeClient(MainActivity context)
{
    this.activity = context;
}

public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
{
    this.message = filePathCallback;
    Intent chooserIntent = fileChooserParams.CreateIntent();
    chooserIntent.AddCategory(Intent.CategoryOpenable);
    this.activity.StartActivity(Intent.CreateChooser(chooserIntent, "File Chooser"), filechooser, this.OnActivityResult);
    return true;
}

private void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    if (data != null)
    {
        if (requestCode == filechooser)
        {
            if (null == this.message)
            {`enter code here`
                    return;
            }

            this.message.OnReceiveValue(WebChromeClient.FileChooserParams.ParseResult((int)resultCode, data));
            this.message = null;
        }
    }
}

ContentLicense: CC BY-SA 4.0


问:
SSRS 2017 Web.config permissions
I have run into an issue with my SSRS 2017 report manager. I have implemented the sample found here and it all seems to work except from the web portal (the server is fine). I have found the solution is that the service user needs to have write permissions to the web.config to copy the machinekey from RSReportingServices.config.

How can I circumvent this? I have tried manually writing to the web.config but the rshostingservice still tries to sync the keys and fails.

答:
I want able to circumvent the need of write permissions. I solved my issue by granting write permission to the service that runs ssrs. i used the below code to bestow the required permissions</p>

```<code>        try
        {
            var fileSecurity = File.GetAccessControl(Path);
            var user = ServiceUserDetails();
            fileSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Write,
                AccessControlType.Allow));
            fileSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Read,
                AccessControlType.Allow));
            fileSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.ReadAndExecute,
                AccessControlType.Allow));
            File.SetAccessControl(Path, fileSecurity);
        }
        catch
        {
            MessageBox.Show(@"Error",
                $@"Unable to set permissions for {Path}. Please ensure service has write permission");
        }
</code>```

Title: SSRS 2017 Web.config permissions

Body:
I want able to circumvent the need of write permissions. I solved my issue by granting write permission to the service that runs ssrs. i used the below code to bestow the required permissions

        try
        {
            var fileSecurity = File.GetAccessControl(Path);
            var user = ServiceUserDetails();
            fileSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Write,
                AccessControlType.Allow));
            fileSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Read,
                AccessControlType.Allow));
            fileSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.ReadAndExecute,
                AccessControlType.Allow));
            File.SetAccessControl(Path, fileSecurity);
        }
        catch
        {
            MessageBox.Show(@"Error",
                $@"Unable to set permissions for {Path}. Please ensure service has write permission");
        }


问:
Check if entry in table A exists in table B
I have a definition table that I know is not being maintained very well, let's call this table A. I have another table (call it table B) that is much smaller and ideally should be a subset of table A but I know that table A is somewhat stale and does not contain new entries that are in Table B.

Note, that tables A and B have different columns.

```<code>Table A:
ID, Name, blah, blah, blah, blah

Table B:
ID, Name
</code>```

I want all rows in Table B such that the ID in Table B does NOT exist in Table A. This does not just match rows in Table A; I want only rows in Table B where the ID does NOT exist at all in Table A.

答:
Or if "NOT EXISTS" are not implemented</p>

```<code>SELECT *
FROM   B
WHERE (SELECT count(*)  FROM   A WHERE  A.ID = B.ID) < 1
</code>```

Body:
I have a definition table that I know is not being maintained very well, let's call this table A. I have another table (call it table B) that is much smaller and ideally should be a subset of table A but I know that table A is somewhat stale and does not contain new entries that are in Table B.

Note, that tables A and B have different columns.

Table A:
ID, Name, blah, blah, blah, blah

Table B:
ID, Name

I want all rows in Table B such that the ID in Table B does NOT exist in Table A. This does not just match rows in Table A; I want only rows in Table B where the ID does NOT exist at all in Table A.

Body:
Or if "NOT EXISTS" are not implemented

SELECT *
FROM   B
WHERE (SELECT count(*)  FROM   A WHERE  A.ID = B.ID) < 1


问:
We want to use the Rocket.chat with our own server instead of open.rocket.chat some how we are not able to go ahead
We want to use Rocket.chat app with our server (domain) instead of open.rocket.chat, but when we replaced the open.rocket.chat with our server URL we are getting the error as below...

```<code>[WebSocket] did disconnect with error (Optional(Error Domain=WebSocket Code=400 "Invalid HTTP upgrade" UserInfo={NSLocalizedDescription=Invalid HTTP upgrade}))
Socket will send message: {
"id" : "0tZIJpxo2ifrm4q18OnFpQfvYQA0OmqS1OyD3kKLFQvme3G4er",
"method" : "public-settings\/get",
"msg" : "method"
}
</code>```

Actually we have done all the server set up as per the guidelines of Rocket.chat forum.

I googled a lot for this issue but some how the google seems to be pretty thin about it.

Is anyone from rocket chat or from all around will help me to trace the issue, Your any help will be highly appreciated..

答:
Can you specify what version of the app are you using, and what version of the server are you using? Also, make sure that your server support WebSocket connection. There's a warning on the repository about that:

Make sure your server supports WebSocket. These are the minimum requirements for Apache 2.4 and Nginx 1.3 or greater.

You can read more information here: https://github.com/RocketChat/Rocket.Chat.iOS

There's also a few issues from other users discussing about app connectivity.

Body:
We want to use Rocket.chat app with our server (domain) instead of open.rocket.chat, but when we replaced the open.rocket.chat with our server URL we are getting the error as below...

[WebSocket] did disconnect with error (Optional(Error Domain=WebSocket Code=400 "Invalid HTTP upgrade" UserInfo={NSLocalizedDescription=Invalid HTTP upgrade}))
Socket will send message: {
"id" : "0tZIJpxo2ifrm4q18OnFpQfvYQA0OmqS1OyD3kKLFQvme3G4er",
"method" : "public-settings\/get",
"msg" : "method"
}

Actually we have done all the server set up as per the guidelines of Rocket.chat forum.

I googled a lot for this issue but some how the google seems to be pretty thin about it.

Is anyone from rocket chat or from all around will help me to trace the issue, Your any help will be highly appreciated..


问:
How to launch a browser from an Iphone application
Any idea how to launch an instance of Safari from an Iphone or Ipad application? But the case its that I would like to manipulate some aspects of the Safari window, for example I would like to launch it in Kiosk mode, without the addres bar.

I found something like openUrl but I am not sure if it is the best way and I can customize the windows properties etc...

答:
From iOS 10.0 this is deprecated,

```<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.google.com"]];
</code>```

You need to use this instead to get the same old behavior,

```<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.google.com"] options:[NSDictionary dictionary] completionHandler:nil];
</code>```

Body:
From iOS 10.0 this is deprecated,

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.google.com"]];

You need to use this instead to get the same old behavior,

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.google.com"] options:[NSDictionary dictionary] completionHandler:nil];


问:
How to wait until loading window close or visible false
I have developed selenium automation framework using JAVA and I facing a problem.
When I click on any button say Filter or clear filter application display a loading window and after that, we are able to perform next action.
i have added following code to wait until loading window visible false but its not working.

```<code>wait.until(ExpectedConditions.invisibilityOf(webElement));
                    System.out.println("Wait Untill Loading Window Closed");
                    existFlag=true;
</code>```

in web element i passing that loading window XPATH. Every time code not wait for window to be closed start clicking on button and  throw exception

unknown error: Element ... is not clickable at point (178, 391). Other element would receive the click:

I also added code for click

```<code>wait.until(ExpectedConditions.elementToBeClickable(webElement));
             webElement.click();
             return true;
</code>```

Please help how i can wait till loading window close.

答:
You can use this :</p>

```<code>wait.until(ExpectedConditions.visibilityOfElementLocated(webElement));
webElement.click();
</code>```

Body:
I have developed selenium automation framework using JAVA and I facing a problem.
When I click on any button say Filter or clear filter application display a loading window and after that, we are able to perform next action.
i have added following code to wait until loading window visible false but its not working.

wait.until(ExpectedConditions.invisibilityOf(webElement));
                    System.out.println("Wait Untill Loading Window Closed");
                    existFlag=true;

in web element i passing that loading window XPATH. Every time code not wait for window to be closed start clicking on button and  throw exception

unknown error: Element ... is not clickable at point (178, 391). Other element would receive the click:

I also added code for click

wait.until(ExpectedConditions.elementToBeClickable(webElement));
             webElement.click();
             return true;

Please help how i can wait till loading window close.

Body:
You can use this :

wait.until(ExpectedConditions.visibilityOfElementLocated(webElement));
webElement.click();


问:
If dynamic table exists in the database Drop the table
I have a table which gets created Dynamically every 1st of a month. something like test201711 for November.

I want to check if test201711 exists in the DB Drop test201711

What I tried so far:

```<code>Declare @ste varchar(max)
set @ste = 'if exists (select * from INFORMATION_SCHEMA.TABLES where   TABLE_NAME =''test'+CONVERT(varchar(6),getdate(),112) + ''');'  + ' Drop table test'+ CONVERT(varchar(6),getdate(),112)
print @ste
exec(@ste)
</code>```

When I am printing the query it is correct, but when I am executing it is giving me an error.

What is wrong with my code here??

答:
Simply use like this. It works for me.</p>

```<code>-- Create the table for testing
CREATE TABLE Test201711
(
    id INT
)

SELECT NAME
FROM   sys.tables AS t
WHERE  t.name = 'Test201711'

DECLARE @TableName VARCHAR(100) = 'Test' + CONVERT(VARCHAR(6), GETDATE(), 112)

IF OBJECT_ID(@TableName) IS NOT NULL
    EXEC ('DROP Table ' + @TableName)

SELECT NAME
FROM   sys.tables AS t
WHERE  t.name = 'Test201711'
</code>```

Body:
I have a table which gets created Dynamically every 1st of a month. something like test201711 for November.

I want to check if test201711 exists in the DB Drop test201711

What I tried so far:

Declare @ste varchar(max)
set @ste = 'if exists (select * from INFORMATION_SCHEMA.TABLES where   TABLE_NAME =''test'+CONVERT(varchar(6),getdate(),112) + ''');'  + ' Drop table test'+ CONVERT(varchar(6),getdate(),112)
print @ste
exec(@ste)

When I am printing the query it is correct, but when I am executing it is giving me an error.

What is wrong with my code here??

Body:
Simply use like this. It works for me.

-- Create the table for testing
CREATE TABLE Test201711
(
    id INT
)

SELECT NAME
FROM   sys.tables AS t
WHERE  t.name = 'Test201711'

DECLARE @TableName VARCHAR(100) = 'Test' + CONVERT(VARCHAR(6), GETDATE(), 112)

IF OBJECT_ID(@TableName) IS NOT NULL
    EXEC ('DROP Table ' + @TableName)

SELECT NAME
FROM   sys.tables AS t
WHERE  t.name = 'Test201711'


问:
Regex [4 characters, one letter, Cannot be all the same character]
Requirements:
Must be more than 4 characters
Must contain at least one letter a-zA-Z
Cannot be all the same character (regardless of length)

based on a previous answer I came up with:

```<code>(?!.*([A-Za-z0-9])\1{2})(?=.*[a-z]).{5,}
</code>```

and it works fine not matching values like "aaaaa".

(?!.*([A-Za-z0-9])\1{2}) makes sure that none of the chars repeat more than twice in a row.

(?=.*[a-z]) requires at least one lowercase letter

The problem is I need the "row" to be valid (I use the regex for validation purposes) if the word with repeated characters is part of a sentence (not on his own) e.g. "includes AAA batteries".

答:
I think this regex is what you need:

```<code>(?=.*[a-zA-Z])(?=.*\d)(?!.*([A-Za-z0-9])\1{1}).{4,}
</code>```

To explain it a bit:

```<code>(?=.*[a-zA-Z])             // To make sure there is at least one letter (uppercase or lower case)
(?!.*([A-Za-z0-9])\1{2})   // To make sure nothing will repeat twice in a row
.{4,}                      // Have at least 4 characters
</code>```

This regex will allow things like

```<code>aa23
A123
a1234
A1234
$%$%a
$%$%A
</code>```

To exclude 'weird' characters you'll need to add (?!.*[\W]) like so:

```<code>(?=.*[a-zA-Z])(?!.*[\W])(?!.*([A-Za-z0-9])\1{1}).{4,}
</code>```

Body:
Requirements:
Must be more than 4 characters
Must contain at least one letter a-zA-Z
Cannot be all the same character (regardless of length)

based on a previous answer I came up with:

(?!.*([A-Za-z0-9])\1{2})(?=.*[a-z]).{5,}

and it works fine not matching values like "aaaaa".

(?!.*([A-Za-z0-9])\1{2}) makes sure that none of the chars repeat more than twice in a row.

(?=.*[a-z]) requires at least one lowercase letter

The problem is I need the "row" to be valid (I use the regex for validation purposes) if the word with repeated characters is part of a sentence (not on his own) e.g. "includes AAA batteries".

Body:
I think this regex is what you need:

(?=.*[a-zA-Z])(?=.*\d)(?!.*([A-Za-z0-9])\1{1}).{4,}

To explain it a bit:

(?=.*[a-zA-Z])             // To make sure there is at least one letter (uppercase or lower case)
(?!.*([A-Za-z0-9])\1{2})   // To make sure nothing will repeat twice in a row
.{4,}                      // Have at least 4 characters

This regex will allow things like

aa23
A123
a1234
A1234
$%$%a
$%$%A

To exclude 'weird' characters you'll need to add (?!.*[\W]) like so:

(?=.*[a-zA-Z])(?!.*[\W])(?!.*([A-Za-z0-9])\1{1}).{4,}


问:
How to set a variable if undefined in typescript?
I'm trying to set the variable value when it's undefined however, I'm getting an error while trying to use vanilla javascript approach.

Block-scoped variable 'x' used before its declaration.

What is the best approach when using typescript for setting undefined variable?

```<code>let x = (typeof x === 'undefined') ? def_val : x;
</code>```

答:
TypeScript can tell that x is definitely not defined, because it is a block-scoped variable and you can see the whole block.

If you know better than the compiler, you can separate the lines:

```<code>const def_val = 'default';

let x: string;
x = (typeof x === 'undefined') ? def_val : x;
</code>```

But you might want to consider how the block scoped variable could possibly be undefined in your case (perhaps your code is not quite as simple as the example in your question).

The common use case would be more like:

```<code>const def_val = 'default';

function work(y: string) {
    let x = (typeof y === 'undefined') ? def_val : y;
}
</code>```

You can also add more strict compiler options to make it less likely the value will be undefined in many cases.

Shorthand

There is also a shorthand falsey-coalesce that may be useful:

```<code>const def_val = 'default';

function work(y: string) {
    let x = y || def_val;
}
</code>```

This will replace undefined, null, 0 (zero) or '' with the default.

Body:
I'm trying to set the variable value when it's undefined however, I'm getting an error while trying to use vanilla javascript approach.

Block-scoped variable 'x' used before its declaration.

What is the best approach when using typescript for setting undefined variable?

let x = (typeof x === 'undefined') ? def_val : x;

Body:
TypeScript can tell that x is definitely not defined, because it is a block-scoped variable and you can see the whole block.

If you know better than the compiler, you can separate the lines:

const def_val = 'default';

let x: string;
x = (typeof x === 'undefined') ? def_val : x;

But you might want to consider how the block scoped variable could possibly be undefined in your case (perhaps your code is not quite as simple as the example in your question).

The common use case would be more like:

const def_val = 'default';

function work(y: string) {
    let x = (typeof y === 'undefined') ? def_val : y;
}

You can also add more strict compiler options to make it less likely the value will be undefined in many cases.

Shorthand

There is also a shorthand falsey-coalesce that may be useful:

const def_val = 'default';

function work(y: string) {
    let x = y || def_val;
}

This will replace undefined, null, 0 (zero) or '' with the default.


问:
how to get driving alternative routes in google map direction api v2
I just want to show driving mode alternative routes in my android app. I done a single shortest route but I want multiple driving routes.

My code is here

my mapsavtivity class

```<code>package com.example.sherazahmed.itis;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

public class onNotificationClick extends FragmentActivity implements       OnMapReadyCallback {

private GoogleMap mMap;
static LatLng current=new LatLng(0,0);
       static LatLng destination=new LatLng(0,0);

public void onNotificationClick(LatLng current,LatLng destination){
    this.current=current;
    this.destination=destination;

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_on_notification_click);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.addMarker(new MarkerOptions().position(current).title("current location"));
    mMap.addMarker(new MarkerOptions().position(destination).title("destination"));

    DownloadTask downloadTask;
    String url=null;
    String mode = "mode=driving";
    String mode1 = "mode=bicycling";
    String mode2 = "mode=walking";
   url = getDirectionsUrl(current, destination,mode);
    downloadTask=new DownloadTask();
// Start downloading json data from Google Directions API
    downloadTask.execute(url);

    //2
    url = getDirectionsUrl(current, destination,mode2);
    downloadTask=new DownloadTask();
// Start downloading json data from Google Directions API
    downloadTask.execute(url);

    //3
    url = getDirectionsUrl(current, destination,mode1);
    downloadTask=new DownloadTask();
// Start downloading json data from Google Directions API
    downloadTask.execute(url);

}

private String getDirectionsUrl(LatLng origin,LatLng dest, String mode){

    // Origin of route
    String str_origin = "origin="+origin.latitude+","+origin.longitude;

    // Destination of route
    String str_dest = "destination="+dest.latitude+","+dest.longitude;

    // Sensor enabled
    String sensor = "sensor=false";
        String alter="Alternative=true";
    // Travelling Mode

    // Building the parameters to the web service
    String parameters =     str_origin+"&"+str_dest+"&"+sensor+"&"+mode+"&"+alter;

    // Output format
    String output = "json";

    // Building the url to the web service
    String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
    return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
    String data =new String();
    InputStream iStream = new InputStream() {
        @Override
        public int read() throws IOException {
            return 0;
        }
    };
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);
        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();
        // Connecting to url
        urlConnection.connect();
        // Reading data from url
        iStream = urlConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
        StringBuffer sb = new StringBuffer();
        String line = "";
        while( ( line = br.readLine()) != null){
            sb.append(line);
        }
        data = sb.toString();
        br.close();
    }catch(Exception e){
        Log.d("Exception in down url", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
    // Downloading data in non-ui thread
    @Override
    protected String doInBackground(String... url) {
        // For storing data from web service
        String data =new String();
        try{
            // Fetching the data from web service
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }
    // Executes in UI thread, after the execution of
    // doInBackground()
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();

        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);
    }
}

/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{

    // Parsing the data in non-ui thread
    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;

        try{
            jObject = new JSONObject(jsonData[0]);
            DirectionsJSONParser parser = new DirectionsJSONParser();

            // Starts parsing data
            routes = parser.parse(jObject);
        }catch(Exception e){
            e.printStackTrace();
        }
        return routes;
    }

    // Executes in UI thread, after the parsing process
    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = new ArrayList<LatLng>();
        PolylineOptions lineOptions = new PolylineOptions();

        // Traversing through all the routes
        for(int i=0;i<result.size();i++){
            points = new ArrayList<LatLng>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for(int j=0;j<path.size();j++){
                HashMap<String,String> point = path.get(j);

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(4);

            // Changing the color polyline according to the mode

        }

        if(result.size()<1){
            Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
            return;
        }

        // Drawing polyline in the Google Map for the i-th route
        mMap.addPolyline(lineOptions);
    }
}
}
</code>```

DirectionJSONParser class

```<code>public class DirectionsJSONParser {

/** Receives a JSONObject and returns a list of lists containing latitude     and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){

    List<List<HashMap<String, String>>> routes = new     ArrayList<List<HashMap<String,String>>>() ;
    JSONArray jRoutes = null;
    JSONArray jLegs = null;
    JSONArray jSteps = null;

    try {

        jRoutes = jObject.getJSONArray("routes");

        /** Traversing all routes */
        for(int i=0;i<jRoutes.length();i++){
            jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
            List path = new ArrayList<HashMap<String, String>>();

            /** Traversing all legs */
            for(int j=0;j<jLegs.length();j++){
                jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");

                /** Traversing all steps */
                for(int k=0;k<jSteps.length();k++){
                    String polyline = "";
                    polyline = (String)((JSONObject)    ((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                    List<LatLng> list = decodePoly(polyline);

                    /** Traversing all points */
                    for(int l=0;l<list.size();l++){
                        HashMap<String, String> hm = new HashMap<String, String>();
                        hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                        hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                        path.add(hm);
                    }
                }
                routes.add(path);
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }catch (Exception e){
    }
    return routes;
}

/**
 * Method to decode polyline points
 * Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-    maps-direction-api-with-java
 * */
    private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }
    return
</code>```

答:
```<code>String alter="Alternatives=true";
</code>```

is the way to do this thing, i just forgot to place
"s" in alternative in above code !
cheers !

Body:
I just want to show driving mode alternative routes in my android app. I done a single shortest route but I want multiple driving routes.

My code is here

my mapsavtivity class

package com.example.sherazahmed.itis;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

public class onNotificationClick extends FragmentActivity implements       OnMapReadyCallback {

private GoogleMap mMap;
static LatLng current=new LatLng(0,0);
       static LatLng destination=new LatLng(0,0);

public void onNotificationClick(LatLng current,LatLng destination){
    this.current=current;
    this.destination=destination;

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_on_notification_click);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.addMarker(new MarkerOptions().position(current).title("current location"));
    mMap.addMarker(new MarkerOptions().position(destination).title("destination"));

    DownloadTask downloadTask;
    String url=null;
    String mode = "mode=driving";
    String mode1 = "mode=bicycling";
    String mode2 = "mode=walking";
   url = getDirectionsUrl(current, destination,mode);
    downloadTask=new DownloadTask();
// Start downloading json data from Google Directions API
    downloadTask.execute(url);

    //2
    url = getDirectionsUrl(current, destination,mode2);
    downloadTask=new DownloadTask();
// Start downloading json data from Google Directions API
    downloadTask.execute(url);

    //3
    url = getDirectionsUrl(current, destination,mode1);
    downloadTask=new DownloadTask();
// Start downloading json data from Google Directions API
    downloadTask.execute(url);

}

private String getDirectionsUrl(LatLng origin,LatLng dest, String mode){

    // Origin of route
    String str_origin = "origin="+origin.latitude+","+origin.longitude;

    // Destination of route
    String str_dest = "destination="+dest.latitude+","+dest.longitude;

    // Sensor enabled
    String sensor = "sensor=false";
        String alter="Alternative=true";
    // Travelling Mode

    // Building the parameters to the web service
    String parameters =     str_origin+"&"+str_dest+"&"+sensor+"&"+mode+"&"+alter;

    // Output format
    String output = "json";

    // Building the url to the web service
    String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
    return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
    String data =new String();
    InputStream iStream = new InputStream() {
        @Override
        public int read() throws IOException {
            return 0;
        }
    };
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);
        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();
        // Connecting to url
        urlConnection.connect();
        // Reading data from url
        iStream = urlConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
        StringBuffer sb = new StringBuffer();
        String line = "";
        while( ( line = br.readLine()) != null){
            sb.append(line);
        }
        data = sb.toString();
        br.close();
    }catch(Exception e){
        Log.d("Exception in down url", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
    // Downloading data in non-ui thread
    @Override
    protected String doInBackground(String... url) {
        // For storing data from web service
        String data =new String();
        try{
            // Fetching the data from web service
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }
    // Executes in UI thread, after the execution of
    // doInBackground()
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();

        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);
    }
}

/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{

    // Parsing the data in non-ui thread
    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;

        try{
            jObject = new JSONObject(jsonData[0]);
            DirectionsJSONParser parser = new DirectionsJSONParser();

            // Starts parsing data
            routes = parser.parse(jObject);
        }catch(Exception e){
            e.printStackTrace();
        }
        return routes;
    }

    // Executes in UI thread, after the parsing process
    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = new ArrayList<LatLng>();
        PolylineOptions lineOptions = new PolylineOptions();

        // Traversing through all the routes
        for(int i=0;i<result.size();i++){
            points = new ArrayList<LatLng>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for(int j=0;j<path.size();j++){
                HashMap<String,String> point = path.get(j);

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(4);

            // Changing the color polyline according to the mode

        }

        if(result.size()<1){
            Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
            return;
        }

        // Drawing polyline in the Google Map for the i-th route
        mMap.addPolyline(lineOptions);
    }
}
}

DirectionJSONParser class

public class DirectionsJSONParser {

/** Receives a JSONObject and returns a list of lists containing latitude     and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){

    List<List<HashMap<String, String>>> routes = new     ArrayList<List<HashMap<String,String>>>() ;
    JSONArray jRoutes = null;
    JSONArray jLegs = null;
    JSONArray jSteps = null;

    try {

        jRoutes = jObject.getJSONArray("routes");

        /** Traversing all routes */
        for(int i=0;i<jRoutes.length();i++){
            jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
            List path = new ArrayList<HashMap<String, String>>();

            /** Traversing all legs */
            for(int j=0;j<jLegs.length();j++){
                jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");

                /** Traversing all steps */
                for(int k=0;k<jSteps.length();k++){
                    String polyline = "";
                    polyline = (String)((JSONObject)    ((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                    List<LatLng> list = decodePoly(polyline);

                    /** Traversing all points */
                    for(int l=0;l<list.size();l++){
                        HashMap<String, String> hm = new HashMap<String, String>();
                        hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                        hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                        path.add(hm);
                    }
                }
                routes.add(path);
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }catch (Exception e){
    }
    return routes;
}

/**
 * Method to decode polyline points
 * Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-    maps-direction-api-with-java
 * */
    private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }
    return

Body:
String alter="Alternatives=true";

is the way to do this thing, i just forgot to place
"s" in alternative in above code !
cheers !


问:
Difference between 'USING' and || in PL SQL
I just need to run a basic SELECT query in PL/SQL code. The following code works perfectly fine:

```<code>BEGIN
EXECUTE IMMEDIATE 'SELECT * FROM ' || 'TNAME';
END;
/
</code>```

But following code

```<code>BEGIN
EXECUTE IMMEDIATE 'SELECT * FROM :1' USING 'TNAME';
END;
/
</code>```

gives error saying

ORA-00903: invalid table name

ORA-06512: at line 2

00000 -  "invalid table name"

*Cause:

*Action:

Can I not pass table name using "USING" in any way ?

答:
As Oracle documentation states:

"You can only use placeholders in places where you can substitute
  variables in the SQL statement, such as conditional tests in WHERE
  clauses. You cannot use placeholders for the names of schema objects.
  For the right way, see "Passing Schema Object Names As
  Parameters."

Body:
I just need to run a basic SELECT query in PL/SQL code. The following code works perfectly fine:

BEGIN
EXECUTE IMMEDIATE 'SELECT * FROM ' || 'TNAME';
END;
/

But following code

BEGIN
EXECUTE IMMEDIATE 'SELECT * FROM :1' USING 'TNAME';
END;
/

gives error saying

ORA-00903: invalid table name

ORA-06512: at line 2

00000 -  "invalid table name"

*Cause:

*Action:

Can I not pass table name using "USING" in any way ?